Monday, December 21, 2015

What is ESB and WSO2 ESB Quick Start

Recently I started learning about wso2 ESB. They have provided a good document. But for a starter it looks little too much of information and going to quick start with given quick start document I found little time consuming.
So I thought of sharing few thing in pretty short.

First we look at what is ESB and let's start it.

What is an ESB ?

As with a Service-Oriented Architecture (SOA), an ESB is essentially a collection of enterprise architecture design patterns that is now implemented directly by many enterprise software products.

ESB is a software architecture that enables communication (Integration) among various applications.
·         Instead of directly communicating each other via their own communication formats, each application communicate directly with ESB. ESB transform and route the message to their appropriate destinations.

ESB provides fundamental service via event driven and standard based messaging engine. (The bus)

 Note : I have using latest version 4.8.1 - this is not supporting Java 1.8

The few important links

About WSO2 esb
https://docs.wso2.com/display/ESB481/About+WSO2+ESB

Download source and compile and build SEB
Prerequisites



Quick Start

1. Download ESB = http://wso2.com/products/enterprise-service-bus/
2. Windows - unzip it
I have added this file inside "WSO2" folder created inside "Softwares". So after unzip my wso2 esb home folder will be
C:\Softwares\wso2\wso2esb-4.8.1

3. Set home variable for Java
JAVA_HOME = C:\Program Files\Java\jdk1.7.0_13


4. Go to "bin" folder and run "wso2server.bat"
you can run with opening command line "cmd". set the path to "C:\Softwares\wso2\wso2esb-4.8.1\bin". type "wso2server.bat" and enter.

C:\Softwares\wso2\wso2esb-4.8.1\bin>wso2server.bat

ESB will start.

There is an easy way. Once you go to "bin" folder. Just type "cmd" in the address bar (--> That is where you can see the folder path "C:\Softwares\wso2\wso2esb-4.8.1") and enter. It will open a command line with path set to "C:\Softwares\wso2\wso2esb-4.8.1\bin>"


5. verify whether ESB started.
Open browser. go to
https://localhost:9443/carbon

Remember to use secure "https" if you omit "S" you will not get the console

6. use username and password  admin/admin  respectively
you will get the admin console


I will give summary steps to quick start in my next article.











Monday, November 2, 2015

turn off open new folder in a new window

In Linux you have a very bad experience. That is when you click a folder. it's content is open in a new window. This is pretty annoying. Below is the command to get rid of it. I have used and it works perfectly fine.
So how to execute command in Linux, If you don't know
just open an terminal and run below command

gconftool-2 -s '/apps/nautilus/preferences/always_use_browser' --type bool true


Monday, October 26, 2015

Cloudera :: at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

I tried to run below code fragment in eclipse. My project was built using maven.

=================================================

package thbase.tutorialPoint;

/*
 * Compile and run with:
 * javac -cp `hbase classpath` TestHBase.java
 * java -cp `hbase classpath` TestHBase
 */
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.*;

public class TestHBase {
public static void main(String[] args) throws Exception {
System.out.println("***1");
Configuration conf = HBaseConfiguration.create();
System.out.println(conf);
System.out.println(conf.getResource("core-default.xml"));
System.out.println(conf.getResource("core-site.xml"));
System.out.println(conf.getResource("hbase-default.xml"));
HBaseAdmin admin = new HBaseAdmin(conf);
try {
HTable table = new HTable(conf, "test-table");
Put put = new Put(Bytes.toBytes("test-key"));
put.add(Bytes.toBytes("cf"), Bytes.toBytes("q"),
Bytes.toBytes("value"));
table.put(put);
} finally {
// admin.close();
}
}
}

==========================================


I get the below error

======================================================================

