Archive

Archive for the ‘JEE’ Category

CDI, an overview – Part 2

May 31st, 2010 Nicolas Frankel 3 comments

In the previous part of CDI, we saw some injection, qualifiers and scope. Now, it’s time to browse through more advanced features.

Producers

Previous examples cannot resolve all our use-cases. Some of these include:

  • injection of random values
  • injection of context-dependent value
  • in general, places where the injection process cannot be narrowed down to a simple new()

These hint at a very well-known pattern, the factory. Factories are implemented in JSR-299 as producers.

Let’s take a simple example, the injection of a connection from a data source. The code that gets the connection either creates it with a direct connection to the database or retrieves it from a data source pool. In the latest case, the following code would fit:

public @interface FromDataSource {}

public class ConnectionProducer {

  @Produces @FromDataSource
  public Connection getConnection() throws Exception {

    Context ctx = new InitialContext();

    // Read the data source name from web.xml
    String name = ...

    DataSource ds = (DataSource) ctx.lookup(name);

    return ds.getConnection();
  }
}

Interceptors

With Java EE 6, you can harness the power of AOP without AOP. Like in the previous example, using interceptors is very straightforward. There are 3 steps. Let’s implement a simple timer, for benchmarking purposes.

The first step is the declaration of the interceptor. To do so, just use the @InterceptorBinding:

@InterceptorBinding
@Retention(RUNTIME)
@Target({METHOD, TYPE})
public @interface Benchmarkable{}

The second step is the interceptor implementation. It uses the @Interceptor annotation, coupled with the previously defined one:

@Benchmarkable @Interceptor</pre>
public class BenchmarkInterceptor {

  @AroundInvoke
  public Object logPerformance(InvocationContext ic) throws Exception {

    long start = System.currentTimeMillis();

    Object value = ic.proceed();

    System.out.println(System.currentTimeMillis() - start);

    return value;
  }
}

Notice:

  • the method annotated with @AroundInvoke returns an Object
  • it uses a parameter of type InvocationContext

The last step is to declare such interceptors in WEB-INF/beans.xml because interceptors are deactivated by default.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
  <interceptors>
    <class>ch.frankel.blog.weld.BenchmarkInterceptor</class>
  </interceptors>
</beans>

The beans.xml also tells the container about how to order the interceptors in case they is more than one.

There are two other interceptor types, @PostConstruct and @AroundTimeout (for EJB).

Decorators

Decorators, guess what, implement the Decorator design pattern. They are very similar to interceptors with two interesting differences:

  • a decorator must implement the interface it is decorating (and yet can be abstract, so it does not have to implement the methods)
  • a decorator can have a reference to the object it decorates. It is done through injection

Like interceptors, they must be referenced in the beans.xml file in order to be activated. Let’s take a simple example and create an interface which contract is to return an HTML representation of an object:

public interface Htmlable {

 String toHtml();
}

Now I need a date class that knows its HTML representation. I know the design is quite bad but bear with me.

public class HtmlDate extends Date implements Htmlable {

  public String toHtml() {

    return toString();
  }
}

If I want a decorator that puts the HTML inside <strong> tags, here’s the way:

@Decorator
public class StrongDecorator implements Htmlable {

  @Inject @Delegate @Any
  private Htmlable html;

  public String toHtml() {

    return "<strong>" + html.toHtml() + "</strong>";
  }
}

Observers

CDI also implements the Observer design pattern, thus at last enabling simple event-driven development paradigm on the Java EE platform. The basis for it is the event type. An event type is a simple POJO.

The Observer is also a POJO: in order for a method of the Observer to be called when an event is fired, just add a parameter of the right event type and annotate it with @Observes:

public class EventObserverService {

  public void afterPostEvent(@Observes PostEvent event) {

    ... // Do what must be done
  }
}

On the other side, the event producer should have an attribute of type javax.enterprise.Event parameterized with the same event type. In order to fire the event, call event.fireEvent() with an event instance:

public class WeldServlet extends HttpServlet {

  @Inject
  private Event<PostEvent> event;

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    event.fire(new PostEvent());
  }
}

Now, when sending a POST request to the servlet, the afterPostEvent() method of the EventObserverService will be called.

Alternatives

In the previous article, I adressed the mock service with calling the setter and passing a newly created instance “by hand”. This is all fine and well in a unit testing case, but I also want to manage integration testing. The situation is thus the following:

  • there are two implementations of the same interface on the classpath
  • you can’t change the servlet code (for example, add a qualifier to the service attribute)

Given the deterministic nature of CDI, you should basically be toast. In fact, nothing could be further from the truth. Just use the @Alternative annotation and CDI will conveniently ignore the annotated class.

@Report(MAIL) @Alternative
public class MockMailReportServiceImpl implements ReportService {
  ...
 }

What’s the point then to create it in the first place? Remember the unused-till-then beans.xml from above. It will come to our help, since it accepts <alternative> tags. These tags activate the alternatives.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
  <alternatives>
    <class>ch.frankel.blog.weld.service.MockMailReportServiceImpl</class>
  </alternatives>
