24
Sep
10

Hibernate – HelloWorld

This a my first hibernate Program.After going through the hibernate documentation from http://www.hibernate.org/docs.html i  have started trying this program and faced a couple of issues before make it to run successfully. Hope this will help you. 

  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    

Directory Structure

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)
  
 <!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>org.hsqldb.jdbcDriver</property>
        <property>jdbc:hsqldb:file:D:\data\workspace\Hibernate\database\mydb;shutdown=true</property> 
        <property>sa</property>
        <property> </property> 

        <property>2</property>
        <property>org.hibernate.dialect.HSQLDialect</property>
        <property>true</property>
        <property>update</property>
        <property>thread</property>
        <mapping resource=”hibernate.hbm.xml”/>
 </session-factory>
</hibernate-configuration> 

Hibernate.hbm.xml  – Defines the mapping between the Java Object and database table
  
  <?xml version=”1.0″?>
  <!DOCTYPE hibernate-mapping PUBLIC
  ”-//Hibernate/Hibernate Mapping DTD 3.0//EN”
  ”http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd“>
  <hibernate-mapping package=”com.upog.demo”>
   <class table=”USER_INFO”>
    <id column=”USER_ID”>
     <generator/>
    </id>
    <property column=”NAME”/>
    <property column=”CREATED_DATE”/>
   </class> 
  </hibernate-mapping> 

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 

<?xml version = “1.0″ encoding = “UTF-8″?>
<project name = “Hibernate” default = “run” basedir = “.”> 

        <property file=”${basedir}/project.properties”/>
        <property file=”${basedir}/log4j.properties”/>
        <property  value=”hibernate” />
        <property   value=”${basedir}/src”/>
        <property      value=”${basedir}/lib” />
        <property    value=”${basedir}/build”/>
        <property  value=”hibernate” />
        

        <path>
         <pathelement path=”${lib}/hibernate3.jar”/>
         <pathelement path=”${lib}/antlr-2.7.6.jar”/>
         <pathelement path=”${lib}/javassist-3.9.0.GA.jar”/>
         <pathelement path=”${lib}/jta-1.1.jar”/>
         <pathelement path=”${lib}/dom4j-1.6.1.jar”/>
         <pathelement path=”${lib}/commons-collections-3.1.jar”/>
         <pathelement path=”${lib}/slf4j-api-1.5.8.jar” />
         <pathelement path=”${lib}/slf4j-simple-1.5.2.jar” />
         <pathelement path=”${lib}/hsqldb.jar” />  
        </path>        
       
        <target>
                <delete dir=”${build}”/>
        </target> 

        <target depends=”clean”>
                <mkdir dir=”${build}”/>
        </target>
       
        <target depends=”mkdir” >
              <javac srcdir=”${source}”  destdir=”${build}”  includes=”com/**/*.java”>
                  <classpath refid=”dependencies”/>
              </javac>
        </target>
 
  <target name = “buildJar” depends=”compile”>
   <copy todir=”${build}”>
    <fileset dir=”${source}” includes = “*.xml, *.properties”/>
   </copy>
   <jar jarfile = “${build}/${jarname}.jar” basedir = “${build}”  />    
  </target>
       
  <target depends=”buildJar”>
   <java  classname=”com.upog.demo.HibernateTest” >
    <classpath >      
       <pathelement location=”${build}/${jarname}.jar”/> 
    </classpath >      
    <classpath refid=”dependencies”/>
    </java>               
  </target>   
 
</project> 

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

Let me know your comments 

14
Feb
10

Clipboard Copy And Paste in Flex web Application

Sometime we may  need to access clipboard data for our Applications. 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

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml ” layout=”absolute”>
<mx:TextArea id=”copyData” x=”70″ y=”96″ width=”272″ height=”65″/>
<mx:TextArea id=”pasteData” x=”70″ y=”195″ width=”272″ height=”65″/>
<mx:Button x=”417″ y=”118″ label=”Copy To Clipboard” width=”126″  click=”CopyToClipboard()”/>
<mx:Button x=”417″ y=”213″ label=”Paste From Clipboard” width=”126″ click=”PasteFromClipboard()”/>
<mx:Script>
<![CDATA[
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;
}
]]>
</mx:Script>
</mx:Application>

