Pages

Thursday, September 22, 2011

First hibernate program – helloworld

SoftWare Used

1. Eclipse 3.2
2. Razorsql (http://www.razorsql.com/)
3 HsqlDB (http://hsqldb.org/)
4 JDK 1.6
5 ant

The following jar are requied to run the appication

1.hibernate3.jar
2.antlr-2.7.6.jar
3.javassist-3.9.0.GA.jar
4.jta-1.1.jar
5.dom4j-1.6.1.jar
6.commons-collections-3.1.jar
7.slf4j-api-1.5.8.jar
8.slf4j-simple-1.5.2.jar
9.hsqldb.jar

Most of the jars will be available in hibernate binary distribution, remaining can be downloaded from findjar.com

Below are the steps to develop and run the hibernate hsql Application

Create the directory structure and source files as shown below


JAVA SOURCE FILES

User.java

package com.upog.demo;
import java.util.Date;
public class User {
private int id;
private String name;
private Date date;
public User() {}

public int getId() {
return id;
}
private void setId(int id) {
this.id = id;
}

public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

HibernateUtil.java

package com.upog.demo;

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

public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try
{
return new Configuration().configure().buildSessionFactory();
}
catch (Exception e)
{
System.out.println(” SessionFactory creation failed” + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}

HibernateTest.java

package com.upog.demo;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class HibernateTest {

public static void RetrieveUser()
{
System.out.println(“Retrieving User list from USER_INFO ….”);
Session session = HibernateUtil.getSessionFactory().openSession();

List UserList = session.createQuery(“from User”).list();
for (Iterator iterator = UserList.iterator(); iterator.hasNext();)
{
User user = (User) iterator.next();
System.out.println(user.getName() + “\t ” + user.getId() + “\t ” + user.getDate());
}
session.close();

}

public static void saveUser( String title)
{
Session session = HibernateUtil.getSessionFactory().openSession();
User user = new User();
user.setName(title);
user.setDate(new Date());
System.out.println(“\n Saving user ” + user.getName());
session.save(user);
session.flush();
session.close();
}

public static void main (String args[])
{
saveUser(“abc”);
saveUser(“def”);
saveUser(“Hi”);
saveUser(“hello”);
RetrieveUser();

}

}

Hibernate Configuration Files
Hibernate.cfg.xml - Contains the information about the database like URL,diver,ID,Password etc
Note: Change the value of connection.url as per you project home (I have given absolute path)

”-//Hibernate/Hibernate Configuration DTD 3.0//EN”
”http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd“>



org.hsqldb.jdbcDriver
jdbc:hsqldb:file:D:\data\workspace\Hibernate\database\mydb;shutdown=true
sa


2
org.hibernate.dialect.HSQLDialect
true
update
thread




Hibernate.hbm.xml – Defines the mapping between the Java Object and database table


”-//Hibernate/Hibernate Mapping DTD 3.0//EN”
”http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd“>










Create USER_INFO table in hsqldb
1. Connect hsqldb using razor sql with the properties as given below.

Login : sa
Password :
Driver class : org.hsqldb.jdbcDriver
Driver location :${PROJECT_HOME}\lib\hsqldb.jar
JDBC URL :jdbc:hsqldb:file:${PROJECT_HOME}\database\mydb;shutdown=true
2. Execute the following command
CREATE MEMORY TABLE PUBLIC.USER_INFO(ID INTEGER DEFAULT 0 NOT NULL PRIMARY KEY,NAME VARCHAR(25),CREATED_DATE DATE)
3. close the connection
Build.xml

[























































Right click on the build.xml file in eclipse Then Click on Run As – > Ant Buid.
Read more

clipboard copy and paste in flex web application

In flex we can easily save our data to System clipboard by using System.setClipboard() method. For security reasons getting clipboard data from flex code is not allowed.

An alternate way to get the clipboard data to flex Application is through java script by ExternalInterface.call(). Once control was transferred to javaScript we can access the clipboard data and return it to flex Application. below is the attached code

CopyAndPaste.mxml








import mx.controls.Alert;
public function CopyToClipboard():void{
System.setClipboard(copyData.text);
}

public function PasteFromClipboard():void{
var str2:String=ExternalInterface.call("PasteFromClipboard");
pasteData.text=str2;
}
]]>



In index.template.html (flex generated html wrapper ) place the following code inside

function PasteFromClipboard()
{
var str=”"
var browser=navigator.appName;
if(browser==”Microsoft Internet Explorer”)
{
return (window.clipboardData.getData(‘Text’));
}
else if (window.netscape)
{
netscape.security.PrivilegeManager.enablePrivilege( ‘UniversalXPConnect’ );
this.clipboardid = Components.interfaces.nsIClipboard;
this.clipboard = Components.classes['@mozilla.org/widget/clipboard;1'].getService( this.clipboardid );
this.clipboardstring = Components.classes['@mozilla.org/supports-string;1'].createInstance( Components.interfaces.nsISupportsString );
netscape.security.PrivilegeManager.enablePrivilege( ‘UniversalXPConnect’ );
var transfer = Components.classes['@mozilla.org/widget/transferable;1'].createInstance( Components.interfaces.nsITransferable );
transfer.addDataFlavor( ‘text/unicode’ );
this.clipboard.getData( transfer, this.clipboardid.kGlobalClipboard );
var str = new Object();
var strLength = new Object();
transfer.getTransferData( ‘text/unicode’, str, strLength );
str = str.value.QueryInterface( Components.interfaces.nsISupportsString );
return str+”";
}
}

Note : Work only in Internet explorer and morzilla firefox

from upog.wordpress
Read more

EJB3 – Helloworld example using weblogic 10.3

It is sample EJB3 Program. It uses weblogic 10.3 server , jdk 1.6 and ant tool

you need the following jars to complie and run the EJB3 Application

wlfullclient.jar
javax.ejb_3.0.1.jar
weblogic.jar
The Ear file consisting of ejb was deployed in weblogic sevrer and it was invoked from a stand alone java client.

Below are the steps to develop sample EJB3 application

1.Create the directory structure and source files as shown below


Remote Interface

package com.upog.demo;

import javax.ejb.Remote;
@Remote
public interface HelloWorld

{
public void sayHello(String name);
}

Bean Class

package com.upog.demo;

import javax.ejb.Stateless;
@Stateless(mappedName=”HelloWorld”)
public class HelloWorldBean implements HelloWorld

{
public void sayHello(String name)

{
System.out.println(“Hello ” + name + ” It’s Working!”);

}

}

Client Program

package com.upog.demo;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;

public class HelloWorldClient {

private static HelloWorld helloWorld;
public static void main(String[] args)

{
try

{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,”weblogic.jndi.WLInitialContextFactory”);
env.put(Context.SECURITY_PRINCIPAL,”weblogic”);
env.put(Context.SECURITY_CREDENTIALS,”weblogic”);
env.put(Context.PROVIDER_URL,”t3://localhost:8003″);
Context ctx = new InitialContext(env);
System.out.println(“Initial Context created”);
helloWorld = (HelloWorld) ctx.lookup(“HelloWorld#com.upog.demo.HelloWorld”);
System.out.println(“lookup successful”);
System.out.println(“Calling EJB method . . .”);
helloWorld.sayHello(“Upog”);
System.out.println(“Output will be in Managed server console”);
}

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

}

}

Note : Change the value of PROVIDER_URL as per your weblogic server. Default value is 7001.

Also give your weblogic id and password for SECURITY_PRINCIPAL and SECURITY_CREDENTIALS

JNDI naming convention for other servers will be different(vendor specific).

For weblogic (mappedName#fully_qualified_name)

developer.properties

BEA_HOME = D:/data/bea
JAVA_HOME = ${BEA_HOME}/jdk160_05
WLS_HOME = ${BEA_HOME}/wlserver_10.3
project.home = D:/data/workspace/EJB-HelloWorld

wls.domain.path = ${BEA_HOME}/user_projects/domains/test_domain
wls.application.path = ${wls.domain.path}/applications

Note : change the value of BEA_HOME variable as per your weblogic

Build.xml






























“Cleaning the directory ”







“Compiling EJB ”











“Compiling Client class ”










“Building EJB EAR”





















2. Place the following jars in ${project.home}/lib folder

wlfullclient.jar

javax.ejb_3.0.1.jar

weblogic.jar

Note: To create wlfullclient.jar. pls refer weblogic docs

javax.ejb_3.0.1.jar will be in ${BEA_HOME}/modules

weblogic.jar will be in ${WLS_HOME}/server/lib

Deploying and Running the Application

1. RUN ant

D:\data\workspace\EJB-HelloWorld>ant

The following folders and class files will be created

Deploy the HelloWorld.ear created in dist folder in your Weblogic server. Ensure the state of the ear deployed was active

2. RUN ant run

D:\data\workspace\EJB-HelloWorld>ant run

The output will be in server console “Hello It’s Working!”
Read more

Java Program--first stepp--hello world.

java – hello world

First Java Program

First to Compile and run a java program you need a Java SE Development Kit . if you don’t have java SE Development Kit download and install from the above link

Below are the steps to compile and run a java Program

Step1.

create a folder JavaProg. I have Created in D:\data\JavaProg

Step2.

Open a text file copy and paste the helloWorld program and save it as “helloWorld.java” in D:\data\JavaProg

public class helloWorld

{

public static void main(String[] args)

{

System.out.println(“Hello World”);

}

}

Step3.

Open a command Promt and type the following commands



Commands are highlighted by a red box and output was highlighted by a green box..
Notify me of follow-up comments via email.
Read more

java phonebook application

It Is a Simple Java Phone Book Application Created Using Eclipse IDE. In this the data are stored in the File System in the form of Objects. Below are the Steps to create and run the Application

Step 1 : Create a New Java Procject Named phoneBookApp in Eclipse. and then Create a new class phoneBook(java file) Click Finish

Step2 : Create a file store.dat in D:/data/workspace/phoneBook/ Path Copy and Paste the below Prog in the “phoneBook. java” File





import java .io .*;

import java .util .*;



public class phoneBook

{

public static void main (String[] args)

{

phoneBook cl=new phoneBook();

BufferedReader br;

String ch=”";

try

{

System.out.println(“Phone Book Application Using JAVA prog”);

do

{

cl.menu();

br=new BufferedReader (new InputStreamReader(System.in));

System.out.print(“Enter your option :”);

ch=br.readLine();

if (ch.equals(“1″))

cl.new_record();

if (ch.equals(“2″))

cl.display_record();

if (ch.equals(“3″))

cl.display_by_name();

if (ch.equals(“4″))

cl.display_by_city();

if (ch.equals(“5″))

cl.display_record_first_letter();

if (ch.equals(“6″))

cl.replace_record();

if (ch.equals(“7″))

cl.delete_record();

if (ch.equals(“8″))

System.out.println(“Thanks”);

} while(!ch.equals(“8″));



}

catch(Exception E){}

}







public void new_record()

{

String id,name,city,add,number,total;

boolean bln=false;

try

{

Properties pr=new Properties();

FileInputStream fin=new FileInputStream(“D:/data/workspace/phoneBook/store.dat”);

if(fin!=null)

{

pr.load(fin);

}

BufferedReader br1=new BufferedReader (new InputStreamReader(System.in));

FileOutputStream fout=new FileOutputStream(“store.dat”);

for(;;)

{

System.out .println(“Enter the ‘ID’, ‘q’ for quit:”);

id=br1.readLine().toUpperCase();

bln=pr.containsKey(id);

if(bln)

{

System.out.println(“ID id already exists, Please Enter another ID:”);

continue;

}

if((id.toUpperCase()).equals(“Q”))

break;

System.out.println(“Enter name:”);

name=br1.readLine().toUpperCase();

System.out.println(“Enter Phone number:”);

number=br1.readLine().toUpperCase();

System.out.println(“Enter address:”);

add=br1.readLine().toUpperCase();

System.out.println(“Enter city:”);

city=br1.readLine().toUpperCase();

total=” Name=”+name+”,”+”Phone no=”+number+”,”+” Address=”+add+”,”+” City=”+city;

total=total.toUpperCase();

pr.put(id,total);

pr.store(fout,”My Telephone Book”);

}

fout.close();

}

catch(Exception e)

{

System.out.println(e);

}

}



public void display_record()

{

String;

String total=”";

int x=1;

try

{

FileInputStream fin=new FileInputStream(“store.dat”);

Properties pr1=new Properties();

pr1.load(fin);

Enumeration enum1=pr1.keys();

while(enum1.hasMoreElements())

{

id=enum1.nextElement().toString();

total=pr1.get(id).toString();

StringTokenizer stk=new StringTokenizer(total,”=,”);

System.out .println(“RECORD ::”+x+”\n”);

x++;

while(stk.hasMoreTokens())

{

String key=stk.nextToken();

String value=stk.nextToken();

System.out.println(“\t”+key+”::\t\t::”+value);

try

{

Thread.sleep(1000);

}

catch(Exception e){}

}

System.out.println(“”);

System.out.println(“”);

}

fin.close();

}

catch(Exception e){}

}

public void display_by_name()

{

String,id,total;

String key[]=new String[4];

String value[]=new String[4];

int i=0;



System.out.println(“Enter Name For Searching Record :-”);

try

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

name=br.readLine().toUpperCase();

FileInputStream fin=new FileInputStream(“store.dat”);

Properties pr1=new Properties();

pr1.load(fin);

Enumeration enum1=pr1.keys();

while(enum1.hasMoreElements())

{

id=enum1.nextElement().toString();

total=pr1.get(id).toString();

StringTokenizer stk=new StringTokenizer(total,”=,”);



while(stk.hasMoreTokens())

{



for(i=0;i<4;i++)

{

key[i]=stk.nextToken();

value[i]=stk.nextToken();

}

if(value[0].equals(name))

{

for(i=0;i<4;i++)

{

System.out.println(“\t”+key[i]+”:”+value[i]);

try

{

Thread.sleep(1500);

}

catch(Exception e){}

}





}

}

System.out.println(“”);





}

fin.close();

}

catch(Exception e){

System.out.println(e);

}

}



public void display_by_city()

{

String city=”",id,total;

String key2[]=new String[4];

String value2[]=new String[4];

int i=0;



System.out.println(“Enter City For Searching Record :-”);

try

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

city=br.readLine().toUpperCase();

FileInputStream fin=new FileInputStream(“store.dat”);

Properties pr1=new Properties();

pr1.load(fin);

Enumeration enum1=pr1.keys();

while(enum1.hasMoreElements())

{

id=enum1.nextElement().toString();

total=pr1.get(id).toString();

StringTokenizer stk=new StringTokenizer(total,”=,”);



while(stk.hasMoreTokens())

{

key2[i]=stk.nextToken();

value2[i]=stk.nextToken();

// System.out.println(“aaaaaaaaaaaaaaa”+value2[i]);

if(i==3)

{

if(value2[i].equals(city))

{

for(int j=0;j<4;j++)

{

System.out.println(“\t”+key2[j]+”:\t”+value2[j]);

try

{

Thread.sleep(1500);

}

catch(Exception e){}



}

}

}

i++;

if(i>3)

i=0;

}

System.out.println(“”);

System.out.println(“”);

}

fin.close();

}

catch(Exception e){

System.out.println(e);

}





}



public void display_record_first_letter()

{



String,id,total,str=”";

String key2[]=new String[4];

String[] value2=new String[4];

int i=0;





try

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println(“ Enter The First Letter Of any Name:”);

name=br.readLine();

name=name.substring(0,1).toUpperCase();

FileInputStream fin=new FileInputStream(“store.dat”);

Properties pr1=new Properties();

pr1.load(fin);

Enumeration enum1=pr1.keys();

while(enum1.hasMoreElements())

{

id=enum1.nextElement().toString();

total=pr1.get(id).toString();

StringTokenizer stk=new StringTokenizer(total,”=,”);



while(stk.hasMoreTokens())

{



for(i=0;i<4;i++)

{

key2[i]=stk.nextToken();

value2[i]=stk.nextToken();

}

str=value2[0].substring(0,1);



if(str.equals(name))

{

for(i=0;i<4;i++)

{

System.out.println(“\t”+key2[i]+”:\t”+value2[i]);

try

{

Thread.sleep(1500);

}

catch(Exception e){}

}

}



}

System.out.println(“”);

System.out.println(“”);







}

fin.close();

}

catch(Exception e){

System.out.println(e);

}

}

public void replace_record()

{

String id,name,city,add,number,total,list;

boolean bln=false;

try

{

Properties pr=new Properties();

FileInputStream fin=new FileInputStream(“store.dat”);

if(fin!=null)

{

pr.load(fin);

}

BufferedReader br1=new BufferedReader (new InputStreamReader(System.in));

FileOutputStream fout=new FileOutputStream(“store.dat”);

for(;;)

{

System.out .println(“Enter the ‘ID’, ‘q’ for quit:”);

id=br1.readLine().toUpperCase();

if((id.toUpperCase()).equals(“Q”))

break;



bln=pr.containsKey(id);

if(bln)

{

System.out.println(“ID id already exists, “);





System.out.println(“enter name:”);

name=br1.readLine().toUpperCase();

System.out.println(“enter Phone number:”);

number=br1.readLine().toUpperCase();

System.out.println(“enter address:”);

add=br1.readLine().toUpperCase();

System.out.println(“enter city:”);

city=br1.readLine().toUpperCase();

total=” Name=”+name+”,”+”Phone no=”+number+”,”+” Address=”+add+”,”+” City=”+city;

total=total.toUpperCase();

pr.put(id,total);

pr.store(fout,”My Telephone Book”);

}

else

{

System.out.println(“ID does’nt Exists, Please Enter A Valid ID:”);

continue;

}



}

pr.store(fout,”My Phone Book”);

fout.close();

}

catch(Exception e)

{

System.out.println(e);

}

}

public void delete_record()

{



String;

boolean bln=false;

try

{

Properties pr1=new Properties();

FileInputStream fin=new FileInputStream(“store.dat”);

if(fin!=null)

pr1.load(fin);



BufferedReader br1=new BufferedReader (new InputStreamReader(System.in));

FileOutputStream fout=new FileOutputStream(“store.dat”);

for(;;)

{

System.out .println(“Enter the ‘ID’, ‘q’ for quit:”);

id=br1.readLine().toUpperCase();

if((id.toUpperCase()).equals(“Q”))





break;



bln=pr1.containsKey(id);



if(bln)

{

System.out.println(“ID exists :”);

String str=pr1.remove(id).toString();

pr1.store(fout,”My Phone Book”);

try

{

Thread.sleep(1000);

}

catch(Exception e){}

System.out.println(“Record deleted successfully”);

}

else

{

System.out.println(“Enter Existing ID:”);

pr1.store(fout,”My Phone Book”);

}



}

pr1.store(fout,”My Phone Book”);

fin.close();

fout.close();

}

catch(Exception e)

{

System.out.println(e);

}

}









public void menu()

{

char ch=30;

char ch1=31;

int l;

for(int i=0;i<27;i++)

{

System.out.print(” “);

}

for(l=0;l<2;l++)

{



for(int j=0;j<38;j++)

{



System.out.print(ch);

}

System.out.println(“”);

for(int k=0;k<27;k++)

{

System.out.print(” “);

}

}

System.out.print(ch);

System.out.print(ch1);

for(int i=0;i<34;i++)

System.out.print(” “);

System.out.print(ch);

System.out.print(ch1);

System.out.println(“”);

for(int i=0;i<27;i++)

System.out.print(” “);



System.out.print(ch);

System.out.print(ch1+” “);

System.out.print (” 1. Enter new Record: “);



System.out.print(” “+ch);

System.out.println(ch1+” “);



for(int i=0;i<26;i++)

System.out.print(” “);

System.out.print(” “+ch1);

System.out.print(ch+” “);





System.out.print (” 2. Display All Record: “);

System.out.print(” “+ch);

System.out.println(ch1+” “);





for(int i=0;i<26;i++)

System.out.print(” “);

System.out.print(” “+ch);

System.out.print(ch1+” “);





System.out.print (” 3. Search Record by name: “);

System.out.print(” “+ch);

System.out.println(ch1+” “);





for(int i=0;i<26;i++)

System.out.print(” “);

System.out.print(” “+ch);

System.out.print(ch1+” “);



System.out.print (” 4. Search Record by city: “);

System.out.print(” “+ch);

System.out.println(ch1+” “);





for(int i=0;i<26;i++)

System.out.print(” “);

System.out.print(” “+ch);

System.out.print(ch1+” “);





System.out.print (” 5. Search Record by 1st letter:”);

System.out.print(” “+ch);

System.out.println(ch1+” “);





for(int i=0;i<26;i++)

System.out.print(” “);

System.out.print(” “+ch);

System.out.print(ch1+” “);





System.out .print(” 6. Replace Record: “);

System.out.print(” “+ch);

System.out.println(ch1+” “);





for(int i=0;i<26;i++)

System.out.print(” “);

System.out.print(” “+ch);

System.out.print(ch1+” “);





System.out .print(” 7. Delete Record: “);

System.out.print(” “+ch);

System.out.println(ch1+” “);





for(int i=0;i<26;i++)

System.out.print(” “);

System.out.print(” “+ch);

System.out.print(ch1+” “);





System.out .print(” 8. Exit: ”);

System.out.print(” “+ch);

System.out.println(ch1+” “);





for(int j=0;j<27;j++)

System.out.print(” “);

System.out.print(ch);

System.out.print(ch1);

for(int i=0;i<34;i++)

System.out.print(” “);

System.out.print(ch);

System.out.print(ch1);

System.out.println(“”);

for(int i=0;i<27;i++)

System.out.print(” “);

for(int i=0;i<38;i++)

System.out.print(ch);

System.out.println(“”);

for(int i=0;i<27;i++)

System.out.print(” “);

for(int i=0;i<38;i++)

System.out.print(ch);



}





}



OUTPUT :



Phone Book Application Using JAVA prog

1. Enter new Record:

2. Display All Record:

3. Search Record by name:

4. Search Record by city:

5. Search Record by 1st letter:

6. Replace Record:

7. Delete Record:

8. Exit:

Enter your option :1



Enter the ‘ID’, ‘q’ for quit:

123

enter name:

gopu

enter Phone number:

12345

enter address:

abc

enter city:

chennai

Enter the ‘ID’, ‘q’ for quit:

q
Read more