***
Configuration: core-default.xml, core-site.xml, hbase-default.xml, hbase-site.xml
jar:file:/home/cloudera/.m2/repository/org/apache/hadoop/hadoop-core/0.20.2/hadoop-core-0.20.2.jar!/core-default.xml
null
jar:file:/home/cloudera/.m2/repository/org/apache/hbase/hbase/0.90.3/hbase-0.90.3.jar!/hbase-default.xml
2015-10-25 23:29:43,378 INFO  [main] zookeeper.ZooKeeper: Client environment:zookeeper.version=3.3.2-1031432, built on 11/05/2010 05:32 GMT
2015-10-25 23:29:43,389 INFO  [main] zookeeper.ZooKeeper: Client environment:host.name=quickstart.cloudera
2015-10-25 23:29:43,389 INFO  [main] zookeeper.ZooKeeper: Client environment:java.version=1.7.0_67
2015-10-25 23:29:43,389 INFO  [main] zookeeper.ZooKeeper: Client environment:java.vendor=Oracle Corporation
2015-10-25 23:29:43,389 INFO  [main] zookeeper.ZooKeeper: Client environment:java.home=/usr/java/jdk1.7.0_67-cloudera/jre
2015-10-25 23:29:43,389 INFO  [main] zookeeper.ZooKeeper: Client environment:java.class.path=/home/cloudera/workspace/HelloHadoop/target/classes:/etc/hbase/conf:/home/cloudera/.m2/repository/org/apache/hadoop/hadoop-core/0.20.2/hadoop-core-0.20.2.jar:/home/cloudera/.m2/repository/commons-cli/commons-cli/1.2/commons-cli-1.2.jar:/home/cloudera/.m2/repository/xmlenc/xmlenc/0.52/xmlenc-0.52.jar:/home/cloudera/.m2/repository/commons-httpclient/commons-httpclient/3.0.1/commons-httpclient-3.0.1.jar:/home/cloudera/.m2/repository/commons-codec/commons-codec/1.3/commons-codec-1.3.jar:/home/cloudera/.m2/repository/commons-net/commons-net/1.4.1/commons-net-1.4.1.jar:/home/cloudera/.m2/repository/org/mortbay/jetty/jetty/6.1.14/jetty-6.1.14.jar:/home/cloudera/.m2/repository/org/mortbay/jetty/jetty-util/6.1.14/jetty-util-6.1.14.jar:/home/cloudera/.m2/repository/tomcat/jasper-runtime/5.5.12/jasper-runtime-5.5.12.jar:/home/cloudera/.m2/repository/tomcat/jasper-compiler/5.5.12/jasper-compiler-5.5.12.jar:/home/cloudera/.m2/repository/org/mortbay/jetty/jsp-api-2.1/6.1.14/jsp-api-2.1-6.1.14.jar:/home/cloudera/.m2/repository/org/mortbay/jetty/jsp-2.1/6.1.14/jsp-2.1-6.1.14.jar:/home/cloudera/.m2/repository/ant/ant/1.6.5/ant-1.6.5.jar:/home/cloudera/.m2/repository/commons-el/commons-el/1.0/commons-el-1.0.jar:/home/cloudera/.m2/repository/net/java/dev/jets3t/jets3t/0.7.1/jets3t-0.7.1.jar:/home/cloudera/.m2/repository/org/mortbay/jetty/servlet-api-2.5/6.1.14/servlet-api-2.5-6.1.14.jar:/home/cloudera/.m2/repository/net/sf/kosmosfs/kfs/0.3/kfs-0.3.jar:/home/cloudera/.m2/repository/junit/junit/4.5/junit-4.5.jar:/home/cloudera/.m2/repository/hsqldb/hsqldb/1.8.0.10/hsqldb-1.8.0.10.jar:/home/cloudera/.m2/repository/oro/oro/2.0.8/oro-2.0.8.jar:/home/cloudera/.m2/repository/org/eclipse/jdt/core/3.1.1/core-3.1.1.jar:/home/cloudera/.m2/repository/org/apache/hbase/hbase/0.90.3/hbase-0.90.3.jar:/home/cloudera/.m2/repository/com/google/guava/guava/r06/guava-r06.jar:/home/cloudera/.m2/repository/commons-lang/commons-lang/2.5/commons-lang-2.5.jar:/home/cloudera/.m2/repository/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar:/home/cloudera/.m2/repository/log4j/log4j/1.2.16/log4j-1.2.16.jar:/home/cloudera/.m2/repository/org/apache/hadoop/avro/1.3.3/avro-1.3.3.jar:/home/cloudera/.m2/repository/org/apache/zookeeper/zookeeper/3.3.2/zookeeper-3.3.2.jar:/home/cloudera/.m2/repository/org/apache/thrift/thrift/0.2.0/thrift-0.2.0.jar:/home/cloudera/.m2/repository/org/jruby/jruby-complete/1.6.0/jruby-complete-1.6.0.jar:/home/cloudera/.m2/repository/org/slf4j/slf4j-api/1.5.8/slf4j-api-1.5.8.jar:/home/cloudera/.m2/repository/org/slf4j/slf4j-log4j12/1.5.8/slf4j-log4j12-1.5.8.jar:/home/cloudera/.m2/repository/com/google/protobuf/protobuf-java/2.3.0/protobuf-java-2.3.0.jar:/home/cloudera/.m2/repository/com/sun/jersey/jersey-core/1.4/jersey-core-1.4.jar:/home/cloudera/.m2/repository/com/sun/jersey/jersey-json/1.4/jersey-json-1.4.jar:/home/cloudera/.m2/repository/org/codehaus/jettison/jettison/1.1/jettison-1.1.jar:/home/cloudera/.m2/repository/com/sun/xml/bind/jaxb-impl/2.1.12/jaxb-impl-2.1.12.jar:/home/cloudera/.m2/repository/org/codehaus/jackson/jackson-core-asl/1.5.5/jackson-core-asl-1.5.5.jar:/home/cloudera/.m2/repository/org/codehaus/jackson/jackson-jaxrs/1.5.5/jackson-jaxrs-1.5.5.jar:/home/cloudera/.m2/repository/org/codehaus/jackson/jackson-xc/1.5.5/jackson-xc-1.5.5.jar:/home/cloudera/.m2/repository/com/sun/jersey/jersey-server/1.4/jersey-server-1.4.jar:/home/cloudera/.m2/repository/asm/asm/3.1/asm-3.1.jar:/home/cloudera/.m2/repository/javax/ws/rs/jsr311-api/1.1.1/jsr311-api-1.1.1.jar:/home/cloudera/.m2/repository/javax/xml/bind/jaxb-api/2.1/jaxb-api-2.1.jar:/home/cloudera/.m2/repository/javax/activation/activation/1.1/activation-1.1.jar:/home/cloudera/.m2/repository/stax/stax-api/1.0.1/stax-api-1.0.1.jar:/home/cloudera/.m2/repository/org/apache/hbase/hbase-client/1.1.2/hbase-client-1.1.2.jar:/home/cloudera/.m2/repository/org/apache/hbase/hbase-annotations/1.1.2/hbase-annotations-1.1.2.jar:/usr/java/jdk1.7.0_67-cloudera/lib/tools.jar:/home/cloudera/.m2/repository/org/apache/hbase/hbase-common/1.1.2/hbase-common-1.1.2.jar:/home/cloudera/.m2/repository/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar:/home/cloudera/.m2/repository/org/apache/hbase/hbase-protocol/1.1.2/hbase-protocol-1.1.2.jar:/home/cloudera/.m2/repository/commons-io/commons-io/2.4/commons-io-2.4.jar:/home/cloudera/.m2/repository/io/netty/netty-all/4.0.23.Final/netty-all-4.0.23.Final.jar:/home/cloudera/.m2/repository/org/apache/htrace/htrace-core/3.1.0-incubating/htrace-core-3.1.0-incubating.jar:/home/cloudera/.m2/repository/org/codehaus/jackson/jackson-mapper-asl/1.9.13/jackson-mapper-asl-1.9.13.jar:/home/cloudera/.m2/repository/org/jruby/jcodings/jcodings/1.0.8/jcodings-1.0.8.jar:/home/cloudera/.m2/repository/org/jruby/joni/joni/2.1.2/joni-2.1.2.jar:/home/cloudera/.m2/repository/org/apache/hadoop/hadoop-auth/2.5.1/hadoop-auth-2.5.1.jar:/home/cloudera/.m2/repository/org/apache/httpcomponents/httpclient/4.2.5/httpclient-4.2.5.jar:/home/cloudera/.m2/repository/org/apache/httpcomponents/httpcore/4.2.4/httpcore-4.2.4.jar:/home/cloudera/.m2/repository/org/apache/directory/server/apacheds-kerberos-codec/2.0.0-M15/apacheds-kerberos-codec-2.0.0-M15.jar:/home/cloudera/.m2/repository/org/apache/directory/server/apacheds-i18n/2.0.0-M15/apacheds-i18n-2.0.0-M15.jar:/home/cloudera/.m2/repository/org/apache/directory/api/api-asn1-api/1.0.0-M20/api-asn1-api-1.0.0-M20.jar:/home/cloudera/.m2/repository/org/apache/directory/api/api-util/1.0.0-M20/api-util-1.0.0-M20.jar:/home/cloudera/.m2/repository/org/apache/hadoop/hadoop-common/2.5.1/hadoop-common-2.5.1.jar:/home/cloudera/.m2/repository/org/apache/hadoop/hadoop-annotations/2.5.1/hadoop-annotations-2.5.1.jar:/home/cloudera/.m2/repository/org/apache/commons/commons-math3/3.1.1/commons-math3-3.1.1.jar:/home/cloudera/.m2/repository/commons-configuration/commons-configuration/1.6/commons-configuration-1.6.jar:/home/cloudera/.m2/repository/commons-digester/commons-digester/1.8/commons-digester-1.8.jar:/home/cloudera/.m2/repository/commons-beanutils/commons-beanutils/1.7.0/commons-beanutils-1.7.0.jar:/home/cloudera/.m2/repository/commons-beanutils/commons-beanutils-core/1.8.0/commons-beanutils-core-1.8.0.jar:/home/cloudera/.m2/repository/org/apache/avro/avro/1.7.4/avro-1.7.4.jar:/home/cloudera/.m2/repository/com/thoughtworks/paranamer/paranamer/2.3/paranamer-2.3.jar:/home/cloudera/.m2/repository/org/xerial/snappy/snappy-java/1.0.4.1/snappy-java-1.0.4.1.jar:/home/cloudera/.m2/repository/com/jcraft/jsch/0.1.42/jsch-0.1.42.jar:/home/cloudera/.m2/repository/com/google/code/findbugs/jsr305/1.3.9/jsr305-1.3.9.jar:/home/cloudera/.m2/repository/org/apache/commons/commons-compress/1.4.1/commons-compress-1.4.1.jar:/home/cloudera/.m2/repository/org/tukaani/xz/1.0/xz-1.0.jar:/home/cloudera/.m2/repository/org/apache/hadoop/hadoop-mapreduce-client-core/2.5.1/hadoop-mapreduce-client-core-2.5.1.jar:/home/cloudera/.m2/repository/org/apache/hadoop/hadoop-yarn-common/2.5.1/hadoop-yarn-common-2.5.1.jar:/home/cloudera/.m2/repository/org/apache/hadoop/hadoop-yarn-api/2.5.1/hadoop-yarn-api-2.5.1.jar:/home/cloudera/.m2/repository/io/netty/netty/3.6.2.Final/netty-3.6.2.Final.jar:/home/cloudera/.m2/repository/com/github/stephenc/findbugs/findbugs-annotations/1.3.9-1/findbugs-annotations-1.3.9-1.jar
2015-10-25 23:29:43,389 INFO  [main] zookeeper.ZooKeeper: Client environment:java.library.path=/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
2015-10-25 23:29:43,389 INFO  [main] zookeeper.ZooKeeper: Client environment:java.io.tmpdir=/tmp
2015-10-25 23:29:43,389 INFO  [main] zookeeper.ZooKeeper: Client environment:java.compiler=
2015-10-25 23:29:43,389 INFO  [main] zookeeper.ZooKeeper: Client environment:os.name=Linux
2015-10-25 23:29:43,389 INFO  [main] zookeeper.ZooKeeper: Client environment:os.arch=amd64
2015-10-25 23:29:43,390 INFO  [main] zookeeper.ZooKeeper: Client environment:os.version=2.6.32-358.el6.x86_64
2015-10-25 23:29:43,390 INFO  [main] zookeeper.ZooKeeper: Client environment:user.name=cloudera
2015-10-25 23:29:43,390 INFO  [main] zookeeper.ZooKeeper: Client environment:user.home=/home/cloudera
2015-10-25 23:29:43,390 INFO  [main] zookeeper.ZooKeeper: Client environment:user.dir=/home/cloudera/workspace/HelloHadoop
2015-10-25 23:29:43,392 INFO  [main] zookeeper.ZooKeeper: Initiating client connection, connectString=localhost:2181 sessionTimeout=180000 watcher=hconnection
2015-10-25 23:29:43,454 INFO  [main-SendThread()] zookeeper.ClientCnxn: Opening socket connection to server localhost/127.0.0.1:2181
2015-10-25 23:29:43,527 INFO  [main-SendThread(localhost:2181)] zookeeper.ClientCnxn: Socket connection established to localhost/127.0.0.1:2181, initiating session
2015-10-25 23:29:43,627 INFO  [main-SendThread(localhost:2181)] zookeeper.ClientCnxn: Session establishment complete on server localhost/127.0.0.1:2181, sessionid = 0x150a2c7aa8f000b, negotiated timeout = 40000
Exception in thread "main" java.lang.NumberFormatException: For input string: "60000�;�W��_�PBUF

