Getting the Streams Right

You should use classloader only for reading INSIDE a file like reading text from inside a text file or properties from inside a properties file. It is useful only for reading from text files etc. The file should be on the classpath . Loading a class means making the class available in your code. Getting a resource as stream means giving access to some “resource” from the classpath. Resource here is any other file other than java-classes.

classLoader = this.getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream(“com/mattiz/test/resources/”);

The above code is used to load a class such as a properties file or an xml file.
The input stream may be passed onto suitable constructors wherever permissible.
The getResourceAsStream is basic java. It reads resources from the classpath. There’s nothing servlet-ish about it. It would work the same with a standalone java application.

If you do want the file literally as a file (not to read it), then use classloader.getResource(). This returns a URL, which would look like this


if it is on the classpath.


Remove the leading file:/// and you have the path to the file.
This uses the same technique as getResourceAsStream but returns a URL instead of inputstream

For example here you use getResourceAsStream() to read from a file to load properties:

// the answer lies in not specifying the absolute/relative path of
// instead load the resource from the classpath using
// this is how to go about it
// create a package inside the EJB project called
//com/mattiz/test/resources/ or some name like that
// and put the file into it.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null)
classLoader = this.getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream(“com/mattiz/test/resources/”);
Properties sqlCache = new Properties();

For simple read access you would do the following where stream is an input stream

BufferedReader br = new BufferedReader(new InputStreamReader(stream));
//printing out contents if text file
while((line = br.readLine()) != null)
//iterate through the contents

The constructor of the transformer class which is used in xsl transformations takes an inputStream as a parameter directly. This input stream may be obtained from an xsl file using the getResourceAsStream() method.

JBoss Descriptor Files


The ejb-jar.xml is a deployment descriptor that is common to all application servers and after configuration supplies the application server container the information required to deploy the beans in the jar/ear files.
It describes the entity or session beans that are included in the application. It is also responsible for declaring those fields in entity beans that are container managed.
It may have the following skeletal structure:


Every ejb-jar.xml has exactly one


tag, which may contain


, or




tag contains the names of the home, remote and the bean class as well as some other info.


tag contains the descriptive name of the bean.
The tag contains the fully qualified name of the home class.


tag contains the fully qualified name of the remote class.


tag contains the fully qualified name of the bean class.


and are specific to session beans.
The tag states whether the session bean is stateless or stateful.
are specific to session beans and is used to specify whether transactions are container managed or bean managed.


is used to map the bean references used within the session bean.
tells whether it is a session or entity bean that is mapped.
In case of entity beans there is a tag that contains the fully qualified name for the entity bean’s primary key class.
This may be a primitive data type such as java.lang.String for a simple key or a fully qualified primary key class name for a compound key


tag declares whether the bean can call another bean, which calls the original bean.


tag contains a tag that describes the CMP fields in the entity bean.
Lastly the


tag contains the name of the primary key field (for simple pry key types) and is not required for compound keys. (In case the


specifies a primitive type such as java.lang.String.)


jboss.xml is a container specific configuration file that is used to define the jndi names for the beans in the package.

jaws.xml is required while deploying entity beans.
It maps a bean to a data table and the instance variables of a bean to the fields in the database.
Container managed finder methods are also described in jaws.xml


web.xml contains the descriptive names for the servlets in the application as well as the fully qualifed servlet name.
It also maps the servlet to a url pattern.
hostname is “localhost”
portnumber is “8080”
context (in application.xml) is for eg. “interest” (usually the same name as the .war file)
url-pattern (in web.xml) is for eg. /InterestServlet
so the url becomes

Struts- Why? What? How?

Application architecture for web applications has been evolving over the past decade. The Model View Controller (MVC) architecture has, in recent times evolved to be the de facto architecture for most web applications. Earlier, application developers went through a phase of first developing the framework usually as a combination of JSP, Servlets and Value Objects) before writing the application itself. There was a strong need for a reusable framework incorporating industry best practices to form the basis for web application development. Struts does an effective job of providing the pre packaged framework.

In addition to being a framework for MVC, Struts provides the following features to ease the developer’s job.

