Monday, February 25, 2013

Store data for reuse in a Java Application, using Google Datastore API

In this article, I will explain how to keep data persistent over multiple runs of a  Java Application (not Web Application) using Google Datastore.

I run this program in  a linux machine ( Ubuntu 10.10 ) using appengine-1.7.0. Most of the work is based on the tutorial on Local Unit Testing for Java by Google Developers.

The unit testing process explained in the tutorial stores all the data in memory. That you can not use the data stored in a particular run in later runs. But data can be made persistent using a file which is actually done by appengine in an web application project. You will find the following file

….. /
<project_name>/war/WEB-INF/appengine-generated/local_db.bin  

in a Web Application project powered by google appengine ( I am using Eclipse IDE ). It is the file used for keeping the data 
persistent over multiple runs of the application. 
I will explain the process through a code. The comments provided in the code will give the guideline. The requirement in the referred article must be fulfilled (i.e. placing jars in classpath) to run the code. Also place the library for App engine SDK in classpath.

Related code for the process can be found here. The init() and finish() is used to controlling the environment.  

Wednesday, September 5, 2012

GWT - JSNI , Facing error while using String[] as return type.

I worked with JSON and JSNI to retrieve data from server and sending the data back to client. The server returns the following JSON as a response to a request   


[{"message": "MMMM","word": "abcd","options": ["I","H","G","F","E"],"answer": 0}]

My class that results in by the eval(json) function is the following

public class Question extends JavaScriptObject{
      
    protected Question() {
    }
      
    public final native String getMessage()/*-{ return this.message ; }-*/;
    public final native String getWord()/*-{ return this.word ; }-*/;               
    public final native String[] getOptions()/*-{ return this.options ; }-*/;
    public final native int getAnswer()/*-{ return this.answer ; }-*/;
    

}


then calling the getOptions() function inside the code greeted me with the following exception