quickstart.cloudera �� �����*

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at org.apache.hadoop.hbase.HServerAddress.(HServerAddress.java:63)
at org.apache.hadoop.hbase.MasterAddressTracker.getMasterAddress(MasterAddressTracker.java:63)
at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.getMaster(HConnectionManager.java:353)
at org.apache.hadoop.hbase.client.HBaseAdmin.(HBaseAdmin.java:89)
at thbase.tutorialPoint.TestHBase.main(TestHBase.java:21)

======================================================================

In my pom.xml

I have

====================================================================


<!-- hadoop dependency -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-core</artifactId>
<version>0.20.2</version>
</dependency>

<!-- hbase -->
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase</artifactId>
<version>0.90.3</version>
</dependency>

<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.1.2</version>
</dependency>

====================================================================

The problem or Issue is inside the versions of the dependencies

we have included 0.****  with 1.****

so the solution

include all dependencies with compatible version
that is from either

0.**** or from only 1.****

I have used 1.1.1 versions for all
===================================================================


<dependencies>
<!-- hadoop dependency -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-core</artifactId>
<version>1.1.1</version>
</dependency>


<!-- hbase
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.1.1</version>
</dependency> -->



<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.1.1</version>
</dependency>

</dependencies>


=================================================================

This will solve the issue

