Presenting at GraphConnect 2012: Building & Deploying Graph-based Web Apps

On November 6th I will be presenting Building & Deploying Graph-based Web Apps at the GraphConnect 2012 conference in San Francisco. Here is the session description:

This session will teach you how to build a Graph-based web application with Java, Play Framework, and Neo4j. You will also lean how to deploy the application on the cloud with Heroku. The session will primarily be code and live demos.

I hope to see you there!

JavaOne Video: Introduction to Play Framework

Check out the recording of my Introduction to Play Framework at JavaOne 2012. If you want to try Play Framework on your own you might want to start with my Play2torial for Java. There you will walk through all the major parts of building a modern web app: Models, Controllers, Views, Tests, JavaScript/CoffeeScript, Twitter Bootstrap, and Cloud Deployment. Let me know how it goes!

NoSQL Inside SQL with Java, Spring, Hibernate, and PostgreSQL

There are many benefits to schema-less NoSQL datastores, but there are always trade-offs. The primary gift the NoSQL movement has given us is the variety of options we now have for data persistence. With NoSQL we no longer must try to shoehorn everything into a relational model. Now the challenge is in deciding which persistence model fits best with each domain in a system and then combining those models in a cohesive way. The general term to describe this is Polyglot Persistence and there are many ways to accomplish it. Lets walk through how you can combine a regular SQL model with a key-value NoSQL model using Java, Spring, Hibernate, and PostgreSQL.

This article covers the pieces of a simple web application which uses regular SQL and PostgreSQL’s hstore for key value pairs. This method is a mix of NoSQL inside SQL. One benefit of this approach is that the same datastore can be used for both the SQL and the NoSQL data.

In this example the server technologies will be Java, Spring, and Hibernate. (The same thing can also be done with Rails, Django, and many other technologies.) To add Hibernate support for hstore I found a fantastic blog about “Storing sets of key/value pairs in a single db column with Hibernate using PostgreSQL hstore type“. I won’t go through that code here but you can find everything in the GitHub repo for my demo project.

This demo app uses Maven to define the dependencies. Embedded Jetty is started via a plain ‘ole Java application that sets up Spring MVC. Spring is configured via Java Config for the main stuff, the web stuff, and the database stuff.

The client technologies will be jQuery and Bootstrap and there is a strict seperation between the client and server via RESTful JSON services. The whole client-side is in a plain ‘ole HTML file. Via jQuery / Ajax the client communicates to JSON services exposed via a Spring MVC Controller.

Ok. Now onto the NoSQL inside SQL stuff. This application stores “Contacts” that have a name but also can have many “Contact Methods” (e.g. phone numbers and email addresses). The “Contact Methods” are a good use of a schema-less, key-value pair column because it avoids the cumbersome alternatives: putting that information into a separate table or trying to create a model object that has all of the possible “Contact Methods”. So lets take a look at the simple Contact Entity:

package com.jamesward.model;
import net.backtothefront.HstoreUserType;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.HashMap;
import java.util.Map;
@TypeDef(name = "hstore", typeClass = HstoreUserType.class)
public class Contact {
    public Integer id;
    @Column(nullable = false)
    public String name;
    @Type(type = "hstore")
    @Column(columnDefinition = "hstore")
    public Map<String, String> contactMethods = new HashMap<String, String>();

If you are familiar with Hibernate / JPA then most of this should look pretty familiar to you. The new / interesting stuff is the contactMethods property. It is a Map<String, String> and it uses PostgreSQL’s hstore datatype. In order for that to work, the type has to be defined and the columnDefinition set. Thanks again to Jakub Głuszecki for putting together the HstoreHelper and HstoreUserType that make this possible.

Now the rest is simple because it’s just plain Hibernate / JPA. Here is the ContactService that does the basic query and updates:

package com.jamesward.service;
import com.jamesward.model.Contact;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import java.util.List;
public class ContactServiceImpl implements ContactService {
    EntityManager em;
    public void addContact(Contact contact) {
    public List<Contact> getAllContacts() {
        CriteriaQuery<Contact> c = em.getCriteriaBuilder().createQuery(Contact.class);
        return em.createQuery(c).getResultList();
    public Contact getContact(Integer id) {
        return em.find(Contact.class, id);
    public void addContactMethod(Integer contactId, String name, String value) {
        Contact contact = getContact(contactId);
        contact.contactMethods.put(name, value);

Now that you understand how it all works, check out a live demo on Heroku.

If you want to run this app locally or on Heroku, then first you need to grab the source code and continue working inside the newly created spring_hibernate_hstore_demo directory:

$ git clone
$ cd spring_hibernate_hstore_demo

To run locally:

  1. Setup your PostgreSQL database to support hstore by opening a psql connection to it:
    $ psql -U username -W -h localhost database
  2. Then enable hstore:
    => create extension hstore;
    => \q
  3. Build the app (depends on having Maven installed):
    $ mvn package
  4. Set the DATABASE_URL environment variable to point to your PostgreSQL server:
    $ export DATABASE_URL=postgres://username:password@localhost/databasename
  5. Start the app:
    $ java -cp target/classes:target/dependency/* com.jamesward.Webapp
  6. Try it out

Cool! Now you can run it on the cloud with Heroku. Here is what you need to do:

  1. Install the Heroku Toolbelt
  2. Login to Heroku:
    $ heroku login
  3. Create a new app:
    $ heroku create
  4. Add Heroku Postgres:
    $ heroku addons:add heroku-postgresql:dev
  5. Tell Heroku to set the DATABASE_URL environment variable based on the database that was just added (replace YOUR_HEROKU_POSTGRESQL_COLOR_URL with your own):
    $ heroku pg:promote YOUR_HEROKU_POSTGRESQL_COLOR_URL
  6. Open a psql connection to the database:
    $ heroku pg:psql
  7. Enable hstore support in your database:
    => create extension hstore;
    => \q
  8. Deploy the app:
    $ git push heroku master
  9. View the app on the cloud:
    $ heroku open

Fantastic! Let me know if you have any questions.

Heroku & Play Framework at JavaOne 2012

This year at JavaOne I’ll be presenting two session and participating in one BOF:

BOF4149 – Web Framework Smackdown 2012 – Monday @ 8:30pm

Much has changed since the first Web framework smackdown, at JavaOne 2005. Or has it? The 2012 edition of this popular panel discussion surveys the current landscape of Web UI frameworks for the Java platform. The 2005 edition featured JSF, Webwork, Struts, Tapestry, and Wicket. The 2012 edition features representatives of the current crop of frameworks, with a special emphasis on frameworks that leverage HTML5 and thin-server architecture. Java Champion Markus Eisele leads the lively discussion with panelists James Ward (Play), Graeme Rocher (Grails), Edward Burns (JSF) and Santiago Pericasgeertsen (Avatar).

CON3845 – Introduction to the Play Framework – Tuesday @ 8:30am

The Play Framework is a lightweight, stateless Web framework for Java and Scala applications. It’s built on Java NIO, so it’s highly scalable. This session gives you an introduction to building Web applications with the Play Framework. You will learn how to set up routes and create controllers and views, plus how to deploy Play Framework applications in the cloud.

CON3842 – Client/Server Applications with HTML5 and Java – Thursday @ 11am

The Web application landscape is rapidly shifting back to a client/server architecture. This time around, the client is JavaScript, HTML, and Cascading Style Sheets in the browser. The tools and deployment techniques for these types of applications are abundant and fragmented. This session shows you how to pull together jQuery, LESS, and Twitter Bootstrap to build the client. The server can be anything that talks HTTP, but this session uses JAX-RS. You will also learn how to deploy client/server Web applications in the cloud with a content delivery network (CDN) for the client and a PaaS for the server.

I hope to see you there!

Heroku at JavaZone 2012

I’m really looking forward to being back at JavaZone in Oslo this September! I’ll be speaking about Running Java, Play! and Scala Apps on the Cloud. This session will teach you how to get started deploying Java and Scala apps on Heroku. I’ll be around for the whole conference, so if anyone wants to grab a drink, deploy some apps, or write some code with me, then let me know. See you there!

Dreamforce 2012: Java Apps on Heroku &

Dreamforce 2012 is going to be a fantastic event! And not just because Red Hot Chili Peppers, Colin Powell, and Richard Branson will be there. I’ll also be there talking about Building Java Apps on Heroku and Here is the description for my session:

In this session you will learn how to build Social Enterprise applications using Salesforce, Heroku, and Java. Through live coding and demonstrations you will learn how to instantly deploy and scale Java apps on the cloud with Heroku. You will also learn how to integrate those applications with Salesforce and through REST.

Sounds pretty exciting when put next the celebrities, right? Hope to see you there!

Containerless Spring MVC

Many of the new JVM-based web frameworks are ditching containers and WAR files and instead using a WAR-less / Containerless approach. But that doesn’t mean you have to ditch your favorite Java web framework. A while back I posted about going containerless with Tapestry. Now lets do the same with Spring MVC. You can grab the full source code from GitHub.

First we need a build that defines the dependencies. Here is the build.gradle file for my Gradle build:

apply plugin:'java'
apply plugin:'application'
version = '0.0.1-SNAPSHOT'
mainClassName = "com.jamesward.Webapp"
applicationName = "webapp"
repositories {
dependencies {
    compile 'org.springframework:spring-webmvc:3.1.2.RELEASE'
    compile 'cglib:cglib:2.2.2'
    compile 'org.eclipse.jetty:jetty-webapp:8.1.5.v20120716'

There isn’t much to this build except a few dependencies: Spring MVC, CGLib, and Jetty.

The src/main/resources/assets/index.html file just contains simple HTML:

<!doctype html>
hello, world

The src/main/java/com/jamesward/ file uses Spring annotations to configure Spring MVC:

package com.jamesward;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
public class WebConfig extends WebMvcConfigurerAdapter {
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    public void addViewControllers(ViewControllerRegistry registry) {

Finally, a simple “static void main” Java class is used to start Jetty. The src/main/java/com/jamesward/ file just sets up the HTTP listener and starts it:

package com.jamesward;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.servlet.DispatcherServlet;
public class Webapp {
    public static void main(String[] args) throws Exception {
        final AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        final ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(applicationContext));
        final ServletContextHandler context = new ServletContextHandler();
        context.addServlet(servletHolder, "/*");
        String webPort = System.getenv("PORT");
        if (webPort == null || webPort.isEmpty()) {
            webPort = "8080";
        final Server server = new Server(Integer.valueOf(webPort));

That’s it! To build and run this project locally you can simple run:

./gradlew run

(Note: Run “gradlew.bat” on Windows.)

So simple it’s hard to believe it works. :) Let me know if you have any questions.