Chicago Groovy User Group

January 6th, 2009

I wanted to remind everyone that in one week from today, the Chicago Groovy User Group will have its inaugural meeting in the Chicago Loop. The featured speaker will be Sten Anderson from CITYTECH who will give a talk on using Groovy to create DSL’s. There will be free food and drinks available and a book raffle provided by CITYTECH. Please visit http://cgug.org for more information and to sign up for future notifications.

We have some cool ideas planned for upcoming meetings. Besides having nationally recognized speakers and authors stop by, we are also working on some informal code camps, as well as Lightning Talks where attendees will bring up their Grails related problem that we’ll discuss and solve as a group.

I am excited and looking forward to a great new year. And, what’s a better way than to start off by joining a new user group that’s focused on a great language and platform.

Inaugural Chicago Groovy Users Group January 13th!

January 6th, 2009

Java in 2009 - Up and Coming/Down and Out

January 6th, 2009

This is the time of the year when we start seeing the “what’s going to be hot in Java this year” posts. Actually, I might be a little late. Anyways, there seems to be two kinds. The ones that focus on the very latest buzzwords (the bad) and the ones that focus on what is beginning to take hold or mature (the good). It is sort of like how I prefer to attend JavaOne every other year. One year is full of specifications, standards, and new frameworks. The next year is specification implementations and the maturing of the previous year’s frameworks. I’m hoping this will be a good one. I am trying to focus on technologies that are not necessarily new, but that are beginning to take hold. And to add a little spice, I’m not just listing the emerging technologies. I’m also listing those that I think will be in decline.

Up and Coming

  1. JCR - I think that 2008 was a great year for the JCR specification, but I expect 2009 will be a great year for adoption. I think Jackrabbit is quite a success. There are still places where databases are more appropriate, but now I’m seeing that there are more and more places where repositories are more appropriate. Earlier on it seemed like web content management was the only place where a JCR seemed like a nartural fit, but I think that is going to change in 2009. On a side note, I’m rather interested in using an object database such as db4o in the future as well. I think there are some similarities between object databases and repositories so that should not be a surprise. If we are using an object oriented language, why not use an object database? It seems like it would be a hell of a lot easier than wrestling with an ORM framework and a traditional database.
  2. Flex - I saw Flex becoming a viable alternative for applications in 2008 from a development perspective, but it appeared that there was a lack of support from a business perspective. I think that this is going to change in 2009. As organizations come to terms with RIAs, they’ll see that Flex is really the only practical solution. I’d prefer to use Flex for all future web applications myself. The ability to run web applications offline with AIR is just icing on the cake. Also, I feel like there is a gap between desktop applications and browser based web applications. It turns out that AIR fills that gap. Finally, my prefer approached is to completely separate the business tier from the presentation tier. That is where RESTful services come in to play, and Flex has great support here. Then we can build as many clients as we like whether they be in Flex, Silverlight, or plain old AJAX.
  3. RESTful Services - They certainly aren’t new, but with the release of JAX-RS I expect organizations will develop more and more services in a RESTful fashion in 2009. In 2008, I’d say it was maybe 70/30 or 60/40 leaning towards SOAP web services. I’m hoping for the reverse in 2009. I also see RESTful services playing a larger role. I imagine web applications being assembled on nothing but RESTful services. Pretty much what I just described when talking about Flex.

Honorable Buzzwords: Cloud Computing, Software as a Service (SaaS)

Down and Out

  1. Fall of the ESB - Honestly, I have seriously lost faith in the notion that an ESB is required for SOA. I’ve only worked on one project (using Mule) where it actually made sense to use one. We had multiple disparate applications (database, command line, service) that needed to be synchronized. Mule proved itself to be the perfect solution to this problem. In the rest of the projects, I saw that organizations were simply using an ESB to proxy/route/monitor service requests. I can use Apache for that. For more complex mediation and routing, I’d look to Camel. Finally, SOA is just one approach to enterprise integration. It is not the only one. Also, how many people are implementing a SOA when they don’t even have any enterprise integration requirements? Too many.
  2. Decline in Web Frameworks/AJAX - I used to think that all these web frameworks were the stweetness. I liked to try new ones, and I liked living on the edge. Now they just annoy me. As for AJAX, I don’t even know where to start. I mean, hammer and nail anyone? Yes, you can do a lot of cool stuff with AJAX but do you really want/need to? Clearly people are just forcing it to do things either for the pure sake of proving they can force it to do things or because it simply wasn’t intended to do those things from the beginning. I suppose if you can’t let go of your favorite web framework then you’ll have to continue using AJAX.
  3. Complex ‘Stacks’ - This is sort of an extension of the web framwork decline. I remember being all about the ’stack’. We had Hibernate, Struts, and Spring. Then we had to add a security framework, and web service client, and so on. We ended up with fairly complex stacks because the holy grail was to have a truly modular application such that you could swap out certain tiers while leaving others in place. Right, that never happened. Once a stack was assembled, it was never touched. These days I like to keep my applications as simple as possible. I’d rather write some code by hand, than have to add another framework that will do it for me.

