Monday, June 14, 2010

Check small java code on groovy console

For this tutorial, Groovy should be installed to your pc.
For how to install Groovy and fundamental of Groovy, check here.
http://ayushsuman.blogspot.com/2010/04/groovy-getting-started-how-use-groovy.html

If you want to check some java code then no need to write the one complete java class to check you bit code.You can use groovy console to check your java codes.

If you have already configured your groovy bin folder with path then
c:\>groovyConsole.bat
It will open one window then you can paste your code

String name = "BINOD KUMAR SUMAN";
System.out.println("Name :: "+name);
System.out.println("Now :: "+new Date());

and press Ctrl+R and see your code result on below screen.
Name :: BINOD KUMAR SUMAN
Now :: Sat Jun 12 11:28:02 EEST 2010

Ctrl+W for clear the output. Again you can check your some code. :)

Get the fild value from java class during run time using reflection

Get the fild value from java class during run time using reflection.

Suppose, you have one java class that is having a lot of static value and you want that int value during run time with dynamic field name.
Like,

public class Types
{
public static final int BIT = -7;
public static final int TINYINT = -6;
public static final int SMALLINT = 5;
public static final int INTEGER = 4;
public static final int BIGINT = -5;
public static final int FLOAT = 6;
public static final int REAL = 7;
public static final int DOUBLE = 8;
public static final int NUMERIC = 2;
public static final int DECIMAL = 3;
public static final int CHAR = 1;
public static final int VARCHAR = 12;
public static final int LONGVARCHAR = -1;
public static final int DATE = 91;
public static final int TIME = 92;
public static final int TIMESTAMP = 93;
}

And you have one string that containg the "TINYINT" during run time, now you have to fetch what is the value of TINYINT dynamically.
string filed = "TINYINT";

String field = "TINYINT";
Class typeClass = Class.forName("java.sql.Types");
int fieldValue = (Integer) typeClass.getField(field).get(null);
System.out.println("fieldValue :: "+fieldValue);


Output:

fieldValue :: -6

Tuesday, June 8, 2010

First Struts Example with Hibernate, Hibernate and Spring first example

1. Create one MyFirstStruts Web Dynamic Project (Say C:\workspaceAll\Struts\FirstStruts)

2. Create JSP pages
a) CustomerForm.jsp (C:\workspaceAll\Struts\MyFirstStruts\WebContent)
b) Success.jsp (C:\workspaceAll\Struts\MyFirstStruts\WebContent\Success.jsp)

3. Configuration Files
a) web.xml (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\web.xml)
b) struts-config.xml (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\struts-config.xml)
c) hibernate.cfg.xml (C:\workspaceAll\Struts\MyFirstStruts\src\hibernate.cfg.xml)
d) Customer.hbm.xml (C:\workspaceAll\Struts\MyFirstStruts\src\Customer.hbm.xml)

4. Java Files
a) CustomerForm.java (C:\workspaceAll\Struts\MyFirstStruts\src\CustomerForm.java)
b) CustomerAction.java (C:\workspaceAll\Struts\MyFirstStruts\src\CustomerAction.java)
c)Customer.java (C:\workspaceAll\Struts\MyFirstStruts\src\Customer.java)

5. Put these jar files (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\lib)
a) commons-beanutils.jar
b) commons-collections.jar
c) commons-digester.jar
d) commons-logging.jar
e) struts.jar
f) mysql-connector-java-3.1.12-bin.jar
g) commons-logging-1.1.jar
h) dom4j-1.6.1.jar
i) commons-collections-3.2.jar
j) log4j-1.2.15.jar
k) slf4j-1.6.0/slf4j-1.6.0/slf4j-api-1.6.0.jar
l) slf4j-1.6.0/slf4j-1.6.0/slf4j-log4j12-1.6.0.jar
m) slf4j-1.6.0/slf4j-1.6.0/slf4j-simple-1.6.0.jar
n) javassist-3.3.jar
o) jta-1.0.1B.jar
p) hibernate-commons-annotations-3.1.0.GA.jar
q) hibernate-annotations-3.1beta8.jar
r) hibernate-core-3.3.1.GA.jar
s) antlr-2.7.5H3.jar

6. Download and put struts-html.tld into C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\struts-html.tld
(If you download struts-1.2.9-lib.zip, then struts-html.tld file is there)