In index.template.html (flex generated html wrapper ) place the following code inside <script> . . . </script>

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 : The above program will work only in Internet explorer and morzilla firefox

copy to clipboard flex
05
Feb
10

Way to find Flash Debugger was installed in the system

    Some times we may not be sure whether normal flash player or Flash player debugger version was installed in our system. Flash Debugger version was required for Flash tracer, flex profiler and to capture run time flash errors

The Simple way to confirm that flash debugger version was installed in you system is by right click on a Launched SWF file in the browser and you should get the following Option as shown below


Flash Debugger Options

18
Oct
09

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

Directory Structure

Directory Structure

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<String, String> env = new Hashtable<String, String>();
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

<?xml version=”1.0″ encoding=”iso-8859-1″?>
<project name=”Ejb_HelloWorld” basedir = “.” default = “buildEar”>

<property file=”${basedir}/developer.properties”/>
<property name=”jarname” value=”HelloWorld-ejb” />

<property name=”appname” value=”HelloWorld” />

<property name=”src”         value=”${basedir}/src”/>
<property name=”build”        value=”${basedir}/build”/>
<property name=”dist”        value=”${basedir}/dist”/>
<property name=”lib”        value=”${basedir}/lib” />

<property name=”src.server”         value=”${src}/server”/>
<property name=”src.client”         value=”${src}/client”/>
<property name=”build.server”        value=”${build}/server”/>
<property name=”build.client”        value=”${build}/client”/>
<property name=”dist.server”        value=”${dist}/server”/>
<property name=”dist.client”        value=”${dist}/client”/>

<path id=”dependencies”>

<pathelement location=”${lib}/javax.ejb_3.0.1.jar”/>
<pathelement location=”${lib}/weblogic.jar”/>

</path>

<target name = “clean” >

<echo> “Cleaning the directory ” </echo>
<delete dir=”${build}” />
<delete dir=”${dist}” />

</target>

<target name=”compile” depends=”clean”>

<echo> “Compiling EJB ” </echo>
<echo message=”BEA_HOME: ${BEA_HOME}”/>
<echo message=”WLS_HOME: ${WLS_HOME}”/>
<mkdir dir=”${build}/server/classes”/>
<javac srcdir=”${src.server}” destdir=”${build}/server/classes” debug=”on” >
<classpath refid=”dependencies”/>
</javac>

</target>

<target name=”compileClient“>

<echo> “Compiling Client class ” </echo>
<mkdir dir=”${build.client}/classes”/>
<javac srcdir=”${src.client}” destdir=”${build.client}/classes” debug=”on” >
<classpath refid=”dependencies”/>
<classpath location=”${build.server}/classes” />
</javac>

</target>

<target name = “buildEar” depends=”compile”>

<echo> “Building EJB EAR” </echo>
<mkdir dir=”${dist.server}”/>
<jar jarfile = “${dist.server}/${jarname}.jar” basedir = “${build}/server/classes”  />
<jar jarfile = “${dist.server}/${appname}.ear”  basedir=”${dist.server}” />

</target>

<target name=”run” depends=”compileClient”>

<echo message=”Executing client class “> </echo>
<java classname= “com.upog.demo.HelloWorldClient” fork=”yes”>
<classpath>
<pathelement location=”${build.client}/classes”/>
<pathelement location=”${dist.server}/HelloWorld-ejb.jar”/>
<pathelement location=”${lib}/wlfullclient.jar”/>
</classpath>
</java>

</target>

</project>

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

Ant build

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 Upog It’s Working!”

05
Sep
09

Flex HttpService HelloWorld