Questionable: Commercial Open Source, Application Servers

Don’t blow a gasket just yet!

Clarifications:

  • Commercial Open Source - I have no problem with the business model. My problem is with the expectations. Just because you have an open source offering does not mean that you can let it get bloated, the architecture antiquated, and the quality of code drop. Too often we cut them some slack just because they are open source. It is like this. Every day you come home and the neighbor’s brat is hurling insults at you. But you let it go. After all, he is just a kid. Then one day you come home and he is getting ready to light a bag of crap on your doorstep. Now he’s gone too far. You have no choice. You chase that little bastard down and introduce him to the back of your hand. The wife if going to have you sleeping on the couch. The kid’s parents are going to have a fit. You might even do a little jail time. But, eventually you’ll get out. The kid is not going to be bothering you again, and you live the rest of your days in piece and quiet. It was worth it.

So until next time, good fight, good night.

JBoss DNA, Hello.

December 31st, 2008

I suprised I didn’t come across this earlier. JBoss has a released a new federated repository system: DNA.

http://www.jboss.org/dna

I’ve caught up with the getting started document and the reference guide, and I quite like what I see. First things first, DNA is itself not a JCR implementation (yet). Rather, it unifies one or more repositories and provides a single point of access via the JCR API. The repositories themselves may be JCR compliant, but do not have to be. DNA comes with a variety of connectors such as the JCR, JDBC, and SVN connectors.

I find this to be quite practical. I worked with a number of clients who had multiple repositories whether they be JCR or simple databases. I’ve seen an environment with FileNet, Day Communique, Alfresco, and a number or Oracle databases. I’ve seen another with Magnolia, Day CQ, and a number of Oracle databases. I could cetainly make use of a unified repository in these environments.

I like that DNA is not simply an application, but an extensible framework for developers. It takes advantage of a very modular/pluggable architecture that allows you to write your own connectors (to connect to various repositories), sequencers (to extract metadata from repository content), and more.

Lastly, I thought there were two particular JIRA tasks that I found interesting.

https://jira.jboss.org/jira/browse/DNA-55 - A RESTful API.
https://jira.jboss.org/jira/browse/DNA-46 - A JCR implementation.

Those two should have a significant impace on just how practical DNA is.

So until next time, good fight, good night.

Better Discovery Through Visualization

December 29th, 2008

Paul Lamere has posted a demo of a new 3D interface that he’s been working on for exploring and discoverying new music. Be sure to click through and watch the YouTube video to behold some very impressive animations. Paul also notes that recommendations from Project Aura are on the way.

Paul continues to win the award for “Software That He Writes in His Spare Time is Better Than the Stuff I Write Professionally”.

Groovy is like Gravy, except that it has the “Groove” in it

December 24th, 2008

My five year old daughter, Meredith, recently asked me what I was working on. “I’m just working on some Groovy stuff”, I responded. She then announced: “Groovy is like Gravy, except that it has the ‘Groove’ in it”.

Besides being an outright adorable thing to say, I’m surprised at the level of truth embedded in it. As my first year of using Groovy draws to a close, I can see that duality in Groovy.

Indeed, in the realm of Java, Groovy can act simply as “gravy”, innocuously living along side existing Java code, harmlessly lending closure support and providing more flexible syntax.

Then on the other hand there is the full-tilt “Groove” aspect of Groovy where you can use Metaprogramming to write DSLs, and generally change the way the language behaves at runtime.

This must be a pretty well-known sentiment, since Scott Davis gives two talks on Groovy along these lines: Groovy the Blue and Red Pill respectively.

Who knows? Perhaps Meredith has sat in on these talks. That would explain her sudden interest in Expandos…

Tutorial: Jackrabbit OCM & Spring Modules JCR

December 19th, 2008

Introduction

Here is a brief tutorial on how to setup and object content mapping with Jackrabbit (1.5) and Spring.