CustomerForm.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:html xhtml="true">
<body>
<html:form action="/submitCustomerForm">
Put Customer First Name <html:text property="firstName" size="16" maxlength="16"/> <BR/>
Put Customer Last Name <html:text property="lastName" size="16" maxlength="16"/> <BR/> <P/>
<html:submit>Save</html:submit>
</html:form>
</body>
</html:html>

Success.jsp
<html>
<h1> THIS IS SUCCESS PAGE </h1>
</html>

CustomerForm.java

import org.apache.struts.action.ActionForm;
public class CustomerForm extends ActionForm {
private String firstName;
private String lastName;
public CustomerForm() { firstName = ""; lastName = ""; }
public String getFirstName() { return firstName; }
public void setFirstName(String s) { this.firstName = s; }
public String getLastName() { return lastName; }
public void setLastName(String s) { this.lastName = s; }
}

Customer.java


/**
* @author Binod Suman
*/
public class Customer {

private int custId;
private String firstName;
private String lastName;
public Customer(){}
public int getCustId() {return custId;}
public void setCustId(int custId) {this.custId = custId;}
public String getFirstName() {return firstName;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public String getLastName() {return lastName;}
public void setLastName(String lastName) {this.lastName = lastName;}

}



CustomerAction.java

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class CustomerAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

ActionForward nextPage = null;
CustomerForm custForm = (CustomerForm) form;
String firstName = custForm.getFirstName();
String lastName = custForm.getLastName();
Customer customer = new Customer();
customer.setFirstName(firstName);
customer.setLastName(lastName);
saveCustomer(customer);
System.out.println("Customer First name is " + firstName);
System.out.println("Customer Last name is " + lastName);
nextPage = mapping.findForward("success");
return nextPage; }

public void saveCustomer(Customer customer){
System.out.println("Inserting new customer record ...... ");
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session =sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(customer);
transaction.commit();
session.flush();
session.close();
System.out.println("Customer record has been successfully saved ");
}

}

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Hello World Struts Application</display-name>
<servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-

name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
<servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <taglib> <taglib-uri>/WEB-INF/struts-

html.tld</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> </web-app>

struts-config.xml
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"><struts-config> <form-beans> <form-bean name="myForm" type="CustomerForm" /> </form-beans>
<action-mappings> <action path="/submitCustomerForm" type="CustomerAction" name="myForm" scope="request"> <forward name="success" path="/Success.jsp" />

</action> </action-mappings>
</struts-config>


create table in mysql sumandb database.

CREATE TABLE customer (
id int(11) NOT NULL,
firstName varchar(100) default NULL,
secondName varchar(100) default NULL,
PRIMARY KEY (id)
)


Start the server after deploy your application:
http://localhost:8080/FirstStruts/CustomerForm.jsp
Put First Name: Binod
Put Second Name: Suman
Click on Save button and check the server console, you should be get
Customer First name is Binod
Customer Last name is Suman

Check your sumandb database, one new record has been inserted.
and new success page will come with message:
THIS IS SUCCESS PAGE

How to use preapredStatment using Spring JdbcOperations.

Even it is very small thing but I searched on net lot with these words on goolge but didnt get solution.

Now I am going to show here how we can use preaparedstatement with spring JdbcOperations.

Create these five file in your Eclipse project.

DaoOperation.java
IDaoOperation.java
App.java
Myconfig.xml
MyProperties.properties

DaoOperation.java

import java.sql.SQLException;
import java.util.Set;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcOperations;

public class DaoOperation implements IDaoOperation{
private JdbcOperations jdbc;
public void saveStudentData() throws SQLException{
String sql = "insert into student (id,name,marks) values (?,?,?)";
Object[] args = {5,"Suman",99};
executeUdpdateSQL(sql,args);
}

public void updateStudentData() throws SQLException{
String sql = "update student set name=?, marks = ? where id = ?";
Object[] args = {"Ayush Suman",999,5};
executeUdpdateSQL(sql,args);
}

public void executeUdpdateSQL(String sql, Object[] args) throws SQLException {
jdbc.update(sql, args);
}

public JdbcOperations getJdbc() {return jdbc;}
public void setJdbc(JdbcOperations jdbc) {this.jdbc = jdbc;}

}

