Você está na página 1de 89

B.E. 4/4 I semester BIT 432 MIDDLEWARE TECHNLOGIES LABORATORY List of Experiments Prescribed by Osmania University 1.

. Creation of a Distributed Name Server, using RMI 2. Creation of a Java Bean application for displaying graphical shapes 3. Developing an EJB for Student Information System. 4. Developing an EJB for Library Information System. 5. Creation of an ActiveX control for Time Table. 6. Developing a component for converting currency values using COM/.NET. 7. Developing a component for browsing the CD catalog using COM/.NET 8. Developing a component for retrieving information from message box using DCOM/.NET. 9. Developing a Middleware component for retrieving Stock Market Exchange information using CORBA 10. Developing a Middleware component for retrieving Bank Balance using CORBA.

Page 1 of 89

MIDDLEWARE TECHNOLOOGIES LAB CONTENTS


S No Title Pg No

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Creation of a Distributed Name Server, Using RMI Creation of a Distributed Name Server, Using RMI to design a calculator Creation of Distributed Name Server Using RMI to Access the Database Server Creation of a Java Bean Application for Displaying Graphical Shapes using BDK Creation of a Java Bean Application for Displaying Graphical Shapes without using BDK Developing an EJB for Displaying a Message Using Stateless Session Bean Developing an EJB for a Calculator Using Stateless Session Bean Developing an EJB for Student Information system Using Stateless Session Bean Developing an EJB for Library Information system Using State full Session Bean Creation of an Active-x Control for Time Table Developing A Component for Converting Currency Values Using COM/.NET Developing a Component for Browsing the CD Catalog Using COM/.NET Developing a Component for Retrieving Information from Message Box Using DCOM/.NET Developing a Middleware Component for Retrieving Message from Server Using CORBA Developing a Middleware Component for Retrieving Stock Market Exchange Information Using CORBA Developing a Middleware component for retrieving Bank Balance using CORBA

3 11 17 23 28 32 38 45 52 60 63 65 68 70 76 81

Page 2 of 89

1. Creation of a Distributed Name Server, Using RMI. AIM: Creation of a Distributed Name Server, Using RMI for displaying the string on client console. Software Required: J2SDK 1.4 or above, RMI compiler, JAVA compiler, JAVA runtime, Notepad Theory: Remote Method Invocation (RMI) 1. 2. 3. object. 4. 5. A remote object is always accessed via its remote interface. In RMI the terms server and client refer to objects, but not physical machines. In Java distributed object model, a remote object is one whose methods can be invoked from another Java Virtual Machine. Allows object-to-object communication between Java Virtual Machines. RMI is the action of invoking a method of a remote interface on a remote

6.

The stubs/skeletons layer intercepts method calls made by the client to the interface reference and redirects these calls to a remote object. Stubs are specific to the client side, whereas, skeletons are found on the server side.

7.

The remote reference layer handles the details relating to interpreting and managing references made by clients on the remote objects. It connects clients to remote objects that are running and exported to a server by a one-to-one connection link.

8.

The transport layer is based on TCP/IP connections between machines in a network.

Algorithm:

Page 3 of 89

Remote Method Invocation (RMI) Allows object-to-object communication between Java Virtual Machines. RMI is the action of invoking a method of a remote interface on a remote object. A remote object is always accessed via its remote interface. In RMI the terms server and client refer to objects, but not physical machines.
Client invoking method on the remote object

Remote Object on Server

Stub

Skeleton

Remote Reference Layer

Remote Reference Layer

TCP

TCP

IP Physical Layer Hardware Interfaces

IP

Hardware Interfaces

Procedure: The basic steps involved in writing client-server applications using RMI: 1. Defining a remote interface 2. Implementing the remote interface 3. Writing the client that uses the remote objects 4. Connecting stubs and skeletons 5. Starting the registry and registering the object 6. Running the server and the client. Defining the Remote interface: 1. The remote interface must be declared public 2. The remote interface must extend java.rmi.Remote interface 3. Each method must throw a java.rmi.RemoteException Page 4 of 89

4. If the remote methods have any remote objects as parameters or return types, they must be interface types not the implementation classes. 5. java.rmi.Remote interface has no methods Programming: // Program to create a remote interface import java.rmi.*; public interface MyRemoteInterface extends java.rmi.Remote { public String displayDate() throws RemoteException; } Implementing the Remote Interface: 1. The implementation class provides the implementation for methods defined in the remote interface. 2. The generic java.rmi.server.RemoteObject is an abstract class and describes the behavior for remote objects. 3. The abstract class java.rmi.server.RemoteServer describes the behavior associated with the server implementation and provides the basic semantics to support remote references. 4. java.rmi.server.RemoteServer has two subclasses : java.rmi.server.UnicastRemoteObject java.rmi.activation.Activatable // Program for implementation of the Remote Interface import java.io.*; import java.util.Date; import java.rmi.server.*; import java.rmi.*; public class MyImplementor extends UnicastRemoteObject implements MyRemoteInterface {

Page 5 of 89

public MyImplementor() throws RemoteException { super(); } public String displayDate() throws RemoteException { System.out.println(Hello! The date is + new Date()); } } A remote class can define any methods, but only methods in th remote interface can be invoked remotely. The Client application // Program to generate the client import java.rmi.*; import java.io.*; public class MyRemoteClient { public static void main(String[] args) { /*if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); }*/ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { System.out.println("Enter IP Address: "); String ipaddr = br.readLine(); /*System.out.println("Enter value2 : ");

Page 6 of 89

int value2 = Integer.parseInt(br.readLine()); System.out.println("The values are : " + value1 + " " + value2); MyRemoteServer mobj = new MyRemoteServer(); Naming.rebind("/MyRemoteServer",mobj);*/ MyRemoteInterface mobj = (MyRemoteInterface) Naming.lookup("rmi://localhost:1099/RemoteService"); String msg1 = mobj.displayDate(); String msg2 = mobj.displayHostname(ipaddr); System.out.println(msg1); System.out.println(msg2); } catch (RemoteException re) { System.err.println("Client Exception : " + re); } catch (IOException ioe) { System.err.println("The exception is : " + ioe); } catch (Exception e) { e.printStackTrace(); } } } The Server application // Program to implement the remote interface import java.rmi.*; import java.rmi.server.*; import java.util.*; import java.rmi.Naming;

Page 7 of 89

public class MyRemoteServer { public MyRemoteServer() { try { MyRemoteInterface c = new MyRemoteImplementer(); Naming.rebind("rmi://localhost:1099/RemoteService", c); } catch (Exception e) { System.out.println("Trouble: " + e); } } public static void main(String args[]) { new MyRemoteServer(); } } javac *.java to compile all the java files rmic Myimplementor to generate stubs and skeletons start rmiregistry java MyRemoteServer java MyRemoteClient Observations: The actual DNS application involves the following modifications to the above mentioned sample program:

Page 8 of 89

1) The services to be provided are to be declared in the remote interface declared by the user. The services could be: getIPAddress, getDomainName, returnIPAddress, returnDomainName 2) The above-mentioned services are to be implemented in the implementer class. As part of implementation the database is to be accessed to retrieve the DNS information, for which JDBC is to be made use of. 3) The client program would have code to get connected to the server and make the remote calls to the server for the required services. 4) The server program would create an instance of the remote implementer and would provide the services requested services to the client. Steps to be followed for execution: 1) All the programs are to be compiled using the command javac. 2) The stub is to be generated by compiling the implementer class using the command rmic <implementerclassname>. 3) The RMI registry service is then started using the command : start rmiregistry. 4) Then the server is registered with the RMI registry by running the server program using the command java. 5) The client is also then run using the command java. Result: If the input to the application is an IP Address, then, it should return back the Domain Name and vice versa.

Page 9 of 89

PreLab Questions:
1.

Why do we get an exception for an unexpected hostname and/or port number when we call Naming.lookup? Do we need to install the XXX_Stub file in the client's CLASSPATH? Does RMI require use of HTTP server? Why we get ClassNotFoundException? Will there be debugging mechanisms built into RMI? Why do we get a java.lang.ClassMismatchError while running the program? While sending an array of remote objects and receive an ArrayStoreException. What's going on? If we get a ClassNotFoundException for stub class when we try to register a remote object in the registry. What's happening? If server is died. Can we get a trace of the server activity?

2. 3. 4. 5. 6. 7.

8.

9.

Page 10 of 89

2. Creation of a Distributed Name Server, Using RMI to design a calculator AIM: Creation of a Distributed Name Server, Using RMI for adding two numbers (passed by client) on the server console and to return the value to client console. Software Required: J2SDK 1.4 or above, rmi compiler, java compiler, Notepad Theory: Remote Method Invocation (RMI) 1. In Java distributed object model, a remote object is one whose methods can be invoked from another Java Virtual Machine. 2. Allows object-to-object communication between Java Virtual Machines. 3. RMI is the action of invoking a method of a remote interface on a remote object. 4. A remote object is always accessed via its remote interface. 5. In RMI the terms server and client refer to objects, but not physical machines.

