Wednesday, January 7, 2009

EJB 3.1 embeddable container and end of life for spring framework.

Just amazing what can be found in borring JCP document. All this story started once I decided to do some research regarding EJB 3.1 specification.

I will print only a few sentences from JSR-318 and will add some thought and comments about only one tiny part of it, just what is related with Embedded EJB container.

Enterprise JavaBeansTM 3.1 and what is said about Embedded Container.

Embeddable usage allows client code and its corresponding EJB 3.1 to run within the same JVM and class loader. This provides better support for testing, offline processing (e.g. batch), and the use of the EJB programming model in desktop applications.

The client uses a spec-defined bootstrapping API to start the container and identify the set of enterprise bean components for execution. The embeddable EJB container provides a managed environment with support for the same basic services that exist within a Java EE runtime : injection, access to a component environment, container-managed transactions, etc. In general, enterprise bean components are unaware of the kind of managed environment in which they are running. This allows maximum reusability of enterprise components across a wide range of testing and deployment scenarios without significant rework.

My comments and thoughts.

What makes me happy, this is an ability to have an EJB in desktop applications or regular java web application packaged as war and running in tomcat or other servlet container. Idea of having an EJB in tomcat is not absolutely new, OpenEJB does exactly that, but to be used in desktop application, for me it's a mind blowing idea. I like it very much.
Most of the people are using spring for their desktop applications and it helps a lot. Everyone knows that there are more frameworks following dependency injection pattern such as google-guice, pico container and others. Some of them have better performance, others are easier to use, but all, all of them without exceptions makes you dependent on them, you can not throw them out or replace by something more suitable later, or remove from runtime. Yes application is always dependent on execution environment and in this case dependent on spring or some other DI or EJB container. The point is an EJB container is a specification and it can be replaced by another more suitable for current task or environment, but spring can be replaced only by a newer version of spring.

What is most amazing, even full blown EJB containers such as Glassfish already are close to or almost at the same level of performance as spring framework and is easier to write and configure. Feel shocked, trust me or read these blog posts.

And here are some other interesting blog posts, for example I will list a few of them with some comments:
* Simplest possible EJB 3.1 shows what effort it takes to write an EJB 3.1 compliant bean, no xml, no interfaces, nothing what you ever could call boilerplate code.
* Some interesting thoughts about EJB vs POJO.
* EJB vs POJO performance
* EJB3 memory consumption.


And now the last thoughts. Everyone knows that spring framework is going to become application server, scary, yeah that's right a Java EE Application Server. Don't you think that spring has no option anymore, EJB's already becoming more effective in some cases and it's not a vendor lock in. Only option for spring is to become another option in list of options. What irony I see, is that spring lost his enemy, spring always was an opposition to EE, and now it becomes an EE by himself. That automatically makes it less appealing choice for new projects.

Have fun feature are bright

Regards Remigijus Bauzys

Monday, January 5, 2009

RESTful Web Services with Jersey JSR-311

Currently I'm excited about RESTful web services. REST is a kind of buzzword at this time and there are some good reasons for buzz. I do believe that REST for web services will stay for long time or hopefully even as long as web will exist. And today I'll try to do my first RESTful web service based on jersey.

Project Jersey is a reference implementation for JSR-311 for building RESTful Web services. As this specification states "it defines a set of Java APIs for the development of Web services built according to the 3
Representational State Transfer (REST) architectural style".

I was watching this project for quite long time, saw some presentations and red quite a lot about it and did a little bit of RESTful web services. So all this staff is not very new to me. Nevertheless this is my first try on JSR-311 and Jersey.

First impressions

At the beginning I thought and hoped that jersey will be something very or reasonably lightweight, few jars and servlet configuration for web.xml. These expectations comes from the stripes framework which I currently use and enjoy it very much. In general it has a very similar annotation based mapping between URI and handler methods and can be used with little bit adoption for similar things. But as you already guessed it is different, actually it has a lot of dependencies and comes even with grizzly or light weight http server, all JAXB jars if you a still on Java SE 5, ASM and other jars as optional. Documentation on jersey site scared me a little bit, it was not easy to understand what do I need for minimal start. I guess if I would be a maven friend everything could be easier.