IDaoOperation.java

import java.sql.SQLException;
/**
* @author Binod Suman
*/
public interface IDaoOperation {
public void saveStudentData() throws SQLException;
public void updateStudentData() throws SQLException;
}

App.java
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
public static void main(String[] args) throws Exception {
IDaoOperation daoOperation;
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("Myconfig.xml");
daoOperation = (IDaoOperation) context.getBean("daoOperation");
daoOperation.saveStudentData();
// daoOperation.updateStudentData();
}

}


Myconfig.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<context:mbean-server/>
<context:property-placeholder location="classpath:/MyProperties.properties"/>

<bean id="daoOperation" class="DaoOperation"
p:jdbc-ref="jdbc" />

<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource" />

<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource" p:driverClassName="${db.driver}"
p:url="${db.url}" p:username="${db.username}" p:password="${db.password}" />

</beans>


MyProperties.properties

db.driver = com.mysql.jdbc.Driver
db.url = jdbc:mysql://localhost/sumandb
db.username = root
db.password = mysql

Sunday, June 6, 2010

First Hibernate example, Hibernate getting started


No need to explain about Hibernate as it is well known ORM tool.

One simple running example I am going to explain here. Just you follow step by step you would be able to run your first Hibernate example. This example will contect mysql database.


1. Download all below jar file.

mysql-connector-java-3.1.12-bin.jar
commons-logging-1.1.jar
dom4j-1.6.1.jar
commons-collections-3.2.jar
log4j-1.2.15.jar
slf4j-api-1.6.0.jar
slf4j-log4j12-1.6.0.jar
slf4j-simple-1.6.0.jar
javassist-3.3.jar
jta-1.0.1B.jar
hibernate-commons-annotations-3.1.0.GA.jar
hibernate-annotations-3.1beta8.jar
hibernate-core-3.3.1.GA.jar
antlr-2.7.5H3.jar
javassist-3.3.jar

2. First create one project in Eclipse say FirstHibernate and add these jar file into that project.

3. Create these below three file into your project src folder.

hibernate.cfg.xml

Student.hbm.xml
Student.java
Client.java

create one student table in database. In our example database name is sumandb.


CREATE TABLE student (
id int(11) NOT NULL,
name varchar(90) default NULL,
marks int(11) default NULL,
PRIMARY KEY (id)
)

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost/sumandb</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.username">root</property>
<property name="connection.password">mysql</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- this will show us all sql statements -->
<property name="hibernate.show_sql">true</property>
<!-- mapping files -->
<mapping resource="Student.hbm.xml" />
</session-factory>
</hibernate-configuration>

Student.hbm.xml



<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="Student" table="student">
<id name="studentId" column="id">
<generator class="increment" />
</id>
<!-- Both property are optional here as property name and column name are same -->
<property name="name" column="name" />
<property name="marks" column="marks" />
</class>
</hibernate-mapping>

Student.java
/**
* @author Binod Suman
*/

public class Student {
private int studentId;
private String name;
private int marks;

public Student() { }


public Student(int studentId, String name, int marks) {
this.studentId = studentId;
this.name = name;
this.marks = marks;
}


public Student(String name, int marks) {
this.name = name;
this.marks = marks;
}






public int getStudentId() {return studentId;}
public void setStudentId(int studentId) {this.studentId = studentId;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public int getMarks() {return marks;}
public void setMarks(int marks) {this.marks = marks;}

}


Client.java
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
/*
* @author Binod Suman
*/


public class Client {
public static void main(String[] args) {
Client test = new Client();
test.saveStudent();
// test.showAllStudent();
// test.searchStudent(2);
}


public void saveStudent(){
System.out.println("Inserting new Student record ...... ");
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session =sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Student student = new Student("Binod Suman",99);
session.save(student);
transaction.commit();
session.flush();
session.close();
System.out.println("Student record has been successfully saved ");
}

public void showAllStudent(){
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session =sessionFactory.openSession();
List students = session.createQuery("from Student").list();

for(Student student : students){
System.out.println("Student Name :: "+student.getName());
System.out.println("Student Roll :: "+student.getStudentId());
System.out.println("Student Marks :: "+student.getMarks());
System.out.println("************************");
}

}

public void searchStudent(int id){
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session =sessionFactory.openSession();
Student student = (Student)session.load(Student.class, id);
System.out.println("Student Name :: "+student.getName());
System.out.println("Student Roll :: "+student.getStudentId());
System.out.println("Student Marks :: "+student.getMarks());
}

}


Even if you are getting below exceptions, just you follow the above steps and add proper version of jar file, all  your below exception be removed.

Exception in thread "main" java.lang.NoSuchMethodError: org.slf4j.Logger.isTraceEnabled()Z


Exception in thread "main" java.lang.IllegalAccessError: tried to access field org.hibernate.cfg.Configuration.xmlHelper from class org.hibernate.cfg.AnnotationConfiguration

Exception in thread "main" java.lang.NoSuchFieldError: sqlResultSetMappings

That's it ........... :)

Thanks ..... :)

