Coding Clarity

Writing simple, clear and readable code.

Browsing Posts in Java

Two of the most useful tools to a developer outside of their development environment are version control and bug tracking systems. Version control allows tracking of changes to the product and allows for branching and merging. Bug tracking systems allow for tracking issues with the product whether they be bugs or enhancements.

Even though these tools are often separate products, they have a major commonality which is the code you are working with. Often times you want to be able to see for any given bug number, what code was changed for that bug. Also, for a change in the code (in version control) you want to see if it was associated with a particular issue in the bug tracking software.

At the company I work for we use Subversion for version control and Bugzilla for bug tracking. We have some best practices around these tools to make things easier.

Version Control and Bug Tracking Best Practices

When resolving issues in the bug tracking database, our team always puts in the build number of the build that contains the fix. This way a person who is looking at the bug can know if the build they have contains the fix. Anytime our team fixes a bug we put in a comment that looks like this:


Build Fixed: 1.0.1.12354

The last number is the revision number in Subversion.

When we commit code changes to Subversion, we also include the bug number for the bug being fixed. Our commit messages always appear in this format:


Bug 1234: Fixed this bug

Subversion Tooling

Recently I came across a neat feature in Subversion that allows you to link it to a bug tracking system. Basically this allows clicking on the bug number in the subversion history view to take you directly to the bug number in the bug tracking software.

Enabling this feature is fairly simple to do and involves setting 2 properties in the subversion repository. These properties need to be set on the root folder in subversion that you would use to checkout your project from. It automatically is available for everything in that tree but you need to checkout from this root for it to work. These are the two properties that need to be set.

  • bugtraq:logregex – This defines a regular expression to ‘match’ bug numbers in subversion comments. For the pattern I listed above, we are using: [Bb][Uu][Gg] (\d+)
  • bugtraq:url – This defines a URL to go to when the user clicks on a bug number. The browser is launched when the number is clicked on and takes you to this URL replacing the BUGID parameter. For our bugzilla repository we are using: https://some.server.somewhere.localhost/show_bug.cgi?id=%BUGID%

The following steps walk through this process of how to set this up using Tortoise SVN:

  • On the root folder of your subversion working copy, right click on the folder and click TortoiseSVN -> Properties.

  • Add each property listed above as new properties to the list.

A lot of the work I do deals with integration with a third party system. Each of these systems typically has their own API and mechanisms for handling errors. Often times writing some code to ‘wrap’ the API is required to make it easier to use from an application. Many times this ends up being an ‘adapter’ from the third-party API format to something more manageable and familiar to the application you are writing.

If you write this sort of thing in Java, you usually end up having a lot of duplicate code, specifically around error handling, that is hard to reuse without a lot of extra code. Lately, I have been using Groovy to solve these sorts of problems. The rest of the post shows a few ways I have learned to use Groovy to solve these problems in a better way. The result is simpler, more readable code.

Groovy Closures for Error Handling

Have you ever written this around a few methods?


try {
    // Some code in here
}
catch (APIException e) {
    log.error(e.getMessage(), e);
    throw new WrappedException(e);
}
finally {
    // cleanup here
}

Using Groovy’s Closures, this can be written as a single closure to do the error handling. Doing error handling this way is much simpler and allows the code to be reused easily.


// Definition of error handling closure
def errorHandling = { Closure c ->
    try {
        c()
    }
    catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new WrappedException(e)
    }
    finally {
        // cleanup here
    }
}

// Code with error handling
errorHandling {
    // Some Code in here
}

For those not familiar with Groovy’s closures, let me explain what is happening here. The errorHandling variable is defined as a closure and is invoked around the code. This closure in turn takes a closure (function or code block in other languages) as a parameter. The error handling routine provides the stock error handling through the standard try catch syntax. Inside the try block, it invokes the closure that the user passed in. This allows the same error handling logic to be reused with the code to run being dynamically provided by the caller.

Groovy Categories for Mapping

Another problem is adapting between types in your application and types in the third party application. This is further complicated when dealing with collections of objects. Consider the following Java code to map from one system to another:


// Assumes some object instance 'util' is provided to map between object types.