</beans>

As such, you could have two beans.xml:

  • a basically empty standard context
  • and another integration testing context full of alternatives

Platform

This article was written with GlassFish v3, which uses Weld v1.0.1, as a platform. Weld is CDI reference implementation, and also a part of the Seam framework.

I had no problems using the platform overall, yet, I couldn’t make alternatives, interceptors and decorators work. Strangely enough, all three must be configured in the WEB-INF/beans.xml. I do not know if I did something wrong or if there’s a bug in the current implementation though.

Conclusion

This 2-parts article only brushes at the surface of CDI. Nevertheless, IMHO, it looks very promising and I wish it much success.

To go further:

  • CDI, an overview – part 1
  • Commons annotations (JSR-250) page: Commons annotations has annotation for DI in Java (@Resource)
  • CDI (JSR-299) page: amazingly enough, CDI is about DI in Java EE
  • Weld’s documentation: Weld is CDI JBoss implementation and also the reference implementation
  • Article on the merits of JSR-299 compared to the merits of JSR-330
Categories: JEE Tags:

CDI, an overview – Part 1

May 22nd, 2010 Nicolas Frankel 1 comment

Introduction

I may be a Spring fanboy but I’m also convinced a technology should embrace standards. Although Spring is now a de facto standard, it is in competition with other products, like Google Guice for example. It makes my work as an architect harder since my craft is to devise the most perennial solutions: standards are my allies in achieving this goal.

CDI, formerly known as JSR 299, is an attempt at describing a true standard on Dependency Injection. What makes CDI appealing at first glance is that both SpringSource and Google took a seat in the specifications team. CDI is a part of the Java EE 6 stack, meaning an application running in a Java EE 6 compatible container can leverage CDI out-of-the-box.

Thus, for a Maven application, all that is required is to add the following dependency:

<dependency>
  <groupId>javax.enterprise</groupId>
  <artifactId>cdi-api</artifactId>
  <version>1.0-SP1</version>
  <scope>provided</scope>
</dependency>

The basics

How is it done? Let’s take a simple example. I still want to use a lighweight service layer: I just need a reference to such a service in my servlet. In order to do that, just add a reference to the service as an attribute and annotate it with @Inject:

public class WeldServlet extends HttpServlet {

  @Inject private HelloService helloService;

  ...
}

Note for Guice users: notice this is the same annotation, only in a standard package (javax.enterprise).

That’s all! No fancy XML configuration, no JNDI resource to use, no nothing. The only thing to do is to follow what I call the Highlander rule:

There can be only one.

This rule enforces that there must be one and only one class on the classpath that extends HelloService, thus fulfilling the interface contract. This is common sense: the injection must be deterministic and you can’t if you have more than one implementation to choose from.

Activation

In truth, if you just use the @Inject annotation, you probably will be faced by a NullPointerException. For CDI to activate, you’ll need to have a XML configuration file named beans.xml under WEB-INF for web applications or META-INF for jars. This file can be empty but is mandatory in order for CDI to bootstrap.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

Qualifiers

Yet, such condition is not met most of the time since you’ll probably have at least another mock implementation for your unit tests. A concept is missing somewhere: it is the qualifier. Qualifiers add a quality to injection so that the Highlander rule is enforced between all classes that meet all the injection qualifiers. Thus, one can add a distinguishing qualifier to the mock service to resolve our quandary. Let’s design such a qualifier:

  • to be considered a qualifier, it uses the @Qualifier annotation
  • since injection is done at runtime, the retention policy must be runtime
  • target will be type, since it’s the class itself that will be annotated

The result is the following:

@Qualifier
@Retention(RUNTIME)
@Target( { TYPE })
public @interface Mock {}

Just annotate your mock service with @Mock and presto, the injection will succeed again. We haven’t seen how to inject the mocked service, but please bear with me, it will be adressed later.

Setter injection

In fact, this situation should not really happen (at least if you use Maven), since your standard classpath and your testing classpath should be different. Moreover, your unit testing should IMHO not use injection. This would slightly change my servlet to be used both in standard context and unit testing context: I will need to be able to inject in the former case and to set manually in the latter. This is not a problem, since CDI also accepts setter injection like in the following snippet:

public class WeldServlet extends HttpServlet {

  private HelloService helloService;

  @Inject
  public void setHelloService(HelloService helloService) {

    this.helloService = helloService;
  }
  ...
}

More qualifiers

As we saw, the qualifier use-case from above was not a good example. A much better one would be the need for a servlet to report an error. There are much ways of reporting this: mail, log, SMS, etc. The service used to report would be dependent of the servlet, meaning all the services should be available on the classpath. Now, as we have seen previously with @Mock, each service would be annotated with @Mail, @Log, @SMS, etc. What we did not see is how to inject the right service. Nothing could be easier, just tell CDI that which service you need by providing the needed qualifier:

public class WeldServlet extends HttpServlet {