Saturday, June 5, 2010

How to install Eclipse on Linux. Eclipse Galileo on Linux



java should be installed before install the Eclipse. Just check
java -version


Follow these steps to install Eclipse Galileo on linux.

1. Download Eclipse for Linux from here.

Choose Eclipse IDE for Java EE Developers (190 MB) Linux 32 bit. You will get eclipse-jee-galileo-SR2-linux-gtk.tar.gz is being save.

2. Save this file in your favorite location. In my case /home/binod

3. Run this below command
[root@localhost binod]# tar -xzvf eclipse-jee-galileo-SR2-linux-gtk.tar.gz

It will create directory eclipse in /home/binod

4. cd eclipse
[root@localhost binod]# cd eclipse

5. and start eclipse
./eclipse


If everything fine then you will get eclipse window and you can start the work

If you are getting below error:

Warning: -XX:MaxPermSize=256m not understood. Ignoring.
Warning: -Xms40m not understood. Ignoring.
Warning: -Xmx512m not understood. Ignoring.
Warning: -jar not understood. Ignoring.
Exception in thread "main" java.lang.NoClassDefFoundError:
.home.binod.eclipse.plugins.org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
at gnu.gcj.runtime.FirstThread.run() (/usr/lib/libgcj.so.5.0.0)
at _Jv_ThreadRun(java.lang.Thread) (/usr/lib/libgcj.so.5.0.0)
at _Jv_RunMain(java.lang.Class, byte const, int, byte const, boolean) (/usr/lib/libgcj.so.5.0.0)
at __gcj_personality_v0 (/home/binod/eclipse/java.version=1.4.2)
at __libc_start_main (/lib/tls/libc-2.3.4.so)
at _Jv_RegisterClasses (/home/binod/eclipse/java.version=1.4.2)


SOLUTION here:

check your JAVA_HOME using this below command
[root@localhost eclipse]# echo $JAVA_HOME

If you do not get result means your path does not set.
Then use this command to set JAVA_HOME path


[root@localhost eclipse]# export PATH=$PATH:/usr/java/jdk1.6.0_20/bin/
[root@localhost eclipse]# export JAVA_HOME=/usr/java/jdk1.6.0_20
In my case Java has been installed at /usr/java/jdk1.6.0_20

Now run this command to verify whether your path and JAVA_HOME is set proplery


echo $PATH
echo $JAVA_HOME

Now you can open eclipse using this below command
[root@localhost eclipse]# ./eclipse -vm /usr/java/jre1.6.0_20/bin

That's it .......... :)

Thanks ...... :)


Friday, June 4, 2010

Best waty to thread implementation in Java, Threads pools with the Executor Framework

Threads were the first approach in Java to support concurrency. The usage of the threads has the following disadvantages.

1. Creating a new thread causes some performance overhead
2. Too many threads can lead to reduced performance, as the CPU needs to switch between these threads.
3.You cannot easily control the number of threads, therefore you may run into out of memory errors due to too many threads.

The java.util.concurrent package offers improved support for concurrency compared to threads. The java.util.concurrent package helps solving several of the isues with threads.

Threads pools with the Executor Framework

Thread pools manage a pool of worker threads. The thread pools contains a work queue which holds tasks waiting to get executed. A thread pool can be described as a collection of runnables (work queue) and a connections of running threads. These threads are constantly running and are checking the work query for new work. If there is new work to be done they execute this Runnable. The Thread class itself provides a method, e.g. execute (Runnable r) to add runnables to the work queue.

