Monday, May 14, 2012

Hessian: Expected "End of Map" Exception

We've been working with Hessian services lately to send Java objects over the wire. So far the work has been trouble free, but from time to time, we run into some cryptic error messages. I'll document one here in case someone runs into a same problem.

Take the following error:

  Caused by: com.caucho.hessian.io.HessianProtocolException: expected end of map ('Z') at 'end of file'

This appear simply means, at least in our case, that the object being received by the caller of a Hessian service cannot be deserialized, either the object being transferred directly, or object contained with the transferred object's graph.

To resolve make sure every object in the graph implements java.io.Serializable.

Note: The above error came from com.caucho:hessian:jar:4.0.7.

Saturday, April 21, 2012

Spring Expression Langauge and Simple Bean References

In this post I'll demonstrate a simple use of Spring Expression Language (SpEL). First, I'll give a little background of the "problem" I used to solve, but feel free to skip ahead to the Spring configuration below.

The project in question was required to make two separate RESTful calls to the same service, for example:

  1. http://service.mycompany.com/business/record
  2. http://service.mycompany.com/business/order

The URLs contain the same base path, http://service.mycompany.com/business, and two separate paths, record and order. The URLs are to be looked up in a service directory, whose entries we have control of.

At first I considered placing both URLs in the directory to avoid having to deal with adding each path to the base URL in code. This sounded like a misuse of the directory however as each URL would not represent a separate service deployment. Then I remembered reading about SpEL and thought this could be help me add the paths to the URL in good ol' Spring configuration.

Here is a simplification of the defintion of the bean for the URL (java.net.URL) we will reference for defining the two service URLs:

    <bean id="serviceUrl" class="org.mycompany.service.entry.ServiceEntryProxy">
       <property name="serviceName" value="businessService"/>
       <property name="serviceDirectory" ref="serviceDirectory"/>
    </bean>

As we planned on using Spring's RestTemplate to invoke the remote service, we can convert the java.net.URL returned by the service lookup and translate them to Strings to be injected in the calling class.

    <bean id="recordServiceUrl" class="java.lang.String">
        <constructor-arg value="#{serviceUrl.toExternalForm()}/record"/>
    </bean>

    <bean id="orderServiceUrl" class="java.lang.String">
        <constructor-arg value="#{serviceUrl.toExternalForm()}/order"/>
    </bean>

We create the expressions above using #{...}, which is similar to syntax used to resolve properies in Spring, ${...}. Inside the expression, we can reference the serviceUrl bean defined earlier and call a method on it, #{serviceUrl.toExternalForm()}, which returns a String representation of the URL. From there we can add the remaining paths, /record and /order.

Given the following property signature of the class required to invoke the service:

    public class ServiceController {
        private RestTemplate restTemplate;

        private String recordUrl;
        private String orderUrl;

        // ...
    }

We can inject the URL string defined earlier:

    <bean id="serviceController" class="org.mycompany.service.business.ServiceController">
        <property name="restTemplate" ref="restTemplate"/>
        <property name="recordUrl" ref="recordUrl"/>
        <property name="orderUrl" ref="orderUrl"/>            
    </bean>

    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>

Admittedly, this is a very simple example of what we can do with SpEL. The feature overview in the documentation does a much better job of enumerating them than I could try to do. Hopefully, now that I've used in once, I'll look to SpEL again for other uses to help get out of some potentially tricky situations.

Saturday, March 10, 2012

Groovy: Regular Expressions and Multiple Lines

Regular expressions are sometimes used on text that spans multiple lines, which Groovy has support for. I had to search for how to enable multi-line searching, so I thought it would be good to post here.

To allow the expression to span multiple lines we can add (?ms) to the beginning of the expression.

Take the following example, where want to grab the entire book element from a single-line XML document:

    def xml = "<library><book><title>Effective Java</title><author>Bloch</author></book></library>"
def matcher = xml =~ /<book>.*<\/book>/
matcher.size() > 0 ? matcher[0] : "NOTHING"

