You are on page 1of 58

M.

Tech CSE, Semester-III DC- LAB Report

DISTRIBUTED COMPUTING - LAB REPORT


_________________________________________

-:By:-
Ms Poonam Singh Chandravanshi

M. Tech. (CSE), Semester-III (PTPG)-2019-2020


Roll No: 1005-18-747115

_______________________________
UNIVERSITY COLLEGE OF ENGINEERING (A)

Osmania University, Hyderabad – 500 007

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

1
M. Tech CSE, Semester-III DC- LAB Report

UNIVERSITY COLLEGE OF ENGINEERING (A)


Osmania University, Hyderabad – 500 007

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE
This is to certify that Ms. Poonam Singh Chandravanshi bearing Roll No:

1005-18-747115, Studying M. Tech, Semester-III (PTPG) has successfully

completed “DISTRIBUTED COMPUTING LAB” for the academic year2019-2020.

INTERNAL EXAMINER

2
M. Tech CSE, Semester-III DC- LAB Report

Table of Contents

1. BUILDING APPLICATION USING WEBSERVICES....................................................................................................4

2. REMOTE METHOD INVOCATION (RMI)....................................................................................................................9

3. COMMON GATEWAY INTERFACE.............................................................................................................................13

4. COMMON OBJECT REQUEST BROKER ARCHITECTURE (CORBA)..................................................................15

5. BUILDING ENTERPRISE APPLICATIONS USING JAVA BEAN (EJB)...................................................................26

6. TCP SERVER USING JAVA...........................................................................................................................................40

7. UDP SERVER USING JAVA..........................................................................................................................................43

8. CHAT SERVER USING JAVA........................................................................................................................................45

/********************************************************************************************* /

1. BUILD AN APPLICATION USING WEBSERVICES.


/*****************************************************************************************/

Software Requirements: Java1.4.0, Apache Tomcat Web-Server

Concept: The W3C Web-Services Architecture Working Group defines a web service as software
system identified by a URL, whose public interfaces and bindings are defined and described using XML.
Its definition can be discovered by other software systems. These systems may then interact with the Web
Service in a manner prescribed by its definition, using XML based messages conveyed by Internet
Protocols.

W3C Web-Services Architecture Working Group, Web Services are basically a way for applications to
discover and interact with other application over the internet using XML.
3
M. Tech CSE, Semester-III DC- LAB Report

Basic Standards: Web Service architecture consists of three primary functions: these are the discovery,
description and transport. For each of these functions there is an XML based standard. Web services are
described by Web Services Description Language (WSDL) discovered through Universal Description,
Discovery and Integration (UDDI) and transported using the Simple Object Access Protocol (SOAP).
 WSDL: The Web Services Description Language (WSDL) is an XML base language for
describing WebServices. A WSDL document defines services as collection of end points, or pots,
and describes the message interactions. A WSDL document consists of the following elements to
describe in a service:
1. Types, data type definitions to describe the messages exchanged.
2. Messages, an abstract definition of the exchanged data messages.
3. Operations, specifying the input and /or output massages.
4. Port types, a named set of abstract operations.
 UDDI: Universal Description, Discovery and Integration (UDDI) is an XML based registry where
web service providers can register their web service and web service consumers can reach for
suitable web services. UDDI registries can act as a global directory for web services.
A listing in a UDDI registry consists of three elements. At the highest level there are White
Pages, which contain basic information about the providing company and services. Next
are Yellow Pages, which organise services by industry, service type or geographical
location. Finally there are Green Pages, which include the technical mechanics (for
example a link to the WSDL) about how to find and execute a web service. UDDI was
developed by IBM, Microsoft and ARIBA, and is now under supervision by a technical
committee of the Organization for the Advancement of Structured Information Standards
(OASIS). Version3 is the most current version although version2 is still most widely used.
 SOAP: The Simple Object Access Protocol (SOAP) describes the XML documents and processing
model that are used in the message exchange between Web Services and Web Service users. A
SOAP message consists of an envelope containing a header and a body part. SOAP messages can
be transported over a variety of transport protocols. However, HTTP over TCP/IP is most widely
used.
A SOAP sender sends SOAP messages to an ultimate SOAP receiver via zero or more SOAP
intermediaries. A SOAP node acts in one or more role when processing a SOAP message. SOAP header
blocks can be targeted to be processed by a code with a specific role.
Service profiling in Business to Business Web Services are the SOAP processing model defines a
distributed, stateless processing model for SOAP messages. When a node receives a SOAP message a
SOAP message, it first has to determine what roles apply. Then all mandatory header blocks targeted at
the node are identified and checked if the nodes understand them. Then the SOAP header blocks and, only
in case the node is the ultimate receiver, the SOAP message is sent further down the SOAP message path.

Java Technology and Web services


Web services are web-based enterprise applications that use open, XML-based standards and transport
protocols to exchange data with calling clients. The Java 2 Platform, Enterprise edition platform provides

4
M. Tech CSE, Semester-III DC- LAB Report

the API’s and tools you need to quickly design, develop, test, and deploy Web services and clients that
fully interoperate with other web services and clients running on any platform. This full interoperability is
possible because application data is translated “behind-the-scenes” to a standardized XML-based data
stream.
Web Services Interoperability Technology (WSIT) is an open-source implementation of next generation
Web Services technologies that deliver interoperability between Java EE and .Net to help you build,
deploy, and maintain Composite Applications for your Service Oriented Architecture. Built upon JAX-
WS (Java API for XML Web Services), this implementation will be made available as the “Web Services
Interoperability Technology (WSIT) “and is focused on four main categories: Messaging, Metadata,
Security, and Quality-of Services (Qos). Project Tango is a Sun initiative focused on delivering
interoperable Web Services Technologies.

EXECUTION STEPS FOR A WEBSERVICES


 Write a Service interface (Ex: Calculator.java) with a package statement : package Calc;
 Write a Service Implementation class (Ex: CalculatorImpl.java) with a package stmt: package
Calc CalculatorImpl implements Calculator.
 Save the above files in Tomcat5.0/webapps/axisCompile the above files as
C:\Tomcat 5.0\webapps\axis>javac Calculator.java CalculatorImpl.java –d web-inf/classes
This will generate the class files in web-inf/classes/Calc
 [Move to C:\Tomcat 5.0\webapps\axis> cd C:\Tomcat 5.0\webapps\axis\web-inf\classes]
 Generate WSDL using following command
Java org.apache.axis.wsdl.Java2WSDL –o call.wsdl –ihttp://localhost/axis/services/ Calc “-n urn:
Calc -p urn: Calc Calc.Calculator
This generates wsdl file Calc.wsdl in C:\Tomcat 5.0\webapps\axis\Web-inf\classes

 Generate Wsdd and Java files using following command:


java.org.appache.axis.wsdl.WSDL2Java –o . -d Session –s –p Calc.ws Calc.wsdl. This generates
files in C:\Tomcat 5.0\webapps\axis\web-inf\classes\ Calc\ws

 [Move to C:\Tomcat 5.0\webapps\axis\web-inf\classes\ Calc\ws]

 Start the Tomcat 5.0 Server.

 Deploy the deploy.wsdd file as java org.apache.axis.client.AdminClient deploy.wsdd If deployed


successfully you get the success message.

 [Move to C:\Tomcat 5.0\webapps\axis\web-inf\classes\ Calc\ws>cd


C:\Tomcat5.0\webapps\axis\web-inf\classes]

 Create a jar file using following command jar cvf CalcJar1.jar Calc\*.class

 Move the jar file to C:\Tomcat5.0\webapps\axis\web-inf\lib and set jar file in classpath.
5
M. Tech CSE, Semester-III DC- LAB Report

Programs:
 Auto generated code.

/* CalcSoapBindingImpl.java
This file was auto generated from WSDL by Apache Axis1.4 Jan 2nd 2008 WSDL2JavaEmitter*/
package Calc.ws;
public class CalcSoapBindingImpl implements Calc.ws.Calculator
{
public int add(int in0, int in1) throws java.rmi.RemoteException {
return -3;
}
public int sub(int in0, int in1) throws java.rmi.RemoteException {
return -3;
}
}
Modify the above class as following:
package Calc.ws;
import Calc.CalculatorImpl;
public class CalcSoapBindingImpl implements Calc.ws.Calculator{
CalculatorImpl ci=new CalculatorImpl();{
public int add(int in0, int in1) throws java.rmi.RemoteException {
return ci.add(in0,in1);
}
public int sub(int in0, int in1) throws java.rmi.RemoteException {
return ci.sub(in0,in1)
}
}

