Printing Greenhopper Cards From Jira

In an attempt to keep a better historical log of our work, my company switched from a whiteboard and 3×5 cards to Greenhopper on top of JIRA. However, we wanted to keep the whiteboard for ambient information and as a location for morning scrum. Greenhopper doesn’t support a way of printing 3×5 cards so what follows is a very convoluted set of instructions that have gotten up 80% of the way there.

Greasemonkey

Greenhopper has a way of printing story cards but the only available layout is a two column setup that doen’t handle page breaks nicely causing cards to be cut between pages. The following greasemonkey script will force a page break after each card.

function addGlobalStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}

addGlobalStyle('.issueCard {page-break-after: always;}');

Include this script on the following url pattern:

http://jira.locamoda.com/secure/Print.jspa*

Printing in Firefox

Ideally you could print directly from firefox to the 3×5 card but with my setup (FF 3.6 on OS X 10.6) Firefox wont accept 3×5 as a valid page size. To get around this create a 4.5 x 7.5 paper size by going to File -> Page Setup and select Manage Custom Sizes… under Paper Size. With that paper size selected, navigate to the Planning Board view in Greenhopper and click the printer icon next to your current sprint. Turn off all the headers and footers and click preview, not print.

Printing in Preview

In preview you are able to create a 3×5 paper size. Choose Print from the File menu and you  will see a Paper Size drop down in the print dialog. Select Manage Custom Sizes…, just like in the Page Setup dialog in Firefox, and create a paper size of 3×5. With that paper size selected click the scale radio button and scale up to 125%. Finally, load your printer with 3×5 cards and click print. You should end up with prints that fill most of a 3×5 card.

Synchronous Request Response with ActiveMQ and Spring

activemq-5-x-box-reflectionA few months ago I did a deep dive into Efficient Lightweight JMS with Spring and ActiveMQ where I focused on the details for asynchronous sending and receiving of messages. In an ideal world all messaging would be asynchronous. If you need a response then you should set up an asynchronous listener and either have enough state stored in the service or in the message that you can continue processing once the response has been received. However, when ideals lead to complexity, we have to make the decision of how much complexity can we tolerate for the performance we need. Sometimes it just makes more sense to use a synchronous request/response.

Request Response with JMS

ActiveMQ documentation actually has a pretty good overview of how request-response semantics work in JMS.

You might think at first that to implement request-response type operations in JMS that you should create a new consumer with a selector per request; or maybe create a new temporary queue per request.

Creating temporary destinations, consumers, producers and connections are all synchronous request-response operations with the broker and so should be avoided for processing each request as it results in lots of chat with the JMS broker.

The best way to implement request-response over JMS is to create a temporary queue and consumer per client on startup, set JMSReplyTo property on each message to the temporary queue and then use a correlationID on each message to correlate request messages to response messages. This avoids the overhead of creating and closing a consumer for each request (which is expensive). It also means you can share the same producer & consumer across many threads if you want (or pool them maybe).

This is a pretty good start but it requires some tweaking to work best in Spring. It also should be noted that Lingo and Camel are also suggested as options when using ActiveMQ. In my previous post I addressed why I don’t use either of these options. In short Camel is more power than is needed for basic messaging and Lingo is built on Jencks, neither of which have been updated in years.

Request Response in Spring

The first thing to notice is that its infeasible to create a consumer and temporary queue per client in Spring since pooling resources is required overcome the JmsTemplate gotchas. To get around this, I suggest using predefined request and response queues that are created at startup, removing the overhead of creating a temporary queue for each request/response.

At this point I implemented the following naive solution:

@Component
public class Requestor {

    private static final class CorrelationIdPostProcessor implements MessagePostProcessor {

        private final String correlationId;

        public CorrelationIdPostProcessor( final String correlationId ) {
            this.correlationId = correlationId;
        }

        @Override
        public Message postProcessMessage( final Message msg ) throws JMSException {
            msg.setJMSCorrelationID( correlationId );
            return msg;
        }
    }

    private final JmsTemplate jmsTemplate;

    @Autowired
    public RequestGateway( JmsTemplate jmsTemplate ) {
        this.jmsTemplate = jmsTemplate;
    }

    public String request( final String request, String queue ) throws IOException {
        final String correlationId = UUID.randomUUID().toString();
        jmsTemplate.convertAndSend( queue+".request", request, new CorrelationIdPostProcessor( correlationId ) );
        return (String) jmsTemplate.receiveSelectedAndConvert( queue+".response", "JMSCorrelationID='" + correlationId + "'" );
    }
}