This gives us an entire book:

    <book><title>Effective Java<title><author>Bloch<author><book>

If the XML was to span multiple lines however, we end up with NOTHING:

    def xml = """<library>
<book>
<title>Effective Java</title>
<author>Bloch</author>
</book>
</library>"""
def matcher = xml =~ /<book>.*<\/book>/
matcher.size() > 0 ? matcher[0] : "NOTHING"

Now if we add the (?ms), we will still get an entire book entry:

    def xml = """<library>
<book>
<title>Effective Java</title>
<author>Bloch</author>
</book>
</library>"""
def matcher = xml =~ /(?ms)<book>.*<\/book>/
matcher.size() > 0 ? matcher[0] : "NOTHING"

The above results in:

  <book>
<title>Effective Java<title>
<author>Bloch<author>
<book>

If you have any other tips or another way to accomplish the same thing, please feel free to leave a comment.

Injecting a Hostname with Spring

Sometimes our applications are required to know the name of the host or server they are running on. Usually, the hostname can be attained using plain old Java, however, in this post, I'll demonstrate a way to inject the name of the host an application is running on using Spring. This may sound like a case of over-engineering, but the main advantage of doing so is we can save our code from knowing how to obtain the hostname and avoid having to catch any exceptions related to retrieving the hostname.

As a use case, I'll recall a project I was working on that was tasked with consuming a service that required a client identifier be passed along in the request. The requirement stated that the ID be unique for every request and contain the hostname of the caller for tracking purposes inside the service. The form of the ID would be:

    <hostname>:<request_number>

Yes, this requirement could be considered a case of internal requirement of the service being called leaking into the implementation of the caller, but this a requirement we could not work around. To start, it made sense to task the creation of the identifier to a separate object. To fulfull the requirement that the ID be unique, we could use a UUID. The ugly part is deriving the hostname. Here is a first pass at the new class:

    public class RequestIdentifier {

public String requestId() {
return new StringBuilder()
.append(hostname())
.append(':')
.append(uuid())
.toString();
}

private String hostname() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException uhe) {
return defaultHostName;
}
}

private String uuid() {
return UUID.randomUUID().toString();
}

private static final String defaultHostName = "myHost";
}

Here we're forced to catch an UnknownHostException. As we still want the request to be made in the unlikely event that the exception is thrown, we default to a hostname (which would probably indicate the calling application) so that processing can proceed. We could improve on this implementation by caching the result of the first hostname lookup, but the potential for the exception to be thrown at least once would still exist.

Having to catch and deal with the exception places a burden on the class and adds complexity. Additionally, to fully cover the class during unit testing, we will have to find a way to simulate the exception, which could be difficult since the call InetAddress.getLocalHost() is static.

It might be better if the class was given its hostname, simplifying the code greatly, and removing the need for the default:

    public class RequestIdentifier {

private String hostname; // setter omitted for brevity

public String requestId() {
return new StringBuilder()
.append(hostname)
.append(':')
.append(uuid())
.toString();
}

private String uuid() {
return UUID.randomUUID().toString();
}
}

To make this situation usable, we can inject the hostname into the class:

    <beans xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="requestIdentifier" class="org.prystasj.service.validation.RequestIdentifier">
<property name="hostname" ref="hostname"/>
</bean>

<bean id="hostname" factory-bean="localhost" factory-method="getHostName"/>

<bean id="localhost" class="java.net.InetAddress" factory-method="getLocalHost"/>
</beans>

Now if there is an issue retrieving the hostname, we will know when the application starts up, before any processing is requested, and we have a cleaner, more usable class for creating the request identifier.

Monday, March 5, 2012

Subversion: Setting the MIME Type Property

As I'm tired of having to look this up every now and then when I need it, here's an example for how to add the MIME type for a file in Subversion:

 $ svn propset svn:mime-type "text/html" src/site/resources/design.html

The above command will cause the HTML file to be loaded as HTML in a browser when it is linked to in Subversion in the event your browser would like to display it as plain text.