Thursday, August 27, 2015

Create Simple Project with Hibernate + Maven

I have another with referring to mkyoung examples with  hibernate
http://cgenit.blogspot.com/2014/05/creating-hibernate-projects.html

but this is in brief
Here I use eclipse IDE and with Maven plugin

1. Create Maven project using maven plugin in  eclipse.
2. Hibernate is ORM tool. we need database table and Java class to map table .
3. As first we add hibernate dependency. We need to add hibernate dependencies

========================================

<!-- Hibernate framework -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.0.Final</version>
</dependency>

========================================
 4. Hibernate configuration file(hibernate.cfg.xml) - we need to config data base. we use MySql. we do this using hibernate configuration file
========================================

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>

<!-- Assume hibernateBasic is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/hibernateBasic
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root123
</property>
<!-- JDBC connectiopn pool (use built in) -->
<property name="connection.pool_size">1</property>
<!-- drop and recreate the database schema on startup -->
<property name="hbmtoddl.auto">create</property>

</session-factory>
</hibernate-configuration>


========================================



5. As we use Mysql we need to add the dependency jar for mysql connector
========================================

                <!-- MySQL database driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>

========================================
 6. Now we create the Model or dto class, UserDetail

=================================================================
package hibernate.basic.dto;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class UserDetails {

@Id
private int userId;
private String userName;

public int getUserId() {
return userId;
}

public void setUserId(int userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

}


==================================================================

7. annotate with @Entity - we need to tell  dto is and entity class map to table
 @Id = map the id - USe "javax.persistence"  annotation over hibernate annotation

8. we need to add the annotated class to configuration

                 <!-- Names the annotated entity class -->
<mapping class="hibernate.basic.dto.UserDetails"/>

9. Now to save the dto -
 Create Session factory - singleton, configurations for database. "hibernate.cfg.xml" file has details using this configurations we create Session Factory
Using Session factory , we create sessions -

======================================================================

package hibernate.basic.main;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import hibernate.basic.dto.UserDetails;

public class HibernateTest {
public static void main(String[] args) {

// set up user object
UserDetails userDetails = new UserDetails();
userDetails.setUserId(1);
userDetails.setUserName("kamal");

// now save object
// config the database. once configure, we build the Session Factory
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();

// create session using Session factory
Session session = sessionFactory.openSession();

// before save, we create transaction
// transaction create single unit of work
session.beginTransaction();
session.save(userDetails);

// once save end transaction using commit
session.getTransaction().commit();

session.close();

}
}

======================================================================

As we are using property "property name="hibernate.hbm2ddl.auto"" as "create"
this will create the database scheme every time transaction happens


If you need the final configuration of , we are not using xml mapping

======================================================================
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>

<!-- Assume hibernateBasic is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/hibernateBasic
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root123
</property>
<!-- JDBC connectiopn pool (use built in) -->
<property name="connection.pool_size">1</property>
<!-- drop and recreate the database schema on startup -->
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>


<!-- List of XML mapping files -->
<!-- <mapping resource="Employee.hbm.xml" /> -->

<!-- Names the annotated entity class -->
<mapping class="hibernate.basic.dto.UserDetails" />

</session-factory>
</hibernate-configuration>

======================================================================



output of the program
=====================================================================
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table if exists UserDetails
Hibernate: create table UserDetails (userId integer not null, userName varchar(255), primary key (userId))
Aug ********* PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into UserDetails (userName, userId) values (?, ?)
Hibernate: update UserDetails set userName=? where userId=?

=====================================================================

Summary
1. create maven project
2. add maven dependency for hibernate and Mysql connector
3. config database for hibernate - hibernate.cfg.xml , put it in resources
4. create model class  and map using annotation "javax.persistence"  @Entity and @Id
5. put the annotated model class to hibernate configuration file
6. to save . Create Session factory using the given configuration in hibernate.cfg.xml.
 Use the Session factory to create session.
 Open session and begin transaction - to create single unit of work
 commit and close session


Note : we have used "hbm2ddl" property "create" , where this will create brand new fresh table every time transaction executes.

If you need to few things

1. Let's add two objects

============================================================
// set up user object
UserDetails userDetails = new UserDetails();
userDetails.setUserId(1);
userDetails.setUserName("kamal");

UserDetails userDetails2 = new UserDetails();
userDetails2.setUserId(2);
userDetails2.setUserName("kamal2");

                  // now save object
// config the database. once configure, we build the Session Factory
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();

// create session using Session factory
Session session = sessionFactory.openSession();

// before save, we create transaction
// transaction create single unit of work
session.beginTransaction();
session.save(userDetails);
session.save(userDetails);
session.save(userDetails2);

// once save end transaction using commit
session.getTransaction().commit();

session.close();

=======================================================
 
Output
=======================================================
# userId, userName
'1', 'kamal'
'2', 'kamal2'

=======================================================

This has no big deal as this will add two entries

output of eclipse will be as below. you can see two insert entries

============================================================
Hibernate: drop table if exists UserDetails
Hibernate: create table UserDetails (userId integer not null, userName varchar(255), primary key (userId))
********* PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into UserDetails (userName, userId) values (?, ?)
Hibernate: insert into UserDetails (userName, userId) values (?, ?)

=======================================================================

2. Now let's change the name or change the value of a model object and see what will happen

============================================================
// set up user object
UserDetails userDetails = new UserDetails();
userDetails.setUserId(1);
userDetails.setUserName("kamal");



// now save object
// config the database. once configure, we build the Session Factory
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();

// create session using Session factory
Session session = sessionFactory.openSession();

// before save, we create transaction
// transaction create single unit of work
session.beginTransaction();
session.save(userDetails);
userDetails.setUserName("name2");
session.save(userDetails);


// once save end transaction using commit
session.getTransaction().commit();

session.close();

============================================================

Output
=======================================================
# userId, userName
'1', 'name2'


=======================================================

Note : you can see the final value has been change. That is because we are using same object and we changing the values of the same reference object before commit.
Note : Before commit.

Also if you look at the eclipse output, you can see the insert and update both statements. So now you may have a problem of session level cache.

why hibernate does make insert and update ?? why not in one single db call ??


eclipse output
=======================================================
Hibernate: drop table if exists UserDetails
Hibernate: create table UserDetails (userId integer not null, userName varchar(255), primary key (userId))
Aug************* PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into UserDetails (userName, userId) values (?, ?)
Hibernate: update UserDetails set userName=? where userId=?
=======================================================

3. Now let's comment the save of  the first model object and save the second object and see what will happen.

============================================================

// set up user object
UserDetails userDetails = new UserDetails();
userDetails.setUserId(1);
userDetails.setUserName("kamal");

UserDetails userDetails2 = new UserDetails();
userDetails2.setUserId(2);
userDetails2.setUserName("kamal2");

// now save object
// config the database. once configure, we build the Session Factory
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();

// create session using Session factory
Session session = sessionFactory.openSession();

// before save, we create transaction
// transaction create single unit of work
session.beginTransaction();
session.save(userDetails);
userDetails.setUserName("name2");
// session.save(userDetails);
session.save(userDetails2);

// once save end transaction using commit
session.getTransaction().commit();

session.close();
============================================================


eclipse output
============================================================
Hibernate: drop table if exists UserDetails
Hibernate: create table UserDetails (userId integer not null, userName varchar(255), primary key (userId))
Aug ********* PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into UserDetails (userName, userId) values (?, ?)
Hibernate: insert into UserDetails (userName, userId) values (?, ?)
Hibernate: update UserDetails set userName=? where userId=?
============================================================

db output
============================================================
# userId, userName
'1', 'name2'
'2', 'kamal2'

============================================================

OOOhhh , it's still adding the value to the database and you can see the both insert and update statement execution flow in the eclipse output.

Whether we call save it or not, the object will be saved with the initial state ("insert  statement") and the update of the state change, update name. All will be saved or persist to data base.

Note: In all above cases, we change the value of the first model object after saving it or after persist. So the once it's persist - the changes are persist in the database as you see.
Also two transations - Insert and Update.

If you do the change of state before save or persist(), then there will be only one insert command to the database. This is the answer for the what is happening with the session level cache.


You will understand more with the hibernate object states and difference between method save() and persist() and update() and dirty checking concepts.

***

Saving without Hibernate
1. we need JDBC Database configuration
2. The model object or POJO class
3. Service method to create a model object
4. Database design
5. DAO methods to save the object using SQL queries



With Hibernate
1. Hibernate Configuration  - JDBC Database configuration
2. Annotation (prevously we have xml mapping file hbm)  -  model object
3. Use Hibernate API - Service method to create a model object
4. Database deign -  Not needed
5. Dao Method - Not needed







Wednesday, July 29, 2015

The archive: xxx hibernate3-3.2.3.GA.jar which is referenced by the classpath, does not exist.

This is recent error came with running a maven project in the eclipse.
I just copied one of the mkyoung test projects on AOP declarative transaction and it gave me the error when trying to run the main method.

error
=================================================

The archive: C:/Users/xxxFolder/.m2/repository/hibernate/hibernate3/3.2.3.GA/hibernate3-3.2.3.GA.jar which is referenced by the classpath, does not exist.

=================================================

Initially pom.xml was refeerenced with

<dependency>
<groupId>hibernate</groupId>
<artifactId>hibernate3</artifactId>
<version>3.2.3.GA</version>
</dependency>


where as this could not found i changed to

                <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.3.ga</version>
</dependency>

And the above issue comes as i did not create dependency file and when i import the project to the eclipse , it still use old dependency file.

So it better to build the dependency file again.

Solution
----------

Just delete ".classpath"  file and ".project" file from the folder and create again by running commad

mvn clean eclipse:eclispe

This will create brand new  ".classpath"  file and ".project" file and issue will be sorted.

Reference project :
http://www.mkyong.com/spring/spring-aop-transaction-management-in-hibernate/


Thursday, July 23, 2015

Find java home set or not

This is to tell you how to find whether you have set the JAVA_HOME

just take the command prompt.

and execute the command

 echo "%JAVA_HOME%"

you will get the output as path for JAVA_HOME

"C:\Program Files\Java\jdk1.7.0_13"

so output in the command line will be as below

===================================================


C:\Users\aprasad> echo "%JAVA_HOME%"
"C:\Program Files\Java\jdk1.7.0_13"


===================================================


Monday, June 29, 2015

Access Webserice - REST

once web service up and running we need to test that app. Alos when we are given end point of REST web app we need to verify.
We can just type the URI and get the details or response given from REST web service.
IF we get the URI for GET request for the example app We built,

http://localhost:8080/Rest/rest/employeeservices/getemployeedetail?employeeId=1

accessing through browser will give us the output

<employee>
<dateOfJoining>01-02-2001</dateOfJoining>
<department>Sales</department>
<email>test@example.com</email>
<employeeId>675436</employeeId>
<firstName>John</firstName>
<lastName>Smith</lastName>
</employee>


but here we don't have much options.
here we get the output in xml format. But if you can remember our service implementation it produces both "xml" and "json"

=======================================================================
@Path("/")
@WebService(name="employeeService" , targetNamespace="http://localhost/cxf-rest/example")
public interface CxfRestService {

@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/getemployeedetail")
public Response getEmployeeDetails(
@QueryParam("employeeId") String employeeId);
}
=======================================================================

So if we need to get the output in the json format then we need to set the few setting "Accept=application/xml"

to help to achieve all these thing we need to use http client.There are various res client applications in the web and here i will be using "Advance Rest Client " plugin in the chrome.
In Rest Client you set the values for Header , type of request and etc.





You can see all the details here.
Request header, Response Header, REST URI, type of the call, and the output - here in XML

So our service produces, both xml and json
let's change output for json.

how to do that ?
Then set the "Accept" in the header "application/json"  for "json".



you can see the out in json format

====================================================================
{
firstName"John"
lastName"Smith"
employeeId"675436"
email"test@example.com"
dateOfJoining"01-02-2001"
department"Sales"
}
====================================================================


Access Webserice - REST1

once web service up and running we need to test that app. Alos when we are given end point of REST web app we need to verify.
We can just type the URI and get the details or response given from REST web service.
IF we get the URI for GET request for the example app We built,

http://localhost:8080/Rest/rest/employeeservices/getemployeedetail?employeeId=1

accessing through browser will give us the output

<employee>
<dateOfJoining>01-02-2001</dateOfJoining>
<department>Sales</department>
<email>test@example.com</email>
<employeeId>675436</employeeId>
<firstName>John</firstName>
<lastName>Smith</lastName>
</employee>


but here we don't have much options.
here we get the output in xml format. But if you can remember our service implementation it produces both "xml" and "json"

Access Webserice - REST

once web service up and running we need to test that app. Alos when we are given end point of REST web app we need to verify.
We can just type the URI and get the details or response given from REST web service.
IF we get the URI for GET request for the example app We built,

http://localhost:8080/Rest/rest/employeeservices/getemployeedetail?employeeId=1

accessing through browser will give us the output

<employee>
<dateOfJoining>01-02-2001</dateOfJoining>
<department>Sales</department>
<email>test@example.com</email>
<employeeId>675436</employeeId>
<firstName>John</firstName>
<lastName>Smith</lastName>
</employee>


but here we don't have much options.
here we get the output in xml format. But if you can remember our service implementation it produces both "xml" and "json"

Thursday, June 25, 2015

Creating WebService

Let's create a web service.
We will use maven as build tool and it will makes our life easy.
I will be using STS , Spring Tool Suite.

First we create a maven  web project using STS.
It will have below structure.
Web Project structure



you can build war file using maven tool.
Go to folder where "pom.xml" file exists. and open a command window
execute the maven command

===============
mvn clean package
==============

above command will build the war file.
eg: Here my folder path is "C:\eclipseWorkSpace\2015-01-19_SpringSecurity\Rest>"  where "pom.xml" file reside and remember this the basic web project create with maven using STS. you can create a web project using maven commands directly also. So when i execute the command "mvn clean package " in the command line I have to change the directory to the above mention folder where "pom.xml" resides.
you will see the war file will be created inside target directory. "C:\eclipseWorkSpace\2015-01-19_SpringSecurity\Rest\target"

Web project structure after building war file - Rest.war created

Now get the war file and deploy in the tomcat.
to deploy copy "Rest.war" and paste it inside "webapps" folder inside tomcat.

To refresh your knowledge in tomcat, we can get the tomcat from site and unzip and go to "bin" folder
Here in my case it is "C:\Softwares\Apache\Apache Tomcat\Apache Tomcat 8.0.3\apache-tomcat-8.0.3\bin" and open commad window. set the path to bin directory. execute the command "catalina.bat run"

===================================
C:\Softwares\Apache\Apache Tomcat\Apache Tomcat 8.0.3\apache-tomcat-8.0.3\bin>catalina.bat run
===================================

you will see the starting of the tomcat and trace will shown in the same command window.
If you need you can also run "startup " also, but it will have a seperate window open and run tomcat.

Now you application is deployed in tomcat and to test open browser and type "http://localhost:8080/Rest/" and you will see the default message or default page created with the app showing "Hello World!" in the browser.

Steps we did so far
========
1. create a maven web project using STS
2. build the project using maven - command line "mvn clean package"
3. deploy the web project "war file" in the  tomcat and view in the browser.

Above are the simple steps to create a default web project , pakage war file , deploy and test whether create project really works.

Below are the inside of the files created in the web project. Initially we do not have lots of files only basic files and folder structure will be as shown above and i won't try to explain it again.

Web.xml
======================================================================
<!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>Archetype Created Web Application</display-name>
</web-app>
======================================================================

index.jsp
======================================================================
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
======================================================================

pom.properties
======================================================================
#Generated by Maven
#Fri Jun 26 10:41:37 IST 2015
version=0.0.1-SNAPSHOT
groupId=com.webservice.rest
artifactId=Rest

======================================================================

pom.xml
======================================================================
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.webservice.rest</groupId>
  <artifactId>Rest</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Rest Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>Rest</finalName>
  </build>
</project>
======================================================================

Now let's go to create the web service application.
Here we use Apache CXF , spring , Jaxon, JAXB

First I will add all coding 

REST Web Service
---------------------
All dependencies

Pom.xml
======================================================================
<modelVersion>4.0.0</modelVersion>
<groupId>com.webservice.rest</groupId>
<artifactId>Rest</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT&lt;/version>
<name>Rest Maven Webapp</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope&gt;
</dependency>

<!-- Spring Dependencies -->
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-core&lt;/artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-context</artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-web&lt;/artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-beans</artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>

<!-- XML dependency -->
<dependency>
<groupId>javax.xml.bind&lt;/groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>

<!-- Apache CXF Dependencies -->
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId&gt;
<version>2.7.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>2.7.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>2.7.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId&gt;
<version>2.7.13</version>
</dependency>
<!-- Jackson The JSON Producer dependency -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>
</dependencies>
<build>
<finalName>Rest</finalName>
</build>
</project>

======================================================================

web.xml
======================================================================
<?xml version="1.0" encoding="UTF-8"?>
id="WebApp_ID" version="3.0">


<display-name>Archetype Created Web Application</display-name&gt;

<welcome-file-list>
<welcome-file>index.jsp&lt;/welcome-file>
</welcome-file-list>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/beans.xml</param-value>
</context-param>

<servlet>
<servlet-name>CXFServlet</servlet-name&gt;
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class&gt;
</servlet>

<servlet-mapping>
<servlet-name>CXFServlet</servlet-name&gt;
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

</web-app>

======================================================================

Employee.java    -->model class
======================================================================
package com.rest.cxfrestservice.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employee")
public class Employee {
private String firstName;
private String lastName;
private String employeeId;
private String email;
private String dateOfJoining;
private String department;

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;
}

public String getEmployeeId() {
return employeeId;
}

public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getDateOfJoining() {
return dateOfJoining;
}

public void setDateOfJoining(String dateOfJoining) {
this.dateOfJoining = dateOfJoining;
}

public String getDepartment() {
return department;
}

public void setDepartment(String department) {
this.department = department;
}

}

