Archive

Archive for the ‘java’ Category

Spring: Handling incoming JMS messages asynchronously

September 2, 2009 Andrew Hahn Leave a comment

Handling incoming JMS messages in an asynchronous manner requires, implementing a MessageListener, creating a connection, starting a thread, handling connection loss and thread death, etc…
Spring’s MessageListenerContainers provide a “Message Driven Pojo” framework that handles all that for you except implementing the MessageListener.

To take advantage of this you first need to create JMS connection factory and Destination:

	<bean id="connectionPool"
		class="org.springframework.jms.connection.SingleConnectionFactory">
		<property name="targetConnectionFactory">
			<bean class="org.apache.activemq.ActiveMQConnectionFactory">
				<property name="brokerURL" value="tcp://localhost"/>
			</bean>
		</property>
	</bean>

	<bean id="messageDestination" class="org.apache.activemq.command.ActiveMQQueue">
		<constructor-arg value="MY.INCOMING" />
	</bean>

Then implement the MessageListener interface:

@Component("IncomingMsgProcessor")
public class IncomingMsgProcessor implements MessageListener {
    @Override
    public void onMessage(Message message)
    {
         //Your message handling code here
    }
}

And finally inject an instance into the MessageListenerContainer:

	<bean id="incommingMessageListenerContainer"
		class="org.springframework.jms.listener.DefaultMessageListenerContainer">
		<property name="connectionFactory" ref="connectionPool" />
		<property name="destination" ref="messageDestination" />
		<property name="messageListener" ref="IncomingMsgProcessor" />
		<!--
			Retry connection every 10 seconds.
		-->
		<property name="recoveryInterval" value="10000" />
	</bean>

org.springframework.jms.listener.DefaultMessageListenerContainer gives a nice set of features, but spring offers other implementations if more (or less) is needed. If your message listener needs access to the JMS session you can implement SessionAwareMessageListener which has a method that take the message and session onMessage(Message message, Session session) instead.

Categories: activemq, java, jms, spring

Spring: Injecting JAXB (Un)Marshaller

September 1, 2009 Andrew Hahn Leave a comment

Create a JAXB context passing an array of root element classes:

	<bean id="jaxbContext" class="javax.xml.bind.JAXBContext"
		factory-method="newInstance">
		<constructor-arg>
			<list>
				<value type="java.lang.Class">my.example.rootclass.Root</value>
			</list>
		</constructor-arg>
	</bean>

Create prototypes for the marshallers/unmarshallers

	<!-- Pool (un)marshallers to improve performance -->
	<bean id="marshallerTarget" class="javax.xml.bind.Marshaller"
		factory-bean="jaxbContext" factory-method="createMarshaller"
		scope="prototype">
	</bean>

	<bean id="unmarshallerTarget" class="javax.xml.bind.Unmarshaller"
		factory-bean="jaxbContext" factory-method="createUnmarshaller"
		scope="prototype">
	</bean>

Wrap these in pool targets:

	<bean id="poolTargetSource" class="org.springframework.aop.target.CommonsPoolTargetSource">
		<property name="targetBeanName" value="marshallerTarget" />
		<property name="maxSize" value="25" />
	</bean>

	<bean id="unmarshallerPoolTargetSource" class="org.springframework.aop.target.CommonsPoolTargetSource">
		<property name="targetBeanName" value="unmarshallerTarget" />
		<property name="maxSize" value="25" />
	</bean>

And create pools for reusing marshallers/unmarshallers:

	<bean id="marshaller" class="org.springframework.aop.framework.ProxyFactoryBean">
		<qualifier value="marshaller" />
		<property name="targetSource" ref="poolTargetSource" />
	</bean>

	<bean id="unmarshaller" class="org.springframework.aop.framework.ProxyFactoryBean">
		<qualifier value="unmarshaller" />
		<property name="targetSource" ref="unmarshallerPoolTargetSource" />
	</bean>

This will create one context that will be used to create up to 25 marshallers/unmarshallers. Each will be created on demand until there are 25 in use simultaneously, then calls to them will block until one becomes available. Be careful changing the state on the (un)marshallers. It would probably be a better idea to create prototypes for each configuration and inject a separate pool for each.

These can be injected in the application context or using annotations:

    @Autowired
    @Qualifier("unmarshaller")
    private Unmarshaller unmarshaller;

    @Autowired
    @Qualifier("marshaller")
    private Marshaller marshaller;
Categories: java, jaxb, spring

Spring: Injecting ActiveMQ JMS Connection

September 1, 2009 Andrew Hahn Leave a comment

First create a connection factory.

	<bean id="connectionPool"
		class="org.springframework.jms.connection.SingleConnectionFactory">
		<property name="targetConnectionFactory">
			<bean class="org.apache.activemq.ActiveMQConnectionFactory">
				<property name="brokerURL" value="tcp://localhost"/>
			</bean>
		</property>
	</bean>

