Coding Conventions
Introduction
There are so many very good Java and J2EE references available on the internet these days that we've decided not to rewrite how you should develop your first Java application or deploy a J2EE project. Instead we'll start with some great on-line references which will definitely help you in your Java quest.
In the sections below you'll also find some J2EE examples based on the coding and naming conventions described in Appendix A. Please re-use these examples as templates for your Java related projects. The complete J2EE source code, including the unit tests, can be downloaded from https://jjguidelines.dev.java.net/servlets/ProjectDocumentList?folderID=287
.
Java Coding
References
Before an author can write about a Java API, the API has gone through the Java Community Process (JCP) as a Java Specification Request (JSR). It's on the JCP website http://www.jcp.org
that you can get your first contact with a potential J2EE API. You can download the specification once the JSR is in public draft, and that's also were the different authors (often already involved in the JSR expert group) start writing more reader friendly pages.
Some interesting Java specifications are:
If you don't like reading the core specifications you can always download some great on-line java books. My personal favorite is the Thinking in Java book
from Bruce Eckel, which I recommend to any person starting with the Java language. Below you can find a few others:
Java Source Files
Each Java source file contains a single public class or interface.
Java source files have the following ordering:
- Beginning file comments
- Package and import statements
- Class and interface declarations
Package And import Statements
All source files should start with a copyright notice. See rule JAD_002: Provide A Correct File Comment For A File (High)
. The first non-comment line of a Java source file is the package statement. After that, import statements can follow.
For example:
\*
* Copyright notice
*
*/
package be.vlaanderen.projectname.subpackage;
 | Note