6. The stubs/skeletons layer intercepts method calls made by the client to the interface reference and redirects these calls to a remote object. Stubs are specific to the client side, whereas, skeletons are found on the server side. 7. The remote reference layer handles the details relating to interpreting and managing references made by clients on the remote objects. It connects clients to remote objects that are running and exported to a server by a one-to-one connection link. 8. The transport layer is based on TCP/IP connections between machines in a network.

Page 11 of 89

Procedure: The basic steps involved in writing client-server applications using RMI: 1. Defining a remote interface 2. Implementing the remote interface 3. Writing the client that uses the remote objects. 4. Creating and Connecting stubs and skeletons. 5. Starting the registry and registering the object. 6. Running the server and the client. Programming: Defining the Remote interface: 1. The remote interface must be declared public. 2. The remote interface must extend java.rmi.Remote interface. 3. Declare a remote method double add (double b1, double b2). 4. Each method must throw a java.rmi.RemoteException 5. java.rmi.Remote interface has no methods // Program to create a remote interface import java.rmi.*; public interface AddServerIntf extends Remote { double add(double d1, double d2) throws RemoteException; } Implementing the Remote Interface, and binding the remote object with registry: 1. The implementation class provides the implementation for methods defined in the remote interface. 2. The generic java.rmi.server.RemoteObject is an abstract class and describes the behavior for remote objects. 3. The abstract class java.rmi.server.RemoteServer describes the behavior associated with the server implementation and provides the basic semantics to support remote references. 4. Provide a default constructor to handle the exceptions thrown by super class.

Page 12 of 89

5. Implement the method double add(double b1, double b2). 6. In main() method create the new object for the class and invoke the rebind(BindName, object) method on Naming class. // Program for implementation of the remote Interface and binding the remote object with the RMI Registry import java.rmi.*; import java.rmi.server.*; public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf { public AddServerImpl() throws RemoteException { } public double add(double d1, double d2) throws RemoteException { } public static void main(String args[]) { try { AddServerImpl addServerImpl = new AddServerImpl(); Naming.rebind("AddServer", ServerImpl); } catch(Exception e) { System.out.println("Exception: " + e); } } } A remote class can define any methods, but only methods in the remote interface can be invoked remotely. The Client application: 1. The client application must import java.rmi packeage. 2. Create the object reference for remote interface by invoking the lookup() method on Naming Interface by passing the object bindName as a parameter. 3. Perform the casting to Interface type. 4. Enter the values to be added.

Page 13 of 89

// Program to generate the client import java.rmi.*; public class AddClient { public static void main(String args[]) { try { AddServerIntf addServerIntf = (AddServerIntf)Naming.lookup(addServerURL); System.out.println("The first number is: " + args[1]); double d1 = Double.valueOf(args[1]).doubleValue(); System.out.println("The second number is: " + args[2]); double d2 = Double.valueOf(args[2]).doubleValue(); System.out.println("The sum is: " + addServer.add(d1, d2)); } catch(Exception e) { System.out.println("Exception: " + e); } } } Steps to be followed for execution: 1. All the programs are to be compiled using the command javac. 2. The stub is to be generated by compiling the implementer class using the command rmic <implementerclassname>. 3. The RMI registry service is then started using the command : start rmiregistry. 4. Then the server is registered with the RMI registry by running the server program using the command java. 5. The client is also then run using the command java. Observations: 1. The actual DNS application involves the following modifications to the above mentioned sample program:

Page 14 of 89

2. The services to be provided are to be declared in the remote interface declared by the user. The services could be: getIPAddress, getDomainName, returnIPAddress, returnDomainName 3. The above-mentioned services are to be implemented in the implementer class. As part of implementation the database is to be accessed to retrieve the DNS information, for which JDBC is to be made use of. 4. The client program would have code to get connected to the server and make the remote calls to the server for the required services. 5. The server program would create an instance of the remote implementer and would provide the services requested services to the client. Result: If the input to the application is an IP Address, then, it should return back the Domain Name and vice versa.

PreLab Questions: 1. Where can we find a list of system properties that might be useful for implementing and debugging RMI applications?

Page 15 of 89

2. How do RMI clients contact remote RMI servers? 3. Why does remote method or "callback" routine fail with a nested java.net.UnknownHostException? 4. How does RMI obtain a server hostname in each of the versions of the JDK? 5. Why do Naming.bind and Naming.lookup take an extraordinarily long time on Windows? 6. Why do we get the exception "java.net.SocketException: Address already in use" when we try to run the registry? 7. How can we use RMI through a firewall? 8. How can we make outgoing RMI calls through a local firewall? 9. How can we receive incoming RMI calls through a local firewall?

Page 16 of 89

3. Creation of Distributed Name Server Using RMI to Access the Database Server AIM: Creation of a Distributed Name Server, Using RMI for accessing the oracle database server using jdbc type 4 driver to retrieve the table data. Software Required: J2SDK 1.4 or above, RMI compiler, JAVA compiler, JAVA runtime, Notepad, Oracle 9i and above, jdbc type 4 driver Theory: Remote Method Invocation (RMI) 1. In Java distributed object model, a remote object is one whose methods can be invoked from another Java Virtual Machine. 2. Allows object-to-object communication between Java Virtual Machines. 3. RMI is the action of invoking a method of a remote interface on a remote object. 4. A remote object is always accessed via its remote interface. 5. In RMI the terms server and client refer to objects, but not physical machines.

6. The stubs/skeletons layer intercepts method calls made by the client to the interface reference and redirects these calls to a remote object. Stubs are specific to the client side, whereas, skeletons are found on the server side. 7. The remote reference layer handles the details relating to interpreting and managing references made by clients on the remote objects. It connects clients to remote objects that are running and exported to a server by a one-to-one connection link. 8. The transport layer is based on TCP/IP connections between machines in a network.

Page 17 of 89

Procedure: The basic steps involved in writing client-server applications using RMI: 1. Defining a remote interface 2. Implementing the remote interface 3. Writing the client that uses the remote objects 4. Connecting stubs and skeletons 5. Starting the registry and registering the object 6. Running the server and the client. Programming: Defining the Remote interface: 1. The remote interface must be declared public 2. The remote interface must extend java.rmi.Remote interface 3. Each method must throw a java.rmi.RemoteException 4. Declare a method in interface String details() to give the rows of the table to client. 5. java.rmi.Remote interface has no methods // Program to create a remote interface public interface DbIface extends java.rmi.Remote { public String details() throws java.rmi.RemoteException; } Implementing the Remote Interface: 1. The implementation class provides the implementation for methods defined in the remote interface. 2. The generic java.rmi.server.RemoteObject is an abstract class and describes the behavior for remote objects. 3. The abstract class java.rmi.server.RemoteServer describes the behavior associated with the server implementation. 4. The class must import java.sql package for necessary database calls. 5. Load the driver class by invoking Class.forName(The Driver Class to be loaded).

Page 18 of 89

6. Obtain the connection with database by invoking getConnection(url,userid,password) on DriverManager Interface. 7. Send the SQL statements to DB Engine using excuteQuery(SQL Statement). 8. Access the database rows using ResultSet interface // Program for implementation of the remote Interface import java.rmi.*; import java.rmi.server.*; import java.sql.*;import java.io.*;import java.util.*; public class DbImpl extends UnicastRemoteObject { public DbImpl() throws RemoteException {} public String details() { try { Class.forName("oracle.jdbc.driver.OracleDriver"); }catch(ClassNotFoundException ce){ System.out.println("Unable to find the driver"); } try { Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521 ","scott","tiger"); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select *from emp"); while(rs.next()) { String name=rs.getString(2); System.out.println("The Name is:"+name);

Page 19 of 89

details=details+name; } con.close(); }catch(SQLException se){System.out.println("Nothing done");} return details; } public static void main(String[] args) { try { DbImpl obj=new DbImpl(); Naming.rebind("Arvind",obj); }catch(Exception e){System.out.println("Error Occured");} } } A remote class can define any methods, but only methods in the remote interface can be invoked remotely. The Client application: 5. The client application must import java.rmi packeage. 6. Create the object reference for remote interface by invoking the lookup() method on Naming Interface by passing the object bindName as a parameter. 7. Perform the casting to Interface type. 8. Invoke the remote method using the object of interface type. // Program to generate the client import java.rmi.*; public class Dbclient { public static void main(String[] args) {

Page 20 of 89