======================================================================

EmployeeDao .java --> dao class
======================================================================
package com.rest.cxfrestservice.dao;

import com.rest.cxfrestservice.model.Employee;

public class EmployeeDao {
public Employee getEmployeeDetails(String employeeId) {
Employee emp = new Employee();
emp.setDateOfJoining("01-02-2001");
emp.setDepartment("Sales");
emp.setEmail("test@example.com");
emp.setEmployeeId("675436");
emp.setFirstName("John");
emp.setLastName("Smith");
return emp;
}
}

======================================================================

CxfRestService .java  -->  Interface for Employee Service.
======================================================================
package com.rest.cxfrestservice.service;

import javax.jws.WebService;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 * Interface for Employee Service.
 * 
 * @author APRASAD
 * 
 */

@Path("/")
@WebService(name="employeeService" , targetNamespace="http://localhost/cxf-rest/example")
public interface CxfRestService {

@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/getemployeedetail")
public Response getEmployeeDetails(
@QueryParam("employeeId") String employeeId);
}

======================================================================

CxfRestServiceImpl .java --> implementation of for Employee Service.
======================================================================
package com.rest.cxfrestservice.service;

import javax.ws.rs.core.Response;

import org.springframework.beans.factory.annotation.Autowired;

import com.rest.cxfrestservice.dao.EmployeeDao;