Wildcard import-declarations must be replaced by a list of single import-declarations, meaning that import statements should not end with an asterisk. See rule JAC_010: Do Not Use A Demand Import (Enforced). |
Class And Interface Declaration
The following table describes the parts of a class or interface declaration, in the order that they should appear.
Table 1.3. Parts Of A Class Or Interface Declaration Notes
| Part Of A Class Or Interface |
Declaration Notes |
| Class/Interface documentation comment with javadoc tags |
This (javadoc) comment will contain more information about the class or interface but also the javadoc author and version information. |
| Class or interface statement |
Member and static variables First the public class variables, then the protected, then package level (no access modifier), and then the private. |
| Instance variables |
First the public, then the protected, then package level (no access modifier), and then the private. |
| Constructors |
The constructor(s) are placed here. |
| Methods |
These methods should be grouped by functionality rather than by scope or accessibility. For example, a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier. |
For example:
/**
* You can place more information about the class or interface here.
*
* Just add an additional javadoc author tag If more than one developer
* has worked on the same class or Interface.
*
* @author firstName lastName - companyName
* @version $Revision: 1.2 $ $Date: 2004/04/02 08:14:02 $
*/
public class MySingleton {
/**
* The instance variable is static so we don't have
* to make the getInstance method synchronized.
*/
private static final MySingleton INSTANCE = new MySingleton();
/**
* More information about the constructor here.
*/
private MySingleton() {
}
/**
* More information about the method here.
*
* @return The singleton reference
*/
public static MySingleton getInstance() {
return INSTANCE; }
/**
* More information about the method here.
*
* @param value A value that needs to be processed.
*/
public void doSomething(int value) {
}
}
Change History (Optional)
Source files could end with an overview of the changes made to the source. The change history can be extracted from your version control system and added to the source file by adding the following comment block.
\*
* $Log: ch01s05.html,v $
* Revision 1.2 2004/04/02 08:14:02 dsc
* minor update
*
* Revision 1.4 2004/02/25 14:21:03 gde
* updated all feedback links
*
* Revision 1.3 2004/02/24 13:54:29 gde
* removed title id
*
* Revision 1.2 2004/02/17 15:04:29 gde
* more bib links
*
* Revision 1.1 2004/02/16 17:37:15 gde
* First version with modulation
*
* Revision 1.16 2004/02/10 15:18:28 gde
* fixed malformed sentence in JAC_027
*
* Revision 1.15 2004/02/10 15:02:34 gde
* adjusted revision number
*
* Revision 1.14 2004/02/10 14:53:44 gde
* fixed all small JAC issues
*
* Revision 1.13 2004/02/10 14:46:54 gde
* finished methodname, classname, ...; fixed image problem, solves a few issues
*
* Revision 1.12 2004/02/09 18:18:23 gde
* fixed methodname/classname from conv.naming.j2ee till rules.conv.naming.java including chapter 2)
*
* Revision 1.11 2004/02/06 18:06:04 gde
* all callouts done
*
* Revision 1.10 2004/02/06 17:18:01 gde
* AFTER callout for Servlet Example only
*
* Revision 1.9 2004/02/06 16:11:04 gde
* issues + programlisting no longer part of para
*
* Revision 1.8 2004/02/05 14:17:53 gde
* adjusted line numbering,
* before changing line numbering to callouts (if allowed)
*
* Revision 1.7 2004/02/05 13:46:36 gde
* before changing line numbering to callouts
*
* Revision 1.6 2004/02/04 14:01:00 gde
* working on table standarization
*
* Revision 1.5 2004/02/04 12:57:56 gde
* resolved several issues created by Stephan
*
* Revision 1.4 2004/02/03 16:53:52 gde
* bibliography's url are now ulinks
*
* Revision 1.3 2004/02/03 13:31:41 gde
* adjusted Overviews, links, xref
* Did not adjust severity links
*
* Revision 1.2 2004/02/03 09:16:05 dsc
* Stephan's merged version
*
* Revision 1.1 2004/02/02 20:13:10 sja
* Chapter One and Two merged + update biblio
*
* Revision 1.8 2004/02/01 10:32:36 dsc
* fixed issue 26
*
* Revision 1.7 2004/01/31 18:16:34 dsc
* continued development
*
* Revision 1.4 2004/01/29 09:50:14 sja
* Fixed issue #2567
*
* Revision 1.3 2004/01/28 10:47:10 sja
* Fixed issue #1245
*
* Revision 1.2 2004/01/27 16:37:15 sja
* continued development
*
* Revision 1.1 2004/01/27 01:07:44 sja
* creation
*/
Methods
- Avoid too long methods ! A method should not be longer than 1 page (60 lines), if a method is longer you can probably re-factor it to smaller methods resulting in more readable code. See rule JAC_013: Do Not Make A Method Longer Then 60 Lines (Normal)
.
- A method should only have one point of entry and exit. So use only one return statement in your method making the method easier to read and debug. This convention will also allow you to easily introduce pre and post conditional assertions. See rule JAC_016: Use A Single return Statement (Normal)
.
- Do not chain method calls, exceptionally a chain of 2 method calls can be used. This convention will avoid scenario's where one of the method returns null but because they're chained you don't know which one it is! See rule JAC_015: Do Not Chain Multiple Methods (Normal)
.
Wrapping Lines
Avoid lines longer than 80 characters since they're not handled well by many terminals and tools.
When an expression will not fit on a single line, break it according to these general principles:
- Break after a comma.
- Break before an operator.
- Prefer higher-level breaks to lower-level breaks.
- Align the new line with the beginning of the expression at the same level on the previous line.
- If the above rules lead to confusing code or to code that's squished up against the right margin, just indent 8 spaces instead.
Statements
Every statement in the Java language has a preferred style and certain conventions that should be followed.
Simple Statements
Each line should contain only one statement.
For example:
argv++; argc++;
argv++; argc++;
Compound Statements
Compound statements are statements that contain lists of statements enclosed in braces { statements; }. See the following sections for examples.
- The enclosed statements should be indented one more level than the compound statement.
- The opening brace should be at the end of the line that begins the compound statement; the closing brace should begin a line and be indented to the beginning of the compound statement.
- Braces are used around all statements, even single statements. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.
if else Statements
The if and else statements should have the following form:
if (condition) {
statements;
}
if (condition) {
statements;
} else {
statements;
}
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
while Statements
A while statement should have the following form:
while (condition) {
statements;
}
do while Statements
A do while statement should have the following form:
do {
statements;
} while (condition);
switch Statements
A switch statement should have the following form:
switch (condition) {
case ABC:
statements;
case DEF:
statements;
break;
case XYZ:
statements;
break;
default:
statements;
break;
}
Every time a case falls through (doesn't include a break statement), add a comment where the break statement would normally be. This is shown in the preceding code example with the falls through comment.
Every switch statement should include a default case. See rule JAC_011: Provide A default case In A switch Statement (Enforced)
. The break in the default case is redundant, but it prevents a fall-through error if later another case is added.
 | Note
Use constant variables after each case instead of meaningless values.
From JDK 1.5 onwards enums will be supported within the Java Language this means the constant variables could be replaced with enum variables. |
try catch Statements
A try catch statement should have the following format:
try {
statements;
} catch (ExceptionClass e) {
statements;
}
A try catch statement may also be followed by finally, which executes regardless of whether or not the try block has completed successfully.
try {
statements;
} catch (ExceptionClass e) {
statements;
} finally {
statements;
}
J2EE Coding
Introduction
In this section you'll find some interesting J2EE references and code examples following the different conventions. A full list of the convention rules are listed in Appendix A.
The complete J2EE source code, including the unit tests, can be downloaded from https://jjguidelines.dev.java.net/servlets/ProjectDocumentList?folderID=287
.
References
Some interesting J2EE 1.3 specifications are:
- JSR-058, Java 2 Platform, Enterprise Edition 1.3 Specification
defines all the features of the J2EE version 1.3 release.
- JSR-019, Enterprise Java Beans 2.0 Specification
introduces the integration with JMS but also improved support for entity bean persistence and relationships. The EJB query language for finder methods, additional home interface methods and support for server interoperability are also included in this release.
- JSR-053, Java Servlet 2.3 and JavaServer Pages 1.2 Specifications
are platform independent Java based web components executed in a web server that generate dynamic content.
- JSR-914, Java Message Service API
provides a common way for Java programs to create, produce and consume messages in an asynchronous way.
- JSR-054, JDBC 3.0 Specification
allows you to access a relational database.
- JSR-052, A standard Tag library for JavaServer Pages Specification
helps JSP authors simplify their web pages.
- JSR-112, J2EE Connector Architecture 1.5
extends the existing 1.0 specification by adding new features like asynchronous integration with enterprise information systems (EIS) and JMS providers.
If the different J2EE specifications are written too cryptic for you, then point your browser to The Source for Java Technology: http://java.sun.com
. This is the most complete web site covering the different Java platforms: J2ME, J2SE and J2EE. Below you can find some great on-line J2EE books that will help you step-by-step in developing your first J2EE application.
You can also find very interesting on-line Java and J2EE related articles on the following sites:
A Servlet Example
Below you can find an example of a Servlet implementing the Command and Controller Strategy.
\*
* Copyright notice Todo_link_1
*
*/
package be.vlaanderen.examples.servlet; Todo_link_2
import java.io.IOException; Todo_link_3
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import be.vlaanderen.examples.common.Constants;
/**
* This Servlet implements a simple Command and
* Controller Strategy.
*
* @author Stephan Janssen - JCS Int.
* @version $Revision: 1.2 $ $Date: 2004/04/02 08:14:02 $
*/
public class FooServlet extends HttpServlet { Todo_link_4
/**
* Catch the GET HTTP requests.
* @param req The HTTP servlet request
* @param res The HTTP servlet response
* @throws IOException thrown when an IO problem is encountered
* @throws ServletException thrown when the Servlet encounters a difficulty
*/
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
processRequest(req, res);
}
/**
* Catch the PUT HTTP requests.
*
* @param req The HTTP servlet request
* @param res The HTTP servlet response
* @throws IOException thrown when an IO problem is encountered
* @throws ServletException thrown when the Servlet encounters a difficulty
*/
protected void doPut(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException{
processRequest(req, res);
}
/**
* Process all HTTP requests.
*
* @param req The HTTP servlet request
* @param res The HTTP servlet response
* @throws IOException thrown when an IO problem is encountered
* @throws ServletException thrown when the Servlet encounters a difficulty
*/
protected void processRequest(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
Command command = null; Todo_link_5
String page = null;
String param = null;
param = req.getParameter(Constants.CMD); Todo_link_6
if (null != param) {
command = CommandFactory.createCommand(param);
page = command.execute(req, res);
}
else {
page = Constants.ERROR_PAGE; Todo_link_7
}
dispatch(req, res, page);
}
/**
* Dispatch the request to the JSP or HTML page
*
* @param req The HTTP servlet request
* @param res The HTTP servlet response
* @param page The HTML or JSP page that will handle the view
* @throws IOException thrown when an IO problem is encountered
* @throws ServletException thrown when the Servlet encounters a difficulty
*/
protected void dispatch(HttpServletRequest req, HttpServletResponse res, String page)
throws IOException, ServletException {
ServletContext ctx = getServletContext();
RequestDispatcher dispatcher = ctx.getRequestDispatcher(page);
dispatcher.forward(req, res);
}
}
The Servlet example is compliant to the following convention rules:
 | Tip
The above example shows a straight forward Servlet implementation of the Command and Controller strategy based on the Model 2 web-tier architecture. |
Below you can find a simple Filter Servlet example.
\*
* Copyright notice
*
*/
package be.vlaanderen.examples.servlet;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import be.vlaanderen.examples.common.Constants;
/**
* Example of a simple Filter that handles character encoding.
*
* @author Stephan Janssen - JCS Int.
* @version $Revision: 1.2 $ $Date: 2004/04/02 08:14:02 $
*/
public class EncodingFilter implements Filter {
/** Default encoding string */
private String encoding = Constants.UTF8;
/**
* Initialization of the filter happens here.
*
* @param config The FilterConfig reference
* @throws ServletException thrown when the Servlet encounters a problem
*/
public void init(FilterConfig config) {
String enc = config.getInitParameter(Constants.ENCODING);
if (null != enc) {
encoding = enc;
}
}
/**
* Dispatching specified request changing its parameter's character
* encoding.
*
* @param req The ServletRequest reference
* @param res The ServletResponse reference
* @param chain The FilterChain reference
* @throws IOException thrown when an IO problem is encountered
* @throws ServletException thrown when the Servlet encounters a problem
*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
req.setCharacterEncoding(encoding);
chain.doFilter(req, res);
}
/**
* Called when filter is destroyed
*
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
}
}
The Filter Servlet example is compliant to the following, not yet mentioned, convention rules:
 | Tip
See alsoJSPSPEC version 2.3 (or higher) - chapter 6 for more information on Servlet Filters. |
A Java ServerPage Example
Below you can find a simple JSP example that's using the JSP Tag Library.
<%@ taglib uri="/WEB-INF/jcs.tld" prefix="jcs" %>
<html>
<body>
<table>
<jcs:employeelist id="employee_list">
<tr>
<td><jcs:employee attribute="name"/></td>
<td><jcs:employee attribute="profile"/></td>
</tr>
</jcs:employeelist>
</table>
</body>
</html>
The JSP example is compliant to the following, not yet mentioned, convention rules:
Enterprise Java Bean Examples
A Session Bean Example
A Statefull Session Bean
Below you can find an example of a statefull session bean.
/*
* Copyright notice
*
*/
package be.vlaanderen.examples.session;
import java.util.logging.Logger;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
/**
* A stateless session bean example
*
* @author Stephan Janssen - JCS Int.
* @version $Revision: 1.2 $ $Date: 2004/04/02 08:14:02 $
*/
public class FooBean implements SessionBean { Todo_link_1
/** Initialize the logging API here and use it for any std. error output */
private static final Logger logger = Logger.getLogger(FooBean.class.getName());
/**
* The session bean context variable
*/
protected SessionContext ctx;
/**
* The constructor
*/ public FooBean() { Todo_link_2
}
/**
* Sets the associated session context.
*
* @param ctx the session bean context
*/
public void setSessionContext(SessionContext ctx) {
this.ctx = ctx;
}
/**
* The Session Bean create method
*/
public void ejbCreate() { Todo_link_3
}
/**
* A container invokes this method before it ends the life
* of the session object.
*/
public void ejbRemove() {
}
/**
* The passivate method is called before the instance
* enters the "passive" state.
*/
public void ejbPassivate() {
}
/**
* The activate method is called when the instance is
* activated from its "passive" state.
*/
public void ejbActivate() {
}
/**
* An example of a session business method
*
* @param value an example of a string parameter
*/
public void bar(String value) {
logger.info(value); Todo_link_4
}
}
The above example is compliant to the following, not yet mentioned, convention rules:
 | Tip
See also EJB20SPEC Chapter 7.10. for more details. |
The Home Interface
The Session home interface extends the javax.ejb.EJBHome interface and will define the create methods that a client can invoke. Every create method corresponds to an ejbCreate method in the session bean.
/*
* Copyright notice
*
*/
package be.vlaanderen.examples.session;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
/**
* An example of the Home Session interface
*
* @author Stephan Janssen - JCS Int.
* @version $Revision: 1.2 $ $Date: 2004/04/02 08:14:02 $
*/
public interface FooHome extends EJBHome {
/**
* A create example method
*
* @return the Bar object is returned
* @throws CreateException if the creation did not succeed
*/
Foo create() throws CreateException, RemoteException; Todo_link_1
}
The above example is compliant to the following, not yet mentioned, convention rules:
The Remote Interface
/*
* Copyright notice
*
*/
package be.vlaanderen.examples.session;
import java.rmi.RemoteException;
import javax.ejb.EJBObject;
/**
* An example of the Remote Session interface
*
* @author Stephan Janssen - JCS Int.
* @version $Revision: 1.2 $ $Date: 2004/04/02 08:14:02 $
*/
public interface Foo extends EJBObject {
void bar(String value) throws RemoteException;
}
The Session remote interface extends the javax.ejb.EJBObject interface and will define the business methods that a client may invoke. The method definitions in a remote interface must follow these rules:
- Each method in the remote interface must match a method implemented in the enterprise bean class.
- The signatures of the methods in the remote interface must be identical to the signatures of the corresponding methods in the enterprise bean class.
A Container Managed Persistency (CMP) Entity Example
Entity Bean Class
Below you can find an example of a simple container managed entity bean.
/*
*
* Copyright notice
*
*/
package be.vlaanderen.examples.entity;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.CreateException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
/**
* A simple CMP Entity bean example
*
* @author Stephan Janssen - JCS Int.
* @version $Revision: 1.2 $ $Date: 2004/04/02 08:14:02 $
*/
public abstract class FooBean implements EntityBean { Todo_link_1
/** Initialize the logging API here and use it for any std. error output */
private static final Logger logger =
Logger.getLogger(FooBean.class.getName());
/** The entity context */
private EntityContext context;
/**
* No-argument constructor
*
*/
public FooBean() { Todo_link_2
}
/**
* Return the foo id
* @return foo id
*/
public abstract String getFooId();
/**
* Set the foo id
*
* @param fooId the foo id
*/
public abstract void setFooId(String fooId);
/**
* Get the bar value
*
* @return returns the bar value
*/
public abstract String getBar();
/**
* Set the bar value
*
* @param bar the given bar value
*/
public abstract void setBar(String bar);
/**
* Create a bar record
*
* @param id the primary key
* @param bar the bar value
* @return return the primary key
* @throws Create Exception
*/
public String ejbCreate(String fooId, String bar) throws CreateException { Todo_link_3
logger.info("FooBean.ejbCreate(" + fooId + "," + bar + ")");
setFooId(fooId);
setBar(bar);
return fooId; Todo_link_4
}
/**
* For each ejbCreate[METHOD](...) method, there is a matching
* ejbPostCreate[METHOD](...) method that has the same input parameters
* but whose return type is void.
*
* @param barId the primary key
* @param bar the bar value
* @throws Create Exception
*/
public void ejbPostCreate(String fooId, String bar)
throws CreateException { Todo_link_5
logger.info("FooBean.ejbPostCreate(" + fooId + "," + bar + ")");
}
/**
* Display the Bar value
*
*/
public void doSomething() {
logger.log(Level.INFO, getBar());
}
/**
* A container uses this method to pass a reference to the
* EntityContext object.
*
* @param ctx the entity bean context
*/
public void setEntityContext(EntityContext ctx) {
context = ctx;
}
/**
* A container invokes this method before terminating the life
* of the instance.
*/
public void unsetEntityContext() {
context = null;
}
/**
* Called in response to a client-invoked remove operation on
* the entity bean's home or component interface or as the result
* of a cascade-delete operation.
*/
public void ejbRemove() {
logger.info("FooBean.ejbRemove [" + getBar() + "]");
}
/**
* When the container needs to synchronize the state of an enterprise
* bean instance with the entity object's persistent state, the container
* calls the ejbLoad() method.
*/
public void ejbLoad() {
}
/**
* When the container needs to synchronize the state of the entity
* object's persistent state with the state of the enterprise bean
* instance, the container first calls the ejbStore() method on the
* instance.
*/
public void ejbStore() {
}
/**
* This method is called when the container decides to disassociate
* the instance from an entity object identity, and to put the instance
* back into the pool of available instances.
*/
public void ejbPassivate() {
}
/**
* This method is called when the container picks the instance from
* the pool and assigns it to a specific entity object identity.
*/
public void ejbActivate() {
}
}
The above example is compliant to the following, not yet mentioned, convention rules:
The Local Home Interface
*
*
* Copyright notice
*
*/
package be.vlaanderen.examples.entity;
import javax.ejb.CreateException;
import javax.ejb.EJBLocalHome;
import javax.ejb.FinderException;
/**
* The Local Home interface for Enterprise Bean Foo
*
* @author Stephan Janssen - JCS Int.
* @version $Revision: 1.2 $ $Date: 2004/04/02 08:14:02 $
*/
public interface FooLocalHome extends EJBLocalHome { Todo_link_1
/**
* Creates an instance from a key for Entity Bean: Foo
*
* @param fooId the primary key
* @param bar the bar value
* @return the business interface Foo
* @throws Create exception
*/
FooLocal create(String fooId, String bar)
throws CreateException;
/**
* Find by primary key
*
* @param fooId the primary key value
* @return the business interface Foo
* @throws Finder exception
*/
FooLocal findByPrimaryKey(String fooId)
throws FinderException;
}
The above example is compliant to the following, not yet mentioned, convention rules:
The Local Interface
/*
*
* Copyright notice
*
*/
package be.vlaanderen.examples.entity;
import javax.ejb.EJBLocalObject;
/**
* The local interface for Enterprise Bean Foo
*
* @author Stephan Janssen - JCS Int.
* @version $Revision: 1.2 $ $Date: 2004/04/02 08:14:02 $
*/
public interface FooLocal extends EJBLocalObject {Todo_link_1
/**
* A Foo business method
*/
void doSomething(); Todo_link_2
}
The above example is compliant to the following, not yet mentioned, convention rules:
A Message Driven Bean Example
Message driven bean example:
/*
* Copyright notice
*
*/
package be.vlaanderen.examples.messagebean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
/**
* A simple Message Driven Bean example
*
* @author firstName lastName - companyName
* @version $Revision: 1.2 $ $Date: 2004/04/02 08:14:02 $
*/
public class FooBean implements MessageDrivenBean, MessageListener Todo_link_1
/** Initialize the logging API here and use it for any std. error output */
private static Logger logger =
Logger.getLogger(FooBean.class.getName());
/** The message driven context */
private MessageDrivenContext ctx = null;
/**
* The default no-args constructor
*
*/
public FooBean() { Todo_link_2
}
/**
* Sets the associated message driven bean context.
*
* @param ctx the message driven bean context
*/
public void setMessageDrivenContext(MessageDrivenContext ctx) {
this.ctx = ctx;
}
/**
* The Message Bean create method
*/
public void ejbCreate() { Todo_link_3
}
/**
* A container invokes this method before it ends the life
* of the message driven bean object.
*/
public void ejbRemove() {
}
/**
* The onMessage method is called when a message
* has been produced for
*
* @param msg The asynchronous received message.
*/
public void onMessage(Message msg) {
String txtMessage = null;
try {
txtMessage = ((TextMessage) msg).getText();
helperMethod(txtMessage);
} catch (JMSException e) {
logger.log(Level.WARNING, "JMS Problem", e);
}
}
/**
* An example of a helper method which
* can be called by the onMessage method.
*
* @param text A String value from the onMessage method
*/
public static void helperMethod(String text) {
logger.info(text);
}
}
The above example is compliant to the following, not yet mentioned, rules:
 | tip
The message driven bean class can have other helper methods which can be invoked by the onMessage method. |