This worked for a while until the system started occasionally timing out when making a request against a particularly fast responding service. After some debugging it became apparent that the service was responding so quickly that the receive() call was not fully initialized, causing it to miss the message. Once it finished initializing, it would wait until the timeout and fail. Unfortunately, there is very little in the way of documentation for this and the best suggestion I could find still seemed to leave open the possibility for the race condition by creating the consumer after sending the message. Luckily, according to the JMS spec, a consumer becomes active as soon as it is created and, assuming the connection has been started, it will start consuming messages. This allows for the reordering of the method calls leading to the slightly more verbose but also more correct solution. (NOTE: Thanks to Aaron Korver for pointing out that ProducerConsumer needs to implement SessionCallback and that true needs to be passed to the JmsTemplate.execute() for the connection to be started.)

@Component
public class Requestor {

    private static final class ProducerConsumer implements SessionCallback<Message> {

        private static final int TIMEOUT = 5000;

        private final String msg;

        private final DestinationResolver destinationResolver;

        private final String queue;

        public ProducerConsumer( final String msg, String queue, final DestinationResolver destinationResolver ) {
            this.msg = msg;
            this.queue = queue;
            this.destinationResolver = destinationResolver;
        }

        public Message doInJms( final Session session ) throws JMSException {
            MessageConsumer consumer = null;
            MessageProducer producer = null;
            try {
                final String correlationId = UUID.randomUUID().toString();
                final Destination requestQueue =
                        destinationResolver.resolveDestinationName( session, queue+".request", false );
                final Destination replyQueue =
                        destinationResolver.resolveDestinationName( session, queue+".response", false );
                // Create the consumer first!
                consumer = session.createConsumer( replyQueue, "JMSCorrelationID = '" + correlationId + "'" );
                final TextMessage textMessage = session.createTextMessage( msg );
                textMessage.setJMSCorrelationID( correlationId );
                textMessage.setJMSReplyTo( replyQueue );
                // Send the request second!
                producer = session.createProducer( requestQueue );
                producer.send( requestQueue, textMessage );
                // Block on receiving the response with a timeout
                return consumer.receive( TIMEOUT );
            }
            finally {
                // Don't forget to close your resources
                JmsUtils.closeMessageConsumer( consumer );
                JmsUtils.closeMessageProducer( producer );
            }
        }
    }

    private final JmsTemplate jmsTemplate;

    @Autowired
    public RequestGateway( final JmsTemplate jmsTemplate ) {
        this.jmsTemplate = jmsTemplate;
     }

    public String request( final String request, String queue ) {
        // Must pass true as the second param to start the connection
        return (String) jmsTemplate.execute( new ProducerConsumer( msg, queue, jmsTemplate.getDestinationResolver() ), true );
    }
}

About Pooling

Once the request/response logic was correct it was time to load test. Almost instantly, memory usage exploded and the garbage collector started thrashing. Inspecting ActiveMQ with the Web Console showed that MessageConsumers were hanging around even though they were being explicitly closed using Spring’s own JmsUtils. Turns out, the CachingConnectionFactory’s JavaDoc held the key to what was going on: “Note also that MessageConsumers obtained from a cached Session won’t get closed until the Session will eventually be removed from the pool.” However, if the MessageConsumers could be reused this wouldn’t be an issue. Unfortunately, CachingConnectionFactory caches MessageConsumers based on a hash key which contains the selector among other values. Obviously each request/response call, with its necessarily unique selector, was creating a new consumer that could never be reused. Luckily ActiveMQ provides a PooledConnectionFactory which does not cache MessageConsumers and switching to it fixed the problem instantly. However, this means that each request/response requires a new MessageConsumer to be created. This is adds overhead but its the price that must be payed to do synchronous request/response.

11 Lesser Known 3rd Party Libraries For Every Project

pennies_in_jar_small The Java 3rd party library ecosystem is a wild wild place. While everyone has heard of the big players such as Spring and Hibernate, too often the more humble, but equally important, libraries get left out in the cold.  It is for that reason that I give you the 11 lesser known 3rd party libraries that no project should be without.

Unit Testing

As always, the easiest place to start playing around with new libraries and languages is in unit tests.  I’m convinced they would be worth writing if only as an outlet for developers to try new and interesting tools, let along the code quality improvements.

DBUnit