At some point, when I was close to getting angry, about insane documentation I made decision to start with NetBeans. For the beginning I created a new Hello World (RESTful) Web Services project from one of the NetBeans samples project, after what I got a new project what was running and ready to go. This is the easiest way to get started. From that point everything went very smooth I knew what REST is and what I like to get at the end. Of course in order to understand what I should expect form Jersey and how can it differ from traditional RESTful I downloaded JSR-311 documentation in PDF form and JavaDocs.

JSR documentation is very short, only 49 pages and easy to read and understand. I'm true believer in the KISS, so I liked simplicity of this JSR.

The source code of my application is in one file. Application is just a simple test case where I want to have a catalog of the products and vendors. For this time I did most of the CRUD operations for vendor, they are : list vendors, add new vendor, and delete vendor. Update operation for vendor I didn't do because just for simplicity vendor has only one field which is a vendor's title and that makes unreasonable to do update operation.


package helloworld;

import java.util.ArrayList;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

/**
*
* @author remis
*/
@Path("/catalog")
public class CatalogResource {

private static ArrayList vendors = new ArrayList();

@GET
public String getCatalog() {
return "catalog index";
}

/**
* On HTTP GET method for /catalog/vendor returns full list of vendors.
* @return string with full list of vendors separated by semicolon.
*/
@GET
@Path("vendor")
public Response getVendors() {
StringBuilder sb = new StringBuilder();
for (String vendor : vendors) {
sb.append(vendor).append(";");
}
return Response.ok(sb.toString()).build();
}

/**
* On HTTP GET method for /catalog/vendor/{title} returns
* data of the specified vendor.
* @return string with title of found vendor. In case if such vendor
* does not exist
*/
@GET
@Produces("text/plain")
@Path("vendor/{title}")
public Response getVendor(@PathParam("title") String title) {
Response result = null;
if (! hasVendor(title)) {
result = Response.ok(title).build();
} else {
result = Response.noContent().build();
}
return result;
}

private boolean hasVendor(String vendor) {
return (vendor != null && vendors.contains(vendor));
}

@DELETE
@Produces("text/plain")
@Path("vendor/{title}")
public Response deleteVendor(@PathParam("title") String title) {
Response result = null;
if (hasVendor(title)) {
vendors.remove(title);
result = Response.ok().build();
}
return result;
}

@POST
@Produces("text/plain")
@Path("vendor/{title}")
public Response addVendor(@PathParam("title") String title) {
Response result = null;
if (! hasVendor(title)) {
vendors.add(title);
result = Response.ok().build();
}
return result;
}

@GET
@Path("product")
public String getProducts() {
return "product list is not implemented yet";
}

@GET
@Path("feature")
public String getFeatures() {
return "feature list";
}

@GET
@Path("tag")
public String getTags() {
return "tag list";
}

@GET
@Produces("text/plain")
public String getList() {
return "catalog list";
}
}


And here is result of my solution. There is a set of steps, with command curl -d "" URI I adding three vendors step by step. Three HTTP post methods are used to add 3 new vendors: SONY, PANASONIC and PHILIPS. Last HTTP GET command is used to retrieve all added vendors.


remis$ curl -X POST http://localhost:8080/restHello/resources/catalog/vendor/SONY
remis$ curl -X POST http://localhost:8080/restHello/resources/catalog/vendor/PANASONIC
remis$ curl -X POST http://localhost:8080/restHello/resources/catalog/vendor/PHILIPS
remis$ curl -X GET http://localhost:8080/restHello/resources/catalog/vendor
remis$ curl -X DELETE http://localhost:8080/restHello/resources/catalog/vendor/PANASONIC
remis$ curl -X GET http://localhost:8080/restHello/resources/catalog/vendor


How does it works? Simple, on every http request jersey does the matching between URI and path annotation, then based on the http method issued, corresponding handler method is executed. In case if method has additional parameter, which in my case is retrieved from URI path, this parameter is passed to the method and method uses parameter for business logic.

