YOUR FEEDBACK
JavaOne 2008: Chris Keene's Prescription for Curing the Java Flu
Rob wrote: I have to agree with Chris - I have been a developer and Java a...
SOA World Conference
Virtualization Conference
$200 Savings Expire May 16, 2008... – Register Today!

2007 West
GOLD SPONSORS:
Active Endpoints
Your SOA Needs BPEL for Orchestration
BEA
Virtualized SOA: Adaptive Infrastructure for Demanding Applications
Nexaweb
Overcoming Bandwidth Challenges with Nexaweb
TIBCO
What is Service Virtualization?
SILVER SPONSORS:
WSO2
Using Web Services Technologies and FOSS Solutions
Click For 2007 East
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts

SYS-CON.TV
TOP THREE LINKS YOU MUST CLICK ON


Shared Sessions Using EJBs

Digg This!

The Problem:
We have a J2EE application where clients with the same userid need to share the session data that is maintained on the server side. In addition, clients aren't just Web clients, but applets and applications as well. How should we implement that?

The Solution:
This is a typical problem when writing J2EE applications, since the J2EE APIs don't provide an out-of-the-box solution for this.

The Servlet API typically used with Web clients provides nice ways to manipulate the client's session and the data related to it, but doesn't offer a direct means of sharing the session data between clients (for security reasons). It's also somewhat limited to Web clients only.

Enterprise Java Beans (EJBs), on the other hand, could be used to implement this quite easily, since they work with any type of Java clients. It may be a bit heavyweight, but programmatically it's quite straightforward, so let's take a closer look at it.

A stateless Session EJB easily comes to mind, since it enables the client's state on the server-side. Session EJBs (or instances of them) are also sharable between client sessions by passing the reference to them (or actually into their remote interface) within the application, like a servlet. In order to pass references between sessions, the application needs to explicitly maintain a look-up table of the references for each client identified, so it knows to relate the user (along with userid) with the proper instance of a Session EJB when that already exists.

However, that's pretty much what WLS does when Entity EJBs are used - or at least there is a lot of similarity in this scenario. It keeps the reference to each Entity EJB instantiated in the memory and then passes it (or the reference to the EJB's Remote Interface of it) to the client, which requests it via the bean's findByPrimaryKey method of the Home Interface. If the Entity EJB is not found since it does not yet exist, it can be created on the fly to be related with the client and its session the first time the client logs in. Therefore, Entity EJB instances are easily shared, even between clients not running in the same JVM.

Note: an Entity EJB instance does not always refer to a row in the database; it can be totally virtual. But since Entity Beans are especially good at accessing persistent data, it gives us a chance to provide persistency for our sessions (and the data in them) in case of application crashes, etc.

To locate the session references for clients, use of the findByPrimaryKey method is logical, since the primary key is actually the client's userid for the application. The only thing that's left for the application to do is the appropriate authentication of clients, before they can access the session data via the bean's findByPrimaryKey method.

Creating the Sample Application
Now we're going to design the sample application. First, we divide the application into four parts:

1.   UserSession: Class containing the user's session data in Hashtable plus some other information like the user's userId. It utilizes the Serializer class for session data persistency (see below). UserSession class can be used locally at first, and then remotely via the Entity EJB "wrapper" to be easily shared with multiple clients of many types (JSP and Java clients, etc.).

2.   UserSessionSerializer: Class for session data persistency. Java serialization is used instead of JDBC in the first step to keep this as simple as possible. Later on, we can replace this with pool-oriented JDBC-based persistency for distributed larger-scale applications. There's always one file on the disk per session - even if it's shared by multiple clients -and an EJB instance accessing it.

3)   EJB wrapper: For distributed UserSession objects. It's subclassed from the UserSession. As an Entity EJB, it consists of three separate classes in the sharedSessionSample.remote package (others are stored in the package "local").

4)   Sample JSP client using SessionData objects, first locally and then remotely

Next, we create a package named sharedSession-Sample.local, and place two classes, the UserSession class and the UserSessionSerializer class, in it. The UserSession class has three class members (variables) and methods:

Members:

protected String path;
protected String userId;
protected Hashtable sessionData;
Methods (the throw definitions are not shown):

public void create(String userId)
public void load(String userId)
public void save()
public void remove()
public Object getValue(String name)
public void setValue(String name, Object object)
public void removeValue(String name)
public Hashtable getValues()
public void setValues(Hashtable values)
The class member path defines the directory where the serialized sessions are stored on the disk and loaded from. Typically, the path is the same for all sessions. The userId defines the owner of the session and is used to name the file when serialized (that is, a session of the user "John" will be serialized as a file named "John.session" onto the disk into the specified directory). The Hashtable sessionData holds the session named values. Note: we don't actually store the whole UserSession when serialized, just the sessionData member object.

Getters and Setters
Methods are constructed so they can easily be extended to work as an Entity EJB. The create() method is used to create a new, empty session, which can be saved by save() method after one or more values have been set to the session via the setters setValue() or setValues(). The difference between these setters is obvious: the first one sets one named value at the time, whereas the latter sets all the values for the session (passed as a Hashtable). It is the same with getters getValue() and getValues(). The method load() is used to load an existing session and its data from the disk, and throws an exception if not found (in that case it should probably be created), as opposed to the method create(), which throws an exception when the session already exists.

The setters do not save() automatically; one has to be called explicitly by the client. However, that's implemented to the Entity EJB.

