Monday, April 12, 2010

The pitfall of setting a list of parameters on a JQL query

I recently had a need to provide a collection as a parameter to a JQL IN expression. This is what I did:

List results = getJpaTemplate()
.find(
"from AbstractEvent e "
+ "where "
+ "(e.subscription, e.eventTime) in "
+ "(select e.subscription, max(e.eventTime) "
+ "from e "
+ "where "
+ "e.class in "
+ "(SentSMSFlightSubscribed,"
+ " ReceivedSMSFlightUnsubscribe) and "
+ "e.subscription.flightNo in (?) and "
+ "e.subscription.scheduled = ? "
+ "group by e.subscription)",
renderedFlight.getFlights(),
renderedFlight.getScheduled());

The problem with the query is that you get a class cast exception when an attempting to substitute the collection (renderedFlight.getFlights) .

To fix this you simply need to be explicit about the parameters:

    + "e.subscription.flightNo in (?1) and "
+ "e.subscription.scheduled = ?2 "

Problem solved.

Updated: Sunday 11 July 2010: Even using position parameters doesn't always work. While it works in the above example it didn't work for me when using a parameter of a non-primitive type; at least I think that was the issue. So in a nutshell, if the above doesn't work for you then just use findByNamedParams instead.

You may also note this beauty of a line:

e.class in (
SentSMSFlightSubscribed,
ReceivedSMSFlightUnsubscribe)

That is how you perform an "instanceof" style of operation in JQL. Nice.

 

Sunday, February 28, 2010

Java's Swing framework for Javascript and Canvas

It is 0051 on Sunday morning and I just had a wild thought...

I've been developing applications in Javascript using jQuery and taking an interest in Sproutcore. I love jQuery but most definitely subscribe to Sproutcore's architecture where it makes a very strong statement about web applications being distinct from web documents (there is a place for both).

...and then it occurred to me... why not try and implement Java's Swing framework in Javascript and use the Canvas element almost exclusively for web applications? Do away as much as possible with CSS and HTML - I don't think they're great for web applications anyhow...

I don't doubt that it'd be a lot of work implementing Swing in Javascript, but there's an awful lot of design to be leveraged there.

I think I'll sleep on it...

Wednesday, February 17, 2010

Does Grails lower the barriers of entry to programming?

Grails is the Groovy equivalent of Ruby on Rails and I've been working with Grails for the past couple of months.

I'm a big fan of programming by convention and adopted Apache Maven many moons ago for just this reason. Grails also promotes programming by convention and by and large its quite reasonable for building server hosted web applications.

However one thing in particular has been bothering me. It seems that there is a view that Grails saves you the trouble of worrying about what goes on underneath it. This attitude is similar to one where using ORMs such as Hibernate save you the need to understand databases.

These attitudes are fraught with dangers as has been beautifully pointed out by Joel Spolsky in his Leaky Abstractions article.

I would agree that Grails can assist in increasing productivity but not at the expense of knowing what goes on under the hood. As Joel puts it, "... the abstractions save us time working, but they don't save us time learning".

Today I came across a Grails situation where I compared a newly instantiated domain object with one obtained through GORM. From my perspective both objects were equivalent as they had the same identifiers. I had wrongly assumed though that GORM had adopted the Hibernate convention of providing hashCode() and equals() on a natural key. Because Grails does all this magic for me, I had just assumed that this would be done. Well, it doesn't; and that's fair enough; how would GORM know what the natural key is? (declaring the natural key could be a nice feature for GORM). The point is that I could quickly find the problem because I'm familiar with Java/JPA/Hibernate and know that hashCode() and equals() should be provided for natural keys.

My advice is to stay curious. Don't be content with copy and pasting a bit of code you found using Google, seeing it work but not understanding it. This situation will bite you on the bum when your product goes live and you get a problem that you can't diagnose because you don't really understand what the code is doing.

Programming computers is a complex business and that's a fact that should not be avoided. Embrace the complexity.

Saturday, February 13, 2010

Processing Javamail emails for specific mime types

I recently had to write some software that received an email and processed it for iCal events. I wanted my program to be tolerant of receiving the iCal events within the body or as a attachment. Furthermore if the attachment was a mail message then I wanted to look inside that email for the event and so on...

When I thought about the problem initially I thought that processing just the attachments of an email would be sufficient. That's not the case given Microsoft Outlook though. I quickly learnt that Outlook sends its iCal events within the body of an email and not as an attachment.

I ended up with the following bit of Javamail/iCal4j/Java code that should generally be useful for processing mail messages. In my case I'm looking for a text/calendar object but it could be anything of course. The addCalendarDataToCalendars function can be called recursively and adds any calendar objects it finds to the collection passed in. Enjoy.