While we can quibble over including databases in unit tests or if they are integration tests the fact of the matter is that at some point most people write a unit test that requires a database with some preexisting data.  Thats when DBUnit shines. It has the ability to use xml from a file or a string or any other type of input to clean and populate database tables with ease.  It even has some nice utilities for asserting data after a test has run.

Mockito

On the other end of the spectrum from full blown database integration is mocking. When you need to disentangle an object from its myriad of dependancies and test it in isolation mock objects come to the rescue. There are a number of solutions out there but Mockito takes the cake. To see why I prefer it to EasyMock check out their comparison. They’ve even added some niceties for BDD style testing.

Hamcrest Matchers

Since Junit 4.4, a core set of hamcrest matchers has been included with the distribution and has gone a long way to simplifying assertions by through a pseduo english DSL. For even more power you can include the whole hamcrest matcher jar and start playing with features such as asserting the contents of collections.

Apache Commons

Configuration

Most projects start with one properties file and before you know it there are two, then three, then ten and it gets out of control. You have static singletons that pull files off the class path and you’ve gone off the deep end. Thats why I say start Commons Configurations, even for that first file. Not only does it greatly simplify dealing with properties from the api point of view but it allows for pulling properties from xml, jdbc, property files, and much more. Its can even work as a simple api for dealing with xml in a jiffy.

DbUtils

These days with Spring JDBC, iBatis, Hibernate, ActiveObjects, and a host of other frameworks and libraries for dealing with JDBC its pretty easy to never have to directly touch the stuff.  However, if you find yourself in the hell which is closing a connection, session, and statement (with all the null checks and finals and exceptions and oh dear god) then Commons DbUtils is for you.  A simple close() method is provided which handles all the null checking and try catching and so on. So basic and yet so helpful.

IO

This one might be a bit more obscure but if you have ever needed to simply read the contents of a file you have no doubt been stymied by which reader gets wrapped by which buffered writer and who flushes what. Commons IO provides a beautifully simple api for file reading as well as some nice utility methods, similar to DbUtils, for closing all those annoying objects with out all the hassle.

Lang

If there was one library on my list it would come down to this or Google Collections. Commons Lang is the place for every utility method you have ever thought of writing. Every time you have though of creating a null safe version of any of the String methods, StringUtils has your back. If you have though of doing the same for Booleans then BooleanUtils is for you. Same for Object and ObjectUtils. But it doesnt stop there, StringUtils has more methods than you can shake a stick at and then there is the Builder package. The Builder package contains a Hashcode, ToString, Equals and CompareTo builder. Better yet they contain methods to build these values dynamically based on reflection. I’ve taken to making a base class from which all my domain objects inherit  that simply overrides Hashcode, ToString and Equals with the reflection based builders. Never again do you need to create these annoying methods by hand or have Eclipse generate them only to forget to regenerate when you add another field.

New Kids On The Block

SLF4J

Logging, everyone needs it. Thats probably why there are at least four major Java logging frameworks.  However, they are not all created equal. Java util logging is known to have a number of shortcomings when compared to Log4J and Commons Logging is just a facade that allows you to switch between the two more easily. Out of this mess comes SLF4J. Created by the creator of Log4J it is simply a set of interfaces that anyone can implement. The default implementation, also made by the same guy, is called logback and takes all the best of Log4J and improves on it. Moreover there are converters that route Log4J, CommonsLogging, and Java util logging to SLF4J. Never again do you have to struggle with multiple libraries and configuration files for all of your 3rd party libraries in your project. Simply drop in the converters and everything nicely flows into SLF4J.

Google Collections

Like I said before, if there were one library on my list it would come down to Commons Lang and Google Collections. If you have every used Commons Collections and cursed at its lack of type safety then Google Collections is for you. If you have ever balked at having to write List<Map<String, List<Integer>>> only to realized you have to type it all over again on the left hand side of the value assignment then Google Collections static methods such as newHashMap() are for you. If you are looking for a poor mans cache then MapMaker is for you. Finally, if you want to play around with functional programing ideas in Java look no farther than Predicate and Function and take it as a challenge to remove all for loops from your application.

c3p0

Database pooling, if you connectot to a database you need it. There are a few out there to choose from and the decision is always a bit of an argument but since Hibernate chose c3p0 as its default connection pool it has gotten significantly more attention than the other options and the prevailing winds seem to suggest that it is the way to go.

Joda Time

Not everyone has to deal with time in their programs but if you do, look no farther than Joda Time. From simple formatting to the complication of subtracting dates and everything in between, Joda Time is an easy to use api for all your date and time needs. No longer will you have deal with Calendars and wonder what exactly is a Gregorian one.