try { DbIface obj=Naming.lookup(addURL); System.out.println(obj.details()); } catch(Exception e) { System.out.println("Eror"); } } } Steps to be followed for execution: 1. All the programs are to be compiled using the command javac. 2. The stub is to be generated by compiling the implementer class using the command rmic <implementerclassname>. 3. The RMI registry service is then started using the command : start rmiregistry. 4. Then the server is registered with the RMI registry by running the server program using the command java. 5. The client is also then run using the command java. Observations: 6. The actual DNS application involves the following modifications to the above mentioned sample program: 7. The services to be provided are to be declared in the remote interface declared by the user. The services could be: getIPAddress, getDomainName, returnIPAddress, returnDomainName 8. The above-mentioned services are to be implemented in the implementer class. As part of implementation the database is to be accessed to retrieve the DNS information, for which JDBC is to be made use of. 9. The client program would have code to get connected to the server and make the remote calls to the server for the required services.

Page 21 of 89

10. The server program would create an instance of the remote implementer and would provide the services requested services to the client. Result: If the input to the application is an IP Address, then, it should return back the Domain Name and vice versa.

PreLab Questions:
1. 2. 3.

Will there be debugging mechanisms built into RMI? Why do we get a java.lang.ClassMismatchError while running the program? While sending an array of remote objects and receive an ArrayStoreException. What's going on? If we get a ClassNotFoundException for stub class when we try to register a remote object in the registry. What's happening? If server is died. Can we get a trace of the server activity? How do RMI clients contact remote RMI servers? Why does remote method or "callback" routine fail with a nested java.net.UnknownHostException?

4.

5. 6. 7.

8.

How does RMI obtain a server hostname in each of the versions of the JDK?

Page 22 of 89

4. Creation of a Java Bean Application for Displaying Graphical Shapes using BDK AIM: Creation of a Java Bean Application for Displaying Graphical Shapes using Bean Development Kit 1.1 Apparatus: J2SDK 1.4 and above, Bean Development Kit 1.1, Notepad Flow/Algorithm: Java Bean 1. A Java Bean is an independent and reusable software component that can be manipulated visually in a builder tool. 2. A bean is represented by an interface that is seen by the users. The environment must connect to the interface, if it wants to interact with this bean. Beans consist of three general-purpose interfaces: events, properties and methods. 3. Bean events are the mechanism for sending asynchronous messages between beans, and, between beans and containers. 4. The Java Beans architecture communicates primarily using event listener interfaces that extend EventListener 5. The properties of a bean can be changed .at runtime through their get and set methods. 6. The JavaBean introspection process exposes the properties, methods and events of a bean and also any global information about a bean. This is done through the BeanInfo interface, provided by the Java Beans API. Procedure: 1. For displaying the various graphical shapes, the classes from the AWT package can be used. 2. The code relevant to this can be put as part of an applet and can be executed in a Java enabled web browser. 3. The application can also be implemented using any of the builder tools like the Eclipse or the NetBeans. 4. The expected output from the application to be done is that it should display various graphical shapes in the browser or in the tool used.

Page 23 of 89

Programming: The following is a sample application that is used to display colors using a bean: // Program to test beans import java.awt.*; public class Bean01 { int b;Color c; public Bean() { setVisible(true); setSize(200,200); c=Color.yellow; } public int getShape() { return b; } public void setShape() { c=Color.red; repaint(); } public void paint(Graphics g) { Dimension d=getSize(); int w=d.width;int h=d.height; g.setColor(c); if(b==0) { g.drawLine(0,0,w,h); }

Page 24 of 89

else if(b==1) { g.fillRect(0,0,w,h); } else if(b==2) { g.fillOval(0,0,w,h); } else if(b==3) { g.fillRoundRect(0,w,h,50,50); } else if(b==4) { g.fillOval(0,w-100,h); } } } // Program to test beans import java.awt.*; import java.beans.*; public class IntrospectorDemo { public static void main(String[] args) { try { Class c = Class.forName("MyColors"); BeanInfo beanInfo = Introspector.getBeanInfo(c); System.out.println("properties:");

Page 25 of 89

PropertyDescriptor propertyDescriptor[] = beanInfo.getPropertyDescriptors(); for( int i=0; i < propertyDescriptor.length; i++) { System.out.println("\t" + propertyDescriptor[i].getName()); } System.out.println("events:"); EventSetDescriptor eventsetDescriptor[] = beanInfo.getEventSetDescriptors(); for(int i =0; i < eventsetDescriptor.length; i++) { System.out.println("\t" + eventsetDescriptor[i].getName()); } } catch (Exception e) { System.out.println("Exception caught. " + e); } } } Steps to be followed for execution: 1. Compile the java source file 2. create the jar file which includes the class file 3. Open the BDK1.1 4. Load the jar file, if it is successful then it will be displayed in ToolBox window. 5. Click on the jar file in the ToolBox and drag it into BeanBox window 6. Change the value of property of the bean, i.e. change the value of shape property value from 0 to suitable number.

Page 26 of 89

Results:

Observations & Result: The expected output from the application to be done is that it should display various graphical shapes in the browser or in the tool used. PreLab Questions: 1. Where can we find the API docs for the JavaBeans Activation Framework? 2. What is the correct way to invoke Beans.instantiate()? 3. Where to find the BeanInfo classes for the Swing components 4. What is introspection in JavaBeans? 5. How can a JavaBean be used as a distributed object in RMI or CORBA? 6. Are there tools to package existing C++ objects as Java Beans? 7. How to instantiate a serialized JavaBean into an applet if .ser file is in jar or zip archive? 8. What is the intention of the EventListener interface as it seems that it actually has no abstract methods no abstract attributes 9. How to read the initialization parameters for a bean, similar to what happens in servlets when we user the ServletConfig class and then use it's etInitParameter()

Page 27 of 89

10. Can we specify a custom class loader to load any beans? 11. With regards to JavaBeans, what is a manifest file and how is it used?

Page 28 of 89

5. Creation of a Java Bean Application for Displaying Graphical Shapes without using BDK AIM: Creation of a Java Bean Application for Displaying Graphical Shapes without using BDK Software Required: J2SDK 1.4 or above, apletviewer, Internet Explorer or any Browser Flow/Algorithm: Java Bean 1. A Java Bean is an independent and reusable software component that can be manipulated visually in a builder tool. 2. A bean is represented by an interface that is seen by the users. The environment must connect to the interface, if it wants to interact with this bean. Beans consist of three general-purpose interfaces: events, properties and methods. 3. Bean events are the mechanism for sending asynchronous messages between beans, and, between beans and containers. 4. The Java Beans architecture communicates primarily using event listener interfaces that extend EventListener 5. The properties of a bean can be changed .at runtime through their get and set methods. 6. The JavaBean introspection process exposes the properties, methods and events of a bean and also any global information about a bean. This is done through the BeanInfo interface, provided by the Java Beans API. Programming: The following is a sample application that is used to display colors using a bean: // Program to test beans import java.awt.*; import java.awt.event.*; import java.io.Serializable; import java.applet.*; public class MyBean extends Applet implements Serializable {

Page 29 of 89

transient private Color color; private boolean rect,flag; public MyBean() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { change(); } }); rect=false; setSize(300,300); change(); } public boolean getRect() { return rect; } public void setRect(boolean flag) { this.rect=flag; repaint(); } public void change() { color=randomColor(); repaint(); } private Color randomColor() {

Page 30 of 89

int r=(int)(255*Math.random()); int g=(int)(255*Math.random()); int b=(int)(255*Math.random()); return new Color(r,g,b); } public void paint(Graphics g) { Dimension d=getSize(); int h=d.height; int w=d.width; g.setColor(color); if(rect) { g.fillRect(10,10,40,40); g.fillOval(100,10,20,20); g.drawLine(0,0,10,50); } else { g.drawRect(10,10,40,40); g.drawOval(100,10,20,20); g.drawRoundRect(0,0,100,100,150,150); } } } Procedure: Steps to be followed for execution: 1. Create a root directory and place the java source file in it. 2. Compile the java source file 3. Create a file with .html/.htm extension and write the following contents in it <applet code="MyBean" width=500 height =500>

Page 31 of 89

</applet> 4. Open the html file and observe that with mouse clicks the color of the graphical shapes will change. Observations & Result: The expected output from the application to be done is that it should display various graphical shapes in the browser or in the tool used.

PreLab Questions: 1. How do we generate an application when using the bean box tool? 2. What is the difference between an ActiveX control and a JavaBean component? 3. How to access EJBs from JavaBeans Components? 4. Is a Java Bean a server side component or client side component? 5. What is the difference between a JavaBean and a traditional AWT object? 6. What is a serialized bean? 7. What is the difference between Java Beans and just normal classes? 8. Why do we need a no argument constructor in a JavaBean component? 9. What is a property editor? 10. How do we create an event to be used in a JavaBeans component? 11. What is a JavaBeans property? 12. Are Enterprise JavaBeans and JavaBeans the same thing?