The Executor framework provides example implementation of the java.util.concurrent.Executor interface, e.g. Executors.newFixedThreadPool(int n) which will create n worker threads. The ExecutorService adds lifecycle methods to the Executor, which allows to shutdown the Executor and to wait for termination.

If you want to use one thread pool with one thread which executes several runnables you can use Executors.newSingleThreadExecutor();

Create two java files:

MyRunnable.java

package com.suman;

/**
* @author Binod Suman
*/
public class MyRunnable implements Runnable {
private final String sql;

MyRunnable(String sql) {this.sql = sql;}

@Override
public void run() {
long sum = 0;
for (long i = 1; i < 5; i++) {
System.out.println(sql);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

App.java

package com.suman;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class App
{
private static final int noOfThreadInPool = 10;
public static void main( String[] args )
{
ExecutorService executor = Executors.newFixedThreadPool(noOfThreadInPool);
String sql="sql";
List> list = new ArrayList>();
for (int i = 1; i <=5; i++) {
if(i==1)sql="FIRST";
if(i==2)sql="SECOND";
if(i==3)sql="THIRD";
if(i==4)sql="FOURTH";
if(i==5)sql="FIFTH";

Runnable worker = new MyRunnable(sql);
executor.execute(worker);
}

// This will make the executor accept no new threads
// and finish all existing threads in the queue

executor.shutdown(); // Very Important

// Wait until all threads are finish

while (!executor.isTerminated()) {}

System.out.println("Finished all threads");
}
}


The main benefit of Executors Framework that you no need to manage thread yourself. Here you can give how many thread maximum do you want to generate in threadpool.

private static final int noOfThreadInPool= 10;
ExecutorService executor = Executors.newFixedThreadPoolnoOfThreadInPool

If you give noOfThreadInPool=5 then it will only create 5 thread to threadpool and you request for 6th thread to call executor.execute(worker); then it has to finish until one thread will free.

How you will use this in your project.

Suppose if you have one fixed work that you have to execute 10 times then make that method inside the MyRunnbale.java and put that method in run() method and call

Runnable worker = new MyRunnable(sql);
executor.execute(worker);

10 times.

But you can not return any value from MyRunnable class as run() method return type is void.

In case you expect your threads to return a computed result you can use java.util.concurrent.Callable. Callables allow to return values after competition. Callable uses generic to define the type of object which is returned.
If you submit a callable to an executor the framework returns a java.util.concurrent.Future. This futures can be used to check the status of a callable and to retrieve the result from the callable.

On the executor you can use the method submit to submit a Callable and to get a future. To retrieve the result of the future use the get() method.

Future and Collable Example
Create one more java file

MyCallable.java

package com.suman;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

/**
* @author Binod Suman
*/

public class MyCallable implements Callable {
private final String sql;

MyCallable(String sql) {this.sql = sql;}

@Override
public List call() throws Exception {
long sum = 0;
List list = new ArrayList();
for (long i = 1; i < 6; i++) {
System.out.println(sql);
list.add(sql+i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return list;
}
}


And do some change in App.java

package com.suman;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class App
{
private static final int noOfThreadInThreadPool = 10;

public static void main( String[] args )
{
ExecutorService executor = Executors.newFixedThreadPool(noOfThreadInThreadPool);
String sql="sql";
List> list = new ArrayList>();
for (int i = 1; i <=5; i++) {
if(i==1)sql="FIRST";
if(i==2)sql="SECOND";
if(i==3)sql="THIRD";
if(i==4)sql="FOURTH";
if(i==5)sql="FIFTH";

// Runnable worker = new MyRunnable(sql);
// executor.execute(worker);

Callable worker = new MyCallable(sql);
Future submit = executor.submit(worker);
list.add(submit);
}


// To see the result
for (Future future : list) {
try {
List list2 = future.get();
System.out.println("ALL LIST:: "+list2);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

}



// This will make the executor accept no new threads
// and finish all existing threads in the queue
executor.shutdown();
// Wait until all threads are finish
while (!executor.isTerminated()) {}

System.out.println("Finished all threads");
}
}

I think, it is best way to use the thread. Your suggestions or question is always most welcom. :)

Thanks ........... :)

source: http://www.vogella.de/articles/JavaConcurrency/article.html#threadpools





JPA One to Many and Many to One easy example

Please follow two previous posting on JPA for basic start
1. JPA getting started, easy example of JPA, JPA annotation example, JPA with Hibernate
2. Configure JPA during run time, dynamic JPA Configuration using Spring context

Now OnetoMany and ManytoOne Example.


Suppose company has many employee. So during saving of company we can save employee also and during fetching company record we can fetch employee records also.

Create one Employee.java

package com.suman;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
* @author Binod Suman
*/

@Entity
@Table(name="blogemployee")
public class Employee {

@Id
private int id;
@Column(name="cid")
private int companyId;
private String name;
private String designation;

@ManyToOne
@JoinColumn(name="cid",nullable=false, insertable=false, updatable=false)
private Company company;
// cid column should be there in company table.
public Employee() { }
public Employee(int companyId, String name, String designation) {
super();
this.companyId = companyId;
this.name = name;
this.designation = designation;
}

public Employee(int id, int companyId, String name, String designation) {
super();
this.id = id;
this.companyId = companyId;
this.name = name;
this.designation = designation;
}

public int getId() {return id;}
public void setId(int id) {this.id = id;}
public int getCompanyId() {return companyId;}
public void setCompanyId(int companyId) {this.companyId = companyId;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getDesignation() {return designation;}
public void setDesignation(String designation) {this.designation = designation;}
public Company getCompany() {return company;}
public void setCompany(Company company) {this.company = company;}
}


Company.java

package com.suman;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.log4j.Logger;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.annotations.OptimisticLock;

/**
* @author Binod Suman
*/

@Entity
@Table(name="blogcompany")
public class Company {

@Id
private int id;
@Column(name="cname")
private String name;
private String city;

@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "company")
private List employees;
@Transient
Logger log = Logger.getLogger(Company.class);
// Use Transient if you dont want to mapping your java bean to database table column.
public Company(){};
public Company(String name, String city) {
super();
this.name = name;
this.city = city;
}

public Company(int id, String name, String city) {
super();
this.id = id;
this.name = name;
this.city = city;
}

public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getCity() {return city;}
public void setCity(String city) {this.city = city;}
public List getEmployees() {return employees;}
public void setEmployees(List employees) {this.employees = employees;}
}


TestApplication.java


package com.suman;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.apache.log4j.Logger;

/**
* @author Binod Suman
*/

public class TestApplication {
Logger log = Logger.getLogger(TestApplication.class);
EntityManagerFactory emf;
EntityManager em;

public static void main(String[] args) {
TestApplication test = new TestApplication();
test.configureEntityManager();
// test.saveCompany();
// test.fetchCompanyData();
// test.saveCompanyAndEmployee();
test.fetchCompanyAndEmployee();
}

public void configureEntityManager(){
Map properties = new HashMap();
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "mysql");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show-sql", "true");
properties.put("hibernate.format_sql", "true");
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);
em = emf.createEntityManager();
}

public void saveCompany(){
log.info("Company data is going to save");
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(120,"TecnoTree","Espoo, Finland");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}

public void saveCompanyAndEmployee(){
log.info("Company and Employee data are going to save");
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(145,"TecnoTree","Finland");
List employees = new ArrayList();
Employee employee = new Employee(10,145,"Binod","Project Manager");
// entityManager.persist(employee);
employees.add(employee);
employee = new Employee(11,145,"Binod Suman","Team Leader");
employees.add(employee);
company.setEmployees(employees);
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company and Employee data have been saved");
}

public void fetchCompanyData(){
Query query = em.createQuery("SELECT c FROM Company c");
List list = (List) query.getResultList();
log.info(list);
for (Company company : list) {
log.info("Company Name :: "+company.getName());
log.info("Company City :: "+company.getCity());
log.info("***************************");
}
}


public void fetchCompanyAndEmployee(){
Query query = em.createQuery("SELECT c FROM Company c");
List list = (List) query.getResultList();
log.info(list);
for (Company company : list) {
log.info("Company Name :: "+company.getName());
log.info("Company City :: "+company.getCity());
log.info("Company Id :: "+company.getId());
List employees = company.getEmployees();
log.info("Employees.size() :: "+employees.size());
for(Employee employee : employees){
log.info("Employee Name :: "+employee.getName());
log.info("Employee Designation :: "+employee.getDesignation());
}
log.info("***************************");
}
}

}

Some time if you have father -> child -> child mapping then it doest not work properly then use this below mapping in father and his child java bean.

@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "company")
@LazyCollection(LazyCollectionOption.FALSE)
private List employees;

If you have question and doubt then please give your comment or if you have any feedback.


Thanks .......... :)