Efficient Lightweight JMS with Spring and ActiveMQ

Spring

© Darwin Bell

Asynchronicity, its the number one design principal for highly scalable systems, and for Java that means JMS, which in turn means ActiveMQ. But how do I use JMS efficiently? One can quickly  become overwhelmed with talk of containers, frameworks, and a plethora of options, most of which are outdated. So lets pick it apart.

Frameworks

The ActiveMQ documentation makes mention of two frameworks; Camel and Spring. The decision here comes down to simplicity vs functionality. Camel supports an immense amount of Enterprise Integration Patterns that can greatly simplify integrating a variety of services and orchestrating complicated message flows between components. Its certainly a best of breed if your system requires such functionality. However, if you are looking for simplicity and support for the basic best practices then Spring has the upper hand. For me, simplicity wins out any day of the week.

JCA (Use It Or Loose It)

Reading through ActiveMQ’s spring support one is instantly introduced to the idea of a JCA container and ActiveMQ’s various proxies and adaptors for working inside of one. However, this is all a red herring. JCA is part of the EJB specification and as with most of the EJB specification, Spring doesn’t support it. Then there is a mention of Jencks, a “lightweight JCA container for Spring”, which was spun off of ActiveMQ’s JCA container. At first this seems like the ideal solution, but let me stop you there.  Jencks was last updated on January 3rd 2007. At that time ActiveMQ was at version 4.1.x and Spring was at version 2.0.x and things have come a long way, a very long way. Even trying to get Jencks from the maven repository fails due to dependencies on ActiveMQ 4.1.x jars that no longer exist. The simple fact is there are better and simpler ways to ensure resource caching.

Sending Messages

The core of Spring’s message sending architecture is the JmsTemplate. In typical Spring template fashion, the JmsTemplate abstracts away all the cruft of opening and closing sessions and producers so all the application developer needs to worry about is the actual business logic. However, ActiveMQ is quick to point out the JmsTemplate gotchas, mostly that JmsTemplate is designed to open and close the session and producer on each call. To prevent this from absolutely destroying the messaging performance the documentation recommends using ActiveMQ’s PooledConnectionFactory which caches the sessions and message producers. However this too is outdated. Starting with version 2.5.3, Spring started shipping its own CachingConnectionFactory which I believe to be the preferred caching method. (UPDATE: In my more recent post, I talk about when you might want to use PooledConnectionFactory.) However, there is one catch to point out. By default the CachingConnectionFactory only caches one session which the javadoc claims to be sufficient for low concurrency situations. By contrast, the PooledConnectionFactory defaults to 500. As with most settings of this type, some amount of experimentation is probably in order. I’ve started with 100 which seems like a good compromise.

Receiving Messages

As you may have noticed, the JmsTemplate gotchas strongly discourages using the recieve() call on the JmsTemplate, again, since there is no pooling of sessions and consumers.  Moreover, all calls on the JmsTemplate are synchronous which means the calling thread will block until the method returns. This is fine when using JmsTemplate to send messages since the method returns almost instantly. However, when using the recieve() call, the thread will block until a message is received, which has a huge impact on performance. Unfortunately, neither the JmsTemplate gotchas nor the spring support documentation mentions the simple Spring solution for these problems. In fact they both recommend using Jencks, which we already debunked. The actual solution, using the DefaultMessageListenerContainer, is buried in the how do I use JMS efficiently documentation. The DefaultMessageListenerContainer allows for the asynchronous receipt of messages as well as caching sessions and message consumers. Even more interesting, the DefaultMessageListenerContainer can dynamically grow and shrink the number of listeners based on message volume. In short, this is why we can completely ignore JCA.

Putting It All Together

Spring Context XML

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:amq="http://activemq.apache.org/schema/core"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-2.5.xsd">

<!-- enables annotation based configuration -->
<context:annotation-config />
<!-- scans for annotated classes in the com.company package -->
<context:component-scan base-package="com.company"/>
<!-- allows for ${} replacement in the spring xml configuration from the system.properties file on the classpath -->
<context:property-placeholder location="classpath:system.properties"/>
<!-- creates an activemq connection factory using the amq namespace -->
<amq:connectionFactory id="amqConnectionFactory" brokerURL="${jms.url}" userName="${jms.username}" password="${jms.password}" />
<!-- CachingConnectionFactory Definition, sessionCacheSize property is the number of sessions to cache -->
<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
    <constructor-arg ref="amqConnectionFactory" />
    <property name="exceptionListener" ref="jmsExceptionListener" />
    <property name="sessionCacheSize" value="100" />
