Archive

Author Archive

Using Apache JAMES Mail Server

January 21st, 2011 11 comments

Recently, I needed an open source email server for testing purposes and I came across JAMES project. The Java Apache Mail Enterprise Server or JAMES is an open source mail application platform that among many other things is a full-fledged e-mail server. It is a pure Java implementation (built on Spring Framework) and supports all the standard e-mail protocols such as SMTP, POP3 etc. In this post, I will quickly demonstrate how you can set up JAMES on your local Windows box and use it to send emails.

Step 1: Download the latest version of JAMES from Apache site. At the time of this writing the latest stable version is 2.3.2 (james-binary-2.3.2.zip). Unzip the downloaded file to a folder on your box. I will be referring to this directory as JAMES_INSTALL_DIR throughout post.

Step 2: To start JAMES, simply run the “run.bat” file under the \bin. This should open up a new window that looks something like this:

Step 3: Before we can start sending and receiving mails, we need to create a user account on our mail server. JAMES provides a Remote Manager Service on port 4555 that you can telnet into and interact with. Simply launch a new Command Prompt and run the command:
telnet localhost 4555

You should see the Remote Administration Tool and a prompt for your login id.

Enter root as your login id and upon prompt for password enter root. This would log you in. To create a new user run the following command: adduser someusername somepassword

Here are some of the useful commands supported by JAMES:

Command Description
help Display help with commands
listusers
setpassword Sets a user’s password. The format is setpassword username password
deluser Deletes an existing user. The format is deluser username
adduser Adds a new user. The format is adduser username password
countusers Shows the number of existing accounts
listusers Lists all the existing accounts in the mail server
quit Closes the connection

Step 4: Now we have everything installed and setup to send emails. Lets give it a try by running the sample code below:


package com.practicalspring.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Main {
	
	public static void main(String[] args) 
	{
		/***** CHANGE THESE FOUR VARIABLE VALUES TO REFLECT YOUR ENVIRONMENT ******/
		String user = "vader";	// Newly created user on JAMES
		String password = "darth"; // user password
		
		String fromAddress = "vader@localhost"; // newlycreateduser@localhost 
		String toAddress = "SOMEUSER@gmail.com";
		 
		
		// Create a mail session
		Properties properties = new Properties();
		properties.put("mail.smtp.host", "localhost");
		properties.put("mail.smtp.port", "25");
		properties.put("mail.smtp.username", user);
		properties.put("mail.smtp.password", password);
		Session session = Session.getDefaultInstance(properties, null);
		
		try 
		{
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(fromAddress));
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
			
			message.setSubject("Email from our JAMES Server");
			message.setText("Luke, I'm your father!!");
			Transport.send(message);
			
			System.out.println("Email sent successfully");
		}
		catch (MessagingException e) 
		{
			e.printStackTrace();
		}
	}
}

Here is the generated email in my inbox:

If you don’t see an email in your inbox in the next couple minutes make sure to check in the Spam folder.

Categories: Mail Server Tags: ,

Flex 4 Custom Validators in 5 Minutes

October 12th, 2010 No comments

Flex out of the box provides several validators that can be used for validating user input. These validators are bundled in the mx.validator package. However, there will be times where we might need to write our own validators. In this post, I will create a custom validator that can be used for validating a combo box.

Creating a custom validator involves extending the mx.validators.Validator class and overriding its doValidation method.


package validators
{
	import mx.validators.Validator;

	public class ComboBoxValidator extends Validator
	{
		public function ComboBoxValidator()
		{
			super();
		}
		
		override protected function doValidation(value:Object):Array 
		{
			return null;
		}
	}
}

The doValidator method holds the logic for validating the passed in value. This value is the data entry control’s property and is passed in by Flex. For our combo box validation we will be using its selectedItem property. Any validation errors will be reported as instances of mx.validators.ValidationResult. With this information in hand, here is the complete implementation of the doValidation method.


override protected function doValidation(value:Object):Array 
{
		var resultArray:Array = [];
		if(value == null) 
		{
			resultArray.push(new ValidationResult(true, "", "", "Validation Failed"));
		}
		return resultArray;
}

And here is the MXML application that uses the custom validator.