a. Custom tag libraries
b. Message repository (
c. Configurable user Input validation
d. Structured views using Tiles and Templates.
e. Reusable utility classes
f. Options for customizing all of the above specific needs

Struts can be used on any Servlet Engine that conforms to the Servlet 2.2 and JSP 1.1 Specification. It has been tested on most popular servers including WebSphere, Weblogic, Tomcat, iPlanet among others.

Struts essentially contains:

· A set of jar files
· A set of configuration files (conforming to the published DTDs)
These are to be included in the Application’s WAR file

The Application logic that developers write is in classes that extend base classes provided in the Struts jar files.
These are action classes and action forms.


Model: The model represents enterprise data and business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real world modeling techniques apply when defining the model.

View: The view renders the contents of a model. It accesses enterprise data through the model and specifies how that data should be presented. It is the view’s responsibility to maintain consistency in its presentation when the model changes. This can be achieved by using a push model, where the view registers itself with the model for change notifications, or a pull model, where the view is responsible for calling the model when it needs to retrieve the most current data.

Controller: The controller translates interactions with the view into actions to be performed on the model. In a stand-alone GUI client, user interactions could be button clicks or menu selections, whereas in a web application, they appear as GET and POST http requests. The actions performed on the model include activating business processes or changing the state of the model. Based on the user interactions and the outcome of the model actions, the controller responds by selecting an appropriate view. (This is configured in the struts-config.xml that sets the action servlet)

Struts implementation of MVC

Struts is pretty much a textbook implementation of MVC. The JSP is the view containing only display formatting. There is a single Servlet controller that services all requests and delegates requests to separate handler actions.
The form beans and java beans form the model part of the equation.

The process flow is described as follows:

The browser sends a request with information to be processed. The information delivered to the application comes in a “ form bean “ – a Java bean which maps that field to html controls on the view page. Struts populates the form bean with data automatically from information that has been entered by the user on the screen. Form bean data is available to the controller servlet and handler classes for processing.

The controller servlet does centralized processing that is common to all requests being serviced and then hands off control to individual handlers that do specific processing based on the actions being performed. The mapping of request URLs to Action handler classes is easily done using an XML configuration file struts-config.xml.

The handlers are tied to model components. They contain logic for interacting with java beans / EJBs that encapsulate business logic and interact with persistent storage. The handler then forwards control to the next appropriate view to be displayed to the user.

Business logic
Beans encapsulate the functional logic of the application. For small to medium sized applications they may be java beans or for larger applications EJBs. These beans would access a database using JDBC.

Sample Struts Config entry

		<form-bean name=”myform” type=”mypackage.MyForm” />
				<action path="/" type=”mypackage.MyAction” name="MyForm">
					<forward name="success" path="views.welcome" />
					<forward name="error" path="views.error" />

In the struts-config file, form beans are defined. In the example, an instance “MyForm” is defined of type mypackage.MyForm. A form bean usually maps to an input view of the application, The form bean extended from the base Struts Action Form is to be coded by the developer in such a way that the fields of the form bean map to input html controls on the view.

The struts-config file also contains action mappings. The URLs of the applications are mapped one to one with a specific action to be performed. In the example “/” URL pattern is mapped to “mypackage.MyAction” handler class and the “MyForm” form bean. Based on decision constructs inside the handler class, control may transfer to either one of the many views defined within action mapping.
Here, the handler classes may decide to show “welcome page” or the “error page” view based on program conditions.

Sample JSP content

Struts provide JSP custom tag libraries to automatically map html elements to form bean fields.

<html:form action=””/>
User Name:<html:text property=”username”/>

Here the username value entered into the HTML page is automatically populated into the username property of the MyForm bean.

Struts Custom Tag Libraries

Struts provides (among others) the following custom tag libraries to be used in JSP pages.
2. Bean
3. Logic

As described previously, HTML tags enchance the functionality of standard HTML controls. Input field types support checkboxes, hidden fields, password, radio buttons, reset buttons, select lists..

<html:text property=”username”/>

Struts bean tags provide useful display mechanisms for bean values. For example

<bean:write name=”MyBean” property=”role”/>

prints the value of the bean property on the screen.

<bean:message property=”label.username”/>

prints the message from properties file for the key label.username

document.forms[0].taskbar.value =”<bean:message key=prompt.warning”/>
return false;

Struts logic tags provide useful decision constructs using which we could avoid, using java scriptlets within the JSP page.
For example

<logic:equal name=”MyBean” property=”role” value=”super”>
Hallo SuperUser
String name=session.getAttribute(“name”);
if (name.equals(“super”))%>
Hallo SuperUser

Other logic tags include logic:notEqual, GreaterEqual, present, notPresent, iterate, empty, match, notMatch among others.

Application Resources

Messages are stored in a single central repository file- Both the view and the handler class have access to
Any text displayed to the user would come from the properties file, instead of being hard coded in Java or JSP.
These could include:
1. JSP/ HTML Text Button Labels..
2. System messages displayed to the user. introduces flexibility into the application in the sense that any changes to textual display content does not necessitate changing java / JSP code but just needs a simple change in the properties file.

A single entry in can be modified at runtime to be used at multiple places.

For example:

IsRequired={0} is required

This message can be modified at runtime and the {0} can be substituted to generate these messages “Username is required” and “Password is required”..

The properties file can effectively be used as a database, to the effect that it can be queried to retrieve single message for display. The key of the message can be used to identify the message text.

Also this repository is flexible enough to account for multiple languages. For instance one could have two different repositories for English and German.
One would be able to switch between the two without any programmatic changes.

Struts Validation

The value addition that Struts brings to the table as regards input validation is flexibility.
Validation can be done using

a) Java Code validation
Java code can be written in the “validate” method of the form bean to validate user input. Here validation happens before control is passed to the handler class, hence validation is isolated from the code in the handler class. This kind of validation is usually used where more complex validation (besides required, mask …) is necessary.
b) Automatic validation using validation.xml
In Struts adding entries into validation.xml configuration file does automatic validation. This is particularly useful in cases where we have to enforce validation for simple rules like “required”, “format mask”, “date”, “numeric” or anything else that can be done by evaluation of regular expressions.


