Tuesday, July 23, 2013

Hibernate SessionFactory buildSessionFactory deprecated fix


Fix for Hibernate SessionFactory buildSessionFactory deprecation as of Hibernate 4.0 

private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

private static SessionFactory configureSessionFactory() throws HibernateException {
   Configuration configuration = new Configuration();
   configuration.configure();
   serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();        
   sessionFactory = configuration.buildSessionFactory(serviceRegistry);
   return sessionFactory;
}



Generic JDBC Program for Derby


This is a simple JDBC Program for Derby database. No standards followed, you can see that connection is not closed, statement is not cleared.

Can be used to check database connectivity.

SQL Queries
create table test (id integer, name varchar(10), age integer, address varchar(30));

insert into test values (1, 'test1', 20, '80 Absolute Avenue');
insert into test values (2, 'test2', 30, '90 Absolute Avenue');

select * from test



package com.hibernate.demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class GenericJDBC {

public static void main(String[] args) {
// TODO Auto-generated method stub
String url ="jdbc:derby://localhost:1527/sample;create=true";

Connection conn;

try
{

Class.forName("org.apache.derby.jdbc.ClientDriver");

conn = DriverManager.getConnection(url, "user", "user");

Statement st = conn.createStatement();

ResultSet rs = st.executeQuery("select * from test");

while(rs.next())
{
System.out.println(rs.getInt(1)
+" " + rs.getString(2) +
" " + rs.getInt(3)+ " "+
rs.getString(4));
}

}catch(Exception e)
{
e.printStackTrace();
}
finally
{

}

}

}

Wednesday, July 17, 2013

ANT Weblogic WebApp Sample File

This article contains the Weblogic Web Application Ant Sample deployment script.

Very useful for configuration and deployment.

<project name="AppBuilder" default="deploy" basedir="."> 
        <property file="build.properties"/> 
<!-- 
Tasks to be done 
1. clean 
2. init 
3. compile 
4. copy 
5. war 
 --> 
        <path id="classpath"> 
                <!--<fileset dir="${lib.dir}" includes="*.jar"/>--> 
                <fileset dir="common" includes="*.jar"/> 
        </path> 

        <target name="clean"> 
                <echo>Cleaning the ${build.dir} and ${dist.dir}</echo> 
                <delete dir="${build.dir}"/> 
                <delete dir="${dist.dir}"/> 
        </target> 
        <target name="init" depends="clean"> 
                <echo>Creating the required directories</echo> 
                <mkdir dir="${dist.dir}"/> 
                <mkdir dir="${build.dir}\WEB-INF\classes"/>                 
                <mkdir dir="${build.dir}\WEB-INF\lib"/> 
        </target> 

        <target name="compile" depends="init"> 
                <echo>Compile the source files</echo> 
                <javac srcdir="${src.dir}" destdir="${build.dir}\WEB-INF\classes"> 
                        <classpath refid="classpath"/> 
                </javac> 
        </target>         
        
        <target name="copy" depends="compile"> 
                <copy todir="${build.dir}"> 
                        <fileset dir="${web.content}"/> 
                </copy> 
                <copy todir="${build.dir}/WEB-INF/classes"> 
                        <fileset dir="${src.dir}" includes="**/*.properties, **/*.xml, **/*.wsdl"/> 
                </copy> 
        </target>                 

        <target name="war" depends="copy"> 
                <echo>Building the war file</echo> 
                <war destfile="${dist.dir}\${project.name}.war" webxml="${build.dir}\WEB-INF\web.xml"> 
                        <fileset dir="${build.dir}"/> 
                </war> 
        </target> 

        <taskdef name="wldeploy" classname="weblogic.ant.taskdefs.management.WLDeploy"> 
          <classpath> 
          <pathelement location="common/weblogic.jar"/> 
          </classpath> 
        </taskdef> 

        <target name="deploy"> 
           <wldeploy action="deploy" 
                  source="dist/SMDBWebservice.war" name="SMDBWebservice" 
                  user="weblogic" password="weblogic" verbose="true" adminurl="t3://localhost:7001" 
                  debug="true" targets="AdminServer"/> 
        </target> 

        <target name="undeploy"> 
           <wldeploy action="undeploy" name="SMDBWebservice" 
                  user="weblogic" password="weblogic" verbose="true" adminurl="t3://localhost:7001" 
                  debug="true" targets="AdminServer"/> 
        </target> 

        <target name="redeploy"> 
           <wldeploy action="redeploy" 
                  source="dist/SMDBWebservice.war" name="SMDBWebservice" 
                  user="weblogic" password="weblogic" verbose="true" 
                  adminurl="t3://localhost:7001" 
                  debug="true" targets="AdminServer"> 
                 <!--<files file="index.jsp"/>--> 
           </wldeploy> 
        </target> 

        <taskdef name="wlconfig" classname="weblogic.ant.taskdefs.management.WLConfig"> 
          <classpath> 
          <pathelement location="common/weblogic.jar"/> 
          </classpath> 
        </taskdef> 

        <taskdef name="wlserver" classname="weblogic.ant.taskdefs.management.WLServer"> 
          <classpath> 
          <pathelement location="common/weblogic.jar"/> 
          <pathelement location="common/ant-weblogic.jar"/> 
          </classpath> 
        </taskdef> 