I have done a sample Http-Service HelloWorld Program . This Program illustrates  data transfer from flex to java using Http service. Data are transferred in xml format.

Step 1: Define Http Service in mxml file

<mx:HTTPService id=”reg” method=”POST” url=”reg” result=”loginres()”>
<mx:request xmlns=”">
<myname>{myname.text}</myname>
<passwd>{passwd.text}</passwd>
</mx:request>
</mx:HTTPService>

Step 2: Map the HTTPService url in web.xml

<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/reg</url-pattern>
</servlet-mapping>


step 3: Call HTTPService’s send method on some event

step 4: The data Defined in HTTPService will be available in servlet that was mapped in web.xml

Step 5: Process the data in servlet  and send back to front end using  as xml string (e.g outputXML=”<status>” + name + “</status>”)

step 6: Retrieve the returned data from java in flex as shown below

<mx:ComboBox id=”resultData” dataProvider=”{reg.lastResult.status}” visible=”false” selectedIndex=”0″>
</mx:ComboBox>

The below is the deployment structure

Deployment Structure

Deployment Structure

Login.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml&#8221; layout=”absolute” cornerRadius=”20″ alpha=”0.38″ themeColor=”#00ff40″ backgroundGradientColors=”[#0080ff, #0080ff]” backgroundGradientAlphas=”[0.84, 0.5]” fontFamily=”Times New Roman” fontSize=”14″ borderColor=”#00ff80″ borderStyle=”solid” >

<mx:HTTPService id=”reg” method=”POST” url=”reg” result=”loginres()”>
<mx:request xmlns=”">
<myname>{myname.text}</myname>
<passsword>{passwd.text}</passsword>
</mx:request>
</mx:HTTPService>

<mx:ComboBox id=”resultData” dataProvider=”{reg.lastResult.status}” visible=”false” selectedIndex=”0″>
</mx:ComboBox>

<mx:Label x=”157″ y=”184″ text=”login” width=”107″/>
<mx:Label x=”157″ y=”250″ text=”passwd” width=”107″/>
<mx:TextInput id=”myname” x=”318″ y=”182″/>
<mx:TextInput id=”passwd” x=”318″ y=”248″/>
<mx:Button x=”318″ y=”302″ label=”submit” click=”onsubmit()” height=”26″/>

<mx:Script>
<![CDATA[
import mx.controls.Alert;

public function onsubmit(): void{

if(myname.text=="" || passwd.text=="")

{

Alert.show("please enter the values");
}
else
{
reg.cancel();
reg.send();
}
}

public function loginres():void{
Alert.show("HelloWorld " +  "Welcome " + resultData.text);

}

]]>
</mx:Script>

</mx:Application>

loginController.java

package com.sample;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class loginController extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request,response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException

{

String name=request.getParameter(“myname”);
String password=request.getParameter(“passwd”);

System.out.println(“\n name ” + name);
System.out.println(“\n password ” + password);

PrintWriter writer = null;
String outputXML = “”;
writer = response.getWriter();
outputXML=”<status>” + name + “</status>”;

writer.println(outputXML);

writer.flush();

writer.close();

}
}

web.xml


<?xml version=”1.0″ encoding=”ISO-8859-1″?>

<web-app xmlns=”http://java.sun.com/xml/ns/j2ee&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&#8221;
version=”2.4″>

<servlet>
<servlet-name>test</servlet-name>
<servlet-class>com.sample.loginController</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/reg</url-pattern>
</servlet-mapping>

<welcome-file-list> <welcome-file>login.swf</welcome-file> </welcome-file-list>

</web-app>

Output

output

22
Aug
09

BlazeDs – HelloWorld Example

BlazeDS is a server-based Java remoting technology that allows you to connect to back-end distributed data and push data in real-time to Adobe Flex and Adobe AIR rich Internet applications (RIA).

You can get more information on BlazeDs on the following link “http://livedocs.adobe.com/blazeds/1/blazeds_devguide/”>