// Given an input of InternalObject internal
List<InternalObject> list = new ArrayList<InternalObject>();
List<ExternalObject> results = api.operation(util.mapToExternal(input);
for (ExternalObject o: results) {
    list.add(util.mapToInternal(o));
}
return list;

Instead of defining mappings as methods in some utility class, Groovy categories can be used to provide a more readable syntax.


// Category definition
class MappingCategory {
    static List<InternalObject> toInternalList(List<ExternalObject> o) {
        o.collect { toInternal(it) }
    }

    static InternalObject toInternal(ExternalObject from) {
         // Map from External to Internal
    }

    static ExternalObject toExternal(InternalObject from) {
         // Map from Internal to External
    }
}

// Code using the category. Input object is 'input'
use (MappingCategory) {
    api.operation(input.toExternal()).toInternalList()
}

The groovy category essentially adds dynamic methods to both the InternalObject and ExternalObject. The definition of the category has static methods which take one or more parameters. The first parameter is the class that the method should be added to. When the new method is invoked, the object it is invoked on is always added as the first parameter.

Also being used here is the list ‘collect’ method. This replaces what needed to be done in Java with creating a new list, looping over each item, converting it and adding it to the new list. The collect method does this in a single step by using a closure that converts the object to a new format. The result is a new list with the objects in the new format but in a single line of code.

Putting it all Together

Using this category can also be combined with the error handling closure that was previously introduced. Consider the following updated version of the error handling closure.


// Definition of error handling closure
def errorHandling = { Closure c ->
    try {
        use (MappingCategory) {
            c()
        }
    }
    catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new WrappedException(e)
    }
    finally {
        // cleanup here
    }
}

With the previously defined error handling closure and category to handle the mappings, we can finally create a very minimal and readable adapter between our system and the third party system. Consider the following operation that uses the third party API. The input and output takes objects in the internal format.


public List<InternalObject> operation(InternalObject internal) throws WrappedException {
    errorHandling {
        return api.execute(internal.toExternal()).toIncidentList()
    }
}

Groovy’s closures allow error handling to be defined more easily and centralized in a single location where the code can be reused. Groovy’s categories allow data transformations to be done in a more readable fashion. The result is code that is easier to read and use.

I had the privilege of attending the SpringOne2gx conference this year in New Orleans. This is the first tech conference I have attended. Where I live, in Moncton, is a bit off the beaten path and is a bit far to travel to these types of conferences regularly. Past employers of mine have not always invested in their developers as much as they should. Thankfully, iWave Software was able to send me this year.

I had an excellent time at the conference and met a lot of smart and equally minded developers. There was plenty of great content at the conference and the Roosevelt hotel in New Orleans was a great place to host the conference. The food was amazing the the service top notch. On a whole the conference was a great experience.

For me, I made a Smörgåsbord of the conference taking a bit for all of the tracks that were provided. In the rest of this post I would like to cover some details on the plethora of technologies on display. Most of them were from SpringSource, the commercial company that backs the Spring technologies. There was a lot of great stuff but some of it I am a bit more skeptical on. The following are purely my opinions on what I saw. I am by no means an expert on any of these technologies but I do want to give you my first impressions of these from the perspective of a Software Developer and Architect working in the Enterprise IT space.