One thing to note is that the UserSession is implemented in such a way that getValues() and setValues() work "by value" instead of "by reference." It's the preferred approach here, to avoid unintentional changes to the session data on JSPs (I've seen it happen many times with objects like a Hashtable). The actual code is shown in Listing 1 (the code for this article may be found online at www.sys-con.com/weblogic/sourcec.cfm.

The methods create(), load(), and save() use the SessionSerializer class, which has no member variables, just static methods:

public static void serialize(String path, String userId,
Hashtable sessionData)
public static Hashtable deserialize(String path, String userId)
public static void remove(String path, String userId)
The serialize() method is used to save (using Java serialization) the Hashtable containing the named session values onto the disk. Deserialize() is the opposite to serialize() in order to instantiate the Hashtable object from existing session values on the disk. The remove() method can delete serialized session values from the disk.

Shown below are examples of the implementation of SessionSerializer's serialize() method and the UserSession's save() method to show how the use of the SessionSerializer has been implemented.

The SessionSerializer's serialize method:

public static void serialize(String path,
String userId,
Hashtable sessionData) throws Exception
{
FileOutputStream ostream =
new FileOutputStream(path + "/" + userId + ".session");
ObjectOutputStream p = new ObjectOutputStream(ostream);
p.writeObject(sessionData);
ostream.close();
}
The UserSession's save() method:

// Note that the path needs to be set first,
before calling save
public void save() throws Exception
{
UserSessionSerializer.serialize(path, userId,
sessionData);
}
Next, the files are compiled into Java classes. Once we get the WLS running and these files copied into the classpath, the sample JSP page can be created to test accessing session values locally (that is, within the same JVM) as the first part of the sample. It uses the setValue() method for incrementing an integer value "i" for the user; if a user isn't specified in the HTTP request it is considered to be "JohnDoe." There's no authentication, which in real life would be needed (the standard Web app definition can be used; see Listing 2).

Alternatively, the method setValues() (instead of setValue()) can be used to increment the value for "i" as shown below:

int i = 0;
Hashtable values = userSession.getValues();
if(values.get("i") != null)
{
i = ((Integer) values.get("i")).intValue();
i++;
}
values.put("i", new Integer(i));
userSession.setValues(values);
Conversion
Now that the classes for accessing the session values locally have been implemented and tested, they're prepared for remote use by both local and remote clients by being converted into an Entity EJB. That also enables easy sharing of the session data between clients, since the Entity EJB takes care of synchronization between client method calls. In addition, using bean-managed persistence (BMP) and Java serialization, we're able to serialize any named values in the Hashtable without having to worry about JDBC datatypes and so on in our EJB.

However, normal rules apply when writing (updating) the same session values from two or more clients simultaneously; there's no way that the EJB could prevent overwriting of data in those cases. For that reason, make sure to add an identifier (e.g., a transaction id or timestamp from the file system, etc.) that's sent between the client and the server to indicate if the session data has been updated elsewhere (another client) when doing updates from multiple clients to the same session and its data.

In order to enable the local.UserSession for remote use, three EJB classes are implemented:

  • UserSessionHome: the home interface of the entity EJB
  • UserSession: the remote interface of the entity EJB
  • UserSessionBean: the bean implementation class that is subclassed from the UserSession of the local package

    All classes are placed in a package named sharedSessionSample.remote to differentiate them from the local classes (partly with same name).

    The UserSessionHome interface defines two methods to create new and locate existing sessions remotely:

    public UserSession create(String userId)
    public UserSession findByPrimaryKey(String userId)
    Since the UserSessionBean (which we'll see in a minute) is subclassed from the local.UserSession, the remote.UserSession remote interface is used to publish the methods of the local.UserSession for remote use (the throw definitions are not shown):

    public Object getValue(String name)
    public void setValue(String name, Object object)
    public void removeValue(String name)
    public Hashtable getValues()
    public void setValues(Hashtable values)
    The EJB implementation class remote. User-SessionBean has only one member variable - along with those that are inherited from the local. UserSession class - and the following methods:

    Members:

    private transient EntityContext ctx;
    Methods (some standard EJB methods and throw definitions are not shown):

    public String ejbCreate(String userId)

    public String ejbFindByPrimaryKey(String userId)
    public void ejbLoad()
    public void ejbStore()
    public void ejbRemove()
    protected void setPath()

    The ejbCreate() method is used to create a new session data object in case it doesn't exist yet. This object is created by calling the create() method of itself inherited from the local.User-Session class. If the creation succeeds (that is, no session exists already with the given userId), the userId is returned and the EJB is instantiated by the WLS for shared and remote use. If the session already exists, a standard DuplicateKeyException is thrown (see Listing 3).

    The setPath() method is used to read the serialization directory path from EJBs' properties and is implemented as follows:

    try
    {
    InitialContext ic = new InitialContext();
    setPath((String)
    ic.lookup("java:/comp/env/storagePath"));

    }
    catch (NamingException ne)
    {
    // defaults to '/sessions' directory under WebLogic
    // root dir, if not defined. For clustering, use a shared dir.
    setPath("./sessions");
    }

    Note that in the case of clustering, which is a nice feature of WebLogic and especially typical of high load sites, the directory path should be a shared resource for all application server instances - otherwise, the clustering wouldn't work properly.

    Load and Store Methods
    The opposite of ejbCreate(), the findByPrimaryKey() is used to locate an existing session on the server. First, the method tries to find a serialized session on the disk by calling its own load() method, inherited from the local.UserSession class, and throws ObjectNotFoundException if it is not found. However, if the session is found (the load() succeeds), it returns the userId, from which the server knows to instantiate the EJB by calling the ejbLoad() method implicitly, resulting in the loading of the actual session data from the disk (see Listing 4).

    The same load() method is used for two purposes: first, for trying to locate an existing session from the disk when doing the findByPrimary-Key(), and then for loading (deserializing) the actual data when the EJB is instantiated by the server (the ejbLoad() method). This may not be the best practice, but it works (We could have a separate find method instead, but to limit the size of the code we omit that).

    The ejbStore() method is called automatically by the server when any setter of the EJB is called. Therefore, there's no need for an explicit save() method in the EJB. We could easily add it for optimization reasons later on, but it's hardly needed here. Thus, the ejbStore() method is as follows:

    try
    {
    save();
    }
    catch(Exception e)
    {
    throw new EJBException(e.toString());
    }
    Finally, the ejbRemove() method, which can be used to delete existing session data:

    try
    {
    remove();
    }
    catch(Exception e)
    {
    throw new EJBException(e.toString());
    }
    Now that the EJB is ready, it's time to modify the JSP for using the EJB instead of the local class. In Listing 5, the UserSession is accessed remotely to do basically the same increment as in Listing 2, but now it enables the client (a standalone Java application, for example) to run in a separate JVM from the server.

    In order to set more than one value at a time, the setValues() method can be used, as in this example of incrementing:

    int i = 0;
    Hashtable values =
    userSession.getValues();
    if(values.get("i") != null)
    {
    i = ((Integer)
    values.get("i")).intValue();
    i++;
    }
    values.put("i", new Integer(i));

    // Put other values as well and finally set them
    userSession.setValues(values);

    For optimization, the JNDI lookup for the EJB could be done only once and stored in the WebLogic Server's memory with application scope (see Listing 6).

    In addition, we could also cache the UserSession object itself to the user's HTTP session once found, in order to avoid subsequent findByPrimaryKey() calls in case of JSP. Of course, for Java clients like applets, the caching isn't needed (used as a local object). The code for caching is shown in Listing 7.

    About Mika Rinne
    Mika Rinne (not mike - it's a Finnish male name even though it ends to 'a' :-) ) Age 31 Senior Consultant, BEA Systems Inc. 2,5 years @BEA Married (actually also divorced but now having a new girlfriend), 1 son, age 7 Working with Web and related stuff since -95, started programming at the age of 13 (1983) Built Internet (WWW) and BEA TUXEDO based on-line ticket selling service 95 being the first of it's kind at least in Scandinavia (maybe Europe) Skills BEA WebLogic, BEA Portal 4, Java, J2EE & stuff

  • Davide Parisi wrote: It's an helpful tips, but the code it's not complete, can we publish the entire source?
    read & respond »
    BEA WEBLOGIC LATEST STORIES
    Microsoft To Keynote 4th International Virtualization Conference & Expo
    Mike Neil is general manager for virtualization strategy in the Windows Server Division at Microsoft. Mike is focused on the delivery of the Windows virtualization technology, including Windows Server 2008 Hyper-V, Microsoft Hyper-V Server and Virtual PC 2007. Mike also directs the tec
    3rd International Virtualization Conference & Expo: Themes & Topics
    From Application Virtualization to Xen, a round-up of the virtualization themes & topics being discussed in NYC June 23-24, 2008 by the world-class speaker faculty at the 3rd International Virtualization Conference & Expo being held by SYS-CON Events in The Roosevelt Hotel, in midtown
    Virtualization Meets DaaS - Desktop-as-a-Service
    After a $1.5 million angel round, Desktone, which was started in 2006 by Eric Pulier, who also started SOA Software, US Interactive and IVT, picked up $17 million in first-round funding about a year ago from Highland Capital Partners, SoftBank Capital, Citrix Systems and the China-base
    Engelbart's Usability Dilemma: Efficiency vs Ease-of-Use
    The mouse was the original idea of Doug Engelbart who was the head of the Augmentation Research Center (ARC) at Stanford Research Institute. Engelbart's philosophy is best embodied, in my opinion, in the design of another device that he invented, the five-finger keyboard - with keys li
    Web 2.0 Is Fundamentally About Empowering People
    'Unlocking content to be remixed into new business value' is the driver of Web 2.0 in the enterprise, says Rod Smith, IBM VP of Emerging Internet Technologies, in this Exclusive Q&A with Jeremy Geelan on the occasion of IBM's release of a new technology created by IBM researchers, code
    Why Do 'Cool Kids' Choose Ruby or PHP to Build Websites Instead of Java?
    Here is a question that I have been pondering on and off for quite a while: Why do 'cool kids' choose Ruby or PHP to build websites instead of Java? I have to admit that I do not have an answer. Why do I even care? Because I am a Java developer. Like many Java developers, I get along w
    SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
    SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
    Click to Add our RSS Feeds to the Service of Your Choice:
    Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
    myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
    Publish Your Article! Please send it to editorial(at)sys-con.com!

    Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

    SYS-CON FEATURED WHITEPAPERS

    ADS BY GOOGLE
    BREAKING NEWS FROM THE WIRES
    AmberPoint Extends SOA Governance to Apache ServiceMix, BEA AquaLogic Service Bus 3.0, BEA WebLogic Integration, Cisco ACE XML Gateway, JBoss Enterprise Application Platform and Oracle Fusion
    AmberPoint announced today that it has extended the reach of its runtime SOA governance