Advertisment

Stateless Weather with EJB

author-image
PCQ Bureau
New Update

In the last issues, we have seen how to deploy the WebLogic platform and set up an application domain under it. One of the uses of the BEA WebLogic suite of tools is to develop enterprise applications. These applications comprise the distinctive functional layers of business logic, data and presentation. In Java, the business logic is encapsulated in something called 'beans', and given a rather exciting name, EJB (Enterprise Java Beans). EJB lets the developer focus on business issues rather than on security, connection pooling and threading, which are taken care of by the EJB container. Let's begin this episode by creating our own bean. Then we shall create and deploy a simple application to report the latest weather from four Indian metros. The code for the same is given on this month's

PCQEssential CD.

Advertisment

Enterprise Java Beans are of three types: session, entity and message driven. Here will focus on stateless-session bean and we'll take up entity

and message-driven beans in detail in the forthcoming issues.

Session beans are unique to a particular client session and cease to exist on termination of that session. These are of two types-stateless and stateful. Stateless beans know nothing of the execution other than the current invocation. Stateful beans, on the other hand, maintain states for the entire session.

Direct Hit!
Applies to: Java developers (Beginners/Intermediate)
USP: Use BEA WebLogic to develop and deploy EJB apps
Links:

http://e-docs.bea.com/wls 
On PCQEssential CD:

system\labs\weblogic
Advertisment

Entity beans are object-specific, persist in a relational database and refer to unique objects. Information can be retrieved even if the relevant server reboots. There are two types of entity bean persistence-bean managed and container managed. If a bean-managed persistence is used, the developer has to write the code to access the database. If container-managed persistence is used, the EJB container generates the required database access code.

Message driven bean allows client to send messages asynchronously while the session and entity beans support synchronous messages. When the client sends messages, it gets queued and message bean then processes it. In short, message driven bean are similar to stateless session beans but the way clients communicate with the beans is different. 

Our application





A complete EJB application comprises three parts: the remote interface, the local interface (called 'home interface') and the bean itself.

Advertisment

The home interface extends the EJBHome interface. The remote interface extends the EJBObject interface. Our bean will implement the SessionBean interface in a class. The bean class contains methods to instantiate, run and manage the life cycle of session beans. The whole application will be placed in a package called

'PCQWeather'.

The remote interface





The remote interface defines the business methods that the client needs to invoke and the implementation of these methods is in the bean class. The methods should throw remote exception. Remote exception will be thrown if there are any communication or system failure when client calls the business methods. Our remote interface is called Weather and defines two business methods: metro_name and metro_temp. metro_name will return the name of metro and metro_temp will return the temperature. Our code for this is in 'Weather.java' will look as follows.

WebLogic Builder validating deployment descriptor files

Advertisment

package com.PCQWeather;



public interface Weather extends EJBObject {


public String metro_name(String s) throws 


RemoteException;


public int metro_temp(int i) throws 


RemoteException;


}




The home interface





The home interface defines a method by which the client can create the bean (bean class). The create() method creates the bean, and its return type is the remote interface. This method may or may not have parameters. It should throw CreateException and RemoteException. CreateException will be thrown if there is an error creating the bean. RemoteException will be thrown if the client cannot locate the home interface. Our code for WeatherHome.java looks like this.

public interface WeatherHome extends EJBHome {



Weather create() throws CreateException, 


RemoteException;


}

Advertisment

The bean





The bean class implements the SessionBean interface and all the methods defined in our remote interface (Weather). The SessionBean interface has methods such as ejbActivate(), ejbPassivate() and setSessionContext() to name a few. These methods are not required by the stateless bean, but we need to define these methods (with no code) as per the J2EE specification. The setSessionContext() sets up the session for the bean. 

public class WeatherBean implements SessionBean {



private String metroname;


private int metrotemp;





public int metro_temp(int i) { metrotemp = i; }


public String metro_name(String s) { metroname = s };


public void ejbActivate() {} // blank function


.


}






The client





The Java client we write next will invoke our bean and provide the user interface at the client side. This can be either Web-based or console/GUI. Our example will use a console-based client and perform three tasks-locate the home interface, create the bean instance and finally invoke the remote methods to display the output.

Advertisment

The JNDI (Java Naming and Directory Interface) is a service that helps the client find the home interface. The getInitialContext() method creates an initial naming context in 'ctx' and then helps search the JNDI. We then search the JNDI through the lookup() function in the returned context, with the value we specify in WebLogic Builder while creating the deployment descriptor. This value is stored in the environment variable JNDI_NAME. The client needs to set up the context first by specifying two additional parameters-the INITIAL_CONTEXT_FACTORY, with the value 'weblogic .jndi. WLInitial Context Factory' and PROVIDER_URL to the location of the EJB application server ('t3://localhost:7001') where 't3' is an EJB protocol type.

Our code at this point looks like this.

Context ctx = getInitialContext();



.


try {


home = (WeatherHome) ctx.lookup(JNDI_NAME);


.


return context;


}





private Context getInitialContext() throws NamingException {


.


h.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");


h.put(Context.PROVIDER_URL, "t3://localhost:7001");


.


}











Advertisment

We then create an instance of the bean, using the create() method of that interface. Then, we use the narrow() method to access the home interface. The narrow method takes two parameters-the create function and the return type as a class. Finally, we call the business methods in the remote interface (metro_name and metro_temp in our case). When the bean is no longer needed, it can be removed from active server memory to free up resources. This is done by calling the interface's remove() method. Corresponding code will resemble our final extract below.

public void example() throws CreateException, 



RemoteException {


Weather w = (Weather) narrow(home.create(), Weather.class);


for (int i = 0; I < citi.length; i++)


System.out.println(w.metro_name(citi) + " temperature is " + w.metro_temp(temp));


.


w.remove();


.


private Object narrow(Object ref, Class c) { 


.


}


}


Compile and deploy





l You need to set the class path as


set classpath = c:\bea\weblogic81\server\lib\


weblogic.jar;c:\PCQWeather;%classpath%
 













- Create a folder called PCQWeather and put the Weather, WeatherHome and WeatherBean JAVA files in it. From the command prompt, compile the JAVA files and create the deployment JAR file using:

javac -d . *.java



jar -cvf deploy.jar com

- Now you need to create deployment descriptor files using WebLogic builder. It automatically creates two deployment descriptor files, weblogic-ejb-jar.xml and ejb.jar.xml. These files have information about the application and WebLogic specific environment properties. Discussing in detail about the file is beyond the scope of the article. 

- Now open the WebLogic Builder and open this deploy.jar (deploy.jar is created in PCQWeather) file by clicking File>Open. When prompted, select 'Yes' to create new descriptors. From the left-side pane, select WeatherBean. Note the JNDI name displayed on the right side under the 'General' tab. The JNDI name in the Java client should be the same as given in the WebLogic builder. Select the 'Advanced' tab and check ON the 'Enabled call by reference' option. Now, from the menu, open the Tools>Validate Descriptors. If you get an 'EJBC Successful' message all is fine, otherwise, you need to recompile the JAVA files. Save and close the Builder.

- Start the server as described in our last article and on the left side in the manager, select Deployments>EJB Modules. Select 'Deploy a new EJB module', browse to C:\PCQWeather and then open the deploy.jar file. Select the 'Target Module' button and then Deploy. You should get a message indicating success.

- To run, copy the WeatherClient.java file to the PCQWeather folder and execute

javac weatherclient.java



java com.PCQWeather.weatherclient

You can create similar applications to perform currency conversion, location and phone number lookups and so on.

Sushil Oswal

Advertisment