Академический Документы
Профессиональный Документы
Культура Документы
0 Tutorial
An application server is an application program that accepts connections in order to service
requests, by sending back responses.
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.
1 | Page
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).
2 | Page
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
system
of
records.
There
are
three
types through
which
two
Dirty read
Phantom read
Control mechanism: Mainly two mechanism are used to control the concurrency.
Optimistic Locking
Pessimistic Locking
3 | Page
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.
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.
4 | Page
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
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.
5 | Page
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.
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.
6 | Page
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.
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
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.
7 | Page
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() {
8 | Page
-----------}
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(){
-------}
Example:
public @interface Example{
String showSomething();
int num;
String name;
Usage:
@Example
(showSomething
9 | Page
"Hi!
How
you",
num=5,
name="zulfiqar"
// 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 using annotations should return a value, one of the types given below:
String
primitive
enum
Class
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.
Override
Depricated
Suppresswarnings
10 | P a g e
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.
11 | P a g e
means
we
can't
class Depricated_method
further
does
use
not
this
method
generate
any
any
more.
error. While
On
compiling
compiling
the
the
class
12 | P a g e
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.PARAMETER)?applicable
method.
13 | P a g e
to
the
parameters
of
@Target(ElementType.CONSTRUCTOR)?applicable to constructors.
14 | P a g e
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();
}
15 | P a g e
16 | P a g e
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;
}
17 | P a g e
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.
A session bean is the enterprise bean that directly interact with the user and
contains
the
business
logic
of
the
enterprise
application.
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.
18 | P a g e
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.
StatefulSessionBeans:
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
19 | P a g e
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
oftencalledtheconversationalstate.
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.
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.
20 | P a g e
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.
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.
21 | P a g e
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.
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.
22 | P a g e
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. Create the enterprise bean: CalculatorBean
2. Create the web client: WebClient
3. Deploy example onto the server.
4. 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 CalculatorRemotebusiness 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);
23 | P a g e
24 | P a g e
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"
<p>Enter
<input
method="POST">
first
type="text"
value:
name="num1"
size="25"></p>
<br>
<p>Enter
<input
second
type="text"
value:
name="num2"
size="25"></p>
<br>
<b>Seclect
<input
type="radio"
your
name="group1"
choice:</b><br>
value
="add">Addition<br>
type="radio"
name="group1"
value
="div">Division<br>
<p>
<input
25 | P a g e
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
CalculatorRemote
new
InitialContext();
calculator
(CalculatorRemote)ic.lookup("example/CalculatorBean/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();
26 | P a g e
calculator = (CalculatorRemote) ic
.lookup("example/CalculatorBean/remote");
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());
27 | P a g e
%>
<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>
28 | P a g e
apache-ant-1.7.0
JBoss 4.2.0
Make a directory structure. You can Click here to extract the readymade directory
structure according to this tutorial.
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"/>
29 | P a g e
30 | P a g e
</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="ejbjar.xml,weblogic-cmp-rdbms-jar.xml,weblogic-ejb-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/">
31 | P a g e
32 | P a g e
</web-app>
Put this file in the Stateless\code\deploymentdescriptors\web directory.
Put all .jsp files in the Stateless\code\web directory.
Put all .java files in the Stateless\code\src directory.
(iii) Start command prompt, and go to the Stateless\code directory. Then type the
command as:
C:\Stateless\code>ant build.xml
The Ant tool will deploy the example.ear file to the jboss4.2.0.GA\server\default\deploy directory.
V. Running the example Web Client
Open the web browser and type the following URL to run the application:
http://localhost:8080/example
33 | P a g e
Give values to the textbox and choose the desire option button as Addition then clicks
the Submitbutton to get the result.
34 | P a g e
35 | P a g e
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();
The class implements the business methods defined in the business interface.
javax.ejb.Stateful;
javax.ejb.Remote;
javax.ejb.Remove;
javax.ejb.*;
36 | P a g e
@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;
}
}
Implement
any
optional
life
cycle
callback
methods,
37 | P a g e
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
@PreDestroy
@PostActivate
The full source code for the WebClient.jsp program is given below.
38 | P a g e
39 | P a g e
40 | P a g e
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>
41 | P a g e
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.
42 | P a g e
allows
the
development
of
portable
and
message
based
applications.
JMS
43 | P a g e
1.
2. 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.
3. 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.
4. 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.
5. 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
44 | P a g e
object is known as the Consumer object. To get hold an object Session and
Destination are used.
6. 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.
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
45 | P a g e
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 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.
46 | P a g e
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:
47 | P a g e
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.
Session beans allow you to send JMS messages and to receive them
synchronously, but not asynchronously.
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.
48 | P a g e
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.MessageListenerinterface
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.
49 | P a g e
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
aQueueConnectionFactory 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:
50 | P a g e
try {
//client creates the connection, session, and message sender:
connection = factory.createQueueConnection();
session = connection.createQueueSession(false,
QueueSession.AUTO_ACKNOWLEDGE);
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();
}
}
51 | P a g e
In the given code of MessageClient application, the javax.jms.* package is imported for
extending
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(
);
52 | P a g e
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:
javax.annotation.Resource(@Resource):
The @Resource method specifies a dependence on an external resource, such as a JDBC
data
source
or
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. For example:
@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:
53 | P a g e
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!
The class must be defined as public and must contain a public constructor with no
arguments. It must not define the finalize method.
or
to
store
it
in
database.
54 | P a g e
processing
is
rolled
back,
the
message
will
be
redelivered.
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( );
55 | P a g e
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
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
namedmessage.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.
56 | P a g e
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
57 | P a g e