Spring Framework 3.0
One of the main focuses of the conference was the upcoming Spring Framework 3.0 release. Beyond just the framework itself, many of the other technologies leveraged some of the new 3.0 features. RC2 of the release should be available shortly. I would like to touch a bit on the feature set and particularly what excites me.

  • Spring Expression Language (SpEL) – This is one of the coolest new parts to the framework. A new expression language can be used to evaluate expressions related to other beans. In simple cases you can use something like #{refBean.value} in either the value attribute on a property or in the annotation directly. More complex expressions are also supported. This will be able to simplify configuration a great deal.
  • @Configuration – This is a rework of the Spring JavaConfig project that allows you to write your spring configurations in Java code directly. This project is now merged into the Spring framework 3.0. This feature did not excite me a whole lot. It seemed like something ‘cool’ but not something I would likely use. The main benefits of using this over XML were explained to be for refactoring, strong typing and losing the verbosity of XML. The refactoring and strong typing is less of an issue if you are using the Spring IDE (or STS) since it does all of that for you and even shows you where errors are. As for the syntax, I found the @Configuration to be clunky and still pretty verbose. If I wanted to express beans in code that are more readable, I would just use the Grails SpringBeanBuilder.
  • Java 5+ – Spring Framework 3.0 will be Java 5 and higher only. This is a great thing because it means that the core framework will fully support generics. All of the core libraries have been updated for this. In the past I stayed away from the JpaTemplate and other Spring libraries because the lack of generics made them more verbose than what I could write in wrappers of my own.
  • Task Executors – All of the scheduling stuff and executors were refactored. The Java 5 until.concurrent package is now used instead of the spring wrappers that they had. Also, scheduling is supported as part of Spring now. So for simple scheduling jobs (including cron), only spring will be required. This is nice since it is a common thing that is needed and Quartz is pretty heavy for this simple feature.
  • Rest Support – Spring Framework MVC now supports Rest. If you are an Spring MVC developer, this is very nice since you will be able to do REST directly from a @Controller method. If you are not using Spring MVC, there is no reason to look into this. The JAX-RS (JSR-311) spec is the way all of the other Java REST frameworks are going. I don’t see any reason to use this custom syntax over the standard for Rest unless you are using Spring MVC.
  • OXM – The Spring WS project created a bunch of stuff for handling Object to XML Mapping (OXM). Basically this is ORM for XML instead of a database. JAXB is one of the most popular frameworks for this and it is built in to the JVM. The OXM from Spring WS is now part of the core framework and allows anyone to have a single binding interface that can delegate to anyone of the many OXM frameworks out there including JAXB, XmlBeans, JiBX and Castor. This would be very nice for someone who wanted to support many different binding types but didn’t want to have to write all of that from scratch.

    On a whole the Spring Framework 3.0 release looks solid. I am going to have to grab the RC and check it out.

    Spring Roo
    Spring Roo was one of the technologies being shown at the conference. I had heard of it before but did not really do much digging into what it was. In a nutshell, it is a coding by convention framework for building applications (mostly web) in Java. Similar to Rails or Grails, it provides a console based utility to create entity beans (model), controllers and views. Instead of taking the dynamic language approach, Aspect J is used to merge common tools and scaffolding into the Java beans you create. It is a very cool product especially if you don’t have the luxury of using dynamic languages.

    One of the more impressive aspects of this was the console they created. The console was intelligent and had full auto-complete support. I would like to see other console based applications use this type of thing in the future.

    I played around with this a bit. It worked well for what it did. It will likely be used mostly for rapid prototyping. I think if I had to do a new web project, I would probably just do it in grails since I am already comfortable with Groovy. This would be great for people learning Java or with a need to rapidly prototype something in Java using Spring. Also, it saves the hassle of setting up things like JPA and MVC. Once the scaffolding is in place, you can customize it how you need.

    SpringSource Tool Suite 2.2 (STS for short)
    The SpringSource Tool Suite is an eclipse based development environment for all things Spring. It includes the old Spring IDE capabilities for editing spring XML files, support for Spring Roo, Groovy, Grails and Maven. The whole package works very well (except for the fact that the 2.2 release did not include the groovy plugin).

    Not much is really new here. I had been using the Spring IDE and Groovy plugins already. Most of the components are available standalone. This will be very useful for people who don’t have any of these plugins and provides a single download.

    The main focus of the IDE was centered around delpoying to dm Server and tc Server, both of which are included. The new Groovy plugin is great and has greatly improved over the last little while. It is available standalone which is probably how I will use it for now as I don’t have a need for many of the other features at this time.

    Spring Integration
    Spring Integration is like an ESB inside a single JVM. It seemed like a good project if you had a need for this type of thing. For me, I see the crossing JVM boundaries (clustering) one of the most important aspects of an ESB and this does nothing to tackle that problem. The samples that were presented showed how the integration could be done with OSGi. The capabilities were there but the configurations were very verbose and required writing some code in places for filters and other such things. I kept thinking how much easier it would be to just do these things in code directly and they would be a whole lot simpler. Thread Pools are so much easier now with Java’s util.concurrent and dynamic languages do routing really well. Both of those I am comfortable with. I think this project still has a long way to go before it can truly compete with an ESB type product.

    Spring Batch
    Spring Batch was shown alongside Spring Integration for handling large batch operations. The framework looked good and provided a lot of monitor capabilities around the status of the batches.

    SpringSource tc Server
    tc Server is SpringSource’s enterprise version of Tomcat. Essentially they took standard Tomcat and wrapped it with better monitoring and clustered deployment capabilities. This looks like a great solution for services type companies who want to deploy to a more enterprise version of Tomcat. For a products company though, it may be more difficult to manage since it is a commercial product. Most customers I have encountered either want to use their millions of dollars JEE environment or expect you to provide your own.

    SpringSource tc Server Developer Edition
    The Developer Edition of tc Server was announced at this conference. The main feature included here was called Spring Insight. This is a very cool tool targeted at application developers. It provides real time monitoring of an application that gives developers information about what is going on in the application. It includes health information, performance and the ability to drill down on web requests to see each call. Even SQL queries being run are shown from this console.

    Everything is done through AOP runtime weaving so no code changes are required to run in this environment. Also, having this free for developers means developers will have a great environment for analyzing the performance of their applications. This is definitely something to check out for anyone who has a .war application.

    SpringSource dm Server
    SpringSource dm Server is Spring’s OSGi server. Similar to tc Server, this is an enterprise grade OSGi Server. They provide a lot of features to make OSGi easier including being able to deploy a standard .war file to the server and have it run.

    OSGi is ready for prime time and has proven to be. It is definitely not one size fits all though. It is not something you just use because you can or because it is cool. The demos of dm Server and OSGi with Spring with littered with caveats and workarounds. OSGi is a great platform but still has a lot of pitfalls for application developers. Yes it has some cool things you can do with dependencies and versioning but they are not free.

    Grails
    I did not get into any of the Grails sessions. There were too many sessions I wanted to attend and I have already had some exposure to Grails so I stayed away from these for the most part. On a whole, it seems like Grails has come a long way from a competitive web framework to one of the best ones out there. If I had a new web application project to do, I would be most likely to choose Grails to do it in.

    Griffon
    Griffon is one of the newer Groovy frameworks to come out. It provides a Coding by Convention framework for Swing development and is targeted for developing Rich Internet Applications. The core is based on the Grails and will likely be familiar for those who already have Grails projects. The framework is built around making MVC easy through Swing and use of data binding. I am really looking forward to digging into this more.

    The biggest hurdle I see is being able to leverage this technology in an existing application. One of our main products is a very large Swing based IDE. The code has been around for a long time and could benefit from newer patterns for GUI development. I would love to be able to integrate Griffon into it but at this time it may not be easy. I intend to look into this more to see if it is possible.

    Groovy
    This groovy language has also come a long way. I started using it when 1.0 was released. Since then it has really grown in capabilities. I learned a few tricks this time that I was not aware of. Most of them had to do with the annotations that were added in 1.6.

    The biggest thing for Groovy though was the IDE support. I love the groovy language but have found that I could write Java faster in many circumstances even though I write more than twice the amount of code. The reason is because of the IDE support. Code Completion, Import completion and Refactoring are huge. The new Groovy plugin for eclipse is fantastic and includes all of these. Finally, I feel I can switch to using Groovy as my primary development language on the JVM. This is also a big step toward convincing others of the benefits of Groovy.