Sample Validation.xml entry

<form name="MyForm">
	<field property="SSN" depends="required,mask">
		<msg name="mask" key="ssn.nine.digits.numeric" />

This entry enforces nine digits numeric validation on the SSN property of the MyForm bean.
If the user does not enter anything in the SSN field of the input page, the “required” validation kicks in and a message “SSN is required” is displayed.

If the user enters an invalid SSN that does not fit the mask of 9 digit numeric digits as specified by the regular expression, then the message specified in corresponding to the key “ssn.nine.digits.numeric” is used for display.

This type of automatic validation can be used for

1. Client side JavaScript validation – Struts automatically generates client side JavaScript to popup a dialog with the message.
2. Server side validation -After the page is submitted, it is reloaded with the error message included.

Structured Views Using Tiles

JSP files (view) can be structured using Struts Tiles. With Tiles one can define a layout of JSP pages and use a layout across pages of an application. This helps in getting a consistent look and feel.
For instance, a header, footer or other component in a JSP page can be defined to be in a certain position of the layout. All the pages using the layout will then effectively position the component on the JSP correctly.

The structure of the views can be changed easily by changing the tiles-defs.xml conf file without modifying each of the individual JSP pages.

This design also encourages the use of JSP pages. It also decouples the physical filename of the JSP page from code by assigning to logical “tiles” names.

Sample tiles-defs.xml entry

<definition name="views.welcome" extends="default.Layout">
	<put name="title" value="/jsp/Title.jsp" />
	<put name="menu" value="/jsp/Welcome.jsp" />

The Reverse Route Action to JSP

Lets say the action class interacted with the database and now has some information to be displayed in the JSP.
Case 1:
The information to be displayed in the next JSP is such that the page should be pre-filled (with value html elements).
In normal java programming you would use the “value=”, for each element.

<input type=”text” name=”somename” value=<%=somejavavalue%>”/>

Struts make it easier to do this.
Look at this part of the struts-config.xml entry:

<action path=”/option” type=”com.mattiz.struts.MyOptionAction” name=”MyOptionForm scope=”request”…..>

What struts does is that it keeps the form bean in the request object as an attribute. The attribute name is “MyOptionForm” in this case.

Now in the action class you do this:
com.mattiz.struts.MyOptionForm nextform=new MyOptionForm(),
set values into nextform and then
request.setAttribute(“MyOptionForm”, nextform)
Now when you forward to the next jsp, struts will read the form bean from request and automatically display contained values in the corresponding html elements of the page.

Note: In the above discussion, if you set scope=”session” then struts will keep the form bean as a session attribute instead of a request attribute.

Case 2:
The information is to be displayed as text display on the next JSP

In this case from the action class you can get some object into request (or session) and in the page you can set the object from the request and output it as you normally would.
In the JSP:

<%ValueObject vo=(ValueObject) request.getAttribute(“vo”);%>

This displays value.
You can achieve the same results as the above scriptlet using bean:write tag
It would look like this:

<bean:write name=”vo” property=”field” scope=”request”/>

EJBs guarantee ACID

With EJB you can avail of the benefits of transactions without coding to any transaction API.
To perform an atomic transaction in the simplest way would be to add code to the catch clause of a try block that encloses the transaction.
In the catch block you would try to undo whatever was done in the try block but this is a primitive way of conducting a transaction and would be prone to many errors and bottlenecks.
Problems that may need transactions:
1. Network crash
2. Database crash
3. The machine on which the database is installed itself might crash
4. Data consistency during simultaneous data access
Points 2, 3 and 4 might lead to corrupted data.
A transaction is a series of operations that appears to execute as one single atomic operation.
Transactions guarantee that all your operations in the transaction succeed or none at all.
Transactions guarantee ACID:
· Atomicity
Atomicity guarantees that all the operations in a transaction such as those involving session/entity beans, a CORBA client, a servlet, a database driver are completed or not at all. This is similar to a voting scheme if any of the constituent transactions fail the complete transaction fails.

· Consistency
Though operations inside a transaction may leave a system in a temporarily inconsistent state, in the end the system is always consistent so that to a third party the system has always remained consistent.

· Isolation
Each user accessing data need not know about other user actions on the same data. They seem to operate in isolation to each other thus ensuring data consistency using low-level synchronization that involves temporary locks on the database.
This ensures that several users can safely access the database concurrently without data corruption.

· Durability
Durability ensures that updates to system-managed resources such as a database survives system failures including power failure, machine failure, network failure or disk crashes by reapplying the steps maintained in a transactional log file maintained for this purpose.

