Saturday, January 9, 2016

hapi with oacle node js driver

 
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
'use strict';
 
 
const Hapi = require('hapi');
const oracledb = require('oracledb');
 
var dbConPool;
 
//gracefull shut down of node js since we need to terminate con pool
 
if (process.platform === "win32") {
    //since no SIGINT on win, watch for Ctl+C
    console.log('win platform...');
    var rl = require("readline").createInterface({
        input: process.stdin,
        output: process.stdout
    });
 
    rl.on("SIGINT", () => {
        console.log('received SIGINT 0..');
        process.emit("SIGINT");
    });
}
 
process.on("SIGINT", () => {
    console.log('received SIGINT..');
    if (dbConPool) {
        console.log('terminate pool..');
        dbConPool.terminate((e) => {
            if (e) {
                console.log(e);
            }
        });
    }
 
    process.exit();
});
 
// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
    host: 'localhost',
    port: 8000
});
 
 
// Add the route
server.route({
    method: 'GET',
    path: '/hapi/employee',
    handler: (request, reply) => {
 
        dbConPool.getConnection(
            (err, connection) => {
                if (err) {
                    console.error(err.message);
                    return reply('error');
                }
 
                connection.execute(
                    "SELECT * from employees where rownum < 10", [],
                    (err, result) => {
                        releaseDbCon(connection);
                        if (err) {
                            console.error(err.message);
                            return reply('error');
                        }
 
                        var employees = [];
                        result.rows.forEach((r) => {
                            employees.push({
                                id: r[0],
                                firstName: r[1],
                                lastName: r[2],
                                email: r[3],
                                phoneNumber: r[4],
                                hireDate: r[5],
                                jobId: r[6],
                                salary: r[7]
                            });
                        });
 
                        return reply(employees);
                    });
            });
 
 
    }
});
 
function releaseDbCon(connection) {
    connection.release(
        (err) => {
            if (err) {
                console.error(err.message);
            }
        });
}
 
// Start the server
server.start((err) => {
 
    if (err) {
        throw err;
    }
    console.log('Server running at:', server.info.uri);
 
    //create db con pool
    oracledb.createPool({
            user: "hr",
            password: "password",
            connectString: "localhost:1521/xe"
        },
        (err, pool) => {
            if (!err) {
                dbConPool = pool;
            }
        });
 
});
 
 
'use strict';


const Hapi = require('hapi');
const oracledb = require('oracledb');

var dbConPool;

//gracefull shut down of node js since we need to terminate con pool

if (process.platform === "win32") {
    //since no SIGINT on win, watch for Ctl+C
    console.log('win platform...');
    var rl = require("readline").createInterface({
        input: process.stdin,
        output: process.stdout
    });

    rl.on("SIGINT", () => {
        console.log('received SIGINT 0..');
        process.emit("SIGINT");
    });
}

process.on("SIGINT", () => {
    console.log('received SIGINT..');
    if (dbConPool) {
        console.log('terminate pool..');
        dbConPool.terminate((e) => {
            if (e) {
                console.log(e);
            }
        });
    }

    process.exit();
});

// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
    host: 'localhost',
    port: 8000
});


// Add the route
server.route({
    method: 'GET',
    path: '/hapi/employee',
    handler: (request, reply) => {

        dbConPool.getConnection(
            (err, connection) => {
                if (err) {
                    console.error(err.message);
                    return reply('error');
                }

                connection.execute(
                    "SELECT * from employees where rownum < 10", [],
                    (err, result) => {
                        releaseDbCon(connection);
                        if (err) {
                            console.error(err.message);
                            return reply('error');
                        }

                        var employees = [];
                        result.rows.forEach((r) => {
                            employees.push({
                                id: r[0],
                                firstName: r[1],
                                lastName: r[2],
                                email: r[3],
                                phoneNumber: r[4],
                                hireDate: r[5],
                                jobId: r[6],
                                salary: r[7]
                            });
                        });

                        return reply(employees);
                    });
            });


    }
});

function releaseDbCon(connection) {
    connection.release(
        (err) => {
            if (err) {
                console.error(err.message);
            }
        });
}

// Start the server
server.start((err) => {

    if (err) {
        throw err;
    }
    console.log('Server running at:', server.info.uri);

    //create db con pool
    oracledb.createPool({
            user: "hr",
            password: "password",
            connectString: "localhost:1521/xe"
        },
        (err, pool) => {
            if (!err) {
                dbConPool = pool;
            }
        });

});

Friday, January 8, 2016

npm install oracledb

npm install oracledb

Trying to install oracle node.js driver requires some effort. Since most of the github conversation on this issues are locked, i will describe it here, may be someone benefit.

My Environment

Windows 10 - 64 bit
Node.js 5.4.0 - 64 bit
Dot net framework 4.x
Visual Studio Community Edition 14
Oracle Xpress 11g 64 bit


Make sure all of your environment is either 64 bit or 32 bit, do not mix.


Prerequisites for oracledb

1- Python 2.7+
2- Dot net framework
3- Visual Studio C/C++ compiler

In win start menu type dev and open vs dev command prompt.
>cd "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC"
>vcvarsall amd64

--This will switch to vs 64 bit compiler

--set following local env variables. Since i have oracle xpress locally installed:

>set OCI_LIB_DIR=C:\oraclexe\app\oracle\product\11.2.0\server\oci\lib\MSVC
>set OCI_INC_DIR=C:\oraclexe\app\oracle\product\11.2.0\server\oci\include

>cd back-to-node-project-dir
>npm install oracledb

It should work!



Wednesday, July 29, 2015

OCR UAE Emirates ID