I have written about the Groovy language a few times. It is a wonderful language and integrates seamlessly with Java. Recently, I have found that it can be very useful for templates and filters.

Using Groovy for Filtering

Consider an application where there are many events that fire on certain conditions. The Observer pattern is often used for these types of event handlers. Also consider that the user (not the developer) wants to restrict or filter out events so only the ones they want are fired by the handler. Essentially the user needs a filter language where they can express their business rules. This filter needs to exist outside of the regular codebase so the user can change it on the fly.

Groovy solves this problem very neatly. Consider an Event class with the following properties:

  • severity
  • timesCalled
  • message

Assume that an instance of this class is provided as the object ‘e’. In groovy we could express a filter script that takes events with a severity less than 2 or times called greater than 5 as the following:


e.severity < 2 || e.timesCalled > 5

The above script is pretty simple and is easily written by a technical savvy user. I have written a simple helper class that facilitates creating reusable scripts like our filter script. Here is the code:


public class ReusableScript {
    private GroovyClassLoader gcl = new GroovyClassLoader(getClass().getClassLoader());
    private Class scriptClass = null;

    public void setScriptString(String scriptString) throws UnsupportedEncodingException {
        if (scriptString == null || scriptString.trim().equals("")) {
            return;
        }
        InputStream in = new ByteArrayInputStream(scriptString.getBytes("UTF-8"));
        scriptClass = gcl.parseClass(new GroovyCodeSource(in, "Filter", ""));
    }

    public Script newScript() throws Exception {
        if (scriptClass == null) {
            return null;
        }
        return (Script) scriptClass.newInstance();
    }
}

To use this script to actually execute the filter, you would do something like this:


// Creating the filter script. Assumes filterString is set by the user (I use spring for this)
ReusableScript filter = new ReusableScript();
filter.setScriptString(filterString);