java.lang.ClassCastException: com.google.gwt.core.client.JavaScriptObject$ cannot be cast to [Ljava.lang.String

After that I changed 
public final native String[] getOptions()/*-{ return this.options ; }-*/;
to
public final native JsArrayString getOptions()/*-{ return this.options ; }-*/;

and make necessary update in code to work with JsArrayString ( It is more or less like ArrayList in java ) . Then the code worked nicely.





Tuesday, August 28, 2012

Using JDO with MySQL

I recently worked with Java Data Object( JDO ) on my machine to store and retrieve data from a local MySQL database. Following is the procedure how I did it. I used Eclipse IDE for writing JAVA codes.

*** Important: To build and run the project this post is useful.

First I created a property file that contains necessary information for connecting to the local MySQL and used by JDO api to create PersistenceManagerFactory class. Put the file in project's root folder.
File    : datanucleus.properties
Code : http://pastebin.com/0npQb4ag
Update username , password ,db-name according to yours.

Then I created a class named "UserInfo" to store username , password , email-address.
File    : UserInfo.java
Code : http://pastebin.com/CAMth7db
For the annotaions' guideline visit here 
Then I created a class named PMF.java to make sure that only one instance of PersistenceManagerFactory  is used through out the application. That file uses datanucleus.properties
file.
File    : PMF.java
Code : http://pastebin.com/24tcVgGk
Finally to test everything works I write TestJDO.java to test every thing works fine.
File    : TestJDO.java
Code :  http://pastebin.com/zeJgpcp9

Monday, August 27, 2012

Eclipse , JDO and MySQL Integration using Ant

I did it in a Linux machine( Ubuntu 10.10 ).I am assuming the following programs are already installed in the machine.

Eclipse JAVA IDE
MySQL

DataNucleus is used as an implementation for JDO( Java Data Object ). Follow the link and download
datanucleus-accessplatform-rdbms-<version>.zip from the latest release (and extarct) . I worked with version= 3.1.0-release.

Also download JDO-API from apache. Find the Latest version and download jdo-api-<jdo-version>.jar.
MySQL JDBC driver is also needed. 

Now create a Java Project in Eclipse and add the following jars to the project's CLASSPATH.

From ....../datanucleus-accessplatform-rdbms-<version>/dep/ folder
       asm-<asm-version>.jar
       log4j-<log4j-version>.jar

From ....../datanucleus-accessplatform-rdbms-<version>/lib/ folder
       datanucleus-api-jdo-<version>.jar
       datanucleus-core-<version>.jar
       datanucleus-enhancer-<version>.jar
       datanucleus-rdbms-<version>.jar

....../jdo-api-<jdo-version>.jar
....../mysql-connector-java-<mysql-version>-bin.jar (For MySQL JDBC driver).

Now Export the created Java project to General > AntBuildFiles . Click next and finish nothing much is needed to be done. A build.xml file has been created in the project's root directory. Open it with Eclipse Ide.

Add following snippet of xml to it

<target
        name="-post-compile"
        depends="init" >

        <taskdef
            name="datanucleusenhancer"
            classname="org.datanucleus.enhancer.tools.EnhancerTask"
            classpathref="<ProjectName>.classpath" />

        <echo message="start datanucleusenhancer" />

        <datanucleusenhancer
            classpathref="<ProjectName>.classpath"
            dir="bin"
            verbose="true" >

            <fileset dir="bin" >

                <include name="**/*.class" />
            </fileset>
        </datanucleusenhancer>

        <echo message="end datanucleusenhancer" /> 
</target>  

add this under <project> tag . Change <ProjectName>  according to yours.

Find <javac> tag and add the following line inside <javac></javac> tag.
<compilerarg line=" -processor org.datanucleus.enhancer.EnhancerProcessor" />
Add an attribute verbose="on" to javac tag.

Now find the following xml

<target
        name="build"
        depends="build-subprojects,build-project"/>


Turn it to
<target
        name="build"
        depends="build-subprojects,build-project,-post-compile" />


Now go to project --- properties -- builders and select new. Then select "Ant Builder" . Add a name and in "Buildfile" tab point the build.xml file. Mark only the newly created builder in the "Builders" list.

Friday, August 3, 2012

Configure Eclipse and Java 3D in Linux( Ubuntu 10.10 )

At the very beginning we need to install Java 3d.

Installation:
- Open the terminal ( Applications >> Accessories >> Terminal  )
- Type the following command
       sudo apt-get install libjava3d-java

After that we need to copy some files.
Copying Files:
- Copy the following jar files 
                j3dcore-1.5.2+dfsg.jar , 
                j3dcore.jar , 
                j3dutils-1.5.2+dfsg.jar , 
                j3dutils.jar , 
                vecmath.jar
to  $JAVA_HOME/jre/lib/ext folder. I found ( hope you also will ) the above files in 
/usr/share/java folder. You can use the following commands to do that
       sudo cp -i /usr/share/java/j3d*.jar $JAVA_HOME//jre/lib/ext
       sudo cp -i /usr/share/java/vecmath.jar $JAVA_HOME//jre/lib/ext
In my case , $JAVA_HOME = /usr/lib/jvm/java-6-sun-1.6.0.24 .


- Copy the libj3dcore-ogl.so to any of the directory that has been pointed out in LD_LIBRARY_PATH . The file is located in /usr/lib/jni/ folder . (This folder may already be in your LD_LIBRARY_PATH. Then copying is not needed ) .  I copied it to 
$JAVA_HOME/java-6-sun-1.6.0.24/jre/lib/i386. You can use the following command 
        sudo cp -i /usr/lib/jni/libj3dcore-ogl.so $JAVA_HOME//jre/lib/i386.


Eclipse Integration:
- Create a new Java Project.
- At project's build path select "Add external archive".
- Point out the following jar files 
       j3dcore.jar , 
       j3dutils.jar , 
       vecmath.jar         


Testing:
You can find a sample program in the tutorial hosted in site.




  




        

Friday, July 20, 2012

Clob datatype , oracle and java

Recently I worked with clob data of oracle. Using java , I found the following code works for the following purpose
- inserting clob data to a database table 
- retrieve clob data from database .


Assuming that reader has already executed the following sql command

create table testclob( _id numeric(5) , data clob );

variable name is not important . What is important is the table structure.


For inserting the following code suffices -
        
PreparedStatement pstmt = conn.prepareStatement("insert into testclob values(?,?)");
        
pstmt.setInt(1, 1);
pstmt.setCharacterStream(2, new FileReader(new File("hello.txt")));
pstmt.execute();
        
        
For retrieving data, the code is given below
         
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("select * from testclob");
while( result.next() )
{
     Clob clob = result.getClob(2);
     Reader in = clob.getCharacterStream();
     char[] buffer = new char[(int)clob.length()];
            
     in.read(buffer);
     System.out.println(buffer); 
} 

As oracle driver , ojdbc6.jar is used.

Thursday, May 3, 2012

Can not start AVD after creating - Android

Android system is emulated in the computer using Android Virtual Devices(AVDs). In my ubuntu ,When I create a new AVD using the AVD and SDK Manager it creates a file named

<avd-name>.ini

in the directory below  

~/.android/avd

When we try to start a virtual machine it tries to read the corresponding .ini file from that directory. Recently I created an AVD and when i tried to run it ,the AVD manger greeted me with the following error massage

PANIC: Could not open: ~/.android/avd/<avd-name>.ini

Just because of I typed
 
    sudo ./android

to run the  SDK and AVD Manager . For that it created the .ini file in
 
   /root/.android/avd

directory instead of the location desired by the Start command. Running
 
   ./android

command and cretaing new AVD there solved my problem.


Wednesday, May 2, 2012

Resuming cancelled download of Google Chrome

Say you are downloading a large file and it gets cancelled before finishing . But you want to resume that file and there is no such option in the chrome's default downloader . In linux, you can do the following -

Chrome usually saves the content of the file it is downloading to a file with following file-name pattern
         <filename>.<extention>.crdownload
in the directory where it usually saves the file after download. If you want to know which directory it is
follow the steps below-
  • Click the "wrench" icon on the upper right corner of the browser
  • Next Go to Preferences >> Under the hood >> Downloads   
So as you have a cancelled download , you most probably get a similar file with .crdownload extension.

Remove the .crdownload portion from the filename. (For safety you can make a copy of that file then remove the extension ) .

Then run a shell and type


wget -c <link to the file>

Here  <link to the file> is that chrome used to download the file . You can get it from the downloader of chrome.

If you do not find wget commnad ( in rare case ) type 

sudo apt-get install wget 

to install it in your machine.

After running the download command, wget will report how much of the target file it has already downloaded. By observing this you can be sure if it is really working.    

Thursday, January 5, 2012

Integrating PeerSim ( P2P Simulator) with Eclipse

In this article I will explain how to integrate PeerSim with Eclipse IDE .
I am using peersim version 1.0.5 and Eclipse Helios IDE

Step 1: Download peersim-1.0.5 and extract it in a folder you like . Say the downloaded zip file was saved in C:\My Documents\Downloads. Extract it here and you will find a folder named peersim-1.0.5 .


Step 2: At first create a JAVA project . ( Go File -> Project -> JAVA Project )
Step 3: In window that popped up , unmark the option Use default location. A text box will be alive and show there the directory where peersim-1.0.5 was extracted . According to Step 1 that should be C:\My Documents\Downloads\peersim-1.0.5


Step 3: Press next to see everything is included correctly .


Step 4: Right Click on project name in the project explorer. Select Build Path -> Configure Build Path . In the window that popped up ,select the Libraries tab . Remove the jars named peersim-1.0.5.jar and peersim-doclet.jar.

Step 5: Right Click on project name in the project explorer. Select Run as -> Run Configuration. In the explorer at the left double click on JAVA Application.You will see a new run configuration window is on the right. Give any name you like at the Name field. Hit  Search to find the main class.
The class name is Simulator under peersim package.

Step 6: Go to the Arguments tab. In the program arguments field input "example/config-example1.txt". The press Run. That will simulate a protocol configured in the example/config-example1.txt file.

There are also some other configuration files in the "example/" directory . Change in the "Argument" tab to check the others.    

Monday, May 16, 2011

Adding ECF real time editor sharing support to Ceditor - Eclipse

ECF ( Eclipse Communication Framework ) currently gives  support of real-time editor sharing to the Default Text Editor and The Java code editor . Recently I worked to enable this feature for C editor. With the help of EclipseWiki , I  created a plugin( with a local update site ). It will act as an update site for eclipse on local pc.

I used to build the project
  • Eclipse Helios 3.6.2
  • Ubuntu 10.10   
Minimum requirement for the plugin is Eclipse 3.6 . This plugin may not work in Windows platform . I didn't test it . I used the plugin with Eclipse CDT 7.0.2 .

But before all this you have to install ECF componants in your IDE ( Eclipse Helios or CDT ). To do that go here.

After your ECF installation is done , time is now for adding the real time editor sharing support for the C editor.

  • Extract the file to a directory you prefer.
  • Open the IDE and select help -> Install New Software
  • Click Add .
  • Select Local . Add the following directory .                    /The/directory/where/you/extracted/the/file/ECFc.site.
  • Add a suitable name. Hit OK.
  • Follow the installing guidline and ignore the warning message.     
Additional Info:
  
 I found that in other pc there occurs a problem regarding site . To overcome the situation, open site.xml in ECFc.site directory. Update the url field in the following line


<description url="file:///home/rafee/Desktop/ECFc.site">

Replace url field value as url="file://directory/where/you/extracted/ECFc.site". The path of the directory should be absolute. Hopefully it works for you then ( If you are facing any problem regarding site ). I 
found it works for me in that way.


Thursday, February 3, 2011

Observer pattern - in an investigative way




Think of a situation when a crime has occurred and the criminal has run away. CID ( Crime Investigation Department ) reached the spot and experiencing the situation , informed the Police Control Room. One of the CID officer using a phone call can easily do this. On response to this request , the  control room informs all the units working on the highways. This informing mechanism is quite simple  and clear.But this can be made complicated by doing the following ... 

One of the officer of CID always remains on phone for doing all the communication works. Then the intension of the officer to be in CID  will be hampered ( He/ She is there for doing investigations , not to remain busy on the phone ).

Observer  pattern is similar to the situation described above. Consider CID as a unit similar to the highway unit that are to be informed.  The Police Control room works as a central communicator . Then all the units are informed on request coming from any of them. ( Sometimes it is not necessary to wait for a request  coming from a unit , Control Room can itself genarate message and notify all.)

In observer pattern there is a Subject( Police Control Room ) who maintains state integrity among all the Observers( units ) In case of any  change in  State( information  ).


Now let's assume that criminal has been traced . A unit informs the control room that they have located the criminal . Then the control room informs

--- CID , to ensure that criminal has been traced.

--- Other units to stop searching ( to prevent any wastage of effort for searching )

In the case above each units ( Observers ) has two states . Let us denote it like the following:

Searching: when all the units are searching on request came from the  Police Control Room.
and 
Free: when a unit has traced the criminal or no notification from the Police Control Room came.

The police control room (Subject) maintains all the units at any of the above state at a given instance of time. 

this is the whole picture of  the observer pattern.  This pattern offers loose coupling .

Monday, January 31, 2011

0/1-Kanpsack Algorithm



Suppose you have been ordered to bring some elements from a place where there are m boxes full of precious elements.
( each box contains elements of only one type. ) . Each element has a weight w_i and a value p_i , where i denotes the box number.

You are told  all the parameters ( weight and value ) of the boxes in advance . But you can not carry more than n units of weight  with your knapsack .Because your boss has given this to you. Now the problem is to find out   what is the highest amount of profit you can make with the knapsack you have. ( The more you make profit, the more your boss become impressed.)

Now take the pencil  and paper and figure out what you should do . Consider one box at a time. Say the box number is k .(Assume that there is no box whose number is higher than k ) You can make two things with the k^{th} box,  

Case 1: Pick an element from the box . It will cause your knapsack size to be reduced by w_k , adding p_k to your total amount of profit.

Case 2: Do not pick an element from the box. That will cause the number of boxes you are considering , reduced by one that is k-1. ( Be careful , when you are not taking an element from on box , you are discarding the box from your consideration. In future you will not be able to take any element from that box )

let profit( i , j) denote the profit you can make when you have i sized knapsack and j boxes. Then according to the first one of the cases above , you have 

                    profit( i-w_j , j  )+p_j  , 

that is your knapsack size is shorten by w_j and you have added p_j to the total amount of profit possible by the reduced knapsack.

Other case says the following ,

                               profit( i , j - 1)

that is , you are assuming that you have only j-1 boxes .

The problem is a maximization problem. So you have to take the maximum of the two situation . Then the solution becomes ,

profit(i,j) = max \left\{ profit(i - w_j , i) + p_j \\ profit( i , j - 1)

and your destination is to find profit(n,m). Here Knapsack size means how much of weight it can hold. 


Thursday, January 20, 2011

Insert blob files into Oracle using Java




In this article  I will discuss how to insert a image into database table using PreparedStatement interface of java. All other blob files can be handled in same way. You will need ojdbc6.jar as the oracle driver. If you try to use ojdbc14.jar you may get the following exception :

Exception in thread "main" java.lang.AbstractMethodError:
 Theoracle.jdbc.driver.T4CPreparedStatement.setBinaryStream(ILjava/io/InputStream;)V


Now let's create a database table using the following sql command.

create table imagetable ( imageid numeric(5) , image blob);

Now use the following java code to insert a image in the table.

Class.forName("oracle.jdbc.driver.OracleDriver"); 
Connection connect = DriverManager.getConnection  
                       ("jdbc:oracle:thin:@IP_ADDRESS:PORT_NUMBER/SERVICE_NAME" ,"username","password"); 
String filename = "Your filename here" ; 
InputStream input = new FileInputStream(filename); 
PreparedStatement pstmt = connect.prepareStatement("insert into imagetable values(?,?)"); 
pstmt.setBinaryStream(2, input); 
pstmt.setInt(1, 1); 
pstmt.execute();


Also change the connection parameters according to your's.

Friday, November 5, 2010

Call Oracle Stored Function using php

Concider the following function code :
create or replace function notify ( pname in varchar2 ) 
return varchar2 
is 
massage varchar2(100); 
begin
     massage := 'hello '||pname||' time is '||sysdate ; 
     return massage ; 
end; 
/


Now write php code to execute the function and catch the return value .


1.  At first connect to oracle server using the following lines


$targetAddress = "localhost/XE"; // ipAddress / servicename or sid   
$username = "hello" ;   
$password = "hello" ;   
//this line of code connects you to desired database   
$conn = oci_connect($username , $password , $targetAddress ); 


 (change the connect parameters according to yours.)


2.  Then prepare a statement using oci_parse() 


$query = oci_parse($conn , "select notify(:pname) message from dual");


3.  Lets declare a php variable which we will use as the function parameter .


$person = "Mike" ;
 
4.  after that bind the php variable with the prepared statement   $query  


using oci_bind_by_name() function 

oci_bind_by_name($query ,":pname",$person , 30 , SQLT_CHR );



5.  now execute the statement using oci_execute()


oci_execute($query);


6.  Now it's time to retrieve the value returned by the function .Like most other result retrieving process its time to fetch and find the value of a particular column  ( in this case it will be "MESSAGE" , we aliased it in the oci_parse() function )


using functions oci_fetch_array() and oci_result() we get our desired result .


while( oci_fetch_array($query))   
{        
  //retrives the value of the specified field from the row fetched by oci_fetch_array()        
  echo "
Notifier: "
 . oci_result($query,"MESSAGE");   
} 
Alternative way:


before step 5 do the following :


define a variable to get the return value by oci_define_by_name().


oci_define_by_name($query ,"MESSAGE",$message);


Then do step 5 .


after that instead of doing step 6 do the following . oci_fetch() is used instead of oci_fetch_array()


while( oci_fetch($query))  
 {        
      echo "Notifier: " . $message ;  
 }