The list of curl commands listed above does the following commands line by line. Adds new vendor SONY, then another vendor PANASONIC and PHILIPS, later it prints out a full list of vendors and removes PANASONIC vendor. At the end of the list another command which outputs full list of vendors, but in this case it will enter only two vendors, because PANASONIC vendor was removed by previous command.

You can use a regular web browser in order to get an output for HTTP GET method, but it will be much harder to do HTTP POST and DELETE methods. If you know any easier and more user friendly way to issue HTTP POST and DELETE methods be very kind and enlighten my.

Maybe, I will update this blog entry later or even will write another story about Jersey, but for now it's enough. I have tried Jersey, I got my own opinion about it and next time decisions will be based on real experience.

As conclusion I would like to say, I haven't seen nothing easier that this Web Service API. It is easy to understand, clean, very productive and looks very fresh as fresh as spring. I haven't tested performance of it, but I guess hardly anything will beat it. As the last word I think I will look at other JSR-311 implementations, maybe they will be easier to start and lighter on dependencies.

Saturday, January 3, 2009

Google app engine templates and custom filters.

Last month I was messing with google app engine. That's right GAE (google app engine) and python. 

Still hardly can find any productivity gains from switching to python or as other will say "dynamic programming language" from java, but I still hope to see a "light at the end of the tunnel". With hope to experience some new, more dynamic and less restrictive thinking and software development, I'm still keep going by this new path.

Here is a new tiny challenge I got and how I'm going to deal with it. GAE uses template engine for view generation, what is greatly welcomed. Template engine and most of other code are borrowed from django, which is a high-level Python web framework. So this is a reason why I going to refer to django. Django Template engine has a nice feature which is called a template filter. Template filters are used to modify variables for display, this means that before variable value will be written to the output it can be formatted or modified in any way as it's needed.

For beginning I used this blog post as my starting point. It has a list of steps what is needed to get started. In order to get solution I like to dig a little dipper and understand what is going on. Here is a few questions what I wold like to know before I will do what I need.

# What are the differences between GAE and django template engine?
# How can I add my custom filters?
# What is a default set of filters in GAE?

Ok here are some my questions and answers to them.

What are the differences between GAE and django template engine?

First difference is a minor one. Location of Template class in django and GAE differs. Django uses django.template.Template class and GAE has it's own appengine.ext.template.Template class and it is just a simple wrapper class for the django Template class. This wrapper class handles all differences between django and app engine and makes programmers work easier.

How can I add my custom filters?

Google app engine and django uses different steps for custom filter registration. I had to create a new package, in my case I created a new package "common" and templatefilters.py file in it with content listed bellow. In case you want to look how can it be done in django here is a source of this file.

import urllib
from google.appengine.ext import webapp

def truncate(value,maxsize,stopper = '...'):
""" truncates a string to a given maximum
size and appends the stopper if needed """
stoplen = len(stopper)
if len(value) > maxsize and maxsize > stoplen:
return value[:(maxsize-stoplen)] + stopper
else:
return value[:maxsize]

def rb_quote_plus(value):
""" Replace special characters in string using
the %xx escape. Letters, digits, and the
characters '_.-' are never quoted. Also
replaces spaces by plus signs, as required
for quoting HTML form values. """

return urllib.quote_plus(value)

# get registry, we need it to register our filter later.
register = webapp.template.create_template_register()
register.filter(truncate)
register.filter(rb_quote_plus)


One last step is needed in your main.py file or any other fail with main method at the top level you have to add code listed bellow. This will instruct app engine to register new teplate filters from common.templatefilters.py file.

webapp.template.register_template_library('common.templatefilters')


Here are default list of filters in django template. In case if it's not enough and you need some more information what can be done with filters, information is provided in django documentation custom template tags and filters. This reference is for django version 1.0 and I guess something will not work because GAE uses 0.96 version as basis.

Conclusions
I was not able to find information in form I liked. This blog post is consequence of that. In general I liked how easy it's to extend and customize templates. I'm impressed how easy to get additional power in view layer without mixing business and UI logic in one place. Some features what I haven't tried yet, and I think they could not work in GAE, such as decorator @register.filter makes me excited. Once I found what and how filters can be added, I should say, this is an easiest way to add custom features to templates.