<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" 
			   xmlns:validators="validators.*"
			   minWidth="955" minHeight="600">
	<fx:Script>
		<![CDATA[
			import mx.validators.Validator;
		]]>
	</fx:Script>

	<fx:Declarations>
		
		<s:ArrayCollection id="countries">
			<s:source>
				<fx:String>Australia</fx:String>
				<fx:String>India</fx:String>
				<fx:String>France</fx:String>
				<fx:String>USA</fx:String>
			</s:source>
		</s:ArrayCollection>
		
		<validators:ComboBoxValidator id="cmbCountryValidator" source="{cmbCountry}" property="selectedItem" />
		
	</fx:Declarations>
	
	<s:layout>
		<s:VerticalLayout paddingLeft="20" paddingTop="20" />
	</s:layout>

	<s:ComboBox id="cmbCountry" dataProvider="{countries}" focusOut="Validator.validateAll( [cmbCountryValidator] )" width="200" />
	
	<s:TextInput width="200" />
	
</s:Application>

Categories: Flex Tags: , ,

JAX-WS Using WebLogic 10.3

October 9th, 2010 1 comment

The Java API for XML Web Services or JAX-WS provides a simple, easy to understand architecture for developing and deploying web services. In this post I will be creating a simple Task List CRUD application that showcases the JAX WS technology. I will be using Eclipse IDE for development and WebLogic 10.3.0 for deployment. Weblogic 10.3.0 supports Java EE 5 specification and implements JSR109. Therefore it does not require any additional jars or configuration such as jax-ws.xml file for running web services.

Here are the requirements for the Task List application:

  • The application should allow new tasks to be created
  • Tasks can be updated, queried and deleted
  • Tasks can be associated with a one or more tags

To keep this blog post manageable, I will not be storing the tasks in to a persistent store such as a database. I am also not going to worry about concerns such as authentication and security. We will start the implementation with the domain model which consists of Task and Tag objects. The figure below gives the UML representation of the domain model.

One To Many Relationship B/N Task and Tag

And here is the associated Java code for the two classes:

	package com.inflinx.blog.taskservice.domain;
	
	import java.util.ArrayList;
	import java.util.List;
	
	public class Task {
		
		private String id;
		private String name;
		private String notes;
		private List<Tag> tags = new ArrayList<Tag>();
	
		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getNotes() {
			return notes;
		}
		public void setNotes(String notes) {
			this.notes = notes;
		}
		public List<Tag> getTags() {
			return tags;
		}
		public void setTags(List<Tag> tags) {
			this.tags = tags;
		}
	}
	package com.inflinx.blog.taskservice.domain;
	
	public class Tag {
		private String id;
		private String name;
	
		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
	}

The next step is to create a Web Service class that would service the client’s requests for creating new tasks or updating, removing and querying existing tasks. Here I am taking a Java to WSDL approach where we start with the Java code and let the tools generate WSDL and related schemas at runtime. Web Service classes in JAX WS are simple pojos and use annotations for providing meta data to the container. Here is the starting point of our web service class:

	package com.inflinx.blog.taskservice.service;
	
	import javax.jws.WebService;
	
	@WebService(serviceName="service", targetNamespace="ns.blog.inflinx.com")
	public class TaskManager {
		
		
	}

The @WebService annotation, part of the javax.jws package, indicates that we are building a JAX WS based web service. The targetNamespace attribute assigns a name space to the service defined. If the targetNameSpace is not used, then the reverse package name will be used. The serviceName defines the URL of the deployed service. In this case, the URL to access the service would be: http://locahost:7001/taskservice/service?wsdl The associated XSD can be found at: http://localhost:7001/taskservice/service?xsd=1. If we would like to expose the service under a different URL, say http://localhost:7001/taskservice/api/service we just need to change the serviceName to “api/service”.

Since we will not be using a database to persist tasks, I have added two Maps to hold submitted task and tag data. These maps are initialized with dummy data in the web service constructor as shown in the code below.


	public class TaskManager {
		
		private static Map<String, Task> TASK_DATA = new HashMap<String, Task>();
		private static Map<String, Tag> TAG_DATA = new HashMap<String, Tag>();
		
		public TaskManager() {
			
			TAG_DATA.put("1", new Tag("1", "Web Service"));
			TAG_DATA.put("2", new Tag("2", "Flex"));
			TAG_DATA.put("3", new Tag("3", "Spring"));
			
			Task task = new Task("1", "Write Blog on JAX WS", "This will be part 1");
			List<Tag> tagList = new ArrayList<Tag>();
			tagList.add(TAG_DATA.get("1"));
			task.setTags(tagList);
			TASK_DATA.put("1", task);
			
			Task task2 = new Task("2", "Write Blog on Flex", "This will be a future post");
			List<Tag> tagList2 = new ArrayList<Tag>();
			tagList2.add(TAG_DATA.get("2"));
			task2.setTags(tagList2);
			TASK_DATA.put("2", task2);
		}
	}	