  @Inject @Mail private ReportService reportService;

  ...
}

When you do not define any qualifier, CDI will use one for you under the cover, @Default. That’s why just annotating the mock service with @Mock succeeded: the real service was annotated implicitly with @Default and that was enough to fulfill the Higlander rule.

Qualifiers with attributes

Using the previous method will likely lead to an exponential proliferation of qualifiers that contradict Java EE 6 goals of readibility and maintainability. CDI will still let you reach them goals with annotation members. Now, the classes are:

public enum ReportType {

  MAIL, SMS, LOG;    // Adding one more type here is easy
}

@Qualifier
@Retention(RUNTIME)
@Target( { TYPE, FIELD })
public @interface Report {
    ReportType value();
}

@Report(MAIL)
public class MailReportServiceImpl implements ReportService {...}

public class WeldServlet extends HttpServlet {

  @Inject @Report(MAIL)
  private ReportService reportService;
  ...
}

Creating another reporting service consists of creating the service implementation itself and adding a value to the enumeration.

Singletons

Traditionally, services are stateless and, as such, have little interest in being instantiated more than once: it’s a good practice to make them singletons. Frameworks such as Spring make container-managed beans singletons as a default. Singletons creation is a feature of CDI but beware that singletons should be explicitly marked as such:

@Singleton
public class HelloServiceImpl implements HelloService {
  ...
}

Scoped beans

Singletons are only a particular case of a scope. In Java EE, scopes are well-defined regarding web applications: application, session, request and page. CDI does not manage page scope and adds a conversation scope that is tied to JSF. Scope usage in CDI is similar as Spring: injected bean will be tied to the defined scope and its visibility restricted to that scope.

Information relative to settings and preferences could well take place in a session-scoped bean for instance. Just add the right scope annotation to this bean:

@SessionScoped
public class UserSettings implements Serializable {

  private static final long serialVersionUID = 1L;
  ...
}

At this point, you should probably able to adress 80% of your needs. The next article will tackle advanced subjects like producers and alternatives.

To go further:

  • Commons annotations (JSR-250) page: Commons annotations has annotation for DI in Java (@Resource)
  • CDI (JSR-299) page: amazingly enough, CDI is about DI in Java EE
  • Weld’s documentation: Weld is CDI JBoss implementation and also the reference implementation
  • Article on the merits of JSR-299 compared to the merits of JSR-330
Categories: JEE Tags:

Decrease your pages load time, one year later

May 17th, 2010 Nicolas Frankel No comments

More than one year ago, I blogged about pages load time and Jawr. Since then, either my projects were intranet applications where load time was not an issue or we had no say in the tools used. So, I had no possibility to use any of the tools I found then. Now, I’m soon to be faced by an application that will be used by people outside our network and I definitely want the application to be as responsive as possible. Armed with my previous Yahoo best practices, I hunted on the web for tools that could help me enforce them.

One rule I hold in high esteem is: minimize the number of HTTP requests. I think this rule has the most impact since browsers only send at most 2 HTTP requests at a time. Let’s take a classical example. Buttons play a big part in many applications and most of the time, you put an icon on them in order to tie them to the action in the user’s mind. This is simply done like so:

<button><img src="path/to/my/image" />Label</button>

This means that any screen that display more than one button type has the potential to be slow. One way to dramatically decrease the number of requests is to aggregate all the images in one and use CSS background images. The latter is available since the first version of CSS, just specify the background-image attribute to display the image behind an element . This usage is called CSS Sprites. The code now looks like:

<button class="update">Label</button>
button.update {
  background-image: url('path/to/my/image');
  background-repeat: no-repeat;
}

The astute reader will have remarked that the previous code has the same effect as the <img> in the <button>. The real usage is to use only the portion of the master image that we want, somehting akin to that:

button.update {
  background: transparent url('path/to/my/aggregate') -50px -50px no-repeat;
}

To aggregate the master image requires the right image tool. To compute the portion we want for each button is a pain in the butt (to speak politely).

Luckily, my old friend Jawr has the right feature to help me. Since version 3.2, it includes SmartSprites, a product that just does all aggregating and computing for me. How does that work? Just by putting some comments in your CSS:

  • to declare how the master(s) image(s) will be constructed
  • to tell which sprite will take part in which master image
/** sprite: master-sprite-gif; sprite-image: url('../img/master-sprite.gif'); sprite-layout: vertical */

button.one {
  background-image: url('../img/certificate_preferences.gif'); /** sprite-ref: master-sprite-gif; */
}

button.two {
  background-image: url('../img/inbox_into.gif'); /** sprite-ref: master-sprite-gif; */
}

button.three {
  background-image: url('../img/mail_forward.gif'); /** sprite-ref: master-sprite-gif; */
}

The previous CSS is an example by which all three GIFs will be found at runtime under ../img/master-sprite.gif. If you look at the generated CSS, it will have the following look:

button.one{background-image:url('../cb3648025844/img/master-sprite.gif');background-position:left -0px;}
button.two{background-image:url('../cb3648025844/img/master-sprite.gif');background-position:left -48px;}
button.three{background-image:url('../cb3648025844/img/master-sprite.gif');background-position:left -96px;}

Of course, the real generated CSS will have been concatenated and minified (see below).

Note: I’m not a GIF expert but I suspect original GIFs should have similar color tables, otherwise, the aggregated GIF will look really strange.

However, Jawr also provides some very interesting features, both old and new:

  • minification, for both CSS and JavaScript. You can also choose the minifying engine (embedded, JSMin or YUI Compressor). The latter is even able to obfuscate your source, thus even making your JS even lighter in the process
  • license inclusion, so that even minified sources can display their license
  • runtime GZip compression if the client browser supports it
  • HTTP header management so that requests for the same resources (beside the first) will be answered by a HTTP 304 – Not Modified code, thus avoiding unnecessary network traffic
  • i18n management in order to use Java standard properties files for internationalized messages in your JavaScript
  • JavaScript to use Jawr without taglibs in plain HTML pages (though it is not recommended since it adds a script to the page, thus another HTTP request)
  • possibility of extension, with new pre- and post- processors
  • ability to switch between development mode (no modification for resources) and production (virtual resources served by Jawr)
  • bundle preprocessing, so that the processing is not done at startup but instead at build time: this can be done either by calling an Ant task or by configuring a Maven plugin
  • for truly engaged application server administrators, support for JMX

During the last year, it seems Jawr has gained some nice upgrades. I don’t know how many people truly use it but I think it deserves some interest when you need to optimize performance on the page loading time front.

You can download the sources for this article in Eclipse/Maven format here.

To go further:

Categories: JEE Tags:

Chicken and egg problem with Spring and Vaadin

May 3rd, 2010 Nicolas Frankel 3 comments

The more I dive into Vaadin, the more I love it: isolation from dirty plumbing, rich components, integration with portlets, Vaadin has it all.

Anyway, the more you explore a technology, the bigger the chances you fall down the proverbial rabbit hole. I found one just yesterday and came up with a solution. The problem is the following: in Vaadin, application objects are tied to the session. Since I’m a Spring fanboy, it does make sense to use Spring to wire all my dependencies. As such, I scoped all application-related beans (application, windows, buttons, resources, …) with session like so:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/aop

    http://www.springframework.org/schema/aop/spring-aop.xsd">

  <context:annotation-config />

  <bean id="application" scope="session">
  <aop:scoped-proxy />
...
</beans>

This works nicely, until you happen to use DI to wire further. By wire further, I mean wiring windows into application, button into windows and then resources (icons) into buttons. It is the last  step that cause a circular dependency. Icon resources are implemented in Vaadin by com.vaadin.terminal.ClassResource. This class has two constructors that both needs an application instance.

The dependency cycle is thus: application -> window -> button -> resource -> application. Spring don’t like it and protests energically to it by throwing an exception which is labeled like so Requested bean is currently in creation: Is there an unresolvable circular reference?

. I think, in this case, that the design of the ClassResource is not adapted. That’s whyI designed a class aligned with Spring deferred instantiation: since the application is session-scoped, Spring uses a proxy that defers instantation from application start (Spring normal behaviour) to session use. The point is to implement the ApplicationResource interface, which needs an interface, but to set application only when needed:

public class DeferredClassResource implements ApplicationResource {

  private static final long serialVersionUID = 1L;
  private int bufferSize = 0;
  private long cacheTime = DEFAULT_CACHETIME;
  private Class<?> associatedClass;
  private final String resourceName;
  private Application application;

  public DeferredClassResource(String resourceName) {

    if (resourceName == null) {

      throw new IllegalArgumentException("Resource name cannot be null");
    }

    this.resourceName = resourceName;
  }

  public DeferredClassResource(Class<?> associatedClass, String resourceName) {

    this(resourceName);

    if (associatedClass == null) {

      throw new IllegalArgumentException("Associated class cannot be null");
    }

    this.associatedClass = associatedClass;
  }

... // standard getters

  @Override
  public String getFilename() {

    int index = 0;

    int next = 0;

    while ((next = resourceName.indexOf('/', index)) > 0
      && next + 1 < resourceName.length()) {
      index = next + 1;
    }

    return resourceName.substring(index);
  }

  @Override
  public DownloadStream getStream() {

    final DownloadStream ds = new DownloadStream(associatedClass
      .getResourceAsStream(resourceName), getMIMEType(),
      getFilename());

    ds.setBufferSize(getBufferSize());

    ds.setCacheTime(cacheTime);

    return ds;
  }

  @Override
  public String getMIMEType() {

    return FileTypeResolver.getMIMEType(resourceName);
  }

  public void setApplication(Application application) {

    if (this.application == application) {

      return;
    }

    if (this.application != null) {

      throw new IllegalStateException("Application is already set for this resource");
    }

    this.application = application;

    associatedClass = application.getClass();

    application.addResource(this);
  }
}