// Typically this code would be running in the event handler. Assumes that an object e is available that is the event
filterScript = filter.newScript();
// Bind the 'e' object into the binding context of the script
filterScript.setProperty("e", e);
Object result = filterScript.run();
if (result instanceof Boolean && ((Boolean) result).booleanValue() == true) {
    // The filter has passed.
    // ... Code that performs the operation
}

Very little code is actually needed to put this together. The ReusableScript class can be used many times. The groovy code is only compiled once so performance is very good.

Using Groovy for Templating

A similar problem is the problem of templating. Consider an application that sends emails on error conditions. The user may wish to customize the email message that is sent out. They also may want to be able to use information from the application to provide meaning to the message. There are many template and expression languages available for Java. I have looked at using Apache Commons EL and Velocity. My main complaint on these languages is their complexity. It requires learning a new language syntax and integrating them often requires quite a bit of code. Let’s consider a more groovy solution.

Using the same ReusableScript class as used for filtering, we can provide templating. Consider a data class called Event that contains the following properties:

  • message
  • detail
  • hostname

Consider the following Groovy script that creates the body of an email message:


"""[$e.hostname] An error occurred: $e.reason

$e.detail
"""

This may produce a message that looks like this:

[localhost] An error occurred: File not found: abc.txt

FileNotFoundException ...

This is essentially making use of Groovy’s Templates that are built in to the language. The template engine can be used by itself standalone, but this provides a simpler integration. The other benefit is the if more complicated logic is required beyond a simple template, actual groovy code can be written beyond the simple script. The script is a full groovy script and would allow you to essentially do anything from it.

The template script would be loaded the same way as our previous filter script. This time instead of evaluating the script as a boolean, we get it as a string.


// ... Setup of filter script ...

Object result = filterScript.run();
if (result instanceof String) {
    // Code that uses the string
}

So that is two easy ways the Groovy can be used in a Java application to solve some of these simple problems.

I was listening to the Stackoverflow podcast number 41 today. One of the issues discussed was unit testing and when is it beneficial to do unit testing. I agreed with some of the points but not all of them. The point I especially found interesting was the “eating your own dogfood” concept where writing tests forces you to use the interfaces you created. I also never considered the perspective on tests serving as documentation or a spec on how the system should work.

There are lots of good reasons to do unit testing but there are a few issues I have run across with it that go beyond the obvious ones of time and effort.

  • Bugs in the tests – Let’s say a hypothetical programmer creates a bug in every 100 lines of code he writes. Logically, that would mean he would be creating a bug in every 100 lines of test code also. Unit tests do provide a double check to validate your code but a bug in the unit test could give you a false positive that your code works. A programmer who writes bad code will also write bad unit tests so even additional unit test coverage will result in poor code quality.
  • Tests are Bias – Unit tests are written by the programmer who wrote the code. If the programmer misunderstands how the code works or should be used (even if they wrote it), then it is likely that the test will also be built around this misunderstanding.
  • Test Failures due to design changes – Most times when I see unit tests fail it is because the code that was being tested was intentionally changed. Often the test is the last piece of code to be updated (right or wrong) to the new functionality of the rest of the system.
  • Code that Must be Maintained – Tests are additional code that developers need to maintain. I try to write as little code as possible to keep it clear and simple which makes it hard to justify writing a lot of extra code.

Writing tests requires effort. They take time to develop and maintain but they do have a payoff. I try to find a balance between the “100% test coverage” people and the “we don’t need any tests” people. The following is a list of criteria I use as a general guide to what I feel is most important to test. I choose the stuff that is most important areas to test.

  • Libraries – I always make sure I write tests for common libraries or utilities. These are generally easiest to test and are designed to be used in many places. Testing these has the biggest payoff.
  • APIs – APIs are a contract between systems. These are logical choices for tests as they should not be changing often and have strict rules.
  • Business Logic/Rules – Anytime there are business rules or logic that perform some defined function where there are clear inputs and outputs, these should be tested.

Libraries are usually number one on my testing priority. I usually aim for 90% or more coverage. GUI testing I have found to be of little benefit since the effort is so high and you end up with very little reward. Glue code or anything that ties different components together is hard to test and are more easily tested with basic smoke tests on the complete product.

The Zune Bug

A few weeks ago I heard of this issue where the Microsoft Zune crashes and won’t startup on December 31, 2008. The reason for this? A bug in the software that handled leap years. There are lots of articles on the original issue.

