Thursday, October 30, 2008

Persisting A List of Custom Objects Using Hibernate in a Spring Env.

The prospect of persisting an object using hibernate into a database and then reading it back did not seem challenging with good old hibernate taking care of most things. 

Piece of cake? Not quite actually as I discovered while trying to do it for a List of custom objects. Let us see what were the challenges and how I found the solutions. Let us assume I wish to persist an object that contains the current situation of all stocks trading in the market. Our simplistic object has an id and a list of stocks: 

The list of stocks is made of a custom object:

And since we refuse to live without spring, we need some bean config:

With spring so near how can we forget maven and the pom dependencies:

Phew! Sometimes I forget how much these XML config make our lives easier (?).  Now, had it been my own custom object, I would have used @Embedded. But what do I do with a java collection. I was tempted to mark it with @Lob and it compiled fine. But when I actually tried to persist it, it gave me one big, fat ClassCastException: java.util.ArrayList cannot be cast to java.sql.Blob. OK, so objects don't turn into byte arrays overnight and that attempt was dumb and desperate. 

Then what? Referring "Java Persistence with Hibernate" (Bauer and King,2006) and official hibernate docs helped my to make my classes look like this:

Now this works like a charm: at least the part about starting your app, seeing your tables created perfectly and storing your objects at the right place with some class like:

In our next post we will see how we read this information back and use it if I face any difficulty with it as well!

Wednesday, October 8, 2008

ActiveMQ Message Consumer in Spring

In the last blog we saw how to configure an ActiveMQ broker to run in a Spring environment. In this blog we will see how to configure a message consumer. Again, I am not trying to explain how consumers work but just sharing code and config to make it work in Spring :p

Since we have the luxury of Spring , we will use a message listener container provided by the framework: SimpleMessageListenerContainer (org.springframework.jms.listener.SimpleMessageListenerContainer ). My needs were simple and non-transactional so this container suffices

The basic reason is the desire to be message driven i.e. I want my app to take some actions as and when it receives messages. The container bean definition should look like:

    <bean id="jmsContainer" class="org.springframework.jms.listener.SimpleMessageListenerContainer">
        <property name="autoStartup" value="true"/>
        <property name="connectionFactory" ref="myConnectionFactory"/>
        <property name="destination" ref="myDestination"/>
        <property name="messageListener" ref="myMessageListener"/>
        <property name="acceptMessagesWhileStopping" value="true"/>

This config makes the container start when the bean gets loaded and makes sure no messages are lost even if it is down. Further we need to specify the connection factory to use to connect to broker, the destination at broker from which we wish to hear and the message listener that ultimately handles the message. The config for these three will look like:

 <bean id="myDestination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg value="myPackage.myQueue"/>

 <bean id="myConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://localhost:61636"/>

<bean id="myMessageListener" class="myPackage.MyMessageListener">       
    <property name="appName" value="My Application"/>

Destination takes the name for destination in order to identify it at broker. the producer would refer it by the same name. JNDI can be used for more sophisticated look-ups which we may see some other time. Connection factory just needs url for a running broker. Message Listener is just our custom bean to handle messages. MyMessageListener would look like:

package myPackage;

import javax.jms.*;

public class MyMessageListener implements MessageListener {
    private String appName;