Page 32 of 89

6. Developing an EJB for Displaying a Message Using Stateless Session Bean AIM: Developing an stateless session EJB for displaying a message on client side Software Requirements: J2SDK 1.4 or above, Web-logic application server 8.1 or above, java compiler, notepad. Theory: Stateless session EJBs have the following behavior:
1. 2. 3. 4. 5. 6.

provide a single use service do not maintain state on behalf of the client are relatively short lived do not survive EJB server crashes any two instances of the same stateless session EJB type are always identical each instance can be shared by multiple clients Stateless Session EJBs View:

Algorithm/Steps to develop EJB:

Page 33 of 89

EJB Remote Interface: EJB remote interfaces extends javax.ejb.EJBObject EJB remote interfaces
1. 2.

provide business-specific functionality of an EJB are similar to RMI Remote interface

//Program for EJB Remote Interface public interface Hello extends javax.ejb.EJBObject { public String sayHello()throws java.rmi.RemoteException; } EJB Home Interface: EJB home interfaces extends javax.ejb.EJBHome EJB home interfaces provide operations for clients to
1. 2. 3. 4.

create EJBs remove EJBs find handles to EJB remote interface objects have its stub placed into JNDI at startup

//Program to write EJB Home Interface public interface HelloHome extends javax.ejb.EJBHome { public Hello create()throws javax.ejb.CreateException; } EJB Implementation: Class in which EJB developer codes the business methods defined in the beans component interface(s) to provide any application specific
1. 2. 3. 4.

business method invocation creation removal Database loading logic.

Page 34 of 89

5.

The Container has already reference to the bean. The bean interacts with the Container through SessionContext and

retrieves home interfaces gets and sets transactions attributes obtains security attribute

The setSessionContext() method is used to inform the bean about the session context //Program to write EJB Bean implementation class import java.rmi.RemoteException; import javax.ejb.*; public class HelloBean implements SessionBean { SessionContext context; public void setSessionContext() throws EJBException { } public void ejbRemove() throws EJBException, RemoteException { } public void ejbActivate() throws EJBException, RemoteException { } public void ejbPassivate() throws EJBException, RemoteException { } public void ejbCreate() throws CreateException { } public String sayHello() throws EJBException { return "Arvind"; } } Client Program: import java.util.Hashtable; import javax.naming.*; public class HelloClient { public static void main(String[] args) {

Page 35 of 89

try { Hashtable ht=new Hashtable (); ht.put(Context.PROVIDER_URL,"t3://localhost:7001"); InitialContext ct=new InitialContext(ht); HelloHome hoh.ct.lookup("HelloBean2"); Hello h=hoh.create(); System.out.println(h.sayHello()); }catch(Exception e) { e.printStackTrace(); } } } Weblogic descriptor files: ejb-jar <ejb-jar> <enterprise-beans> <session> <ejb-name>HelloBean</ejb-name> <home>HelloHome</home> <remote>Hello</remote> <ejb-class>HelloBean</ejb-class> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> </session> </enterprise-beans> </ejb-jar> weblogic-ejb-jar <weblogic-ejb-jar> <weblogic-enterprise-bean> <ejb-name>Hello</ejb-name> <jndi-name>Hello</jndi-name>

Page 36 of 89

</weblogic-enterprise-bean> </weblogic-ejb-jar> Procedure: 1. Compile the java source files and place all the .class files in it. 2. Now configure the weblogic server and start the server. 3. Open the weblogic builder IDE to create the deployment descriptors 4. Create the jar file with root directory contents 5. Deploy the jar file into weblogic configured domain 6. Run the client, get the results. Results: H:\MWT Lab 2010-11\EXP6\client>java HelloClient Arvind H:\MWT Lab 2010-11\EXP6\client>

PreLab Questions: 1. The EJB specification says that we cannot use Bean Managed Transaction in Entity Beans. Why 2. Can we invoke Runtime.gc() in an EJB? 3. What is the advantage of using Entity bean for database operations, over directly using JDBC API to do database operations? When would I use one over the other?

Page 37 of 89

4. What is the role of serialization in EJB? 5. What is EJB QL? 6. What is the relationship between local interfaces and container-managed relationships? 7. What does a remove method do for different cases of beans? 8. How does a container-managed relationship work? 9. What are the basic classes required in the client for invoking an EJB? 10. What is Vertical Scaling? 11. What is Horizontal Scaling? 12. What is a Clone?

Page 38 of 89

7. Developing an EJB for a Calculator Using Stateless Session Bean AIM: Developing a stateless session EJB for a calculator that adds two numbers and subtracts them. Software Requirements: J2SDK 1.4 or above, Web-logic application server 8.1 or above, java compiler, notepad. Theory: Stateless session EJBs have the following behavior:
1. 2. 3. 4. 5. 6.

provide a single use service do not maintain state on behalf of the client are relatively short lived do not survive EJB server crashes any two instances of the same stateless session EJB type are always identical each instance can be shared by multiple clients Stateless Session EJBs View:

Algorithm/Steps to develop EJB:

Page 39 of 89

EJB Remote Interface: EJB remote interfaces extends javax.ejb.EJBObject EJB remote interfaces
1. 2.

provide business-specific functionality of an EJB are similar to RMI Remote interface

//Program for EJB Remote Interface public interface AddEjb extends javax.ejb.EJBObject { public float addNum(float num1,float num2) throws java.rmi.RemoteException; public float subNum(float num1,float num2) throws java.rmi.RemoteException; } EJB Home Interface: EJB home interfaces extends javax.ejb.EJBHome EJB home interfaces provide operations for clients to
1. 2. 3. 4.

create EJBs remove EJBs find handles to EJB remote interface objects have its stub placed into JNDI at startup

//Program to write EJB Home Interface public interface AddEjbHome extends javax.ejb.EJBHome { public AddEjb create() throws javax.ejb.CreateException, java.rmi.RemoteException; }

Page 40 of 89

EJB Implementation: Class in which EJB developer codes the business methods defined in the beans component interface(s) to provide any application specific
1. 2. 3. 4. 5.

business method invocation creation removal finding The Container has already reference to the bean. The bean interacts with the Container through SessionContext and

retrieves home interfaces gets and sets transactions attributes obtains security attribute

The setSessionContext() method is used to inform the bean about the session context //Program to write EJB Bean implementation class //Bean Development import java.rmi.RemoteException; import javax.ejb.*; public class AddEjbBean implements SessionBean { public void setSessionContext() throws EJBException { System.out.println("Inside the Context Method"); } public void ejbRemove() throws EJBException, RemoteException { System.out.println("Inside the ejbremove()"); } public void ejbActivate() throws EJBException, RemoteException { System.out.println("Inside the ejbActivate()"); } public void ejbPassivate() throws EJBException, RemoteException { System.out.println("Inside the ejbPassivate()");

Page 41 of 89

} public void ejbCreate() throws CreateException { System.out.println("Inside the ejbCreate()"); } public float addNum(float num1,float num2) { return (num1+num2); } public float subNum(float num1,float num2) { return (num1-num2); } }//end of class Client Program: import java.util.*; import javax.naming.*; public class AddEjbClient { public static void main(String[] args) { try { Hashtable ht=new Hashtable(); ht.put(Context.PROVIDER_URL,"t3://localhost:7001"); Context ct=new InitialContext(); AddEjbHome adhome=(AddEjbHome)ct.lookup("AddEjb"); AddEjb adrem=adhome.create(); float num1=Float.parseFloat(args[0]); float num2=Float.parseFloat(args[1]); float addition=adrem.addNum(num1,num2); float substract=adrem.subNum(num1,num2); System.out.println(addition); System.out.println(substract);

Page 42 of 89

}catch(Exception e) { e.printStackTrace(); } } } Weblogic descriptor files: ejb-jar <ejb-jar> <enterprise-beans> <session> <ejb-name>AddEjb</ejb-name> <home>AddEjbHome</home> <remote>AddEjb</remote> <ejb-class>AddEjbBean</ejb-class> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> </session> </enterprise-beans> </ejb-jar> weblogic-ejb-jar <weblogic-ejb-jar> <weblogic-enterprise-bean> <ejb-name>AddEjb2</ejb-name> <stateless-session-descriptor> </stateless-session-descriptor> <jndi-name>AddEjbJndi</jndi-name> </weblogic-enterprise-bean> </weblogic-ejb-jar> Procedure: 1. Compile the java source files and place all the .class files in it. 2. Now configure the weblogic server and start the server. 3. Open the weblogic builder IDE to create the deployment descriptors 4. Create the jar file with root directory contents 5. Deploy the jar file into weblogic configured domain. Run the client Results: H:\MWT Lab 2010-11\EXP7\client>java AddEjbClinet 100 20