When I heard of this issue, I originally thought ‘How could that happen?’. Sure I could understand not handling things correctly when it is a leap year but causing a crash?

Well, if you like me were wondering how that could happen, you can now find out for yourself. This is a post someone made of the actual code that runs on the Zune. Look at line 249 and on.

If you missed it, there is a bug (obviously) where if the number of days passed in is 366, which is the case for December 31, 2008, the loop never terminates. The code checks to see if days is greater than 365 in a while loop. It then handles the greater than 366 condition but never checks if the days is equal to 366.

Write as Little Code as Possible

The less code you write the fewer bugs you will have in it. Most languages today have built in support for common tasks. One example of this is the Java Calendar object which would allow a developer to do what the zune code does using the platform APIs. Unfortunately, High level languages are usually not an option when writing code for a small embedded device.

Tips for writing as little code as possible:

  • Start with a high level language. Preferably use an agile and dynamic language if possible (Groovy, Ruby and Python etc). This of course depends largely on the requirements of the application.
  • Where possible using the built in platform APIs to do what you need.
  • Use open source software to fill in the gaps of platform APIs. Apache and Codehaus are great sources of open source software that are commercial friendly to ship.

For one project I was working on, I needed to get access to the SOAP headers of web service call. I am using the Apache CXF services stack. There were quite a few threads on how to get access to SOAP headers from an interceptor. In my case, I needed the contents of the header inside the implementation.

wsdl2java does have the ability to create a java service class that provides access to the headers using the -exsh option. This was not an option for me since even with this flag on, the headers were not added to the service calls. I think it was how the WSDL I had was designed. This meant that I needed to do the work of pulling out the headers myself.

The SOAP headers can be retrieved from the JAX-WS SOAPMessageContext the easiest. Getting access to this was not trivial. I added the resource annotation to get access to the WebServiceContext. Unfortunately the MessageContext this gave me was not a SOAPMessageContext and provided no way to access the SOAP headers.

After looking through the code for the SoapMessage CXF class, I found how it gets the headers out of the Message. I came up with the following to access the headers from my implementation class:


@Resource
private WebServiceContext context;

private List<Header> getHeaders() {
    MessageContext messageContext = context.getMessageContext();
    if (messageContext == null || !(messageContext instanceof WrappedMessageContext)) {
        return null;
    }

    Message message = ((WrappedMessageContext) messageContext).getWrappedMessage();
    List<Header> headers = CastUtils.cast((List<?>) message.get(Header.HEADER_LIST));
    return headers;
}

This provides all of the headers available. To get the specific one I needed using JAXB I added the following to my code:


List<Header> headers = getHeaders();
if (headers != null) {
    for (Header h: headers) {
        Object o = h.getObject();

        // Unwrap the node using JAXB
        if (o instanceof Node) {
            o = getJaxb().createUnmarshaller().unmarshal((Node) o);
        }

        if (o instanceof DesiredHeaderType) {
            // Do whatever is required with the header object instance
        }
    }
}

This way of accessing the headers turns out to be much simpler than writing an interceptor and trying to stuff the results of that into the request.

I use JAXB in conjunction with Apache CXF for web services. One requirement for the data model is to allow data fields to be “cleared”. This is done by entering no value in the XML. Data elements of the model can also be left out completely. This means that the value should not be set and is very different from a clear. Consider a JAXB class with one string field, one number field and one date field.


<string-value/>
<number-value/>
<date-value/>

The previous XML indicates that the string, number and date values should all be cleared. The actual values you would get in the data model are as follows:


string-value: "" (empty string)
number-value: NULL
date-value: NULL

If no XML was passed in, the following would be the resulting values in the data model:


string-value: NULL
number-value: NULL
date-value: NULL

For string values, you can tell if the user intends to clear the value by checking if the value is empty string. The problem comes in when you look at the number and date fields. You get NULL if the XML element is present or not. This makes it impossible to tell the difference between no XML being specified and an empty XML element.

The solution I came up with was to use a special number and date to denote a clearable value. I wanted to pick numbers that should never occur in the data model so I chose the following:


Date: Epoch, 1970-01-01T00:00:00.0-00:00
Number: Integer.MIN_VALUE, -2147483648

In JAXB, I set these values to the “default value” in the XML schema. This means that if the user types in the XML element by itself with no text value, it should be treated as the default value. If the user leaves the element out, according the the schema spec, the default value should not be used. This is exactly the behaviour I want for the “clearable” fields.