</bean>
<!-- JmsTemplate Definition -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
   <constructor-arg ref="connectionFactory"/>
</bean>
<!-- listener container definition using the jms namespace, concurrency is the max number of concurrent listeners that can be started -->
<jms:listener-container concurrency="10" >
    <jms:listener id="QueueListener" destination="Queue.Name" ref="queueListener" />
</jms:listener-container>
</beans>

There are two things to notice here. First, I’ve added the amq and jms namespaces to the opening beans tag. Second, I’m using the Spring 2.5 annotation based configuration. By using the annotation based configuration I can simply add @Component annotation to my Java classes instead of having to specify them in the spring context xml explicitly. Additionally, I can add @Autowired on my constructors to have objects such as JmsTemplate automatically wired into my objects.

QueueSender

package com.locamoda.messaging;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

@Component
public class QueueSender
{
    private final JmsTemplate jmsTemplate;

    @Autowired
    public QueueSender( final JmsTemplate jmsTemplate )
    {
        this.jmsTemplate = jmsTemplate;
    }

    public void send( final String message )
    {
        jmsTemplate.convertAndSend( "Queue.Name", message );
    }
}

Queue Listener


package com.company;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.springframework.stereotype.Component;

@Component
public class QueueListener implements MessageListener
{
    public void onMessage( final Message message )
    {
        if ( message instanceof TextMessage )
        {
            final TextMessage textMessage = (TextMessage) message;
            try
            {
                System.out.println( textMessage.getText() );
            }
            catch (final JMSException e)
            {
                e.printStackTrace();
            }
        }
    }
}

JmsExceptionListener

package com.company;

import javax.jms.ExceptionListener;
import javax.jms.JMSException;

import org.springframework.stereotype.Component;

@Component
public class JmsExceptionListener implements ExceptionListener
{
    public void onException( final JMSException e )
    {
        e.printStackTrace();
    }
}

Update

I have finally updated the wiki at activemq.apache.org. The following pages now recommend using MessageListenerContainers and JmsTemplate with a Pooling ConnectionFactory instead of JCA and Jencks.

Simple Interrupt Driven Multitasking with scripts

Compiling. Searching. Downloading with wget. They take a long time and are kind of boring to stare at. You have two choices. Choice one is to follow the xkcd model:

xkcd comic about wasting time compiling

xkcd comic about wasting time compiling

But once in a while, you actually have some other stuff to do. Maybe if you had a few minutes you could go a few emails closer to Inbox Zero or you could go watch something to make you smarter or go read something. Either way, if you’re like me and that guy from Momento and you try to do something else useful while your computer is working you will immediate forget that it was off doing your bidding and you will stumble across the idle terminal hours/days later.

Here’s a really quick solution. Put this script in your path somewhere.

#!/bin/bash

if [ $(uname) = "Darwin" ] ; then
  # osascript doesn't allow you to interact with the UI so just raise the terminal
  osascript < /dev/null 2>&1
elif [ $(uname) = "Linux" ] ; then
  zenity --title "Finished" --info --text "I'm done doing what you asked." > /dev/null 2>&1
elif [ $(uname) = "Cygwin" ] ; then
  echo "Left as an exercise for the reader. Helpful hints may be found at http://store.apple.com and http://ubuntu.com"
else
  echo "Unknown platform: $(uname)"
  exit 1
fi

I call it fin like that classy word at the end of old movies.

Then when you start a long running command run it like this:
bash$ go-search-my-whole-harddrive.sh ; fin
or
bash$ compile-my-kernel.sh ; fin

Then, when your thing is done, whether it worked or not, you will get some sort of indication that its done and you can get back to what you were doing.

I have really started to love this little script the last few days. One thing though, make sure that the other thing you start to do while waiting is an easily interruptable task or your brain will explode when the indication pops up. No one likes brain explosions.

Why emacs is still in my toolbelt

When I first started out as a developer one of the crackpot nutjobs with whom I worked at the time convinced me that emacs was absolutely the best editor to use.  I didn’t really know any better and he was by far the fastest and most nimble code navigator of anyone else in the group so I gave it a try.  Many hundreds of hours of elisp hacking and a 37MB ~/.emacs.d directory later I am a fairly well worn emacs yeoman.  For many years I used nothing but emacs, cramming all sorts of language modes in it to make it do fun stuff and syntax highlight everything from shell script to Java to Ruby to InstallScript (insert vomiting in own mouth joke here).

