• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Ejb notes
 

Ejb notes

on

  • 900 views

EJB 3.0, 3.1, Framework, Tutorials, Learning, Beginners, Basics, Environment Setup, Application Server, Container, Enterprise Bean, Annotations, Session Bean, Stateless Session Bean, Stateful Session ...

EJB 3.0, 3.1, Framework, Tutorials, Learning, Beginners, Basics, Environment Setup, Application Server, Container, Enterprise Bean, Annotations, Session Bean, Stateless Session Bean, Stateful Session Bean, Message Driven Bean, Entity Bean, Remote Interface, Lookup, Life Cycle, Interfaces, Interceptors, Callbacks, Deployment Descriptor, Create Application, Access Database, Query Language, Dependency Injection, Exception Handling

Statistics

Views

Total Views
900
Views on SlideShare
900
Embed Views
0

Actions

Likes
0
Downloads
49
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Ejb notes Ejb notes Document Transcript

    • Uploaded by - EJB 3.0 Tutorials This tutorial gradually takes a new comer to master EJB along with learning the updated JEE specifications using glass-fish server. Tutorials provided are easy to grasp and subsequently shift onto the practical implementations. 1. Introduction to Application Server Application server was developed to support for developing the enterprise applications for security and state maintenance with the data base and persistence. 2. What is EJB-Container? Transaction Management Security Resource and life cycle management Remote Accessibility Concurrency control Clustering and load-balancing 3. Enterprise Beans What is an enterprise bean Benefits of enterprise beans When to use enterprise beans Types of enterprise beans 4. Features of EJB 3.0 Elimination of Home and Remote Interfaces Elimination of Component Interface Simplified Access to Environment Dependency Injection EJB Context Enhanced Lifecycle Methods and Callback Listener Classes Interceptors Simple JNDI lookup of EJB 5. Annotations To make the development easier and execution of the programs fast and efficient sun micro system added the features like annotation in jdk 5. The main objectives behind the development of annotations is to make the development easier. Annotations behaves like
    • the meta 6. Session Beans What is a session bean Types of session beans Stateless Session Bean Stateful session bean When to use session bean Life Cycle of Stateless session Life Cycle of Stateful session bean 7. Getting Started Examples with Enterprise Session Beans o Stateless Session Bean Example o Statelful Session Bean Example 8. Message Driven Beans Motivations for messaging Non blocking request processing Decoupling Reliability Support for multiple senders and receivers Java Message Services (JMS) JMS API JMS Architecture Integrating JMS with EJB Using a Java Object that receives the JMS messages to call EJB client Reuse an existing type of EJB component somehow to receive JMS messages Message driven bean 9. A Message-Driven Bean Example To receive messages asynchronously, a Message-driven bean is used. Message driven beans are the light weight components used for communication via messages (e.g., email or IM messages). 10. Introduction to POJO (Plain Old Java Object) One of the new features of added by Sun Microsystems in EJB 3.0 is POJO (Plain Old Java Object). It is a Java object that doesn't implement any special interfaces require by the EJB framework. 11. Java Persistence API Java Persistence API is the standard API used for the management of the persistent data and object/relational mapping. Java Persistence API is added in Java EE 5 platform. Every application server compatible with Java EE 5 supports the Java Persistent APIs.
    • Features of JPA Advantages of JPA Domain Model: The Basics of EJB3 JPA and O-R Framework: Metedata Annotation in Action Entities Requirements of Entity Classes Persistence Fields and Properties in Entity Classes Persistence Fields Persistent Properties Primary Keys in Entities Primary Key Classes Multiplicity in Entity Relationships Direction in Entity Relationships Queries and Relationship Direction Cascade Deletes and Relationships Entity Inheritance Abstract Entities Mapped Superclasses Non-Entity Superclasses Entity Inheritance Mapping Strategies Single Table per Class Hierarchy Strategy 12. A Java Persistence Example In the Book catalog example, we define a Book entity bean class. The bean has three properties (title, author and price) to model a Book product. The id property is used to uniquely identify the Book bean instance by the EJB3 container. The id value is automatically generated when the bean is saved to the database. 13. Web Services Web services are the mechanism to develop a Service-Oriented-Architecture (SOA). SOA is an architectural approach for designing large scale distributed systems to integrate heterogeneous application on the service interfaces. WSDL SOAP Implementing Web Services Packaging and Deploying a Web Service Session Bean Implementing a Web Service Client 14.  EJB remote interface The program given below describes the way of creating a remote interface in EJB. The meaning of Remote interface in terms of Ejb is the java source file which contain the bean implementation logic.
    • 15.  Ejb message driven bean This tutorial explains you the process which are involved in making a message driven bean using EJB. 16.  EJB lookup example Bean30Remote.java:-This is the Remote interface which extends javax.ejb.EJBObject package. These are similar to RMI Remote interface. 17.  EJB life cycle method The various stages through which an enterprise bean go through its lifetime is known as the life cycle of EJB. Each type of enterprise bean has different life cycle. 18.  EJB Interfaces Remote interface are the interface that has the methods that relate to a particular bean instance. In the Remote interface we have all get methods as given below in the program. 19.  EJB Insert data This is the Remote Interface for the Bean. Here we have used @Remote annotation to declare the class as a Remote Interface. 20.  EJB deployment descriptor Deployment descriptor is the file which tells the EJB server that which classes make up the bean implementation, the home interface and the remote interface. 21.  EJB create method In this tutorial we are describing you about the EJB create method. The create() method is used for creating the EJBean. 22.  EJB container services The EJB container is a container that deploys EJB automatically when Web Server is started. All of the entity objects live in container during its creation to removal. 23.  EJB Hello world example Creating and testing the "Hello World" Example is the very first step towards learning of any application or programming language. 24.  EJB directory structure The tutorial is going to explain the standard directory structure of an EJB application . The figure given below is taken of Netbeans IDE. Here in the given figure NewsApp is the application name of the project which we have created. 25.  Deleting a Row from SQL Table Using EJB In the given example of Enterprise Java Bean, we are going to delete a row from the SQL Table. Find out the steps given below that describes how to delete a particular row from the database table using EJB.
    • 26.  Accessing Database using EJB This is a simple EJB Application that access the database. Just go through the EJB example given below to find out the steps involved in accessing Database. Application Server An application server is an application program that accepts connections in order to service requests, by sending back responses. An application server can run remotely (connected to client through a computer network) or can exist on the same computer where the client application is running. Examples include file server, database server, backup server, print server, mail server, web server, FTP server, application server, VPN server, DHCP server, DNS server, WINS server, logon server, security server, domain controller, backup domain controller, proxy server, firewall, etc. Application server are developed to support the quick development of the enterprise applications. They provide security and state maintenance with the data base and persistence. An application server may be a part of a three tier architecture model. A three tier architecture includes the Client Tier, Middle Tier and the EIS (Enterprise Information System ) Tier. It may consists of Presentation Tier (as the GUI interface), Middle Tier as the collection of business logic application and the EIS (Enterprise Information System). The view tier is nothing but the web based graphical user interface to interact with the clients, Middle tier is the combination of web containers and the EJB containers. EIS contains persistence and the database management systems to support the applications. JEE Platform requires database to store the business data. This database is accessible by means of JDBC, JDO or the SQLJ APIs. We can also access the database through enterprise beans, web components and the application client components.
    • EJB Container or EJB Server An EJB container is nothing but the program that runs on the server and implements the EJB specifications. EJB container provides special type of the environment suitable for running the enterprise components. Enterprise beans are used in distributed applications that typically contains the business logic. The container performs the various tasks few of them are illustrated below: Transaction Management: EJB container allows you for transaction management that enables the transaction services, a low level implementation of transaction management and coordination. Container uses the Java Transaction APIs to expose the transaction services. JTA, a high level interface is used to control transactions. Security: JSE mainly focuses on how to become the environment more secure. Enterprise beans add this feature to provide transparent security so that access to the beans can be made secure just by applying the security attributes rather than coding against the security API. Resource and Life Cycle Management: EJB container manages the resources like database connections, threads and socket on behalf of enterprise beans. Container creates, destroys, registers the objects and also activates and passivates them. The container is also capable of reusing them whenever required.
    • Remote Accessibility: A client on the remote machine containing JVM can invoke an enterprise bean running on the host machine. To support the remote accessibility the container uses the remote procedure call technology. When the software is developed by using the OOPs concept then Remote procedure call (RPC) may be referred to as Remote Method Invocation (RMI). Concurrency Control: Concurrency control is necessary to know the basics of collisions and type of collisions that can occur. If you are not interested to occur them then you can bypass them later they will cause to create problems. So try to detect and resolve them. To do so the EJB Container supports for various types of concurrency controls. First we will concentrate on collision and then techniques to resolve these collisions. Collision: A collision can occur when two or more transactions tries to change the entities within a system of records. There are three types through which two or more activities may interfere: • • • Dirty read Non Repeatable read Phantom read Control mechanism: Mainly two mechanism are used to control the concurrency. • • Optimistic Locking Pessimistic Locking Clustering and load-balancing: Clustering is the process of combining the multiple peripherals, computers and other resources into a single unit. A clustered system then works as load balanced system. In a distributed system when a request is send to the server, an algorithm running on the server decides which server has less load and sends the request to that server. EJB container encapsulates these features to provide smooth and efficient service. Enterprise Beans Enterprise beans are the Java EE server side components that run inside the ejb container and encapsulates the business logic of an enterprise application. Enterprise applications are the software applications developed intended to use at large scale. These applications involves large number of data accessing concurrently by many users. Enterprise beans are used to perform various types of task like interacting with the client, maintaining session for the clients retrieving and holding data from the database and communicating with the server.
    • Benefits of enterprise beans: Enterprise beans are widely used for developing large and distributed applications. EJB container provides the system-level services (like transaction management and security authorization) to the enterprise beans. These services simplifies the development process of large and distributed applications and the developer just have to concentrate on solving the problem occurred in it. The client developer can focus only on the representation style of the client as all the business logic of the application is contained in the enterprise beans. The client developer does not bother about the code that implements business logic or the logic to access the databases. This means that the clients are thinner. It benefits the client to be thin because the client runs on the small devices. Developing new applications from the existing beans is much easier because the enterprise beans are portable components. That means applications developed by using the enterprise components can run on any complaint J2EE server. When to use the enterprise beans: Some of the points are illustrated below that signifies the use of enterprise beans. • • • Applications developed by using the enterprise beans deal with a variety of clients, simply by writing few lines of code, so that the client can locate the enterprise beans. The client locating the enterprise bean may be various, numerous and thin. Enterprise beans support transaction to ensure the integrity of the database. Transaction is the mechanism of managing the concurrent access of shared objects. Managing the fast growing number of users requires distributed application components across multiple machines means that the application must be scalable. Types of enterprise beans: EJB 3.0 defines two types of enterprise beans. These are: 1. Session bean: These types of beans directly interact with the client and contains business logic of the business application. 2. Message driven bean: It works like a listener or a consumer for a particular messaging service such as Java Message API or JPA for short. Features of EJB 3.0 Now its time to look over the new features of EJB 3.0 that provides some simplification over the previous EJB API. There are various simplification made in EJB 3.0 like:
    • • • • • No need of home and object interface. No need of any component interface. Made use of java annotations. Simplifies APIs to make flexible for bean's environment. Now we will discuss all the above aspects of EJB3.0 that makes the EJB programming model simple and more efficient. Elimination of Home and Remote Interfaces: Deprecation of home and remote interfaces simplifies the development. The new session beans contain all the business methods inside the business interface. The bean provider designates the business interface as local business interface or the remote business interface or both according to the client whether it is local or remote. Business methods on remote interface can throw arbitrary application exceptions, while they are not allowed to throw java.rmi.RemoteException. While in case of EJB 2.1 all the methods of home and object interface throws the java.rmi.RemoteException. Package javax.ejb.EJBException encapsulates exceptions such as protocols, system level problems, or otherwise that the container returns to the client. Since EJBException is the subclass of the java.rmi.RemoteException therefore we did not include it in throws clause of business methods. A message driven bean does not need to include the business interface as there is no direct interaction of the client with the message driven bean. Whenever a MDB has an unexpected problem then the container logs the error and communicate it with the help of javax.ejb.EJBException to the corresponding resource adapter rather than the client. Elimination of Component Interface: Component interface in EJB2.1 or in earlier versions are used to provide a way through which the container notifies the bean instances of various life cycles they are affecting it. The previous versions of the component interface are used to stay in the events in its lifecycle. These component interfaces includes the various life cycles methods implemented by the bean class. The container used to call the appropriate method of the component interface to handle the bean's instance life cycle events according to the way it wants. For example, the container notifies the message driven bean instance that it is about to destroy, simply by invoking ejbDestroy() method on the corresponding class of the message driven bean. Bean class can close the JDBC database connection within the ejbDestroy() method to free up the resources. Similarly the container that is going to associate a client in case of stateful notifies the bean instance by calling the ejbCreate() method on the bean class and the bean class instantiates the bean instance. Consider the situation, when the bean does not receive the notification from the container about its life cycle's methods then the bean has to implement the component interfaces regardless whether it is needed or not. In case of session bean, the bean class does not need to implement the javax.ejb.SessionBean or javax.ejb.MessageDrivenBean in case of message driven bean. Now the next question that arises is that how a bean class get notified by the container if it is interested? The solution is that there are two ways to do so, the first one is, the bean provider can implement a separate bean class that consists of all the callback notification methods that inform the container to treat it as a listener class. The second way is that, a bean provider can implement
    • the notification method inside the bean class and designate this method to handle the corresponding events In both the cases bean class uses annotations. Annotations are the additional key features of EJB 3.0 specifications. To know about the annotation just click on the link annotations. Simplified Access to Environment: Almost all the EJBs are required to access the environment to gain access to external resources, enterprise beans and other entries like properties. To get hold of these entries EJB mainly relies on JNDI API. EJB 3.0 also includes the features like lookup method on the EJBContest and dependency injection to access the bean's dependencies. Dependency Injection: Dependency injection is the mechanism through which the container injects the requested environmental entry to make available to the bean instance before any bean instance is invoked on that particular instance. Then the container injects these entries into bean variables or methods. It is bean provider's duty to tell the container that which method or variables should be injected at runtime. The bean provider can do this by using the deployment descriptor or annotations. Bean methods used for dependency injection should follow the java naming convention for properties in that they should follow the setXXX() convention. Consider the situations like dependency injection fails due to some reasons, the container can not make available the environmental entries due to which the bean is functioning properly, in such situations the container discards the bean instances and creates new instances. EJB Context: Bean must know about its environment at runtime such as security principle, transaction context in which its method is invoked and so on. javax.ejb.EJBContext API works like a window for the bean to the outside world through which it is interacting to the container. EJBContext is further categorized into SessionContext and MessageDrivenContext for the session beans and message driven beans respectively. Bean instances may use the dependency injection to access EJBContext instance. Another way through which a JNDI accesses the environment variables is the lookup() method of the EJBContext interface. Bean must use the JNDI API to access the environmental dependencies. Enhanced Lifecycle Methods and Callback Listener Classes: EJB 3.0 does not enforce to implement all unnecessary callback methods but can designate any other method to receive the notification for life cycle events. We can also use the callback listener class instead of callback methods defined in the same bean class. Interceptors: An intercept is a method used to intercept a business method invocation. Stateless session beans, Stateful session beans and message driven beans may includes the interceptors. We can also define an interceptor class instead of defining the interceptor methods in the bean class. Simple JNDI lookup of EJB: Lookup of the EJB has been simplified so that the client can directly invoke methods on EJB rather than creating the bean instance simply by invoking create method on EJB.
    • Annotations Sun Microsystem added the features like annotation to make the development easier and more efficient in jdk 5. The main objective to develop the annotations is to make the development easier. Annotations behaves like the meta. The literal meaning of meta data is data about data. Java also signifies this meaning. Annotations are like meta data, means you are free to add your code and can also apply them to variables, parameters, fields type declarations, methods and constructors. Metadata is also used to create the documentation to perform rudimentary compile time checking and even for tracking down the dependencies in code. XDoclet contains all these features and is widely used. Annotations provide a means of indicating about methods, classes, dependencies, incompleteness and also about the references on other methods and classes respectively. Quoting from Sun's official site, "It (annotation-based development) lets us avoid writing boilerplate code under many circumstances by enabling tools to generate it from annotations in the source code. This leads to a declarative programming style where the programmer says what should be done and tools emit the code to do it." Annotation is the way of associating the program elements with the meta tags so that the compiler can extract program behavior to support the annotated elements to generate interdependent code when necessary. Fundamentals of annotations While going through the annotations you should consider two things. The first one is the "annotation" itself and second one is the "annotations types". An annotation is the meta tag, used to give some life to the code you are using. While annotation type is used to define annotations so that you can use them while creating your own custom annotations. An annotation type definition appends an "at" @ sign at the start of the interface keyword with the annotation name. On the other hand, an annotation includes the "at" @ sign followed by the annotation type. You can also add the data within the parenthesis after the annotation name. Lets illustrate the concept more clearly by using some examples. Defining an annotation (Annotation type) public @interface Example { String showSomething(); } Annotating the code (Annotation) Example (showSomething="Hi! How r you") public void anymethod() {
    • .... } Annotation Types: Three types of annotations types are there in java. Marker: Like the marker interface, marker annotations does not contain any elements except the name itself. The example given below clarifies the concept of marker interface. • Example: public @interface Example{ } Usage: @Example public void anymethod() { -----------} Single-value: This type of elements provide only single value. It means that these can be represented with the data and value pair or we can use the shortcut syntax (just by using the value only within the parenthesis). • Example: public @interface Example{ String showSomething(); } Usage: @Example ("Hi ! How r you") public void anymethod(){ -------} • Multi-value or Full-value: These types of annotations can have multiple data members. Therefore use full value annotations to pass the values to all the data members.
    • Example: public @interface Example{ String showSomething(); int num; String name; } Usage: @Example (showSomething = "Hi! How r you", num=5, name="zulfiqar" ) public void anymethod{ // code here } Rules defining the Annotation type: Here are some rules that one should follow while defining and using annotations types • • • • Start the annotation declaration starting with the symbol "at" @ following the interface keyword that should follow the annotation name. Method declaration should not throw any exception. Method declaration should not contain any parameter. Method using annotations should return a value, one of the types given below: • • • • • String primitive enum Class array of the above types Annotations: JDK 5 (Tiger) contains two types of annotations: • • Simple annotations: These types of annotations are used to annotate the code only. We can not use these types of annotations for creating the custom annotation type. Meta annotations: Also known as annotations of annotations are used to annotate the annotation-type declaration. Simple annotations: JDK 5 includes three types of simple annotations. • • • Override Depricated Suppresswarnings
    • JDK 5 (also known as Tiger) does not include many built-in annotations but it facilitates to core java to support annotation features. Now will discuss in brief each of the above simple annotation types along with examples. Override annotation: The override annotation ensures that the annotated method is used to override the method in the super class. If the method containing this type of annotation does not override the method in the super class then the compiler will generate a compile time error. Lets take an example and demonstrate what will happen if the annotated method does not override the method in the super class. Example 1: public class Override_method{ @Override public String toString(){ return super.toString() + "Will generate an compile time error."; } } Suppose there is spell mistake in the method name such as the name is changed from toString to toStrimg. Then on compiling the code will generate the message like this: Compiling 1 source file to D:tempNew Folder (2) TestJavaApplication1buildclasses D:tempNew Folder (2)TestJavaApplication1srctest myannotationTest_Override.java:24: method does not override a method from its superclass @Override 1 error BUILD FAILED (total time: 0 seconds) Deprecated annotation: These types of annotations ensure that the compiler warns you when you use the deprecated element of the program. The example given below illustrates this concept. Example: Lets first create the class containing the deprecated method. public class Deprecated_method{ @Deprecated public void showSomething() { System.out.println("Method has been depricated'"); } }
    • Now lets try to invoke this method from inside the other class: public class Test_Deprication { public static void main(String arg[]) throws Exception { new Test_Deprication(); } public Test_Deprication() { Deprecated_method d = new Deprecated_method(); d.showSomething(); } The method showSomething() in the above example is declared as the deprecated method. That means we can't further use this method any more. On compiling the class Depricated_method does not generate any error. While compiling the class Test_Deprication generates the message like this: Compiling 1 source file to D:tempNew Folder (2)TestJavaApplication1buildclasses D:tempNew Folder (2)TestJavaApplication1srctestmyannotation Test_Deprication.java:27: warning: [deprecation] showSomething() in test.myannotation.Deprecated_method has been deprecated d.showSomething(); 1 warning The Suppresswarning annotation: These types of annotations ensure that the compiler will shield the warning message in the annotated elements and also in all of its sub-elements. Lets take an example: Suppose you annotate a class to suppress a warning and one of its method to suppress another warning, then both the warning will be suppressed at the method level only. Lets demonstrate it by an example: public class Test_Depricated { public static void main(String arg[]) throws Exception { new TestDepricated().showSomething(); } @SuppressWarnings({"deprecation"}) public void showSomething() { Deprecation_method d = new Deprecation_method(); d.showSomething(); } }
    • This example is suppressing the deprecation warnings that means we can't see the warnings any more. Note: Applying annotation at most deeply nested elements is a good idea. It is better to apply annotations at the method level rather than the class to annotate a particular method. Meta-Annotations (Annotation Types): There are four types ofm Meta annotations (or annotations of annotations) defined by the JDK 5. These are as follows: • • • • Target Retention Documented Inherited Target annotation: Target annotation specifies the elements of a class to which annotation is to be applied. Here is the listing of the elements of the enumerated types as its value: @Target(ElementType.TYPE)—applicable to any element of a class. @Target(ElementType.FIELD)—applicable to field or property. @Target(ElementType.PARAMETER)—applicable to the parameters of a method. • @Target(ElementType.LOCAL_VARIABLE)—applicable to local variables. • @Target(ElementType.METHOD)—applicable to method level annotation. • @Target(ElementType.CONSTRUCTOR)—applicable to constructors. • @Target(ElementType.ANNOTATION_TYPE)—specifies that the declared type itself is an annotation type. • • • Here is an example that demonstrates the target annotation: Example: @Target(ElementType.METHOD) public @interface Test_Element { public String doTestElement(); } Now lets create a class that use the Test_Element annotation: public class Test_Annotations { public static void main(String arg[]) { new Test_Annotations().doTestElement(); } @Test_Target(doTestElement="Hi ! How r you") public void doTestElement() {
    • System.out.printf("Testing Target Element annotation"); } } The @Target(ElementType.METHOD) specifies that this type of annotation can be applied only at method level. Compiling and running the above program will work properly. Lets try to apply this type of annotation to annotate an element: public class Test_Annotations { @Test_Target(doTestElement="Hi! How r you") private String str; public static void main(String arg[]) { new Test_Annotations().doTestElement(); } public void doTestElement() { System.out.printf("Testing Target Element annotation"); } } Here we are trying to apply @Target(ElementType.METHOD) at the field level by declaring the element private String str; after the @Test_Target(doTestElement="Hi ! How r you") statement. On compiling this code will generate an error like this: "Test_Annotations.java": D:R_AND_DTest_Annotationsrctestmyannotation Test_Annotations.java:16: annotation type not applicable to this kind of declaration at line 16, column 0 @Test_Target(doTestElement="Hi ! How r you") ^ Error in javac compilation Retention annotation: These types of annotation specify where and how long annotation with this types are to be retained. There are three type of Retention annotations are of three types. • • • RetentionPolicy.SOURCE: This type of annotation will be retained only at source level and the compiler will ignore them. RetentionPolicy.CLASS: This type of annotation will be retained at the compile time the virtual machine (VM) will ignore them. RetentionPolicy.RUNTIME: Virtual machine will retained the annotation of this type and they can be read only at run-time. Lets demonstrate that how this type of annotations are applied by taking an example using RetentionPolicy.RUNTIME. Example:
    • @Retention(RetentionPolicy.RUNTIME) public @interface Retention_Demo { String doRetentionDemo(); } This example uses the annotation type @Retention(RetentionPolicy.RUNTIME) that indicates the VM will retained your Retention_Demo annotation so that it can be read effectively at runtime. Documented annotation: This type of annotation should be documented by the javadoc tool. javadoc does not include the annotation by default. Include the annotation type information by using @Documented in the generated document. In this type of annotation all the processing is done by javadoc-like tool. The given example demonstrates the use of the @Documented annotations. Example: @Documented public @interface Documented_Demo { String doTestDocumentedDemo(); } Next, make changes in Test_Annotations class as follows: public class Test_Annotations { public static void main(String arg[]) { new Test_Annotations().doTestRetentionDemo(); new Test_Annotations().doTestDocumentedDemo(); } @Retention_Demo (doTestRetentionDemo="Hello retention annotation") public void doTestRetentionDemo() { System.out.printf("Testing 'Retention' annotation"); } @Documented_Demo (doTestDocumentedDemo="Hello Test documentation") public void doTestDocumentedDemo() { System.out.printf("Testing 'Documented' annotation"); } } Inherited Annotation: This annotation is little bit complex. It inherits the annotated class automatically. If you specify @Inherited tag before defining a class then apply the annotation at your class and finally extend the class then the child class inherits the properties of the parent class automatically. Lets demonstrate the benefits of using the @Inherited tag by an example: Example:
    • Lets first, define the annotation: @Inherited public @interface ParentObjectDemo { boolean isInherited() default true; String showSomething() default "Show anything?"; } Now, annotate the class with our annotation: @ParentObjectDemo public Class ChildObjectDemo { } The above example shows that you do not need to define the interface methods inside the implemented class. The @Inherited tag automatically inherits the methods for you. Suppose you define the implementing class in the old-fashioned-java-style then let us see the effect of doing this: public class ChildObjectDemo implements ParentObjectDemo { public boolean isInherited() { return false; } public String showSomething() { return ""; } public boolean equals(Object obj) { return false; } public int hashCode() { return 0; } public String toString() { return ""; } public Class annotationType() { return null; } } Have you seen the difference? You have to implement all the methods of the parent interface. You will have to implement the equals(), toString(), and the hashCode() methods of the Object class and also the annotation type method of the java.lang.annotation.Annotation class. You will also have to include all these methods in your class regardless of whether you are implementing all these methods or not.
    • Session Beans What is a Session bean A session bean is the enterprise bean that directly interact with the user and contains the business logic of the enterprise application. A session bean represents a single client accessing the enterprise application deployed on the server by invoking its method. An application may contain multiple sessions depending upon the number of users accessing to the application. A session bean makes an interactive session only for a single client and shields that client from complexities just by executing the business task on server side. For example, whenever a client wants to perform any of these actions such as making a reservation or validating a credit card, a session bean should be used. The session bean decides what data is to be modified. Typically, the session bean uses an entity bean to access or modify data. They implement business logic, business rules, algorithms, and work flows. Session beans are relatively short-lived components. The EJB container may destroy a session bean if its client times out. A session bean can neither be shared nor can persist (means its value can not be saved to the database) its value. A session bean can have only one client. As long as the client terminates, session bean associated with this client is also terminated and the data associated with this bean is also destroyed.
    • The above figure shows how Session Bean interacts with the clients as well as with the Entity Beans. Session beans are divided into two parts. • • Stateless Session Beans: A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the instance of bean variables may contain a state specific to that client only for the duration of a method invocation. Once the method is finished, the client-specific state should not be retained i.e. the EJB container destroys a stateless session bean. These types of session beans do not use the class variables (instance variables). So they do not persist data across method invocation and therefore there is no need to passivates the bean's instance. Because stateless session beans can support multiple clients, they provide the better scalability for applications that require large numbers of clients. Stateful Session Beans: These types of beans use the instance variables that allows the data persistent across method invocation because the instance variables allow persistence of data across method invocation. The client sets the data to these variables which he wants to persist. A stateful session bean retains its state across multiple method invocations made by the same client. If the stateful session bean's state is changed during a method invocation, then that state will be available to the same client on the following invocation. The state of a client bean is retained for the duration of the client-bean session. Once the client removes the bean or
    • terminates, the session ends and the state disappears. Because the client interacts with its bean, this state is often called the conversational state. For example, consider a customer using a debit card at an ATM machine. The ATM could perform various operations like checking an account balance, transferring funds, or making a withdrawal. These operations could be performed one by one, by the same customer. So the bean needs to keep track its state for each of these operations to the same client. Thus Stateful session beans has the extra overhead for the server to maintain the state than the stateless session bean. The user interface calls methods of session beans if the user wants to use the functionality of the session bean. Session beans can call to other session beans and entity beans. When to use session beans: Generally session beans are used in the following circumstances: • • • When there is only one client is accessing the beans instance at a given time. When the bean is not persistent that means the bean is going to exist no longer. The bean is implementing the web services. Stateful session beans are useful in the following circumstances: • • • What the bean wants to holds information about the client across method invocation. When the bean works as the mediator between the client and the other component of the application. When the bean have to manage the work flow of several other enterprise beans. Stateless session beans are appropriate in the circumstances illustrated below: • • If the bean does not contain the data for a specific client. If there is only one method invocation among all the clients to perform the generic task. Life Cycle of a Stateless Session Bean: Since the Stateless session bean does not passivates across method calls therefore a stateless session bean includes only two stages. Whether it does not exist or ready for method invocation. A stateless session bean starts its life cycle when the client first obtains the reference of the session bean. For this, the container performs the dependency injection before invoking the annotated @PreConstruct method if any exists. After invoking the annotated @PreConstruct method the bean will be ready to invoke its method by the client.
    • The above figure demonstrates how the Stateless Session Beans are created and destroyed. The container calls the annotated @PreDestroy method while ending the life cycle of the session bean. After this, the bean is ready for garbage collection. Life Cycle of a Stateful Session Bean: A Stateful session bean starts its life cycle when the client first gets the reference of a stateful session bean. Before invoking the method annotated @PostConstruct the container performs any dependency injection after this the bean is ready. The container may deactivate a bean while in ready state (Generally the container uses the least recently use algorithm to passivates a bean). In the passivate mechanism the bean moves from memory to secondary memory. The container invokes the annotated @PrePassivate method before passivating the bean. If a client invokes a business method on the passivated bean then the container invokes the annotated @PostActivate method to let come the bean in the ready state.
    • The above image shows the various states of the Stateful Session Beans While ending the life cycle of the bean, the client calls the annotated @Remove method after this the container calls the annotated @PreDestroy method which results in the bean to be ready for the garbage collection Stateless Session Bean Example In this part of Enterprise Session Beans, you will learn how to develop, deploy, and run a simple Java EE application named example using stateless session bean. The purpose of example is to performs the mathematical operations such as Addition, Subtraction, Multiplication, and Division. The example application consists of an enterprise bean, which performs the calculations, and two types of clients: an application client and a web client. There are following steps that you have to follow to develop a example JEE application. 1. 2. 3. 4. Create the enterprise bean: CalculatorBean Create the web client: WebClient Deploy example onto the server. Using a browser, run the web client. I. Creating the enterprise bean: The enterprise bean in our example is a stateless session bean called CalculatorBean. The source code for CalculatorBean is in “net/roseindia/ejb3/stateless” directory. Creating CalculatorBean requires these steps: (i) Coding the bean’s Remote business interface and Enterprise bean class. (ii) Compiling the source code with the Ant tool. (i) Coding the Business Interface The business interface defines the business methods that a client can call remotely. The business methods are implemented in the enterprise bean class. The source code for the CalculatorRemote business interface is given below.
    • package net.roseindia.ejb3.stateless; import java.math.*; import javax.ejb.Remote; import java.lang.annotation.*; @Remote public interface CalculatorRemote { public float add(float x, float y); public float subtract(float x, float y); public float multiply(float x, float y); public float division(float x, float y); } Note that, the @Remote annotation decorating the interface definition. This lets the container know that CalculatorBean will be accessed by remote clients. II. Coding the Enterprise Bean Class The enterprise bean class for this example is called CalculatorBean. This class implements the four business methods (add, subtract, multiply, division) that are defined in the CalculatorRemote business interface. The source code for the CalculatorBean class is given below. package net.roseindia.ejb3.stateless; import java.math.*; import javax.ejb.Stateless; import javax.ejb.Remote; @Stateless(name="CalculatorBean") @Remote(CalculatorRemote.class) public class CalculatorBean implements CalculatorRemote{ public float add(float x, float y){ return x + y; } public float subtract(float x, float y){ return x - y; } public float multiply(float x, float y){ return x * y; } public float division(float x, float y){ return x / y; } }
    • Note that, the @Stateless annotation decorating the enterprise bean class. This lets the container know that CalculatorBean is a stateless session bean. Compiling and Packaging the example Example Now you are ready to compile the remote business interface (CalculatorRemote.java), the enterprise bean class (CalculatorBean.java) and the application client (CalculatorClient.java), then package the compiled classes into an enterprise bean JAR. II. Creating the calculator Web Client The web client is contained in the JSP page "WebClient.jsp". A JSP page is a text-based document that contains JSP elements, which construct dynamic content, and static template data, expressed in any text-based format such as HTML, WML, and XML. The source code for the “form.jsp” is given below. <html> <head> <title>Calculator</title> </head> <body bgcolor="pink"> <h1>Calculator</h1> <hr> <form action="WebClient.jsp" method="POST"> <p>Enter first value: <input type="text" name="num1" size="25"></p> <br> <p>Enter second value: <input type="text" name="num2" size="25"></p> <br> <b>Seclect your choice:</b><br> <input type="radio" name="group1" value ="add">Addition<br> <input type="radio" name="group1" value ="sub">Subtraction<br> <input type="radio" name="group1" value ="multi">Multiplication<br> <input type="radio" name="group1" value ="div">Division<br> <p>
    • <input type="submit" value="Submit"> <input type="reset" value="Reset"></p> </form> </body> </html> The following statements given below in “WebClient.jsp” are used for locating the business interface, creating an enterprise bean instance, and invoking a business method. InitialContext ic = new InitialContext(); CalculatorRemote calculator = (CalculatorRemote)ic.lookup("example/CalculatorBea n/remote"); The classes needed by the client are declared using a JSP page directive (enclosed within the <%@ %> characters). Because locating the business interface and creating the enterprise bean are performed only once, this code appears in a JSP declaration (enclosed within the <%! %> characters) that contains the initialization method, jspInit, of the JSP page. A scriptlet (enclosed within the <% %> characters) retrieves the parameters from the request and converts it to a Float object. Finally, a JSP scriptlet invokes the enterprise bean’s business methods, and JSP expressions (enclosed within the <%= %> characters) insert the results into the stream of data returned to the client. The full source code for the WebClient program is given below. <%@ page contentType="text/html; charset=UTF-8" %> <%@ page import="com.javajazzup.examples.ejb3.stateless.*, javax.naming.*"%> <%! private CalculatorRemote calculator = null; float result=0; public void jspInit() { try { InitialContext ic = new InitialContext(); calculator = (CalculatorRemote) ic.lookup("example/CalculatorBean/remot e"); System.out.println("Loaded Calculator Bean"); //CalculatorBean
    • } catch (Exception ex) { System.out.println("Error:"+ ex.getMessage()); } } public void jspDestroy() { calculator = null; } %> <% try { String s1 = request.getParameter("num1"); String s2 = request.getParameter("num2"); String s3 = request.getParameter("group1"); System.out.println(s3); if ( s1 != null && s2 != null ) { Float num1 = new Float(s1); Float num2 = new Float(s2); if(s3.equals("add")) result=calculator.add(num1.floatValue(),num2.floatValue()); else if(s3.equals("sub")) result=calculator.subtract(num1.floatValue(),num2.floatValue()); else if(s3.equals("multi")) result=calculator.multiply(num1.floatValue(),num2.floatValue()); else result=calculator.division(num1.floatValue(),num2.floatValue()); %> <p> <b>The result is:</b> <%= result %> <p> <% } }// end of try catch (Exception e) { e.printStackTrace (); //result = "Not valid"; } %> Note: The Application Server automatically compiles web clients that are JSP pages. If the web client were a servlet, you would have to compile it. The source code for the “index.jsp” is given below that will actual call the client-design form.
    • <%@page language="java" %> <html> <head> <title>Ejb3 Stateless Tutorial</title> </head> <body bgcolor="#FFFFCC"> <p align="center"><font size="6" color="#800000"><b>Welcome to <br> Ejb3-Jboss 4.2.0 Tutorial</b></font> Click <a href="ejb3/form.jsp">Calculator Example</a> to execute Calculator<br></p> </body> </html> III. Deploy example onto the server To deploy the created example application we are going to use Jboss 4.2.0 Application Server about which you have read in the previous section of this Javajazzup issue. So you first need to download the following tools to deploy this application. • JDK 1.5 or Higher • apache-ant-1.7.0 • JBoss 4.2.0 Do the following steps to deploy the example application: (i) Make a directory structure. You can Click here to extract the readymade directory structure according to this tutorial. (ii) Create the essential deployment descriptor .xml files. build.xml <?xml version="1.0"?> <project name="Jboss Tutorials" default="all" basedir="."> <target name="init"> <!-- Define --> <property name="dirs.base" value="${basedir}"/> <property name="classdir" value="$ {dirs.base}/build/classes"/>
    • <property name="src" value="${dirs.base}/src"/> <property name="web" value="${dirs.base}/web"/> <property name="deploymentdescription" value="$ {dirs.base}/deploymentdescriptors"/> <property name="warFile" value="example.war"/> <property name="earFile" value="example.ear"/> <property name="jarFile" value="example.jar"/> <property name="earDir" value="$ {dirs.base}/build/ear"/> <property name="warDir" value="${dirs.base}/build/war"/> <property name="jarDir" value="${dirs.base}/build/jar"/> <!-- classpath for Project --> <path id="library.classpath"> <pathelement path ="libext/servletapi.jar"/> <pathelement path ="libext/ejb3persistence.jar"/> {classpath}"/> <pathelement path ="libext/javaee.jar"/> <pathelement path ="$ </path> <!-- Create Web-inf and classes directories --> <mkdir dir="${warDir}/WEB-INF"/> <mkdir dir="${warDir}/WEB-INF/classes"/> <!-- Create Meta-inf and classes directories --> <mkdir dir="${earDir}/META-INF"/> <mkdir dir="${jarDir}/META-INF"/> <mkdir dir="${classdir}"/> </target> <!-- Main target --> <target name="all" depends="init,build,buildWar,buildJar,buildEar"/> <!-- Compile Java Files and store in /build/src directory --> <target name="build" > <javac srcdir="${src}" destdir="${classdir}" debug="true" includes="**/*.java" > <classpath refid="library.classpath"/> </javac> </target>
    • <!-- Create the web archive File --> <target name="buildWar" depends="init"> <copy todir="${warDir}/WEB-INF/classes"> <fileset dir="${classdir}" includes="**/*.class" /> </copy> <copy todir="${warDir}/WEB-INF"> <fileset dir="${deploymentdescription}/web/" includes="web.xml" /> </copy> <copy todir="${warDir}"> <fileset dir="${web}" includes="**/*.*" /> </copy> <!-- Create war file and place in ear directory --> <jar jarfile="${earDir}/${warFile}" basedir="${warDir}" /> </target> <!-- Create the jar File --> <target name="buildJar" depends="init"> <copy todir="${jarDir}"> <fileset dir="${classdir}" includes="**/*.class" /> </copy> <copy todir="${jarDir}/META-INF"> <fileset dir="${deploymentdescription}/jar/" includes="ejb-jar.xml,weblogic-cmp-rdbms-jar.xml,weblogicejb-jar.xml" /> </copy> <!-- Create jar file and place in ear directory --> <jar jarfile="${earDir}/${jarFile}" basedir="${jarDir}" /> </target> <!-- Create the ear File --> <target name="buildEar" depends="init"> <copy todir="${earDir}/META-INF"> <fileset dir="${deploymentdescription}/ear" includes="application.xml" /> </copy> <!-- Create ear file and place in ear directory -->
    • <jar jarfile="../${earFile}" basedir="${earDir}" /> <copy todir="C:/jboss-4.2.0.GA/server/default/deploy/"> <fileset dir="../" includes="${earFile}" /> </copy> </target> </project> Put this file in the base (statelesscode)directory. Application.xml <?xml version="1.0" encoding="UTF-8"?> <application xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd"> <display-name>Stateless Session Bean Example</display-name> <module> <web> <web-uri>example.war</web-uri> <context-root>/example</context-root> </web> </module> <module> <ejb>example.jar</ejb> </module> </application> Put this file in the Statelesscodedeploymentdescriptorsear directory. web.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/webapp_2_3.dtd"> <web-app > </web-app>
    • Put this file in the Statelesscodedeploymentdescriptorsweb directory. Put all .jsp files in the Statelesscodeweb directory. Put all .java files in the Statelesscodesrc directory. (iii) Start command prompt, and go to the Statelesscode directory. Then type the command as: C:Statelesscode>ant build.xml The Ant tool will deploy the example.ear file to the jboss-4.2.0.GAserverdefaultdeploy directory. V. Running the example Web Client Open the web browser and type the following URL to run the application: http://localhost:8080/example Click at the given link as Calculator Example:
    • Give values to the textbox and choose the desire option button as Addition then clicks the Submit button to get the result. The result is: 9.0 Stateful Session Bean Example
    • In this part of Enterprise Session Beans, you will learn how to develop, deploy, and run a simple Java EE application named account using stateful session bean. The purpose of account is to performs two transaction operations (deposit and withdraw) for the customer. The account application consists of an enterprise bean, which performs the transactions, and two types of clients: an application client and a web client. here are following steps that you have to follow to develop a account JEE application. 1. 2. 3. 4. Create the enterprise bean: AccountBean Create the application client: AccountCustomer Deploy account onto the server. Run the application client. I. Creating the enterprise bean: The enterprise bean in our example is a statelful session bean called AccountBean. The account session bean represents an account information in an online customer account. The bean’s customer can deposit to or withdraw the amount from his account. To manage account, you need the following code: • • Remote business interface (Account) Session bean class (AccountBean) The Business Interface: The Account business interface is a plain Java interface that defines all the business methods implemented in the bean class. If the bean class implements a single interface, that interface is assumed to the business interface. The business interface is a local interface unless it is annotated with the javax.ejb.Remote annotation. The bean class may also implement more than one interface. If the bean class implements more than one interface, the business interfaces must be specified by decorating the bean class with @Local or @Remote. The source code for the Account business interface is given below. package ejbExample.stateful; import javax.ejb.Remote; @Remote public interface Account { public float deposit(float amount); public float withdraw(float amount); @Remove public void remove();
    • } Coding the Session Bean Class: The session bean class for this example is called AccountBean. This class implements the two business methods (deposit and withdraw). The AccountBean class must meet these requirements: The class is annotated @Stateful. The class implements the business methods defined in the business interface. • • The source code for the AccountBean class is given below. package ejbExample.stateful; import import import import javax.ejb.Stateful; javax.ejb.Remote; javax.ejb.Remove; javax.ejb.*; @Stateful(name="AccountBean") @Remote(AccountRemote.class) public class AccountBean implements AccountRemote { float balance = 0; public float deposit(float amount){ balance += amount; return balance; } public float withdraw(float amount){ balance -= amount; return balance; } @Remove public void remove() { balance = 0; } } The Remove Method Business methods annotated with javax.ejb.Remove in the stateful session bean class can be invoked by enterprise bean client to remove the bean instance. The container will remove the enterprise bean after a @Remove method completes, either normally or abnormally. Thus, we can retain the bean's state invoked by the client until we call the annotated @Remove method.
    • In AccountBean , the remove method is a @Remove method shown as: @Remove public void remove() { balance = 0; } Stateful session beans also may: • • Implement any optional life cycle callback methods, annotated @PostConstruct, @PreDestroy, @PostActivate, and @PrePassivate. Implement optional business method annotated @Remote. Life-Cycle Callback Methods: Methods in the bean class may be declared as a life-cycle callback method by annotating the method with the following annotations: • • • • javax.annotation.PostConstruct javax.annotation.PreDestroy javax.ejb.PostActivate javax.ejb.PrePassivate Life-cycle callback methods must return void and have no parameters. Lets understands these callback annotated methods shown in the table given below: Stateful Session Bean Example In this part of Enterprise Session Beans, you will learn how to develop, deploy, and run a simple Java EE application named account using stateful session bean. The purpose of account is to performs two transaction operations (deposit and withdraw) for the customer. The account application consists of an enterprise bean, which performs the transactions, and two types of clients: an application client and a web client. here are following steps that you have to follow to develop a account JEE application. 1. 2. 3. 4. Create the enterprise bean: AccountBean Create the application client: AccountCustomer Deploy account onto the server. Run the application client.
    • I. Creating the enterprise bean: The enterprise bean in our example is a statelful session bean called AccountBean. The account session bean represents an account information in an online customer account. The bean’s customer can deposit to or withdraw the amount from his account. To manage account, you need the following code: • • Remote business interface (Account) Session bean class (AccountBean) The Business Interface: The Account business interface is a plain Java interface that defines all the business methods implemented in the bean class. If the bean class implements a single interface, that interface is assumed to the business interface. The business interface is a local interface unless it is annotated with the javax.ejb.Remote annotation. The bean class may also implement more than one interface. If the bean class implements more than one interface, the business interfaces must be specified by decorating the bean class with @Local or @Remote. The source code for the Account business interface is given below. package ejbExample.stateful; import javax.ejb.Remote; @Remote public interface Account { public float deposit(float amount); public float withdraw(float amount); @Remove public void remove(); } Coding the Session Bean Class: The session bean class for this example is called AccountBean. This class implements the two business methods (deposit and withdraw). The AccountBean class must meet these requirements: • • The class is annotated @Stateful. The class implements the business methods defined in the business interface.
    • The source code for the AccountBean class is given below. package ejbExample.stateful; import import import import javax.ejb.Stateful; javax.ejb.Remote; javax.ejb.Remove; javax.ejb.*; @Stateful(name="AccountBean") @Remote(AccountRemote.class) public class AccountBean implements AccountRemote { float balance = 0; public float deposit(float amount){ balance += amount; return balance; } public float withdraw(float amount){ balance -= amount; return balance; } @Remove public void remove() { balance = 0; } } The Remove Method Business methods annotated with javax.ejb.Remove in the stateful session bean class can be invoked by enterprise bean client to remove the bean instance. The container will remove the enterprise bean after a @Remove method completes, either normally or abnormally. Thus, we can retain the bean's state invoked by the client until we call the annotated @Remove method. In AccountBean , the remove method is a @Remove method shown as: @Remove public void remove() { balance = 0; } Stateful session beans also may: • Implement any optional life cycle callback methods, annotated @PostConstruct,
    • • @PreDestroy, @PostActivate, and @PrePassivate. Implement optional business method annotated @Remote. Life-Cycle Callback Methods: Methods in the bean class may be declared as a life-cycle callback method by annotating the method with the following annotations: • • • • javax.annotation.PostConstruct javax.annotation.PreDestroy javax.ejb.PostActivate javax.ejb.PrePassivate Life-cycle callback methods must return void and have no parameters. Lets understands these callback annotated methods shown in the table given below: Method Description Invoked by the container on newly constructed bean instances before the first @PostConstr business method is invoked on the enterprise uct bean and after all dependency injection has completed. Invoked, when the bean is about to be destoryed by EJB container before removing @PreDestroy the enterprise bean instance and after any method annotated @Remove has completed. Invoked by the container after the container @PostActivat moves the bean from secondary storage to e active status. Invoked by the container before the container passivates the enterprise bean, i.e. the @PrePassiva container temporarily removes the bean from te the environment and saves it to secondary storage. II. Coding the account Web Client The application client source code is in the WebClient.jsp file That illustrates the basic tasks performed by the client of an enterprise bean:
    • Creating an enterprise bean instance Invoking a business method • • The full source code for the WebClient.jsp program is given below. <%@page language="java" %> <%@ page contentType="text/html; charset=UTF-8" %> <%@ page import="com.javajazzup.examples.ejb3.stateful.*, javax.naming.*"%> <%! public AccountRemote account = null; float bal=0; public void jspInit() { try { InitialContext ic = new InitialContext(); account = (AccountRemote) ic.lookup("example/AccountBean/remote"); System.out.println("Loaded Account Bean"); } catch (Exception ex) { System.out.println("Error:"+ ex.getMessage()); } } public void jspDestroy() { account = null; } %> <% try { String s1 = request.getParameter("amt"); String s2 = request.getParameter("group1"); if ( s1 != null) { Float amt = new Float(s1); if(s2.equals("dep")) bal=account.deposit(amt.floatValue()); else if(s2.equals("with")) bal=account.withdraw(amt.floatValue()); else %> <p>Please select your choice</p> <%
    • } else %> <br>Please enter the amount<br> <p> The Transaction is complete<br> <b>Your Current Balance is:</b> <%= bal%> <p> <% }// end of try catch (Exception e) { e.printStackTrace (); } %> The source code for the “form.jsp” is given below. <html> <head> <title>Bank Account</title> </head> <body> <h1><p align="center"><font size="6" color="#800000">Bank Transaction Request Form</h1> <hr><br> <table bgcolor="#FFFFCC" align="center"> <form action="WebClient.jsp" method="POST"> <tr><td></tr></td> <tr><td>Enter the amount in rupees: <input type="text" name="amt" size="10"></tr></td> <br> <tr><td><b>Select your choice:</b></tr></td> <tr><td><input type="radio" name="group1" value ="dep">Deposit</tr></td> <tr><td><input type="radio" name="group1" value ="with">Withdraw<br></tr></td> <tr><td> <input type="submit" value="Transmit"> <input type="reset" value="Reset"></tr></td>
    • <tr><td></tr></td> </form> </table> </body> </html> The source code for the “index.jsp” is given below that will actual call the client-design form. <%@page language="java" %> <html> <head> <title>Ejb3 Stateful Tutorial</title> </head> <body bgcolor="#FFFFCC"> <p align="center"><font size="6" color="#800000"><b>Welcome to <br> Ejb3-Jboss 4.2.0 Tutorial</b></font> Click <a href="ejb3/form.jsp">Bank Transaction Example</a> to execute Bank Bean<br></p> </body> </html> III. Deploy account onto the server IV. Running the account Application Client Message Driven Beans
    • Message driven beans are the light weight components used for communication. In message driven beans the messaging service is in asynchronous mode because the user is not intended to get the instant result. To understand the concept of message driven beans more clearly first we should go through the various concepts illustrated given below: • • • • Techniques to implement messaging, message-oriented-middleware (MOM) and the asynchronous behavior. Utilization of JMS, message-oriented-middleware to implement JMS based messagedriven-beans. Features and comparison of message-driven-beans with entity and session beans. Techniques to develop message driven beans, including advanced topics like gotchas and possible actions. Motivations for messaging: EJB components are used to develop the applications for the distributed computing network . Distributed computing network uses the RMI-IIOP protocol to communicate with each other. This protocol is used to call the EJB components. RMI-IIOP accepts challenges in several areas like: • Asynchrony: A typical RMI-IIOP client has to wait until the server completes its processing and returns the result to the client. After that the server enables to the client to continue its processing. • • • Decoupling: An RMI-IIOP server must have the knowledge about the server that it want to use. The client can address them directly through object references. It is not possible to remove a server from the server without directly impacting the clients because the client and server are closely coupled with each other. Reliability: Data may be lost or the client can't perform any operation if the server or the network crashes. Support for multiple senders and receivers: You can use messaging server instead of remote method invocation (RMI) but the messaging service uses the middleman between the client and the server. This middleman simply receives the messages from one or more senders and sends these messages to one or more consumers. It is not required to get the response instantly from the receiver. The receiver may sends back response back to the sender after completing all the processing. This is known as asynchronous programming. There are four previous concerns that the messaging addresses with RMI-IIOP as follows: Non blocking request processing: There is no need to block the messaging request while executing another request. For example suppose you are purchasing a book from Amazon.com having a single click functionality. you are enable to continue browsing the site without waiting to check the authorization of your credit card. Until and unless there is something wrong Amazon.com sends you a confirmation email. These types of systems are developed by using the messaging technique.
    • Decoupling: In case of message-oriented-middleware, it is not necessary for the sender to have the knowledge about the message receiver. It only interacts with the messaging system while sending messages. Thus the message senders are decoupled from consumers. Reliability: Your message-oriented-middleware guarantees to send a message to its destination if the receiver is not temporarily available, simply by sending the message to the messageoriented-middleware which sends the message to the receiver when he is available. While it is not possible with RMI-IIOP protocol because there is no middleman in this case. If you send a message using the RMI-IIOP protocol and if server is down then it throws the exception. Support for multiple senders and receivers: Most of the message-oriented-middleware supports this features i.e. receiving messages from multiple senders and can also broadcast them to many receivers. Message-oriented-middleware is the term that can be given to any system that supports the messaging system. There are a number of products based on MOM architecture. BEA Tuxedo/Q, Sun Java System Messaging Server, IBM WebSphere MQ, Tibco Rendezevous, Microsoft MSMQ, FioranoMQ and Sonic Software SonicMQ are the examples of MOM based architecture. Java Message Services (JMS): JMS API is an enterprise tool developed by Sun Microsystems used to develop the enterprise applications. JMS API supports to a framework that allows the development of portable and message based applications. JMS communicates in synchronous or in asynchronous mode by using point-to-point and the publish-subscribe models respectively. JMS has become vendor specific and many vendors such as IBM, Oracle, Hewlett-Packard, BEA Systems and Macromedia are providing the JMS implementation. JMS API: JMS APIs play an important role as comparing the RMI-IIOP protocol. You need to aware with different interfaces, low level topology issues like structure, messaging format, networking protocol and server location.
    • 1. Locate the JMS provider's ConnectionFactory instance: First establish the 2. 3. 4. 5. 6. connection by using a ConnectionFactory instance to get access the JMS provider of the MOM product you are using. An administrator typically creates and configures the ConnectionFactory for the JMS client's use. Create a JMS connection: A JMS connection manages the low level network communications similar to JDBC connection. Use ConnectionFactory to get a connection. For large deployment this connection may be load balance across a group of machines. Create a JMS session: A JMS session object is used to send and receive the messages and works as the ConnectionFactory for message producers and message consumers. It also allows the encapsulation of messages in transactions. We use Connection to get the session object. Locate the JMS Destination: A JMS destination is an object to which we are sending or from which we are receiving the messages. Locating the right destination is similar to tuning the channel in the right direction to get the clear picture while watching the television or answering the correct phone to get the desired message. Create a JMS producer or a JMS consumer: If you are interested to send a message then you need an object to pass your message. This object is known as the JMS producer. If you want to receive a message you need to call a JMS object. This object is known as the Consumer object. To get hold an object Session and Destination are used. Send or Receive a message: There may be different types of messages like text, streams, maps, bytes, objects and so on. To send a messages first instantiate it and then send it by using the Producer object. If you are intended to receive a message then first receive the message with the help of Consumer object and then crack it to see what it contains.
    • All the points described above are applicable to both point-to-point as well as publish/subscribe. Here we are going to discuss JMS by taking the queuing system. Queuing system includes the following parts: • • • • JMS Server: The JMS server maintains the message queue to receive emails. JMS Queue: In case of point-to-point messaging system, a queue is used to hold the messages from clients. Messages holding this queue are of MapMessages type that stores the information about the email as name/value pair. Email Message Client: A client of this messaging system creates the JMS message to put it on the JMS Queue. This message contains the information about the message to be sent out. Email Message Driven Bean: It is the message driven bean that is responsible to take the JMS MapMessage to mail it out. JMS Architecture: Talk first about JMS while talking about the message driven beans. There are a lot of messaging systems exist in the market. Messaging systems provide a mechanism to exchange data and events asynchronously. JMS API defines a standard way to access any messaging system such as JDBC that enables the user to talk to SQL Server, Oracle and Sybase simply by using the same API. The additional benefits of JMS API are loose coupling between the generated request and the code that services the request. Here are some of the basics of the messaging server that one should know to more clearly understand the concept of JMS APIs: • • Messaging Domains JMS Messages Messaging Domains: A messaging system includes several models of operation. JMS API provides separate domains corresponding to different models. JMS provider is free to implement one or more domains. Point-to-Point and Publish/Subscribe are the two most commonly used domains. These two domains concludes the following concepts. • • • Producer: The client, responsible for sending the message to the destination is known as the producer. Consumer: The client, responsible for receiving the message is known as the consumer. Destination: Destination is the object used by the client to specify the target that uses it to send the message to or to receive the message from. Point-to-Point (PTP): An application that uses the point-to-point technique for messaging has the following characteristics. • • • • A PTP producer is the sender. A PTP consumer is the receiver. PTP uses a queue as the destination. A receiver can consume only a single message.
    • A call center application is the example of a PTP domain, where a phone call enters in the queue therefore only one operator takes care of this call rather than all of the operators. Publish/Subscribe (pub/sub): An application that uses the pub/sub technique must include the following characteristics. • • • • A pub/sub producer is the publisher A pub/sub consumer is the subscriber pub/sub uses the topic as the destination. A message can have the multiple consumer. An email newsletter application may use the pub/sub model, where an interested candidate may become the subscriber to receive a new published message. Integrating JMS with EJB: Integration of JMS with EJB is the excellent idea because of it the EJB components gets benefit from the value proposed by messaging like multinary communications and non blocking clients. The idea behind the introduction of new type of bean is to consume messages in an EJB application. Use a Java Object that receives the JMS messages to call an EJB client: Instead of developing the whole new bean the java community proposed an idea of object to receive a message and to call the appropriate EJB component such as the session bean or the entity bean. But the problems that come with this approach are: • • • • • You have to implement the multithreading concept just to increase the message consumption so that you can listen the messages in multiple threads. However developing the multithreaded application is not a tuff task for the developer. Register yourself as a listener by writing the special code for JMS messages. Hard code the JMS destination name in your java object that access the destination information required for extra effort to access the destination information from the dish like property files. JMS message listener receives services from the EJB container just like a plain java object such as clustering, pooling, transaction, automatic life cycle management and many more. You need to hard code this yourself that is a tuff task and error prone. Your java object is wrapped by other EJB components therefore it requires some way to start up. If the class is running inside the container then you are required to use a server specific startup class for the activation of the java object when the EJB server starts. This is not portable as the EJB container does not define an standard way to activate the given logic. Reuse an existing type of EJB component somehow to receive JMS messages: Session beans or entity beans may receive messages but the problem with this approach is: • Life-cycle-management: The container doesn't know the way of creating a bean when a JMS message arrives.
    • • Threading: EJB does not allow multithreading when a message arrives to the bean that is processing other request. If a bean is processing a request it does not take the new message arrive to the bean. Message driven bean: Message driven beans are the special type of components that can receive the JMS as well as other type of messages. Message driven bean can also be used to receive the messages other than JMS. When a message is reached at the destination then the EJB container invokes the message driven bean. A message driven bean is decoupled with the client that sends the message. A client is not allowed to access the message driven bean through a business interface. The client can interact with the message driven bean only through the messaging system. To interact with the message driven bean use the message provider specific API such as JMS. A Message-Driven Bean Example Introduction Session beans allow you to send JMS messages and to receive them synchronously, but not asynchronously. To receive messages asynchronously, a Message-driven bean is used. Message driven beans are the light weight components used for communication via messages (e.g., email or IM messages). In message driven beans, the messaging service is in asynchronous mode because the user is not intended to get the instant result. Message-driven beans can implement any messaging type. Most commonly, they implement the Java Message Service (JMS) technology. Message-driven beans have the following characteristics: • • • • • • • A message-driven bean’s instances retain no data or conversational state for a specific client i.e. they are stateless. A single message-driven bean can process messages from multiple clients. They are invoked asynchronously. They can be transaction-aware. They do not represent directly shared data in the database, but they can access and update this data. A message-driven bean has only a bean class i.e. unlike a session bean, the clients don't access message-driven beans through interfaces. They don't have the remote or local interfaces that define client access. The given diagram shows the working process of a Message driven bean.
    • In Message driven beans (MDB), the client components don't locate message-driven beans and invoke methods directly. Instead, The JMS clients send messages to message queues managed by the JMS server (e.g., an email inbox can be a message queue) for which the javax.jms.MessageListener interface is implemented. The message queue is monitored by a special kind of EJB(s) - Message Driven Beans (MDBs) That processes the incoming messages and perform the services requested by the message. The MDBs are the end-point for JMS service request messages. You assign a message-driven bean’s destination during deployment by using Application Server resources. JMS: The Java Message Service (JMS) is an API for Java messaging clients. JMS provides two programming models: point-to-point and publish-and-subscribe. In the point-to-point model, one sender puts a message on a queue that is delivered to only one receiver. The publish-and-subscribe model adds a broadcast mode in which any number of senders can add messages to a topic, and any number of recievers receive all messages posted to topics. JMS queues and topics are bound in the JNDI environment and made available to J2EE applications. Example: Our application assumes the point-to-point model, and requires setting up a queue with a QueueConnectionFactory in JMS. This section shows, how to implement an MDB with EJB 3.0 describing the source code of a simple message-driven bean application. In this example, we are going to implement a Message-driven bean application named "massage" that has the following components:
    • A client application that sends several messages to a queue: MessageClient A message-driven bean that asynchronously receives and processes the messages that are sent to the queue: MessageBean • • Code for the client application: package mdb; import import import import javax.jms.*; javax.naming.*; java.text.*; javax.annotation.*; @Resource(mappedName="jms/Queue") class MessageConn{ private static Queue queue = null; QueueConnectionFactory factory = null; QueueConnection connection = null; QueueSender sender = null; QueueSession session = null; public MessageConn(){ try { //client creates the connection, session, and message sender: connection = factory.createQueueConnection(); session = connection.createQueueSession(false, QueueSession.AUTO_ACKNOW LEDGE); sender = session.createSender(queue); //create and set a message to send TextMessage msg = session.createTextMessage(); for (int i = 0; i < 5; i++) { msg.setText("This is my sent message " + (i + 1)); //finally client sends messages asynchronously to the queue sender.send(msg); } System.out.println("Sending message"); session.close (); } catch (Exception e) { e.printStackTrace (); } } } public class MessageClient{ public static void main(String[] args){ MessageConn msgcon = new MessageConn(); } } Description of the given code:
    • In the given code of MessageClient application, the javax.jms.* package is imported for extending the Queue, QueueConnectionFactory, QueueConnection, QueueSender, and QueueSession class. After you get the QueueConnectionFactory object, you use its createQueueConnection to construct a QueueConnection object, like this: connection = factory.createQueueConnection( ); Then, you use the createQueueSession method of the QueueConnection interface to create a QueueSession object, as in the following code: session = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); Note that you pass false as the first argument to the createQueueSession method to indicate that you are not creating a transactional session object. Next, you can call the createSender method of the QueueSession interface, passing a Queue object. The return value of this method is a message producer, which is a QueueSender: sender = session.createSender(queue); Then you create a TextMessage object based on the message received by passing the text for the TextMessage to the createTextMessage method of the QueueSession object and then set the text to the object of TextMessage TextMessage msg = session.createTextMessage( ); msg.setText("This is my sent message " + (i + 1)); Now, you are ready to send the new message. You do this by calling the send method of the QueueSender object, as you see here: sender.send(msg); The JMS resource is mapped to the JNDI name of the destination from which the bean receives messages. The New Message-Driven Bean wizard has already created the JMS resources for us. The EJB 3.0 API enables us to look up objects in the JNDI namespace from within the bean class so that we do not need to configure deployment descriptors to specify the JMS resources. The EJB 3.0 specifications allow us to use annotations to introduce resources directly into a class. The MDB's connection process can be seen in the figure shown below:
    • avax.annotation.Resource(@Resource): The @Resource method specifies a dependence on an external resource, such as a JDBC data source or a JMS destination or connection factory. If you specify the annotation on a field or method, the EJB container injects an instance of the requested resource into the bean when the bean is initialized. If you apply the annotation to a class, the annotation declares a resource that the bean will look up at runtime. The mappedName attribute of the annotation Resource specifies the global JNDI name of the dependent resource. Forexample: @Resource(mappedName ="jms/Queue") Specifies that the JNDI name of the dependent resources is jms/Queue and deployed in the JEE Server JNDI tree. For Web-client: In a Web-client application "jms/Queue" and ConnectionFactory" argument are used in the JNDI lookup. Both are logical JNDI names, and use the outbound connectivity provided by the JMS resource adapter. Make the JNDI lookup to use a Web Service shown as. InitialContext ctx = new InitialContext(); queue = (Queue) ctx.lookup("jms/Queue"); QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory"); connection = factory.createQueueConnection();
    • session = cnn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); Code for the message-driven bean: The MessageBean class demonstrates the following requirements to its implementation: • • • • In EJB 3.0, the MDB bean class is annotated with the @MessageDriven annotation that specifies, which message queue monitors the MDB (i.e., jms/Queue). If the queue does not exist, the EJB container automatically creates it at deploy time. There is no XML configuration file needed! For the Application Server, the @MessageDriven annotation typically contains a mappedName attribute that specifies the JNDI name of the destination from which the bean will consume messages. The class must be defined as public and must contain a public constructor with no arguments. It must not define the finalize method. It is recommended, but not required, that a message-driven bean class should implement the MessageListener interface for the message type it supports. This interface defines only one method onMessage( ). When the EJB container arrives a message, it calls the onMessage( ) method of the message-driven bean to process the message. The onMessage( ) method contains the business logic and handles the processing of the message in accordance with the application’s business logic. It can call helper methods, or invoke a session bean to process the information in the message or to store it in a database. A message is delivered to a message-driven bean within a transaction context, so all operations within the onMessage method are part of a single transaction. If message processing is rolled back, the message will be redelivered. In our example, the MessageBean.onMessage( ) method retrieves the message body, parses out the messages to a TextMessage, perform the necessary business logic, and displays the text to the message-client. A message-driven bean can also inject a MessageDrivenContext resource which is commonly used to call the setRollbackOnly method to handle exceptions for a bean during container-managed transactions. package mdb; import javax.ejb.*; import javax.ejb.MessageDriven; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.ObjectMessage; import java.text.*; import javax.naming.*; import java.util.logging.Logger;
    • @MessageDriven(mappedName="jms/Queue") public class MessageBean implements MessageListener { @Resource private MessageDrivenContext mdc; private static final Logger logger; public void onMessage(Message msg) { TextMessage tmsg = null; try { tmsg = (TextMessage) msg; logger.info("MESSAGE BEAN: Message received: " + tmsg.getText( )); System.out.println ("The onMessage() is called"); } catch (JMSException e) { e.printStackTrace( ); mdc.setRollbackOnly( ); } catch (Throwable th) { th.printStackTrace(); } } public void ejbRemove( )throws EJBException{ loger.fine("ejbRemove()"); } } Logger: When writing log messages from EJBs within JRun, you have the following options: • • Nonportable Use JRun-specific methods and services. These methods write to the JRun server's event log. Portable Use one of the System.out.println methods. These methods write to the console (if used when starting JRun). An EJB can acquire a logger instance from the container and use the logger's info( ) method to display the messages for the client-end, as shown in the following code examples: logger.info("MESSAGE BEAN: Message received: " + msg.getText( ));
    • Packaging, Deploying, and Running the message application. To create and package the application using Ant, use the default target for the build.xml file: ant This target packages the application client and the message-driven bean, then creates a file named message.ear in the dist directory. You simply avoid having to create deployment descriptor files for the message-driven bean and application client by using resource injection and annotations. You need to use deployment descriptors only if you want to override the values specified in the annotated source files. To deploy the application and run the client using Ant, use the following command: ant run The output in the terminal window looks like this: In the server log file, the following lines should be displayed, wrapped in logging information: MESSAGE BEAN: Message received: This is my sent message 1 MESSAGE BEAN: Message received: This is my sent message2 MESSAGE BEAN: Message received: This is my sent message 3 MESSAGE BEAN: Message received: This is my sent message 4 Introduction to POJO (Plain Old Java Object) Programming Model One of the new features of added by Sun Microsystems in EJB 3.0 is POJO (Plain Old Java Object). It is a Java object that doesn't extend or implement some specialized classes and interfaces respectively require by the EJB framework. Therefore, all normal Java objects are POJO’s only. The following classes are not POJO classes shown as: class MyServlet extends HttpServlet {} class MyRemote implements SessionBean {} In POJO model, it is recommended that, interfaces should be explicitly implemented whenever you want to pick and choose the methods of the interface. The interfaces are optional for entity beans but required for session beans and message-driven beans. In this model, both the interface and the bean class do not have to throw unnecessary exceptions such as RemoteException.
    • The interface class in POJO model is a Plain Old Java Interface (POJI). The Benefits of POJOs: Decoupling: It decouples the application components from the infrastructure of the EJB framework that lets you construct an application from loosely coupled components. There are no longer need to write the tedious JNDI framework-specific lookup code. You can design and implement the business logic. Once that's working, and then you can deal with persistence and transactions. Easier testing: You can test or run your business logic outside of the application server in a few seconds. Flexible: A Java POJO code can be implemented with any type of enterprise bean such as Message Driven Bean and Entity Bean. The POJO technology can be used with any type of Enterprise Java Beans(e.g Session Bean, Message Driven Bean or Entity Bean). Let’s understand the POJO with Message Driven Bean: Message Driven POJOs: Message-driven POJOs offer the functionality like MDB to make a simple JavaBeans for the developers. Similar to a MDB in EJB, it acts as a receiver for JMS messages. Writing a message-driven POJO is not much different than writing a message-driven EJB. The major difference between both is that, an message-driven POJO (MDP) must implement the javax.jms.MessageListener interface. Like an MDB, you don't have to implement javax.ejb.MessageDrivenBean and the EJB lifecycle methods defined by the interface. The EJB 3.0 uses annotations to build completely POJO-based messaging applications. In EJB 3.0’s container application server, there is an easier way to implement message driven RPCs. You can use POJOs as message end-points (message driven POJO). The RPC caller retrieves an automatically generated stub of the POJO and makes regular calls against the POJO methods. The message driven POJO works much like a session bean of EJB3, except that all calls are tunneled via a message queue. Let’s see the structure of Message Driven POJO given below:
    • Now, let’s see how message driven POJO is used in EJB3 taking an example. In our sample application, the class MessagePojoClient.java asynchronously invokes the onMessage method to display a simple “Hello...” message on a message driven POJO over a message queue. After the message driven POJO finishes the display task, it saves the result in a server wide cache manager. The POJO business interface: In our example, we are using the javax.jms.MessageListener interface, so we don’t need to define it again. You can also define new interface using @producer annotation to implement specific methods. The message driven POJO implementation: The implementation of the message driven POJO is tagged with the @Consumer annotation. You can specify the message queue property in the annotation attribute. If a message queue is un-defined, the EJB container will create one for you at server start-up. The code for MDP is given below: package mdb.pojo;
    • import import import import javax.jms.JMSException; javax.jms.Message; javax.jms.MessageListener; javax.jms.TextMessage; @Consumer(activationConfig = { @ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"), @ActivationConfigProperty(propertyName="destination", propertyValue="queue/mdpojo") }) public class MDPojoBean implements MessageListener { public void onMessage(Message message) { if (message instanceof TextMessage) { try { TextMessage tmsg = null; tmsg = (TextMessage) msg; System.out.println( "Message received: " + tmsg.getText()); } catch (JMSException ex) { throw new RuntimeException(ex); } } else { throw new IllegalArgumentException("Message must be of type TextMessage" ); } } } Note that, here we didn’t use @MessageDriven annotation to map the JNDI name. The Client: To use the message driven POJO on the client side, client looks up a stub object of the @Producer interface from the JNDI. The auto-generated stub-object not only implements the @Producer interface but also a component interface named ProducerObject. Using the ProducerObject.getProducerManager() method, you can get a ProducerManager object, which is used to make JMS connections. After a JMS connection is established, you can call any method in the @Producer stub object and the method is actually invoked over the pre-defined message queue. The following code snippet shows how the message driven POJO client works. package mdb.pojo; import javax.jms.*; import javax.naming.*; import java.text.*; class MessagePojoConn{
    • public MessagePojoConn(){ ProducerManager manager = null; MessageListener msglst=null; try { // lookup a stub object of the MessageListener interface from t he JNDI InitialContext ctx = new InitialContext(); msglst = (MessageListener) ctx.lookup(MessageListener.class.get Name()); ProducerObject po = (ProducerObject)msglst; ProducerManager manager = po.getProducerManager(); } catch (Exception e) { e.printStackTrace (); } manager.connect(); // internally create a JMS connection try{ msglst.onMessage("Hello Message Driven POJO"); } finally{ manager.close(); // clean up the JMS connection } } } public class MessagePojoClient{ public static void main(String[] args){ MessagePojoConn msgcon = new MessagePojoConn(); } } Description of Code: When the EJB3 container deploys the @Consumer, it looks for all of its implemented interfaces and registers each one of them in JNDI under. The client code above looks up the MessageListener interface in JNDI. Each producer implements the ProducerObject. The client typecasts the MessageListener to the ProducerObject. It then gets a ProducerManager that manages the JMS connection for this proxy. To start being able to send messages to the Queue, the client calls Connect( ) method on the manager. It then can successfully call methods on the "msglst" object. This method called onMessage( ) is converted into a JMS message and published to the Queue of the Consumer. The consumer will receive the message and invoke its onMessage method. There are a variety of ways to send a JMS message such as using JmsTemplate or Spring. Let’s see the configuration of the message listener containers that ships with Spring. <!-- this is the Message Driven POJO (MDP) --> <bean id="queue/mdpojo" class="jmsexample.MDPojoBean" />
    • <!--This is the message listener container --> <bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"> <property name="connectionFactory" ref="connectionFactory"/> <property name="destination" ref="destination"/> <property name="messageListener" ref="messageListener" /> </bean> Deploy and Run the MDP Application: Java Persistence API Java Persistence API is the standard API used for the management of the persistent data and object/relational mapping. Java Persistence API is added in Java EE 5 platform. Every application server compatible with Java EE 5 supports the Java Persistent APIs. Java Persistence API ensures the management of persistence and object/relational mapping. These are helpful while using the JPA in the development of applications using the platform for Java EE 5. It provides O-R mapping facility to manage relational data in java application. The Java Persistence API contains the following areas: • • • Java Persistence API O-R mapping metadata The query language Features of JPA: Java Persistence API is a lightweight framework based on POJO for object-relational mapping. Java language metadata annotations and/or XML deployment descriptor is used for the mapping between Java objects and a relational database . It allows the SQL-like query language that works for both static as well as dynamic queries. It also allows the use of the pluggable persistence API. Java Persistence APIs are mainly depends on metadata annotations. API includes: • Java Persistence API
    • • • Metadata annotations Java Persistence query language Advantages of JPA: Java Persistence API is build upon the best ideas from the persistence technologies like TopLink, JDO and Hibernate. Java Persistence API is compatible with Java SE environment as well as Java EE and allows developers to take advantages of the standard persistence API. Persistency of data is not so easy for most of the enterprise applications because for this they require access to the relational database like Oracle 10g. It is your responsibility to update and retrieve the database by writing the code using SQL and JDBC. While several object-relational (O-R) frameworks such as JBoss Hibernate and OracleTopLink make persistence challenges simpler and became popular. They let the java developer free from writing JDBC code and to concentrate only on the business logic. In EJB 2.x, container manage persistence (CMP) try to solve the persistence challenges but not successful completely. Persistence tier of the application can be developed in several ways but Java platform does not follow any standard that can be used by both Java EE and Java SE environment. But the Java Persistence API (JPA) part of EJB 3.0 spec (JSR-220) makes the persistence API standard for the Java platform. O/R mapping vendors like Hibernate and TopLink as well as JDO vendors and other leading application server vendors are receiving the JSR-220. Here we are describing EJB3 JPA by using the simple domain object model by an example. Working process of an EJB application using JPA: Domain Model: While developing an enterprise application, first design the domain object model required to persist the data in the database. Domain model represents the persistence objects or entities in the
    • database. An entity represents a row in the data. An entity may be a person, place or a thing about which you want to store the data in the database. A rich domain model includes the characteristics of all the object oriented behavior like inheritance, polymorphism and many more. While developing an enterprise application, first design the domain object model to persist the data in the database then design the database schema with the help of database designer. The figure illustrated below shows the bi-directional one-to-many relationship between the Employee and Department. The Contractor and the fulltime entities are inherited from the entity Employee. Sample domain object model The Basics of EJB3 JPA and O-R Mapping Framework: Each of the O-R mapping framework such as Oracle TopLink provides three facilities: 1. It defines a declarative way known as O-R mapping metadata to perform O-R mapping. Most of the framework use XML to store the O-R mapping metadata. 2. An API is required to manipulate like to perform CRUD (CRUD stands for create, read, update, and delete) operations. The API allows you to persist, remove, update or retrieve the object from the database. O-R framework performs operations using the API and the O-R mapping metadata on your behalf. 3. Use of a query language for retrieving objects from the database is the proper way since improper SQL statements may result in slow down the performance of the operation performing on the database. A query language allows to retrieve the entities from the database and spares you from writing the SQL SELECT statements. EJB 3 provides a standard way to use the persistence by providing a standard O-R mapping mechanism, a way to extend EJB-QL to retrieve entities and an EntityManager API to perform CRUD operations. EJB3 Java Persistence API (JPA) standardizes the use of persistence for the Java platform by providing a standard mechanism for O-R mapping, an EntityManager API to perform CRUD operations, and a way to extend EJB-QL to retrieve entities. I'll discuss these three aspects of JPA later.
    • Metadata Annotation in Action: Metadata annotations are first time introduced in Java SE 5.0. To make the development easy all the components of Java EE including EJB3 uses the metadata annotations. In EJB3 JPA annotation defines the objects, O-R mappings, and the relationships among them. JPA also have another option to use XML descriptor, But use of the metadata annotations make the development simpler and more efficient. Entities: An entity can be considered as a light weight persistence domain object. An entity defines a table in a relational database and each instance of an entity corresponds to a row in that table. An entity refers to a logical collection of data that can be stored or retrieved as a whole. For example, in a banking application, Customer and BankAccount can be treated as entities. Customer name, customer address etc can be logically grouped together for representing a Customer entity. Similarly account number, total balance etc may be logically grouped under BankAccount entity. Persistence fields or persistent properties defines the persistent state of an entity. To map the entities and their relationship to the data in the relational database these entities use the objectrelational mapping. Requirements of Entity Classes: There are some requirements that an entity must follow: • • • • • • The class must contain either a public or a protect no argument constructor, while it can contain other constructors. The class as well as methods and persistence instance variables must not be declared as final. Use the annotation javax.persistence.Entity to annotate the class. Declare the persistence instance variables as protected, private or package-private so that they can directly accessed only by the entity class's methods. Entity class may extend the entity as well as non-entity classes or vice-versa. The class must implement the serializable interface if an entity instance is passed by value. Persistence Fields and Properties in Entity Classes: There are two ways to access the persistent state of an entity either by instance variables or by using the JavaBeans-style properties. The fields or the properties must follow the Java language types: • • • • • • • • • Java primitive types java.lang.String Other serialization types including: wrappers of java primitive types java.util.Date java.util.Calender java.math.BigDecimal java.math.BigInteger java.sql.Time
    • • • • • • • • • • • java.sql.Date java.sql.TimeStamp User-defined serializable types char[] Character[] byte[] Byte[] Enumerated types Other entities and/or collection of entities Embedded classes Entity uses the persistent fields while mapping annotations. Annotations are applied to the entity's instance variable. On the other hand entity uses the persistence properties while mapping annotations. Annotations are applied to the entity's getter methods for JavaBeans-style properties. We can not apply mapping annotations to both fields as well as properties simultaneously in a single entity. Persistence Fields: Persistence accesses the entity class instance variables directly at runtime, if the entity class uses persistence fields. It is necessary to apply the object/relational mapping annotation on the instance variables. Persistent Properties: Entity must follow the method conventions of JavaBeans components while using the persistent properties. JavaBeans-style properties use getter and setter methods that are used after the entity class's instance variable names. There is a getter and a setter method for each persistence property. In case of a boolean property you may use isProperty instead of getProperty. Lets take an example to clarify this: Suppose an entity of type customer uses persistent property that has a private instance variable named firstName, the class defines two methods named getFirstName and setFirstName to retrieve and set the values of the instance variable. Use the following method signature for a single-valued persistent property. • • Type getProperty() void setProperty(Type type) Multi-valued (Collection-valued) persistent fields and properties must use the supported Java collection interfaces without worrying whether the entity uses the persistence fields or properties. The collection interfaces may be used at the following places: • • • • java.util.Collection java.util.Set java.util.Map java.util.List
    • If the entity class uses persistent fields then the method signatures of the collection types must be one of these collection types. Suppose an entity of type customer includes a persistent property that uses a set of phone numbers then it should have the following methods: Set<PhoneNumber> getPhoneNumber() {} void setPhoneNumbers(Set<PhoneNumber>) {} The O-R mapping annotations must be applied to the getter methods. Note here that mapping annotations can not be applied to the fields or properties marked transient or annotated transient. Primary Keys in Entities: Each entity contains a unique identity contained in the object. E.g. A customer entity has an identity that might be identified by the customer number. A primary key allows a client to be a particular entity instance. Every unique entity must be associated with a primary key. To prove its uniqueness every entity may have either a simple or a composite primary key. To denote the primary key property or field Simple primary key use javax.persistence.Id annotations. Composite primary keys must be composed of either a single persistent property or field or a set of single persistent properties or fields. Composite primary keys uses javax.persistence.IdClass and javax.persistence.EmbededId. The primary key, or the fields of the composite primary key (like property or field) must follow one of the following Java language types. • • • • • Java primitive types Java primitive wrapper types java.lang.String java.util.Date (the temporal type should be DATE) java.sql.Date Floating point types are not allowed to use in primary keys. Primary Key Classes: A primary class must follow the certain rules: • • • • • • The class must have an access modifier as public. The class must include a public default constructor. Primary key must contain the properties of the type public or protected if property-based access is used. The class must be serialized. The class must implement the equals(Other other) and hashCode() methods. If the class has the mapping to multiple fields or properties of the entity class then the names and types of the primary key fields must match with those of the entity class.
    • The fields order_Id and itemId are combined together to make the primary key to uniquely identify the composite key. The code for managing composite key is shown as: public final class ListItemKey implements Serializable{ public Interger order_Id; public int item_Id; public ListItemKey() {} public ListItemKey(Integer order_Id, int item_Id){ this.order_Id = order_Id; this.item_Id = item_Id; } public boolean equals(Object otherOb){ if(this == otherOb){ return true; } if(!otherOb instanceof ListItemKey){ return false; } ListItemKey other = (ListItemKey) otherOb; return ((order_Id==null? other.order_Id==null:order_Id.equals(other.order_Id)) &&(item_Id == other.item_Id)); } public int hashCode(){ return ((orderId==null?0:orderId.hashCode())^((int) itemId)); } public String toString() { return "" + orderId + "-" + itemId; } } Multiplicity in Entity Relationships: There are four types of multiplicities defined for entity relationships like one-to-one, one-tomany, many-to-one, and many-to-many. One-to-one: When each entity instance is mapped to a single instance of another entity, then the mapping is known as one- to-one mapping. One-to-one relationships use the javax.persistence.OneToOne annotation on the corresponding persistent field or property.
    • For Example: A reference variable in java contains the address of a single object so that there exists only one-to-one mapping between the object of the reference variable. One-to-many: When an entity instance is related to many instances of other entities, then the relation is known as one-to-many. These types of relationships use the javax.persistence.OneToMany annotation on the corresponding field or property. For Example: A sales order may contain the order of multiple items so there is a one-to-many relationship between the sales order and the items. Many-to-many: When the multiple instances of an entity have the mapping to the multiple instances of the other entity then the mapping is said to many-to-many mapping. Many-to-many mapping relationships use the javax.persistence.ManyToMany annotation corresponding to the field or property. For Example: A college student have the admission in several courses while each course may have many students. Therefore there is many-to-many relationship between the students and the courses. Direction in Entity Relationships: A relationship can be either unidirectional or bi-directional. Unidirectional Relationship: A unidirectional relationship is a relationship in which only one of the two entities have the owing side. In unidirectional relationship only one entity can have the relationship property or field that may refer to the other. Example: In the example given above, the List_Item contains the relationship field that refers to the other entity named as Product, while the Product doesn't have any knowledge about the List_Item that refers to it. Bi-directional Relationships: A bi-directional relationship is the relationship in which both the entities have the owing side. In bi-directional relationship each entity in the relation have the relationship fields or property. Example: Suppose the Order in the above example have the knowledge about the List_Item instance it has and also suppose that the List_Item have the knowledge about what the Order it belongs to, then the relationship between them is said to be the bi-directional relation. Rules: There are some rules that each bi-directional relationship must follow: • • • You must use its owing side simply using the mappedBy element of the @OneToOne, @OneToMany, or @ManyToMany annotation of the inverse side of a bi-directional relationship. mappedBy element is used to designate the field or property in an entity. In a one-to-one bi-directional relationship, owing side is the side that contains the corresponding foreign key. In a many-to-one bi-directional relationships the many side is always the owing side of the relationship and must not define the mappedBy element.
    • • In case of many-to-many bi-directional relationships either side may be the owing side. Queries and Relationship Direction: Java Persistence query language navigates queries across relationships. The direction of the relationship can be determined by checking the navigation of a query from one entity to another. Example: In case of the unidirectional relationship, in the above example a query can navigate from List_Item to Product, but can not navigate from Product to List_Item. In case of the above Order and List_Item, a query can navigate in both the direction because both the entities have the bi-directional relationship. Cascade Deletes and Relationships: Entities having the relationships are dependent on other entities in the relationship. Lets take the above example to clarify this: While deleting the order, the list item is also deleted since it is the part of the order, this is known as cascade delete relationship. Use the element cascade=REMOVE element to delete the cascade relationships specified for @OneToOne and OneToMany relationship. Example: OneToMany(cascade=REMOVE, mappedBy="customer") public Set<Order>getOrders() { return order; } Entity Inheritance: Entities also supports the various features like inheritance, polymorphic queries, and polymorphic associations. Moreover they can also be the non-entity classes, while the non-entity classes can also extend the entity classes. These entity classes can be of the type either concrete or abstract. Abstract Entities: An abstract class can be defined as entity simply by declaring the class with the @Entity. The difference between the abstract and the concrete entities is that the concrete entities can be instantiated while the abstract entities can not. Concrete entities are queried same as the abstract entities. Suppose a query makes the target to an abstract entity then the query operates on all the concrete subclasses of the abstract entity. @Entity public abstract class Student{ @Roll_no protected Integer StudentRoll_no;
    • ............ } @Entity public class FullTimeStudent extends Student{ public Integer fee; ............ } @Entity public class PartTimeStudent extends Student{ protected Float classTime; } Mapped Superclasses: We can inherit the entities from their superclasses containing the persistence state and the mapping information but are not entities. The super class does not need to decorate with the @Entity annotation, and does not map as an entity by the Java Persistence provider. These superclasses are used in most of the cases when the multiple entity classes have the common state and mapping information. Mapping superclasses are declared simply by specifying the class with the javax.persistence.MappedSuperclass annotation. @MappedSuperclass public class Student{ @Roll_no protected Integer StudentRoll_no; ............ } @Entity public class FullTimeStudent
    • extends Student{ protected Integer fee; .................. } @Entity public class PartTimeStudent extends Student{ protected Float classTime; ............. } We can not query the mapped superclasses and can also neither be used in Query operations nor EntityManager. But use the entity subclasses of the mapped superclasses to perform the Query operations or EntityManager. Entity relationship can not target to the mapped superclasses. Mapped superclass can be either of concrete or abstract type and also don't have any corresponding table in the underlying database. Entities inherited from the mapped superclasses define the table-mapping. For instance the above code snippet contains the underlying table FULLTIMESTUDENT and PARTTIMESTUDENT but did not have any STUDENT table. Non-Entity Superclasses: As discussed above that the entities may have non-entity superclasses and these superclasses can either be abstract or concrete. The state of the non-empty superclasses and any state inherited from these superclasses are not persistent. Non-entity superclasses can be used either in Query operations or in EntityManager. While the non-entity superclasses ignore any mapping or relationship annotations. Entity Inheritance Mapping Strategies: There is a way to configure the mapping between the underlying datastore and the inherited entities simply by decorating the parent class in the hierarchy with the javax.persistence.Inheritance annotation. Entities uses three types of mapping strategies to map the entity data to the underlying database. • • • A table for each concrete entity class. A single table for each class hierarchy. A "join" strategy for the specific fields or properties to a subclass are mapped to different tables rather than the fields that are common to the parent class. You can configure the strategy simply by setting the "strategy" element of @Inheritance to one of the options defined in the javax.persistence.InheritanceType enumerated type:
    • public enum InheritanceType{ SINGLE_TABLE, JOINED, TABLE_PER_CLASS }; InheritanceType.SINGLE_TABLE is the default strategy value and is used in such situations where @Inheritance annotation is not specified in the parent class of the hierarchy. Single Table per Class Hierarchy Strategy: This strategy corresponds to the default InheritanceType.SINGLE_TABLE, a single table in the database is mapped to all the classes in the hierarchy. This table includes a column containing a value to identify the subclass that belongs to the row represented by the instance. This column is known as discriminator column and can be specified by the javax.persistence.DiscriminatorColumn annotation at the root in the class hierarchy of the entity. The javax.persistence.DiscriminatorType enumerated type is used to set the type of the discriminator column in the database simply by setting the discriminatorTypeelement of @DiscriminatorColumn to one of the defined types. DiscriminatorTypeis defined as: public enum DiscriminatorType{ STRING, CHAR, INTEGER }; While @DiscriminatorColumn in not specified at the root of the entity hierarchy and the discriminator column is required then the persistence provider assumes the coulumn type as DiscriminatorTypeSTRING and column name as DTYPE by default. A Java Persistence Example ava Persistence API is the standard API used for the management of the persistent data and object/relational mapping. Java Persistence API is added in Java EE 5 platform. Persistence, deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0. Every application server compatible with Java EE 5 supports the Java Persistent APIs. Java Persistence API is a lightweight framework based on POJO for object-relational mapping. Java language metadata annotations and/or XML deployment descriptor is used for the mapping between Java objects and a relational database. Entity: An entity can be considered as a lightweight persistence domain object. An entity defines a table
    • in a relational database and each instance of an entity corresponds to a row in that table. An entity refers to a logical collection of data that can be stored or retrieved as a whole. For example, in a banking application, Customer and BankAccount can be treated as entities. Customer name, customer address etc can be logically grouped together for representing a Customer entity. Similarly account number, total balance etc may be logically grouped under BankAccount entity. Entity beans: Entity beans are enterprises beans, which represent persistent data stored in a storage medium, such as relational database an entity bean persists across multiple session and can be accessed by multiple clients. An entity bean acts as an intermediary between a client and a database. For example, consider a bank entity bean that is used for accessing account details from a database. When a client wants to perform a transaction, the information regarding their specific account is loaded into an entity bean instance from the database. Operations are performed on the data present in the instance and updated in the bank’s database at regular intervals. The EJB 3.0 entity beans are used to model and access relational database tables. It is a completely POJO-based persistence framework with annotations that specify how the object should be stored in the database. The EJB 3.0 container does the mapping from the objects to relational database tables automatically and transparently. The Java developer no longer needs to worry about the details of the database table schema, database connection management, and specific database access APIs. Entity beans do not need to implement home interfaces and business interfaces. They are optional. Mapping with EJB3/JPA Annotations: EJB3 entities are POJOs. Their mappings are defined through JDK 5.0 annotations (an XML descriptor syntax for overriding is defined in the EJB3 specification). Annotations can be split in two categories, the logical mapping annotations which allows programmer to describe the object model, the class associations, etc. and the physical mapping annotations which describes the physical schema, tables, columns, indexes, etc. The combination of annotations from both categories makes an entity-based application. Primary Key Generation: In EJB 3.0, a primary key is used with @Id annotation. Depending upon the application requirement, Id annotation can be used with different primary key generation strategies defined by GeneratorType enum. The GeneratorTypes are TABLE, SEQUENCE, IDENTITY, AUTO, and NONE. Declaring an entity bean: Every bound persistent POJO class is an entity bean and is declared using the @Entity annotation (at the class level):
    • @Entity public class Book implements Serializable { Long empid; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } } @Entity declares the class as an entity bean (i.e. a persistent POJO class), which tells the EJB3 container that this class needs to be mapped to a relational database table. @Id declares the identifier property of this entity bean. @GeneratedValue annotation indicates that the server automatically generates the primary key value. The class Book is mapped to the Book table, using the column id as its primary key column. Defining the table: @Table is set at the class level; it allows you to define the table, catalog, and schema names for your entity bean mapping. If no @Table is defined the default values are used, that is the unqualified class name of the entity. @Entity @Table(name="book") @SequenceGenerator(name = "book_sequence", sequenceName = "book_id_seq") public class Book implements Serializable { The @Table defines the table name. Each instance of the entity bean represents a row of data in the table. Each column in the table corresponds to a data attribute in the entity bean. The @SequenceGenerator defines a sequence generator. A sequence is a database feature. It returns the next Integer or Long value each time it is called. Managing Entities: The entity manager manages entities. The entity manager is represented by javax.persistence.EntityManager instances. Each EntityManager instance is associated with a persistence context. A persistence context defines the scope under which particular entity instances are created, persisted, and removed. It is a set of managed entity instances that exist in a particular data store. The EntityManager interface defines the methods that are used to interact with the persistence context. The EntityManager Interface: The EntityManager API creates and removes persistent entity instances, finds entities by the entity’s primary key, and allows queries to be run on entities.
    • To obtain an EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; Managing an Entity Instance’s Life Cycle: You manage entity instances by invoking operations on the entity by means of an EntityManager instance. Entity instances are in one of four states: new, managed, detached, or removed. New entity instances have no persistent identity and are not yet associated with a persistence context. Managed entity instances have a persistent identity and are associated with a persistence context. Detached entity instances have a persistent identify and are not currently associated with a persistence context. Removed entity instances have a persistent identity, are associated with a persistent context, and are scheduled for removal from the data store. A Domain model of JPA represents the persistence objects or entities in the database.
    • There are following steps that you have to follow to develop a ‘book’ JEE application. 1. Create Remote business interface: BookCatalogInterface 2. Implement the Annotated Session Bean: BookCatalogBean 3. Create the Entity bean: BookBank 4. Create the web client: WebClient 5. Deploy book on the server. 6. Run web client on the web browser. I. The BookBank entity bean class: In the Book catalog example, we define a Book entity bean class. The bean has three properties (title, author and price) to model a Book product. The id property is used to uniquely identify the Book bean instance by the EJB3 container. The id value is automatically generated when the bean is saved to the database. The code for the Book bean is given below. package entity.library; import import import import import import import import javax.persistence.Entity; javax.persistence.GeneratedValue; javax.persistence.GenerationType; javax.persistence.Id; javax.persistence.Table; java.util.Collection; javax.persistence.*; java.io.Serializable; @Entity @Table(name="bookbank") public class BookBank implements Serializable { long id; String title; String author; double price; //protected Collection <LineItems> lineitems; public BookBank() { super(); } public BookBank(String title, String author, double price) { super(); this.title = title; this.author = author; this.price = price; } @Id
    • @GeneratedValue(strategy=GenerationType.AUTO) // Getter and setter methods for the defined properties.. public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } The @Table annotation is used to specify the table name to be used by this Entity bean. The @Id annotation is used to mark the id field as the primary key of the entity bean. II. SQL Schema for the Book table mapped from the Book bean: CREATE TABLE BOOKBANK ( ID int(11) NOT NULL auto_increment, TITLE varchar(50) NOT NULL, AUTHOR varchar(50) NOT
    • NULL, PRICE decimal(12,2) NOT NULL, PRIMARY KEY (ID) ); III. The Business Logic: Now, the next step is to develop the business logic of the application. The Book catalog application needs to be able to save a new Book object into the database and retrieve all existing Book objects from the database. We use EJB3 session bean POJOs to implement the business logic. To implement a session bean, we first determine the interface it exposes. In the Book catalog application, this is a simple Java interface declaring all business methods. package entity.library; import javax.ejb.Remote; import java.util.Collection; @Remote public interface BookCatalogInterface { public void addBook(String title, String author, double price); public Collection <BookBank> getAllBooks(); } IV. Annotated Session Bean Implementation Class: The EJB3 container creates instances of the session bean based on the implementation classes. The application itself never creates session bean instances. It simply asks the container for an instance of the session bean to use, either through dependency injection or, for external components, through a JNDI lookup. The class is tagged with the @Stateless annotation, which tells the container that the bean object does not maintain any client state information between method invocations. The caller component gets a fresh and random BookCatalogBean instance every time when it makes a bean method call. In order to use the entity beans in the session bean, you need a special utility class called the EntityManager. The EntityManager acts as a generic DAO (Data Access Object) for all entity beans in the JAR. It translates operations on entity beans to SQL statements to the database. To obtain an EntityManager, the container creates one object and injects it into the session bean. The addBook() and getAllBooks() methods in the BookCatalogBean class show the EntityManager in action. The EntityManager.persist() method takes a new entity bean POJO and writes it to the database. The code for the BookCatalogBean is given below.
    • package entity.library; import java.util.Iterator; import java.util.Collection; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.io.Serializable; import javax.ejb.Remote; @Remote(BookCatalogInterface.class) @Stateless public class BookCatalogBean implements Serializable, BookCatalogInterface { @PersistenceContext(unitName="EntityBean") EntityManager em; protected BookBank book; protected Collection <BookBank> bookList; public void addBook(String title, String author, double price) { // Initialize the form if (book == null) book = new BookBank(title, author, price); em.persist(book); } } public Collection <BookBank>getAllBooks() { bookList=em.createQuery("from BookBank b").getResultList(); return bookList; } The EntityManager API creates persistent entity instances and allows queries to be run on entities. Context context = new InitialContext(); BookCatalogInterface bookcat = (BookCatalogInterface) context.lookup(BookCatalogBean.class.getName()); V. Web Client Code: Here is the full source code of the book client (WebClient.java): <%@ page contentType="text/html; charset=UTF-8" %> <%@ page import="entity.library.*, javax.naming.*, java.util.*"%> <%! private BookCatalogInterface bci = null; String s1,s2,s3;
    • Collection list; public void jspInit() { try { InitialContext ic = new InitialContext(); bci = (BookCatalogInterface) ic.lookup("book/BookCatalogBean/remote"); System.out.println("Loaded Bank Bean"); } catch (Exception ex) { System.out.println("Error:"+ ex.getMessage()); } %> } public void jspDestroy() { bci = null; } <% try { s1 = request.getParameter("t1"); s2 = request.getParameter("aut"); s3 = request.getParameter("price"); if ( s1 != null && s2 != null && s3 != null) { Double price= new Double(s3); bci.addBook(s1, s2, price.doubleValue()); System.out.println("Record added:"); %> <p> <b>Record added</b> <p> <% } list=bci.getAllBooks(); for (Iterator iter = list.iterator(); iter.hasNext();){ BookBank element = (BookBank)iter.next(); %> <br> <p>Book ID: <b><%= element.getId() %></b></p> <p>Title: <b><%= element.getTitle() %></b></p> <p>Author: <b><%= element.getAuthor() %></b></p> <p>Price: <b><%= element.getPrice() %></b></p> <% } }// end of try catch (Exception e) { e.printStackTrace (); } %> The source code for the “index.jsp” is given below that will actual call the client-design form.
    • <%@page language="java" %> <html> <head> <title>Ejb3 JPA Tutorial</title> </head> <body bgcolor="#FFFFCC"> <p align="center"><font size="6" color="#800000"><b>Welcome to <br> Ejb3-Jboss 4.2.0 Tutorial</b></font> Click <a href="ejb3/form.jsp">Book Catalog Example</a> to execute Library<br></p> </body> </html> The source code for the “index.jsp” is given below that will call the web client. <html> <head> <title>Library</title> </head> <body bgcolor="pink"> <h1>Library</h1> <hr> <form action="WebClient.jsp" method="POST"> <p>Enter the Title: <input type="text" name="t1" size="25"></p> <br> <p>Enter Author name: <input type="text" name="aut" size="25"></p> <br> <p>Enter Price:
    • <input type="text" name="price" size="25"></p> <br> <p> <input type="submit" value="Submit"> <input type="reset" value="Reset"></p> </form> </body> </html> V. Deploy book application on the Application Server jboss-app.xml The jboss-app.xml file defines a class loader for this application. It makes it simpler for EJB 3.0 to find the default EntityManager. <jboss-app> <loader-repository> book:archive=book.ear </loader-repository> </jboss-app> Application.xml <?xml version="1.0" encoding="UTF-8"?> <application xmlns="http://java.sun.com/xml/ns/javaee" mlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ve rsion="5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd"> <display-name>JPA Example</display-name> <module> <web> <web-uri>book.war</web-uri> <context-root>/book</context-root> </web> </module> <module> <ejb>book.jar</ejb>
    • </module> </application> Put both files in the EntityBeancodedeploymentdescriptorsear directory. persistence.xml The persistence.xml file contains one or several persistence-unit element. Each persistence-unit defines the persistence context name, data source settings, and vendor specific properties. In this example, we are using the HSQL database that is default provided by the Jboss AS. The hibernate property “create-drop” will automatically create & drop a table (according to the POJO class) each time when you deploy and run the application on server. <persistence> <persistence-unit name="EntityBean"> <jta-data-source>java:/DefaultDS</jta-data-source> <properties> <property name="hibernate.hbm2ddl.auto" value="create-drop"/> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/> </properties> </persistence-unit> </persistence> Put this files in the EntityBeancodedeploymentdescriptorsjar directory. web.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app > </web-app> Start command prompt, and go to the EntityBeancode directory. Then type the command as: C: EntityBeancode>ant build.xml
    • The Ant tool will deploy the book.ear file to the jboss-4.2.0.GAserverdefaultdeploy directory. VI. Running the book application Open the web browser and type the following URL to run the application: http://localhost:8080/book Click at the given link as Book Catalog Example:
    • Enter the Title, Author and Price for the book to the textbox then clicks the Submit button to get the result. Book ID: 1 Title: EJB-JPA
    • Author: Nisha Price: 300.00 Web Services Normally a Service represents any kind of feature or some piece of functionality that a specific kind of client can take it from. For example, a printer service, where the clients are either the applications or the programs using the printers. Likewise, consumers of an ATM service are Bank Customers. These are the list of real-world services goes on in our daily-life. Web services was first time introduced in EJB2.1, while EJB3.0 made the web services development easy and more flexible. Here we are going to describe the general concept of web services and then explain them how the ejb supports to implement both the web services and web services client. Web Services Concept: Web services are the mechanism to develop a Service-OrientedArchitecture (SOA). SOA is an architectural approach for designing large scale distributed systems to integrate heterogeneous application on the service interfaces. Web services technologies support to the Service-Oriented-Architecture in various ways. Some of them are illustrated below: • • A service requestor uses the selection criteria to the query registry for finding the services description. A service requestor can bind and use the service if it finds a suitable descriptor. Web services are used in various fields such converting a temperature value from Fahrenheit to Celsius. More realistic examples built using the web services are heterogeneous applications such as billing application and report generator, interconnected in-house architectures. A service interface is just like an object interface with a slight difference that the contract between the interface and the client is more flexible and the implementation of client and the service is not much tightly coupled as compared to EJB or other distributed platform. Looser coupling allows the client and service implementation to run on various platforms, independently such as Microsoft .NET is capable of using a Java EE application server to access a service running on it. From the client's point of view, web services's life cycle is more static as compared to average objects because web services stay around rather than pop-up and go away, even if the services are implemented using the object technology. Features of Web Services: Following are the unique features of a Web-Service based application.
    • • • Language Independent Operating System Independent Language Independent: Let us assume that a Web-Service is running in a remote machine. Suppose an application (can be a Web-Service also) want to gain the functionality of the Web-Service by accessing it. It is not that both the Web-Service and the client application must be built in the same language or technology. They can be different. Web Services Standards: The de facto standardized set of web services can be summarized by using an equation. Web Services = WSDL + SOAP + UDDI Lets take a quick look over WSDL and UDDI, but we are not going to cover these topics here because these are less useful. The requestor does not necessarily have the registry to know the services and its end point address. Registry not only supports a simple naming service but also queries for the services that follow the given predicate. WSDL: There is no need to write down the xml file. The tool you are using automatically creates an xml file. A number of things are worth nothing while using WSDL. • • • • The service description includes an endpoint address: WSDL is similar to java interface and an object reference joined together or in other words, we can say web services don't have distinct identities. Since they are not objects therefore they must be viewed like objects. It does not have any client visible state therefore your are not able to compare the two references for equality. It uses larger number of concepts than in java: Service provides one or more ports at an address. Ports are the representation of the service interfaces that binds to protocols. Operations result in terms of input and output messages rather than parameters and return values: Services are bind using SOAP binding: Building a Web Service with JEE: The creation of the portable and interoperable distributed components from the web services is not a trivial task. Either regular Java classes or stateless EJBs can be easily deployed as web services. Package the Java regular classes in a web module and EJB web services in normal ejb-jar modules. Two options are there to deploy an application, you can use one of the two deployment options given below: Java Class versus Stateless EJB: It depends upon you whether you should have a regular Java class or EJBs as your technology to build a Web Service. We can easily develop java classes than EJBs. Java classes are pure java objects and do not have the extra baggage that the EJBs do. One benefit of using EJB is that it supports the features such as declarative transaction and
    • security. EJB leaves free to the developer just to concentrate only on applying the business logic without worrying about the infrastructure services. Packaging Requirement: Whatever you are using either a regular Java class or EJB, in both the conditions you need to package several artifacts into your WAR or ejb-jar accordingly, to expose components as a Java Web Service. Web Services use the following two packaging structures based on either regular Java classes or EJBs. Web app (.war) for a regular Java web service: /WEB-INF/ web.xml webservices.xml oracle-webservices.xml mapping-file.xml wsdl/ it is wsdl file /classes/(includes endpoint and bean classes) /lib/ ejb-jar for an EJB-based web service: /META-INF/ ejb-jar.xml webservices.xml oracle-webservices.xml mapping-file.xml wsdl/ the wsdl file ejb classes (includes endpoint and bean classes) Lets discuss each of the descriptors and the deployment-time artifacts one-by-one. • • • WSDL: We are not going to discuss about the WSDL any more as we have already discuss it in the previous section. Web Services Deployment Descriptor: webservices.xml is the standard deployment descriptor that a JEE plateform requires. This descriptor specifies the description for deployment about the set of web services into the JEE application server and also their dependencies on the container resources and services. The mapping.xml file that contains Java-to-WSDL mapping and the service endpoint interface for the HelloWorld web service is also specified by this deployment descriptor. Endpoint interface: The Web Service endpoint implements the java.rmi.Remote interface therefore every method of web service endpoint interface must throw the java.rmi.RemoteException. The deployment descriptor registers to the end point for the
    • module (ejb-jar.xml) or web.xml. The deployment descriptor (e.g. ejb-jar.xml) should have the following entry. <service-endpoint> oracle.ejb21.ws.HelloServiceInf </service-endpoint> Following is the code for the Web Service endpoint for a HelloWorld web service: public interface HelloServiceInf extends java.rmi.Remote { java.lang.String sayHello(java.lang.String name) throws java.rmi.RemoteException; } • • Vendor-specific deployment descriptors: We can not specify several implementationspecific reference, such as endpoint addresses, context root in the Web Services deployment descriptor but we can rather specify the vendor-specific deployment descriptor. For example if you are using OC4J then an oracle-webservices.xml file is required to package in WAR or ejb-jar to define the properties. Java-WSDL mapping: Mapping between the WSDL and Java types is defined in this file. Mapping file does not have any standard name, web services deployment descriptor defines its name. Before deploying your component as a web service, first you must package all these artifacts in the ejb-jar module or in the WAR. Most of the development tools like Oracle JDeveloper simplifies the development task of web services simply by mapping files, generating the deployment descriptor etc. Moreover most of the application servers provide Web Services assembly tools that fulfill the JEE web service packaging requirements. Before understanding the components required to make up a Web Service and the associated packaging requirements, first you must deal with the architectural issues when developing a web service. Approaches to Construct Services: The main thing about building a Web Service is to identify the service along with its right granularity. Its depends upon you either you can expose an existing component that is built as a Java class or EJB and expose it as a service or build the new service. You can use either top-down or bottom-up approach while building a new service. • Top-down approach: While building the services from scratch, this is the most appropriate approach. With this approach start describing the service with WSDL instead of jumping right into the implementation. This is the most preferable approach since services become maintainable, more usable and interoperable due to the control over the WSDL while deploying your web service, careful consideration of the operations and message exposed. Several JEE vendors provide tools to make the approach easier such as
    • • Oracle Application Server's web services assembler generates deployment descriptors, interfaces and skeleton implementation classes which can be used to build your application. Bottom-up approach: This approach is used whenever an existing Java class or EJB is to be exposed as a Web Service. The reason behind the populalrity of this approach is that, this approach allows to reuse the existing business logic without rewriting the applications. While using this approach, you have to create a WSDL to describe the Web Service along with other deployment descriptors and add a web service end-point interface for the implementation to which you want to expose as a Web Service. Tools provided by application servers (such as Oracle Application Server's web services assembler tool) are used to make the life simpler by generating the descriptors such as webservices.xml, WSDL and mapping files for Web Services components free up the developer from manually creating these files. Tips for developing Web Services: Here are the some points that must follow while developing Web Services. • • • • Most of the conventional best practices are for JEE applications that are relevant to Web Services. for example, avoid exposing a component involve in the long-run transaction as a Web Service. Confirm design of your Web Service so that it can create minimum network traffic. Do not overuse Web Services in your applications. Check the necessity to expose your application as a Web Service. Compare your security requirements with the performance of your application as security comes with the higher cost. Performance of end-toend security for web services are quite costly. To build java based web services, J2EE Blueprint Application ( Java Adventure Builder) provides a nice blueprint application. After designing, developing and deploying, we generally create the associated components to interact with the given service. Invoking Web Services: Web Service can have the client of any of the following type: Dynamic Invocation Interface (DII) or dynamic proxy, static stub. Building a Web Service client may be complex similar to build a simple web service. But JEE 1.4 makes it simple to use the web services for JEE developers from any type of JEE component such as EJB components or web clients. Invoking a Web Service is similar to invoking any other resource using JNDI via the following: • First define your component by using a "service-ref" element in the deployment descriptor. For example, if you are accessing the HelloWorldService web service by using web module then the module's web.xml file may contain the following:
    • <service-ref> <service-refname>service/HelloWorldService</servic e-ref-name> <serviceinterface>oracle.ws.HelloWorldService</s ervice-interface> <wsdl-file>METAINF/HelloWorldService.wsdl</wsdl-file> <service-qname>urn:oracle-ws</serviceqname> </service-ref> • • • Allow your application to find Web Service just by specifying the location of the Web Service in the vendor-specific deployment descriptor. <service-ref-mapping name="service/HelloWorldService"> <port-info> <wsdl-port namespaceURI="urn: HelloWorldService" localpart="HelloWorldServicePort"/> <stub-property> <name>javax.xml.rpc.service.endpoint.address </name> <value>http://localhost:8888/hello/HelloWorldI nf</value> </stub-property> </port-info> </service-ref-mapping> Package type classes and end-point interface with your application before deploying it to the server. Make the JNDI lookup to use a Web Service. InitialContext ctx= new InitialContext(); HelloServiceInf hs = (HelloServiceInf) ctx.lookup("java:comp/env/service/HelloWorld Service"); HelloWorld hello= hs.getHelloWorldServicePort(); String myhello = hs.sayHello("Zulfiqar") ;
    • Simplifying SOA Development with JEE 5.0: Building service-oriented applications are rather difficult with JEE, JEE 5.0 is designed to simplify the development by using Web Services Metadata annotations defined by JSR 181. Web Services Metadata and EJB 3.0 both are used to provide friendly environment to the developer. To develop a simple Java Web Service in JEE 1.4, several Web Service artifacts such as mapping files, WSDL, proprietary web services deployment descriptor and several verbose standard are designed in JEE 5.0. Web Services Metadata specification receives a by default configuration approach similar to EJB 3.0 for simplifying the development process. Web Services Metadata annotation process generates these files for you so just concentrate on the implementation class. Following is the Java Web Service developed using Web Services Metadata: package oracle.jr181.demo; import javax.jws.WebMethod; import javax.jws.WebService; @WebService(name = "HelloWorldService", targetNamespace = "http://hello/targetNamespace" ) public class HelloWorldService { @WebMethod public String sayhello(String name ) { return "Hello” +name+ “ from jws"; } } EJB 3.0 uses regular Java classes to simplify the development process. EJB-based Web Services developed using EJB 3.0 and Web Services Metadata, are much simpler. HelloWorld EJB is the example given below developed by using EJB 3.0 and Web Services Metadata. Don't worry while creating WSDL, deployment descriptors, etc., since the application server generates these artifacts during deployment. package oracle.ejb30.ws; import javax.ejb.Remote; import javax.jws.WebService; @WebService public interface HelloServiceInf extends java.rmi.Remote{ @WebMethod java.lang.String sayHello(java.lang.String name)
    • throws java.rmi.RemoteException; } Implementation of HelloWorld EJB using EJB 3.0 is given below: package oracle.ejb30.ws; import java.rmi.RemoteException; import javax.ejb.Stateless; @Stateless(name="HelloServiceEJB ") public class HelloServiceBean implements HelloServiceInf { public String sayHello(String name) { return("Hello "+name +" from first EJB3.0 Web Service"); } } The above example demonstrates the simplification of service development while simplifying by using Web Services Metadata and EJB 3.0. Conclusion This articles gives you the understanding about the basics of building Web Services using the J2EE platform. You can build and deploy your Web Services in J2EE-compliant application servers such as Sun Java System Application Sever, Oracle Application Server 10g, etc. EJB remote interface The program given below describes the way of creating a remote interface in EJB. The meaning of Remote interface in terms of Ejb is the java source file which contain the bean implementation logic. These are very much similar to the RMI Remote interface and provides the business specific functionality of an EJB. Here we have created the Remote interface named SessionBeanRemote.java @Remote:- This is the annotation which is used to declare the interface as Remote.
    • String getResult(); String getAddress();String getCompanyname():-These are the methods which are to be defined inside the bean. SessionBeanRemote.java package ejb; import javax.ejb.Remote; @Remote public interface SessionBeanRemote { String getResult(); String getAddress(); String getCompanyname(); } SessionBeanBean.java:- This is the session bean in which we will declared all the methods of the Remote interface. This bean is used for controlling the business process and filling the gaps between the data of the entity beans. Here @Stateless is the annotation which denotes the bean is of session type. SessionBeanBean.java package ejb; import javax.ejb.Stateless; @Stateless public class SessionBeanBean implements SessionBeanRemote { public String getResult() { return "Hello World"; } public String getAddress() { return "Sec-3,D-16/116,Rohini"; } public String getCompanyname() { return "Roseindia.net Pvt.Ltd."; } } Main.java:- This is the client application from which we can access all the methods of the session bean.
    • @EJB:-This is the annotation that configure the EJB values for a field or a method. This annotation is a Resource annotation and is used where it is known that the resultant is an EJB interface. Main.java package ejb_remote; import ejb.SessionBeanRemote; import javax.ejb.EJB; public class Main { @EJB private static SessionBeanRemote sessionBeanBean; public static void main(String[] args) { System.err.println("Accessing Remote Interface using EJB:"); System.out.println("================================="); System.err.println("Name of the Company is : =" + sessionBeanBean.get Companyname()); System.err.println("Address of the Company is : =" + sessionBeanBean. getAddress()); System.err.println("Message is : =" + sessionBeanBean.getResult()); System.out.println("================================="); } } Output of the Program Accessing Remote Interface using EJB: ================================= Name of the Company is : =Roseindia.net Pvt.Ltd. Address of the Company is : =Sec-3,D16/116,Rohini Message is : =Hello World ================================= Ejb message driven bean This tutorial explains you the process which are involved in making a message driven bean using EJB. Mesaage driven bean in EJB have the following features:1) is a JMS listener
    • 2) provides a single-use service 3) is relatively short lived For developing the message driven bean we are using both the EJB module and web module. The steps involved in creating message driven bean are as follows:Step1:-Create a persistence unit named as persistence.xml. Persistence unit defines the data source and entity manager used in our application. The use of persistence unit to describe a convenient way of specifying a set of metadata files, and classes. persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/ persistence_1_0.xsd"> <persistence-unit name="NewsApp-ejbPU" transactiontype="JTA"> <provider>oracle.toplink.essentials.PersistenceProvider</provider> <jta-data-source>jdbc/sample</jta-data-source> <exclude-unlisted-classes>false</exclude-unlisted-classes> <properties> <property name="toplink.ddl-generation" value="drop-and-createtables"/> </properties> </persistence-unit> </persistence> Step2:-Create an Entity class named NewsEntity.java By Entity class we mean a java class that represent table from the database. The annotation which is used for Representing a class as Entity is @Entity. Here in the program given below :@Id annotation is used to declare the field as a primary key. @GeneratedValue association is used for a primary key property. it specifies auto-generation parameters and methods for primary key. private Long id; private String title; private String body; private String email; private String dob:-These are the field declaration to the class NewsEntity.java
    • package ejb; import import import import import java.io.Serializable; javax.persistence.Entity; javax.persistence.GeneratedValue; javax.persistence.GenerationType; javax.persistence.Id; @Entity public class NewsEntity implements Serializable { private static final long serialVersionUID = 1L; private Long id; private String title; private String body; private String email; private String dob; public void setId(Long id) { this.id = id; } @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getEmail() { return email; } public String getDob() { return dob; } public void setDob(String dob) { this.dob = dob; } public void setEmail(String email) { this.email = email; } public String getBody() { return body;
    • } public void setBody(String body) { this.body = body; } } Step3:-Create a messagedriven bean named NewMessageBean.java @MessageDriven(mappedName = "jms/Queue", activationConfig = { @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = " Auto-acknowledge"), @ActivationConfigProperty(propertyName = "destinationType", propertyValue = " javax.jms.Queue") }) This is the message driven annotation that tells the container that the component is a messagedriven bean and the JMS resource is used by the bean. private EntityManager em:-By this we define the entity manager into the class. NewMessageBean.java package ejb; import import import import import import import import import import javax.annotation.Resource; javax.ejb.ActivationConfigProperty; javax.ejb.MessageDriven; javax.ejb.MessageDrivenContext; javax.jms.JMSException; javax.jms.Message; javax.jms.MessageListener; javax.jms.ObjectMessage; javax.persistence.EntityManager; javax.persistence.PersistenceContext; @MessageDriven(mappedName = "jms/Queue", activationConfig = { @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = " Auto-acknowledge"), @ActivationConfigProperty(propertyName = "destinationType", propertyValue = " javax.jms.Queue") }) public class NewMessageBean implements MessageListener { @Resource private MessageDrivenContext mdc; @PersistenceContext private EntityManager em; public NewMessageBean() { } public void onMessage(Message message) { ObjectMessage msg=null;
    • try { if (message instanceof ObjectMessage) { msg = (ObjectMessage) message; NewsEntity e = (NewsEntity) msg.getObject(); save(e); } } catch (JMSException e) { e.printStackTrace(); mdc.setRollbackOnly(); } catch (Throwable te) { te.printStackTrace(); } } public void save(Object object) { em.persist(object); } } Step4:-Create a session bean named NewsEntityFacade.java @Stateless is the annotation used to declare the class as a stateless session bean component. NewsEntityFacade.java package ejb; import import import import java.util.List; javax.ejb.Stateless; javax.persistence.EntityManager; javax.persistence.PersistenceContext; @Stateless public class NewsEntityFacade implements NewsEntityFacadeLocal { @PersistenceContext private EntityManager em; public void create(NewsEntity newsEntity) { em.persist(newsEntity); } public void edit(NewsEntity newsEntity) { em.merge(newsEntity); } public void remove(NewsEntity newsEntity) { em.remove(em.merge(newsEntity)); } public NewsEntity find(Object id) { return em.find(ejb.NewsEntity.class, id); }
    • public List findAll() { return em.createQuery("select object(o) from NewsEntity as o").getResultList( ); } } Step5:-Create a local Interface named NewsEntityFacade.java NewsEntityFacadeLocal.java package ejb; import java.util.List; import javax.ejb.Local; @Local public interface NewsEntityFacadeLocal { void create(NewsEntity newsEntity); void edit(NewsEntity newsEntity); void remove(NewsEntity newsEntity); NewsEntity find(Object id); List findAll(); } Step6:-Create a servlet named ListNews.java This is the servlet for displaying our data. @EJB:-This is the annotation that configure the EJB values for a field or a method. Normally this annotation is a Resource annotation where it is known that the resultant is an EJB interface. ListNews.java package web; import import import import import import import import import ejb.NewsEntity; ejb.NewsEntityFacadeLocal; java.io.*; java.net.*; java.util.Iterator; java.util.List; javax.ejb.EJB; javax.servlet.*; javax.servlet.http.*; public class ListNews extends HttpServlet {
    • @EJB private NewsEntityFacadeLocal newsEntityFacade; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>EJB Message driven bean</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>EJB Message driven bean using Servlet</h1>"); out.println("<hr></hr>"); out.println("<h3>Details You have Entered is:</h3>"); List news = newsEntityFacade.findAll(); for (Iterator it = news.iterator(); it.hasNext();) { NewsEntity elem = (NewsEntity) it.next(); out.println(" <b>" + "Name is: " + "</b>" + elem.getTitle() + "<br />"); out.println("<b>" + "E-mail is: " + "</b>" + elem.getEmail() + "<br /> "); out.println("<b>" + "Dob is: " + "</b>" + elem.getDob() + "<br /> "); out.println("<b>" + "Address is: " + "</b>" + elem.getBody() + "<br /><br /> "); } out.println("<a href='PostMessage'><b>Post new message</b></a>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } protected void doGet(HttpServletRequest request, HttpServletResponse resp onse) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse res ponse) throws ServletException, IOException { processRequest(request, response); } public String getServletInfo() { return "Short description"; } } Step7:-Create a servlet named PostMessage.java This servlet is used to post message.
    • PostMessage.java package web; import import import import import import import import import import import import import ejb.NewsEntity; java.io.*; java.net.*; javax.jms.Connection; javax.annotation.Resource; javax.jms.ConnectionFactory; javax.jms.JMSException; javax.jms.MessageProducer; javax.jms.ObjectMessage; javax.jms.Queue; javax.jms.Session; javax.servlet.*; javax.servlet.http.*; public class PostMessage extends HttpServlet { @Resource(mappedName = "jms/NewMessageFactory") private ConnectionFactory connectionFactory; @Resource(mappedName = "jms/NewMessage") private Queue queue; protected void processRequest(HttpServletRequest request, HttpServletResp onse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String title = request.getParameter("title"); String body = request.getParameter("body"); String email = request.getParameter("email"); String dob = request.getParameter("dob"); ull)) { if ((title != null) && (body != null) && (email != null) && (dob != n try { Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUT O_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(queu e); ObjectMessage message = session.createObjectMessage(); NewsEntity e = new NewsEntity(); e.setTitle(title); e.setBody(body); e.setEmail(email); e.setDob(dob); message.setObject(e); messageProducer.send(message); messageProducer.close(); connection.close(); response.sendRedirect("ListNews");
    • } catch (JMSException ex) { ex.printStackTrace(); } } PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet PostMessage</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>EJB Servlet PostMessage at </h1>"); out.println("<hr></hr>"); out.println("<form>"); out.println("Name:<input type='text' name='title'><br/><br/>"); out.println("E-mail:<input type='text' name='email'><br/><br/>"); out.println("Dob:<input type='text' name='dob'><br/><br/>"); out.println("Address: <textarea name='body'></textarea><br/><br/>" ); out.println("<input type='submit' value='Submit'><br/>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } protected void doGet(HttpServletRequest request, HttpServletResponse resp onse) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse res ponse) throws ServletException, IOException { processRequest(request, response); } public String getServletInfo() { return "Short description"; } } Output of the program
    • EJB lookup example This examples describes you the lookup method used in EJB. Bean30Remote.java:-This is the Remote interface which extends javax.ejb.EJBObject package. These are similar to RMI Remote interface. The use of remote interface is particularly helpful in providing business-specific functionality of an EJB. Here @Remote is the annotation used to declare the interface as Remote. Bean30Remote.java package ejb; import javax.ejb.Remote; @Remote public interface Bean30Remote {
    • String getMessage(); String getAddress(); } String getCompanyname(); Bean30Bean.java:-This is the bean of type session in which we have defined the body of the method which were declared in the interface named SessionBeanRemote.java.@Stateless is the annotation used to declare the bean as a session type. @Stateless(mappedName="Bean30"):-It is used to change the mapped name from Bean30Bean to Bean30.After this we will use Bean30 to look up the bean in our application client. Bean30Bean.java package ejb; import javax.ejb.Stateless; @Stateless(mappedName="Bean30") public class Bean30Bean implements Bean30Remote { } public String getMessage() { return "Roseindia.net"; } public String getAddress() { return "Sec-3,D-16/116,Rohini"; } public String getCompanyname() { return "Roseindia.net Pvt.Ltd."; } Main.java:-This is the client application from which we can access the methods which are defined in the bean. InitialContext ctx = new InitialContext():-InitialContext is the class which is used to find out the starting context for performing naming operations. Initial Context is used to lookup home interfaces with inside an EJB. Here all the naming convention are relative to context. Bean30Remote br = (Bean30Remote) ctx.lookup("Bean30"):-This is the method that is used to retrieve the named object i.e. ("Bean30"). Main.java
    • package ejbmodule30; import ejb.Bean30Remote; import javax.naming.InitialContext; public class Main { } public static void main(String[] args) throws Exception { InitialContext ctx = new InitialContext(); Bean30Remote br = (Bean30Remote) ctx.lookup("Bean30"); System.err.println("================================="); System.err.println("EJB message is:" + br.getMessage()); System.err.println("Company name is:" + br.getCompanyname()); System.err.println("Address is:" + br.getAddress()); System.err.println("================================="); } Output of the program ================================= EJB message is:Roseindia.net Company name is:Roseindia.net Pvt.Ltd. Address is:Sec-3,D-16/116,Rohini ================================= EJB life cycle method The various stages through which an enterprise bean go through its lifetime is known as the life cycle of EJB. Each type of enterprise bean has different life cycle. Here we are telling you about the lifecycle of message driven bean. This type of bean follow three steps: 1)setMessageDrivenContext:-This method is used to pass the context object to the instance. 2)ejbCreate:-This method is generated automatically whenever a new enterprise bean is created. 3)ejbRemove:-At this stage the bean instance is ready to move for the garbage collection. em.persist(newsEntity):-This method makes an entity instance that is managed and persistence. em.merge(newsEntity):-By using this method we can merge the state of the given entity into the current persistence context.
    • em.remove(em.merge(newsEntity)):-This method is used for removing the entity instance. Here is the program denoting life cycle of message driven bean. package ejb; import import import import java.util.List; javax.ejb.Stateless; javax.persistence.EntityManager; javax.persistence.PersistenceContext; @Stateless public class NewsEntityFacade implements NewsEntityFacadeLocal { @PersistenceContext private EntityManager em; public void create(NewsEntity newsEntity) { em.persist(newsEntity); } public void edit(NewsEntity newsEntity) { em.merge(newsEntity); } public void remove(NewsEntity newsEntity) {em.remove(em.merge(newsEntity)); }} EJB Interfaces Interface in java means a group of related methods with empty bodies. EJB have generally 4 interfaces. These are as follows 1)Remote interface:- Remote interface are the interface that has the methods that relate to a particular bean instance. In the Remote interface we have all get methods as given below in the program. This is the interface where all of the business method go.javax.ejb.Remote package is used for creating Remote interface. package ejb; import javax.ejb.Remote; @Remote public interface Bean30Remote {
    • String getMessage(); String getAddress(); String getCompanyname(); } 2)Local Interface:-Local interface are the type of interface that are used for making local connections to EJB.@Local annotation is used for declaring interface as Local. javax.ejb.Local package is used for creating Local interface. package ejb; import javax.ejb.Local; @Local public interface NewSessionLocal { } 3)Home Interface:-Home interface is the interface that has methods that relate to all EJB of a certain class as a whole. The methods which are defined in this Interface are create() methods and find() methods . The create() method allows us to create beans. find() method is used in Entity beans. import javax.ejb.EJBHome; import javax.ejb.CreateException; import java.rmi.RemoteException; public interface Bean30RemoteHome extends EJBHome{ public Bean30Remote create() throws CreateException, RemoteException; } 4)Localhome Interface:-The local interfaces extend the following interfaces. These interfaces are generally for use by clients javax.ejb.EJBLocalObject - for the Object interface javax.ejb.EJBLocalHome - for the Home interface
    • package ejb; import javax.ejb.EJBLocalHome; import javax.ejb.CreateException; public interface NewSessionLocalHome extends EJBLocalHome { public NewSessionLocal create() throws CreateException; } EJB Insert data The program given below describes you the way to insert data into the database using EJB. The steps involved in inserting data are as :1)Create an interface named AccountStatusRemote.java AccountStatusRemote.java :-This is the Remote Interface for the Bean. Here we have used @Remote annotation to declare the class as a Remote Interface. The use of annotation here is that through it we can create a java source file which contain the bean implementation logic. String getStatus(); String getAddress(); Integer getInsert(); :-These are the method which is to be defined in the Bean and is called in the client application. AccountStatusRemote.java package bean; import javax.ejb.Remote; import java.util.*; @Remote public interface AccountStatusRemote { String getStatus(); String getAddress(); Integer getInsert(); } 2)Create a Bean named AccountStatusBean.java
    • AccountStatusBean.java:-This is the session bean we have created. By session bean we mean the bean which act as an agents to the client. it is generally used in controlling the business process and filling the gaps between the data of the entity beans. Here @Stateless is the session type. @RolesAllowed(value = {"USERS"}):-This is also the annotation which means that only users in the security role USERS can access the method declared in the Bean . @SuppressWarnings:-SuppressWarnings are the warning which is to fix the cause of the warning. AccountStatusBean.java package bean; import import import import java.sql.*; java.util.*; javax.annotation.security.RolesAllowed; javax.ejb.Stateless; @Stateless public class AccountStatusBean implements AccountStatusRemote { private String name = "Roseindia.net"; private String address = "sec-3,D-16/116,Rohini"; private int insert; @RolesAllowed(value = {"USERS"}) public String getStatus() { return "Name of the company is: " + name; } public String getAddress() { return "Address of the company is: " + address; } @SuppressWarnings(value = "unchecked") public Integer getInsert() { Connection con = null; String url = "jdbc:mysql://192.168.10.75:3306/"; String dbName = "komal"; String driver = "com.mysql.jdbc.Driver"; int val = 0; String userName = "root"; String password = "root"; try { Class.forName(driver).newInstance(); con = DriverManager.getConnection (url + dbName, userName, password); Statement st = con.createStatement(); val = st.executeUpdate("INSERT INTO employees VALUES ('ABC','CDE','Rohini','indian')");
    • st.close(); } catch (Exception e) { System.out.println(e); } return val; } } 3)Create a client application named Main.java Main.java:-This is the client application through which we can access the methods which are defined in the bean. @EJB:-This is the annotation that configure the EJB values for a field or a method. Normally this annotation is a Resource annotation where it is known that the resultant is an EJB interface. private static AccountStatusRemote accountStatusBean:-By this we have created an instance of the interface AccountStatusRemote . Main.java package secure; import bean.AccountStatusRemote; import javax.ejb.EJB; import java.util.*; public class Main { @EJB private static AccountStatusRemote accountStatusBean; public static void main(String[] args) { System.out.println(accountStatusBean.getStatus()); System.out.println(accountStatusBean.getAddress()); System.err.println("====================================="); System.err.println("Data inserted successfully"); System.err.println(accountStatusBean.getInsert()+ " rows affected"); } } Output of the program Name of the company is: Roseindia.net Address of the company is: sec-3,D-16/116,Rohini ===================================== Data inserted successfully
    • 1 rows affected EJB deployment descriptor Deployment descriptor is the file which tells the EJB server that which classes make up the bean implementation, the home interface and the remote interface. it also indicates the behavior of one EJB with other. The deployment descriptor is generally called as ejb-jar.xml and is in the directory META-INF of the client application. In the example given below our application consists of single EJB .Here the node <?xml version="1.0" encoding="UTF-8"?> <application-client version="5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/applicationclient_5.xsd"> <description>Accessing Database Application</description> <display-name>Secure-app-client</displayname><enterprise-beans> <session> <ejb-name>secure</ejb-name> <home>org.glassfish.docs.secure.secureHome</home> <remote>org.glassfish.docs.secure.secure</remote> <ejb-class>org.glassfish.docs.secure.secureBean</ejb-
    • class> <session-type>Stateless</session-type> </session> </enterprise-beans> </application-client> <ejb-name>secure</ejb-name>:-This is the node that assigns the name to the EJB. <description>Accessing Database Application</description>:-This node gives the brief description about the Ejb module created. <session-type>Stateless</session-type>:-This node assigns the Session bean as stateless or stateful. Here stateless means to say accessing Remote interface. EJB create method In this tutorial we are describing you about the EJB create method. The create() method is used for creating the EJBean. The other methods which are used in the program given below .. private EntityManager em:-Defines an Interface instance. The interface Entity manager is associated with the persistence context. em.persist(newsEntity):-This method makes an entity instance managed and persistent. em.merge(newsEntity):-This method merge the state of the given entity into the current persistence context. em.remove(em.merge(newsEntity)):-By using this method we can remove the entity instance. em.find(ejb.NewsEntity.class, id):-This methods find the entity instance by the primary key. Here primary key is id. package ejb; import import import import java.util.List; javax.ejb.Stateless; javax.persistence.EntityManager; javax.persistence.PersistenceContext; @Stateless
    • public class NewsEntityFacade implements NewsEntityFacadeLocal { @PersistenceContext private EntityManager em; public void create(NewsEntity newsEntity) { em.persist(newsEntity); } public void edit(NewsEntity newsEntity) { em.merge(newsEntity); } public void remove(NewsEntity newsEntity) { em.remove(em.merge(newsEntity)); } public NewsEntity find(Object id) { return em.find(ejb.NewsEntity.class, id); } public List findAll() { return em.createQuery("select object(o) from NewsEntity as o").getRes ultList(); } } EJB container services The EJB container is a container that deploys EJB automatically when Web Server is started. All of the entity objects live in container during its creation to removal. We can deploy more than one entity beans in a container. When the entity bean is deployed in the container the work of the container is to provide a home interface for the entity bean. This home interface allows a client in removing, creating and finding entity objects. It also helps in executing home interface business methods that are not specific to a particular entity bean object. JNDI(Java Naming and Directory Interface) is the standard interface by which the client can look up the entity bean's home interface. The table given below illustrates the EJB container services:-
    • EJB Hello world example Creating and testing the "Hello World" Example is the very first step towards learning of any application or programming language . In the given example we are going to show you, how to create your first hello world example in EJB and testing it. You can also create a hello world example to test your EJB environment setup. This simple application will required three different files to print the message. 1. SessionBeanRemote.java:- This is the Remote interface which extends javax.ejb.EJBObject package. These are similar to RMI Remote interface. The use of remote interface is particularly helpful in providing business-specific functionality of an EJB.Here @Remote is the annotation used to declare the interface as Remote. String getAddress(); String getCompanyname(); String getResult():-These are the methods which is to be defined in the bean. 2. SessionBeanBean.java:-This is the bean of type session in which we have defined the body of the method which were declared in the interface named SessionBeanRemote.java.@Stateless is the annotation used to declare the bean as a session type. 3. Main.java:-This is the client application from which we can access the methods which are defined in the bean.@EJB is the annotation used for configuring the EJB values for a field and method. SessionBeanRemote.java package ejb; import javax.ejb.Remote; @Remote public interface SessionBeanRemote { String getResult(); String getAddress(); String getCompanyname(); } SessionBeanBean.java
    • package ejb; import javax.ejb.Stateless; @Stateless public class SessionBeanBean implements SessionBeanRemote,SessionBeanLocal { public String getResult() { return "Hello World"; } public String getAddress() { return "Sec-3,D-16/116,Rohini"; } public String getCompanyname() { return "Roseindia.net Pvt.Ltd."; } } Main.java package enterpriseappee5; import ejb.SessionBeanRemote; import javax.ejb.EJB; public class Main { @EJB private static SessionBeanRemote sessionBeanBean; public static void main(String[] args) { System.out.println("Displaying Message using EJB:"); System.out.println("================================="); System.err.println("Name of the Company is : =" + sessionBeanBean.get Companyname()); System.err.println("Address of the Company is : =" + sessionBeanBean. getAddress()); System.err.println("Message is : =" + sessionBeanBean.getResult()); System.out.println("================================="); } } Output of the program Displaying Message using EJB: ================================= Name of the Company is : =Roseindia.net Pvt.Ltd. Address of the Company is : =Sec-3,D16/116,Rohini Message is : =Hello World =================================
    • EJB directory structure The tutorial is going to explain the standard directory structure of an EJB application . The figure given below is taken of Netbeans IDE. Here in the given figure NewsApp is the application name of the project which we have created. The other files which are created are described below:MANIFEST.MF:-This is the file which provides meta-information for the JAR. This file is a standard component of a JAR file. It is used to extend the class path that is being used by the EJB module. NewsApp-ejb.jar:-This is the jar file which is used for compressing, packaging, and delivering several files together. The use of the JAR file in EJB is to package all the interfaces and classes that are associated with beans into one file. This file contain the following files :1) XML deployment descriptor 2) bean classes 3) remote and home interfaces 4) primary key class 5) interfaces NewsApp-war.war:-This is the file in which we deploy the ejb remote interfaces and the stub classes .This file includes the EJB client classes NewsApp-ejb:-This is the EJB module where we have stored beans and interfaces. NewsApp-war:-This is the web module for our project. Here we have created the servlet and JSP pages. Figure: EJB Directory Structure in NetBeans
    • Above given is the standard directory structure of the Enterprise Java Bean application. Just follow the above mentioned steps and test your EJB application using NetBeans.
    • Deleting a Row from SQL Table Using EJB In the given example of Enterprise Java Bean, we are going to delete a row from the SQL Table. Find out the steps given below that describes how to delete a particular row from the database table using EJB. The steps involved in this process are as :1)Create an interface named AccountStatusRemote.java AccountStatusRemote.java :-This is the Remote Interface for the Bean. Here we have used @Remote annotation to declare the class as a Remote Interface. The use of annotation here is that through it we can create a java source file which contain the bean implementation logic. String getStatus(); String getAddress(); String getUpdate();:-These are the method which is to be defined in the Bean and is called in the client application . AccountStatusRemote.java package bean; import javax.ejb.Remote; import java.util.*; @Remote public interface AccountStatusRemote { String getStatus(); String getAddress(); } String getUpdate(); 2)Create a Bean named AccountStatusBean.java AccountStatusBean.java:-This is the session bean we have created. By session bean we mean the bean which act as an agents to the client. it is generally used in controlling the business process and filling the gaps between the data of the entity beans. Here @Stateless is the session type. @RolesAllowed(value = {"USERS"}):-This is also the annotation which means that only users in the security role USERS can access the method declared in the Bean . Main.java:-This is the client application through which we can access the methods which are defined in the bean.
    • @EJB:-This is the annotation that configure the EJB values for a field or a method. Normally this annotation is a Resource annotation where it is known that the resultant is an EJB interface. private static AccountStatusRemote accountStatusBean:-By this we have created an instance of the interface AccountStatusRemote . AccountStatusBean.java package bean; import import import import java.sql.*; java.util.*; javax.annotation.security.RolesAllowed; javax.ejb.Stateless; @Stateless public class AccountStatusBean implements AccountStatusRemote { private String name = "Roseindia.net"; private String address = "sec-3,D-16/116,Rohini"; private String Update; @RolesAllowed(value = {"USERS"}) public String getStatus() { return "Name of the company is: " + name; } public String getAddress() { return "Address of the company is: " + address; } @SuppressWarnings(value = "unchecked") public String getUpdate() { Connection con = null; String url = "jdbc:mysql://192.168.10.75:3306/"; String dbName = "komal"; String driver = "com.mysql.jdbc.Driver"; String updateString=null; String userName = "root"; String password = "root"; try { Class.forName(driver).newInstance(); con = DriverManager.getConnection(url + dbName, userName, password ); Statement st = con.createStatement(); updateString="delete from employees where st.executeUpdate(updateString); st.close(); } } catch (Exception e) { } return updateString ; First_Name='A'";
    • } Output of the program Name of the company is: Roseindia.net Address of the company is: sec-3,D-16/116,Rohini ===================================== Data updated successfully : See sql table to verify delete from employees where First_Name='A' Accessing Database using EJB This is a simple EJB Application that access the database. Just go through the EJB example given below to find out the steps involved in accessing Database. Creating a simple Database driven application in EJB 1)Create an interface named AccountStatusRemote.java AccountStatusRemote.java :-This is the Remote Interface for the Bean. Here we have used @Remote annotation to declare the class as a Remote Interface. The use of annotation here is that through it we can create a java source file which contain the bean implementation logic. String getStatus(); String getAddress(); List getData();:-These are the method which is to be defined in the Bean and is called in the client application. AccountStatusRemote.java package bean; import javax.ejb.Remote; import java.util.*; @Remote public interface AccountStatusRemote { String getStatus(); String getAddress();
    • } List getData(); 2)Create a Bean named AccountStatusBean.java AccountStatusBean.java:-This is the session bean we have created. By session bean we mean the bean which act as an agents to the client. it is generally used in controlling the business process and filling the gaps between the data of the entity beans. Here @Stateless is the session type. @RolesAllowed(value = {"USERS"}):-This is also the annotation which means that only users in the security role USERS can access the method declared in the Bean .This is to be declared in the the sun-application.xml file. <security-role-mapping> <role-name>USERS</rolename> <groupname>bank_users</groupname> </security-role-mapping> @SuppressWarnings:-SuppressWarnings are the warning which is to fix the cause of the warning. AccountStatusBean.java package bean; import import import import java.sql.*; java.util.*; javax.annotation.security.RolesAllowed; javax.ejb.Stateless; @Stateless public class AccountStatusBean implements AccountStatusRemote { private String name = "Roseindia.net"; private String address = "sec-3,D-16/116,Rohini"; private List list = new ArrayList(); @RolesAllowed(value = {"USERS"}) public String getStatus() { return "Name of the company is: " + name; } public String getAddress() { return "Address of the company is: " + address;
    • } @SuppressWarnings(value = "unchecked") public List getData() { Connection con = null; String url = "jdbc:mysql://192.168.10.75:3306/"; String dbName = "komal"; String driver = "com.mysql.jdbc.Driver"; String userName = "root"; String password = "root"; try { Class.forName(driver).newInstance(); con = DriverManager.getConnection(url + dbName, userName, passwor d); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select* from employees"); HashMap row; while (rs.next()) { row = new HashMap(); row.put("First_Name", rs.getString(1)); row.put("Last_Name", rs.getString(2)); row.put("Address",rs.getString(3)); row.put("Nationality",rs.getString(4)); list.add(row); } st.close(); } catch (Exception e) { e.printStackTrace(); } return list; } } 3)Create a client application named Main.java Main.java:-This is the client application through which we can access the methods which are defined in the bean. @EJB:-This is the annotation that configure the EJB values for a field or a method. Normally this annotation is a Resource annotation where it is known that the resultant is an EJB interface. private static AccountStatusRemote accountStatusBean:-By this we have created an instance of the interface AccountStatusRemote . Main.java package secure; import bean.AccountStatusRemote; import javax.ejb.EJB;
    • import java.util.*; public class Main { @EJB private static AccountStatusRemote accountStatusBean; public static void main(String[] args) { System.out.println(accountStatusBean.getStatus()); System.out.println(accountStatusBean.getAddress()); s" List list = accountStatusBean.getData(); HashMap row; System.out.println("First_Name" + "t" + "Last_Name" + "t" + "Addres + "tt" + "Nationality"); System.out.println("=============================================; " ); for (int i = 0; i < list.size(); i++) { row = (HashMap) list.get(i); String a = (String) row.get("First_Name"); String s = (String) row.get("Last_Name"); String b = (String) row.get("Address"); String d = (String) row.get("Nationality"); System.out.println(a + "tt" + s + "tt" + b + "tt" + d); } System.out.println("============================================="); } } Output of the program Name of the company is: Roseindia.net Address of the company is: sec-3,D-16/116,Rohini First_Name Last_Name Address Nationality ============================================================== Girish Tewari Rohini Indian Komal Singh Rohini Indian Sandeep kumar Rohini Indian Amit Singh Rohini Indian Girish Tewari Rohini Indian Darshan Tewari Rohini Indian ==============================================================