Page 43 of 89

The Addition is 120 The Sustraction is 80 H:\MWT Lab 2010-11\EXP7\client>

PreLab Questions: 1. Does RMI-IIOP support code downloading for Java objects sent by value across an IIOP connection in the same way as RMI does across a JRMP connection? 2. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes? 3. What is the advantage of putting an Entity Bean instance from the Ready State to Pooled state? 4. Can a Session Bean be defined without ejbCreate() method? 5. Are enterprise beans allowed to use Thread.sleep()? 6. Is it possible to write two EJBs that share the same Remote and Home interfaces, and have different bean classes? if so, what are the advantages/disadvantages? 7. Is it possible to specify multiple JNDI names when deploying an EJB? an Entity Bean to store itself to the db? 8. Is there a guarantee of uniqueness for entity beans? 9. Will an attribute like Required lock out other readers until Im finished updating?

Page 44 of 89

10. Can the primary key in the entity bean be a Java primitive type such as int? implementations does RMI have? 11. What is the need of Remote and Home interfaces. Why cant there be one? 12. What is the difference between Java Beans and EJB? 13. With regard to Entity Beans, what happens if both my EJB Server and Database crash, what will happen to unsaved changes? Is there any transactional log file used? 14. Does RMI-IIOP support dynamic downloading of classes? 15. Does EJB 1.1 support mandate the support for RMI-IIOP ? What is the meaning of the client API must support the Java RMI-IIOP programming model for portability, but the underlying protocol can be anything ?

Page 45 of 89

8. Developing an EJB for Student Information system Using Stateless Session Bean AIM: Developing a stateless session EJB for student information system stored as data in application. Software Requirements: J2SDK 1.4 or above, Web-logic application server 8.1 or above, java compiler, notepad. Theory: Stateless session EJBs have the following behavior:
1. 2. 3. 4. 5. 6.

provide a single use service do not maintain state on behalf of the client are relatively short lived do not survive EJB server crashes any two instances of the same stateless session EJB type are always identical each instance can be shared by multiple clients Stateless Session EJBs View:

Algorithm/Steps to develop EJB:

Page 46 of 89

EJB Remote Interface: EJB remote interfaces extends javax.ejb.EJBObject EJB remote interfaces
1. 2.

provide business-specific functionality of an EJB are similar to RMI Remote interface

//Program for EJB Remote Interface //remote Interface import java.util.*; public interface Student extends javax.ejb.EJBObject { public ArrayList details() throws java.rmi.RemoteException; } EJB Home Interface: EJB home interfaces extends javax.ejb.EJBHome EJB home interfaces provide operations for clients to
1. 2. 3. 4.

create EJBs remove EJBs find handles to EJB remote interface objects have its stub placed into JNDI at startup

//Program to write EJB Home Interface public interface StudentHome extends javax.ejb.EJBHome { public Student create() throws javax.ejb.CreateException, java.rmi.RemoteException; }

Page 47 of 89

EJB Implementation: Class in which EJB developer codes the business methods defined in the beans component interface(s) to provide any application specific
1. 2. 3. 4. 5.

business method invocation creation removal Database loading logic. The Container has already reference to the bean. The bean interacts with the Container through SessionContext and

retrieves home interfaces gets and sets transactions attributes obtains security attribute

The setSessionContext() method is used to inform the bean about the session context //Program to write EJB Bean implementation class //Bean Development import java.rmi.RemoteException; import java.sql.*; import javax.ejb.*; import java.util.*; public class StudentBean implements SessionBean { ArrayList v=new ArrayList(); public void setSessionContext() throws EJBException { context = newContext; System.out.println("Inside the Context Method"); } public void ejbRemove() throws EJBException, RemoteException { System.out.println("Inside the ejbremove()"); } public void ejbCreate() throws CreateException { System.out.println("Inside the ejbCreate()");

Page 48 of 89

} public ArrayList details() throws EJBException { try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@xe","scott","tiger"); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select *from Student"); System.out.println("After query excuted"); while(rs.next()) { v.add(rs.getString(1)); v.add(rs.getString(2)); v.add(rs.getString(3)); }//end of while con.close(); }catch(Exception e) { e.printStackTrace(); }//end of try-catch return v; }//end of details() method }//end of class Client Program: import java.util.*; import javax.naming.*; public class StudentClient { public static void main(String[] args) { try { Hashtable ht=new Hashtable(); ht.put(Context.PROVIDER_URL,"t3://localhost:7001");

Page 49 of 89

Context ct=new InitialContext(); StudentHome lb=ct.lookup("StudentJndi"); Student l=lb.create(); ArrayList ar=(ArrayList)l.details(); Iterator itr=ar.iterator(); while(itr.hasNext()) { System.out.println(el); } }catch(Exception e) { e.printStackTrace(); } } } Weblogic descriptor files: ejb-jar <ejb-jar> <enterprise-beans> <session> <ejb-name>StudentBean</ejb-name> <home>StudentHome</home> <remote>Student</remote> <ejb-class>StudentBean</ejb-class> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> </session> </enterprise-beans> </ejb-jar> weblogic-ejb-jar <weblogic-ejb-jar> <weblogic-enterprise-bean> <ejb-name>StudentBean2</ejb-name> <stateless-session-descriptor> </stateless-session-descriptor> <jndi-name>Student</jndi-name> </weblogic-enterprise-bean> </weblogic-ejb-jar>

Page 50 of 89

Procedure: 1. Create a root directory with name EXP8 and place all the source files in it. 2. Compile the java source files and place all the .class files in it. 3. Now configure the weblogic server and start the server. 4. Open the weblogic builder IDE to create the deployment descriptors 5. Create the jar file with root directory contents 6. Deploy the jar file into weblogic configured domain 7. Run the client, get the results. Observations: For the Student and Library information systems, the services to be provided are to be declared in the remote interface. The services are to be implemented in the bean classes. For the implementation part, the data retrieval is to be done by getting connected to the database using JDBC. For the Student Information System, the input would be the student ID and the output would be the relevant information of the student. Results: In case of the Library System, the book-ID would be given as input and the relevant information of the book is to be retrieved as output. Name: Arvind Id: 12345 Dept: ECE

Page 51 of 89

PreLab Questions: 1. Is possible for an EJB client to marshal an object of class java.lang.Class to an EJB? 2. Is it legal to have static initializer blocks in EJB? 3. Is it possible to stop the execution of a method before completion in a SessionBean? 4. What is the default transaction attribute for an EJB? - There is no default transaction 5. What is the difference between session and entity beans? When should I use one or the other? 6. Why is ejbFindByPrimaryKey mandatory? 7. Why do we have a remove method in both EJBHome and EJBObject? 8. How can I call one EJB from inside of another EJB? 9. What is the difference between a Server, a Container, and a Connector? 10. How is persistence implemented in enterprise beans? 11. What is an EJB Context? 12. Is method overloading allowed in EJB? 13. Should synchronization primitives be used on bean methods? 14. Are we allowed to change the transaction isolation property in middle of a transaction? 15. For Entity Beans, What happens to an instance field not mapped to any persistent storage, when the bean is passivated?

Page 52 of 89

9. Developing an EJB for Library Information system Using State full Session Bean AIM: Developing a state full session EJB for library information system stored as data in oracle table. Software Requirements: J2SDK 1.4 or above, Web-logic application server 8.1 or above, java compiler, notepad. Theory: Statefull session EJBs have the following behavior:
1. 2. 3. 4. 5. 6.

provide a single use service Maintain the state on behalf of the client are relatively short lived do not survive EJB server crashes any two instances of the same statefull session EJB type are always identical each instance can be shared by multiple clients Statefull Session EJBs View:

Algorithm/Steps to develop EJB:

Page 53 of 89

EJB Remote Interface: EJB remote interfaces extends javax.ejb.EJBObject EJB remote interfaces
1. 2.

provide business-specific functionality of an EJB are similar to RMI Remote interface

//Program for EJB Remote Interface //remote Interface public interface Library extends javax.ejb.EJBObject { public void libraryInfo()throws java.rmi.RemoteException; } EJB Home Interface: EJB home interfaces extends javax.ejb.EJBHome EJB home interfaces provide operations for clients to
1. 2. 3. 4.

create EJBs remove EJBs find handles to EJB remote interface objects have its stub placed into JNDI at startup

//Program to write EJB Home Interface public interface LibraryHome extends javax.ejb.EJBHome { public void create()throws javax.ejb.CreateException; } EJB Implementation: Class in which EJB developer codes the business methods defined in the beans component interface(s) to provide any application specific
1. 2. 3. 4.

business method invocation creation removal finding

Page 54 of 89

5. 6. 7. 8.

activation passivation, database storage Database loading logic. The Container has already reference to the bean. The bean interacts with the Container through SessionContext and

