Category Archives:

Avi and Patrick: Java Quick Tips

Posted on May 5, 2008 by Doug Burns

Java Quick Tip: Restlet & Spring Integration

Here at arc90 we use the Restlet framework for Java REST web services. Recently, we’ve also been considering Spring for dependency injection and AOP within these services. Restlet 1.0.x provides an extension for Spring integration, but I had a hard time finding an example of its use, so I thought I would post one here.

DemoApplication Class

package com.arc90.demo;

import ...

/**
 * Starts the Restlet application and defines its resources
 */
public class DemoApplication extends Application
{
	private static final String RESOURCE_MAP = "resourceMap";
	private static final int HTTP_PORT = 8182;
	
	public DemoApplication(Context context)
	{
		super(context);
	}

	/**
	 * Initialize the application when this class is executed.
	 * @param args
	 */
	public static void main(String[] args)
	{
		try
		{
			Component component = new Component();
			component.getServers().add(Protocol.HTTP, HTTP_PORT);
			DemoApplication application = new DemoApplication(component.getContext());
			component.getDefaultHost().attach(application);
			component.start();
		}
		catch (Exception e)
		{
			/*
			 * Convert any checked exceptions to unchecked for the purpose of this demo.
			 */
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * Set up the spring-defined resources
	 */
	public Restlet createRoot()
	{
		Router router = new Router(getContext());
		
		/*
		 * Retrieve a map of available resources from spring and attach each to the router
		 */
		ApplicationContext context = 
			new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
		Map<String, Finder> resourceMap = (Map<String, Finder>) context.getBean(RESOURCE_MAP);
		for (String key : resourceMap.keySet())
		{
			router.attach(key, resourceMap.get(key));
		}
		
		return router;
	}
}

DemoResource Class

package com.arc90.demo;

import ...

/**
 * Handles all requests to the demo resource.
 */
public class DemoResource extends Resource
{
	@Override
	public void init(Context context, Request request, Response response)
	{
		super.init(context, request, response);
		getVariants().add(new Variant(MediaType.TEXT_PLAIN));
	}

	@Override
	public Representation getRepresentation(Variant variant)
	{		
		return new StringRepresentation("Restlet Spring Integration Demo", MediaType.TEXT_PLAIN);
	}
}

Spring applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
		
	<util:map id="resourceMap">
		<entry key="/demo">
			<bean id="configurationFinder" class="org.restlet.ext.spring.SpringFinder">
				<lookup-method name="createResource" bean="demoResource"/> 
			</bean>
		</entry>
	</util:map>
	
	<!-- Resources classes -->
	<bean name="demoResource"
		class="com.arc90.demo.DemoResource" scope="prototype" />
</beans>

This uses Restlet's built in HTTP server, so to access the demo resource, simply run DemoApplication, then point your browser to: http://localhost:8182/demo

As you can see, it takes a little non-Spring code to get Restlet up and running. However, the Resources themselves are Spring beans, so everything from the Resource level down can be wired by Spring.

Restlet version 1.1 (currently in testing) provides improved Spring integration where the entire Restlet framework can be configured in the Spring application context. I plan to post another quick tip demonstrating the 1.1 configuration soon.

| Comments (0) | Technorati Tags :

Posted on April 18, 2008 by Avi Flax

Patrick & Avi's Java Tips #2: Graceful JVM Shutdown in Eclipse

If your Java application has any Shutdown Hooks, you probably want them to run every single time you stop your app - even when it's running within Eclipse. Unfortunately, when you click the red "Terminate" button in Eclipse, it kills the JVM process abruptly; Shutdown Hooks don't have a chance to run.

<p>Here's my approach to this problem:

  1. Add an environment variable to your run configuration, in the Environment tab. I call it RUNNING_IN_ECLIPSE, I like to be super-explicit. Set its value to TRUE.
  2. Add this block to the bottom of main():
    /* a hack to make sure that our shutdown hooks get called from within eclipse */
    if (Boolean.parseBoolean(System.getenv("RUNNING_IN_ECLIPSE")) == true)
    {
           System.out.println("You're using Eclipse; click in this console and
    press ENTER to call System.exit() and run the shutdown routine.");
           System.in.read();
           System.exit(0);
    }
    

As the code says: from now on, any time you run your app using this run configuration, the console will listen for input, blocking. As soon as you click in the console to give it focus and press enter, the next line will call System.exit(0), which will tell the JVM to gracefully shut down, which includes calling your shutdown hook.

| Comments (0) | Technorati Tags :

Posted on March 17, 2008 by Patrick Force

String Concatenation vs. StringBuilder

When developing applications, a common concern often creates a battle in the mind of the developer: How can I write this to make it easier to maintain, versus how can I optimize performance?

The debate of string concatenation via the + operator vs. StringBuilder in Java illustrates one tip on how to approach the higher level argument in this particular case:

String s = "";
for(i = 0; i <= 10000; i++)
{
    s += " word";
}

vs.

StringBuilder stringBuilder = new StringBuilder();
for(i = 0; i <= 10000; i++)
{
    stringBuilder.append(" word");
}

In most every case, using StringBuilder will prove faster than the string concatenation. Performing concatenations 5-10 times and above in a single operation may justify using StringBuilder for performance reasons, but never so much as to sacrifice clean code or the easier ability to manage what you've written. For instance, consider the following:

String s = "<Customers>" +
               "<Customer>" +
                    "<Name>Steven Jones</Name>" +
                    "<Address>123 Greenwich St.</Address>" +
               "</Customer>" +
               "<Customer>" +
                    "<Name>Gary Hall</Name>" +
                    "<Address>54 Rector St.</Address>" +
               "</Customer>" +
          "</Customers>";

For this particular case, I'd drastically prefer to write and work with the above piece of code before having to deal with the alternative w/ StringBuilder:

StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<Customers>");
stringBuilder.append("<Customer>");
stringBuilder.append("<Name>Steven Jones</Name>");
stringBuilder.append("<Address>123 Greenwich St.</Address>");
stringBuilder.append("</Customer>");
stringBuilder.append("<Customer>");
stringBuilder.append("<Name>Gary Hall</Name>");
stringBuilder.append("<Address>54 Rector St.</Address>");
stringBuilder.append("</Customer>");
stringBuilder.append("</Customers>");
String s = stringBuilder.toString();

In fact, I can't believe I even finished the StringBuilder example because it felt like such a waste of time, not to mention for this particular case of an XML string, it's not nearly as friendly to traverse through with StringBuilder.

Basically StringBuilder can produce performance gains (somewhat noticeable at very large iterations), but a developer should base his decision of whether to use + concatenation or StringBuilder primarily on ease of implementation and maintenance.

| Comments (0) | Technorati Tags :