The next step is to add operations to the web service. Here is a simple delete operation with JAX WS annotations.

@WebMethod
public void delete(@WebParam(name="taskId") String taskId) {
	TASK_DATA.remove(taskId);		
}

The @WebMethod annotation is used to indicate a web service operation. The @WebParam is used to provide additional information about the parameters for the generated service. If a name is not specified, then the parameters in the Schema will be named as arg0, arg1 etc. Currently JAX WS does not provide a way to mark a parameter as required. It is not required to annotate web service operations with @WebMethod annotation. However, if you choose to annotate one, then you should annotate all the operations that needs to be exposed as part of the service.

Before we move further, we need to indicate how Java Task objects should be marshalled to XML. In order to do this, we will be using the Java Architecture for XML Binding or JAXB. JAXB provides a convenient model for marshalling Java objects into XML and unmarshalling XML back into Java Objects. The JAXB API constitutes a set of annotations that
enable mapping between Java classes and their XML representations. The table below lists the commonly used JAXB annotations along with their descriptions:

XmlRootElement This annotation indicates a class to be used as a root element in the generated XML document. If the name attribute is not specified then JAXB would automatically use the class name with first letter lowercased as the root element name.
XmlType This annotation can be used to provide additional information for generating the XML schema. For example the propOrder attribute can be used to indicate the order of the child elements in the marshalled document
XmlAccessorType This annotation can be used to control the data that gets serialized. For example, XmlAccessType.FIELD indicates that all non static, non transient fields of a class to be marshalled.
XmlElement This annotation is used to map a JavaBean property to an XML element.
XmlAttribute This annotation is used to map a JavaBean property to an XML attribute.
XmlElementWrapper This annotation can be used to create a wrapper around generated XML for a particular element.

Here are the modified Task and Tag Java classes that uses the above JAXB annotations.

	package com.inflinx.blog.taskservice.domain;
	
	import java.util.ArrayList;
	import java.util.List;
	
	import javax.xml.bind.annotation.XmlAccessType;
	import javax.xml.bind.annotation.XmlAccessorType;
	import javax.xml.bind.annotation.XmlElement;
	import javax.xml.bind.annotation.XmlElementWrapper;
	import javax.xml.bind.annotation.XmlRootElement;
	import javax.xml.bind.annotation.XmlType;

	@XmlAccessorType(XmlAccessType.FIELD)
	@XmlType(name="", propOrder={"id", "name", "notes", "tags"})
	@XmlRootElement(name = "task")
	public class Task {
		
		@XmlElement(required=true)
		private String id;
		
		@XmlElement(required=true)
		private String name;
		
		@XmlElement(required=false)
		private String notes;
		
		@XmlElementWrapper(name="tags", required=false)
		@XmlElement(required=false, name="tag")
		private List<Tag> tags = new ArrayList<Tag>();
		
		// Getters and Setters
		
	}
	package com.inflinx.blog.taskservice.domain;
	
	import javax.xml.bind.annotation.XmlAccessType;
	import javax.xml.bind.annotation.XmlAccessorType;
	import javax.xml.bind.annotation.XmlElement;
	import javax.xml.bind.annotation.XmlRootElement;
	import javax.xml.bind.annotation.XmlType;
	
	@XmlAccessorType(XmlAccessType.FIELD)
	@XmlType(name="", propOrder={"id", "name"})
	@XmlRootElement(name = "tag")
	public class Tag {
		
		@XmlElement(required=true)	
		private String id;
		
		@XmlElement(required=true)
		private String name;
		
		// Getters and setters
	}
	

Finally, here is the rest of the web service implementation.

		@WebMethod	
		public Task findTask(@WebParam(name="taskId") String id) {
					return TASK_DATA.get(id);
		}
		
		@WebMethod
		public @WebResult(name="task") Task[] findAll() {
				return TASK_DATA.values().toArray(new Task[0]);
		}	
		
		@WebMethod
		public void create(@WebParam(name="task") Task task) {
			TASK_DATA.put(task.getId(), task);
		}
			
		@WebMethod
		public void update(@WebParam(name="task") Task task) {
			TASK_DATA.put(task.getId(), task);
		}
			
		@WebMethod
		public void delete(@WebParam(name="taskId") String taskId) {
			TASK_DATA.remove(taskId);
		}

