A Software Craftsman's Toolbox: Lightweight Java libraries that make life easier.
As a software developer you will use plenty of frameworks during your career. There are the big beasts like Spring, ActiveMQ or OSGi that you have to master in order to build the foundations of your applications. And then, there are the small frameworks. Let’s call them lightweight tools. Like a carpenter, the lightweight tools are kept in a toolbox. The carpenter will use industrial machines to get his project started and shaped but he will always go back to his handy, personalized set of tools to finish up the details. In his toolbox he has many tools that each do just one job well. This post is about those tools!
Most of the time I work on the server-side. As a result my toolbox is full of libraries that are good for servers but not limited to them. So, I split up the tools into categories. Let’s start with the screwdrivers ;). Nothing bigger than a birdhouse can be built without screws! Screwdrivers in software development are core libraries. In my toolbox there are two.
The first one is Google Guava. You may have read some previous posts about Guava or you may already know this little library. For those of you who don’t, Guava is a core Library developed by, and also used at Google. It’s a good example of “What helps me, may help you”. This library contains a lot of helpers that you will find useful in your day-to-day work with Java. This includes working with collections, hashing, I/O, primitive types and others. It also contains what I think is a rich, enhanced feature set. This includes concepts for caching, functional idioms or an event bus. While most of the time I use the basics of this framework, I found the enhanced features are also useful for those special occasions.
When I am working with code that has to deal with date and time, the second core library that comes in handy is Joda Time. This library exists because Java’s Date API prior to 1.7 is simply “not so good”. The Joda guys rethought the problem of handling dates, and as a result created a well-designed, small, API for handling dates. Convince yourself with this self-explanatory example:
public boolean isAfterPayDay(DateTime datetime) {
if (datetime.getMonthOfYear() == 2) { // February is month 2!!
return datetime.getDayOfMonth() > 26;
}
return datetime.getDayOfMonth() > 28;
}
When it comes to implementing a WebService e.g. a REST API, the screwdrivers don’t help much anymore. A special tool is needed like a pipe box spanner ;). Two of the libraries I like most for the server-side are Jersey and Gson.
Jersey is an implementation of the JAX-RS specification. This specification defines an annotation-based API that makes it possible to publish plain Java objects as web resources. While Jersey is the reference implementation of JAX-RS it also influenced the JAX-RS 2.0 specification by providing a Client API that as far as I can tell, acted as a basis for the specification’s client API. Another cool thing about Jersey is its loose coupling. It ships as different jar files. The full bundle contains a server, the client and all the other stuff needed. But it can also be used as a plain JAX-RS implementation by bridging the specification API and the Servlet API. A nice side effect is that all jar files are packaged as OSGi bundles and a good OSGi integration exists ;). A simple service can look like this:
// The Java class will be hosted at the URI path "/helloworld"
@Path( "/helloworld" )
public class HelloWorldResource {
// The Java method will process HTTP GET requests
@GET
// The Java method will produce content identified by the MIME Media
// type "text/plain";
@Produces( "text/plain" )
public String getClichedMessage() {
// Return some cliched textual content
return "Hello World";
}
}
Gson is not dedicated to server-side deployment, but is widely used on servers. It’s a mapper between Java Objects and JSON. This is nothing new but the API provided by Gson is very useable. I don’t know the Gson developers but they seem to have committed themselves to this principle: “Make it easy to do the commonly correct thing. Make it possible to do the exotic things.” As a result it’s very, very easy to de/serialize objects with Gson and the standard de/serialization is good enough for 90% of the use cases I’ve encountered. But when it comes to special de/serialization it’s possible to hook in and define per type de/serializers. A simple serialization of an object looks like this:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
...
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
When we talk about servers we also need to talk about clients. So, when a client is implemented that uses any kind of HTTP connection one task comes up every time. This is sending requests. Honestly, I could never understand why this topic was so hard. I mean, it’s just sending some Strings over the ether. If you search for Java HTTP libraries you will find a whole bunch of them with all kinds of fancy features. But sorry - we’re talking about tools and adding a whole framework for just sending HTTP requests feels odd to me. Of course, there is the URLConnection API, but from my point of view, this is as suboptimal as the standard Date API. Recently I found one HTTP client wrapper that really fit my needs. This is the HttpRequest class from Kevin Sawicki. It’s just a single class called HttpRequest that provides static methods to send requests. That’s it! Ok, it makes testing a little more complicated, but this is a topic for another post ;). A simple HTTP request with this tool looks like this:
String response = HttpRequest.get( "https://google.com" ).body();
System.out.println( "Response was: " + response);
The libraries above are very useful but we haven’t talked about the tools that really form an application. These are tools for testing! In our carpenter’s world, these are the spirit levels (with the bubble) ;). I always go with Junit, so most of the tools I will list are for this framework.
If a core library for testing exists, for me, it’s definitely Mockito. The Mockito developers have done their job right! They have combined a kick-ass API with a rich feature set, and I really believe that the creators have brought mocking in Java to a new level. Mockito provides a well-designed, fluent, API to handle mocks. Probably the most valuable feature of Mockito is that it allows me to stick with the “build, operate, check” testing pattern. A simple mocked test looks like this in Mockito:
public class SecondPartTest {
@Test
public void testSomething() {
Strategy strategy = mock( Strategy.class );
Something objectUnderTest = new Something( strategy );
objectUnderTest.doSomething();
verify( strategy ).doSomethingConcrete();
}
}
The second library that is pretty handy is Caliper. It’s not really for testing but for performance measurement. (I just added this to the testing category for lack of a better place.) With Caliper you can code micro benchmarks. To understand what a micro benchmark is, it’s best to read the Caliper Definition:
A microbenchmark attempts to measure the performance of a “small” bit of code. These tests are typically in the sub-millisecond range. The code being tested usually performs no I/O, or else is a test of some single, specific I/O task.
Microbenchmarking is very different from profiling! When profiling, you work with an entire application, either in production or in an environment very painstakingly contrived to resemble production. Because of this, you get performance data that is, for lack of a better term, real. When you microbenchmark, you get a result that is essentially fictional, and you must be very careful about what conclusions you draw from it.
The cool thing about Caliper is that they also provide an app to view the results in a meaningful way. They also store the different runs of your tests for comparison. It’s worthwhile to take a look at it. A simple micro benchmark can look like this:
public class MyBenchmark extends SimpleBenchmark {
public void timeMyOperation( int reps ) {
for( int i = 0; i < reps; i++ ) {
MyClass.myOperation();
}
}
}
The last tool for testing I wrote myself. (So, yes, here comes a little self-marketing ;).) This library is called restfuse and it’s for testing REST APIs. I wrote it to solve the pain of spending half my test code building up simple requests. Restfuse just sits on top of JUnit and uses the JUnit @Rule mechanism to accomplish its tasks. The thinking behind it is that the request is just a configuration topic and this can be executed outside of the test method’s body. The result is an annotation-based API that’s also capable of testing asynchronous REST API’s. A simple test can look like this:
public class RestfuseTest {
@Rule
public Destination destination = new Destination( "https://restfuse.com" );
@Context
private Response response; // will be injected after every request
@HttpTest( method = Method.GET, path = "/" )
public void checkRestfuseOnlineStatus() {
assertOk( response );
}
}
Editor’s note: Restfuse is no longer maintained and has been archived. However, you can still access the sources on GitHub.
Now you know what’s in my toolbox! Feel free to disagree or let me have a look inside your toolbox by writing a comment ;).