<target name="JDBCPool"> 
                <wlconfig url="t3://localhost:7001" username="weblogic" password="weblogic"> 
                        
                        <query domain="base_domain" type="Server" name="AdminServer"  property="server"/> 
                <create type="JDBCConnectionPool" 
                         name="CMSPool"       
                         property="cmspool">       
                         <set attribute="CapacityIncrement" value="1"/>       
                         <set attribute="DriverName"         
                                         value="com.ibm.db2.jcc.DB2Driver"/>       
                         <set attribute="InitialCapacity" value="1"/>       
                         <set attribute="MaxCapacity" value="10"/>       
                         <set attribute="Password" value="smdbuat"/>       
                         <set attribute="Properties" value="user=dsmdd1d;SecurityMechanism=EncryptedUIDPassword;databaseName=DPSMSSMD;serverName=160.254.49.155;batchPerformanceWorkaround=true;portNumber=3600;"/>       
                         <set attribute="RefreshMinutes" value="0"/>       
                         <set attribute="ShrinkPeriodMinutes" value="15"/>       
                         <set attribute="ShrinkingEnabled" value="true"/>       
                         <set attribute="TestConnectionsOnRelease" value="false"/>       
                         <set attribute="TestConnectionsOnReserve" value="false"/>       
                         <set attribute="URL" value="jdbc:db2://160.254.49.155:3600/DPSMSSMD"/>       
                         <set attribute="Targets" value="${server}"/>   
                 </create> 

                 <create type="JDBCTxDataSource" name="CMSDataSource"> 
                        <set attribute="JNDIName" value="JDBCIBM2"/> 
                        <set attribute="PoolName" value="CMSPool"/> 
                        <set attribute="Targets" value="${server}"/> 
                 </create> 
        </wlconfig> 
</target> 

</project> 

Hello World with Apache Ant

Apache Ant (Another Neat Tool) is a Java library and Command line utility useful for automating batch code build process.

For example, let say there is Java Class file HelloWorld.java   you need to compile, jar, move and run. In command you will perform the following activities

To Compile 

javac HelloWorld.java

To Create the jar file 

jar -cvf HelloWorld.jar HelloWorld.class

or

jar -cvf HelloWorld.jar HelloWorld.class jar -cvf HelloWorld.jar HelloWorld.java

To Move the program 

move HelloWorld.jar HelloWorld1.jar

To run the program

java -cp HelloWorld.jar HelloWorld


Executing all the above steps is ok for one time, lets say you have to do 100 times in a month. This is troublesome and can be automated.

Lets see how this can be automated

Step 1: Download the Apache Ant Latest Stable Version

http://ant.apache.org



Step 2:  Extract the Zip file

Step 3:  Go to Environment Variables


Step 4:  Create variable ANT_HOME 


Step 5: Add ANT_HOME\bin in the path 


Step 6:  Open Command prompt and execute the command ant -version



Step 7:  Create the build.xml  


1. target element with name attribute 

<target name="clean"> 

Create target for each of your activities example, clean, compile, move, jar, execute etc., 

2.  Echo Command 

    <echo>Cleaning the directories</echo> 

The echo command is useful while running the ant, it show which step it is currently in. Basically it is just print command.

3. Depends Attribute

        <target name="init" depends="clean"> 

Depends is a very useful command which will execute the depends target before executing the current target. It is like parent child relationship.

4. Console Commands

                <javac srcdir="${currentfolder}\src" destdir="${currentfolder}\classes"> 
                        <classpath refid="classpath"/> 
                </javac> 

For most of the generic commands you have Ant Task defined, tasks such as Javac, Jar, War etc., 

5.  Project Root Element and Attributes

<project name="HelloWorld" default="execute" basedir="."> 

The project element defines the project name the default target it should execute and the base directory from where it should run. 

Sample build.xml file as below,

<project name="HelloWorld" default="execute" basedir="."> 
        <!-- <property file="build.properties"/> -->
<!-- Tasks to be done 1. clean  2. init  3. compile  4. jar 5. move 6.execute --> 
 
<property name="currentfolder" location="C:\Temp"/>
 
        <path id="classpath"> 
                <!--<fileset dir="${lib.dir}" includes="*.jar"/>--> 
        </path> 
<target name="clean"> 
                <echo>Cleaning the ${build.dir} and ${dist.dir}</echo> 
                <delete dir="${currentfolder}\classes"/> 
                <delete dir="${currentfolder}\lib"/> 
        </target> 
        <target name="init" depends="clean"> 
                <echo>Creating the required directories</echo> 
                <mkdir dir="${currentfolder}\classes"/> 
                <mkdir dir="${currentfolder}\lib"/> 
        </target> 

        <target name="compile" depends="init"> 
                <echo>Compile the source files</echo> 
                <javac srcdir="${currentfolder}\src" destdir="${currentfolder}\classes"> 
                        <classpath refid="classpath"/> 
                </javac> 
        </target>

<target name="jar" depends="compile">
<echo>Creating the jar file</echo> 
<jar jarfile="${currentfolder}\lib\HelloWorld.jar" basedir="${currentfolder}\classes"/>
</target>
        <target name="move" depends="jar"> 
<echo>Moving the HelloWorld.jar file</echo> 
<move file="${currentfolder}\lib\HelloWorld.jar" tofile="${currentfolder}\lib\HelloWorld1.jar"/>
        </target>            
        <target name="execute" depends="move"> 
                <echo>Executing Hello World</echo> 
<java  fork="true"
  failonerror="true"
  maxmemory="128m"
  classname="HelloWorld">
<arg value="-h"/>
<classpath>
  <pathelement location="${currentfolder}\lib\HelloWorld1.jar"/>
  <pathelement path="${java.class.path}"/>
</classpath>
</java>
        </target> 
</project> 



Step 8:  Go to Command and run ant where you have the build.xml




This is just tip of an Ice Berg, you can perform lot of activities like deploying code to the server, creating war files, create ear files, creating stubs, skeletons, ftp etc., As long you can perform some operation in command line you can perform the same using ant but in a sequence.