retrieves home interfaces gets and sets transactions attributes obtains security attribute

The setSessionContext() method is used to inform the bean about the session context //Program to write EJB Bean implementation class //Bean Development import java.rmi.RemoteException; import java.sql.*; import javax.ejb.*; import java.util.*; public class LibraryBean implements SessionBean { String bookid; Connection con;Vector v=new Vector(); public void setSessionContext() throws EJBException { context = newContext; } public void ejbRemove() throws EJBException, RemoteException { } public void ejbActivate() throws EJBException, RemoteException { } public void ejbPassivate() throws EJBException, RemoteException { } public void ejbCreate(String param) throws CreateException { }

Page 55 of 89

public void libraryInfo() throws EJBException { try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger" ); PreparedStatement stmt=con.prepareStatement("select *from library where bid=?"); stmt.setString(1,bookid); ResultSet rs=stmt.executeQuery(); System.out.println("After query excuted"); while(rs.next()) { v.add(rs.getString(1)); v.add(rs.getString(2)); v.add(rs.getString(3)); } con.close(); }catch(Exception e) { e.printStackTrace(); } } }//end of class Client Program: import java.util.*; import javax.naming.*; public class LibraryClient { public static void main(String[] args) { try { Hashtable ht=new Hashtable();

Page 56 of 89

ht.put(Context.PROVIDER_URL,"t3://localhost:7001"); Context ct=new InitialContext(); LibraryHome libraryHome=(LibraryHome)ct.lookup("Library"); String number=args[0]; Library library=libraryHome.create(args[0]); System.out.println(library.libraryInfo()); Iterator itr=library.libraryInfo().iterator(); while(itr.hasNext()) { String el=(String)itr.next(); } }catch(Exception e) { e.printStackTrace(); } } } Weblogic descriptor files: ejb-jar <ejb-jar> <enterprise-beans> <session> <ejb-name>EXP9</ejb-name> <home>LibraryHome</home> <remote>Library</remote> <ejb-class>LibraryBean</ejb-class> <session-type>Stateful</session-type> <transaction-type>Container</transaction-type> </session> </enterprise-beans> <assembly-descriptor> <container-transaction> <trans-attribute>Required</trans-attribute> </container-transaction> </assembly-descriptor> </ejb-jar>

Page 57 of 89

weblogic-ejb-jar <weblogic-ejb-jar> <weblogic-enterprise-bean> <ejb-name>EXP9</ejb-name> <jndi-name>ejb/Library</jndi-name> </weblogic-enterprise-bean> </weblogic-ejb-jar> Procedure: 1. Create a root directory with name EXP6 and place all the source files in it. 2. Compile the java source files and place all the .class files in it. 3. Now configure the weblogic server and start the server. 4. Open the weblogic builder IDE to create the deployment descriptors 5. Create the jar file with root directory contents 6. Deploy the jar file into weblogic configured domain 7. Run the client, get the results. Observations: For the Student and Library information systems, the services to be provided are to be declared in the remote interface. The services are to be implemented in the bean classes. For the implementation part, the data retrieval is to be done by getting connected to the database using JDBC. For the Student Information System, the input would be the student ID and the output would be the relevant information of the student. Results: In case of the Library System, the book-ID would be given as input and the relevant information of the book is to be retrieved as output.

Page 58 of 89

PreLab Questions: 1. What is the difference between URL instance and URLConnection instance? 2. Whats the difference between JNDI lookup(), list(), listBindings(), and search() 3. Components of JNDI 4. What is the Max amount of information that can be saved in a Session Object? 5. What is the function of T3 in WebLogic Server? 6. Can you briefly describe local interfaces? 7. What are the special design care that must be taken when you work with local interfaces? 8. What happens if remove( ) is never invoked on a session bean? 9. What is the difference between creating a distributed application using RMI and using a EJB architecture? 10. Can the bean class implement the EJBObject class directly? If not why? 11. What does isIdentical() method return in case of different type of beans 12. What is the difference between session and entity bean? 13. What is a JavaBean? 14. What is EJB 15. What is EJB role in J2EE?

Page 59 of 89

16. What is the difference between EJB and Java beans? 17. What are the key features of the EJB technology? 18. What are the key benefits of the EJB technology? 19. What is Entity Bean and Session Bean

Page 60 of 89

10. Creation of an Active-x Control for Time Table AIM: Creation of an Active-x Control for Time Table Apparatus: Microsoft Visual Studio 2005 Programming: TIME TABLE PROGRAM using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; namespace TimeTable { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { switch (comboBox1.SelectedIndex) { case 0: comboBox2.Items.Clear(); comboBox2.Items.Add("1styear"); comboBox2.Items.Add("2ndyear"); comboBox2.Items.Add("3rdyear");

Page 61 of 89

break; case 1: comboBox2.Items.Clear(); comboBox2.Items.Add("1styear"); comboBox2.Items.Add("2ndyear"); break; case 2: comboBox2.Items.Clear(); comboBox2.Items.Add("1styear"); comboBox2.Items.Add("2ndyear"); comboBox2.Items.Add("3rdyear"); comboBox2.Items.Add("4thyear"); break; } } private void Form1_Load(object sender, EventArgs e) { } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { OleDbConnection cn = new OleDbConnection("user id=scott;password=tiger;provider=msdaora.1"); string t = "select * from " + comboBox1.SelectedItem + comboBox2.SelectedItem; //MessageBox.Show(t); OleDbDataAdapter da = new OleDbDataAdapter(t, cn); DataSet ds = new DataSet(); da.Fill(ds, "timetable"); dataGridView1.DataSource = ds.Tables["timetable"]; } private void label1_Click(object sender, EventArgs e)

Page 62 of 89

{ } } } Result & Observation:

Page 63 of 89

11. Developing A Component for Converting Currency Values Using COM/.NET AIM: Developing a component for converting currency values using com .net Apparatus: Microsoft Visual Studio 2005 Programming: CURRENCY TRANSLATOR PROGRAM using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace currencytranslator { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { textBox2.Text = ((Double.Parse(textBox1.Text))/43.50).ToString(); } private void button2_Click(object sender, EventArgs e) { textBox4 .Text = ((Double.Parse(textBox3.Text)) * 43.50).ToString(); } private void Form1_Load(object sender, EventArgs e)

Page 64 of 89

{ } } } Result& Observations:

Page 65 of 89

12. Developing a Component for Browsing the CD Catalog Using COM/.NET AIM: Developing a component for browsing the CD catalog using com .net Apparatus: Microsoft Visual Studio 2005 Programming: CD CATALOGUE PROGRAM using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace CDCatalogue { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { string s = comboBox1.SelectedItem.ToString(); listBox1.Items.Clear(); label2.Text = s; try

Page 66 of 89

{ string[] x = Directory.GetDirectories(s); for (int i = 0; i < x.Length; i++) { DirectoryInfo di = new DirectoryInfo(x[i]); listBox1.Items.Add(di.Name ); } } catch (IOException io) { MessageBox.Show(io.Message); } } private void Form1_Load(object sender, EventArgs e) { string x = "D:\\"; string[] f = Directory.GetDirectories(x); for (int i = 0; i < f.Length; i++) { comboBox1.Items.Add(f[i]); } } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { listBox2.Items.Clear(); string t = comboBox1.SelectedItem + "\\" + listBox1.SelectedItem; label3.Text = t; string[] x = Directory.GetFiles(t); for (int i = 0; i < x.Length; i++) { FileInfo f = new FileInfo(x[i]);

Page 67 of 89

listBox2.Items.Add(f.Name); } } private void listBox2_SelectedIndexChanged(object sender, EventArgs e) { } } } Result & Observations:

Page 68 of 89

13. Developing a Component for Retrieving Information from Message Box Using DCOM/.NET AIM: developing a component for retrieving information from message box using .net Apparatus: Microsoft Visual Studio 2005 Programming: ///Message Box Program using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace msgbox { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(textBox1.Text); MessageBox.Show("Successfully submitted."); } } }

Page 69 of 89

Result& Observations:

Page 70 of 89

14. Developing a Middleware Component for Retrieving Message from Server Using CORBA Aim: To developing a Middleware component for retrieving message from server using CORBA Software required: j2sdk 1.4 or above, Notepad Theory: CORBA (Common Object Request Broker Architecture) 1. CORBA is a specification that defines how distributed objects can interoperate. 2. CORBA specification is controlled by OMG. 3. CORBA objects can be written in almost any language and can exist on almost any platform. 4. Language Independence is possible using the construction of interfaces to objects using the Interface Definition Language (ICL). The only requirement is a bridge between the natural language and IDL. 5. ORB (Object Request Broker) is at the core of CORBA. This is the principal component for the transmission of information between the client and the server of the CORBA application. 6. The Java IDL enables distributed Java applications to transparently invoke operations or remote network services, using the industry standard IDL and IIOP. Architecture: This figure shows how a one-method distributed object is shared between a CORBA client and server to implement the classic "Hello World" application.

