Saturday, August 7, 2010

A MessageBodyWriter isWriteable method for a collection example

I can’t believe how much time I’ve spent today on providing an isWritable method for my JAX-RS MessageBodyWriter class. I just couldn't find a good example out there that did what I wanted to do. Maybe Google search wasn't behaving today!

My goal was to have a provider that translates a List<GPSTrackerCollection> object into an application/xml output stream. GPSTrackerCollection is my own class.

The tricky thing was learning how to test for the presence of a List of GPSTrackerCollection objects within my provider.

First things first, I needed to wrap my collection in a GenericEntity object in order to preserve information on the parameterised type; the runtime strips this information of course (this is known as erasure). Here's an example service implementation from my code base:

@GET
@Path("/history")
public Response getHistory() {
List<GPSTrackerCollection> list = new ArrayList<GPSTrackerCollection>();
GenericEntity<List<GPSTrackerCollection>> entity =
new GenericEntity<List<GPSTrackerCollection>>(list) {};
return Response.ok(entity).build();
}

My MessageBodyWriter ends up looking something like the following:

@Produces("application/xml")
@Provider
public class GPSTrackerCollectionProvider implements
MessageBodyWriter<List<GPSTrackerCollection>> {

@Override
public long getSize(List<GPSTrackerCollection> arg0, Class<?> arg1,
Type arg2, Annotation[] arg3, MediaType arg4) {
return -1;
}

@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] arg2, MediaType arg3) {

// Ensure that we're handling only List<GPSTrackerCollection> objects.
boolean isWritable;
if (List.class.isAssignableFrom(type)
&& genericType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericType;
Type[] actualTypeArgs = (parameterizedType.getActualTypeArguments());
isWritable = (actualTypeArgs.length == 1 && actualTypeArgs[0]
.equals(GPSTrackerCollection.class));
} else {
isWritable = false;
}

return isWritable;
}

@Override
public void writeTo(List<GPSTrackerCollection> gpsTrackerCollections,
Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4,
MultivaluedMap<String, Object> arg5, OutputStream os)
throws IOException {

...
}
}

The key thing here is that we check the parameterised type argument for equality against the class of GPSTrackerCollection. My intuition was that I could do an instanceof operation here, but this is not permitted. Check out this FAQ as to why.

Enjoy.

Saturday, July 31, 2010

Application development feelings 2010

Every now and again I review my practice of developing web based software. Here is a summary of how I write my applications in the context of a multi-tier architecture.

The presentation layer

In essence I'm a big fan of RIA (Rich Internet Application) for situations where I'm interested in developing a web based application as distinct from a web site full of HTML pages. I feel that this is a distinction lost on many people and I also think that those same people struggle with combining HTML/CSS/JS to make a web application.

I'm quite keen on developing something with Sproutcore as in a way, it blows away HTML and CSS and gives you the widgets to build a fully fledged MVC style app that works within the browser; its very similar to developing a native desktop application. The same can be said for Google Web Toolkit (GWT) however I slightly favour Sproutcore as it embraces JavaScript (JS) as a language whereas GWT embraces Java that produces JS i.e. Sproutcore "feels" lighter. Perhaps I should get over that... what Google have developed in the form of Google Wave is impressive.

There are other JS MVC frameworks out there (JavascriptMVC and PureMVC for starters), but I'm not sure that they drop HTML/CSS as a dependency for the developer to consider. I suppose what I'm feeling is that HTML and CSS do not belong in a web based application. Given HTML's start in life as a mark up language for documents I'm comfortable in acknowledging that it does not have a place in my web application.

The biggest thing for me right now with regards to JS RIA is the lack of development tooling. I've been using the Jetbrains WebStorm IDE for a couple months and while I'm impressed on its Window's implementation, it doesn't feel like a native Mac OS X application. Given that Mac OS X is where I like to spend a lot of my time this unfortunately creates a problem for me.

In my ideal world I'd be using Apache Maven for building and deploying my JS RIA's. I've really come to appreciate Maven in the Java space and it is just waiting for someone (may be even me!) to extend it for JS development (I'm familiar with JS Maven Tools but I understand that this project hasn't had activity for a long time). The pressures of family life and my daily job curtails the development of developer tools.