First things first, download this zip and import the source into your project. As mentioned in this post support for Jackrabbit OCM in Spring still hasn’t found a home. Thus you have to download the zip from the JIRA.

The source includes an updated JackrabbitSessionFactory that we are going to reference in our Spring configuration.

Basic Spring/JCR Configuration


<bean id="password" class="java.lang.String">
   <constructor-arg index="0" value="superuser"/>
</bean>

<bean id="jcrRepository"
      class="org.springmodules.jcr.jackrabbit.RepositoryFactoryBean">
   <property name="configuration" value="classpath:repository.xml"/>
   <property name="homeDir" value="file:../repo"/>
</bean>

<bean id="jcrSessionFactory"
      class="org.springmodules.jcr.jackrabbit.ocm.JackrabbitSessionFactory">
   <property name="repository" ref="jcrRepository"/>
   <property name="workspaceName" value="default"/>
   <property name="credentials">
      <bean class="javax.jcr.SimpleCredentials">
         <constructor-arg index="0" value="superuser"/>
         <constructor-arg index="1">
            <bean factory-bean="password" factory-method="toCharArray"/>
         </constructor-arg>
      </bean>
   </property>
</bean>

Transaction Configuration - Required for OCM


<bean id="jcrTransactionManager"
      class="org.springmodules.jcr.jackrabbit.LocalTransactionManager">
   <property name="sessionFactory" ref="jcrSessionFactory"/>
</bean>

<bean id="txProxyTemplate" abstract="true"
      class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
   <property name="proxyTargetClass" value="true"/>
   <property name="transactionManager" ref="jcrTransactionManager"/>
   <property name="transactionAttributes">
      <props>
         <prop key="save*">PROPAGATION_REQUIRED</prop>
         <prop key="*">PROPAGATION_REQUIRED, readOnly</prop>
      </props>
   </property>
</bean>

List Beans to be Persisted


<util:list id="pages">
   <value>org.company.bean.Person</value>
   <value>org.company.bean.Address</value>
</util:list>

Register Beans with AnnotationMapper


<bean id="jcrMapper"
      class="org.apache.jackrabbit.ocm.mapper.impl.annotation.AnnotationMapperImpl">
   <constructor-arg index="0" ref="pages"/>
</bean>

<bean id="jcrMappingTemplate"
      class="org.springmodules.jcr.jackrabbit.ocm.JcrMappingTemplate">
   <property name="sessionFactory" ref="jcrSessionFactory"/>
   <property name="mapper" ref="jcrMapper"/>
   <property name="allowCreate" value="true"/>
</bean>

Add OCM Annotations



You need to add an @Node annotation to every bean you plan to persist. In addition, you need to add @Field annotations to every field to be persisted. The parent bean needs to have at least one field to store the node path. That is to say that our Person bean will need this field while our Address bean will not. In this case you need to use @Field(path = true). For a collection, you’ll use the @Collection annotation. That is it. These 3 annotation are all you need to get going.

The Person bean…

@Node
public class Person {

   private String path;
   private String firstName;
   private String lastName;

   @Collection List<Address> addresses;

   public List<Address> getAddresses() {
      return addresses;
   }

   public void setAddresses(List<Address> addresses) {
      this.addresses = addresses;
   }

   @Field
   public String getFirstName() {
      return firstName;
   }

   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }

   @Field
   public String getLastName() {
      return lastName;
   }

   public void setLastName(String lastName) {
      this.lastName = lastName;
   }

   @Field(path = true)
   public String getPath() {
      return path;
   }

   public void setPath(String path) {
      this.path = path;
   }

}

The Address bean…

@Node
public class Address {

   private String prefix;
   private String street;
   private String suffix;

   @Field
   public String getPrefix() {
      return prefix;
   }

   public void setPrefix(String prefix) {
      this.prefix = prefix;
   }

   @Field
   public String getStreet() {
      return street;
   }

   public void setStreet(String street) {
      this.street = street;
   }

   @Field
   public String getSuffix() {
      return suffix;
   }

   public void setSuffix(String suffix) {
      this.suffix = suffix;
   }

}

Use the JcrMappingTemplate



Now let us assume that the JcrMappingTemplate we configured has been wired to a DAO. Here is what the code might look like.

public class PersonDAO {

   private JcrMappingTemplate jcrMappingTemplate;

   public void testInsertPerson() {

      final Person person = new Person();

      person.setFirstName("Shane");
      person.setLastName("Johnson");

      person.setPath("/people/skj");

      final List<Address> addresses = new ArrayList<Address>();

      final Address address = new Address();

      address.setPrefix("123");
      address.setStreet("Main");
      address.setSuffix("St");

      addresses.add(address);

      person.setAddresses(addresses);

      jcrMappingTemplate.insert(person);
      jcrMappingTemplate.save();

   }