Create destiation:

	<bean id="messageDestination" class="org.apache.activemq.command.ActiveMQQueue">
		<constructor-arg value="MY.OUTGOING" />
	</bean>

Inject this into spring a template:

	<bean id="jmsSendTemplate" class="org.springframework.jms.core.JmsTemplate">
		<qualifier value="messageTemplate" />
		<property name="connectionFactory">
			<ref bean="connectionFactory" />
		</property>
		<property name="defaultDestination">
			<ref bean="messageDestination" />
		</property>
	</bean>

Which can then be injected in the application context or using annotations:

    @Autowired
    @Qualifier("messageTemplate")
    JmsTemplate jmsReceiveTemplate;
Categories: activemq, java, jms, spring

Next Sequence Value Using Hibernate Entity Manager

September 1, 2009 Andrew Hahn Leave a comment

To retrieve the next value of an Orcale sequence using the Hibernate Entity Manager first create a result set mapping.

@SqlResultSetMapping(name = "NextSequenceVal", columns = { @ColumnResult(name = "NEXTVAL") })

The mapping can go anywhere, I like to put it on the entity it is most closely associated with.
Then in your DAO.

    public Long getNextElecTransUniqueId()
    {
        Query query = entityManager.createNativeQuery("SELECT MY_SEQUENCE.NEXTVAL from Dual",
                "NextSequenceVal");
        // Workaround for
        // http://opensource.atlassian.com/projects/hibernate/browse/EJB-434
        // which breaks query.getSingleResult()
        return ((BigDecimal) query.getResultList().get(0)).longValue();

    }

This example is written for Hibernate 3.3.2, Hibernate Entity Manager 3.4.0, Oracle 10g.

Note: in Entity Manager 3.4.0 if you use query.getSingleResult() you will get the exception:
Exception: org.hibernate.exception.SQLGrammarException: could not execute query^M
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)^M
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)^M
at org.hibernate.loader.Loader.doList(Loader.java:2235)^M
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129)^M
at org.hibernate.loader.Loader.list(Loader.java:2124)^M
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:312)^M
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1723)^M
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165)^M
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:175)^M
at org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:88)^M
Caused by: java.sql.SQLException: ORA-02287: sequence number not allowed here

Categories: hibernate, java

What jar is that friggin class in?!?!?!

March 21, 2009 Andrew Hahn Leave a comment

It seems to me that one of the most common tasks I have to preform when packaging a J2EE project is to find out what jar a class I depend on is in.

I have written (multiple times now) a simple perl script that finds all the jars in a given directory and scans them for a file. Thanks to the power of regular expressions you can pass in either com.foo.bar.Class or com/foo/bar/Class which ever is easier to cut-n-paste from the java.lang.NoClassDefFoundError, or similar, stack trace.

#!/usr/bin/perl

$JAR_COMMAND = "jar";
#Uncomment to use fastjar instead
#$JAR_COMMAND = "fastjar";

$class = "";
$lookin = ".";
if(@ARGV < 1) {
    print "USAGE: \n\tclassfinder [dir to search fo jars]
<packageName>\n";
    exit;
} elsif (@ARGV > 1) {
  $lookin = $ARGV[0];
  $class = $ARGV[1];
} else {
  $class = $ARGV[0];
}

foreach $jar (`find $lookin -name '*\.jar'`) {
    chomp $jar;
    foreach $file (`$JAR_COMMAND -tf $jar`) {
        chomp $file;
        if($file =~ $class) {
            print "$jar:$file\n"}
    }
}

The script relies on the standard unix utility find, it works on unix, linux, osx and cygwin. If you have an easy way to do this without using find I’d love to see it.

Adventures in Grails – WS-Security Part 2

March 11, 2008 Andrew Hahn 2 comments

This post builds on the previous post WS-Secutiry Part 1 by adding inHandlers that populate an acegi security context.

Integrating acegi

It turned out that initial integration of acegi with xfire + WSS was even easier than hooking up WSS for xfire in Grails. Though I can’t claim much original work here. In his blog Propagating Acegi’s Security Context in a WSS UsernameToken SOAP Header via XFire using wss4j Michael Vorbuger provides everything necessary to get it working.

To get it running I added the three classes from Michael’s code acegi-ws-security-xfire-example to the appropriate packages in src/java/ in my Grails app.

  • ch.vorburger.acegiwss.server.PasswordHandler
  • ch.vorburger.acegiwss.server.ForgivingWSS4jInHandler
  • ch.vorburger.acegiwss.server.ValidateUserTokenHandler

and changed the inhandlers to use these classes in XfireGrailsPlugin.groovy.


"xfire.passHandler"(ch.vorburger.acegiwss.server.PasswordHandler) { bean ->
        }

"xfire.DOMhandler"(org.codehaus.xfire.util.dom.DOMInHandler) { bean ->
        }

"xfire.WSS4JHandler"(ch.vorburger.acegiwss.server.ForgivingWSS4jInHandler) {
     properties = ["passwordCallbackRef":ref("xfire.passHandler"),
                    "action":"UsernameToken"]
        }