That is all it takes to create a JAX WS web service. Once the web service is deployed to the WebLogic server, you can test it using tools like SoapUI.

Categories: JAX WS, JAXB Tags: ,

SiteMesh And Script Tag

July 29th, 2010 No comments

In a Sitemesh application I recently had to read code inside <script> tags of the decorated pages and use it in the decorator page. After little research, I found this solution. Based on this, I extended the HTMLPageParser and created a ScriptExtractionRule. The ScriptExtractionRule extends the BlockExtractingRule and retrives the content inside script tag.

However with Sitemesh 2.4.1, this solution did not work for the script tag. When I replaced script with any other HTML tag such as form, I was able to read the content inside that tag. Eventually I ended up putting the JavaScript inside a content tag. Here is a portion of the decorated page.

<content tag=”script”>
function somejsfunction() {
}
</content>

Now in the decorator page, I used the tag to read the JavaScript. Hopefully this helps others struggling with similar issue.

Categories: SiteMesh, Solutions Log Tags:

Maven Multi Module Versioning

April 28th, 2010 6 comments

Recently I have been working on a Maven multi module project with ear, war and ejb artifacts. It has been a pleasant experience till I got to versioning my modules. Consider a multi module project with the following structure:

parent-project
|
|- child-moudle
| |
| |–pom.xml
|
|- pom.xml

The parent project pom.xml holds the version information of the parent project:

com.inflinx
project-parent
1.0.0-SNAPSHOT
pom

Now the child module pom contains a reference to the parent information:


	com.inflinx
	project-parent
	1.0.0-SNAPSHOT


4.0.0
com.inflinx
child-module
jar

Now this is where the problem starts. Since all the child modules need to have an explicit reference to the parent pom version, when it is time to do a release, we have to change the version in parent pom and all the child module poms. This can be a real pain and is very error prone. With a little help from Google, here is what I found:

  1. Ceki on his blog suggested using a property in the parent pom to control the version numbering.
  2. Several maven users would like “automatic parent versioning” according this improvement
  3. Use maven release plugin which would automate the process of changing version numbers across the project

Option three seems to be the correct approach to solve this problem here. But I have heard horrible things about the release plugin and how fragile it is. I will be giving it a try soon. I still think that Maven should support automatic parent versioning as an option for users who don’t (or cannot) get to use the release plugin.

Categories: Maven, Solutions Log Tags: ,

Creating Maven Archetypes – Spring MVC Example

April 16th, 2010 7 comments

Maven Archetypes are project templates that allow users easily create new projects. Maven Archetypes are great way to share best practices and enforce consistency beyond Maven’s standard directory structure. For example, an organization can provide its developers an archetype bundled with company’s approved CSS and JavaScript libraries.

Recently, I have been creating a lot of Spring MVC based projects and each time I do, I copy a lot of information (configuration files, css files, dependency information etc) from an existing project. Following the DRY principles, I decided to create several Spring MVC based archetypes that can help me bootstrap my projects quickly. In this post I will share my experiences creating and using a new Maven Archetype.

Maven provides several ways to create a new archetype as described here. Since I have an existing Spring MVC project, I will be using the archetype:create-from-project goal.

 

Creating Archetype

Step 1: Identify the Maven Project that would be used as prototype for the archetype. Make sure it has only the resources (configuration, properties and Java files) that you would like to be part of the archetype. It is recommended to remove IDE specific files (.project, .classpath etc) from the project directory. Here is the spring-mvc-prototype project that I will be using:

Prototype Project Layout

Prototype Project Layout

Step 2: Using command line, navigate to the project folder spring-mvc-prototype and run the following command:

	mvn archetype:create-from-project
	

Upon completion of the command, you should see the message “Archetype created in target/generated-sources/archetype”. The newly created archetype is now under spring-mvc-prototype/target/generated-sources/archetype

Step 3: The next step is to move the newly created archetype into a separate folder so that it can be tweaked and published. I have moved the content inside the spring-mvc-simple-archetype folder.

Archetype Directory Structure

Archetype Directory Structure

Step 4: Modify the artifactId in the archetype’s pom.xml located at the root of spring-mvc-simple-archetype folder.