On the data model class, I added the annotations on dates and numbers respectively (actually I used a constant):


@XmlElement(defaultValue="1970-01-01T00:00:00.0-00:00")
@XmlElement(defaultValue="-2147483648")

Now, if you have the original XML example:


<string-value/>
<number-value/>
<date-value/>

You will get the following values in the data model:


string-value: "" (empty string)
number-value: -2147483648
date-value: new Date(0) (1970-01-01T00:00:00.0-00:00)

Now we can easily differentiate between an empty XML element and leaving out the element altogether.

I receive a lot of traffic to my post about HTTP Basic Authentication in Apache CXF. I decided to do a followup to that post to address some of the comments.

I have never tried to use this with Mule but if someone has, please let me know so I can update this post.

I have uploaded the Java code for the BasicAuthAuthorizationInterceptor class. There are a few changes over the original version. This one includes a Map of authorized users and their corresponding passwords. I believe the original example I created was for Apache CXF 2.0. This version works with Apache CXF 2.1.1.

In the original post, I also did not include a sample of how to use this code in a real application. The following section shows a sample of how to define the security interceptor and enable it on a simple endpoint.


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

    <bean id="securityInterceptor" class="BasicAuthAuthorizationInterceptor">
      <property name="users">
        <map>
          <entry key="username" value="password"/>
        </map>
      </property>
    </bean>

    <bean id="service" class="sample.Service"/>

    <jaxws:endpoint
      id="serviceEndpoint"
      implementor="#service"
      address="${services.url}/Service">
      <jaxws:inInterceptors>
        <ref bean="securityInterceptor"/>
      </jaxws:inInterceptors>
    </jaxws:endpoint>
</beans>

I’ve decided to use Apache Maven for building the code for my new project. So far I have had a love-hate relationship with Maven. If you don’t know what maven is, the folks over at Apache say Maven is …

“… a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project’s build, reporting and documentation from a central piece of information.”

Unfortunately that definition is about as vague as you can get so I will explain what Maven gives me and my project. This also happens to be the list of what I love about Maven:

  • Maven enforces a standardized project structure to all modules in a project.
  • Maven handles dependencies between libraries.
  • Maven builds all of my code and creates a distribution package.

Essentially by using Maven, I can get all of these things without having to write and maintain ant scripts to do most of the work for me. Maven is not without its problems though.

  • Often times the number of lines of XML you need to write ends up to be just as complicated and long as an ant script to do the same thing.
  • I’ve found a lot of bugs particularly with the assembly module. It seems to include dependencies of modules that are set with the “compile” or “test” scope only.
  • The Groovy building plugin for maven does not yet work for Groovy 1.5.x.

I still think using maven was a good choice for my project. It may have some qwerks but I think that I am further ahead than if I had to build everything from scratch.

Using Maven to Generate a Build Number

Earlier I metioned that I use the subversion revision number as a build number. This is actually quite easy to do from Maven. The following plugin descriptor provides you access to the subversion revision number using the ${scm.revision} property.


  <build>
    <plugins>
      <plugin>
        <artifactId>maven-scm-plugin</artifactId>
        <executions>
          <execution>
            <id>getting-scm.revision</id>
            <phase>validate</phase>
            <goals>
              <goal>update</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

Once you have access to the revision number, you can construct a build number using the product version and the revision number. I have added this build number to the Implementation-Version property of the jar manifest. The following plugin definition does this for me:


      <plugin>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <archive>
            <manifestEntries>
              <Implementation-Version>${this.version}.${scm.revision}</Implementation-Version>
            </manifestEntries>
          </archive>
        </configuration>
      </plugin>

The resulting manifest in the jar looks something like this:


Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: cdail
Build-Jdk: 1.6.0_03
Implementation-Version: 1.0-SNAPSHOT.93

From Java code, this build number can be easily retrieved. The following code retrieves the Implementation-Version from the manifest:


Package p = getClass().getPackage();
String version = p.getImplementationVersion();

The result is quite elegant but it takes a bit of work to get things into place. Like with many other things to do with Maven, it takes a while to figure out how to do what you want and you need to write a bunch of XML. Once that was done, everything fell into place. It is hard to say at this point if this is better or worse than the chunk of ant script I used to use to perform the same function.

Powered by WordPress Web Design by SRS Solutions © 2010 Coding Clarity Design by SRS Solutions