I shall pursue the use of SproutCore for my next RIA. So far I've just used HTML/CSS/JS and jQuery having implemented MVC in the raw. However when it comes to developing a website with perhaps a few dynamic requirements, may be I'll stay with trusty old JSP/Struts that communicates with my logic layer. When it comes to mobile and desktop, I will continue to do as the Romans do and develop native applications that communicate with my logic layer.

The logic layer

I've used Apache Camel on several projects now and just love it. What I end up with is a Java based application that can be managed as a service typically deployed to some brand of Unix. I've been using VMware's Hyperic to monitor the applications and given JMX I get some very deep monitoring capabilities.

I just love the Spring IoC framework and associated toolkits; particularly Spring JPA DAOs and Spring Test.

My applications tend to consist to lots of components that can exist independently of each other, and each with minimal dependencies on other frameworks and toolkits. For example, my application services containing the important business logic tend to be written as Java beans and have no or very little dependence on external libraries.

I lean towards creating RESTful services and look to leverage Apache CXF in this regard. I'm not yet using a toolkit to scaffold some of my RESTful DAO functionality but will at some point. I'm also a big fan of JSON as a payload format but XML's schema definitions have an important place in my heart. JSON with schemas would be a killer and I've just got to get into this.

Messaging is key and Active/MQ has been a great performer. I'm really looking forward to v.5.4 and its support of HTML 5 web sockets. This will allow messaging to be utilised by the JS RIA and I find that prospect quite exciting.

Apache Maven plays a huge role in developing and deploying my logic layer applications.

The data layer

I've been very happy with Postgres as a database and look forward to its forthcoming redundancy features. I'm also curious about Big table style approaches and Document Oriented Databases. I'm not quite sure why SQL should continue to play an application development standpoint (reporting, data mining etc. yes, but perhaps not within the application itself). ORMs have pushed me to the "NoSQL" conclusion and I like not having to deal with queries as much.

Summary

Multi-tier works for me. RIA appears to be the way of the future for web applications as distinct from web documents/pages. If you've not seen Apache Camel check it out. Postgres is great but I'm curious about Document Oriented Databases.

Please share your thoughts.

Friday, July 30, 2010

Development using Salesforce

I'm presently on a short contract developing using the Salesforce platform.

I've been using Salesforce for over 2 months now and I'm afraid to conclude that it doesn't make it as a viable platform for cloud application deployment. The reason for this is quite simple: it forces you to develop in the cloud as distinct from deploying to the cloud.

Salesforce thought that it would be great to re-invent the wheel, introduce a new language (Apex) and introduce the associated tooling. From a developer perspective this means that all of your regular tooling such as version control, continuos integration, deployment management, dependency management... I could go on... simply isn't there. Let me re-state a bit of that: no version control!

Developing on the Salesforce platform also means that you're dealing with 300ms (ish) round trips for every resource in their web development screens. This is because the platform is hosted in the US and the speed of light being what it is. A developer can quite commonly be waiting for several seconds while the development web app is doing its thing; reminds of my COBOL days 25 years ago when we had to submit stuff to a shared compiler resource and wait.

I'm quite turned on by the idea of deploying to the cloud and I think that VMforce and Google App Engine have chosen the right approach; they of course allow you to develop locally and then deploy to the cloud. Full scale application development in the cloud though is another thing and frankly Salesforce have got it wrong.

Friday, June 4, 2010

Invoking Maven and having it ignore your local settings

I recently found myself working remotely from my network and needed to perform a build using Maven. My ~/.m2/settings.xml file is configured with information about my network's Nexus repository and a few other things. I therefore needed to find a way to tell Maven to ignore my regular settings; preferably without mutating my settings.xml file. In particular I just wanted to have Maven pull out a plugin from the Central repo.

The documentation on the Maven command doesn't mention how it can be invoked to ignore your settings.xml. However if you type the following then it will ignore it (in my case I wanted to download the wonderful Cobertura plugin and produce a code coverage report) :

mvn -s/dev/null cobertura:cobertura

All good.

Wednesday, May 12, 2010

Flash on the iPhone

Given Steve Job's most recent letter concerning Flash on the iPhone, I'd like to broaden the debate to native plugins on the iPhone. Mr. Jobs provides a host of reasons why Flash is not permitted and it reminds me largely of his previous argument around needing native applications on the iPhone (remember that they encouraged us to create nice web apps instead at first; then there was the whole multi-tasking debate..).