public class CxfRestServiceImpl implements CxfRestService {

@Autowired
private EmployeeDao employeeDao;

public Response getEmployeeDetails(String employeeId) {
if (employeeId == null) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
return Response.ok(employeeDao.getEmployeeDetails(employeeId)).build();
}
}

======================================================================

bean.xml
======================================================================

<import resource="classpath:META-INF/cxf/cxf.xml" />
<context:component-scan base-package="com.rest.*" />

<jaxrs:server id="employeeService" address="/employeeservices"&gt;
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
<jaxrs:serviceBeans>
<ref bean="cxfServiceImpl" />
</jaxrs:serviceBeans>
<jaxrs:extensionMappings&gt;
<entry key="xml" value="application/xml" />
<entry key="json" value="application/json" />
</jaxrs:extensionMappings&gt;
</jaxrs:server>

<bean id="cxfServiceImpl" class="com.rest.cxfrestservice.service.CxfRestServiceImpl" />
<bean id="employeeDao" class="com.rest.cxfrestservice.dao.EmployeeDao" />
</beans>
======================================================================


access above depolyed jar with


you will get out as

======================================================================
<employee>
<dateOfJoining>01-02-2001</dateOfJoining>
<department>Sales</department>
<employeeId>675436</employeeId>
<firstName>John</firstName>
<lastName>Smith</lastName>
</employee>
======================================================================



======================================================================

<grammars/>
<resource path="/">
<resource path="getemployeedetail">
<method name="GET">
<request>
<param name="employeeId" style="query" type="xs:string"/>
</request>
<response>
<representation mediaType="application/xml"/&gt;
<representation mediaType="application/json"/&gt;
</response>
</method>
</resource>
</resource>
</resources>
</application>
======================================================================