A one-method distributed object shared between a CORBA client and server. Procedure: We will build the "Hello World" program as a distributed application. The "Hello World" program has a single operation that returns a string to be printed. The following steps provide a general guide to designing and developing a distributed object application with Java IDL: 1. Define the remote interface 2. Compile the remote interface Page 71 of 89

3. Implement the server 4. Implement the client 5. Start the applications Programming: //Define the remote interface: module HelloApp { interface Hello { string sayHello(); } } //Implementation of Server Application The server consists of two classes, the servant and the server. The HelloServer class has the server's main() method, which: 1. Creates and initializes an ORB instance 2. Gets a reference to the root POA and activates the POAManager 3. Creates a servant instance (the implementation of one CORBA Hello object) and tells the ORB about it 4. Creates a tie with the servant being the delegate 5. Gets a CORBA object reference for a naming context in which to register the tie. This step also implicitly activates the object. See the POA topic for more information on POA policies and activations. 6. Gets the root naming context 7. Registers the new object in the naming context under the name "Hello" 8. Waits for invocations of the new object from the client // HelloServer.java import HelloApp.*; import org.omg.CosNaming.*; import org.omg.CosNaming.NamingContextPackage.*;

Page 72 of 89

import org.omg.CORBA.*; import java.util.*; class HelloImpl extends HelloPOA { public String sayHello() { return "\nHello Arvind !!\n"; } } public class HelloServer { public static void main(String args[]) { try{ // create and initialize the ORB ORB orb = ORB.init(args,pr); // get reference to rootpoa & activate the POAManager POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA")); // create servant and register it with the ORB HelloImpl helloImpl = new HelloImpl(); helloImpl.setORB(); // get remote object reference from the servant org.omg.CORBA.Object ref = rootpoa.servant_to_reference(helloImpl); Hello href = HelloHelper.narrow(ref); // get the root naming context. NameService invokes the name service org.omg.CORBA.Object objRef = orb.resolve_initial_references("Service"); // Use NamingContextExt which is part of the Interoperable Naming Service pecification. NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); // bind the Object Reference in Naming NameComponent path[] = ncRef.to_name("Hello"); ncRef.rebind(path, href); System.out.println("HelloServer ready and waiting ..."); // wait for invocations from clients } catch (Exception e) {

Page 73 of 89

e.printStackTrace(System.out); } System.out.println("HelloServer Exiting ..."); } } Client Application in Java 1. 2. 3. 4. result // HelloClient.java import HelloApp.*; import org.omg.CosNaming.*; import org.omg.CosNaming.NamingContextPackage.*; public class HelloClient { public static void main(String args[]) { try{ // create and initialize the ORB ORB orb = ORB.init(args,pr); // get the root naming context org.omg.CORBA.Object objRef = orb.resolve_initial_references("Service"); // Use NamingContextExt.This is part of the //Interoperable naming Service. NamingContextExt ncRef = Creates and initializes an ORB Obtains a reference to the root naming context Looks up "Hello" in the naming context and receives a reference to that CORBA object Invokes the object's sayHello() and shutdown() operations and prints the

Page 74 of 89

NamingContextExtHelper.narrow(objRef); // resolve the Object Reference in Naming hello = HelloHelper.narrow(ncRef.resolve_str("Hello")); System.out.println(hello.sayHello()); //hello.shutdown(); } catch (Exception e) { e.printStackTrace(); } } } Execution Steps: The following steps are to be carried out to execute the above application: 1. Firstly, the IDL file is to be converted into a Java format. For doing so the following command is used - idlj -fall -oldImpBase hello.idl. 2. After this a set of Java classes are created in a separate folder by name Hello. 3. All the java files, including those in the Hello folder, are to be compiled using the following command - javac *.java hello\*.java. 4. The ORB directory service is now started using the following command - start orbd -ORBIntitialPort 5. The server is then started using the command - java HelloServer -ORBIntitialPort 6. The client is then started using the command - java HelloCli -ORBIntitialPort Observations& results: 1. For the applications of Stock Market Exchange information and Bank balance retrieval, the services are to be declared in the IDL nad to be implemented in the implementation class. 2. A connection to the database is to be made, using JDBC, in the implementation class, to retrieve the data. 3. Clients may be written in any of the natural languages and are to converted into the IDL form using the compatible tools.

Page 75 of 89

CORBA PreLab Question 1. Why do we get this message when trying to run HelloServer: Exception in thread "main" java.lang.NoClassDefFoundError: HelloServer/java 2. If existing programs aren't running using J2SE 1.4.2. Are there any compatibility issues that could affect this? 3. Why can't we connect using IOR's from a Linux server when the IOR contains 127.0.0.0 as the host address? 4. What does this minor code mean? 5. How to add multiple classpaths when starting a server using servertool? 6. What is the thread model supported by the JDK 1.4.2 CORBA implementation? 7. Does Java IDL contain notification/event services? an Interface Repository? 8. How to run the Hello World example on two machines? 9. Is Java IDL compliant with OMG CORBA specifications?

Page 76 of 89

15. Developing a Middleware Component for Retrieving Stock Market Exchange Information Using CORBA AIM: developing a middleware component for retrieving stock market exchange information using CORBA Software required: j2sdk 1.4 or above, Notepad Flow: CORBA (Common Object Request Broker Architecture) 1. CORBA is a specification that defines how distributed objects can interoperate. 2. CORBA specification is controlled by OMG. 3. CORBA objects can be written in almost any language and can exist on almost any platform. 4. Language Independence is possible using the construction of interfaces to objects using the Interface Definition Language (ICL). The only requirement is a bridge between the natural language and IDL. 5. ORB (Object Request Broker) is at the core of CORBA. This is the principal component for the transmission of information between the client and the server of the CORBA application. 6. The Java IDL enables distributed Java applications to transparently invoke operations or remote network services, using the industry standard IDL and IIOP. Programming: The following is a sample application using CORBA: module stock { // this is a interface and all the method which are called from client and executed at the server are define in it. interface stock { // the return type and parameter (in , out , inout ) are idl data type string displayDate(); float displayResult(in float f1, in float f2); };

Page 77 of 89

// an interface can have more than one method }; // A module can have more than one interface // implementation class import stock.*; import org.omg.CORBA.*; import java.util.*; public class stock Impl extends _ stock ImplBase { public String displayDate() { return " " + new Date(); } public float displayResult(float f1, float f2) { return f1 * f2; } } // Program to implement the Client import org.omg.CosNaming.*; import org.omg.CosNaming.NamingContextPackage.*; import org.omg.CORBA.*; import java.io.*; public class stock Client { static stock stock Impl; public static void main(String args[]) { try { // create and initialize the ORB

Page 78 of 89

ORB orb = ORB.init(args, null); // get the root naming context org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); NamingContext ncRef = NamingContextHelper.narrow(objRef); // resolve the Object Reference in Naming NameComponent nc = new NameComponent("Date", ""); NameComponent path[] = {nc}; stock stock Impl = stock Helper.narrow(ncRef.resolve(path)); System.out.println(stockImpl.displayDate()); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.println("Enter the first float value : "); float f_val1 = Float.parseFloat(br.readLine()); System.out.println("Enter the second float value : "); float f_val2 = Float.parseFloat(br.readLine()); System.out.println("The result is : " + stockImpl.displayResult(f_val1,f_val2)); } catch (Exception e) { System.out.println("ERROR : " + e) ; e.printStackTrace(System.out); } } } // Program to implement the Server import org.omg.CosNaming.*; import org.omg.CosNaming.NamingContextPackage.*; import org.omg.CORBA.*;import java.util.Properties; public class stockServer

Page 79 of 89

{ public static void main(String args[]) { try { // create and initialize the ORB ORB orb = ORB.init(args, null); // create servant and register it with the ORB stockImpl stockImpl = new stockImpl(); // get the root naming context org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); NamingContext ncRef = NamingContextHelper.narrow(objRef); stock href = stockHelper.narrow(helloImpl); // bind the Object Reference in Naming NameComponent nc = new NameComponent("Date", ""); NameComponent path[] = {nc}; ncRef.rebind(path, href); System.out.println("HelloServer ready and waiting ..."); // wait for invocations from clients orb.run(); } catch (Exception e) { e.printStackTrace(System.out); } System.out.println("HelloServer Exiting ..."); } } Procedure: The following steps are to be carried out to execute the above application:

Page 80 of 89

1) Firstly, the IDL file is to be converted into a Java format. For doing so the following command is used - idlj -fall -oldImpBase hello.idl. 2) After this a set of Java classes are created in a separate folder by name Hello. 3) All the java files, including those in the Hello folder, are to be compiled using the following command - javac *.java hello\*.java. 4) The ORB directory service is now started using the following command - start orbd -ORBIntitialPort 5) The server is then started using the command - java HelloServer -ORBIntitialPort 6) The client is then started using the command - java HelloCli -ORBIntitialPort Observations& results: 1. For the applications of Stock Market Exchange information and Bank balance retrieval, the services are to be declared in the IDL and to be implemented in the implementation class. 2. A connection to the database is to be made, using JDBC, in the implementation class, to retrieve the data. 3. Clients may be written in any of the natural languages and are to converted into the IDL form using the compatible tools. PreLab Questions:

1. Can we add multiple classpaths when starting a server using servertool?


2. What is the thread model supported by the JDK 1.4.2 CORBA implementation? 3. Does Java IDL contain notification/event services? an Interface Repository? 4. How to run the Hello World example on two machines? 5. Is Java IDL technology compliant with CORBA specifications? 6. What is the difference between Java IDL and Java RMI-IIOP? 7. What are the options for developing CORBA applications using Java technology? 8. Can we use the Java IDL ORB with a C++ CORBA server? (Interoperability) 9. Any examples that use a CORBA client and an EJB server application? 10. How to test whether JDK ORB Client can communicate with another company's ORB implementation?

Page 81 of 89

16. Developing a Middleware component for retrieving Bank Balance using CORBA AIM: To Developing a Middleware component for retrieving Bank Balance using CORBA Software Required: J2sdk 1.4 or above, Notepad Theory: Java IDL is a technology for distributed objects--that is, objects interacting on different platforms across a network. Java IDL enables objects to interact regardless of whether they're written in the Java programming language or another language such as C, C++, COBOL, or others. CORBA (Common Object Request Broker Architecture) 1. CORBA is a specification that defines how distributed objects can interoperate. 2. CORBA specification is controlled by OMG. 3. CORBA objects can be written in almost any language and can exist on almost any platform. 4. Language Independence is possible using the construction of interfaces to objects using the Interface Definition Language (ICL). The only requirement is a bridge between the natural language and IDL. 5. ORB (Object Request Broker) is at the core of CORBA. This is the principal component for the transmission of information between the client and the server of the CORBA application. 6. The Java IDL enables distributed Java applications to transparently invoke operations or remote network services, using the industry standard IDL and IIOP. Architecture: This figure shows how a one-method distributed object is shared between a CORBA client and server to implement the classic "Hello World" application.

A one-method distributed object shared between a CORBA client and server. Procedure for developing the application: Page 82 of 89

The following steps provide a general guide to designing and developing a distributed object application with Java IDL. 1. Define the remote interface 2. Compile the remote interface 3. Implement the server 4. Implement the client 5. Start the applications IDL to Java Language Mapping: IDL Type module String, wstring float sequence, array interface exception operation Programming: To create the Hello.idl file, Create a new directory, named Hello, for this application. Start your favorite text editor and create a file named Hello.idl in this directory. In your file, enter the code for the interface definition, Hello.idl: module BankApp { interface Bank { //string deposit(in long acno,in long amt); //void withdraw(in long acno,in long amt); long showBalance(in long acno); } 2. Implement the server The server class has the server's main() method, which: Java Type package java.lang.String float array signature interface, helper class, holder class class method

1. Define the remote interface

Page 83 of 89

1. Creates and initializes an ORB instance 2. Gets a reference to the root POA and activates the POAManager 3. Creates a servant instance (the implementation of one CORBA Hello object) and tells the ORB about it 4. Gets a CORBA object reference for a naming context in which to register the new CORBA object 5. Gets the root naming context 6. Registers the new object in the naming context under the name "Hello" 7. Waits for invocations of the new object from the client // BankServer.java import BankApp.*; import org.omg.CosNaming.*; import org.omg.CosNaming.NamingContextPackage.*; import org.omg.CORBA.*; import org.omg.PortableServer.*; import java.sql.*; class BankImpl { ResultSet rs;PreparedStatement pstmt; BankImpl()throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger" ); } public String deposit(int acno,int amt) { try{ pstmt=con.prepareStatement("select amt from banktab where acno=?"); pstmt.setInt(1,acno); rs=pstmt.executeQuery(); while(rs.next()) {

Page 84 of 89

int v=rs.getInt("amt"); v+=amt; pstmt=con.prepareStatement("update banktab set amt=? where acno=?"); pstmt.setInt(1,v); pstmt.setInt(2,acno); pstmt.executeUpdate(); } con.close(); } catch (Exception e) { System.out.println("Nothing done"); } return v; } //end of deposit() public int showBalance(int acno) { int v=0; try { pstmt=con.prepareStatement("select amt from banktab where acno=?"); pstmt.setInt(1,acno); rs=pstmt.executeQuery(); while(rs.next()) { v=rs.getInt("amt"); } }

Page 85 of 89

catch (Exception e) { v=0; e.printStackTrace(); } return v; }//end of showBalance() }//end of Servent public class BankServer { public static void main(String args[]) { try{ // create and initialize the ORB Properties pr=new Properties(); pr.put("org.omg.CORBA.ORBInitialPort","1050"); pr.put("org.omg.CORBA.ORBInitialHost","localhost"); ORB orb = ORB.init(args,pr); // get reference to rootpoa & activate the POAManager POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA")); rootpoa.the_POAManager().activate(); // create servant and register it with the ORB BankImpl bankImpl = new BankImpl(); bankImpl.setORB(orb); // get remote object reference from the servant org.omg.CORBA.Object ref = rootpoa.servant_to_reference(bankImpl); Bank href = BankHelper.narrow(ref); // get the root naming context. NameService invokes the name service org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); // Use NamingContextExt which is part of the Interoperable Naming Service specification. NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); // bind the Object Reference in Naming

Page 86 of 89

NameComponent path[] = ncRef.to_name("Bank"); ncRef.rebind(path, href); System.out.println("HelloServer ready and waiting ..."); // wait for invocations from clients orb.run(); } catch (Exception e) { System.err.println("ERROR: " + e); e.printStackTrace(); } System.out.println("HelloServer Exiting ..."); } } 3. Implement the client To create HelloClient.java, Start your text editor and create a file named BankClient.java in your main project directory, Hello. Enter the following code for BankClient.java in the text file. The following section, Understanding BankClient.java, explains each line of code in some detail. // BankClient.java import BankApp.*; import org.omg.CosNaming.*; import org.omg.CosNaming.NamingContextPackage.*; public class BankClient { static Bank bank; public static void main(String args[]) { try{ // create and initialize the ORB ORB orb = ORB.init(args,pr);

Page 87 of 89

// get the root naming context org.omg.CORBA.Object objRef = orb.resolve_initial_references("Service"); // Use NamingContextExt.This is part of the Interoperable naming Service. NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); // resolve the Object Reference in Naming bank = BankHelper.narrow(ncRef.resolve_str("BankIdl")); System.out.println("The amount in account is"); System.out.println(bank.showBalance(1234)); } catch (Exception e) { System.out.println("ERROR : " + e) ; } } } Procedure: The following steps are to be carried out to execute the above application: 1) Firstly, the IDL file is to be converted into a Java format. For doing so the following command is used - idlj -fall -oldImpBase hello.idl. 2) After this a set of Java classes are created in a separate folder by name Hello. 3) All the java files, including those in the Hello folder, are to be compiled using the following command - javac *.java hello\*.java. 4) The ORB directory service is now started using the following command - start orbd -ORBIntitialPort 5) The server is then started using the command - java HelloServer -ORBIntitialPort 6) The client is then started using the command - java HelloCli -ORBIntitialPort 1200. Observations& results: 1. For the applications of Bank Information and Bank balance retrieval, the services are to be declared in the IDL to be implemented in the implementation class.

Page 88 of 89

2. A connection to the database is to be made, using JDBC, in the implementation class, to retrieve the data. 3. Clients may be written in any of the natural languages and are to converted into the IDL form using the compatible tools. PreLab Questions: 1. How to specify a different ORB? 2. How to test whether my JDK ORB Client can communicate with another vendor's ORB implementation? 3. List any examples that use a CORBA client and a Java server application? 4. How to connect to a 3rd-party Naming Service from Sun's ORB? 5. How use the Java IDL ORB with a C++ CORBA server? (interoperability) 6. What are the options for developing CORBA applications using Java technology? 7. What is the difference between Java IDL and Java RMI-IIOP? 8. What are the limitations of Java IDL and Java RMI-IIOP in this release? 9. Why to get this message when trying to run HelloServer: "Exception in thread "main" java.lang.NoClassDefFoundError: HelloServer/java" 10. If existing programs aren't running using J2SE 1.4.2. Are there any compatibility issues that could affect this?

Page 89 of 89