There reaches a point with web applications where HTML, Javascript and CSS just can't do what you need them to do. These technologies have come an awful long way and HTML5 in particular is great. I spend a lot of time with these technologies and they are top of mind when considering new applications.

Let's take a concrete example of when you do require a plugin: Google Earth. Google Earth exists as a web plugin as well as a standalone executable. There are times when you'd like to embed Google Earth in a web page given its 3D capabilities; that's why the plugin exists of course!

Another example is with our own web plugin; it is something similar to Google Earth and has advanced capabilities with regards to map projections. We rely on third party C++ libraries and we utilise OpenGL.

Actually I think when it comes to 3D and the use of, say, OpenGL, web technologies fall short. There is a Mozilla proposal to expose OpenGL ES to Javascript, and that's great, but ES doesn't provide full OpenGL capability. Believe me, there are times when you need full OpenGL capability.

If I thought about it I'm sure there are other applications with dependencies such that you need to go native with a web plugin; not often perhaps, but we need to leave the native plugin door open for these situations.

I think Mr. Jobs has his reasons for not supporting Flash, but that's a separate consideration to supporting native web plugins.

In the end, I think that Adobe and Apple will come to an agreement and Adobe will release a well written and performant Flash plugin. The rest of us will then be able to install and write plugins for the iPhone when they are required.

Friday, April 16, 2010

Spring PropertyEditor for JSON map and array properties

I'm a big fan of Spring but found that it does not support map and list expressions in a property file to be substituted when using a PropertyPlaceholder. So I rolled my own PropertyEditor and can now express a map using JSON in my properties file e.g.:

myMapProperty ={"en-AU": "SKY", "ms": "SKY"}

Here's the property editor (depends on json-lib):

package <packagename>;

import java.beans.PropertyEditorSupport; 

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;

/**
* Converts JSON expressions to Java arrays or maps and vice versa.
*
* @author huntc
*
*/
public class JSONPropertyEditor extends PropertyEditorSupport {

@Override
public String getAsText() {
Object object = getValue();
JSON jsonObject = JSONSerializer.toJSON(object);
return jsonObject.toString();
}

@Override
public void setAsText(String text) {
JSON json = JSONSerializer.toJSON(text);
setValue(json);
}
}

and here's what you must declare in your spring configuration xml:

<bean id="customEditorConfigurer"
class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Map">
<bean class="<packagename>.JSONPropertyEditor" />
</entry>
</map>
</property>
</bean>

The above indicates that for any required substitution of a map, use my property editor e.g.:

<bean id="someBeanWithAMapProperty"
class="someClass">
<property name="someMapProperty"
value="${myMapProperty}" />
</bean>

 

Tuesday, April 13, 2010

iPhone and multitasking

So here we are. Apple appears to be finally opening up the threading APIs to developers on the iPhone.

I've had numerous conversations with colleagues since the iPhone came out and they've been all sorts of reactions as to why there's no multithreading. Actually, now that I've just typed multithreading let's get this straight. Multitasking relates to the human experience of doing multiple things at the same time; it is a use-case; it is something that I've been told (by my wife) that men can't do and women can (!).

Multithreading is the ability for an OS to cooperatively or pre-emptively (generally the latter) slice processor time between different paths of execution within and outside of a number of processes (generally applications).

The iPhone has supported multitasking and multithreading forever. The difference now is that Apple appears to have opened up the multithreading API to non-Apple developers. I've not seen the details on this, perhaps they've constrained the thread APIs in some interesting way with the goal of limiting battery usage, but it is a very good (and necessary) thing that there will now be multithreading.

One application that I'm really looking forward to using is Skype. Finally, we'll be able to receive Skype calls with the same experience of receiving regular mobile calls; so long as you're on a WiFi network of course. I think that this will be amazing as I'm never near my computer when someone wants to contact me via Skype. However, I always have my iPhone at hand of course.

I can't wait for SIP supporting applications to come along for the iPhone either. The prospect of receiving my home phone calls when away from home via VOIP is fantastic.

Oh and one thing I'd like to joyfully throw back at the multithreading doubters: get over it. Yes, multithreaded programming is harder but its just the way the world is. Multiple things happen at the same time. Embrace it.

Well done Apple. I look forward to iPhone 4.0.