Thursday, June 3, 2010

Configure JPA during run time, dynamic JPA Configuration using Spring context

You can set the database information during run time. Then remove all the database specific stuff
from persistance.xml and use Hash properties in your java class.

1. Removed all your database properties from persistance.xml
<persistence>
<persistence-unit name="jpablogPUnit" transaction-type="RESOURCE_LOCAL">
<class>com.suman.Company</class>
</persistence-unit>
</persistence>

2. Changed your java file where you are configuring entityManager, in our case TestApplication.java


package com.suman;

import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.Logger;

/**
* @author Binod Suman
*/
public class TestApplication {

Logger log = Logger.getLogger(TestApplication.class);
public static void main(String[] args) {
TestApplication test = new TestApplication();
test.saveCompany();
}

public void saveCompany(){
log.info("Company data is going to save");
EntityManagerFactory emf;
Map properties = new HashMap();
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "mysql");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show-sql", "true");
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(120,"TecnoTree","Espoo, Finland");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}

}

Now run the application.
One more record has been inserted.

How to fetch data using JPA

Change the code of TestApplcation.java

package com.suman;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.apache.log4j.Logger;

/**
* @author Binod Suman
*/
public class TestApplication {

Logger log = Logger.getLogger(TestApplication.class);
EntityManagerFactory emf;
EntityManager em;

public static void main(String[] args) {
TestApplication test = new TestApplication();
test.configureEntityManager();
// test.saveCompany();
test.fetchCompanyData();
}

public void configureEntityManager(){
Map properties = new HashMap();
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "mysql");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show-sql", "true");
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);
em = emf.createEntityManager();
}