Existing pom.xml:

  com.inflinx.blog
  spring-mvc-prototype-archetype
  1.0.0-SNAPSHOT
  maven-archetype
  spring-mvc-prototype-archetype

Modified pom.xml:

	com.inflinx.blog
	spring-mvc-simple-archetype
	1.0.0-SNAPSHOT
	maven-archetype
	spring-mvc-simple-archetype	

Step 5: Modify the finalName in the resource’s pom.xml file located at spring-mvc-simple-archetypesrcmainresourcesarchetype-resources.

		 
		spring-mvc-prototype

		
		${artifactId}
	

During project creation, maven will replace the ${artifactId} expression with the user supplied artifactId value.

Step 6: When creating a project from an archetype, Maven prompts the user for a package name. Maven will create the package in the source folder (srcmainjava) of the project being created and will move the contents under archetype-resourcessrcmainjava into the package.

Maven File Copy

Maven File Copy

While generating the “testproject” above, the user specified the package “com.inflinx.blog.testproject”. So the SomeJavaClass.java file got moved to the root of the package and the HomeController.java got moved under the web.controller subpackage.

Step 7: The next step is to verify that the generated archetype.xml (located under src/main/resources/META-INF/maven) has all the files listed and they are located in the right directories. For example, the HomeController is located under archetype-resources/src/main/java/web/controller/HomeController.java. So there should be an entry under sources in the archetype.xml that looks something like this:

	  
	    src/main/java/com/inflinx/blog/mvcprototype/web/controller/HomeController.java
	  

Step 8: Modify the configuration files to correctly use the ${package} variable. For example, the webContext.xml file is modified so that the controllers located under web.controller sub package are picked up:

		
	

Step 9: The final step in creating the archetype is to run the following on command line inside the folder spring-mvc-simple-archetype:

	mvn clean install
	

 

Using the archetype

Once the archetype is installed, there are several ways to create a project from it.

Generate goal: Create an empty folder and run the following command:

 		
 		mvn archetype:generate -DarchetypeCatalog=local
		

This goal would scan the local catalog for archetypes and prompts the user to select an archetype to use.

Command Line Archetype Usage

Command Line Archetype Usage

Once the user enters 1, Maven selects the spring-mvc-simple-archteype for project creation.

m2Eclipse Plugin: If you are an Eclipse user, use the New Project Wizard and search and select the spring-mvc-simple-archetype.

m2Eclipse Archetype Usage

m2Eclipse Archetype Usage

Using m2Eclipse plugin is a real time saver since it creates the associated IDE specific configuration files.

 

Adding Custom Properties

On some projects, additional information such as user name or web application context might be needed to generate the project. Here are the steps to prompt the user for information and use it:

Step 1: Add to the archetype-metadata.xml file located under spring-mvc-simple-archetypesrcmainresourcesMETA-INFmaven a required properties entry:

	
    	
  	

Step 2: Modify the file where you would like to use the information. Below, I have modified weblogic.xml to have the context root value the user has provided:

 
	
		
	        true
	    
		${contextRoot}	
	

When the user uses the archetype with the above modifications, he will be prompted for the contextRoot.

Custom Attribute Usage In Action

Custom Attribute Usage In Action

Spring + JTA + JPA + JMS

April 8th, 2010 13 comments

I recently worked on a Spring application that used Hibernate as JPA provider and JTA for transaction demarcation. In this post I will create a simple Order Processing Message Driven Bean that showcases this integration. I will be using an Oracle database and deploy the application on a WebLogic 10.3 server.

To keep things manageable, the Message Driven Bean is designed to consume messages from a Queue. When a new message gets added to the Queue, the Application Server delivers it to the MDB. The MDB then uses a Spring Managed Service/Repository to persist a new “Order” JPA Entity in the database. The application is configured such that this entire process runs in a container managed transaction. I will be using the Blog Queue I created in a previous post.

Step 1: The first step is to create an Order Entity and the corresponding database table to store the newly created orders.

 
package com.inflinx.blog.orderprocessing.domain;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="ORDER_TABLE", schema="BLOGDEMO")
public class Order 
{
	@Id
	@Column(name="ORDER_ID")
	private Long id;
	
	@Column(name="NAME")
	private String name;
	
	@Column(name="CREATED_DATE")
	private Date createdDate;

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getCreatedDate() {
		return createdDate;
	}
	public void setCreatedDate(Date createdDate) {
		this.createdDate = createdDate;
	}
}