/**
* Process a data handler's content looking for a
* calendar object.
*
* @param calendars
* the collection of calendars that we
* must add any found calendar to.
* @param dataHandler
* the data handler to use.
*/
private void addCalendarDataToCalendars(
Collection calendars,
DataHandler dataHandler) {
MimeType mimeType;
try {
mimeType =
new MimeType(dataHandler.getContentType());

if (mimeType.getBaseType()
.equals("text/calendar")) {
// Calendar data is what we're ultimately
// searching for.
CalendarBuilder builder =
new CalendarBuilder();
Calendar calendar = builder.build(
dataHandler.getInputStream());
calendars.add(calendar);

} else if (mimeType.getBaseType()
.equals("message/rfc822")) {
// Found an object representing an email
// address in its entirety.
Message mailMessage = (Message) dataHandler
.getContent();
addCalendarDataToCalendars(calendars,
mailMessage.getDataHandler());

} else if (mimeType.getBaseType()
.startsWith("multipart/")) {
// Found a bunch of attachments so
// process them each.
Multipart multipart =
(Multipart) dataHandler.getContent();
for (int i = 0, n = multipart.getCount();
i < n; ++i) {
Part part = multipart.getBodyPart(i);

String disposition =
part.getDisposition();

if ((disposition != null)
&& ((disposition.equals(Part.ATTACHMENT)
|| (disposition.equals(Part.INLINE))))) {
addCalendarDataToCalendars(calendars,
part.getDataHandler());

} else if (disposition == null) {
MimeBodyPart mimeBodyPart =
(MimeBodyPart) part;
addCalendarDataToCalendars(calendars,
mimeBodyPart.getDataHandler());

}
}
}

} catch (MimeTypeParseException e) {
logger
.warn("Ignoring attachment - could not " +
"parse the mime type of: "
+ dataHandler.getContentType()
+ " - " + e);
} catch (IOException e) {
logger.error(e);
} catch (ParserException e) {
logger
.warn("Ignoring attachment - could not " +
"interpret the calendar object: "
+ dataHandler.getName() + " - " + e);
} catch (MessagingException e) {
logger
.warn("Ignoring attachment - could not " +
"decode the calendar object: "
+ MimeUtility.getEncoding(dataHandler)
+ " - " + e);
}
}

Monday, December 28, 2009

Eclipse and friends are memory hungry

I've been using Eclipse Galileo for some time now and have quite a few favourite (and necessary!) plugins installed. These included m2eclipse, subeclipse, findbugs, checkstyle and many more.

I had noticed though that things started to slow down. Even clicking between tabs was slow (started out ok after launching and then got worse over time).

This smelled like a memory performance issue so I re-configured Eclipse to have a maximum memory size of 2GB and all now appears well. 2GB may have been an over-reaction - your mileage might vary, but for me it seems to have done the trick.

Thursday, December 10, 2009

Chrome on Mac - No Google Earth plugin though

I've just installed the Chrome beta on my Mac. Looks good overall.

However the first thing I did ('cause its close to what I'm involved in) was try out the Google Earth Plugin.

No dice:



So perhaps the same constraints holding back the plugin under Safari 4 are holding up it working under Chrome also; perhaps it is the out of process plugin architecture, and/or the new requirement to use Core Animation to render OpenGL...

Actually I've noticed that Chrome doesn't presently support the Core Animation for OpenGL NPAPI plugins (my CA NPAPI plugin isn't able to instantiate - most likely due to the browser stating that CA/Cocoa is unsupported due to the graceful failure).

In searching for some technical insight I noticed that Google provide a great article on the motivation behind Chrome.

First impressions then are that Chrome looks interesting but it isn't quite there for me yet given my specialised NPAPI requirements.

Friday, December 4, 2009

MacPorts - my new best friend

Perhaps it is just that I'm getting older, but I've resisted using package managers on Linux and Mac OS X for some time. I dunno, I guess I preferred to download the source and build it myself. What a sucker I am for punishment!

I think that I had a similar resistance to Apache Maven originally - I just didn't want the learning curve of a new tool.

I'd got to the point with a C++ project that I was fed up managing, building and sorting out the dependencies of various C/C++ based libraries. The catalyst for me was when I started using Cairo, a 2D vector and imaging library (which is great!). Cairo had many dependencies and the project recommended a number of package managers for my OS X build environment.

I ended up with MacPorts and haven't looked back. Managing those dependencies just got a whole lot easier. MacPorts was apparently started by a group of Apple engineers and it grew from there. At the time of writing there are now over 6,000 packages available through MacPorts.

MacPorts likes to put everything in /opt by default. For some bizarre reason I was against using /opt as my root folder for all MacPorts derived packages - talk about resisting change for no good reason! However I got over that and must take a leaf out here and try to resist such time consuming temptations. Who really cares where MacPorts puts stuff so long as at the end of the day your dependencies are being managed and your applications build?

The only thing I found myself changing with the default configuration was the /opt/local/etc/macports/variants.conf file. I wanted +universal as a default. My projects tend to build both 32 bit and 64 bit targets and so I needed MacPorts to do this by default (I kept forgetting to specify the variant on the command line).

All good. MacPorts is great and is another tool that helps me focus on the problem at hand.