 Compile all the classes in C:\Tomcat5.0\webapps\axis\web-


inf\classes\Calc\ws>javac*.java

 Generate the jar file C:\Tomcat5.0\webapps\axis\web-inf\classes>jar cvf CalcJar2.jar


Calc\ws\*.class

 Move the jar file to C:\Tomcat5.0\webapps\axis\web-inf\lib and set jar file in classpath

 Now Create the Client Program.

 Verify that Tomcat Server is started.

 Compile and run the Client

 Written code.

//Service Interface
6
M. Tech CSE, Semester-III DC- LAB Report

Calculator.java
package Calc;
interface Calculator
{
int add(int a, int b);
int sub(int a, int b);
}
//Service Implementation
Calculatorimpl.java
package Calc;
public class CalculatorImpl implements Calculator
{
public int add(int a, int b);
{
int sum=a+b;
return sum;
}
public int sub(int a, int b);
{
int s=a+b;
return s;
}
}

//Client Program
Calclient.java
package client;
import Calc.*;
import Calc.ws.*;
public Class CalcClient
{
public static void main(String args[])
{
try
{
CalculatorService cals=new CalculatorServiceLocator();
Calculator cal=cals.getCalc123();
int a=Interger.parseInt(args[0]);
int b=Interger.parseInt(args[1]);
int ad=cal.add(a,b);
int s=cal.sub(a,b);
}
catch(Exception e)
{
e.printStackTrace();
7
M. Tech CSE, Semester-III DC- LAB Report

}
}
}

/*******************************************************************************************/

2. REMOTE METHOD INVOCATION (RMI)


*******************************************************************************************/

RMI Architecture
The design goal for the RMI architecture was to create a distributed object model that
integrates naturally into the programming language and the local object model. RMI architects
have succeeded; creating a system that extends the safety and robustness of the architecture
to the distributed computing world.

Interfaces: The Heart of RMI


The RMI architecture is based on one important principle: the definition of behavior and the
implementation of that behavior are separate concepts. RMI allows the code that defines the
behavior and the code that implements the behavior to remain separate and to run on

8
M. Tech CSE, Semester-III DC- LAB Report

separate JVMs.

This fits nicely with the needs of a distributed system where clients are concerned about the
definition of a service and servers are focused on providing the service.

Specifically, in RMI, the definition of a remote service is coded using a interface. The
implementation of the remote service is coded in a class. Therefore, the key to understanding
RMI is to remember that interfaces define behavior and classes define implementation.

RMI supports two classes that implement the same interface. The first class is the
implementation of the behavior, and it runs on the server. The second class acts as a proxy for
the remote service and it runs on the client. This is shown in the following diagram.

A client program makes method calls on the proxy object, RMI sends the request to the
remote JVM, and forwards it to the implementation. Any return values provided by the
implementation are sent back to the proxy and then to the client's program.

Programs:

9
M. Tech CSE, Semester-III DC- LAB Report

// Hello Interface

import java.rmi.*;

public interface Hello extends Remote {

String sayHello(String s) throws RemoteException;

// HelloClient

import java.rmi.*;

public class HelloClient {

public static void main(String[] args) {

try {

Remote r = Naming.lookup("rmi://127.0.0.1:1112/value");

Hello i = (Hello) r;

String result = i.sayHello(args[0]);

System.out.println( "From Server: " + result);

catch (Exception e) {

System.out.println(e);

// HelloImpl implementaion class.

import java.rmi.*;

import java.rmi.server.*;

public class HelloImpl extends UnicastRemoteObject implements Hello {

private int i;

10
M. Tech CSE, Semester-III DC- LAB Report

public HelloImpl() throws RemoteException {

//UnicastRemoteObject.exportObject(this);

System.out.println("Object created");

public String sayHello(String s) throws RemoteException {

i++;

return "Hello " + s + " Yours is " + i + " request.";

}}

// HelloServer class

import java.rmi.*;

import java.rmi.registry.*;

public class HelloServer {

public static void main(String[] args) {

try { LocateRegistry.createRegistry(1112);

HelloImpl r = new HelloImpl();

Naming.rebind("rmi://127.0.0.1:1112/value", r);

System.out.println(" Object ready");

catch (Exception e) {

System.out.println(e);

RMI: Remote Method Invocation

RMI generally consists of four files:-

11
M. Tech CSE, Semester-III DC- LAB Report

1. An interface which has the methods defined.

2. An implementation file which implements the interface and provides the body for all the methods.

3. A server class which is ready at some port. It creates a common object to the interface and the impl file.

4. A client class which accesses the server at that port and calls the methods.

************************* STEPS TO RUN THE PROGRAM **********************************

workdir> javac *.java

workdir> rmic on impl file (the file which implements the interface)

workdir> type start rmiregistry if in u r impl program there is no following line.

***LocateRegistry.createRegistry( PORT );***

workdir> run the server (ie) impl file java ....impl

workdir> In another c

/*******************************************************************************************/

3. COMMON GATEWAY INTERFACE


/******************************************************************************************/

CGI defines a standard way by which a Web Server can execute a program taking a user data as
input. Usually, user data once come from an HTML form; it specifies the program that is to be executed
by the server side, along with parameter values that are filled in by the user. Once the form has been
completed, the programs name and collected parameter values are sent to the server, as shown in Fig.

12
M. Tech CSE, Semester-III DC- LAB Report

When the server sees the request, it starts the program names in the request and passes it the parameter
values. At that point, the program simply does its work and generally returns the results in the form of a
document that is sent back to the user’s browser to be displayed.
CGI programs can be as sophisticated as a developer wants. For example as shown in fig, many
programs operate on a database local to the Web server. After processing the data, the program generates
an HTML document and returns that document to the server. The server will then pass the document to
client. An interesting observation is that to the server, it appears as if it is asking the CGI program to fetch
a document. In other words, the server does nothing else but delegates the fetching of a document to an
external program.
The main task of server used to handling client request by simply fetching documents. With CGI
programs, fetching a document could be delegated in such a way that the server remains unaware of
whether the document had been generated on the fly, or actually read from the local file system. However,
servers nowadays do much more than only fetching documents.
One of the most important enhancement is that server can also process a fetched document before
passing it to the client. In particular, a document may contain a server-side script, which is executed by
the server when the document has been fetched locally.
The result of executing a script is sent along with the rest of the document to the client. However,
the script itself is not sent. In other words, using a server side script changes a document by essentially
replacing the script with the result of its execution.
CGI programming

To execute a CGI program server receives a request


Server must recognize that the URL maps to a program, not a document. Server executes program feeds
data from request message to program as output takes program output, adds appropriate HTTP headers,
and sends back CGI (Common Gateway Interface) protocol for input/output of a server-side program
which can be written in any language as long as it accepts input and produces output as specified by CGI
server must be able to recognize a URL as being a CGI program generally done by placing program in
special cgi-bin directory.

Program:
# !/usr/local/bin/perl
#
# hello _s.pl—simple “hello, world” program to demonstrate basic
# CGI output.
#
#Print the CGI response header, required for all HTML output
#Note the extra \n, to send the blank line
Print “Content-type: text/html\n\n”;
#Print the HTML response page to STDOUT
Print <<EOF;
<html>
<head><title>CGI Results</title></head>
<body>
<h1> Hello, world. </h1>
13
M. Tech CSE, Semester-III DC- LAB Report

</body>
</html>
EOF
Exit;

/******************************************************************************************/

4. COMMON OBJECT REQUEST BROKER ARCHITECTURE (CORBA)


/******************************************************************************************/

CORBA Technology and the Java 2 Platform Standard Edition

The Java 2 Platform Standard Edition, v1.4, provides an Object Request Broker (ORB) and two CORBA
programming models that can utilize the Java CORBA ORB and Internet InterORB Protocol (IIOP).

CORBA technology is an integral part of the Java 2 platform. It consists of an Object Request Broker
(ORB), APIs for the RMI programming model, and APIs for the IDL programming model.

How does J2SE leverage CORBA

Common Object Request Broker Architecture (CORBA) technology is the open standard for
heterogeneous computing. CORBA complements the Java platform by providing a distributed object
framework, services to support that framework, and interoperability with other languages. The Java
platform complements CORBA by providing "Write Once, Run Anywhere" portability, a highly
productive implementation environment, and a very robust platform. By combining the Java platform with
CORBA and other key enterprise technologies, the Java 2 Platform is the ultimate platform for distributed
technology solutions.

14
M. Tech CSE, Semester-III DC- LAB Report

CORBA standards provide the proven, interoperable infrastructure to the Java platform. IIOP (Internet
Inter-ORB Protocol) manages the communication between the object components that power the system.
The Java platform provides a portable object infrastructure that works on every major operating system.
CORBA provides the network transparency, Java provides the implementation transparency.

The Object Request Broker

The ORB is a runtime component that can be used for distributed computing using IIOP communication.

The Object Management Group (OMG) is an industry consortium that creates and publishes specifications
for CORBA. Vendors implement the specifications to produce products known as Object Request Brokers
(ORB). The good news for developers is that the Java Platform Standard Edition, v1.2 and higher includes
an ORB that is available in every deployment of the Java 2 Platform Standard Edition.

The Java CORBA ORB supports both the RMI and IDL programming models, both of which can use the
underlying IIOP wire-level protocol for communication.

What is the IDL Programming Model

The IDL programming model, known as Java IDL, consists of both the Java CORBA ORB and the idlj
compiler that maps the OMG IDL to Java bindings that use the Java CORBA ORB, as well as a set of
APIs. Java IDL adds CORBA (Common Object Request Broker Architecture) capability to the Java
platform, providing standards-based interoperability and connectivity. Java IDL enables distributed Web-
enabled Java applications to transparently invoke operations on remote network services using the
industry standard IDL (Object Management Group Interface Definition Language) and IIOP (Internet
Inter-ORB Protocol) defined by the Object Management Group. Runtime components include a Java ORB
for distributed computing using IIOP communication.

To use the IDL programming model, you define remote interfaces using the Object Management Group's
(OMG) Interface Definition Language (IDL), and then compile the interfaces using the idlj compiler.
When you run the idlj compiler over your interface definition file, it generates the Java version of the
interface, as well as the class code files for the stubs and skeletons that enable your applications to hook
into the ORB.

Java IDL is part of the Java 2 Platform Standard Edition, v1.2 and above. To develop applications with
Java IDL, use Java IDL Compiler, idlj, which is included in every installation of J2SE v1.3 and higher.

When should I use the IDL programming model instead of the RMI programming model?

The OMG IDL (Interface Definition Language) is a purely declarative language designed for specifying
programming-language-independent operational interfaces for distributed applications. OMG specifies a
mapping from IDL to several different programming languages, including Java, C, C++, Lisp, Python,
Smalltalk, COBOL, and Ada. When mapped, each statement in OMG IDL is translated to a corresponding
statement in the programming language of choice. Java IDL is an implementation of the CORBA
specification. For example, we can use the Java IDL Compiler, idlj, to map an IDL interface to Java and
implement the client class in Java. If you map the same IDL to C++, using an IDL-to-C++ compiler and a

15
M. Tech CSE, Semester-III DC- LAB Report

C++ ORB, and implement the server in that language, the Java client and C++ server interoperate through
the ORB.

Should I use Java IDL or Java RMI-IIOP technology?

This is a fundamental question and it's important to understand the distinction between these two ways of
integrating the Java programming language with CORBA.

Java IDL technology is for CORBA programmers who want to program in the Java programming
language based on interfaces defined in CORBA Interface Definition Language (IDL).

Java Remote Method Invocation over Internet Inter-ORB Protocol ("RMI-IIOP") technology is for Java
programmers who want to program to the Java Remote Method Invocation ("Java RMI") interfaces, but
use IIOP as the underlying transport. RMI-IIOP provides interoperability with other CORBA objects
implemented in various languages - but only if all the remote interfaces are originally defined as Java
RMI interfaces. It is of particular interest to programmers using Enterprise JavaBeans (EJB) technology,
since the EJB remote object model is based on Java RMI technology.

PROGRAMMING:

Hello.idl:

1. module HelloApp
2. {
3. interface Hello
4. {
5. string sayHello();
6. oneway void shutdown();
7. };
8. };

HelloClient.java:

1. import HelloApp.*;
2. import org.omg.CosNaming.*;

3. import org.omg.CosNaming.NamingContextPackage.*;
16
M. Tech CSE, Semester-III DC- LAB Report

4. import org.omg.CORBA.*;

5. public class HelloClient

6. {

7. static Hello helloImpl;

8. public static void main(String args[])

9. {

10. try{

11. // create and initialize the ORB

12. ORB orb = ORB.init(args, null);

13. // get the root naming context

14. org.omg.CORBA.Object objRef =

15. orb.resolve_initial_references("NameService");

16. // Use NamingContextExt instead of NamingContext. This is

17. // part of the Interoperable naming Service.

18. NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

19. // resolve the Object Reference in Naming

20. String name = "Hello";

21. helloImpl = HelloHelper.narrow(ncRef.resolve_str(name));

22. System.out.println("Obtained a handle on server object: " + helloImpl);

23. System.out.println(helloImpl.sayHello());

24. helloImpl.shutdown();

25. } catch (Exception e) {

26. System.out.println("ERROR : " + e) ;

27. e.printStackTrace(System.out);

17
M. Tech CSE, Semester-III DC- LAB Report

28. }

29. }

30. }

31.

HelloServer.java:

1. import HelloApp.*;
2. import org.omg.CosNaming.*;

3. import org.omg.CosNaming.NamingContextPackage.*;

4. import org.omg.CORBA.*;

5. import org.omg.PortableServer.*;

6. import org.omg.PortableServer.POA;

7. import java.util.Properties;

8. class HelloImpl extends HelloPOA {

9. private ORB orb;

10. public void setORB(ORB orb_val) {

11. orb = orb_val;

12. }

13. // implement sayHello() method

14. public String sayHello() {

15. return "\nHello world !!\n";

16. }

17. // implement shutdown() method

18. public void shutdown() {

19. orb.shutdown(false);

20. }
18
M. Tech CSE, Semester-III DC- LAB Report

21. }

22. public class HelloServer {

23. public static void main(String args[]) {

24. try{

25. // create and initialize the ORB

26. ORB orb = ORB.init(args, null);

27. // get reference to rootpoa & activate the POAManager

28. POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));

29. rootpoa.the_POAManager().activate();

30. // create servant and register it with the ORB

31. HelloImpl helloImpl = new HelloImpl();

32. helloImpl.setORB(orb);

33. // get object reference from the servant

34. org.omg.CORBA.Object ref = rootpoa.servant_to_reference(helloImpl);

35. Hello href = HelloHelper.narrow(ref);

36. // get the root naming context

37. org.omg.CORBA.Object objRef =

38. orb.resolve_initial_references("NameService");

39. // Use NamingContextExt which is part of the Interoperable

40. // Naming Service (INS) specification.

41. NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

42. // bind the Object Reference in Naming

43. String name = "Hello";

44. NameComponent path[] = ncRef.to_name( name );

19
M. Tech CSE, Semester-III DC- LAB Report

45. ncRef.rebind(path, href);

46. System.out.println("HelloServer ready and waiting ...");

47. // wait for invocations from clients

48. orb.run();

49. }

50. catch (Exception e) {

51. System.err.println("ERROR: " + e);

52. e.printStackTrace(System.out);

53. }

54. System.out.println("HelloServer Exiting ...");

55. }

56. }

Generated Package: HelloApp:

Hello:

1. package HelloApp;
2. /**

3. * HelloApp/Hello.java .

4. * Generated by the IDL-to-Java compiler (portable), version "3.1"

5. * from Hello.idl

6. * Sunday, January 20, 2008 7:36:04 PM PST

7. */

8. public interface Hello extends HelloOperations, org.omg.CORBA.Object,


org.omg.CORBA.portable.IDLEntity

9. {

10. } // interface Hello

20
M. Tech CSE, Semester-III DC- LAB Report

HelloHelper:

1. package HelloApp;
2. /**

3. * HelloApp/HelloHelper.java .

4. * Generated by the IDL-to-Java compiler (portable), version "3.1"

5. * from Hello.idl

6. * Sunday, January 20, 2008 7:36:04 PM PST*/

7. abstract public class HelloHelper

8. {

9. private static String _id = "IDL:HelloApp/Hello:1.0";

10. public static void insert (org.omg.CORBA.Any a, HelloApp.Hello that)

11. {

12. org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();

13. a.type (type ());

14. write (out, that);

15. a.read_value (out.create_input_stream (), type ());

16. }

17. public static HelloApp.Hello extract (org.omg.CORBA.Any a)

18. {

19. return read (a.create_input_stream ());

20. }

21. private static org.omg.CORBA.TypeCode __typeCode = null;

22. synchronized public static org.omg.CORBA.TypeCode type ()

23. {

24. if (__typeCode == null)


21
M. Tech CSE, Semester-III DC- LAB Report

25. {

26. __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (HelloApp.HelloHelper.id (), "Hello");

27. }

28. return __typeCode;

29. }

30. public static String id ()

31. {

32. return _id;

33. }

34. public static HelloApp.Hello read (org.omg.CORBA.portable.InputStream istream)

35. {

36. return narrow (istream.read_Object (_HelloStub.class));

37. }

38. public static void write (org.omg.CORBA.portable.OutputStream ostream, HelloApp.Hello value)

39. {

40. ostream.write_Object ((org.omg.CORBA.Object) value);

41. }

42. public static HelloApp.Hello narrow (org.omg.CORBA.Object obj)

43. {

44. if (obj == null)

45. return null;

46. else if (obj instanceof HelloApp.Hello)

47. return (HelloApp.Hello)obj;

48. else if (!obj._is_a (id ()))

22
M. Tech CSE, Semester-III DC- LAB Report

49. throw new org.omg.CORBA.BAD_PARAM ();

50. else

51. {

52. org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate


();

53. HelloApp._HelloStub stub = new HelloApp._HelloStub ();

54. stub._set_delegate(delegate);

55. return stub;

56. }

57. }

58. }

59.

HelloHolder:

1. package HelloApp;
2. /**

3. * HelloApp/HelloHolder.java .

4. * Generated by the IDL-to-Java compiler (portable), version "3.1"

5. * from Hello.idl

6. * Sunday, January 20, 2008 7:36:04 PM PST

7. */

8. public final class HelloHolder implements org.omg.CORBA.portable.Streamable

9. {

10. public HelloApp.Hello value = null;

11. public HelloHolder ()

12. {

23
M. Tech CSE, Semester-III DC- LAB Report

13. }

14. public HelloHolder (HelloApp.Hello initialValue)

15. {

16. value = initialValue;

17. }

18. public void _read (org.omg.CORBA.portable.InputStream i)

19. {

20. value = HelloApp.HelloHelper.read (i);

21. }

22. public void _write (org.omg.CORBA.portable.OutputStream o)

23. {

24. HelloApp.HelloHelper.write (o, value);

25. }

26. public org.omg.CORBA.TypeCode _type ()

27. {

28. return HelloApp.HelloHelper.type ();

29. }

30. }

HelloOperations:

1. package HelloApp;
2. /**

3. * HelloApp/HelloOperations.java .

4. * Generated by the IDL-to-Java compiler (portable), version "3.1"

5. * from Hello.idl

6. * Sunday, January 20, 2008 7:36:04 PM PST*/


24
M. Tech CSE, Semester-III DC- LAB Report

7. public interface HelloOperations

8. {

9. String sayHello ();

10. void shutdown ();

11. } // interface HelloOperations

HelloPOA:

1. package HelloApp;
2. /**

3. * HelloApp/HelloPOA.java .

4. * Generated by the IDL-to-Java compiler (portable), version "3.1"

5. * from Hello.idl

6. * Sunday, January 20, 2008 7:36:04 PM PST

7. */

8. public abstract class HelloPOA extends org.omg.PortableServer.Servant

9. implements HelloApp.HelloOperations, org.omg.CORBA.portable.InvokeHandler

10. {

11. // Constructors

12. private static java.util.Hashtable _methods = new java.util.Hashtable ();

13. static

14. {

15. _methods.put ("sayHello", new java.lang.Integer (0));

16. _methods.put ("shutdown", new java.lang.Integer (1));

17. }

18.

19. public org.omg.CORBA.portable.OutputStream _invoke (String $method,


25
M. Tech CSE, Semester-III DC- LAB Report

20. org.omg.CORBA.portable.InputStream in,

21. org.omg.CORBA.portable.ResponseHandler $rh)

22. {

23. org.omg.CORBA.portable.OutputStream out = null;

24. java.lang.Integer __method = (java.lang.Integer)_methods.get ($method);

25. if (__method == null)

26. throw new org.omg.CORBA.BAD_OPERATION (0,


org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);

27. switch (__method.intValue ())

28. {

29. case 0: // HelloApp/Hello/sayHello

30. {

31. String $result = null;

32. $result = this.sayHello ();

33. out = $rh.createReply();

34. out.write_string ($result);

35. break;

36. }

37. case 1: // HelloApp/Hello/shutdown

38. {

39. this.shutdown ();

40. out = $rh.createReply();

41. break;

42. }

43. default:
26
M. Tech CSE, Semester-III DC- LAB Report

44. throw new org.omg.CORBA.BAD_OPERATION (0,


org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);

45. }

46. return out;

47. } // _invoke

48. // Type-specific CORBA::Object operations

49. private static String[] __ids = {

50. "IDL:HelloApp/Hello:1.0"};

51. public String[] _all_interfaces (org.omg.PortableServer.POA poa, byte[] objectId)

52. {

53. return (String[])__ids.clone ();

54. }

55. public Hello _this()

56. {

57. return HelloHelper.narrow(

58. super._this_object());

59. }

60. public Hello _this(org.omg.CORBA.ORB orb)

61. {

62. return HelloHelper.narrow(

63. super._this_object(orb));

64. }

65. } // class HelloPOA

_HelloStub:

1. package HelloApp;
27
M. Tech CSE, Semester-III DC- LAB Report

2. /**

3. * HelloApp/_HelloStub.java .

4. * Generated by the IDL-to-Java compiler (portable), version "3.1"

5. * from Hello.idl

6. * Sunday, January 20, 2008 7:36:04 PM PST

7. */

8. public class _HelloStub extends org.omg.CORBA.portable.ObjectImpl implements HelloApp.Hello

9. {

10. public String sayHello ()

11. {

12. org.omg.CORBA.portable.InputStream $in = null;

13. try {

14. org.omg.CORBA.portable.OutputStream $out = _request ("sayHello", true);

15. $in = _invoke ($out);

16. String $result = $in.read_string ();

17. return $result;

18. } catch (org.omg.CORBA.portable.ApplicationException $ex) {

19. $in = $ex.getInputStream ();

20. String _id = $ex.getId ();

21. throw new org.omg.CORBA.MARSHAL (_id);

22. } catch (org.omg.CORBA.portable.RemarshalException $rm) {

23. return sayHello ();

24. } finally {

25. _releaseReply ($in);

28
M. Tech CSE, Semester-III DC- LAB Report

26. }

27. } // sayHello

28. public void shutdown ()

29. {

30. org.omg.CORBA.portable.InputStream $in = null;

31. try {

32. org.omg.CORBA.portable.OutputStream $out = _request ("shutdown", false);

33. $in = _invoke ($out);

34. } catch (org.omg.CORBA.portable.ApplicationException $ex) {

35. $in = $ex.getInputStream ();

36. String _id = $ex.getId ();

37. throw new org.omg.CORBA.MARSHAL (_id);

38. } catch (org.omg.CORBA.portable.RemarshalException $rm) {

39. shutdown ();

40. } finally {

41. _releaseReply ($in);

42. }

43. } // shutdown

44. // Type-specific CORBA::Object operations

45. private static String[] __ids = {

46. "IDL:HelloApp/Hello:1.0"};

47. public String[] _ids ()

48. {

49. return (String[])__ids.clone ();

29
M. Tech CSE, Semester-III DC- LAB Report

50. }

51. private void readObject (java.io.ObjectInputStream s) throws java.io.IOException

52. {

53. String str = s.readUTF ();

54. String[] args = null;

55. java.util.Properties props = null;

56. org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init (args, props).string_to_object (str);

57. org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate


();

58. _set_delegate (delegate);

59. }

60. private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException

61. {

62. String[] args = null;

63. java.util.Properties props = null;

64. String str = org.omg.CORBA.ORB.init (args, props).object_to_string (this);

65. s.writeUTF (str);

66. }

67. } // class _HelloStub

EXECUTION PROCESS:

1. <workdir> idlj -fall Hello.idl


2. write the HelloServer & helloClient program

3. compile the programs

30
M. Tech CSE, Semester-III DC- LAB Report

<workdir> javac HelloServer.java HelloApp\*.java

<workdir> javac HelloClient.java HelloApp\*.java

4. Running of the client & server

start orbd -ORBInitialPort 1050 -ORBInitialHost localhost

java HelloServer -ORBInitialPort 1050 -ORBInitialHost localhost

5. In another window

java HelloClient -ORBInitialPort 1050 -ORBInitialHost localhost

OUTPUT:

lPort 1050 -ORBInitialHost localhost

Obtained a handle on server object: HelloApp.HelloStub:IOR: 00000000000000174944

4c3a48656c6c6f4170702f48656c6c6f3a312e300000000000010000000000000068000102000000

000a3132372e302e302e3100040800000021afabcb00000000209adaa39a00000001000000000000

000000000004000000000a0000000000000100000001000000200000000000010001000000020501

000100010020000101090000000100010100

Hello world!!

/******************************************************************************************/

5. BUILDING ENTERPRISE APPLICATIONS USING JAVA BEAN (EJB)


/******************************************************************************************/

Software Requirements: JDK 6.0, J2EE Server

Concept:

What Is an Enterprise Bean?

31
M. Tech CSE, Semester-III DC- LAB Report

Written in the Java programming language, an enterprise bean is a server-side component that
encapsulates the business logic of an application. The business logic is the code that fulfills the purpose of
the application. In an inventory control application, for example, the enterprise beans might implement
the business logic in methods called checkInventoryLevel and orderProduct. By invoking
these methods, remote clients can access the inventory services provided by the application.

Benefits of Enterprise Beans


For several reasons, enterprise beans simplify the development of large, distributed applications. First,
because the EJB container provides system-level services to enterprise beans, the bean developer can
concentrate on solving business problems. The EJB container--not the bean developer--is responsible for
system-level services such as transaction management and security authorization.

Second, because the beans--and not the clients--contain the application's business logic, the client
developer can focus on the presentation of the client. The client developer does not have to code the
routines that implement business rules or access databases. As a result, the clients are thinner, a benefit
that is particularly important for clients that run on small devices.

Third, because enterprise beans are portable components, the application assembler can build new
applications from existing beans. These applications can run on any compliant J2EE server.

When to Use Enterprise Beans

We should consider using enterprise beans if our application has any of the following requirements:
The application must be scalable. To accommodate a growing number of users, we may need to distribute
an application's components across multiple machines. Not only can the enterprise beans of an application
run on different machines, but their location will remain transparent to the clients.

Transactions are required to ensure data integrity. Enterprise beans support transactions, the mechanisms
that manage the concurrent access of shared objects. The application will have a variety of clients. With
just a few lines of code, remote clients can easily locate enterprise beans. These clients can be thin,
various, and numerous.

Types of Enterprise Beans

What Is a Session Bean?

A session bean represents a single client inside the J2EE server. To access an application that is deployed
on the server, the client invokes the session bean's methods. The session bean performs work for its client,
shielding the client from complexity by executing business tasks inside the server.
As its name suggests, a session bean is similar to an interactive session. A session bean is not shared--it
may have just one client, in the same way that an interactive session may have just one user. Like an
interactive session, a session bean is not persistent. (That is, its data is not saved to a database.) When the
client terminates, its session bean appears to terminate and is no longer associated with the client.

State Management Modes


There are two types of session beans: Stateful and stateless.
32
M. Tech CSE, Semester-III DC- LAB Report

Stateful Session Beans

The state of an object consists of the values of its instance variables. In a stateful session bean, the
instance variables represent the state of a unique client-bean session. Because the client interacts ("talks")
with its bean, this state is often called the conversational state.
The state is retained for the duration of the client-bean session. If the client removes the bean or
terminates, the session ends and the state disappears. This transient nature of the state is not a problem,
however, because when the conversation between the client and the bean ends there is no need to retain
the state.
The Life Cycle of a Stateful Session Bean given below illustrates the stages that a session bean passes
through during its lifetime. The client initiates the life cycle by invoking the create method. The EJB
container instantiates the bean and then invokes the setSessionContext and ejbCreate methods
in the session bean. The bean is now ready to have its business methods invoked.

Life Cycle of a Stateful Session Bean

While in the ready stage, the EJB container may decide to deactivate, or passivate, the bean by moving it
from memory to secondary storage. (Typically, the EJB container uses a least-recently-used algorithm to
select a bean for passivation.) The EJB container invokes the bean's ejbPassivate method
immediately before passivating it. If a client invokes a business method on the bean while it is in the
passive stage, the EJB container activates the bean, moving it back to the ready stage, and then calls the
bean's ejbActivate method.
At the end of the life cycle, the client invokes the remove method and the EJB container calls the bean's
ejbRemove method. The bean's instance is ready for garbage collection.
Our code controls the invocation of only two life-cycle methods--the create and remove methods in
the client. All other methods are invoked by the EJB container. The ejbCreate method, for example, is
inside the bean class, allowing we to perform certain operations right after the bean is instantiated. For
instance, we may wish to connect to a database in the ejbCreate method.
A stateless session bean does not maintain a conversational state for a particular client. When a client
invokes the method of a stateless bean, the bean's instance variables may contain a state, but only for the
duration of the invocation. When the method is finished, the state is no longer retained. Except during
method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign
an instance to any client.
Because stateless session beans can support multiple clients, they can offer better scalability for
applications that require large numbers of clients. Typically, an application requires fewer stateless session
beans than stateful session beans to support the same number of clients.
At times, the EJB container may write a stateful session bean to secondary storage. However, stateless
33
M. Tech CSE, Semester-III DC- LAB Report

session beans are never written to secondary storage. Therefore, stateless beans may offer better
performance than stateful beans.

The Life Cycle of a Stateless Session Bean

Because a stateless session bean is never passivated, its life cycle has just two stages: nonexistent and
ready for the invocation of business methods.

Life Cycle of a Stateless Session Bean

When to Use Session Beans

In general, we should use a session bean if the following circumstances hold: At any given time, only one
client has access to the bean instance. The state of the bean is not persistent, existing only for a short
period of time (perhaps a few hours). Stateful session beans are appropriate if any of the following
conditions are true: The bean's state represents the interaction between the bean and a specific client. The
bean needs to hold information about the client across method invocations. The bean mediates between
the client and the other components of the application, presenting a simplified view to the client. Behind
the scenes, the bean manages the work flow of several enterprise beans. For an example, see the
AccountControllerEJB session bean. To improve performance, we might choose a stateless session
bean if it has any of these traits: The bean's state has no data for a specific client. In a single method
invocation, the bean performs a generic task for all clients. For example, we might use a stateless session
bean to send an e-mail that confirms an online order.

The bean fetches from a database a set of read-only data that is often used by clients. Such a bean, for
example, could retrieve the table rows that represent the products that are on sale this month.

What Is an Entity Bean?


An entity bean represents a business object in a persistent storage mechanism. Some examples of business
objects are customers, orders, and products. In the J2EE SDK, the persistent storage mechanism is a
relational database. Typically, each entity bean has an underlying table in a relational database, and each
instance of the bean corresponds to a row in that table.

What Makes Entity Beans Different from Session Beans?


Entity beans differ from session beans in several ways. Entity beans are persistent, allow shared access,
have primary keys, and may participate in relationships with other entity beans.

34
M. Tech CSE, Semester-III DC- LAB Report

Persistence
Because the state of an entity bean is saved in a storage mechanism, it is persistent. Persistence means
that the entity bean's state exists beyond the lifetime of the application or the J2EE server process. If
we've worked with databases, we're familiar with persistent data. The data in a database is persistent
because it still exists even after we shut down the database server or the applications it services.
There are two types of persistence for entity beans: bean-managed and container-managed. With bean-
managed persistence, the entity bean code that we write contains the calls that access the database. If the
bean has container-managed persistence, the EJB container automatically generates the necessary
database access calls.
Entity beans may be shared by multiple clients. Because the clients might want to change the same data,
it's important that entity beans work within transactions. Typically, the EJB container provides transaction
management. In this case, we specify the transaction attributes in the bean's deployment descriptor.

Primary Key
Each entity bean has a unique object identifier. A customer entity bean, for example, might be identified
by a customer number. The unique identifier, or primary key, enables the client to locate a particular entity
bean.
Like a table in a relational database, an entity bean may be related to other entity beans. For example, in a
college enrollment application, StudentEJB and CourseEJB would be related because students enroll
in classes.
We implement relationships differently for entity beans with bean-managed persistence and those with
container-managed persistence. With bean-managed persistence, the code that we write implements the
relationships. But with container-managed persistence, the EJB container takes care of the relationships
for we. For this reason, relationships in entity beans with container-managed persistence are often referred
to as container-managed relationships.

The Life Cycle of an Entity Bean


The figure shows the stages that an entity bean passes through during its lifetime. After the EJB container
creates the instance, it calls the setEntityContext method of the entity bean class. The
setEntityContext method passes the entity context to the bean.
After instantiation, the entity bean moves to a pool of available instances. While in the pooled stage, the
instance is not associated with any particular EJB object identity. All instances in the pool are identical.
The EJB container assigns an identity to an instance when moving it to the ready stage.
There are two paths from the pooled stage to the ready stage. On the first path, the client invokes the
create method, causing the EJB container to call the ejbCreate and ejbPostCreate methods.
On the second path, the EJB container invokes the ejbActivate method. While in the ready stage, an
entity bean's business methods may be invoked.
There are also two paths from the ready stage to the pooled stage. First, a client may invoke the remove
method, which causes the EJB container to call the ejbRemove method. Second, the EJB container may
invoke the ejbPassivate method.

35
M. Tech CSE, Semester-III DC- LAB Report

Life Cycle of an Entity Bean

At the end of the life cycle, the EJB container removes the instance from the pool and invokes the
unsetEntityContext method.
In the pooled state, an instance is not associated with any particular EJB object identity. With bean-
managed persistence, when the EJB container moves an instance from the pooled state to the ready state,
it does not automatically set the primary key. Therefore, the ejbCreate and ejbActivate methods
must assign a value to the primary key. If the primary key is incorrect, the ejbLoad and ejbStore
methods cannot synchronize the instance variables with the database. In the section The
SavingsAccountEJB Example, the ejbCreate method assigns the primary key from one of the input
parameters. The ejbActivate method sets the primary key (id) as follows:
id = (String)context.getPrimaryKey();

In the pooled state, the values of the instance variables are not needed. We can make these instance
variables eligible for garbage collection by setting them to null in the ejbPasssivate method.

What Is a Message-Driven Bean?


A message-driven bean is an enterprise bean that allows J2EE applications to process messages
asynchronously. It acts as a JMS message listener, which is similar to an event listener except that it
receives messages instead of events. The messages may be sent by any J2EE component--an application
client, another enterprise bean, or a Web component--or by a JMS application or system that does not use
J2EE technology.
Message-driven beans currently process only JMS messages, but in the future they may be used to process
other kinds of messages.

What Makes Message-Driven Beans Different from Session and Entity Beans?
The most visible difference between message-driven beans and session and entity beans is that clients do
not access message-driven beans through interfaces. Interfaces are described in the section Defining
Client Class with Interface. Unlike a session or entity bean, a message-driven bean has only a bean class.
In several respects, a message-driven bean resembles a stateless session bean.

A message-driven bean's instances retain no data or conversational state for a specific client.
All instances of a message-driven bean are equivalent, allowing the EJB container to assign a message to
any message-driven bean instance. The container can pool these instances to allow streams of messages to
be processed concurrently.
36
M. Tech CSE, Semester-III DC- LAB Report

A single message-driven bean can process messages from multiple clients.


The instance variables of the message-driven bean instance can contain some state across the handling of
client messages--for example, a JMS API connection, an open database connection, or an object reference
to an enterprise bean object.

When a message arrives, the container calls the message-driven bean's onMessage method to process
the message. The onMessage method normally casts the message to one of the five JMS message types
and handles it in accordance with the application's business logic. The onMessage method may call
helper methods, or it may invoke a session or entity bean to process the information in the message or to
store it in a database.

A message may be delivered to a message-driven bean within a transaction context, so that all operations
within the onMessage method are part of a single transaction. If message processing is rolled back, the
message will be redelivered.

When to Use Message-Driven Beans


Session beans and entity beans allow we to send JMS messages and to receive them synchronously, but
not asynchronously. To avoid tying up server resources, we may prefer not to use blocking synchronous
receives in a server-side component. To receive messages asynchronously, use a message-driven bean.

The Life Cycle of a Message-Driven Bean

The EJB container usually creates a pool of message-driven bean instances. For each instance, the EJB
container instantiates the bean and performs these tasks: It calls the setMessageDrivenContext
method to pass the context object to the instance. It calls the instance's ejbCreate method.

Life Cycle of a Message-Driven Bean

Like a stateless session bean, a message-driven bean is never passivated, and it has only two states:
nonexistent and ready to receive messages. At the end of the life cycle, the container calls the
ejbRemove method. The bean's instance is then ready for garbage collection.

The Contents of an Enterprise Bean


To develop an enterprise bean, we must provide the following files:
Deployment descriptor: An XML file that specifies information about the bean such as its persistence
type and transaction attributes. The deploytool utility creates the deployment descriptor when we step
37
M. Tech CSE, Semester-III DC- LAB Report

through the New Enterprise Bean wizard.

Enterprise bean class: Implements the methods defined in the following interfaces.
Interfaces: The remote and home interfaces are required for remote access. For local access, the local and
local home interfaces are required.
Helper classes: Other classes needed by the enterprise bean class, such as exception and utility classes.
We package the files in the preceding list into an EJB JAR file, the module that stores the enterprise bean.
An EJB JAR file is portable and may be used for different applications. To assemble a J2EE application,
we package one or more modules--such as EJB JAR files--into an EAR file, the archive file that holds the
application. When we deploy the EAR file that contains the bean's EJB JAR file, we also deploy the
enterprise bean onto the J2EE server.

A Session Bean Example


Session beans are powerful because they extend the reach of the clients into remote servers--yet they're
easy to build.

The CartEJB Example

The CartEJB session bean represents a shopping cart in an online bookstore. The bean's client may add
a book to the cart, remove a book, or retrieve the cart's contents. To construct CartEJB, we need the
following code:
Session bean class (CartBean)
Home interface (CartHome)
Remote interface (Cart)
All session beans require a session bean class. All enterprise beans that permit remote access must have a
home and remote interface. To meet the needs of a specific application, an enterprise bean may also need
some helper classes. The CartEJB session bean uses two helper classes, BookException and
IdVerifier, which are discussed in the section Helper Classes.
The source code for this example is in the j2eetutorial/examples/src/ejb/cart directory.
To compile the code, go to the j2eetutorial/examples directory and type ant cart. A sample
CartApp.ear file is in the j2eetutorial/examples/ears directory.
Session Bean Class
The session bean class for this example is called CartBean. Like any session bean, the CartBean
class must meet these requirements:
It implements the SessionBean interface.
The class is defined as public.
The class cannot be defined as abstract or final.
It implements one or more ejbCreate methods.
It implements the business methods.
It contains a public constructor with no parameters.
It must not define the finalize method.
The source code for the CartBean class follows.
import java.util.*;
import javax.ejb.*;

public class CartBean implements SessionBean {


38
M. Tech CSE, Semester-III DC- LAB Report

String customerName;
String customerId;
Vector contents;

public void ejbCreate(String person)


throws CreateException {

if (person == null) {
throw new CreateException("Null person not allowed.");
}
else {
customerName = person;
}

customerId = "0";
contents = new Vector();
}

public void ejbCreate(String person, String id)


throws CreateException {

if (person == null) {
throw new CreateException("Null person not allowed.");
}
else {
customerName = person;
}

IdVerifier idChecker = new IdVerifier();


if (idChecker.validate(id)) {
customerId = id;
}
else {
throw new CreateException("Invalid id: "+ id);
}

contents = new Vector();


}

public void addBook(String title) {


contents.addElement(title);
}

public void removeBook(String title) throws BookException {

39
M. Tech CSE, Semester-III DC- LAB Report

boolean result = contents.removeElement(title);


if (result == false) {
throw new BookException(title + "not in cart.");
}
}

public Vector getContents() {


return contents;
}

public CartBean() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext sc) {}

The SessionBean Interface


The SessionBean interface extends the EnterpriseBean interface, which in turn extends the
Serializable interface. The SessionBean interface declares the ejbRemove, ejbActivate,
ejbPassivate, and setSessionContext methods. The CartBean class doesn't use these
methods, but it must implement them because they're declared in the SessionBean interface.
Consequently, these methods are empty in the CartBean class. Later sections explain when we might
use these methods.
The ejbCreate Methods
Because an enterprise bean runs inside an EJB container, a client cannot directly instantiate the bean.
Only the EJB container can instantiate an enterprise bean. During instantiation, the example program
performs the following steps.
The client invokes a create method on the home object:
Cart shoppingCart = home.create("Duke DeEarl","123");
The EJB container instantiates the enterprise bean.
The EJB container invokes the appropriate ejbCreate method in CartBean:
public void ejbCreate(String person, String id)
throws CreateException {

if (person == null) {
throw new CreateException("Null person not allowed.");
}
else {
customerName = person;
}

IdVerifier idChecker = new IdVerifier();


if (idChecker.validate(id)) {
customerId = id;
40
M. Tech CSE, Semester-III DC- LAB Report

}
else {
throw new CreateException("Invalid id: "+ id);
}

contents = new Vector();


}

Typically, an ejbCreate method initializes the state of the enterprise bean. The preceding ejbCreate
method, for example, initializes the customerName and customerId variables with the arguments
passed by the create method.
An enterprise bean must have one or more ejbCreate methods. The signatures of the methods must
meet the following requirements:
The access control modifier must be public.
The return type must be void.
If the bean allows remote access, the arguments must be legal types for the Java Remote Method
Invocation ("Java RMI") API.
The modifier cannot be static or final.
The throws clause may include the javax.ejb.CreateException and other exceptions that are
specific to the application. The ejbCreate method usually throws a CreateException if an input
parameter is invalid.
Business Methods
The primary purpose of a session bean is to run business tasks for the client. The client invokes business
methods on the remote object reference that is returned by the create method. From the client's
perspective, the business methods appear to run locally, but they actually run remotely in the session bean.
The following code snippet shows how the CartClient program invokes the business methods:
Cart shoppingCart = home.create("Duke DeEarl", "123");
...
shoppingCart.addBook("The Martian Chronicles");
shoppingCart.removeBook("Alice In Wonderland");
bookList = shoppingCart.getContents();

The CartBean class implements the business methods in the following code:
public void addBook(String title) {
contents.addElement(new String(title));
}

41
M. Tech CSE, Semester-III DC- LAB Report

public void removeBook(String title) throws BookException {


boolean result = contents.removeElement(title);
if (result == false) {
throw new BookException(title + "not in cart.");
}
}

public Vector getContents() {


return contents;
}

The signature of a business method must conform to these rules:


The method name must not conflict with one defined by the EJB architecture. For example, we cannot
call a business method ejbCreate or ejbActivate.
The access control modifier must be public.
If the bean allows remote access, the arguments and return types must be legal types for the Java RMI
API.
The modifier must not be static or final.
The throws clause may include exceptions that we define for the application. The removeBook
method, for example, throws the BookException if the book is not in the cart.
To indicate a system-level problem, such as the inability to connect to a database, a business method
should throw the javax.ejb.EJBException. When a business method throws an EJBException,
the container wraps it in a RemoteException, which is caught by the client. The container will not
wrap application exceptions such as BookException. Because EJBException is a subclass of
RuntimeException, we do not need to include it in the throws clause of the business method.
Home Interface
A home interface extends the javax.ejb.EJBHome interface. For a session bean, the purpose of the
home interface is to define the create methods that a remote client may invoke. The CartClient
program, for example, invokes this create method:
Cart shoppingCart = home.create("Duke DeEarl", "123");

Every create method in the home interface corresponds to an ejbCreate method in the bean class. The signatures of the
ejbCreate methods in the CartBean class follow:
public void ejbCreate(String person) throws CreateException
...
public void ejbCreate(String person, String id)
throws CreateException
42
M. Tech CSE, Semester-III DC- LAB Report

Compare the ejbCreate signatures with those of the create methods in the CartHome interface:
import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

public interface CartHome extends EJBHome {


Cart create(String person) throws
RemoteException, CreateException;
Cart create(String person, String id) throws
RemoteException, CreateException;
}

The signatures of the ejbCreate and create methods are similar, but differ in important ways. The
rules for defining the signatures of the create methods of a home interface follow.
The number and types of arguments in a create method must match those of its corresponding
ejbCreate method.
The arguments and return type of the create method must be valid RMI types.
A create method returns the remote interface type of the enterprise bean. (But an ejbCreate method
returns void.)
The throws clause of the create method must include the java.rmi.RemoteException and the
javax.ejb.CreateException.
Remote Interface
The remote interface, which extends javax.ejb.EJBObject, defines the business methods that a
remote client may invoke. Here is the source code for the Cart remote interface:
import java.util.*;
import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface Cart extends EJBObject {

public void addBook(String title) throws RemoteException;


public void removeBook(String title) throws
BookException, RemoteException;
public Vector getContents() throws RemoteException;
}

43
M. Tech CSE, Semester-III DC- LAB Report

The method definitions in a remote interface must follow these rules:


Each method in the remote interface must match a method implemented in the enterprise bean class.
The signatures of the methods in the remote interface must be identical to the signatures of the
corresponding methods in the enterprise bean class.
The arguments and return values must be valid RMI types.
The throws clause must include the java.rmi.RemoteException.
Helper Classes
The CartEJB session bean has two helper classes: BookException and IdVerifier. The
BookException is thrown by the removeBook method and the IdVerifier validates the
customerId in one of the ejbCreate methods. Helper classes must reside in the EJB JAR file that
contains the enterprise bean class.
Running the CartEJB Example
Start the J2EE server and deploytool.
In deploytool open the j2eetutorial/examples/ears/CartApp.ear file (File Open).
We should see the application that is displayed in figure.
Deploy the CartApp application (Tools Deploy). In the Introduction dialog box, make sure that we
select the Return Client JAR checkbox. Run the application. In a terminal window, go to the
j2eetutorial/examples/ears directory. Set the APPCPATH environment variable to
CartAppClient.jar.
Type the following command:
runclient -client CartApp.ear -name CartClient -textauth

At the login prompts, enter guest for the user name and guest123 for the password.

Output:

44
M. Tech CSE, Semester-III DC- LAB Report

General Tabbed Pane of the CartApp Application

45
M. Tech CSE, Semester-III DC- LAB Report

/****************************************************************************************/

6. TCP SERVER USING JAVA


/****************************************************************************************/

TCPServer.java

import java.net.*;
import java.io.*;
public class TCPServer {
public static void main(String a[])
{
Socket s=null;
try
{
int serverPort=8117;
ServerSocket listenSocket=new ServerSocket(serverPort);
while(true)
{
Socket clientSocket=listenSocket.accept();
Connection c=new Connection(clientSocket);
}
}
catch(IOException e)
{ System.out.println("Listen:"+e.getMessage()); }
}
}
class Connection extends Thread {
DataInputStream in;
DataOutputStream out;
Socket clientSocket;
public Connection(Socket aClientSocket) {
try {
clientSocket=aClientSocket;
in=new DataInputStream(clientSocket.getInputStream());
out=new DataOutputStream(clientSocket.getOutputStream());
this.start();
}
catch(IOException e)
{
System.out.println("Connection:"+e.getMessage());
}
}
public void run() {
try {
46
M. Tech CSE, Semester-III DC- LAB Report

String data=in.readUTF();
out.writeUTF(data);
System.out.println("Received: "+ data) ;
}
TCPServTCPServercatch(EOFException e)
{
System.out.println("EOF:"+e.getMessage()); }
catch(IOException e)
{
System.out.println("IO:"+e.getMessage()); }
finally
{
try
{
clientSocket.close();
}
catch(IOException e)
{ System.out.println("IO:"+e.getMessage()); }
}}}

TCPClient.java

import java.net.*;
import java.io.*;
public class TCPClient {
public static void main (String args[]) {
// arguments supply message and hostname
47
M. Tech CSE, Semester-III DC- LAB Report

Socket s = null;
try{
int serverPort = 8117;
s = new Socket(args[1],serverPort);
DataInputStream in = new DataInputStream( s.getInputStream());
DataOutputStream out =new DataOutputStream( s.getOutputStream());
out.writeUTF(args[0]); // UTF is a string encoding
String data = in.readUTF(); // read a line of data from the stream
System.out.println("Received: "+ data) ;
}catch (UnknownHostException e){System.out.println("Socket:"+e.getMessage());
}catch (EOFException e){System.out.println("EOF:"+e.getMessage());
}catch (IOException e){System.out.println("readline:"+e.getMessage());
}finally {if(s!=null) try {s.close();}catch (IOException
e){System.out.println("close:"+e.getMessage());}}
}}

/******************************************************************************************/

7. UDP SERVER USING JAVA


/******************************************************************************************/
UDPServer.Java

import java.net.*;
import java.io.*;
public class UDPServer {
public static void main(String args[]) {
48
M. Tech CSE, Semester-III DC- LAB Report

DatagramSocket aSocket = null;


try {
aSocket = new DatagramSocket(8117);
byte[] buffer = new byte[1000];
while(true)
{
DatagramPacket request = new DatagramPacket(buffer, buffer.length);
aSocket.receive(request);
DatagramPacket reply = new DatagramPacket(request.getData(),request.getLength(),
request.getAddress(), request.getPort());
aSocket.send(reply);
System.out.println("Reply:"+new String(reply.getData()));
}
}
catch (SocketException e)
{
System.out.println("Socket: " + e.getMessage());
}
catch (IOException e)
{
System.out.println("IO: " + e.getMessage());
}
finally
{
if(aSocket != null) aSocket.close();
}
}
}

UDPClient.java

import java.net.*;
import java.io.*;
public class UDPClient {
public static void main(String args[]) {
DatagramSocket aSocket=null;
try {
aSocket=new DatagramSocket();
byte[]m=args[0].getBytes();
InetAddress aHost=InetAddress.getByName(args[1]);
int serverPort=8117;
DatagramPacket request=new DatagramPacket(m,args[0].length(),aHost,serverPort);
aSocket.send(request);
byte[] buffer=new byte[1000];
49
M. Tech CSE, Semester-III DC- LAB Report

DatagramPacket reply=new DatagramPacket(buffer,buffer.length);


aSocket.receive(reply);
System.out.println("Reply:"+new String(reply.getData()));
}
catch(SocketException e)
{ System.out.println("Socket:"+e.getMessage()); }
catch(IOException e)
{ System.out.println("IO:"+e.getMessage()); }
finally
{
if(aSocket!=null)
aSocket.close();
}
}
}

/********************************************************************************************/

8. CHAT SERVER USING JAVA


*********************************************************************************************/
import java.net.*;
import java.io.*;
public class ChatServer implements Runnable {
private ChatServerThread clients[]=new ChatServerThread[50];
private ServerSocket server=null;
private Thread thread=null;
private int clientCount=0;
public ChatServer(int port) {
try {
System.out.println("binding to port"+port+",please wait ...");
server=new ServerSocket(port);
System.out.println("server started:"+server);
thread=new Thread(this);
50
M. Tech CSE, Semester-III DC- LAB Report

thread.start();
}
catch(IOException e)
{ System.out.println("cannot bind to port"+port+":"+e.getMessage()); }
}
public void run() {
while(thread!=null) {
try {
System.out.println("waiting for a client...");
addThread(server.accept());
}
catch(IOException e)
{
System.out.println("server accept error:"+e);
if(thread!=null)
{
thread.stop();
thread=null;
}}
}}
public void stop()
{
if(thread!=null)
{
thread.stop();
thread=null;
}
}
private int findClient(int ID) {
for(int i=0;i<clientCount;i++)
if(clients[i].getID()==ID)
return i;
return -1;
}
public synchronized void handle(int ID,String input) {
if(input.equals("quit"))
{
clients[findClient(ID)].send("quit");
remove(ID);
}
else
System.out.println(ID+":"+input);
for(int i=0;i<clientCount;i++)
clients[i].send(ID+":"+input);
}
public synchronized void remove(int ID) {
51
M. Tech CSE, Semester-III DC- LAB Report

int pos=findClient(ID);
if(pos>=0) {
ChatServerThread closing=clients[pos];
System.out.println("removing client thread:"+ID+"at"+pos);
if(pos<clientCount-1)
for(int i=pos+1;i<clientCount;i++)
clients[i-1]=clients[i];
clientCount--;
try {
closing.close();
}
catch(IOException e)
{ System.out.println("error closing thread;"+e); }
closing.stop();
}
}
private void addThread(Socket socket) {
if(clientCount<clients.length) {
System.out.println("client accepted:"+socket);
clients[clientCount]=new ChatServerThread(this,socket);
try {
clients[clientCount].open();
clients[clientCount].start();
clientCount++;
}
catch(IOException e)
{ System.out.println("error opening thread;"+e); }
}
else
System.out.println("client refused;maximum"+clients.length+"reached");
}
public static void main(String a[])
{
ChatServer server=null;
if(a.length!=1)
System.out.println("Usage:java ChatServer Port");
else
server=new ChatServer(Integer.parseInt(a[0]));
}
}

52
M. Tech CSE, Semester-III DC- LAB Report

ChatServerThread.java
import java.net.*;
import java.io.*;
public class ChatServerThread extends Thread {
private ChatServer server=null;
private Socket socket=null;
private DataInputStream In=null;
private int ID=-1;
private PrintStream Out=null;
public ChatServerThread(ChatServer serv,Socket sock) {
super();
server=serv;
socket=sock;
ID=socket.getPort();
}
public void send(String msg) {
Out.println(msg);
Out.flush();
}
public int getID()
{
return ID;
}
public void run() {
System.out.println("Server thread"+ID+"running");
while(true) {
try {
server.handle(ID,In.readLine());
}
catch(IOException e) {
53
M. Tech CSE, Semester-III DC- LAB Report

System.out.println(ID+"error reading"+e.getMessage());
server.remove(ID);
stop();
}
}
}
public void open()throws IOException
{
In=new DataInputStream(socket.getInputStream());
Out=new PrintStream(socket.getOutputStream());
}
public void close()throws IOException
{
if(socket!=null)
socket.close();
if(In!=null)
In.close();
if(Out!=null)
Out.close();
}
}

ChatClient.java
import java.net.*;
import java.io.*;
public class ChatClient implements Runnable {
private ChatClientThread client=null;
private Socket socket=null;
private DataInputStream console=null;
private Thread thread=null;
private PrintStream Out=null;
public ChatClient(String serverName,int serverPort) {
System.out.println("Establishing connection please wait...");
try {
socket=new Socket(serverName,serverPort);
System.out.println("connected"+socket.toString());
console=new DataInputStream (System.in);
Out=new PrintStream(socket.getOutputStream());
if(thread==null)
{
client=new ChatClientThread(this,socket);
thread=new Thread(this);
thread.start();
}
}
catch(UnknownHostException e)
54
M. Tech CSE, Semester-III DC- LAB Report

{
System.out.println("Host unknown"+e.getMessage());
}
catch(IOException ioe)
{
System.out.println("Unexcepted exception"+ioe.getMessage());
}
}
public void run() {
while(thread!=null) {
try {
Out.println(console.readLine());
Out.flush();
}
catch(IOException e)
{
System.out.println("sending error"+e.getMessage());
stop();
}
}
}
public void handle(String msg) {
if(msg.equals("quit"))
{
System.out.println("good bye, press RETURN to exit...");
stop();
}
else
System.out.println(msg);
}
public void stop() {
if(thread!=null) {
thread.stop();
thread=null;
}
try {
if(console!=null)
console.close();
if(Out!=null)
Out.close();
if(socket!=null)
socket.close();
}
catch(IOException e)
{
System.out.println("error closing...");
55
M. Tech CSE, Semester-III DC- LAB Report

}
client.close();
client.stop();
}
public static void main(String args[]) {
ChatClient client=null;
if(args.length!=2)
System.out.println("usage:java ChatClient host port");
else
client=new ChatClient(args[0],Integer.parseInt(args[1]));
}
}

56
M. Tech CSE, Semester-III DC- LAB Report

ChatClientThread.java
import java.net.*;
import java.io.*;
public class ChatClientThread extends Thread {
private ChatClient client=null;
private Socket socket=null;
private DataInputStream In=null;
public ChatClientThread(ChatClient cli,Socket sock)
{
client=cli;
socket=sock;
try
{
In=new DataInputStream(socket.getInputStream());
}
catch (IOException e)
{
System.out.println("error geting input stream:"+e);
client.stop();
}
start();
}
public void close()
{
try
{
if(In!=null)
In.close();
}
catch (IOException e)
{
System.out.println("error closing input stream:"+e);
}
}
public void run()
{
while(true)
{
try
{
client.handle(In.readLine());
}
catch(IOException e)
{
System.out.println("Listening error"+e.getMessage());
client.stop();
57
M. Tech CSE, Semester-III DC- LAB Report

}
}
}
}

58

You might also like