Transactional Models

The two most popular transaction models are 1. Flat transaction and 2. Nested transaction
Nested transactions are not supported by all EJB servers

Flat transactions:
A flat transaction is a series of transactions that is performed as one unit of work. Either the entire atomic transaction is committed or rolled back. All operations that are performed in the transaction are undone in a rollback.
Flat transactions may be rolled back for any of the following reasons:
1. Invalid parameters passed to one of the components
2. System consistency is compromised
3. Hardware/ Software failures

Nested transaction:
This consists of independent sub transactions within a main transaction, which can be independently rolled back without affecting the main transaction. This allows users to perform units of transactional activity within a main transaction without letting the entire transaction fail.

Types of transactions:

1. Programmatic transactions

With a programmatic transaction it is the programmer who decides when to start a transaction and when to end it. He issues a begin statement to start a transaction and a commit or abort to end the transaction.

The advantage of using programmatic transactions is that you can have any number of sub transactions within the main transaction which is not possible with declarative or client controlled transactions.

With programmatic transactions all you would need to deal with is the Java Transaction API. (JTA)

With JTA you can control several things such as when to start a transaction and when to issue a commit or abort.
Client code can also use the JTA.
.begin() To start a transaction
.commit() commits a transaction
.getStatus() gets the status of the current transaction under which the bean is running
.rollback() forces a rollback
.setRollbackOnly forces the current transaction to rollback, eventually causing the transaction to abort.
.setTransactionTimeout(int) will force the transaction to abort after specified amount of time elapses