   public JcrMappingTemplate getJcrMappingTemplate() {
      return jcrMappingTemplate;
   }

   public void setJcrMappingTemplate(JcrMappingTemplate jcrMappingTemplate) {
      this.jcrMappingTemplate = jcrMappingTemplate;
   }

}

We can now persist Persons to Jackrabbit!

So until next time, good fight, good night.

Griffon: Grails-for-Swing

December 19th, 2008

What do you get your Swing developers with Grails Envy this holiday season? Consider getting them Griffon: the Grails-for-Swing framework.

Griffon brings the Grails “convention over configuration” to the embattled Swing space. Among many other things Griffon takes all of the terribleness out of Java deployment. With but one command (and no coding) I can create a simple scaffolded Swing application deployed via webstart, applet, and as a standalone app. Note that’s all three: I don’t even need to choose my deployment method.

While it’s still very new (0.1 Beta has just been released — hey, I didn’t say it was ready for production), great things are in the pipeline, like GORM integration.  Indeed, a great selling point of Griffon (I assume) is that it can mature right alongside of Grails.

The coolest part though is that it enables you to write Java desktop apps in Groovy — and really, isn’t that what we all want to be doing?

Wealthy donors and Benevolent Corporations: throw money at this project.  Something like this in the Java desktop realm is sorely needed.

Spring, JAX-RS, Freemarker, & MVC

December 15th, 2008

I’ve realized that JAX-RS can be used to build a web applications based on the MVC pattern just like any other framework (Wicket, Stripes, etc). Typically I use JAX-RS to build services that return XML and/or JSON, but there is no reason I can’t return HTML as well. I feel that the hierarchal nature of RESTful services makes them perfect for delivering website pages too. The only thing that was missing for me was an HTML provider. I’m used to using the JAXB and JSON providers, and I didn’t see a built in one for rendering HTML. So, I decided to build a custom JAX-RS Freemarker provider.

Freemarker Model

When you build a custom JAX-RS provider you have to implement the isWritable method. The JAXB and JSON providers look for the @XmlRootElement annotation and return true if it is found. In addition, the JAX-RS runtime first selects the appropriate providers based on the mime type. It then calls the isWritable method on these providers. The first one that returns true is used.

At the time, I was not using any custom annotations so I decided to create a new class to be used specifically for my Freemarker provider. This way I can just rely on the class.isAssignableFrom method when I implement the isWritable method. That, and it made sense to use my own model because I needed very specific information. I needed the name of the Freemarker template, and the actual ‘model’ to apply to it.

public class FreemarkerModel {

   private Map<String, Object> model;

   private String view;

   // getters and setters
   ...

}

Freemarker Provider

Next, I just created a new provider and implemented MessageBody<FreemarkerModel>. This is what I ended up with.

@ProduceMime("text/html")
@Provider
public class FreemarkerProvider implements
      MessageBodyWriter<FreemarkerModel> {

   private static final Logger LOGGER =
      Logger.getLogger(FreemarkerProvider.class);

   private Configuration freemarkerConfig;

   public long getSize(FreemarkerModel viewModel) {
      return -1;
   }

   public boolean isWriteable(Class<?> type, Type genericType,
         Annotation[] annotations) {
      return FreemarkerModel.class.isAssignableFrom(type);
   }

   public void writeTo(FreemarkerModel viewModel, Class<?> type,
         Type genericType, Annotation[] annotations,
         MediaType mediaType,
         MultivaluedMap<String, Object> headers, OutputStream os)
         throws IOException, WebApplicationException {

      final Template t =
         freemarkerConfig.getTemplate(viewModel.getView());

      try {
         t.process(viewModel.getModel(),
            new OutputStreamWriter(os));
      }
      catch (TemplateException ex) {
         LOGGER.error(ex.getMessage(), ex);
      }

   }

   public Configuration getFreemarkerConfig() {
      return freemarkerConfig;
   }

   public void setFreemarkerConfig(
         Configuration freemarkerConfig) {
      this.freemarkerConfig = freemarkerConfig;
   }

}

Spring Configuration

Finally, I needed to wire it all together in my Spring configuration.

<bean id="freemarkerConfig"
      class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
   <property name="templateLoaderPath"
      value="/WEB-INF/templates/ftl"/>
</bean>