I say, with no small amount of nostalgia, that emacs is no longer the development workhorse it once was for me.  I spend most of my time writing large Java projects and have fallen prey to the siren song of fancy IDE’s with their “Show me a list of all the places this specific method is called anywhere in my project” tricks and “Refactor this entire package hierarchy with all the file renaming and moving and even rename the getters and setters to reflect the new names” chicanery.  Emacs had a few tricks to make it look like it was doing these things but it was always kinda hacky and required a great deal of TLC to keep it working across JDK upgrades and switching projects with environment variables and jdk-* elisp variables that were just right.

All that said, you can have my emacs when you pry it from my cold dead hands, and here’s a glimpse into why:

  1. Zip file handling smooth as a baby’s butt
    Have you ever tried to open a zip file with emacs?  Give it a try, its awesome. It shows you a normal list of all of the files in the zip archive.  No big deal, right?  Now move the cursor onto one of the files.  Shows you the file, doesn’t it.  Not bad, huh?  Now try editing the file.  Let’s you edit it, doesn’t it.  Now try saving it.  Oh baby.  Right back into the archive where it belongs and you don’t even have temp files to clean up.  Seriously? That’s worth the price of admission right there.
  2. That’s what you’re computer is for, numbskull
    If I see one more person with their hands hovering over their keyboards in some weird way just so that they can type “Down arrow, End, BkSpace, BkSpace” over and over for every line in a 500 line file I’m going to scream.  I know emacs is not the only editor that does simple macro recording and playback, but if your editor doesn’t have that (yes, I’m staring at your Eclipse) then you most likely have wasted some time this week.
    “C-x-( <do your thing here> C-x-) Ctrl-u 500 C-e” and 500 lines later your done.  Menial tasks should not be done by people.
  3. Graphical and terminal mode
    This may be specific to you server developers out there, but sometimes you just need a decent editor on a headless server.  I know, I know, use vi. If I wanted to ask my editors permission to type a letter I would install Clippy (ducks).  Sorry, had to get that in there.  Having a workable dev environment on a headless server has been a huge help on many occasions where fun graphical wizbang is just not an option.
  4. Cross Platform
    Linux, OS X, Solaris, even Windows if I really have to, but emacs comes with me everywhere.  It always works and so does my well worn ~/.emacs.d directory of everything I’ve ever needed.  Its a great way to lower the cognitive load of jumping around all the time.  What good is your trust side kick if it doesn’t come with you wherever the fates may carry you?

The list really goes on and on.  The idea here is less about emacs specifically and having really amazingly good reliable all purpose text editor to sit next to your honkin’ cool IDE and fill in the gaps.  If you are a gainfully employed programmer and you use notepad.exe for anything, then you are a thief stealing from your employer.

I’ll be honest, I spend a lot less time in emacs than I used to, but every good carpenter needs a good hacksaw/screwdriver/nail puller/hedge trimmer/ladder/rotary drill/french coffee press/drop cloth/tire rotater.  Right?

xkcd emacs comic

Top 5 Static Analysis Plugins for Eclipse

Eclipse Icon

Static Analysis

How is it that static analysis is still a best kept secret while so much lips service is paid to code reviews?  We have long since understood that boring repetitive jobs should be left for the machines, but when it comes to code inspection there seems to be a mental block.  Humans hold the advantage when reviewing architecture, use of design patterns and code organization, but a machine will find when a known null value is dereferenced 100% of the time and that can hardly be said for even the OCD coders I know.  Therefore, I present the top five static analysis tools for Eclipse.  While you might not have the delight of working on a project running continuous integration with a full unit test suite, code coverage, and static analysis, you can at least run your own private versions and rest comfortably knowing you’ve done your best.

Code Coverage

I assume at the very least that you’ve written some unit tests in Junit or maybe TestNG, the next step is to see if you are actually testing enough of your code.  Code coverage has saved me a number of times when I’ve been a little lax in my TDD discipline.  Having written some code, followed by some tests, its very easy to forget that one code branch and fail to exercise it; EclEmma to the rescue.  EclEmma installs a Coverage mode right next to the run and debug modes that are standard to Eclipse.  Simply run your unit test with the Coverage mode and bang, your code shows up bright green, yellow or red, letting you quickly know where you forgot a test or two.

Bytecode Analysis

The next level of analysis comes from the well respected FindBugs tool.  After installing the plugin, FindBugs inspects the actual .class files of your compiled code for well know bugs and other suspicious behavior.  I’m constantly surprised at the lack of false positives and overall quality of the bugs it finds, from comparing strings with ==, to failing to close resources, and more, its spot on.