DeferredClassResource is just a copy of ClassResource, but with adaptations that let the application be set later, not only in constructors. My problem is solved, I just need to let application know my resources so it can call setApplication(this) in a @PostConstruct annotated method.

Categories: JEE Tags: ,

Vaadin Spring integration

April 6th, 2010 Nicolas Frankel 6 comments

I lately became interested in Vaadin, another web framework but where everything is done on the server side: no need for developers to learn HTML, CSS nor JavaScript. Since Vaadin adress my remarks about web applications being to expensive because of a constant need of well-rounded developers, I dug a little deeper: it will probably be the subject of another post.

Anyway, i became a little disappointed when I wanted to use my favourite Dependency Injection framework, namely Spring, in Vaadin. After a little Google research, I found the Vaadin Wiki and more precisely the page talking about Vaadin Spring Integration. It exposes two ways to integrate Spring in Vaadin.

The first one uses the Helper “pattern”, a class with static method that has access to the Spring application context. IMHO, those Helper classes should be forgotten now we have DI since they completely defeat its purpose. If you need to explicitly call the Helper static method in order to get the bean, where’s the Inversion of Control?

The second solution uses Spring proprietary annotation @Autowired in order to use DI. Since IoC is all about decoupling, I’m vehemently opposed to coupling my code to the Spring framework.

Since neither option seemed viable to me, let me present you the one I imagined: it is very simple and consists of subclassing the Vaadin’s AbstractApplicationServlet and using it instead of the classical ApplicationServlet.

public class SpringVaadinServlet extends AbstractApplicationServlet {

  /** Class serial version unique identifier. */
  private static final long serialVersionUID = 1L;

  private Class clazz;

  @Override
  public void init(ServletConfig config) throws ServletException {

    super.init(config);

    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(
      config.getServletContext());

    Application application = (Application) wac.getBean("application", Application.class);

    clazz = application.getClass();
 }

  /**
  * Gets the application from the Spring context.
  *
  * @return The Spring bean named 'application'
  */
  @Override
  protected Application getNewApplication(HttpServletRequest request)
    throws ServletException {

    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(
      request.getSession().getServletContext());

    return (Application) wac.getBean("application", Application.class);
  }

  /**
  * @see com.vaadin.terminal.gwt.server.AbstractApplicationServlet#getApplicationClass()
  */
  @Override
  protected Class getApplicationClass()
  throws ClassNotFoundException {

    return clazz;
  }
}

This solution is concise and elegant (according to me). Its only drawback is that it couples the servlet to Spring. But a class-localized coupling is of no consequesence and perfectly acceptable. Morevoer, this lets you use Spring autowiring mechanism, JSR 250 autowiring or plain old XML explicit wiring.

Categories: JEE Tags: ,

Clustering Tomcat

February 24th, 2010 Nicolas Frankel No comments

In this article, I will show you how to use Apache/Tomcat in order to set up a load balancer. I know this has been done a zillion time before, but I will use this setup in my next article (teaser, teaser) so at least I will have it documented somewhere.

Apache Tomcat is the reference JSP/container since its inception. Despite a lack of full JEE support, it certainly has its appeal. The reasons behind using a full-featured commercial JEE application server are not always technical ones. With lightweight frameworks such as Spring being mainstream, it is not unusual to think using Tomcat in a production environment. Some companies did it even before that.

When thinking production, one usually think reliability and scalability. Luckily, both can be attained with Apache/Tomcat through the set up of a load-balancing cluster. Reliability is thus addressed so that if a Tomcat fails, following requests can be directed to a working Tomcat. Requests are dispatched to each Tomcat according to a predefined strategy. If the need be, more Tomcat can be added at will in order to scale.

In the following example, I will set up the simplest clustering topology possible: an Apache front-end that balances 2 Tomcat instance on the same physical machine.

Set up Apache

The first step is to configure Apache to forward your requests to Tomcat. There are basically 2 options in order to do this (I ruled out the pre-shipped load-balancer webapp):

  • use mod_jk, the classic Apache/Tomcat module
  • use mod_proxy, another Apache module

