<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tales From The Cloud &#187; java</title>
	<atom:link href="http://blog.newsplore.com/tag/java/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.newsplore.com</link>
	<description>Everything beta</description>
	<lastBuildDate>Sun, 05 Feb 2012 09:03:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Using Spring 3.0 MVC for RESTful web services (rebuttal)</title>
		<link>http://blog.newsplore.com/2010/02/23/spring-mvc-3-0-rest-rebuttal</link>
		<comments>http://blog.newsplore.com/2010/02/23/spring-mvc-3-0-rest-rebuttal#comments</comments>
		<pubDate>Tue, 23 Feb 2010 22:18:53 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[SpringMVC]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1486</guid>
		<description><![CDATA[Update Mar.04 Thanks to @ewolff some of the points described below are now official feature requests. One (SPR-6928) is actually scheduled in Spring 3.1 (cool!). I&#8217;ve updated the post and added all open tickets. Please vote! This post is somewhat a response to InfoQ&#8217;s Comparison of Spring MVC and JAX-RS. Recently I have completed a [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F02%2F23%2Fspring-mvc-3-0-rest-rebuttal"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F02%2F23%2Fspring-mvc-3-0-rest-rebuttal" height="61" width="51" /></a></div><p><i>Update Mar.04</i> Thanks to @ewolff some of the points described below are now official feature requests. One (<a href='http://jira.springframework.org/browse/SPR-6928'>SPR-6928</a>) is actually scheduled in Spring 3.1 (cool!). I&#8217;ve updated the post and added all open tickets. Please vote!</i></p>
<p>This post is somewhat a response to InfoQ&#8217;s <a href='http://www.infoq.com/articles/springmvc_jsx-rs'>Comparison of Spring MVC and JAX-RS</a>.<br />
Recently I have completed a migration from a JAX-RS implementation of a web service to Spring 3.0 MVC annotation-based <i>@Controllers</i>. The aforementioned post on InfoQ was published a few days after my migration so I&#8217;m dumping below the list of problems I had, along with solutions. </p>
<p>Full list of issues:</p>
<ul>
<li> <a href='#relpaths'>Same relative paths in multiple controllers not supported</a>
<li> <a href='#exchandling'>@ExceptionHandler is controller-centric</a>
<li> <a href='#views'>Standard content negotiation can&#8217;t respond with a fixed response type</a>
<li> <a href='#jsr303'>JSR 303 bean validation not applied in @Controllers</a>
<li> <a href='#respfmt'>Formatting responses (i.e. Date) not working when using Spring formatter annotations</a>
</ul>
<p><a name='relpaths'></a><br />
<b>Same relative paths in multiple @Controllers not supported</b><br />
Consider two Controllers where I use a versioned URL and a web.xml file that uses two URL mappings:</p>
<pre>
@Controller
public class AdminController {
   @RequestMapping("/v1/{userId}")
   public SomeResponse showUserDetails(String userId) {
      ...
   }
}

@Controller
public class UserController {
   @RequestMapping("/v1/{userId}")
   public SomeOtherResponse showUserStreamtring userId) {
      ...
   }
}
In web.xml:
	&lt;servlet-mapping&gt;
	  &lt;servlet-name&gt;public-api&lt;/servlet-name&gt;
	  &lt;url-pattern&gt;/public&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;
	&lt;servlet-mapping&gt;
	  &lt;servlet-name&gt;admin-api&lt;/servlet-name&gt;
	  &lt;url-pattern&gt;/admin&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;
</pre>
<p><span id="more-1486"></span><br />
Here I want to implement handling for <i>/admin/v1/{userId}</i> as well as <i>/user/v1/{userId}</i>. Each controller serves a different purpose (admin and public) and I want to keep the servlet application contexts separate for each servlet mapping (for instance add authentication and different view resolvers to all /admin/* URLs).<br />
Deploying this configuration barfs the following exception:</p>
<pre>
java.lang.IllegalStateException: Cannot map handler [UserController] to URL path
[/v1/{userId}]: There is already handler [com.test.controller. UserController@6b177115]
mapped.
</pre>
<p>I would like Spring MVC to account for web.xml servlet mappings before deciding that two identical @RequestMappings in different controllers refer to the same URI. My solution was to have all @RequestMappings specifying the full path and resorting to a custom <a href='#views'>view</a> to work around this issue).</p>
<p><a name='exchandling'></a><br />
<b>@ExceptionHandler is controller-centric</b><br />
RESTful web services respond with the usual HTTP responses (200s, 400s, 500s, etc.). These responses are being mapped from application exceptions and it only makes sense to specify the same @ExceptionHandler for all @Controllers since most (if not all) exceptions handled by them are for the same business domain. Currently SpringMVC only supports declaring and @ExceptionHander per controller and not globally per webapp. This forces the implementors to extend their @Controller classes from a common one where the @ExceptionHandler is specified or, to use composition and delegate exception handling to one service which leads to duplication. Both are ugly. There are several ways to deal with exceptions (check <a href='http://jira.springframework.org/browse/SPR-5622?focusedCommentId=43377&amp;page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_43377'>SPR-5622</a>; please guys, add this to the main Spring documentation) but ideally I&#8217;d like to see a global scoped handler like @ExceptionHandler(scope=APPLICATION) where I can remap once framework exceptions to more suitable ones that translate into proper error codes (like working around <a href='http://jira.springframework.org/browse/SPR-5622'>SPR-5622</a> like issues).</p>
<p><a name='views'></a><br />
<b>Standard content negotiation can&#8217;t respond with a fixed response type (<a href='http://jira.springframework.org/browse/SPR-6937'>SPR-6937</a>)</b><br />
Here&#8217;s a simple requirement: Implement an RSS feed that serves a user&#8217;s activity stream.<br />
Here&#8217;s another requirement (make that best practice): </p>
<pre>Service methods should have as arguments primitives, wrappers or other POJOs and
 respond with void, primitives, wrappers or other POJOs.</pre>
<p>I want testability, readability and portability for service classes and using framework objects for arguments/return objects adds unacceptable clutter.<br />
As such, no framework objects are allowed as arguments or return types in a @Controller and in this case I don&#8217;t want to work with <a href='http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/ModelAndView.html'>ModelAndView</a>s just to be able to select the desired View.<br />
Since this new requirement (add RSS view) belongs to the user domain, I want to add a method in the UserController class that returns a POJO which should be always unmarshalled into RSS regardless of request content type (there goes <a href='http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.html'>ContentNegotiationViewResolver</a>). The same controller has other methods returning POJO view objects that I want marshalled into JSON or plain text response body and an HTTP response status. This is already available in RESTEasy via the elegant <a href='http://jboss.org/file-access/default/members/resteasy/freezone/docs/1.0.1.GA/javadocs/javax/ws/rs/Produces.html'>Produces</a> annotation. The same RESTful controller should respond with different response types for different requests since I want to keep its domain centered around the user (and not response types).</p>
<pre>
...
public class UserController {
...
   @RequestHandler("/rss/{userId}")
   public SomePOJO getRssFeed(String userId) {
      ...
      //returns a POJO that should always be resolved by an RSS view
   }

   @RequestMapping("/activity/{userId}")
   public SomeOtherPOJO showUserStream(String userId) {
      ...
      //return POJO that should always be resolved by a JSON view
   }
...
}
</pre>
<p>It turns out this is not immediately possible. To my knowledge none of the included view resolvers provide a straight mapping between URLs and views so I had to write one that configures like this:</p>
<pre>
&lt;bean class="UrlToViewViewResolver"&gt;
   &lt;map name="urlToViewMap"&gt;
      &lt;property key="/user/rss/*" value="rssView"/&gt;
      &lt;property key="/user/activity/*" value="jsonView"/&gt;
      ...
   &lt;/map&gt;
&lt;/bean&gt;
</pre>
<p>The implementation (not included) is trivial and based on <a href='http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/AntPathMatcher.html'>AntPathMatcher</a>, a utility class readily available in Spring.</p>
<p><a name='jsr303'></a><br />
<b>JSR 303 bean validation not applied in @Controllers (<a href='http://jira.springframework.org/browse/SPR-6928'>SPR-6928</a>, scheduled for 3.1)</b><br />
On Springsource&#8217;s weblog there&#8217;s a nice tutorial on how to get validation and type conversion in Spring 3.0 <a href='http://blog.springsource.com/2009/11/17/spring-3-type-conversion-and-validation/'>here</a>. When it comes to validation though, Spring only supports it &#8220;after binding user input to it&#8221;. It is not possible to validate arguments and return types for a RESTful controller (no web forms or user input of any kind there). This means this won&#8217;t work out of the box:</p>
<pre>
   @RequestHandler("/admin/", method = RequestMethod.PUT )
   public void updateUser(@Valid User user) {
      ...
      //returns a POJO that should always be resolved by an RSS view
   }
</pre>
<p>since in a RESTful scenario the User object won&#8217;t be bound from a form but unmarshalled from XML/JSON/CSV or any other wire format.<br />
To enable validation for a RESTful controller I chose to use @Valid at the method level and add an around advice that intercepts all methods annotated as such then use a <a href='http://java.sun.com/javase/6/docs/api/javax/xml/validation/Validator.html'>Validator</a> to  validate arguments and return objects.</p>
<pre>
&lt;aop:config proxy-target-class="true"&gt;
	&lt;aop:pointcut id="validatableMethodExecution"
        expression="execution(* com.mycorp..*.*(..)) and @annotation(javax.validation.Valid)"/&gt;

	&lt;aop:aspect id="validateArgumentsAndReturnObject" ref="validatorAspect"&gt;
		&lt;aop:around pointcut-ref="validatableMethodExecution" method="validate"/&gt;
	&lt;/aop:aspect&gt;
&lt;/aop:config&gt;

public class ModelValidatorAspect {
	@Autowired
	private Validator validator;

    public Object validate(ProceedingJoinPoint pjp) throws Throwable {
        Set&lt;ConstraintViolation&gt; violations =new HashSet&lt;ConstraintViolation&gt;();
        for(Object obj : pjp.getArgs()) {
            if(obj != null) {
                violations.addAll(validator.validate(obj));
            }
        }
        if(!violations.isEmpty()) {
            throw new BadRequestException(composeErrorMessage(violations));
        }

        Object ret = pjp.proceed();

        //validate return object and throw exception if the validation fails.
        if(ret != null) {
            violations = validator.validate(ret);
        }
        if(!violations.isEmpty()) {
            throw new BusinessValidationException(violationsStr);
        }
   }
}
</pre>
<p>This could get more complex if you have deal with collections of validatable objects but it&#8217;s not hard to enhance the code to handle that.</p>
<p><a name='respfmt'></a><br />
<b>Formatting responses (i.e. Date) not working using Spring formatter annotations</b><br />
Spring comes with some niceties like @DateTimeFormat and @NumberFormat and naturally I want to rely on them by annotating the class attributes of return types used by @Controllers.<br />
That&#8217;s not quite working since the formatters work with form-backed model objects. However, if you use a <a>MappingJacksonJsonView</a> there is a way of formatting using Jackson&#8217;s own <a href='http://jackson.codehaus.org/1.2.1/javadoc/org/codehaus/jackson/map/annotate/JsonSerialize.html'>@JsonSerialize</a>.</p>
<p>Although at times it felt that the switch to SpringMVC was too much, the features that come with it (like abstracting web-related properties as annotations) will turn your RESTful controllers into annotated POJOs focused on the business domain which ultimately means maintainable code.</p>
<p><i>Update Mar.04</i> I left out several points about JSON marshalling that didn&#8217;t work as expected (Jackson marshaller is a handful).<br />
- One enhancement I suggested to ease the pain of configuring JSON marshalling is creating a namespace similar to oxm (<a href='http://jira.springframework.org/browse/SPR-6943'>SPR-6943</a>)<br />
- The second was to add <a href='http://jettison.codehaus.org/'>Jetisson</a> support (<a href='http://jira.springframework.org/browse/SPR-6938'>SPR-6938</a>) as an alternative to Jackson JSON marshaller.</p>
<p>I&#8217;m keen on your feedback regarding these issues so if you have better solutions please comment.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2010/02/23/spring-mvc-3-0-rest-rebuttal/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Unit testing with Commons HttpClient library</title>
		<link>http://blog.newsplore.com/2010/02/09/unit-testing-with-httpclient</link>
		<comments>http://blog.newsplore.com/2010/02/09/unit-testing-with-httpclient#comments</comments>
		<pubDate>Wed, 10 Feb 2010 00:31:25 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1442</guid>
		<description><![CDATA[I want to write testable code and occasionally I bump into frameworks that make it challenging to unit test. Ideally I want to inject a service stub into my code then control the stub&#8217;s behavior based on my testing needs. Commons Http Client from Jakarta facilitates integration with HTTP services but how to easily unit [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F02%2F09%2Funit-testing-with-httpclient"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2010%2F02%2F09%2Funit-testing-with-httpclient" height="61" width="51" /></a></div><p>I want to write testable code and occasionally I bump into frameworks that make it challenging to unit test. Ideally I want to inject a service stub into my code then control the stub&#8217;s behavior based on my testing needs.<br />
<a href='http://hc.apache.org/httpclient-3.x/'>Commons Http Client</a> from Jakarta facilitates integration with HTTP services but how to easily <i>unit test</i> code that depends on the HttpClient library? Turns out it&#8217;s not that hard.<br />
I&#8217;ll cover both 1.3 and the newer 1.4 versions of the library since the older v1.3 is still widely used.<br />
Here&#8217;s some typical service (HttpClient v1.3) we want to test. It returns the remote HTML page title:</p>
<pre>
public class RemoteHttpService {
   private HttpClient client;

   public String getPageTitle(String uri)  throws IOException {
     String contentHtml = fetchContent(uri);
     Pattern p = Pattern.compile("&lt;title&gt;(.*)&lt;/title&gt;");
     Matcher m = p.matcher(contentHtml);
     if(m.find()) {
        return m.group(1);
     }
     return null;
   }

   private String fetchContent(String uri)  throws IOException {
      HttpMethod method = new GetMethod("http://blog.newsplore.com/" + uri);
      int responseStatus = client.executeMethod(method);
      if(responseStatus != 200) {
        throw new IllegalStateException("Expected HTTP response status 200 " +
"but instead got [" + responseStatus + "]");
      }
      byte[] responseBody = method.getResponseBody();
      return new String(responseBody, "UTF-8");
   }

   public void setHttpClient(HttpClient client) {
      this.client = client;
   }
}
</pre>
<p>with the HttpClient is injected at runtime (via some IoC container or explicitly).<br />
To be able to unit-test this code we have to come-up with a stubbed version of the HttpClient and emulate the GET method. </p>
<p><span id="more-1442"></span><br />
 What we really want is to be able to control the byte array returned by method.getResponseBody() and although we can inject a mocked HttpClient, the actual class that is responsible for producing the response body is GetMethod which is instantiated (and completely encapsulated) in the method body so we can&#8217;t inject a stubbed GetMethod version directly.<br />
The solution is to create a simple HttpClient mock that is able to control the response status and response body. Here it is:</p>
<pre>
package org.apache.commons.httpclient;

import org.apache.commons.httpclient.*;

public class HttpClientMock extends HttpClient {
   private int expectedResponseStatus;
   private String expectedResponseBody;
   public HttpClientMock (int responseStatus, String responseBody) {
      this.expectedResponseStatus = responseStatus;
      this.expectedResponseBody = responseBody;
   }
   @Override
   public int executeMethod(HttpMethod method) {
      ((HttpMethodBase)method).setResponseStream(
new ByteArrayInputStream(expectedResponseBody.getBytes("UTF-8")));
      return expectedResponseStatus;
   }
}
</pre>
<p>There are two things to notice: Firstly, I placed HttpClientMock in the org.apache.commons.httpclient package to be able to have access to the protected member HttpMethodBase:setResponseStream. Secondly, I downcasted HttpMethod to HttpMethodBase to get access to setResponseStream (it&#8217;s safe since all concrete HttpMethods (GetMethod, PostMethod, etc) inherit from it).</p>
<p>Now I can unit test RemoteHttpService like this:</p>
<pre>
public class RemoteHttpServiceTest {
   private RemoteHttpService remoteHttpService = new RemoteHttpService();

   @Test
   public void extractTitleResponseOK()  throws IOException {
      String pageTitle = "A Title";
      String responseBody = "&lt;title&gt;" + pageTitle + "&lt;/title&gt;";
      HttpClientMock mockHttpClient = new HttpClientMock(200, responseBody);
      remoteHttpService.setHttpClient(mockHttpClient);
      String resultedPageTitle = remoteHttpService.getPageTitle(""); //home page
      Assert.assertTrue(pageTitle.equals(resultedPageTitle));
   }
}
</pre>
<p>I can also add a negative test:</p>
<pre>
   @Test(expected = IllegalStateException.class)
   public void respondsWithInternalServerError()  throws IOException {
      HttpClientMock mockHttpClient = new HttpClientMock(500, "");
      remoteHttpService.setHttpClient(mockHttpClient);
      remoteHttpService.getPageTitle("");
   }
</pre>
<p>For HttpClient version 4.x here&#8217;s the refactored service code :</p>
<pre>
   private String fetchContent(String uri) {
        HttpGet httpget = new HttpGet("http://blog.newsplore.com/" + uri);
        HttpResponse response = client.execute(httpget);
        int responseStatus = response.getStatusLine().getStatusCode();
        if(responseStatus != 200) {
           throw new IllegalStateException("Expected HTTP response status 200 " +
"but instead got [" + responseStatus + "]");
        }
        InputStream responseStream = response.getEntity().getContent();
        byte[] responseBytes = IOUtils.toByteArray(responseStream);
        return new String(responseBytes, "UTF-8");
   }
</pre>
<p>Turns out that implementing a HttpClient mock by extending the DefaultHttpClient (the provided implementation of HttpClient) is not easy. The method I want to override is <i>public HttpResponse execute(HttpUriRequest request) </i> which is marked &#8216;final&#8217; and the code in DefaultHttpClient looks just too complex to inject stubbed behavior.<br />
What we actually want is to be able to control the return of the aforementioned &#8216;execute&#8217; method since it encapsulates the response status and body (better encapsulation than HttpClient 1.3 if you noticed).<br />
Luckily in this case we can use a readily available mocking framework, Mockito that can stub this entire method and return an HttpResponse that we instantiate with the needed status and response body. Here&#8217;s how to rewrite the tests using it:</p>
<pre>
@Test
public void extractTitleResponseOK() throws IOException {
	String pageTitle = "A Title";
	String responseBody = "";
	HttpResponse response = prepareResponse(200, responseBody);
	HttpClient mockHttpClient = Mockito.mock(HttpClient.class);
	Mockito.when(mockHttpClient.execute(Mockito.any(HttpUriRequest.class)))
			.thenReturn(response);

	remoteHttpService.setHttpClient(mockHttpClient);
	String resultedPageTitle = remoteHttpService.getPageTitle(""); // home page
	Assert.assertTrue(pageTitle.equals(resultedPageTitle));
}

@Test(expected = IllegalStateException.class)
public void respondsWithInternalServerError() throws IOException {
	HttpClient mockHttpClient = Mockito.mock(HttpClient.class);
	HttpResponse response = prepareResponse(500, "");
	Mockito.when(mockHttpClient.execute(Mockito.any(HttpUriRequest.class)))
			.thenReturn(response);
	remoteHttpService.setHttpClient(mockHttpClient);
	remoteHttpService.getPageTitle("");
}

private HttpResponse prepareResponse(int expectedResponseStatus,
               String expectedResponseBody) {
      HttpResponse response = new BasicHttpResponse(new BasicStatusLine(
    		  new ProtocolVersion("HTTP", 1, 1), expectedResponseStatus, ""));
      response.setStatusCode(expectedResponseStatus);
      try {
		response.setEntity(new StringEntity(expectedResponseBody));
	} catch (UnsupportedEncodingException e) {
		throw new IllegalArgumentException(e);
	}
	return response;
}
</pre>
<p>The meat of the above code is</p>
<pre>
HttpClient mockHttpClient = Mockito.mock(HttpClient.class);
HttpResponse response = prepareResponse(...);
Mockito.when(mockHttpClient.execute(Mockito.any(HttpUriRequest.class)))
	.thenReturn(response);
</pre>
<p>that instructs the mocked HttpClient to return a HttpResponse that is instantiated in the test context (seeded if you like) when &#8216;execute&#8217; is called (check Mockito documentation for more details on the syntax).</p>
<p>That&#8217;s it. Happy testing.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2010/02/09/unit-testing-with-httpclient/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Proposal to standardize the Level 2 query cache configuration in JPA 2.0</title>
		<link>http://blog.newsplore.com/2009/05/28/a-call-to-standardize-level-2-cache-configuration-in-jpa-20</link>
		<comments>http://blog.newsplore.com/2009/05/28/a-call-to-standardize-level-2-cache-configuration-in-jpa-20#comments</comments>
		<pubDate>Thu, 28 May 2009 21:41:54 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[opinions]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JPA 2.0]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=1174</guid>
		<description><![CDATA[Level 2 cache is one of the most powerful features of the JPA spec. It&#8217;s a transparent layer that manages out-of-session data access and cranks-up the performance of the data access tier. To my knowledge it has been first seen in Hibernate and was later adopted by the then-emerging JPA spec (driven mostly by the [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2009%2F05%2F28%2Fa-call-to-standardize-level-2-cache-configuration-in-jpa-20"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2009%2F05%2F28%2Fa-call-to-standardize-level-2-cache-configuration-in-jpa-20" height="61" width="51" /></a></div><p>Level 2 cache is one of the most powerful features of the JPA spec. It&#8217;s a transparent layer that manages out-of-session data access and cranks-up the performance of the data access tier. To my knowledge it has been first seen in Hibernate and was later adopted by the then-emerging JPA spec (driven mostly by the Hibernate guys back in the day).<br />
As annotations gained strength and adoption, L2 caching that was initially configured through XML or properties files, was brought closer to the source code, alas in different forms and shapes. This becomes apparent if you ever have to deploy your webapp across a multitude of containers as you have to painfully recode the cache configuration (or worse, <a href="http://blog.newsplore.com/?p=981">hand-coded cache access</a>). Why not standardizing the cache control in JPA? This seems to be simple enough to achieve and yet it isn&#8217;t there. Now that JPA 2.0 is standardizing on Level 2 cache access (See JSR 317 section 6.10) it is the natural thing to do.<br />
Every JPA provider has its own way of specifying cache access (both Entity and query cache).<br />
To grasp the extent of the various ways cache is configured, here are some examples:</p>
<p><b>Hibernate:</b><br />
Cache control for entities</p>
<pre>@Entity
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Employee {...</pre>
<p>Cache control for named queries:</p>
<pre>@javax.persistence.NamedQuery(name="findEmployeesInDept",
query="select emp from Employee emp where emp.department = ?1",
hints={@QueryHint(name="org.hibernate.cacheable",value="true")})

or

@org.hibernate.annotations.NamedQuery(cacheable=true, cacheRegion="employeeRegion")</pre>
<p><b>OpenJPA</b><br />
Cache control for entities</p>
<pre>@Entity
@org.apache.openjpa.persistence.DataCache(timeout=10000)
public class Employee {...</pre>
<p><a href="http://openjpa.apache.org/builds/1.0.2/apache-openjpa-1.0.2/docs/manual/ref_guide_caching.html#ref_guide_cache_query">Query cache</a> requires hand coded cache access:</p>
<pre>OpenJPAEntityManagerFactory oemf = OpenJPAPersistence.cast(emf);
QueryResultCache qcache = oemf.getQueryResultCache();</pre>
<p><span id="more-1174"></span><b>EclipseLink</b><br />
Cache control <a href="http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)#How_to_Use_the_.40Cache_Annotation">for entities</a></p>
<pre>@Entity
@org.eclipse.persistence.annotations.Cache(expiry=10000,
    type=org.eclipse.persistence.annotations.CacheType.FULL)
public class Employee {...</pre>
<p>Query cache is hand coded (example from <a href="http://wiki.eclipse.org/Using_Advanced_Query_API_(ELUG)#Using_Queries_and_the_Cache">here</a>):</p>
<pre>ReadObjectQuery query = new ReadObjectQuery(Employee.class);

// Instruct the ReadQuery to cache its query results
query.cacheQueryResults();

// The first time you invoke it, the ReadQuery reads from the database, session
// cache, or both and stores the result set in its internal query cache
Employee employeeFirst = (Employee) session.executeQuery(query);</pre>
<p>Another JPA provider, <b>DataNucleus </b>is used by Google AppEngine for Java and they have thir own way of defining the cache access.<br />
Entity cache control in DataNucleus:</p>
<pre>@javax.jdo.annotations.Extension(vendorName="datanucleus", key="cacheable", value="false")
@Entity
public class Employee {...</pre>
<p>Query caching is again <a href="http://www.datanucleus.org/products/accessplatform/rdbms/query.html">manual</a>:</p>
<pre>query.setHint("datanucleus.query.resultCacheType", "weak");</pre>
<p>Looking at the above examples it looks to me that caching was an afterthought for most of the JPA providers. Let&#8217;s remember that the cache should be transparent and pluggable and the value that a cache provider delivers stays in performance and not in configuration.<br />
JPA cache configuration is in need of standardization and in my opinion the closest to a standard is (again) Hibernate.</p>
<p>A great addition to the JPA2 spec is the introduction of @Cacheable that controls entity caching but there&#8217;s still no standard on how to control query caching.<br />
Here are some enhancements that I&#8217;m proposing:</p>
<p>1. An enhancement to @NamedQuery and @NamedNativeQuery to allow explicit cache enablement through a boolean attribute called cacheable, the same way @org.hibernate.annotations.NamedQuery is defined.</p>
<pre>@NamedQuery(name="findEmployeesInDept", query="...", <span style="color: red;">cacheable=true</span>)
...
@Entity
public class Employee {...</pre>
<p>2. Both @javax.persistence.Cacheable and @NamedQuery to support optional attributes: <em>timeout</em> (in sec.)  and a <em>cacheRegion</em> attribute that in turn, will point to a cache policy where a more complex configuration can be used (to add the cache concurrency strategy and eviction policy for instance).</p>
<pre>@NamedQuery(name="findEmployeesInDepartment", query="...",
   <span style="color: red;">cacheRegion="DepartmentEmployeesCacheRegion"</span>)
@Entity
@javax.persistence.Cacheable(<span style="color: red;">cacheRegion="EmployeeCacheRegion"</span>)
public class Employee {...</pre>
<p>Cache regions can be configured through a new annotation, @java.persistence.annotation.CacheRegion.</p>
<pre>
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Cacheable {
    boolean value() default true;
    <font color='red'>int timeout();
    String cacheRegion();  //takes precedence if used</font>
}

package java.persistence.annotation;
@Target({TYPE, PACKAGE}) @Retention(RUNTIME)
public @interface CacheRegion {
    int timeout();   //i.e. 300 s
    javax.cache.EvictionStrategy evictionStrategy(); //EvictionPolicy.LRU, FIFO, etc
    String name();  //region name
    ConcurrencyStrategy concurrencyStrategy();
    String hints();  //vendor extensions
}</pre>
<p>If specified, a @CacheRegion exists either in-place along with the entity definition or separately through a new annotation @java.persistence.annotation.CacheRegions:</p>
<pre>package java.persistence.annotation;
@Target({TYPE, PACKAGE}) @Retention(RUNTIME)
public @interface CacheRegions {
	CacheRegion[] value();
}

example:
@CacheRegions ({
  CacheRegion(name="EmployeeCacheRegion", timeout=300, evictionPolicy=
EvictionStrategy.LRU, ConcurrencyStrategy.TRANSACTIONAL),
  CacheRegion(name="OfficeLocationsCacheRegion", timeout=-1, evictionPolicy=
EvictionStrategy.LRU, ConcurrencyStrategy.READ_ONLY),
})
public class OrganizationStructureDAO {...</pre>
<p>4. Sensible and well-defined defaults if some of the values are nor specified: default timeout, default eviction policy and default concurrency.</p>
<p>Vendor extensions of cache configurations will still be able to be deployed through the <em>hints</em> attribute both for @NamedQuery and @CacheRegion.</p>
<p>In the end, configuring the cache should be executed the same way across containers given that the cache providers that will be used will likely be the same. At least that&#8217;s what I&#8217;m hoping to see in JPA 2.0.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2009/05/28/a-call-to-standardize-level-2-cache-configuration-in-jpa-20/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Choosing a Java hosting provider</title>
		<link>http://blog.newsplore.com/2009/03/14/choosing-a-java-hosting-provider</link>
		<comments>http://blog.newsplore.com/2009/03/14/choosing-a-java-hosting-provider#comments</comments>
		<pubDate>Sat, 14 Mar 2009 05:38:48 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[hardware]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[hosting]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=880</guid>
		<description><![CDATA[Selecting a web hosting provider is a tough job for any web developer that wants to put a Java/JEE web application online. The choice is much simpler when it comes to publishing a PHP web site and there are a load of cheap (and sometimes quite reliable) PHP hosting providers to choose from with LAMP [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2009%2F03%2F14%2Fchoosing-a-java-hosting-provider"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2009%2F03%2F14%2Fchoosing-a-java-hosting-provider" height="61" width="51" /></a></div><p>Selecting a web hosting provider is a tough job for any web developer that wants to put a Java/JEE web application online. The choice is much simpler when it comes to publishing a PHP web site and there are a load of cheap (and sometimes quite reliable) PHP hosting providers to choose from with <a href="http://en.wikipedia.org/wiki/LAMP_(software_bundle)">LAMP</a> being the de facto standard in the web hosting world. But when it comes to Java hosting providers the picture becomes blurrier. The common thing that all these environments need is a Java container. The most popular choice is Tomcat but there are providers that use Resin, Weblogic or Websphere (the latter two are full fledged JEE containers).<br />
With the raise of lightweight J2EE servers started by the <a href='http://springframework.org'>Spring</a> folks, a little revolution began in the Java world: running enterprise-grade JEE webapps without the need for an EJB container; a servlet container is enough. Tomcat should fill the bill for just about any Java web application that doesn&#8217;t use EJBs. The advantage that comes from running a servlet container is the smaller footprint compared with an EJB container. This is critical when it comes to selecting hosting environments since you&#8217;re paying for resources (especially RAM) that have to be sized to accommodate the memory requirements of the web application.</p>
<p><i>Self hosting: Home-based dedicated server (near $0)</i></p>
<table>
<tr>
<td><img class="alignnone size-full wp-image-916" src="http://blog.newsplore.com/wp-content/uploads/2009/03/homepc.png" alt="homepc" width="136" height="206" /></td>
<td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
<td valign='top'>You can use your home internet connection and a PC where the web container runs and deploys your web application. There is an obvious advantage since the server is physically located close to the development team: complete control and physical access to the machine. The other big plus is the price: you&#8217;re already paying for the internet connection and chances are you already have a PC that can be transformed into a server. And chances are that you already have a development environment that can be the basis of the production deployment. Here are the shortcomings:</p>
<p>- Bandwidth limitations: the webserver where the webapp lives will <em>upload</em> content to the web browsers that access the application. The upload bandwidth is smaller than the download bandwidth and will result in longer load times for web clients.<br />
- Some internet providers cap the internet traffic so you may run beyond the limit.
</td>
</tr>
</table>
<p>- You may violate contractual obligations you agreed with your Internet provider by running your own web server.<br />
- The internet connection is not reliable: provider&#8217;s downtime directly translates in downtime for your webapp.<br />
<span id="more-880"></span></p>
<div style='height:14px'></div>
<p><i>Managed hosting ($6 and up)</i><br />
This is the cheapest solution but it poses the most restrictions. The main limitation is the inability to deploy webapps that depend on Java bytecode manipulation at runtime, mainly Hibernate and Spring. This is due to classloading security constraints that prevent the bytecode manipulation libraries (CGLIB or javassist) to perform runtime code enhancements.<br />
Working with managed hosting environments poses more limitations:<br />
- Deployment: some popular hosting providers deploy once a day: you drop the war file or the exploded war in a specific folder on the hosted environment and it will be deployed at a specific time picked by the provider (more <a href="http://help.godaddy.com/topic/319/article/67">here</a>). If it fails, you have to wait another day till the app will be redeployed or pick a provider that supports instant drop&amp;deploy.<br />
- Debugging a failed deployment: I couldn&#8217;t make log4j write the log into a location on my hosted file space so I had to resort to a <a href="http://www.dankomannhaupt.de/projects/index.html">JDBC appender</a> to actually see what causes a failed deployment. This required two deployments (one to try a location on  the hosted folder and a second one to use the JDBC appender; that&#8217;s two days due to the deployment constraint detailed above) and the issue turned out to be the classloader security issue preventing CGLIB to change the bytecode. I have only tried to deploy a war file with Hibernate and Spring dependencies in Godaddy&#8217;s Java hosting environment (their <a href="http://www.godaddy.com/gdshop/hosting/shared.asp?ci=9009">Linux Deluxe plan</a>) before I gave up on managed Java hosting.<br />
- Sharing the environment with other webapps. Your app will be deployed along with other applications and compete for the same resources.<br />
- Access to server logs and traffic stats is very limited. You can only use Google Analytics (or similar) but not <a href="http://awstats.sourceforge.net/">Awstats</a> (at least not for free).<br />
- Outgoing traffic may be restricted or blocked.</p>
<div style='height:16px'></div>
<p align="justify"><b>Unmanaged hosting solutions</b><br />
Unmanaged doesn&#8217;t necessarily mean that the hosting company doesn&#8217;t manage anything, they just leave the actual OS administration in your hands so you&#8217;ll have a physical server under your complete control, everything else from network management to hardware maintenance is done by the hosting company. You/your team has to have solid server administration knowledge: Linux, Apache, Java AppServers, software firewall (iptables), backup/restore, monitoring, security, patching, DNS and more. A web administrator inside your team usually takes care of all these details. After the machine is up and running you are free to install and run any Java container and deploy your application.<br />
Below are the options when choosing to run a dedicated server.
<div style='height:14px'></div>
<p><i>Colocated server ($70 and up)</i></p>
<table>
<tr>
<td><img src="http://blog.newsplore.com/wp-content/uploads/2009/03/mountcolo.png" alt="mountcolo" width="233" height="173" class="alignnone size-full wp-image-942" /></td>
<td>&nbsp;&nbsp;&nbsp;</td>
<td>You can <a href="http://en.wikipedia.org/wiki/Colocation_centre">colocate</a> the server which means that you buy then ship your own rack-mountable server to a data centre where it will be installed by on-site technicians. The monthly fee you&#8217;ll pay starts at around $70 (prices are per one unit which is a slot in the rack) and includes the rack space rental, network connectivity, location security, 24/7 power (not counting <a href="http://www.techcrunch.com/2007/11/12/quick-plug-the-internet-back-in-major-rackspace-outage/">mishaps</a>), etc. Denial of Service prevention services are usually provided as part of the package.<br />
There is complete freedom in terms of the deployment environment since you own it. However, there are two problems that come with this solution:</td>
</tr>
</table>
<p>- Initial cost associated with buying rack-mountable servers that usually start from $1.5k (check <a href="http://www.supermicro.com">SuperMicro</a>, they&#8217;re good). These machines contain redundant components to cope with failures.<br />
- Maintenance: When components break you have to manage their replacement. If the whole machine crashes then your website will be offline until the machine is replaced.</p>
<div style='height:14px'></div>
<p><i>Rent a dedicated server ($100 and up)</i></p>
<table>
<tr>
<td><img src="http://blog.newsplore.com/wp-content/uploads/2009/03/fullrack.png" alt="fullrack" width="106" height="143" class="alignnone size-full wp-image-937" /></td>
<td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
<td valign='top'>Instead of buying your own server, you can choose to rent a dedicated server from the hosting provider. Kevin Rose unveils how digg.com was initially hosted on dedicated servers rented from <a href="http://www.ev1servers.net/">Ev1Servers.net</a> (see full <a href="http://www.ev1servers.net/">article</a>). The benefit of this solution is the lower initial cost compared to colocation, beginning at around $100/month and of course the complete control over the environment. The drawbacks are the same as colocation except for servicing the box that falls under the hosting provider&#8217;s responsibility.</td>
</tr>
</table>
<div style='height:14px'></div>
<p align="justify"><i> Virtual Private Server ($20 and up)</i></p>
<table>
<tr>
<td><img src="http://blog.newsplore.com/wp-content/uploads/2009/03/vpsnodes.png" alt="vpsnodes" width="129" height="234" class="alignnone size-full wp-image-944" /></td>
<td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
<td valign='top'>A <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> &#8221; is a method of partitioning a physical server computer into multiple servers&#8221;. Each of these partitions behaves like a full fledged server, has an IP address and can be reachable from the internet. The computers that are VPS partitioned, sit on the hosting provider&#8217;s infrastructure. The provider is responsible for network connectivity, bandwidth and continuity of service in case  of physical server failure. There are two main VPS software providers: Virtuozzo and Xen. Of the two, I recommend Xen-based VPS providers since the virtualized machines cannot be oversold and thus you&#8217;ll get consistent performance for the money (a detailed explanation <a href="http://www.hostcube.com/blog/virtuozzo-vs-xen">here</a>). The main benefit of the VPS is the excellent price/performance ratio starting as low as $20/month. Another big advantage is the ability to &#8220;resize&#8221; the virtual partition on demand in a matter of minutes (you&#8217;ll pay more of course), add more virtual machines to your deployment () as well as &#8220;relocating&#8221; it to a different data center </td>
</tr>
</table>
<p>if the provider has multiple locations (West Coast and East Coast for instance). Root access is also provided. The drawbacks are:<br />
- the operating systems that you can run are controlled by the hosting provider and usually are Linux distributions (here&#8217;s an <a href="https://www.linode.com/faq.cfm">example</a>). However, the choices are very popular Linux distros.<br />
- you have to have server administration expertise.<br />
I run this blog, <a href="http://spincloud.com">spincloud.com</a> and the rest of my web properties on a VPS. I use the excellent <a href="http://www.linode.com/?r=603cdcbaa7d1fecb2a560592fcf36b3021818071">Linode</a> after I had switched from <a href="http://slicehost.com">Slicehost</a>, having performance issues. I am quite happy with Linode, their service rocks and they&#8217;ve been delivering consistent performance since day one.</p>
<div style='height:14px'></div>
<p><i>Cloud services (EC2: $100 and up)</i></p>
<table>
<tr>
<td><img src="http://blog.newsplore.com/wp-content/uploads/2009/03/cloud.png" alt="cloud" width="138" height="119" class="alignnone size-full wp-image-953" /></td>
<td>&nbsp;&nbsp;&nbsp;</td>
<td valign='top'>Cloud computing is today&#8217;s trend. The company that kick-started the trend was Amazon with their <a href="http://aws.amazon.com/ec2/">Elastic Computing Cloud</a>. EC2 is actually an advanced form of VPS: you can run your own virtual machine image (or AMI) or pick one from the existing stock. After the AMI is booted and configured, you have the liberty of installing any Java environment. You get root access too.<br />
From the high profile websites, <a href="http://smugmug.com">Smugmug</a> uses EC2 and S3 and they <a href="http://blogs.smugmug.com/don/2006/11/10/amazon-s3-show-me-the-money/">save money</a> doing so. In fact Smugmug was one of the early adopters of Amazon&#8217;s cloud services.</td>
</tr>
</table>
<p>Drawbacks:<br />
- If you reboot the machine or if it simply crashes then all data is lost, including any database records you happen to have. This was a real problem for developers until Amazon added the possibility to <a href="http://www.infoq.com/news/2008/04/amazon-storage">mount a persistent S3 volume</a> in an EC2 instance. S3 stands for <a href="http://aws.amazon.com/s3/">Simple Storage Service</a> and is Amazon&#8217;s offering for cloud-based storage.<br />
- You have to learn new terminology and set of skills that are applicable to Amazon&#8217;s problem-set only. You&#8217;ll also tie the solution to a single vendor.<br />
The cost for an EC2+S3 starts at close to $100/month.<br />
<del datetime="2009-05-19T23:21:20+00:00">If you&#8217;re thinking of using the dirt-cheap (starts free) <a href='http://code.google.com/appengine/'>Google AppEngine</a> for deploying a Java application you&#8217;re out of luck, they only support Python.</del> Update: Google has added Java support to Appengine.  at the begining of April. I have a dev account and I&#8217;ll evaluate it in a separate post.</p>
<p><b>Common concerns when selecting a hosting provider</b><br />
<i>Price</i><br />
Don&#8217;t pick a service just because it&#8217;s cheap. Perform some due diligence on the company, where their data centers are located and how good their service is. You don&#8217;t want your website hosted on the wrong side of the world. Monitor <a href='http://www.webhostingtalk.com/'>WebHostingTalk forums</a>; hosting providers often run promotions there.<br />
Look for monthly plans and don&#8217;t commit to yearly plans since you may end-up being unhappy with the provider and with no choice to get out of the contract.<br />
Be suspicious when you see associated setup fees coming with setting-up an account. They are not refundable and good hosting providers simply don&#8217;t have them.</p>
<p><i>Uptime</i><br />
You want no interruption in service for your web servers so <a href="http://en.wikipedia.org/wiki/Uptime">uptime</a> is a must. You can&#8217;t afford to have downtime since it translates directly into lost customers and ultimately lost business. Look for hosting providers that offer SLAs (Service level agreements) and have proven reliability. <a href="http://netcraft.com">Netcraft</a> is a neat tool that measures the reliability of hosting providers on a monthly basis. Look for the providers that guarantee five nines (99.999%) uptime, that is five minutes <i>a year</i>.</p>
<p><i>Technical support</i><br />
My personal experience is that I used the tech support while I was using a shared web hosting. I haven&#8217;t used any after moving to the VPS.</p>
<p><i>Transfer volume</i><br />
Perform some basic calculations for the required traffic based on the expected traffic and data volume sent out. Providers bundle 200GB/month or more in their offerings these days. This should be enough for most of the cases. Make sure your website doesn&#8217;t get cut-off if your traffic spikes and/or you&#8217;re not paying a ridiculous amount of money per GB if you go beyond your quota.</p>
<p><i>Security</i><br />
All hosting providers offer a form of protection against DDOS but you are responsible for the software that runs on the server. I got the online forum I was running for <a href='http://newsplorer.com'>Newsplorer</a> hacked a couple of years ago because I didn&#8217;t upgrade the forum software to patch a security vulnerability that was promptly exploited.</p>
<p><i>Backup</i><br />
Hosting providers offer backups or you can do it yourself with a bit of effort and some cron knowledge. Save the backed-up files on a different location (I use S3 for my backup needs but there are <a href='http://skydrive.live.com/'>free solutions</a> too).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2009/03/14/choosing-a-java-hosting-provider/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>java.lang.Void</title>
		<link>http://blog.newsplore.com/2008/11/01/javalangvoid</link>
		<comments>http://blog.newsplore.com/2008/11/01/javalangvoid#comments</comments>
		<pubDate>Sun, 02 Nov 2008 01:20:03 +0000</pubDate>
		<dc:creator>Florin</dc:creator>
				<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://blog.newsplore.com/?p=158</guid>
		<description><![CDATA[I&#8217;ve considered myself a Java guy (that&#8217;s before I recently started with Ruby). I&#8217;ve stumbled upon Java in 1998 and fell in love with it at first sight. I remember quite crisply my first encounter of the third kind with Hello World. But I confess, I only learned about java.lang.Void yesterday. I was digging through [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="padding-right:0;margin-top:3px"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.newsplore.com%2F2008%2F11%2F01%2Fjavalangvoid"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.newsplore.com%2F2008%2F11%2F01%2Fjavalangvoid" height="61" width="51" /></a></div><table border="0">
<tbody>
<tr valign="top">
<td valign="top"><img style="margin-bottom: 0px; margin-right: 8px" src="http://blog.newsplore.com/wp-content/uploads/2008/11/void.jpg" alt="Void" width="140" height="140" /></td>
<td>I&#8217;ve considered myself a Java guy (that&#8217;s before I recently started with Ruby). I&#8217;ve stumbled upon Java in 1998 and fell in love with it at first sight. I remember quite crisply my first encounter of the third kind with Hello World. But I confess, I only learned about java.lang.Void yesterday. I was digging through the <a title="ThreadWorker" href="https://swingworker.dev.java.net/nonav/javadoc/index.html">SwingWorker</a> concepts and as I went through the tutorial I was intrigued by a mention about the Void type in the <a href="https://swingworker.dev.java.net/nonav/javadoc/index.html">Simple Background Tasks</a> section.</td>
</tr>
</tbody>
</table>
<p>I already experimented with the SwingWorker before reading the tutorial and liked it except for the annoying return and interim results types as I&#8217;m migrating an ancient Java 1.1.8 GUI to JDK 6 at work and those Runnable classes I&#8217;m thinking of converting to don&#8217;t have any return types.</p>
<p><span id="more-158"></span></p>
<p>In short, <a href="http://java.sun.com/javase/6/docs/api/java/lang/Void.html">java.lang.Void</a> is a class representing the <strong>void</strong> type (non-instantiable, mind you). I should have known, all primitives have class.&lt;primitive&gt; representations and the reflection mechanism should have a representation of void too. Well, I didn&#8217;t.</p>
<p>The nice thing about this little-known-to-me class is that it fits like the proverbial Cinderellian shoe straight into the <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html">generics</a> of SwingWorker (and elsewhere now that I know about it). From the example:</p>
<pre>SwingWorker worker = new SwingWorker&lt;ImageIcon[], Void&gt;();</pre>
<p>In other words, if you don&#8217;t have a return type for your SwingWorker::done() method just slap a java.lang.Void and you&#8217;re saved.<br />
<span style="font-size: x-small;">[Copyrighted image courtesy of <a title="toulcophoto" href="http://www.flickr.com/photos/tolucophoto/" target="_blank">toulcophoto</a>]</span></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.newsplore.com/2008/11/01/javalangvoid/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