In this post, i will share my experience in trying to OCR (extract textual information) from UAE Emirates ID. The id has MRZ lines (similar to machine readable passports etc) on the back side which makes this task easier. But there is a background image in the middle of MRZ which can cause some problems.



 I evaluated few proprietary APIs specifically Asprise Java SDK and Abbyy OCR Rest services. .


I tried scanned colored image, and black white images with different orientation.

Among these Abbyy API was better with fewer mistakes. But it suffered when the image orientation is not straight or the image is black and white.


The best result was shown by an Android app called Regula Document Reader. It worked for disoriented black and white images also.
Could not find their evaluation API though.


Here is my attempt using Tess4j. It works very good when the image is scanned (colored or grey scale but not black and white)

The algorithm to correct orientation is not part of Tesseract.

The method here i used is simple:
Change the image to grey scale
Increase contrast and brightness
Use white list of chars that can appear in MRZ
Than do OCR.
public class Test {
public static void main(String[] args) throws Exception {
File imageFile = new File("0501013286_4.tif");
BufferedImage img = ImageIO.read(imageFile);
BufferedImage greyScaleImg = ImageHelper.convertImageToGrayscale(img);

RescaleOp rescaleOp = new RescaleOp(3f, 15, null);
rescaleOp.filter(greyScaleImg, greyScaleImg);

Tesseract instance = Tesseract.getInstance();
instance.setTessVariable("load_system_dawg", "false");
instance.setTessVariable("load_freq_dawg", "false");
instance.setTessVariable("tessedit_char_whitelist",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ</0123456789");

String result = instance.doOCR(greyScaleImg);


System.out.println(result);

}

}

Thursday, May 21, 2015

Maven JAX-WS Plugin

Here is how you use maven jax-ws plugin. I am using


Order of XJC args is important, Xew should come before others.




<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>my_group_id</groupId>
<artifactId>my_artificat</artifactId>
<version>0.0.1-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>2.1.5</version>
</dependency>
</dependencies>

<build>

<plugins>
<plugin>
<groupId>org.jvnet.jax-ws-commons</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
</execution>
</executions>
<configuration>
<verbose>true</verbose>
<sourceDestDir>src/main/java</sourceDestDir>
<wsdlDirectory>src/main/resources</wsdlDirectory>
<wsdlLocation>src/main/resources/*</wsdlLocation>
<xjcArgs>
<xjcArg>-no-header</xjcArg>
<xjcArg>-Xxew</xjcArg>
<xjcArg>-Xxew:instantiate lazy</xjcArg>
<xjcArg>-Xxew:delete</xjcArg>
<xjcArg>-extension</xjcArg>
<xjcArg>-b ${basedir}/src/main/resources/jaxb_binding.xml</xjcArg>
<xjcArg>-Xfluent-api</xjcArg>
<!-- <xjcArg>-Xvalue-constructor</xjcArg> -->
</xjcArgs>
</configuration>
<dependencies>
<dependency>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-fluent-api</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-tools</artifactId>
<version>2.1.5</version>

</dependency>
<dependency>
<groupId>com.github.jaxb-xew-plugin</groupId>
<artifactId>jaxb-xew-plugin</artifactId>
<version>1.2</version>
</dependency>
<!-- 
<dependency>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-value-constructor</artifactId>
<version>3.0</version>
</dependency>
-->
</dependencies>
</plugin>
</plugins>

</build>
</project>

Setting up SublimetText3 for javascript

- install node
- npm install -g jshint
- install sublime package manager
- install package SublimeLinter 3
- install package SublimeLinter-jshint (See errors in console Ctl+`)
- install jsformat. Ctl+Alt+F to format

To install using sublime packager
1- Ctl+Shift+P
2-select package install 
3-wait and than choose desired package

Thursday, August 26, 2010

Weblogic Listeners



J2EE standard ServletContextListener has following two methods:


1- public void contextInitialized(ServletContextEvent event)
2- public void contextDestroyed(ServletContextEvent event)


And you need to have web application (may by dummy) where you put following snippet in web.xml

 <listener>
   <listener-class>
   ServletContextListener
   </listener-class>
  </listener>


When you need more application events you can use weblogic.application.ApplicationLifecycleListener by extending your listener class from it. It provides:


1- public void preStart(ApplicationLifecycleEvent event)
2- public void postStart(ApplicationLifecycleEvent event)
3- public void preStop(ApplicationLifecycleEvent event)
4- public void postStop(ApplicationLifecycleEvent event)


Add an entry in weblogic-application.xml



<wls:listener>
  <wls:listener-class>ApplicationListener</wls:listener-class>
</wls:listener>


For server related events you can implement following interface:

com.bea.wlcp.wlng.core.wls.module.WlsStatusListener

It has a method which you can implement to listen for events:


public void handleWlsStatusChange(WlsStatus wlsStatus);

Example events are


WlsStatus.RESUMING;
WlsStatus.RUNNING;
WlsStatus.STANDBY


You can add/remove your listener as:


WlsListener.addWLSStatusListener
WlsListener.removeWLSStatusListener


Sometimes you need to check whether weblogic server is running or not e.g. if you are calling a webservice at application startup which is also deployed in the same server, you can use:


WlsListener.isServerRunning()



Wednesday, August 25, 2010

Log4j in J2EE

1- Create log4j.properties with following example contents. Important part is bold, i.e. you are creating a logger which will act as root of all of your classes. In this case all you classes reside in com.abc.xyz package or its sub-packages.


log4j.logger.com.abc.xyz=DEBUG, CONSOLE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d : [%-5p] - %m%n



2- Put log4j.properties in EarContent/APP-INF/classes or WebContent/WEB-INF/classes.


3- Any where in your startup code e.g. ServletContext or Servlet or EJB, configure log4j.

PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties"));