Saturday, February 18, 2012

Linux: Burning an ISO Image from the Command Line

Here's a little tip (and reminder for myself) if you ever need to burn an ISO image to CD from the command line:

  $ cdrecord -v -eject speed=<speed> dev=<cdrom device> </path/to/iso>

Here's an example I used to burn the latest copy of Linux Mint Debian:

 $ cdrecord -v -eject speed=48 dev=/dev/cdrom \
/home/prystasj/Downloads/linuxmint-12-gnome-cd-nocodecs-64bit.iso

No GUI needed!

Addressing Database Connection Timeouts with c3p0

Many of our web applications run in Apache Tomcat and communicate with a MySQL database to persist data. After leaving one such development instance of an application up overnight, I was greeted with an error message when after trying to access it the next day. Looking at the Tomcat log, I found the following exception message:

   Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: 
The last packet successfully received from the server was 241,479,103 milliseconds ago.
The last packet sent successfully to the server was 241,479,103 milliseconds ago. is longer than the server configured value of 'wait_timeout'.
You should consider either expiring and/or testing connection validity before use in your
application, increasing the server configured values for client timeouts, or using the
Connector/J connection property 'autoReconnect=true' to avoid this problem.

The application was using commons-dbcp from the Apache Commons project. Below was the Spring configuration of the data source that connected to the database.

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${batch.jdbc.driver}" />
<property name="url" value="${batch.jdbc.url}" />
<property name="username" value="${batch.jdbc.user}" />
<property name="password" value="${batch.jdbc.password}" />
</bean>

Apparently, the connection to the database had timed out and needed to reconnect. After some searching, several posts mentioned that adding autoReconnect=true to the end of the database URL would fix the problem, but an exception would still be thrown before a reconnect is attempted.

A more popular answer seemed to be replacing the use of commons-dbcp with c3p0. I swapped out the dependency on commons-dbcp with:

    <dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<scope>runtime</scope>
</dependency>

Followed by a new definition of the data source:

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${batch.jdbc.driver}" />
<property name="jdbcUrl" value="${batch.jdbc.url}" />
<property name="user" value="${batch.jdbc.user}" />
<property name="password" value="${batch.jdbc.password}" />
<property name="maxPoolSize" value="${mysql.db.maxPoolSize}"/>
<property name="maxIdleTime" value="${mysql.db.maxIdleTime}"/>
<property name="maxConnectionAge" value="${mysql.db.maxConnectionAge}"/>
<property name="acquireRetryAttempts" value="${mysql.db.acquireRetryAttempts}"/>
<property name="maxIdleTimeExcessConnections" value="${mysql.db.max.idle.time.excess.connections}"/>
<property name="idleConnectionTestPeriod" value="${mysql.db.idle.connection.test.period}"/>
<property name="preferredTestQuery" value="${mysql.db.preferred.test.query}"/>
<property name="testConnectionOnCheckout" value="${mysql.db.test.connection.on.checkout}"/>
<property name="testConnectionOnCheckin" value="${mysql.db.test.connection.on.checkin}"/>
<property name="checkoutTimeout" value="${mysql.db.checkout.timeout}"/>
</bean>

As you can see, there are lot more properties that can be set on the ComboPooledDataSource. The following additional properties settings appear to do the trick, although I must admit not spending much time yet fine tuning them:

    mysql.db.maxPoolSize = 10
mysql.db.maxConnectionAge = 0
mysql.db.acquireRetryAttempts = 5
mysql.db.max.idle.time.excess.connections = 300
mysql.db.idle.connection.test.period = 540
mysql.db.preferred.test.query = SELECT 1
mysql.db.test.connection.on.checkout = false
mysql.db.test.connection.on.checkin = false
mysql.db.checkout.timeout = 60000
mysql.db.maxIdleTime = 500

For now, the connection issue has been resolved in the application. Hope this helps someone out in a similar situation. Thanks for reading.