Wednesday, September 10, 2014

Getting Scalatra to work on Google App Engine

Scalatra is a neat lightweight Scala web framework. Scalatra 2.3.0 is based on the Servlet API 3.1 , while App Engine Java runtime only supports Servlet API 2.5 . App Engine imposes additional restrictions as described here, but they are not as significant as lack of support for Servlet 3.0/3.1 .

After digging and experimenting, I succeeded in getting Scalatra to work on App Engine with a few workarounds. Basically we need to refrain from using Servlet 3.0/3.1 specific features in our code, and override Scalatra's parts that do use them with Servlet 2.5 compatible alternatives.

The first obstacle you'll encounter is that you can't mount your servlets and filters programmatically in your ScalatraBootstrap class like this:

import org.scalatra.LifeCycle

import javax.servlet.ServletContext

class ScalatraBootstrap extends LifeCycle {

   override def init(context: ServletContext) {

      // This will fail
      context mount (new MyCustomServlet, "/*")

Instead, you leave the init() method empty, and add your servlets and filters to web.xml :


Then, at runtime when accessing a path which is mapped by your Scalatra endpoints, you will encounter a NoSuchMethodError because Scalatra attempts to call HttpServletResponse.getStatus(), which was added in Servlet API 3.0 . The problematic code is in RichResponse.status(). RichResponse is an implicit replacement for HttpServletResponse as defined in ServletApiImplicits.enrichResponse(). To overcome the reading of the status from the original response, we'll subclass RichResponse and change the setter and getter of the status to use a local variable:

import org.scalatra.servlet.RichResponse
import javax.servlet.http.HttpServletResponse
import org.scalatra.ResponseStatus

class RichResponseLocalStatus(response:HttpServletResponse) extends RichResponse(response) {

   var statusCode:Int = _

   override def status = ResponseStatus(statusCode)

   override def status_=(statusLine: ResponseStatus) {
      statusCode = statusLine.code
} }

The Scalatra code made it impossible to override the implicit definition for our need, so we have to rewrite ServletApiImplicits to look like this:

package org.scalatra
package servlet

import javax.servlet.ServletContext
import javax.servlet.http.{HttpServletRequest, HttpServletResponse, HttpSession}
import test.RichResponseCustom

trait ServletApiImplicits {

   implicit def enrichRequest(request: HttpServletRequest): RichRequest =

   implicit def enrichResponse(response: HttpServletResponse): RichResponse =

      // This is changed
      new RichResponseLocalStatus(response)

   implicit def enrichSession(session: HttpSession): RichSession =
implicit def enrichServletContext(servletContext: ServletContext): RichServletContext = RichServletContext(servletContext) } object ServletApiImplicits extends ServletApiImplicits

Remember to place the changed ServletApiImplicits with your sources in the "org.scalatra.servlet" package. If you place it in another JAR, remember to make sure it takes precedence over Scalatra's JAR using App Engine's classloader JAR ordering.

That's it. It's not a perfect solution as it won't support Servlet 3.0/3.1 features such as asynchronous processing, and you have to define and map each servlet and filter in web.xml, but these are limitations you have to live with anyway on App Engine and this solution does let you use the nice and clean Scalatra code to write your web tier.

Sunday, May 25, 2014

Spring Social Google 1.0.0 Reaches General Availability

I am happy to announce the release of Spring Social Google 1.0.0.RELEASE ! I would like to thank everyone who contributed by testing and submitting issues and pull requests.

Spring Social Google contains bindings to Google Plus, Google Tasks and Google Drive APIs, and allows you to use any Java client library for any Google API while using Spring Social for authentication and connection management.

Project on GitHub:

Distribution bundle:

Reference manual:


Example application:

To use with Maven add the following code to your POM:

Creating a Google Cloud Project and Using it with Spring Social Google

Navigate to

Click "Create Project" and enter a name and ID for the project.

Enter the project and in the left menu select "APIs & Auth". In "APIs" activate the APIs you want to use in the application. The example application uses Google+ API and Tasks API.

In the left menu go to "Credentials" and click "Create new client ID". For "Application Type" choose "Web Application" and for "Authorized Redirect URI" enter "http://localhost:8080/signin/google".

The new set of credentials will be added. Note the "Cliend ID" and "Client Secret" values - we will use them when running the example application.

Get the example application from GitHub:
git clone git://

Enter the application directory and run it with Tomcat (replace CLIENT_ID and CLIENT_SECRET with the values you saw in Google Developers Console):
cd spring-social-google-example
mvn tomcat7:run \
   -Dgoogle.clientId=CLIENT_ID \

The application will run at http://localhost:8080/

The Road Ahead

There is no shortage of Google APIs. My current though is to proceed to YouTube and Calendar, but I really want to know what you want, so please submit your requests and issues in the GitHub project.

Enjoy using Spring Social Google!

Monday, April 9, 2012

Spring Social Google First Milestone Is Out

I'm happy to announce that the first milestone of Spring Social Google is out! Since the project started I received a lot of feedback from the community that helped shape this milestone and I would like to thank everyone who helped with suggestions, bug reports, patches and kind words.

This milestone includes integration with Google+, Portable Contacts and Google Tasks. It also lets you integrate with the GData Java Client Library, letting you use Spring Social Google for authentication and authorization, and applying the OAuth2 access token to an instance of a GData client. Please see the reference manual for usage instructions.

The example application demonstrates most of the available functionality. You can see it in action here.

To use Spring Social Google in a maven project, add the following repository and dependency to your pom.xml :

    <name>Spring Social Google</name>



or download the JAR here.

The project roadmap mostly depends on community feedback. Integration with more Google APIs will be added and you can help decide which will be first, so let me know what you think.

Enjoy using Spring Social Google!

Thursday, October 27, 2011

Replacing javac with eclipse compiler in Maven

I was working on a Java project with eclipse where I used cyclic dependencies. Specifically I implemented the Reverse MVP pattern with GWT Platform. Everything went well in as long as I was using eclipse to compile the project, but once I tried to use Maven to compile the project, I got compilation errors for every case where I had a cyclic dependency. I figured that if eclipse is good enough to compile the sources in development time, it might as well be used in build time instead of JDK's javac. Here is the maven-compiler-plugin configuration from the project POM I initially had:

In order to replace javac with eclipse compiler we need to do two things: we need to add a dependency for plexus-compiler-eclipse, and we need to tell the maven-compiler-plugin to use the eclipse compiler as described here. Here is the updated configuration:

After that it was possible to build the project with Maven.

Thursday, September 22, 2011

Spring Social Meets Google APIs

For the past several weeks I have been working on the Spring Social Google project. The goal of Spring Social is to act as an abstraction layer between your application code and various social APIs, and removes the need for you to deal with authentication and HTTP-Java mapping, and now you can use it with a growing number of Google APIs, starting with the Contacts API and Google+ API.

Why do I need this? Google already provides Java libraries for its APIs.

Indeed you can use the Java libraries from Google, but there are cases where you may benefit from using Spring Social instead. For once, Spring Social comes with an authentication mechanism that removes the need for you to write Servlet code for the stages of the OAuth2 process. You can read about it here. Another goodie Spring Social provides is connection management and persistence, so you don't have to deal with session management and and writing your own database schema to store the users' access tokens. You can read about it here. You can see how to set up both mechanisms in the example application, specifically in and spring-config.xml .

Spring Social also takes a different approach than Google's Java libraries in that Google's libraries provide a Java API that mirrors the underlying REST API (be it Atom, Portable Contacts or other), while Spring Social aims to provide you with data structure and operations you are likely to use.
Let's use both tools to write a program that fetches the user's contacts and prints their names and primary e-mail addresses.

Here is how it's done with Google Contact API Java library:

ContactsService service = getContactsService();
URL feedUrl = new URL("");
ContactFeed resultFeed = service.getFeed(feedUrl, ContactFeed.class);
for (ContactEntry entry : resultFeed.getEntries()) {
   String fullName = entry.getName().getFullName().getValue();
   String email = null;
   for(Email e : entry.getEmailAddresses() {
      if(email.getPrimary) {
         email = e;
   System.out.println(fullName + " " + email);

And here is the equivalent Spring Social Google code:

GoogleOperations google = getGoogleOperations();
List<Contact> contacts = google.contactOperations().getContactList();
for(Contact contact : contacts) {
   String fullName = contact.getFullName();
   String email = contact.getPrimaryEmail();
   System.out.println(fullName + " " + email);

It's up to you to decide if you prefer the simplicity of Spring Social or the flexibility of the Google API Java libraries.

Is the project stable? What is its roadmap?

Spring Social Google is still at an early stage, so there are no builds and the API may change. Aside of the currently implemented Contacts and Google+ APIs, the project is expected to include more and more of Google APIs over time. You are welcome to download the sources and play with the example application, which is also deployed on Cloud Foundry

Enjoy and send feedback!

Saturday, July 30, 2011

Dynamically Adding Styles to HTML Pages

I came into a situation where I needed to apply styles to the entire page after the page was loaded. Using techniques like targeting elements by their CSS selectors and applying styles to them with jQuery or similar tools would not be sufficient, because I would have to do it every time elements are added to the DOM and it would have required specifically adding a class (or some other attribute) to each element I wanted to apply the style to.

The solution I ended up implementing was to add styles to the page dynamically using JavaScript. Normal browsers let you manipulate the Head element as any other element, so all I needed to do was to append the Style element as a child of the Head element, and set the style's inner HTML with the CSS content:

function addCustomStyle() {
   var style = document.createElement("style");
   style.innerHTML = ".someclass {color: green;}";
   var head = document.getElementsByTagName("head")[0];

Unsurprisingly like so many other cases, Internet Explorer has its own way of doing stuff. It doesn't allow manipulating the Head element as other elements, but it does provide an API for adding CSS rules to the document. Here is how it's done:

function addCustomStyle() {
   var style = document.createStyleSheet();
   style.addRule(".someclass", "color: green;");

You could wrap the two methods with IE conditional tags ([if !IE] and [if IE]) so only one of them will actually be used depending on the browser, or you can come up with your own mechanism. If you are using GWT, deferred binding is perfect for this.

Thursday, January 20, 2011

Better Enum Mapping with Hibernate

JPA and Hibernate provides two ways to map enum fields to database fields: either map the enum value ordinal with @Enumerated(EnumType.ORDINAL) or the enum value name with @Enumerated(EnumType.STRING) . Both cases are not ideal, because it's very easy to make changes to the enum, such as changing values order or renaming values, and forgetting to migrate the existing values in the database accordingly. Actually the need to migrate existing data is not justified if you just want to change Java code.

Here is a mechanism that lets you decouple the enum value names and ordinals from the data, while still making it easy to map enum fields to database columns.

The solution can be specific to an enum type, but it would be better to have all your persistent enum types implement the same interface to reuse the mechanism. Let's define the PersistentEnum interface:

public interface PersistentEnum {
    int getId();

and it will be implemented by enum types, for example:

public enum Gender implements PersistentEnum {


    private final int id;

    Gender(int id) { = id

    public int getId() {
        return id;


Now we need to define the Hibernate User Type that will do the conversion both ways. Each enum requires its own user type, so first we will code an abstract superclass that works with the PersistentEnum interface and then subclass it for each enum:

public abstract class PersistentEnumUserType<T extends PersistentEnum> implements UserType {

    public Object assemble(Serializable cached, Object owner)
            throws HibernateException {
        return cached;

    public Object deepCopy(Object value) throws HibernateException {
        return value;

    public Serializable disassemble(Object value) throws HibernateException {
        return (Serializable)value;

    public boolean equals(Object x, Object y) throws HibernateException {
        return x == y;

    public int hashCode(Object x) throws HibernateException {
        return x == null ? 0 : x.hashCode();

    public boolean isMutable() {
        return false;

    public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
            throws HibernateException, SQLException {
        int id = rs.getInt(names[0]);
        if(rs.wasNull()) {
            return null;
        for(PersistentEnum value : returnedClass().getEnumConstants()) {
            if(id == value.getId()) {
                return value;
        throw new IllegalStateException("Unknown " + returnedClass().getSimpleName() + " id");

    public void nullSafeSet(PreparedStatement st, Object value, int index)
            throws HibernateException, SQLException {
        if (value == null) {
            st.setNull(index, Types.INTEGER);
        } else {
            st.setInt(index, ((PersistentEnum)value).getId());

    public Object replace(Object original, Object target, Object owner)
            throws HibernateException {
        return original;

    public abstract Class<T> returnedClass();

    public int[] sqlTypes() {
        return new int[]{Types.INTEGER};


The interesting methods are nullSafeGet() which is called when the resultset from the database is mapped to an object, and nullSafeSet() which is called when the fields of an object are mapped to SQL parameters of insert/update/delete statements.

The extension point is the abstract method returnedClass() - in every subclass we will override it so it returns the specific enum class. A User Type for the Gender enum defined above would like this:

public class GenderUserType extends PersistentEnumUserType<Gender> {

    public Class<Gender> returnedClass() {
        return Gender.class;


The last thing to do is to configure fields of enum types to use the appropriate user types:

public class Person {

    private Gender gender;

    // other fields and methods...

Note that the type attribute should contain the fully qualified class of the user type, including the package.

That's it - now you can safely make changes to your enum classes without worrying about problems with existing data, as long as you don't change the id values in the constructors (which you have no reason to do).