I’m not a system engineer, so I can’t decide on facts whether to use one or the other: I will use mod_jk since I’ve already used it before.

  • Download the mod_jk that is adapted to your Apache and Tomcat versions
  • Put it in the ‘modules’ folder of your Apache installation
  • Update your httpd.conf configuration to load it with Apache
    LoadModule jk_module modules/mod_jk-1.2.28-httpd-2.2.3.so
  • Configure Apache. Put these directive in the httpd.conf:
    JkWorkersFile	conf/worker.properties
    JkShmFile	logs/mod_jk.shm
    JkLogLevel	info
    JkLogFile logs/mod_jk.log
    JkMount		/servlets-examples/* lb

This configuration example is minimal but needs some comments:

Parameter Description
JkWorkersFile Where to look for the module configuration file (see below)
JkShmFile Where to put the shared memory file
JkLogLevel Module log level (debug/error/info)
JkLogFile Log file location. It is the default but declaring it avoid the Apache warning
JkMount Which url pattern will be forwarded to which worker

Since mod_jk can be used in non-clustered setups, there could be any JkMount, each forwarding to its own worker (see below). In our case, it means any request beginning with /servlets-examples/ (the trailing slash is needed) will be forwarded to the ‘lb’ worker .

Configure the workers

Workers are destination routes as viewed by Apache. They’re are referenced by an unique label in the httpd.conf and parameteirzed under the same label in the worker.properties file.
My workers.properties is the following:

worker.list=lb

worker.worker1.port=8010
worker.worker1.host=localhost
worker.worker1.type=ajp13

worker.worker2.port=8011
worker.worker2.host=localhost
worker.worker2.type=ajp13

worker.lb.type=lb
worker.lb.balance_workers=worker1,worker2

I define 3 workers in this file: lb, worker1 and worker2. The ‘lb’ worker is the load-balancing worker: it is virtual and it balances the latter two. Both are configured to point to a real Tomcat instance.

Now, with the Apache configuration in mind, we see that requests beginning with /servlets-examples/ will be managed by the load balancer worker which will in turn forward to a random worker.

Note: one can also put weight on workers hosted by more powerful machines so that these are more heavily loaded than less powerful ones. In our case, both are hosted on the same machine so it has no importance whatsoever.

Configure the Tomcat instances

The last step consist of the configuration of Tomcat instances. In order to do so, I shamelessly copied entire Tomcat installations (I’m on Windows). While editing the server.xml of the Tomcat instances, three points are worth mentioning:

  • The Engine tag has a jvmRoute attribute. It’s value should be the same as the worker’s name used in both httpd.conf and worker.properties. Otherwise, sessions will be recreated for each request
  • Look out for duplicated port numbers if all Tomcat instances are on the same machine. For example, use an incremental rule to configure every stream on a different port
  • Be sure that the tcpListenPort attribute of the Receiver is unique across all Tomcat instances

Use it!

With the previous set up, one can now start both Tomcat and Apache, then browse to the servlet-examples webapp, and more precisely to the Session page. Look there for Tomcat 5.5 and there for Tomcat 6. The servlet-example page page displays the associated session ID:

ID de Session: 324DAD12976045D197435033A67C025D.worker2
Crée le: Tue Feb 23 23:15:13 CET 2010
Dernier accès: Tue Feb 23 23:31:47 CET 2010

Notice that on my Tomcat instance, the worker’s name is part of the session ID.

If everything went fine, two interesting things should take place: first, when refreshing the page, the session ID should not change because of the sticky session (enabled by default). Morevoer, if I shutdown the Tomcat instance associated with the worker (the second in my case), and if I try to refresh the page, I still can access my application, but under a new session.

Thus, I lose all the information I stored under my session! In my following article, I will study how on can try to remedy to this.

To go further:

Categories: JEE Tags: ,

Context root tweaking

February 1st, 2010 Nicolas Frankel No comments

JEE never ceases to amaze me. Even when I think I’m on top and I know all there’s to know about webapps, I’m in for a surprise. Good news is, whatever you think you know about a subject, there’s still room for one more fact. Bad news is, I’m deeply disturbed by what I learned.

Fact is: web applications context root can contain the / characte, meaning an URL such as http://localhost/multipart/context can refer to the root of the multipart/context webapp as well as to the context servlet mapping of the http://localhost/multipart webapp. When I was told that, my first reaction was disbelief. I immediately hurried to run a few tests on the JOnAS and JBoss application servers and it confirmed that was entirely possible.

In fact, if you look at the application.xml XML Schema, you see that the context-root is of a type that extends string (with an id) :

This means the context root can effectively contains anything, including slashes, backslashes and what have you.

The J2EE 1.4 specifications does not enforce additional constraints (p 125) :

Each web module must be given a distinct and non-overlapping name for its context root. [...] See the servlet specification for detailed requirements of context root naming.

I did not see additional requirements in the Servlet 1.4 specifications for the context root.

Tomcat even takes this tweak into account when creating Context with individual XML files. It calls it “multi-level context paths” :

In individual files (with a “.xml” extension) in the $CATALINA_HOME/conf/[enginename]/[hostname]/ directory. The name of the file (less the .xml) extension will be used as the context path. Multi-level context paths may be defined using #, e.g. foo#bar.xml for a context path of /foo/bar.

So, in order to deploy the context.war under the multipart/context root, you’ll have to name the context XML file multipart#context.xml.

The content of the file is the following:

<?xml version='1.0' encoding='utf-8'?>
<Context docBase="${catalina.home}/context.war" />
<!-- this means the context.war should be available at the root of Tomcat -->

In the tests I’ve made, if the multi-level context path shadows a classic context-root with a servlet mapping, the former takes precedence. I do not advise using this since the case is not specified in the specification, it could be handled differently from product to product.

OK, now we’ve established these facts, what is the point in knowing this, aside from setting you as the übergeek in a JEE geek convention? Since http://localhost/multipart/context and http://localhost/multipart are clearly separated web applications, they do not even share context.

In my case, that was the solution for a simple use-case. Imagine monitoring web applications: you know the URL you have to monitor. Now a product, developped in-house for diagnostics purpose, is deployed side-by-side with each webapp in webapp form. It would be very nice if you could reach the diagnostics webapp without looking at the documentation to know its URL. Let’s say it is the business webapp’s URL appended with /diag.

So, if the main webapp’s URL is http://myserver.com/mywebapp and the person in charge of monitoring knows about it, he knows he has to access http://myserver.com/mywebapp/diag and he gets what he wants! On the development side, it means both webapps are different products, are developed by different teams and have different lifecycles.

Categories: JEE Tags: , , ,

HTML UI over a REST backend

December 26th, 2009 Nicolas Frankel No comments

In this article, I will show you that forms sent by browsers to a server can only use GET and POST HTTP methods and which workaround to apply in order to still use a REST backend.

REST web-services are becoming more and more common in today’s landscape. We can only imagine the reasons, but I guess that SOAP’s structured approach is only useful in the most complex use-cases and is overkill the rest of the time. On the contrary, REST is quite easy to setup.

In the Java world, REST has its own specification, JAX-RS with JSR 311, and is supported by all major frameworks :

In my humble opinion, it is not inconceivable that, given the adoption of REST, the next step would be the development of REST backends accessible by standard clients and browsers alike, in order to factorize code and thus decrease costs.

Traditionallly, making a resource accessible on the web is realized through a hyperlink. Hyperlinks use the GET method. Likewise, REST is based on using the HTTP methods where each has an associated verb:

HTTP method Verb
POST Create
GET Read
PUT Update
DELETE Delete

Unluckily, the real world comes into play. In order for this to work, the HTML 4 specification is a big obstacle in the way:

The FORM element [...]

Method: this attribute specifies which HTTP method will be used to submit the form data set. Possible (case-insensitive) values are “get” (the default) and “post”.

The implication is that HTML 4 compliant browsers will only let you read and create but not update nor delete. For example, the versions of Firefox and Internet Explorer I used, respectively 3.5.6 and 6.0 (!) use POST for POST and GET for everything else. That’s a real case against using REST. There are some workarounds, though.

The first one is not to use the HTTP method for the verb but to put it in the URL. Thus

  • to access a customer, one would use http://frankel.ch/get/customer/1
  • and to remove one, http://frankel.ch/delete/customer/1

This clearly violates REST’s principle of using the HTTP method for the verb but this works for simple cases.

The second workaround is a bit more complex but it has two big advantages: it conforms to REST principles and it is usable with most modern-days browsers.

The trick is to use a neat little object created by Microsoft but now implemented everywhere, the XMLHttpRequest object. Yes, this is the object at the foundation of Ajax but is is also the solution of our problem. XMLHttpRequest‘s open() method takes two parameters, the first being the HTTP method to use for accessing the url (which is the second parameter). Now you can pass the verb you want, like the following example.

xmlhttp = new XMLHttpRequest();
xmlhttp.open('DELETE', 'http://frankel.ch/customer/1');
xmlhttp.send(null);

Morevover, you can not only use the 4 CRUD verbs but also any verb you want.

This solution has two main limitations:

  • it requires modern-day browsers since the XMLHttpRequest object is not available in more ancient ones
  • it requires JavaScript, so you need to enable it on client browsers and you need to manage browser compatibilities. For example, the above script with Firefox 3.5 but not IE 6 (and to be blunt, I’m not really bothered by it)

It seems this hack will be rendered useless by the HTML 5 specifications which declares (in their draft state) that all 4 basic CRUD verbs will have to be supported.

You can find an example for this article here. Tu use, navigate to http://localhost:8080/httpmethods/ if deployed in Eclipse. It was tested on Firefox 3.5 and works on it flawlessly. On the contrary, it doesn’t work for IE 8 since my script is not crafted to be cross-browsers. For Tomcat users, you have to add JSTL capabilities to Tomcat (meaning adding standard.jar and jstl.jar in the commons/lib directory).

To go further :

Categories: JEE Tags: ,

Simple templating solution with SiteMesh

October 24th, 2009 Nicolas Frankel No comments

In this article, I will show you how to use SiteMesh in your JEE web sites in order to bring a sense of unity to them.

When talking about templating, the method everyone uses at first is to use <@include> tags throughout the JSP pages. This course of action is flawed from the start since all JSPs are responsible to call includes and thus, there’s no real enforcement to use the correct ones.

The most used method is Apache Tiles. To be frank, I didn’t have a look at Tiles since it went from Struts to Apache. Struts Tiles were meant to be used in conjunction with Struts. Apache Tiles seems to support many more technologies (JSP, Velocity, Freemarker, …) but I didn’t see any JSF support out-of-the-box though there seem to exist plenty of articles that tackle the subject and its problems.

When I used Struts Tiles, I found it was a very powerful framework, yet many junior developers had some problems with it. In most projects I worked on, a senior developer assembled tiles while junior ones created the pages themselves. I found Tiles very configurable but this came at the cost of complexity. In most cases, I didn’t need all the functionalities of Tiles: I only wanted to have a header, a footer and a menu nicely crafted around my main page.

When investigating AppFuse, I stumbled upon a nice templating tool that just does that: SiteMesh. SiteMesh is technology-neutral, meaning it can be used with whatever view framework is used, JSF included. It is based on the very simple concept of servlet filters. An XML file forms the basis of the template’s configuration. This configuration holds what pages are decorated and with what templates.

The templating mechanism is made so each page is seen as complete either when viewed standalone or when viewed through the filter. For example, when you write the page normally, you provide the title’s text (what is displayed in most browser’s title bar). If you are using SiteMesh, nothing changes. At runtime, the servlet filter reads the title’s text value from the source HTML (which can come from a dynamic source) and outputs the decorated page with the same title’s text value, although the page design will be different.

The following example shows how it is achieved in the template:

<html>
  <head>...</head>
  <body>
    <div id="top">Header</div>
    <h1><decorator:getProperty property="title" /></h1>
    ...
  </body>
<html>

Nothing could be simpler. Yet, the solution decouples the standalone view from the decorated view. The former has no need to know about the latter!

A common use-case is to put common CSS and JavaScript declarations in the template.

Moreover, the choice of which decorator(s) to use can come from different strategies:

  • configuration files,
  • cookies,
  • browser language,
  • display agent (browser or printer),
  • etc.

The simplicity and the robustness of the solution is what will make me deeply think about using it if I have simple templating needs. On the opposite site, if you have complex templating requirements, SiteMesh won’t be enough.

You will find a very simple project here in Maven/Eclipse format.

To go further:

Tomcat’s Valve, an alternative to Filter

September 11th, 2009 Nicolas Frankel 1 comment

Tomcat's logoIn this article, I will show you how to replace filters declared in web.xml with unobtrusive mechanism in Tomcat.

I’m a big friend of Apache Tomcat. In many cases, even enterprise applications can run with a simple JSP – servlet container and Tomcat has passed through all the evolutions of the standards with flying colors. This is not to say that other containers are bad (Jetty for instance, is very good at being embedded), only that I know enough about Tomcat to know it’s stable and bugfixes are regularly available: a condition for using a product in the enterprise. I am always amazed at why so few Tomcat run in production, compared to big fat application servers. Is it because it is too simple? Yet, it can be very powerful, as I will show with the Valve concept.

Designers and architects know about the Intercepting Filter pattern: these filters intercept requests and responses and can be chained. The implementation of this pattern is the javax.servlet.Filter interface available since Servlet v2.3. Let’s take an example: suppose you have to get additional informations in a database (suche as name, ect.) when authentifying with a classical JAAS login. Since your application is not responsible for performing the check, it is impossible to get these infos at the right time. It is very simple when using a filter.

First problem: you do not want your developers to write the database access code with each new application. You create the filter once, put it in the JAR and tell your teams to use this filter in their web.xml once and for all. Now your enterprise evolve and put information relative to people in a LDAP server (not really a bad idea). For newly created applications, you create another filter that access LDAP and use it from now on.

Second problem: what do you do with your applications that use the legacy filter?

  1. You can run a batch that update the web.xml throughout your entire filesystem. Well, for me, that’s too risky… I wouldn’t want to get my production down in one big shot! And if the webapps run in non-exploded mode, it is impossible.
  2. You can still use the database and create a batch that synchronize data from the LDAP server to the database. Not risky at all. And 20 years latter, your information system is a big plate of spaghetti because information is duplicated everywhere. Not very urban.
  3. Finally, you can rely on our Tomcat friend from the beginning, remove the filter from applications at all and put a specific filter called a valve in Tomcat itself. A big disadvantage is that you now are coupled to Tomcat. This is not as bad as it sounds since the code is so isolated it can safely be migrated to another application server API real quick.

I suppose mad dogs would go with option 1 and managers that change every 2 years would go with option 2. Of course, from my clearly subjective presentation of the solutions, you can guess i would go with option 3.

“Valve is a request processing component associated with a particular Container. A series of Valves are generally associated with each other into a Pipeline.”

From Tomcat’s Javadoc

A valve is designed with a very generic interface org.apache.catalina.Valve. Tomcat also provides an abstract class org.apache.catalina.valves.ValveBase that can be safely extended. The main method of the latter is the invoke() method where you can access both request and response. Don’t forget to call the next valve in it or, like in filters, the chaining will stop.

From this point, you are free to do as you choose: access the LDAP server, put a cookie, log performances, etc.

You can find the Maven sources for 2 very simple examples here.

To go further:

Please note that the links point to the latest v6.0 version but the concepts exposed above are available in v5.5 and v4.1.

Categories: JEE Tags: , ,