I have created the ORDER_TABLE in an Oracle database under the BLOGDEMO schema:

Order Table

Order Table

Step 2: In the WebLogic console, create a XA datasource to the database with the JNDI name jdbc.blgods.

XA Blog Data Source

XA Blog Data Source

The XA datasource is necessary for Hibernate to participate in a JTA global transaction. WebLogic also provides an option to emulate XA with the Emulate Two-Phase Commit.

Step 3: The next step is to create an OrderRepository that deals with persistence logic such as creating a new Order.

package com.inflinx.blog.orderprocessing.repository;

import com.inflinx.blog.orderprocessing.domain.Order;

public interface OrderRepository 
{
	public void createOrder(Order order);
}
package com.inflinx.blog.orderprocessing.repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.inflinx.blog.orderprocessing.domain.Order;

@Repository("orderRepository")
public class OrderRepositoryImpl implements OrderRepository 
{
	// Spring injected EntityManager
	@PersistenceContext
    private EntityManager entityManager;
	
	@Override
	public void createOrder(Order order) 
	{
		 entityManager.persist(order);
	}
}

Step 4: Following the principles of layered architecture, the next step is to create an OrderService and its implementation.

package com.inflinx.blog.orderprocessing.service;

import com.inflinx.blog.orderprocessing.domain.Order;

public interface OrderService {
	public void createOrder(Order order);
}
package com.inflinx.blog.orderprocessing.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.inflinx.blog.orderprocessing.domain.Order;
import com.inflinx.blog.orderprocessing.repository.OrderRepository;

@Service("orderService")
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	@Qualifier("orderRepository")
	private OrderRepository orderRepository;
	
	@Override
	public void createOrder(Order order) {
		// Simply delegate the call to repository layer
		orderRepository.createOrder(order);
	}
}

As you can see, the implementation is annotated with @Transactional to make the service call transactional.

Step 5: The next step is to create a persistence.xml file without any JPA provider information.

 

	
		
			com.inflinx.blog.orderprocessing.domain.Order
		

		

Step 6: The next step is to create a Spring configuration application-context.xml file to hold bean and transaction definition. In addition, the file also holds the JPA provider information.


       
	     
    
     
    
    
    
	
	
	
	
    
	    
    
    			
    				
    					
    					
    				
    			
    			
    				
    					hibernate.transaction.factory_class=org.hibernate.transaction.JTATransactionFactory
					hibernate.transaction.manager_lookup_class=org.hibernate.transaction.WeblogicTransactionManagerLookup
					hibernate.current_session_context_class=jta
					hibernate.transaction.flush_before_completion=true						
					hibernate.connection.release_mode=auto
    				
    			
    			
    	
             

Step 7: With the above configuration in place, the next step is to create a Message Driven Bean that processes incoming messages. The MDB is annotated to use container managed transactions:

 
package com.inflinx.blog.mdb;

import java.util.Date;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.interceptor.Interceptors;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor;

import com.inflinx.blog.orderprocessing.domain.Order;
import com.inflinx.blog.orderprocessing.service.OrderService;


@MessageDriven(
		mappedName = "jndi.blogQueue",
		name="orderProcessor",
		activationConfig = { @ActivationConfigProperty(
				propertyName = "destinationType", propertyValue = "javax.jms.Queue"
		)}
)
@Interceptors(SpringBeanAutowiringInterceptor.class)
@TransactionManagement(TransactionManagementType.CONTAINER)
public class OrderProcessor implements MessageListener
{
	@Autowired
	@Qualifier("orderService")
	private OrderService orderService;
	
    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void onMessage(Message message) 
	{
    	// Create a new Order
    	Order order = new Order();
    	order.setId(System.currentTimeMillis());
    	order.setName(RandomStringUtils.randomAlphabetic(5));
    	order.setCreatedDate(new Date());
    	
    	// Save the order
    	orderService.createOrder(order);
	}
	
}

Step 8: The SpringBeanAutowiringInterceptor by default looks for a beanRefContext.xml file to create a spring context. So the final step in the process is to create a beanRefContext.xml with a reference to the application-context.xml.




			 
		
							
				application-context.xml
			
		 		
	
	 

Now when a new message gets added to the Queue, the onMessage method will run inside a transaction and will create a new Order. Here is a new Order record in the database:

Order Table Populated

Order Table Populated

Categories: JMS, JPA, JTA, Spring Tags: , , ,