Code Complexity Analysis

Next in my list of favorites is complexity analysis.  These metrics, from simple lines of code in a method to the lesser know but more powerful Cyclomatic Complexity and Efferent Coupling, are the closest thing to a “stinky code” test that software engineering has come up with.  If you strive for loose coupling and DRY code, then EclipseMetrics is right up your alley.  Once it is installed you will see warnings where your methods are overly long or complex, or your classes are poorly organized.  Let the OCD run wild.

Dependancy Analysis

Dependancies are one of those things that can go unnoticed until they bite you in the rear.  Once circular dependancies creep in it can become incredibly hard to break apart and modularize your code.  This might not seem important in a small to medium sized project but once a project scales up, the need to break it apart becomes critical and keeping your ducks in a line from the get go makes life that much easier.  For this task we employ JDepend4Eclipse.

Source Code Analysis

Finally we come to PMD. This is the twin brother of FindBugs.  Where FindBugs checks the .class file, PMD checks the .java file.  There is a lot of overlap here but you can find some interesting things like unused code that javac might have optimized away in the .class file.

Monitoring ActiveMQ Using JMX Over SSH

Frustration If you want to know true confusion and frustration I suggest you attempt to monitor ActiveMQ using JMX over SSH port forwarding.

For those who use ActiveMQ, the JMX monitoring is some pretty impressive stuff.  You can dive into connections, queues, topics, subscriptions, etc and get stats about the current state of the system.  However, this nirvana of information is practically unreachable when AMQ is in a data center.  For the first six months or so working on AMQ I was able to get around this using the web console which gives some level of detail on topics and queues but once we moved into trying to debug bigger and bigger problems the console wasn’t cutting it any longer.

The Investigation Begins

As with anything AMQ, I started looking into the JMX documentaion.  Step one was to enable JMX in the activemq.xml file.

<broker useJmx="true" brokerName="BROKER1">

Fire it up, forward port 1099 (the default JMX port), give it a try, and, no go.  Come to find out, JMX uses two ports, one which is defaults to 1099 and one which is negotiated at runtime.  No worries, there is an “Advanced JMX Configuration” seciton in the documentation which lead me to this xml configuration.

<managementContext>
    <managementContext connectorPort="2011" jmxDomainName="test.domain"/>
</managementContext>

Awesome, I can change the default 1099 port but nothing else.  The AMQ documentation was failing me, as usual.  Google, here I come.  After some searching around I was able to dig up AMQ-892.  (Power user tip, search AMQ’s Jira site once the documentation has inevitably failed.)  It turns out you can configure the RMI server port and have been able to do so since version 4.1.

<managementContext connectorPort="11099" rmiServerPort="11119" jmxDomainName="org.apache.activemq"/>

I particularly liked the “This necessitates a documentation update in the wiki.” comment from 2007.  Way to jump on that.  Confident that this is bound to work I forward port 11099 and 11109, give it a whirl, and, failure.  It was at this point that I started to despair.

Deeper Down The Rabbit Hole

Quickly running out of options I decided to try running the same configuration on a dev box in the office, and of course I could connect to it flawlessly.  To add insult to injury I tried another dev box and this one failed.  The only difference I could easily see was one was running a VM image and the other was native but this didn’t point at any easily understandable target.  I was done.  I conceded defeat.  I would soldier on without JMX.

Meanwhile, my co-worker had been pressuring me to start packet sniffing with wireshark.  I had resisted, mostly because I dislike getting that low level, but also because RMI is a binary protocol and I didn’t think I could learn much.  However, I was bloody and beaten at this point and gave in. I downloaded the package, fired it up and started sniffing away.  Sure enough the binary was a bunch of gibberish, but tucked away in there was one string, the hostname of the amq server I was trying to connect to.  What the hell is this?!?  That question is left to the reader but at least the issue was clear, the hostname was inside the data center and not something I could connect to from my machine.  It also jived with the test on the local dev boxes.  The box with the VM image had an internal hostname that was not in the office dns, where as the native machine had an addressable hostname.

I attacked the problem with renewed vigor.  I found a JConsole FAQ on the AMQ website that I had previously dismissed for its cryptic message.  However, this time it made sense.  I quickly added

-Djava.rmi.server.hostname=127.0.0.1

to the Java Service Wrapper configuration for AMQ so communication would be forced back through the SSH tunnel, rebooted AMQ, and, wait for it, VICTORY.