    public void setAppName(String appName){
        this.appName = appName;    

    public void onMessage(Message message) {
        //do your stuff

Finally, don't forget the POM dependencies included in last blog if you are using Maven. You should be good to go.

Tuesday, October 7, 2008

Running ActiveMQ Broker in Spring

ActiveMQ can run as an independent JMS server. This may be desirable if we want to run it independently of our spring application. However it is also possible that we may want to deploy a message broker within a spring environment. This may be simply because we need to do some unit testing or because our webapp is too small to break across several machines. Whatever be the reason. Let us make a note of basic steps to do it:

1. Put in your activemq.xml under the WEB-INF folder. Your ActiveMQ distribution(5.1.0 at time of this article) has this config file under the "conf" folder. We will not discuss configuring it here. Go here to read about configuring

2. The lib folder of the distribution has all possible jars that JMS may ever need in its lifetime. If you are not using Maven, you may need to copy the jars to your classpath. If you are using Maven, these dependencies should generally suffice for basic use.





Go here if you wish to simply run ActiveMQ using Maven
3. Put this bean definition in your spring conf:
<bean id="broker" class="org.apache.activemq.xbean.BrokerFactoryBean">
<property name="config" value="/WEB-INF/activemq.xml"/>
<property name="start" value="true"/>
You should be good to go. Bringing up your Spring application will start the broker at tcp://localhost:61636

Friday, October 3, 2008

Understanding JMS with a Spring Perspective

Making some notes from the official JMS tutorial.

Why Messaging?
Messaging enables distributed communication that is loosely coupled. Messaging is used for communication between software applications or software components.

What is NOT Messaging?
Messaging is different from RMI, RPC or email

What is JMS?
The Java Message Service is a Java API to help you with your messaging needs

When to use JMS/ Messaging?
Use JMS if
  • you do not want to depend on any information about other components’ interfaces( so they are easily replaceable)
  • you want your app to run whether or not all components are up and running simultaneously
  • you want an app design that allows a component to send information to another and to continue to operate without receiving an immediate response
  • you want a guaranteed delivery, not necessarily immediately

What is the support for JMS in J2EE?
  • Message driven beans support JMS
  • JMS messages can participate in distributed transactions

Where can I get an open-source implementation for JMS API?
ActiveMQ from Apache is a great open source implementation. You can see others at

What is a Messaging Domain?
Messaging domain denotes the style of messaging. There are basically two types of messaging domains: Point-to-Point(PTP) and Publish/Subscribe(pub/sub)

How is PTP different for pub/sub?
PTP style of messaging has following features:
• Each message has only one consumer.
• A sender and a receiver of a message have no timing dependencies. The receiver can fetch the message whether or not it was running when the client sent the message.
• The receiver acknowledges the successful processing of a message.

Use PTP messaging when every message you send must be processed successfully
by one consumer.

pub/sub is characterized by:
• Each message may have multiple consumers
• Publishers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages.

Use pub/sub messaging when each message can be processed by zero, one, or many consumers.

What does JMS support out of these two?

JMS supports both. In fact it even provides something called durable subscriptions which allow you to combine flexibility and reliability of queues of PTP with the ability to allow clients to send messages to many recipients of pub/sub

Using JMS will the messages be consumed asynchronously or synchronously?
JMS supports both. However the biggest advantages of JMS arise out of asynchronous communication

What are the main parts of a JMS application?
  • Administred Objects (connection factories, destinations)
  • Connections
  • Sessions
  • Message producers
  • Message consumers
  • Messages
A connection factory is used to create a connection. A connection is used to create a session. A session can create a producer, consumer or a message. Producer send messages to a destination while consumers receive messages from the destination.

Does Spring support JMS?
Absolutely. You can read it here. If you are using ActiveMQ, you may want to see this too.

Why should I use spring to manage interactions with JMS?
For pretty much the same reason you would use spring to manage your database, cache etc. etc. : it makes your life easier. Seriously. Helps you cut down the "boiler-plate" code and gives you more specific exceptions besides the regular dependency injection benefits.

Wednesday, October 1, 2008

Setting up Quartz in a Spring-MySQL Environment

If you are using a persistent JobStore in Quartz, you will have to back your spring application with a DB. MySQL can be pretty convenient for local unit testing. Besides the regular spring DataSource config, you need a few more things here and there. I did not find any comprehensive "todo" checklist for MySQL online. So summing up what worked for me.

Using SchedularFactoryBean you can specify a MySQL DataSource and fine-tune it using quartz properties. You can see this in a config file I had published earlier:

XML Config

Besides this, you need to have the following dependencies for sure in your pom if you are using Maven:

POM dependencies

If you are not using maven, the corresponding jars should be in the classpath.

Finally, don't forget to run the SQL script to create tables in your database provided by quartz:

Creating DB Tables for Quartz