Professional Documents
Culture Documents
-:By:-
Ms Poonam Singh Chandravanshi
_______________________________
UNIVERSITY COLLEGE OF ENGINEERING (A)
1
M. Tech CSE, Semester-III DC- LAB Report
CERTIFICATE
This is to certify that Ms. Poonam Singh Chandravanshi bearing Roll No:
INTERNAL EXAMINER
2
M. Tech CSE, Semester-III DC- LAB Report
Table of Contents
/********************************************************************************************* /
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.
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.
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)
}
}
Move the jar file to C:\Tomcat5.0\webapps\axis\web-inf\lib and set jar file in classpath
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
}
}
}
/*******************************************************************************************/
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.
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.*;
// HelloClient
import java.rmi.*;
try {
Remote r = Naming.lookup("rmi://127.0.0.1:1112/value");
Hello i = (Hello) r;
catch (Exception e) {
System.out.println(e);
import java.rmi.*;
import java.rmi.server.*;
private int i;
10
M. Tech CSE, Semester-III DC- LAB Report
//UnicastRemoteObject.exportObject(this);
System.out.println("Object created");
i++;
}}
// HelloServer class
import java.rmi.*;
import java.rmi.registry.*;
try { LocateRegistry.createRegistry(1112);
Naming.rebind("rmi://127.0.0.1:1112/value", r);
catch (Exception e) {
System.out.println(e);
11
M. Tech CSE, Semester-III DC- LAB Report
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.
workdir> rmic on impl file (the file which implements the interface)
workdir> In another c
/*******************************************************************************************/
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
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;
/******************************************************************************************/
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.
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 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.
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.
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.*;
6. {
9. {
10. try{
15. orb.resolve_initial_references("NameService");
23. System.out.println(helloImpl.sayHello());
24. helloImpl.shutdown();
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;
12. }
16. }
19. orb.shutdown(false);
20. }
18
M. Tech CSE, Semester-III DC- LAB Report
21. }
24. try{
29. rootpoa.the_POAManager().activate();
32. helloImpl.setORB(orb);
38. orb.resolve_initial_references("NameService");
19
M. Tech CSE, Semester-III DC- LAB Report
48. orb.run();
49. }
52. e.printStackTrace(System.out);
53. }
55. }
56. }
Hello:
1. package HelloApp;
2. /**
3. * HelloApp/Hello.java .
5. * from Hello.idl
7. */
9. {
20
M. Tech CSE, Semester-III DC- LAB Report
HelloHelper:
1. package HelloApp;
2. /**
3. * HelloApp/HelloHelper.java .
5. * from Hello.idl
8. {
11. {
16. }
18. {
20. }
23. {
25. {
27. }
29. }
31. {
33. }
35. {
37. }
39. {
41. }
43. {
22
M. Tech CSE, Semester-III DC- LAB Report
50. else
51. {
54. stub._set_delegate(delegate);
56. }
57. }
58. }
59.
HelloHolder:
1. package HelloApp;
2. /**
3. * HelloApp/HelloHolder.java .
5. * from Hello.idl
7. */
9. {
12. {
23
M. Tech CSE, Semester-III DC- LAB Report
13. }
15. {
17. }
19. {
21. }
23. {
25. }
27. {
29. }
30. }
HelloOperations:
1. package HelloApp;
2. /**
3. * HelloApp/HelloOperations.java .
5. * from Hello.idl
8. {
HelloPOA:
1. package HelloApp;
2. /**
3. * HelloApp/HelloPOA.java .
5. * from Hello.idl
7. */
10. {
11. // Constructors
13. static
14. {
17. }
18.
22. {
28. {
30. {
35. break;
36. }
38. {
41. break;
42. }
43. default:
26
M. Tech CSE, Semester-III DC- LAB Report
45. }
47. } // _invoke
50. "IDL:HelloApp/Hello:1.0"};
52. {
54. }
56. {
58. super._this_object());
59. }
61. {
63. super._this_object(orb));
64. }
_HelloStub:
1. package HelloApp;
27
M. Tech CSE, Semester-III DC- LAB Report
2. /**
3. * HelloApp/_HelloStub.java .
5. * from Hello.idl
7. */
9. {
11. {
13. try {
24. } finally {
28
M. Tech CSE, Semester-III DC- LAB Report
26. }
27. } // sayHello
29. {
31. try {
40. } finally {
42. }
43. } // shutdown
46. "IDL:HelloApp/Hello:1.0"};
48. {
29
M. Tech CSE, Semester-III DC- LAB Report
50. }
52. {
59. }
61. {
66. }
EXECUTION PROCESS:
30
M. Tech CSE, Semester-III DC- LAB Report
5. In another window
OUTPUT:
4c3a48656c6c6f4170702f48656c6c6f3a312e300000000000010000000000000068000102000000
000a3132372e302e302e3100040800000021afabcb00000000209adaa39a00000001000000000000
000000000004000000000a0000000000000100000001000000200000000000010001000000020501
000100010020000101090000000100010100
Hello world!!
/******************************************************************************************/
Concept:
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.
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.
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.
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.
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.
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.
Because a stateless session bean is never passivated, its life cycle has just two stages: nonexistent and
ready for the invocation of business methods.
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.
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.
35
M. Tech CSE, Semester-III DC- LAB Report
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 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
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.
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.
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.
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.
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.*;
String customerName;
String customerId;
Vector contents;
if (person == null) {
throw new CreateException("Null person not allowed.");
}
else {
customerName = person;
}
customerId = "0";
contents = new Vector();
}
if (person == null) {
throw new CreateException("Null person not allowed.");
}
else {
customerName = person;
}
39
M. Tech CSE, Semester-III DC- LAB Report
public CartBean() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext sc) {}
if (person == null) {
throw new CreateException("Null person not allowed.");
}
else {
customerName = person;
}
}
else {
throw new CreateException("Invalid id: "+ id);
}
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
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;
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;
43
M. Tech CSE, Semester-III DC- LAB Report
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
45
M. Tech CSE, Semester-III DC- LAB Report
/****************************************************************************************/
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());}}
}}
/******************************************************************************************/
import java.net.*;
import java.io.*;
public class UDPServer {
public static void main(String args[]) {
48
M. Tech CSE, Semester-III DC- LAB Report
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
/********************************************************************************************/
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