Below Are the steps to configure and run a Sample Program Using BlazeDS

Requirement:

Apache-tomcat-6.0.18 (download zip (pgp, md5) )

FlexBuilder

Step1:
Create a folder named BlazeDs in ${Tomcat}/webapps

Step2:
Download the BlazeDS Binaries from the following link
Download the BlazeDS binary distribution and extract it to ${Tomcat}/webapps/BlazeDs

step3:
Create a java Program “HelloWorld.java” in ${tomcat}\webapps\BlazeDs\WEB-INF\classes location

public class HelloWorld

{
public HelloWorld(){}
public String sayHello()
{
return “Hello World. It’s Working”;
}
}
compile and create the class file in the same location

step4:

Add the Following node in ${tomcat}\webapps\BlazeDs\WEB-INF\flex\remoting-config.xml

<service id=”remoting-service”  class=”flex.messaging.services.RemotingService”>
. . .
. . .

<destination id=”HelloWorld”>
<properties>
<source>HelloWorld</source>
</properties>
</destination>

. . .
. . .

</service>

Step5:
Create a new Project(name “BlazeDS”) using Flex Builder.

Copy and Paste the below code in BlazeDs.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml&#8221; layout=”horizontal” >
<mx:RemoteObject id=”ro” destination=”HelloWorld” result=”resultHandler(event)” fault=”faultHandler(event)”/>
<mx:Panel x=”10″ y=”10″ width=”604″ height=”643″ layout=”absolute” backgroundColor=”#DFE8EC” cornerRadius=”6″ alpha=”1.0″ backgroundAlpha=”0.52″ borderStyle=”inset” fontWeight=”bold” themeColor=”#1611EF” color=”#1B3DE8″>
<mx:TextArea id=”text” text=”initial text” x=”240″ y=”61″ width=”273″ height=”56″/>
<mx:Text x=”62″ y=”10″ text=”Blaze DS Example” width=”431″ height=”28″ fontFamily=”Georgia” fontSize=”15″ alpha=”0.58″ color=”#389AAF” textAlign=”center” fontWeight=”bold” fontStyle=”italic”/>
<mx:Button x=”244″ y=”152″ label=”Click Me” fontStyle=”italic” themeColor=”#0B0BF6″ borderColor=”#291AE6″ click=”ro.sayHello()” />
<mx:Label x=”32″ y=”62″ text=”Data Returned from the server ” width=”189″ color=”#5BA9BA”/>
<mx:Button x=”338″ y=”152″ label=”Reset” fontStyle=”italic” themeColor=”#0B0BF6″ borderColor=”#291AE6″ click=”reset()”  width=”62″/>
</mx:Panel>

<mx:Script>
<![CDATA[

import mx.controls.Alert;

import mx.rpc.events.ResultEvent;

import mx.rpc.events.FaultEvent;

import mx.utils.ObjectUtil;

import mx.utils.StringUtil;

var str:String

private function resultHandler(event:ResultEvent):void

{

text.text= ObjectUtil.toString(event.result)

}

private function faultHandler(event:FaultEvent):void

{

Alert.show( ObjectUtil.toString(event.fault) );

}

public function reset():void{

text.text="initial text";

}

]]>
</mx:Script>

</mx:Application>

set the Additional compiler arguments for Flex Compiler

-services ${tomcat}\webapps\BlazeDS\WEB-INF\flex\services-config.xml -context-root /BlazeDs

Clean and build the Project again

now copy and paste the generated output files BlazeDS.html , BlazeDS.swf and AC_OETags files to ${tomcat}\webapps\BlazeDS\

Step6:

Stop and Start your tomcat server

Hit The Following URL

http://localhost:8080/BlazeDs/BlazeDS.swf  (or)

http://localhost:8080/BlazeDs/BlazeDS.html

output

21
Aug
09

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

Notify me of follow-up comments via email.




Follow

Get every new post delivered to your Inbox.