public void dothis()

	javax.transaction.UserTransaction jta=null;
	//Do something
   }catch(Exception e){

If you are participating in a transaction that someone else started (not declarative but container managed) you cannot explicitly call rollback() to end the transaction.
In declarative transaction the best way to do this would be to call setRollBackOnly() on your EJB context object.
If you want to doom a transaction running on a non EJB object, such as a java object, then you can call the JTA’s setRollBackOnly()

2. Declarative transactions

In this case the enterprise beans never issue the call for starting or ending a transaction but it is the EJB container that is responsible for doing so. EJB allows you to declare whether your bean is enrolled in a transaction by declaring it in the ejb-jar.xml deployment descriptor.
This is done within the transaction-type tag nested in the session tag where the user either specifies Container or Bean. Declaring the transaction as bean would imply programmatic transaction.

Declarative transactions allow you to initiate transactions without hard coding it in the bean/client code.

You must specify transaction attributes on all the business methods for your beans Further more with entity beans you need to specify transactional attributes for home methods too.

This attribute joins a transaction only if one exists. If no transaction was running the bean runs without any transaction.
Be careful to use this attribute under mission critical applications.

This ensures that your bean is never run under a transaction.
If a transaction is running it is suspended when your bean is called.

is used if you want your bean to always run under a transaction.
If you call session beans B and C from a bean A, and if A and B have “required” transactional attributes B joins the transaction initiated by A as soon as B is called. If A then calls C which also has a “required” transactional attribute, C too joins the transaction.
Thus “required” transactional attribute allows you to initiate a transaction or join an existing transaction depending on the circumstances.

This attribute ensures that always a new transaction is initiated.
If a transaction is already running, that transaction is suspended and a new transaction started. When this transaction ends the old transaction resumes.
Of course if there was no transaction initiated, there is nothing to suspend or resume.

Mandatory mandates that a transaction should already be running when a transaction is called, otherwise it throws an exception.
This is the chief difference between mandatory and supports.
It is useful to use this attribute when you are running a sub transaction within a main transaction and you want to ensure that a transaction was initiated before your bean was called.

This ensures that your bean is never run under a transaction and if it is run it throws an exception.
This is the chief difference between “never” and “notsupported”.
This attribute is useful if you want to ensure that your beans are never called within at transaction in your client code.

3. Client Initiated Transactions

In this case the transaction is initiated and closed within the client code that calls the beans. The client may be a servlet, applet, CORBA client or another bean.
The client calls would still need to be done using declarative or programmatic transactions.

Try not to use client-controlled transactions as frequently the transaction may be rolled back due to conflicts.

Bean managed transactions are illegal for entity beans and is always container managed.

It is a good design strategy to include maximum number of entity bean calls within a transaction in your session bean / client code.

You can use JTA to control transactions in the client code.
First you lookup the JTA interface using JNDI.

	Context ctx=new InitalContext();
	jta= (javax.transaction.UserTransaction)ctx.lookup(“jndi name”);
	//do something
}catch(Exception e){

Hold On! The EJBs will CALL BACK…..

EJB 2.0 introduced the bean model in which the programmer writes the code for the entity bean in a super class devoid of any jdbc. The container subclasses this bean and generates the jdbc itself. Thus there is a clear separation between the business logic and the jdbc.The actual bean is a combination of this subclass and super class. EJB 1.1 does not require such subclassing. EJB 2.0 on the other hand must support both these models.
In EJB 2.0 the superclass does not have any declared fields. On the other hand the persistent fields are container generated in the subclass. The subclass not the super class implements the get/set methods. The super class on the other hand contains empty abstract method declarations and the super class itself is declared abstract.
Any method in the super class that needs to use instance variables for some operation has to call these abstract get/set methods instead. The ejbCreate method in the entity bean (super class) sets the value of the primary keys by calling the corresponding set methods instead of initializing the instance variables unlike EJB 1.1. The container knows which fields are container managed from the information in the deployment descriptor ejb-jar.xml. Finder methods are container generated from the information in the deployment descriptor.
Guidelines for container managed persistent entries
These methods are left empty for CMP beans.
call the beans abstract set methods to initialize the primary keys.
you can pass your beans ejb object reference to other beans.
Acquire any required resources such as socket connections etc.
Release any acquired system resources such as socket connections, etc.
Called after the data is loaded into the bean
You can work on the data loaded by the container from the db such as decompressing etc.
Called just before data is stored to the database.
You can work on data about to be put into the db such as compressing etc.
Called before the bean and the corresponding data in the bean is destroyed.

The only differences between ejb 1.1 and ejb 2.0 implementations come in the bean class. The remote, home and primary key classes remain unchanged.

Why one more layer? – for the Business thing

Servlets would have logic that only deals with “web-related” stuff.
Like… getting or setting values from request/session, redirecting to the next JSP..etc…

Session beans (and not Servlets) ideally would contain all of the “business” logic.
The entire heavy programming that interacts with Entity beans should be inside the session beans.

Helper classes would have logic that will be used by different parts of the application.
Usually this is menial tasks like formatting a Date in MM/dd/yyyy format etc…
Another example is the Home lookup code, or the get sql Connection code.
These kinds of tasks need to be done all over the place and is not specific to any single part of the application.

When you port the logic from servlets to session beans, Session beans will not be dealing with the request object or any other servlet api.
Instead the servlet will be responsible for extracting values from the request object. These values will be passed as parameters into the method of the session bean.
The session bean methods will use the values passed in, and do complicated logic or interaction with entity beans, and return the result to the servlet.

For example this is how the code would look like…

Let’s say we have one “value object” class that we will use to hold values for us.
Let’s call it “Interest” class

public class InterestVO {
	private double principal;
	private int numberOfDays;
	// getters and setters for above

Now a servlet gets values from the request object (typed into the preceding page).

public class InterestServlet extends HttpServlet {
public service(request, response) {
	double principal = request.getParameter("principal");
	int numberOfDays = request.getParameter("numberOfDays");

	// now set these into the value object
	InterestVO interestVO = new InterestVO();

	//use helper class to lookup InterestSessionBean

	// get a session bean and invoke its method -- the passed in param interestVO has values that are needed
	double interestValue = interestSessionBean.calcInterest(interestVO);

	// set the retrieved value into request for display in the next page
	request.setAttribute("interestCalculated", new Double(interestValue));

	// forward to next page

The session bean will have all the logic for calculating interest, interacting with entity beans etc…

public class InterestSessionBean {

public double calcInterest(InterestVO interestVO) {

	// get Values from interestVO
	double principal = interestVO.getPrincipal();
	int numberOfDays = interestVO.getNumberOfDays();

	double interestCalculated = 0;

	// interact with entity beans to lookup the rate of interest.
	// use some formulas to calculate interest

return interestCalculated;

Getting your E J and B’s right

J2ee is a collection of programming standards, innovations, concepts and strategies all written in the Java language. With EJB, which is a vital part of J2ee, you can quickly build scalable, robust, distributed, portable, secure and reliable server side components.
Server side components are distributed business objects (these objects can be physically separated as per their utility) that encapsulate business logic.
Server side components being object oriented are reusable, extensible and flexible.
EJB components can be ported across any EJB compliant application server that supports the EJB model avoiding locking into any vendor’s solution. This gives the EJB component designer the option to scale to other EJB compliant application servers if required. Thus the EJB components are independent of the implementation of the EJB Server.
Middleware services for server side components is handled by the Application Servers that support large user populations in mission critical systems and handle resources, concurrency, transactions, security, persistence, load balancing and distribution of objects automatically, allowing the application developer to focus on business logic.
EJB is basically consists of a set of specifications to be followed by EJB Application Servers and a set of interfaces to be implemented by Server side components and application servers.
J2EE is one of three different platforms:
J2ME: Java 2 Micro Edition
A restricted form of the Java language.
J2SE: Java 2 Standard Edition
Standard services for servlets and applets. The JDK that most people are familiar with.
J2EE: A complete server side platform for enterprise class applications.
J2EE provides the following APIs to application programmers:

Ø EJB specification
Ø RMI-IIOP: J2EE needs Java’s language of communicating with remote distributed objects.
Ø Java Naming and Directory Interface
Ø Java Messaging Service
Ø Java Transaction API
Ø Servlets
Ø JSP pages
Ø Java Mail
Ø Java API for XML parsing

EJB technology is based on two important technologies:


JNDI is Java’s de facto mechanism for performing simple, powerful networking.
RMI-IIOP replaced RMI to provide compatibility with CORBA.
RMI-IIOP allows an object distributed across a network call a method on another object residing elsewhere on the network using a procedure called Remote Method Invocation.

Marshalling and Unmarshalling

Primitive types as well as objects can be transferred across a network using RMI. To ensure compatibility of data transferred between heterogeneous environments, parameters are marshaled at one end and unmarshalled automatically at the other end by Java and RMI-IIOP.
RMI-IIOP supports both passing by value (passing a copy of the variable) as well as passing by reference (passing a reference to the variable).

Distributed object architectures are based on a network communication layer that contains of an object server, a skeleton and a stub.
The object server and the skeleton reside on the middle tier while the stub resides on the client side.
The object server is the business object (in EJB parlance: the bean class).
The skeleton listens to requests from the stub.
The stub acts as a proxy and passes on requests from the stub to the object server via the skeleton.

Note that this process is generally taken care of by the application server and is part of the middle ware services it provides.
When using RMI-IIOP you need to create a remote interface that exposes all the beans business methods.
All java basic primitives are passed by value when methods are called remotely.
If you want to pass an object over the network by value it must be serializable.
If you want to pass an object over a network by reference it has to be a remote object and has to implement java.rmi.Remote.


JNDI is the de facto mechanism by which java locates objects anywhere across a network. Internally a directory has a tree structure.
A directory service can be looked upon as a scaled down version of a database.
JNDI is a bridge over naming and directory services.
It is a good idea to cache an initial context for future use instead of creating it when required.
Relation between JNDI and RMI-IIOP
An RMI-IIOP server first registers itself using JNDI.
A client then looks up this server using its JNDI name.
Enterprise Beans are server side components that are distributed over a multi-tiered, distributed environment.
Session beans model business logic while entity beans model business data. A message bean typically contains message-oriented logic.
Constituents of an Enterprise Bean
The Enterprise Bean class:
All entity beans must implement the javax.ejb.EntityBean interface, which in turn implements the javax.ejb.EnterpriseBean interface, which in turn extends
All session beans must implement the javax.ejb.SessionBean interface which also extends the javax.EnterpriseBean interface.
When a client wants to invoke a method on a bean class, it does not do so directly, rather the request is intercepted by a container class called the EJB Object, which then delegates it to the bean instance.
By intercepting the client call, the container can perform middleware activities effectively.
The container generates the code for the EJB object automatically.
The Remote Interface:
All remote interfaces should extend from javax.ejb.EJBObject which extends java.rmi.Remote.
All methods in a remote interface throw a remote exception.
The Home Interface:
Just like the EJBObject the EJBHome object from which the home interface is derived is container generated.
All home interfaces extend from javax.ejb.EJBHome, which derives from java.rmi.remote.
All methods in the home interface throw a create exception in addition to a remote exception.
The remote and the home interface indirectly extend from the rmi.remote interface, which implies that they are fully networked rmi objects.
The deployment descriptor:
To declare the middleware service requirements of your component to the bean container you must configure the deployment descriptor (usually the ejb-jar.xml).
Some of the requirements you could declare may be
Transaction control
Lifecycle management
By having a deployment descriptor you can migrate to another ejb environment without changing source code.
There may be other xml files, text files or binary files to configure the container specific requirements of your component, which may vary with the container.
After creation of all files they may be packaged into an ejb.jar file ready for deployment in the web server container.
Note: the home interface and the remote interface are network aware because clients use them across a network. Hence they need to extend from the java.rmi.remote interface.

In case create methods are system defined, how come we can create different create () methods with different signatures?
One doesn’t write any code into the create methods of the home interface, one just defines them and leaves them blank.
Now the Home interface extends EJBHome so when rmi compiler is run on this home interface, it figures that there’s one (or more with different signatures) create methods that need to have equivalents in the stubs that are generated.
The create methods of the generated stubs contain logic to marshall the parameters and transport them over the network.
Its okay to create different create methods with different signatures. The rmi compiler creates the equivalent create methods in the stubs (which has the serializing marshalling logic).

ejbCreate (for session ejb) optional
ly contains logic(user written) in a bean. It gets executed when the corresponding create () method of the home interface is executed by the client code.

ejbCreate (for Entity ejb)For a CMP bean this method is called just prior to insertion of a row into the database. Here the developer can perform actions such as initialization of fields to be inserted, etc.
For a BMP bean the bean developer has to code the logic to enter a row into the database inside the ejbCreate() method.

The ejbCreate() is invoked before the new record is created. ejbPostCreate is called after the new record is inserted. The primary key is initialized and the remaining fields are set to null when the new record is inserted using CMP.
When the setFoo() method is called the remaining fields are updated from NULL to the value specified in the parameter.

ejbPostCreate (for Entity ejb) contains actual logic in a bean. This may be code for getting a handle or getting the primary key and then doing something useful with them. The difference is that the logic is executed after the create (row insertion) happens.

The ejbFindByPrimaryKey() contains logic(user written for BMP beans and machine generated for CMP beans : behind the scenes) that looks like
Select * from table where prykey1=“doo” and prykey2=”bar”;

More about the primary key class:

The primary key class is just a simple java class, which has a set of properties that have a one to one correlation with the primary key columns of the relevant table.
So the ejbFindByPrimaryKey() should be accepting a primary key as a parameter, retrieve values of each of the properties by retrieving the relevant row from the database. In case of CMPs all this is container generated while in BMPs they have to be handwritten.
The hashcode() and equals() methods are just regular methods for primary key classes.

Object Serialization:
What is the difference between serialization and persistence?
Serializable: Enables the conversion(back and forth) of java objects into bit-byte blobs (series of 1s and 0s) that can can be transmitted over a network or stored to disk. It’s mostly used in Object Streams, sockets, RMI, temporary storage (like activaton/ passivation of beans,etc)

Persistence: means saving data (objects or primitive values) to storage. This may include serialization for the purposes of storage. This may include serialization for the purposes of storage (but for the purposes of transmission over a network)
Usually however persistence means storage to a database (usually an RDBMS).

The Remote Interface:
Extends javax.ejb.EJBObject
The remote interface is accessed using RMI-IIOP and hence every method it has needs to throw a java.rmi.Remote exception.
The same method in the bean has only one other difference in it’s signature in that it does not throw the remote exception.
The Home Interface:
The home interface extends javax.ejb.EJBHome.
It has a create method which throws a remote exception as well as a create exception.
The Bean class:
The bean class needs to implement server call back methods in addition to the business methods.
A session bean needs to implement javax.ejb.SessionBean while an entity bean implements javax.ejb.EntityBean
The ejbActivate and ejbPassivate methods do not apply for stateless session beans and hence they are left empty.
Any resources that need to be cleaned up should be included in the ejbRemove method.
The Deployment Descriptor:
tag specifies the common name of the entity bean.
The tag gives the fully qualified class name of the home interface.
The tag gives the fully qualified class name of the remote interface.
tag specifies the fully qualified name for the bean class.
only applies to session beans and specifies whether it is a stateless or stateful session bean.
There may be other vendor specific files or a GUI to make configurations specific to the application server you are using.
The ejb-jar.xml must always be placed in the meta-inf folder while creating the ejb-jar file.
When you build the ejb-client.jar only those interfaces, helper classes and stubs needed by the client should be included.

EJB Callback methods

(for stateful session beans)
can have one or more ejbCreate() methods with or without parameters.
These parameters can be used to initialize instance variables.
Must have at least one ejbCreate() method.
(for stateless session beans)
Only one empty ejbCreate method with no arguments

Instance pooling:
To conserve memory resources session beans are pooled. In case of stateless session beans, they are simply destroyed when not required and recreated when more instances are required.
However for stateful session beans instance pooling is not efficient as the state of the bean has to be preserved/ restored before they can be added/ removed from the pool.

Activation and Passivation:
The conversational state of stateful session beans is serialized to a permanent storage device during passivation and this state is retrieved during activation.
Activation and passivation may be necessary to conserve system resources.
Activation and passivation is not necessary for stateless session beans as there is not state to be conserved. They can simply be created or destroyed as required.

(for stateful session beans)
This must contain code to relinquish resources used by the session bean such as socket connections.
(for stateless session beans)
left empty as there is no conversational state

(For stateful session beans)
acquire resources required
(for stateless session beans)
left empty as there is no conversational state

method is useful in the case of session beans and you want to call another bean and a pass a reference to your original bean.

This method is called just before the bean is destroyed and must contain code to relinquish system resources no longer required.
The home interface has no corresponding remove () method; it inherits this method from it’s superclass the ejbHome object.

Entity Beans

Entity beans can be made persistent using various methods including serialization.
The primary key class should be serializable.
Called after data is loaded into into the entity bean
Called before data is stored to permanent storage. (Made persistent)

An entity bean can also be activated, passivated.

Before the instance is returned to the instance pool after dissociating itself from its client (passivation) ejbPassivate() is called and this must contain code to release resources such as sockets, connections, etc

Before the instance is retrieved from the instance pool for servicing a client it has to retrieve all necessary resources required.
This is done in the ejbActivate() method.

There are two types of persistence: BMP and CMP.

The ejbCreate() method is called just before data is entered into the database.
The ejbDestroy() method is called before the data in the database is destroyed. This method is left empty in CMP beans.

For each create () method in the home interface you need a corresponding ejbCreate() method in the bean class.

The home interface may have a method
public Authors create() throws CreateException, RemoteException.
The bean class should have a corresponding method:
public AuthorsKey ejbCreate() throws…
Note that the create method in the home interface returns a bean type whereas the create method in the bean class returns a primarykey type.
Similary the findByPrimaryKey() method returns a bean type in the home interface whereas it returns a primarykey type in t
he bean class.
This is because the bean class interacts with the client via the container while the home interface is a networked object, which can be directly called by the client.
An entity context identifies the environment of the bean.

The Remote, Home, javax.ejb.EnterpriseBean, javax.ejb.EntityBean, javax.ejb.SessionBean, javax.ejb.EjbObject, javax.ejb.EjbHome are interfaces.
The PrimaryKey, Bean, are classes. is an interface.
java.rmi.Remote is an interface.
The remote interface extends javax.ejb.EjbObject
The home interface extends javax.ejb.EjbHome
The Bean class implements either javax.ejb.EntityBean or javax.ejb.SessionBean.
The primary key class implements

For primitive values as pry keys, a separate pry key class is not required.
Consider the primary key is a primitive String.
The find method in the home interface looks like
public Vorgeleg findByPrimaryKey(String key) throws FinderException, RemoteException

In the bean class the find method looks like
public String ejbFindByPrimaryKey(String key)
The create method looks like
public String ejbCreate(String key)
key is the primitive primary key for that bean.

If the primitive key is compound, create a primary key class say VorgelegKey
The find method in the home interface looks like
public Vorgeleg findByPrimarykey(VorgelegKey pk) throws FinderException, RemoteExcepion

In the bean class the find method looks like
public VorgelegKey ejbFindByPrimaryKey(VorgelegKey key)
The create method looks like
public VorgelegKey ejbCreate(String arg1,int arg2,int arg3)
These arguments are the primary keys for that bean.

In addition to the findByPrimaryKey method the home interface may contain any number of custom defined finder methods. These need to be configured while deploying and in vendor specific.

create() in an entity bean has an entirely different meaning in entity beans as compared to session beans.

The create() method of the home interface inserts a primary key value into the database and initializes all the other table attributes to be null (which means the fields other than the primary keys should be able to accept null values- default NULL) whereas setter methods are used to update the remaining fields in the database. (equivalent to a jdbc update)

The create method of the session bean on the other hand is involved with the association of a bean client with a session bean instance.

The java.lang.reflect.UndeclaredThrowableException is usually just a mask for some other exception inside it. In the stack trace the actual exception thrown is available.

All arguments into the methods of the remote interface should extend serializable. Database connections, resultset, etc are not serializable and hence cannot be marshaled/ unmarshalled across a network.

Usually stateless session beans are used to access data that is more or less static that might be read only.

Updates and inserts are done via entity beans, which have better container managed middleware services such as transactions and rollbacks.

Searching the right way

Search Forums

List of forums for searching- (my all time favorite) – since this searches the entire Internet, it helps in retrieving information from other forums too. for Java Language related problems.
Sometimes people post all kind of stuff as well. So you never know you might get lots of useful stuff.
Remember to select “Java forums” option for searching.
This is a collection of forums. So if you are looking for a problem related to postgresql just type into the text box and it will give you a list of discussion forums for postgresql.
Joss specific forum
I haven’t used it much but know people who do.

Search tips

How to look at search results:

When search results are displayed on the page, don’t open every link displayed. It is easy to get lost reading page after page of stuff that has little relevance to the problem at hand.
Just quickly scan through the search results to look at the titles of the pages displayed and read the one or two sentences that are displayed below the title. Open a link if you get a feeling that it contains the answer to your problem.

How to specify keywords

This sometimes differs from Website to Website. But usually the following is true:

A keyword search for word1 word2 word3
Usually returns every link that contains ANY of the words

A keyword search for word1+word2+word3 usually returns a link that contains all the above words.

A keyword search for “word1 word2 word3” usually returns links that contain ALL the above words as a SINGLE PHRASE.

What keywords to search for

While searching, try to be as specific as possible. If you don’t get any matches for specific criteria then search for more general terms.
For example:

If searching for a specific error message displayed by the server or database, then type in the complete error message in the search box. You will have to consider that google limits search criteria to 10 words. The rest it will chop off. So try to keep within limit.

For example for the error message “X” reported “The type of the field named in the..”

If you search google for the word Jboss and the above error message text, then first link that google shows might contain the solution.

Some database or server software products display an error number. For example Oracle database displays error messages like ORA-1433. Postgresql or Jboss may also have specific error messages like that.

If you have error messages like that, it makes it perfect to include it in the search.

If you are searching for a general doubt (not a specific error) in that case there is a good technique you can use.
Try to frame a short sentence that captures the gist of the problem and strip out all the common words (like it for as the etc) you can do the search on the remaining words that are left.

For example, if you have a question on how to get the PK field from the remote interface when you don’t have getters/setters. You want to find out if getters and setters are allowed in the remote interface for PK fields.
Your search criteria would be “getter primary key remote interface entity EJB”