The Morale of the Story

So the short answer is add the broker configuration, the management context (the second on up there), and the rmi hostname configuration, port forward 11099 and 11109, and fire up jconsole

jconsole service:jmx:rmi://127.0.0.1:11119/jndi/rmi://127.0.0.1:11099/jmxrmi

As with most of these posts, so easy once you know, but so hard to get there.

Unit Testing Spring Jersey Integration

Recently, I’ve been working on a side project which has given me the opportunity to play with an interesting Java technology stack. After a few weekends of working on the build and moving my way up the stack from database to service layer I was at the point of writing a full integration test. In the past I’ve done integration testing with an iBatis/Spring stack, which, with the help of DBUnit is a fairly simple exercise. However, this project is heavily REST based and the addition of Jersey (JAX-RS) was a serious curveball.

To really test the whole stack an embedded webserver is required.  Looking through the Jersey/Spring unit tests they make use of an exploded WAR using Glassfish.  Assuming this was the optimal solution I added Glassfish to my ivy.xml config and ran an ivy update.  However, once I realized the overwhelming volume of jars being downloaded I decided it was much too heavy weight of a solution.

My next choice was Jetty.  I have had experience with using Jetty in the past but I quickly ran into issues trying to get it working right with Jersey, Spring, and an exploded WAR configuration.  It was then that I saw the GrizzlyServerFactory referenced in another Jersey unit test.  After some prodding and reading into the source code I ended up with the following:

final URI baseUri = UriBuilder.fromUri( "http://localhost/" ).port( 9998 ).build();
final ServletAdapter adapter = new ServletAdapter();
adapter.addInitParameter( "com.sun.jersey.config.property.packages", <your-package-name> );
adapter.addContextParameter( "contextConfigLocation","classpath:applicationContext.xml" );
adapter.addServletListener( "org.springframework.web.context.ContextLoaderListener" );
adapter.setServletInstance( new SpringServlet() );
adapter.setContextPath( baseUri.getPath() );
SelectorThread threadSelector = GrizzlyServerFactory.create( baseUri, adapter );

We start by making a base Uri for localhost at a high numbered port.  Then we build the Grizzly ServletAdaptor.  The first parameter is the package name where your Jersey enabled are located.  The next two lines are taken directly from the web.xml file that is used for the actual WAR.  The first is the config location for the Spring Context and the second is the ContextLoaderListener servlet.  Finally we add the Jersey SpringServlet and the context path.  With these two objects created we can build a SelectorThread and begin using the server using the Jersey Client api that I talked about in my previous post.  When you are done, don’t forget to call stopEndpoint() on the SelectorThread when you are done.

EDIT:

I’ve recently come across one additional helpful tip regarding this setup. If you need to get access to your ApplicationContext, for instance to get access to the spring managed DataSource for database testing, there is a simple but non obvious way of doing this. The simple part is using Spring’s built in utilities for getting the application from a ServletContext.


WebApplicationContextUtils.getWebApplicationContext( adapter.getServletInstance().getServletConfig().getServletContext() );

However, when I first tried this I got an unexplained null pointer exception. After a long while trying to google around for the answer I gave up and dug into the source code. Turns out you need to add one important property to the ServletAdaptor for this to all work.


adapter.setProperty( "load-on-startup", 1 );

This will force your adaptor to initialize the servlet immediately and you populate the ServletConfig and ServletContext so you can get the ApplicationContext from them.

REST calls and JSON results in Java

I recently had the need interact with Twittervision’s RESTful api from Java. As usual, I started googling around for a solution but nothing obviously stood out. There are a handful of RESTful java frameworks, but these focus on providing a RESTful api and not consuming one. Finally, after an annoyingly difficult search I found an impressively simple solution based on Jersey.

The point to realize is that Jersey provides both a sever and a client api. To make use of the client api requires three simple lines:

Client client = Client.create();
WebResource webResource = 
client.resource("http://twittervision.com/user/current_status/bdarfler.json");
String response = webResource.get(String.class);

The result is a string of JSON, but now, how to parse it. After searching around I ended up settling on json-simple. A few simple lines of code and we can get the address for any twitter user.

final JSONObject jsonObj = (JSONObject) JSON_PARSER.parse( response );
if ( jsonObj != null &amp;&amp; jsonObj.containsKey( "location" ) )
{
final JSONObject location = (JSONObject) jsonObj.get( "location" );
return location.get( "address" ).toString();
}

So, once again, simple stuff but not as obvious as I was hoping it would be.

Next Page »