"xfire.ValidateUserTokenHandler"(ch.vorburger.acegiwss.server.ValidateUserTokenHandler) {}

That makes the SecurityContext avaliable in the service. To see it work I paraphrased Michael’s example in the test service.

import org.acegisecurity.Authentication
import org.acegisecurity.context.SecurityContextHolder

class TestService {

    static expose=['xfire']

    boolean transactional = true

    String serviceMethod() {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		 if (auth == null || auth.getName() == null || auth.getName().length() == 0) {
			 // In a real service, this would be a proper SOAP Fault, NOT an IllegalArgumentException
			 throw new IllegalArgumentException(NOAUTH_FAULT_TEXT);
		 }

       return "You did it ${auth.getName()}!!!"
    }
}

Thats it!

Categories: grails, groovy, java, programming Tags:

Adventures in Grails

February 8, 2008 Andrew Hahn Leave a comment

I was recently face with the need to rewrite an entire (ok, 3/4 finished) web application from scratch. The app provided SOAP services for external clients, had integrated search (in both the web interface and WS), restricted user access and search results based on profile and needed to be very scalable. We had previously used AppFuse to build the app, so it was using Spring, Hibernate, Lucene, Compass, Acegi,WebWork, CXF (after upgrading XFire) using WS-Security, etc… I needed to maintain the robustness and scalability of those tools while increasing the flexibility and prototyping efficiency. Enter Grails.

I have been using Groovy to do my scripting tasks for the last 4-5 months. I love it. I can write a script with the same ease and power as I can in Perl or Python and have direct access to my domain model and Hibernate DAOs. Once its working, it is no great leap to wire it up in Spring and have it run on a timer in my app. Groovy alone was enough to get me to give Grails a shot. Once there the near instant ability to create a web UI for CRUD with just three total lines of controller code had me hooked. The fact that plugins for XFire, Acegi and Compass/Lucene already exist make it appear to be the perfect platform for what I need to accomplish. Sure the plugins are young, and I may have to do some work to get some of them to the level I need, but that is the beauty of open source.

I plan to blog my experiences as I put the app together. Stay tuned to see how it goes.

Getting Started

I found a wealth of information to get me started using Grails.

Web Services (XFire)

Once I had an idea of how to start building the app with Grails I figured I would get the Web Services running with the XFire plugin. Using the getting started section of the XFire plugin page I quickly had a simple service up and running.
grails install-plugin xfire
grails create-service Test

Add the expose property to the service.
static expose=['xfire']

and
grails run-app
fire off a test SOAP message and IT WORKS!!!!!
Cool, now I need some data in the DB to see how that looks. Enter it by hand? No, I’ll create a controller and use the web UI! OK, now run the app and fire off a test message….

Pttthhhbbbbb!?!?!?!

Unexpected EOF in prolog at [row,col {unknown-source}]: [1,0]

What the….? Adding a controller breaks the web services? My first wrinkle!
Turns out that you have to pay attention to the “Upgrade to Grails 0.5(URL Mapping)” section on the XFire plugin page too. If you don’t add the following constraint to the Grails URL mapping the controller framework mangles the request.

static mappings = {
          "/$controller/$action?/$id?"{
              constraints {
                        controller(matches:/.*[^(services)].*/)
                  }
          }
}

Thanks to Jason Morris-5 on the Grails mailing list, he worked through the same issue just a few weeks earlier and found the answer.Well, can’t beat an active mailing list. Another plus. All in all a very good experience so far.

Getting the sorted and paginated contents of a collection in Hibernate

January 9, 2008 Andrew Hahn Leave a comment

Normally getting the contents of a collection from Hibernate is as easy as retrieving the parent object and calling ‘parent.getCollection()’. But what if you have no interest in the parent and the result set could be huge? I found some help in the hibernate.org ‘Tips and Tricks’ section, but not quite what I was looking for. The solutions given there used filters or pre-defined sorting on the collection.
Sorting
Pagination

The following query retrieves the contents of a collection sorts and paginates them:

public List<Category> getSubCategories(Long categoryId, int start, int size) {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        String queryString = "select subCategory from SubCategory as subCategory, Category as category where category.id = " + categoryId + " and subCategory in elements(category.subCategories) order by subCategory.name";
        List<Category> subCategories = getList(session.createQuery(queryString), start, size);
        return subCategories;
    }

I’m using Spring, but any way of getting a Hibernate session should work.

Here Category and SubCategory look like:

public class Category {
    protected Long id;

    protected String name;
    protected Set<SubCategory> subCategories = new HashSet<SubCategory>();

    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 Set<SubCategory> getSubCategories() {
        return subCategories;
    }

    public void setSubCategories(Set<SubCategory> subCategories) {
        this.subCategories = subCategories;
    }
}

public class SubCategory {
    protected Long id;
    protected String name;

    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;
    }

}

I have intentionally left out the xdoclet tags I use to configure hibernate. The mapping is as simple as it gets.