public void saveCompany(){
log.info("Company data is going to save");
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(120,"TecnoTree","Espoo, Finland");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}

public void fetchCompanyData(){
Query query = em.createQuery("SELECT c FROM Company c");
List<Company> list = (List<Company>) query.getResultList();
log.info(list);

for (Company company : list) {
log.info("Company Name :: "+company.getName());
log.info("Company City :: "+company.getCity());
log.info("***************************");
}
}
}


You can configure the EntityManagerFactory from spring configuration file also.

<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
lazy-init="false">
<property name="persistenceUnitName" value="VMSPersistenceUnit" />
<property name="dataSource" ref="sourceDataSource" />
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>

If you want to configure entityManagerFactory during runt time then use these code. As if you dont have database name and information then you can not use the spring context for entityManagerFactory.


private EntityManagerFactory entityManagerFactory;
private JpaTemplate jpaTemplate;


LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setDataSource(sourceDataSource);
bean.afterPropertiesSet();
entityManagerFactory = bean.getObject();
log.info("entityManagerFactory :: " + entityManagerFactory);
this.jpaTemplate = new JpaTemplate(this.entityManagerFactory);

Even you can fetch record in batch wise manner also.
Use this below code:
public Collection fetchQueryListFromSourceDatabaseForSubscriber(final String sql,final int firstPosition, final int numberOfRecords) throws DataAccessException {
return (Collection) this.jpaTemplate.execute(new JpaCallback() {
public Object doInJpa(EntityManager em) throws PersistenceException {
Query query = em.createQuery(sql);
query.setFirstResult(firstPosition);
query.setMaxResults(numberOfRecords);
List result = query.getResultList();
return result;
}
});
}

If will fetch record from firstPosition and number of record will be numberOfRecords.
A persistence provider may or may not optimize access to database using database specific limit clause, like select * from table limit 10,

Then in TestApplication.java

public Collection fetchQueryListFromSourceDatabase(final String sql) throws DataAccessException {
return (Collection) this.jpaTemplate.execute(new JpaCallback() {
public Object doInJpa(EntityManager em) throws PersistenceException {
Query query = em.createQuery(sql);
List result = query.getResultList();
log.info("FINALLY JPA WORKING :: "+result.size());
return result;
}
});
}

Please feedback to improve this tutorial ....... :)

Thanks :)