<jaxrs:server id="myServer" address="/">
   <jaxrs:serviceBeans>
      <ref bean="myService" />
   </jaxrs:serviceBeans>
   <jaxrs:providers>
      <bean class="org.company.jaxrs.provider.FreemarkerProvider">
         <property name="freemarkerConfig" ref="freemarkerConfig"/>
      </bean>
   </jaxrs:providers>
</jaxrs:server>

JAX-RS service/Freemarker

That’s all there is to it! Here is an example of using this provider in a JAX-RS service.

@GET
@Path(value = "/page/{path}", limited = false)
public FreemarkerModel getPage(@PathParam("path") String path) {

   final Map model;
   final String view;

   // populate the model and select a view template (ftl)
   ...

   final FreemarkerModel viewModel = new FreemarkerModel();

   viewModel.setModel(model);
   viewModel.setView(view);

   return viewModel;

}

Coming Up: Spring, Jackrabbit, & OCM (A working configuration.)

So until next time, good fight, good night.

The Map vs. the Terrain (or DSLs as Documentation)

December 11th, 2008

In the late David Foster Wallace’s Infinite Jest, several of the main characters participate in a grand scale “Scorched Earth” style turn-based artillery game on a set of tennis courts. The object for each player was to lob tennis balls across court to opposing player’s targets where the balls represent some sort of ballistic warhead complete with a damage radius.

At one point it starts snowing, and one of the players argues that the damage caused by a recent “explosion” would not be as great due to the snow. One of the other players retorts that “It’s snowing on the map, not the [gosh darn] terrain!”, meaning that there was a confusion between where the line lay between the game world and that which represented the game world — that is, the terrain and the map.

It seems to me that there is a similar struggle going on within software engineering: between the software we write (the terrain), and that which describes the software (the map). Typically the “map” to software’s “terrain” has been documentation. One of the eternal (or more accurately: perennial) issues in the projects that I’ve been a part of has revolved around the tension of documentation.

In a previous project of years past, we were told to document every single method and variable. That of course didn’t work out since at that point, you get a map that perfectly describes (or even over-describes) the terrain. Beyond the maintenance nightmare (and gross violation of the DRY principle), when your “map” effectively covers your “terrain”, you start to call into question just who is supposed to be describing who.

Thankfully I’ve spent the vast majority of my time on the other end of the spectrum, more toward the realm of (attempting) “self-documenting code”, supported by languages that are designed more for humans than computers.  This is because in-line comments as documentation is not the entire story — code can be used to document itself — and this is where things start to get interesting.

Some advocate that unit tests should serve as a primary source of documentation. Neal Ford said in a recent talk that the first thing he does when he returns to a project after being away is not to catch up on documentation or even the codebase, but is to read the tests.

Unfortunately I have a passive-aggressive approach to writing documentation, in that when I’m told to write it for its own sake, I actually end up writing less. So if it starts sinking into my head that writing tests is like writing documentation, I’m likely to just write fewer tests.

But this idea goes further still: with so-called Behavior Driven Development (BDD) we start approaching an “executable specification”. With BDD the idea is almost completely turned around and the software becomes the map to describe the terrain of behaviors.

I’m not sure what I think about BDD yet, or for that matter even TDD. It may be that they are super productive, super-collaborative and error-less ways to develop software — but they are also extremely intrusive. I think it would be difficult to be lukewarm about either of the “DD”s since it requires such a significant buy-in.

Fortunately self-describing code found another way into my life.

In my most recent project, we used an internal DSL, partly for ease of development, but also, as a nice side-effect, for its self-documenting nature. Internal DSLs (more or less by definition) aim to be more readable than the host language in which they reside. This makes for code that more or less matches anything that I would put in a javadoc comment.

In many ways I think it makes sense to write entire applications in a combination of various DSLs. This isn’t much of a stretch since we basically do this already (SQL in the DA layer, declarative UI languages in the presentation layer).

It seems that most “business” layers would additionally benefit from their own DSL. What’s more is that we’re starting to see tools that will aid in generating DSLs, such as Language Workbenches, and on a much smaller scale, Groovy’s MetaBuilder.

As we migrate more toward each piece of an application being written in a language that perfectly describes the domain, perhaps we’ll even live to see the death of the in-line comment in our lifetimes.

Incidentally, if you want to learn more about DSLs and how you might benefit from them (and you live in the Chicago area), then come to my talk “Using Groovy to Create DSLs: A Real-World Case Study” at the first ever Chicago Groovy User Group on January 13th 2009.