Archive

Archive for the ‘Java’ Category

Managing POM versions

July 26th, 2010 Nicolas Frankel No comments

This article won’t be long but can be a lifesaver. If you use Maven, how many times did you need to manually update POM versions in an entire modules hierarchy? For me, the answer is: “too many”.

When you project grows to include many Maven modules, releasing a new version can be a nightmare. Sure, you have the maven-release-plugin. It does many things under the cover but in some cases, I saw it fail. What do you do then? You manually change your POM version in your modules hierarchy:

  • the version of the module’s POM
  • the version of the parent’s POM

It’s not only a boring taks, it’s also an error-prone one. Imagine my surprise when I found the maven-version-plugin and its little jewel of a command line:

mvn versions:set -DnewVersion=1.0.1-SNAPSHOT

And presto, the plugin does it all for you, entering each module and changing the previous informations:

[INFO] [versions:set]
[INFO] Searching for local aggregator root...
[INFO] Local aggregation root: D:\workspace\Champion Utilities
[INFO] Processing ch.frankel.champions.license:license
[INFO]     Updating project ch.frankel.champions.license:license
[INFO]         from version 1.0.0 to 1.0.1-SNAPSHOT
[INFO]
[INFO] Processing ch.frankel.champions.license:license-check
[INFO]     Updating parent ch.frankel.champions.license:license
[INFO]         from version 1.0.0 to 1.0.1-SNAPSHOT
[INFO]     Updating project ch.frankel.champions.license:license-check
[INFO]         from version 1.0.0 to 1.0.1-SNAPSHOT
[INFO]
[INFO] Processing ch.frankel.champions.license:license-common
[INFO]     Updating parent ch.frankel.champions.license:license
[INFO]         from version 1.0.0 to 1.0.1-SNAPSHOT
[INFO]     Updating project ch.frankel.champions.license:license-common
[INFO]         from version 1.0.0 to 1.0.1-SNAPSHOT
[INFO]
[INFO] Processing ch.frankel.champions.license:license-generation
[INFO]     Updating parent ch.frankel.champions.license:license
[INFO]         from version 1.0.0 to 1.0.1-SNAPSHOT
[INFO]     Updating project ch.frankel.champions.license:license-generation
[INFO]         from version 1.0.0 to 1.0.1-SNAPSHOT

Give it a try, it’s a real powerful yet easy!

Categories: Java Tags:

Further into CDI

July 13th, 2010 Nicolas Frankel 2 comments

In one of my latest articles on CDI, one of the lessons I learned was to use factory methods in order to reduce the number of classes. In this article, I will go into the detail since I think it is of some importance. More basic informations on CDI can be found in some previous posts: overview part 1 and overview part 2.

The naive approach

During school, you were probably taught to create a class for each component. For example, if your application has 4 buttons, North, East, South and West, you’ll have 4 classes. Each class configures its label, its icon and its action, either in the constructor or in some other method.

Note: in CDI, your can annotate such method with @PostConstruct in order for the container to call it just after the constructor.

This produces the following code, when taking Swing as an example:

public class NorthButton extends JButton {

  public NorthButton() {

    // Initializes label
    // Initializes icon
    // Initializes action
  }

  ...
}

Common behaviour and attributes may be factorized into one superclass, thus you end up with 5 classes.

Using the right number of classes is very important in any object-oriented language:

  • If you use too few classes, you run the risk that each class you develop has too many responsabilities and are too big.
  • On the contrary, if you use too much classes, you’ll explode code into many places and it will be a maintenance nightmare. Moreover, in the Sun (Oracle ?) JVM, classes are loaded into the PermGen space which has a fixed size. Who has never seen the dreaded java.lang.OutOfMemoryError: PermGen space?

IMHO, both are good reasons not to create a single class for each instancied component.

The factory approach

The second logical step is to create methods that produce the right instance. In our previous example, that would mean a factory class, with 4 methods to produce buttons, one for each button and probably a 5th method with common behaviour:

public class ComponentFactory {

  @North
  @Produces
  public JButton createJButton() {

    JButton button = new JButton();

    // Set label
    // Set icon
    // Set action

    return button;
  }

  ...
}

Notice that you’ll still need an annotation for each single component:

@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD,METHOD,PARAMETER,TYPE})
@Qualifier
public @interface North {}

In our case, that makes @North, @East, @South and @West. If these components are found throughout your application, fine (such as a Cancel button). If not, you still have a class for each component (annotations are transformed into classes at compile-time).

The “generic” annotations approach

CDI let you qualify injection not only from the annotation type but also from some (or all) their elements. We can thus greatly diminish the number of needed annotations. In order to do this, just create an annotation on this model:

@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD,METHOD,PARAMETER,TYPE})
@Qualifier public @interface TypeName {

  Class value();

  String name(); }

Now the factory method becomes:

public class ComponentFactory {

  @TypeName(value = JButton.class, name = "North")
  @Produces public JButton createJButton() {

    JButton button = new JButton();

    // Set label
    // Set icon
    // Set action

    return button;
  }

  ...
}

Although this method meets our requirements regarding the number of classes (and annotations), it still has one major drawback: now, it’s the number of methods that is vastly increased. Though not nearly as great a disadvantage as a great number of classes, it makes the code less readable and thus less maintainable.

The fully “generic” approach

CDI let you use an injection point parameter for producer method. This parameter has much information about, guess what… the injection point. Such informations include:

  • the reflection object, depending on injection’s type, respectively Field, Method and Constructor for field, method parameter and constructor parameter injection
  • the required type to inject
  • annotations relative to the injection point

The latter point is what drives what comes next. It means you can annotate your injection point, then get those annotations during producer method execution. In our case, we could have an annotation for each attribute we want to set (text, icon and action). Let’s create such an annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD,METHOD,PARAMETER,TYPE})
public @interface Text { String value(); }

Such annotation could be used in the producer method in the following manner:

public class ComponentFactory {
  @Produces
  @TypeName(JButton.class)
  public JButton createJButton(InjectionPoint ip) {

    JButton button = new JButton();

    Annotated annotated = ip.getAnnotated();

    if (annotated.isAnnotationPresent(Text.class)) {

      Text textAnnotation = (Text) annotated.getAnnotation(Text.class);

      String text = textAnnotation.value();

      button.setText(text);
    }

    // Set icon
    // Set action

    return button;
  }
}

Now, the only thing you have to do is annotate your button field like so:

public class Xxx {

  @Inject
  @TypeName(JButton.class)
  @Text("North")
  private JButton northButton;

  ...
}

This will get us a button with “North” as label. And nothing prevents you to do the same with icon and action.

Morevover, with just text, you could go further and manage internationalization:

@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD,METHOD,PARAMETER,TYPE})
public @interface Text {

  // Key in the properties file
  String value();

  // Path to the resource bundle
  String resourceBundle() default "path/to/resource/bundle";
}

This annotation could also be reused of other components that manage text, such as labels.

Conclusion

There’s no right or wrong approach in using CDI. However, the latter approach has the merit of being the most powerful. Additionally, it also let you write code relative to a component type in one single place. This is the road I’ve taken so far, and I’m very satisfied with it.

Categories: Java Tags:

Safely give away your demo applications

July 5th, 2010 Nicolas Frankel No comments

Last month, I had to develop a Proof-of-Concept web application for a potential customer. Everything went fine, but at the end of the meeting, the customer asked “Surely you will give us the demo so we can play with it further on our own”. I was pretty sure of my craft, so I had no problem about bugs and yet I gently refused anyway. Why so? Because I didn’t want to risk that my customer open the WAR and see how I made things happen.

Afterwards, I spent much time thinking how I could have done things differently, so that next time I will be the one to propose to let the demo in my customer’s hands. The following is the result of these thoughts.

Online hosting

This is the solution I choosed on the spur of the moment. It think it has many drawbacks, though.

There are two basic choices for it: either host the webapp on your own infrastructure or host it on a third-party’s. Hosting it on your infrastructure is a good idea, since it will fit your need. However, this requires a competent and willing IT team. Using a third party is tricky since you’re basically giving away both your responsibilities and your ability to do something.

Morevover, depending on where you host your application and your customer’s location, this could have response time issues and thus impact your demo’s image very negatively. Remember this is a POC, so the customer should focus on features, not performance.

Obfuscation

Java code can be easily decompiled: I remember there’s a tool in the JDK but I mostly use JAD since my beginnings in the Java world.

Only two things are lost when compiling code: comments and parameter names; class names, method names and attribute names are kept by the compiling process, as well as imports. Thus, decompiling Java code gets you most of the important stuff.

I already used obfuscation some years ago, in order to let contractors use a proprietary framework on site without so much risk to code decompiling with the yGuard product. yGuard let you define your API, which will be kept. All other classes and their associated members will be renamed with gobbledygook such as a, b, string and such in the compiled code. Code obfuscated with yGuard is very hard (but not impossible) to read.

Using obfuscation, whether with yGuard or another tool, has three main disadvantages. First, you’ll have to define your API, meaning you’ll have to manually set one by one all entry points of your application. These entry points are all files that are out of the scope of the obfuscator and that references your classes:

  • for standard application, this means the main class
  • for web applications, this means servlets
  • for Spring applications, this means beans referenced by Spring beans definitions files
  • etc.

Moreover, since the obfuscator only works on Java references, and thus not on Strings, you can kiss all your reflection code good bye. Of course, this is not the case of all applications, but if you think of obfuscating your code in the future, this means a constraint on your design.

Last but not least, most applications are nowadays done through configuration files. I wrote of Spring above, but it also properties files, deployment descriptors, and so on. These files are out of the scope of the obfuscator but they can give some pretty good idea about the code itself.  Of course, for Spring files, you can also use annotations, but then, that’s another constraint you have to consider from the start.

And now for something completely different

Sorry for this Monty Python reference… And yet, as seen from the previous possibilities, there truly is a need for something else, off the traditional paths.

The only thing truly satisfying I found so far is Excelsior’s Jet product. It produces an executable (one version for Windows, one for Linux) that is fully self contained. Decompiling such code does take much more effort than decompiling simple Java bytecode. From my point of view, I don’t think that’s impossible (I’ve learned nothing is in computers) but shouldn’t be worth the effort in most cases.

Using JET is a multi-step process done in two applications.

JET

Notice that JET let you create executable from web applications running on a Tomcat as well as standard Java SE or even Eclipse RCP applications!

JET’s features include:

  • system properties settings, meaning your executable will already be configured as you need
  • choice over the final format of the application: fully contained executable or executable with attached libraries
  • integration on the platform: this way, the executable will show information about the application the platform way
  • trial version time expiration if the need be
  • how your application launches and runs: splash screen, icon and console
  • optimization of the application: a dummy run let the compiler see how the application works and do what is needed to improve its performance considering its usage

JetPack II

Once you’ve described your project in the format JET wants, the time is to do the real work: package your application.

Here you can also:

  • choose additional components that will make way into your applications, such as the JRE itself. This means your application can really be contained in a fully independent executable!
  • detach a subset of the JRE and make it available on a web server of your choosing. This way, you only package what you use but prepare the rest to download if the need be
  • choose the packaging format: an installer or the executable itself

The only I found lacking so far is that JET does not provide Maven integration out-of-the-box. Since I do not give my web applications every day, it’s something I can live with…

Conclusion

Having tried the three options (hosting, obfuscating and JET), I am to say I find the latter to be the most powerful tool in my toolbox as of now.

Next time I am faced by a customer asking for my demo, I won’t bang my head against the wall to find the right solution, I will reply “Of course” on the fly, knowing JET will handle it for me.

Categories: Java, Product review Tags:

Flamingo tutorial

June 27th, 2010 Nicolas Frankel 4 comments

In this article, I will provide you with the documentation to easily use the Flamingo framework and more precisely, its ribbon widget.

Introduction

Never say that Microsoft never innovates: in Office, it introduced an interesting concept, the ribbon band.

The ribbon band is a toolbar of sort. But whereas toolbars are fixed, ribbons layout can change according to the width they display. If you have such an application, just play with it for a few seconds and you will see the magic happens.

Recent versions of Swing do not have such widgets. However, I found the Flamingo project on java.net. Examples made with Flamingo look awfully similar to Office.

Trying to use Flamingo for the first time is no small feat since there’s no documentation on the Web, apart from Javadocs and the source for a test application. The following is what I understood since I began my trial and error journey.

The basics

Semantics

  • the ribbon is the large bar on the screenshot above. There can be only a single ribbon for a frame
  • a task is a tabbed group of one or more band. On the screenshot, tasks are Page Layout, Write, Animations and so on
  • a band is a group of one or more widgets. On the screenshot, bands are Clipboard, Quick Styles, Font and so on

Underlying concepts

The core difference between buttons in a toolbar and band in a ribbon bar is that bands are resizable. For examples, these are the steps for displaying the Document band, in regard to both its relative width and the ribbon width.

The last step is known as the iconified state. When you click on the button, it displays the entire band as a popup.

Your first ribbon

Setup

In order to use the Flamingo framework, the first step is to download it. If you’re using Maven, tough luck! I didn’t find Flamingo in central nor java.net repositories. So download it anyway and install it manually in your local (or enterprise) repository. For information, I choosed the net.java.dev.flamingo:flamingo location.

The frame

If you are starting from scratch, you’re lucky. Just inherit from JRibbonFrame: the method getRibbon() will provide you a reference to the ribbon instance. From there, you will be able to add tasks to it.

However, chances are you probably already have your own frame hierachy. In this case, you have to instantiate a JRibbon and add it on the NORTH location of your BorderLayout-ed frame.

In both cases, the result should be something akin to that:

Adding a task

Tasks represent logical band grouping. They look like tabs and act the part too. Let’s add two such tasks aptly named “One” and “Two”.

public class MainFrame extends JRibbonFrame {

  public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {

      @Override
      public void run() {

        MainFrame frame = new MainFrame();

        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

        RibbonTask task1 = new RibbonTask("One");
        RibbonTask task2 = new RibbonTask("Two");

        frame.getRibbon().addTask(task1);
        frame.getRibbon().addTask(task2);
      }
    });
  }
}

Notice the getRibbon() method on the JRibbonFrame. It is the reference on the ribbon bar.

Also notice that the addTask() method accepts a task but also a varargs of JRibbonBand. And if you launch the above code, it will fail miserably with the following error:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot have empty ribbon task
  at org.jvnet.flamingo.ribbon.RibbonTask.<init>(RibbonTask.java:85)
  at MainFrame$1.run(MainFrame.java:37)
  at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
  at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
  at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
  at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
  at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
  at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Adding bands

To satisfy our Flamingo friend, let’s add a ribbon band to each task. The constructor of JRibbonBand takes two argument, the label and an instance of a previously unknown class, ResizableIcon. It will be seen in detail in the next section.

As for now, if you just create the RibbonTask with a reference to the JRibbonBand and launch the application, you will get such an error:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Inconsistent preferred widths
Ribbon band 'Hello has the following resize policies
  org.jvnet.flamingo.ribbon.resize.CoreRibbonResizePolicies$None with preferred width -4
  org.jvnet.flamingo.ribbon.resize.CoreRibbonResizePolicies$Low2Mid with preferred width -4
  org.jvnet.flamingo.ribbon.resize.CoreRibbonResizePolicies$Mid2Mid with preferred width -4
  org.jvnet.flamingo.ribbon.resize.CoreRibbonResizePolicies$Mirror with preferred width -4
  org.jvnet.flamingo.ribbon.resize.CoreRibbonResizePolicies$Mid2Low with preferred width -4
  org.jvnet.flamingo.ribbon.resize.CoreRibbonResizePolicies$High2Mid with preferred width -4
  org.jvnet.flamingo.ribbon.resize.IconRibbonBandResizePolicy with preferred width 42

Remember that bands are resizable? Flamingo needs information on how to do it. Before initial display, it will check that those policies are consistent. By default, they are not and this is the reason why it complains: Flamingo requires you to have at least the iconified policy that must be in the last place. In most cases, however, you’ll want to have at least a normal display in the policies list.

Let’s modify the code to do it:

JRibbonBand band1 = new JRibbonBand("Hello", null);
JRibbonBand band2 = new JRibbonBand("world!", null);

band1.setResizePolicies((List) Arrays.asList(new IconRibbonBandResizePolicy(band1.getControlPanel())));
band2.setResizePolicies((List) Arrays.asList(new IconRibbonBandResizePolicy(band1.getControlPanel())));

RibbonTask task1 = new RibbonTask("One", band1);
RibbonTask task2 = new RibbonTask("Two", band2);

The previous code let us at least see something:

Adding buttons (at last!)

Even if the previous compiles and runs, it still holds no interest. Now is the time to add some buttons!

JCommandButton button1 = new JCommandButton("Square", null);
JCommandButton button2 = new JCommandButton("Circle", null);
JCommandButton button3 = new JCommandButton("Triangle", null);
JCommandButton button4 = new JCommandButton("Star", null);

band1.addCommandButton(button1, TOP);
band1.addCommandButton(button2, MEDIUM);
band1.addCommandButton(button3, MEDIUM);
band1.addCommandButton(button4, MEDIUM);

Too bad there’s no result! Where are our buttons? Well, they are well hidden. Remember the resize policies? There’s only one, the iconified one and its goal is only to display the iconified state. Just update the policies line with the code:

band1.setResizePolicies((List) Arrays.asList(new CoreRibbonResizePolicies.None(band1.getControlPanel()),
  new IconRibbonBandResizePolicy(band1.getControlPanel())));

The result looks the same at first, but when you resize the frame, it looks like this:

Even if it’s visually not very attractive, it looks much better than before. We see the taks, the name of the band and the labels on our four buttons.

Resizable icons

The JCommandButton‘s constructor has 2 parameters: one for the label, the other for a special Flamingo class, the ResizableIcon. Since Flamingo is all about displaying the same button in different sizes, that’s no surprise. Resizable icons can be constructed from Image, ico resources or even SVG.

Let’s add an utility method to our frame, and spice up our UI:

public static ResizableIcon getResizableIconFromResource(String resource) {

  return ImageWrapperResizableIcon.getIcon(MainFrame.class.getClassLoader().getResource(resource), new Dimension(48, 48));
}
...
JCommandButton button1 = new JCommandButton("Square", getResizableIconFromResource("path"));
JCommandButton button2 = new JCommandButton("Circle", getResizableIconFromResource("to"));
JCommandButton button3 = new JCommandButton("Triangle", getResizableIconFromResource("the"));
JCommandButton button4 = new JCommandButton("Star", getResizableIconFromResource("resource"));

band1.addCommandButton(button1, TOP);
band1.addCommandButton(button2, MEDIUM);
band1.addCommandButton(button3, MEDIUM);
band1.addCommandButton(button4, MEDIUM);

This is somewhat more satisfying:

Choosing policies

Now we’re ready to tackle Flamingo’s core business, resizing management. If you have Office, and played with it, you saw that the resizing policies are very rich. And we also saw previously that with only two meager policies, we can either see the iconified display or the full display.

Let’s see how we could go further. You probably noticed that the addCommandButton() of JRibbonBand has 2 parameters: the button to add and a priority. It is this priority and the policy that Flamingo use to choose how to display the band.

Priorities are the following: TOP, MEDIUM and LOW.

Policies are:

Policy Description
CoreRibbonResizePolicies.None Command buttons will be represented in the TOP state (big button with label and icon)
CoreRibbonResizePolicies.Mid2Mid Command buttons that have MEDIUM priority will be represented in the MEDIUM state (small button with label and icon)
CoreRibbonResizePolicies.Mid2Low Command buttons that have MEDIUM priority will be represented in the LOW state (small button only icon)
CoreRibbonResizePolicies.High2Mid Command buttons that have HIGH priority will be represented in the MEDIUM state
CoreRibbonResizePolicies.High2Low Command buttons that have HIGH priority will be represented in the LOW state
CoreRibbonResizePolicies.Low2Mid Command buttons that have LOW priority will be represented in the MEDIUM state
CoreRibbonResizePolicies.Mirror Command buttons will be represented in the priority they were assigned to
IconRibbonBandResizePolicy Command buttons will be not represented. The entire band will be represented by a command button that when pressed will show a popup of the unconstrained band

Now, you have all elements to let you decide which policies to apply. There’s one rule though: when setting policies, the width of the band must get lower and lower the higher the index of the policy (and it must end with the IconRibbonBandResizePolicy) let you’ll get a nasty IllegalStateException: Inconsistent preferred widths (see above).

Let’s apply some policies to our band:

band1.setResizePolicies((List) Arrays.asList(
  new CoreRibbonResizePolicies.None(band1.getControlPanel()),
  new CoreRibbonResizePolicies.Mirror(band1.getControlPanel()),
  new CoreRibbonResizePolicies.Mid2Low(band1.getControlPanel()),
  new CoreRibbonResizePolicies.High2Low(band1.getControlPanel()),
  new IconRibbonBandResizePolicy(band1.getControlPanel())));

This will get us the following result:

Note: there won’t be any iconified state in my example since the band does not compete for space with another one.

More features

Flamingo’s ribbon feature let you also:

  • add standard Swing components to the ribbon
  • add a menu on the top left corner

  • integration with standard Look and Feels

Those are also undocumented but are much easier to understand on your own.

It also has other features:

  • Breadcrumb bar
  • Command button strips and panels

Conclusion

Flamingo is a nice and powerful product, hindered by a big lack of documentation. I hope this article will go one step toward documenting it.

Here are the sources for this article in Eclipse/Maven format.

To go further:

– Edit on 28th june 2010: feedback from Kirill –

  1. Version 5.0 no longer requires “iconified” policy to be present
  2. I strongly suggest not using image-based icons. The recommended way is to transcode SVG files to Java2D-based classes with an offline process and use those classes at runtime. This is what i do in the BasicCheckRibbon class.
Categories: Java Tags:

Lessons learned from CDI in Swing

June 21st, 2010 Nicolas Frankel 4 comments

Sinced I dived into CDI, I explored classical Java EE uses. Then, I used CDI into a pet project of mine to see how it could be used in Swing applications. This article sums up what lessons I learned from itthis far.

Note: this article assumes you have some familiarity with CDI; if not, please read my previous articles on CDI (CDI an overview part 1 and part 2) or read the documentation.

In my last attempts at Swing (I’m more of a web developer), I figured it could be nice to configure most of the UI components in Spring rather than coding the parameters by hand. In doing this, I used the traditional XML configuration approach, since using annotations would couple my code to Spring JAR, something I loathe to do. With CDI, however, I can live with having my code tied to a standard API: I can change the implementation. This is akin to developing a servlet where you reference the Servlet API, then run it in any container you want.

I coded and coded this way, looked at things made, refactored, then code some more, just like when it’s a personal project and you have no deadlines to meet. Then, I realized I could learn some lessons I could put to good use for the future. Here they are, in no particular order.

The right JAR

Getting all the right CDI JARs for your Java SE project can be a rather daunting task. In order to ease your pain, Weld provides you with a all-in-one JAR aptly named weld-se. Don’t argue that it’s bloated and repackaged, just use it, you will save yourself a lot of pain. For Maven users, this is the configuration:

<project>
...
  <dependencies>
    <dependency>
      <groupId>org.jboss.weld</groupId>
      <artifactId>weld-se</artifactId>
      <version>1.0.1-Final</version>
    </dependency>
  </dependencies>
</project>

She’s an easy logger

All the log frameworks I know of (JDK, Commons Logging, Log4J and SLF4J) let you declare your class logger rather easily:

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

Anyway, most of the time, in order to use this, you either:

  • create a template in your IDE. Yet configuring templates in each of your IDE can be rather tedious. Note to self: propose a feature where such templates (and preferences) could be saved on the web and shared across all of my IDE instances
  • copy the line from somewhere then paste it where you need it. Then you change the class to be logged. To be frank, and though it does not add to my legend (quite the contrary) this is what I do all the time

And doing the latter all the time, it happens I forget to change the logged class. Stupid, isn’t it? Perhaps, but what’s even more stupid is that I have to write it in the first place: the class is my context, it should be inferred. Guess what, Weld does it, with a little help from the weld-logger JAR (it uses SLF4J so beware or use the code as a template to use another framework):

@Inject
private Logger logger;

I truly don’t think it could be easier! The only drawback is that you lose the constant: for the projects I handle now, I can live with it. To use this feature, just add the following dependency to your POM:

<project>
...
  <dependencies>
    <dependency>
      <groupId>org.jboss.weld</groupId>
      <artifactId>weld-logger</artifactId>
      <version>1.0.1-Final</version>
    </dependency>
  </dependencies>
</project>

Remember initialization

CDI can of course inject your dependencies. But injecting your dependencies does not assemble them on the screen. Luckily, CDI also provides you with a hook in order to do it: this is the realm of the @PostConstruct annotation. Let’s take a very simple example:

public class MyPanel extend JPanel {

  @Inject
  private JCheckBox checkbox;

  @PostConstruct
  public void afterPropertiesSet() {

    setLayout(new FlowLayout());

    add(checkbox);
  }
}

The afterPropertiesSet() method is called after having injected all dependencies, and plays the role previously done in the constructor.

Note: yes, the method is named after an old Spring method defined in the InitializingBean interface, dating from version 1. It can now be replaced by specifying the init-method attribute of the bean in the XML beans definition file or using the @PostConstruct annotation.

(Don’t) grow in numbers

With CDI, your classes are injected into one another. However, this means that each component should have its own class. Tthis can be rather cumbersome: for buttons, for example, each should be attached its action on a specific basis. With time, even a moderately size application will grow in term of classs to be much bigger than a standard application. IMHO, this is not desirable since:

  • it makes your codebase bigger, and thus increase your development complexity
  • in Sun’s JVM, loading more classes mean you will use more PermGen space and you’re more likely to run into OutOfMemoryError

In order to limit the number of classes I produce, I used a component factory filled with producer methods. These methods are identified by CDI as injection providers.

public class ComponentFactory {

  @Produces
  public JButton getButton() {

    return new JButton();
  }
}

Use the injection point

This is good but not enough, since action (or text and icon) association will have to be done in the injected class. I would like to annotate the injected attribute with informations like the text of the button and get that information in my producer method. This is the goal of the InjectionPoint optional parameter. CDI provides it to you free of charge if you reference it in your method as a parameter.

public class ComponentFactory {

  @Produces
  public JButton getButton(InjectionPoint ip) {

    JButton button = new JButton();

    // Do something based on annotations on the parameter
    ...

    return button;
  }
}

This is exactly the way that Weld loggers (see above) are created.

Respect the Higlander rule

The Highlander rule is: “There can be only one”. Apart from being taken from a movie that young people mostly don’t know, it also enunciate a basic truth. Since injection must be deterministic, there cannot be two candidates for an injection point. Using producer methods as previously stated will run you into this problem: CDI will have both the JButton class and the producer method and will loudly complains about it in its usual way.

Exception in thread "main" org.jboss.weld.exceptions.DeploymentException: WELD-001409 Injection point has ambiguous dependencies.....
 at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:280)
 at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:122)
 at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:141)
 at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:331)
 at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:317)
 at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:399)
 at org.jboss.weld.environment.se.Weld.initialize(Weld.java:81)
 at org.jboss.weld.environment.se.StartMain.go(StartMain.java:45)
 at org.jboss.weld.environment.se.StartMain.main(StartMain.java:57)

To be compliant with the Highlander rule, you’ll have to discard the JButton class as a candidate for injection. In order to do this, I used qualifiers, both on the injection point and on the producer method. Since I did not want a qualifier per injection point / producer method pair, I made it parameterizable:

@Qualifier
@Target( { FIELD, METHOD })
@Retention(RUNTIME)
public @interface JType {

  public Class<? extends JComponent> value();
}

Annotating both the injected attribute and the producer method with the JType annotation made my code compliant with the Highlander rule!

Spread the word

A good practice I can recommend is to create a special Properties class tasked with initializing your labels (and another for your preferences, etc.), then inject it in all the client classes you need. Now, all classes have access to your internationalized labels. Truly terrific!

Forget Java WebStart

Weld JAR analyze process is incompatible with Java WebStart. You will likely have such nice error messages:

122 [javawsApplicationMain] WARN org.jboss.weld.environment.se.discovery.URLScanner - could not read entries
java.io.FileNotFoundException: http:\xxxxxxxxxx\weld-logger-1.0.0-CR2.jar (La syntaxe du nom de fichier, de répertoire ou de volume est incorrecte)
  at java.util.zip.ZipFile.open(Native Method)
  at java.util.zip.ZipFile.<init>(Unknown Source)
  at java.util.zip.ZipFile.<init>(Unknown Source)
  at org.jboss.weld.environment.se.discovery.URLScanner.handleArchiveByFile(URLScanner.java:142)
  at org.jboss.weld.environment.se.discovery.URLScanner.handle(URLScanner.java:126)
  at org.jboss.weld.environment.se.discovery.URLScanner.scanResources(URLScanner.java:107)
  at org.jboss.weld.environment.se.discovery.SEWeldDiscovery.scan(SEWeldDiscovery.java:71)
  at org.jboss.weld.environment.se.discovery.SEWeldDiscovery.<init>(SEWeldDiscovery.java:45)
  at org.jboss.weld.environment.se.discovery.SEBeanDeploymentArchive$1.<init>(SEBeanDeploymentArchive.java:45)
  at org.jboss.weld.environment.se.discovery.SEBeanDeploymentArchive.<init>(SEBeanDeploymentArchive.java:44)
  at org.jboss.weld.environment.se.discovery.SEWeldDeployment.<init>(SEWeldDeployment.java:37)
  ...
  at com.sun.javaws.Launcher.run(Unknown Source)
  at java.lang.Thread.run(Unknown Source)

I hope it will be fixed in future releases…

Singletons are NOT evil

Twice already I stumbled upon a strange behaviour: toggle buttons selected when they shouldn’t or state was lost. After debugging like mad, I saw that @PostConstruct methods where called well beyond the initial call. It seems my code called for another injection after that. In order to remedy to this, annotate your class with @Singleton in order to share the instance across multiple calls. I haven’t investigated more than that because:

  • I resolved the bug
  • I don’t know why I shouldn’t use singletons in a Swing application

Conclusion

I’m still in development, so I don’t think I’ve seen all there’s to see. Yet, the previous points can make a good starting point for any project wanting to use CDI in a Java SE context.

And please pardon the puns, I was feeling jolly because of this fine summer of ours :-S

Categories: Java Tags: ,

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:

The power of proxies in Java

May 10th, 2010 Nicolas Frankel No comments

In this article, I’ll show you the path that leads to true Java power, the use of proxies.

They are everywhere but only a handful of people know about them. Hibernate for lazy loading entities, Spring for AOP, LambdaJ for DSL, only to name a few: they all use their hidden magic. What are they? They are… Java’s dynamic proxies.

Everyone knows about the GOF Proxy design pattern:

Allows for object level access control by acting as a pass through entity or a placeholder object.

Likewise, in Java, a dynamic proxy is an instance that acts as a pass through to the real object. This powerful pattern let you change the real behaviour from a caller point of view since method calls can be intercepted by the proxy.

Pure Java proxies

Pure Java proxies have some interesting properties:

  • They are based on runtime implementations of interfaces
  • They are public, final and not abstract
  • They extend java.lang.reflect.Proxy

In Java, the proxy itself is not as important as the proxy’s behaviour. The latter is done in an implementation of java.lang.reflect.InvocationHandler. It has only a single method to implement:

public Object invoke(Object proxy, Method method, Object[] args)
  • proxy: the proxy instance that the method was invoked on
  • method: the Method instance corresponding to the interface method invoked on the proxy instance. The declaring class of the Method object will be the interface that the method was declared in, which may be a superinterface of the proxy interface that the proxy class inherits the method through
  • args: an array of objects containing the values of the arguments passed in the method invocation on the proxy instance, or null if interface method takes no arguments. Arguments of primitive types are wrapped in instances of the appropriate primitive wrapper class, such as java.lang.Integer or java.lang.Boolean

Let’s take a simple example: suppose we want a List that can’t be added elements to it. The first step is to create the invocation handler:


public class NoOpAddInvocationHandler implements InvocationHandler {

  private final List proxied;

  public NoOpAddInvocationHandler(List proxied) {

    this.proxied = proxied;
  }

  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    if (method.getName().startsWith("add")) {

      return false;
    }

    return method.invoke(proxied, args);
  }
}

The invoke method will intercept method calls and do nothing if the method starts with “add”. Otherwise, it will the call pass to the real proxied object. This is a very crude example but is enough to let us understand the magic behind.

Notice that in case you want your method call to pass through, you need to call the method on the real object. For this, you’ll need a reference to the latter, something the invoke method does not provide. That’s why in most cases, it’s a good idea to pass it to the constructor and store it as an attribute.

Note: under no circumstances should you call the method on the proxy itself since it will be intercepted again by the invocation handler and you will be faced with a StackOverflowError.

To create the proxy itself:


List proxy = (List) Proxy.newProxyInstance(
  NoOpAddInvocationHandlerTest.class.getClassLoader(),
  new Class[] { List.class },
  new NoOpAddInvocationHandler(list));

The newProxyInstance method takes 3 arguments:

  • the class loader
  • an array of interfaces that will be implemented by the proxy
  • the power behind the throne in the form of the invocation handler

Now, if you try to add elements to the proxy by calling any add methods, it won’t have any effect.

CGLib proxies

Java proxies are runtime implementations of interfaces. Objects do not necessarily implement interfaces, and collections of objects do not necessarily share the same interfaces. Confronted with such needs, Java proxies fail to provide an answser.

Here begins the realm of CGLib. CGlib is a third-party framework, based on bytecode manipulation provided by ASM that can help with the previous limitations. A word of advice first, CGLib’s documentation is not on par with its features: there’s no tutorial nor documentation. A handful of JavaDocs is all you can count on. This said CGLib waives many limitations enforced by pure Java proxies:

  • you are not required to implement interfaces
  • you can extend a class

For example, since Hibernate entities are POJO, Java proxies cannot be used in lazy-loading; CGLib proxies can.

There are matches between pure Java proxies and CGLib proxies: where you use Proxy, you use net.sf.cglib.proxy.Enhancer class, where you use InvocationHandler, you use net.sf.cglib.proxy.Callback. The two main differences is that Enhancer has a public constructor and Callback cannot be used as such but only through one of its subinterfaces:

  • Dispatcher: Dispatching Enhancer callback
  • FixedValue: Enhancer callback that simply returns the value to return from the proxied method
  • LazyLoader: Lazy-loading Enhancer callback
  • MethodInterceptor: General-purpose Enhancer callback which provides for “around advice”
  • NoOp: Methods using this Enhancer callback will delegate directly to the default (super) implementation in the base class

As an introductory example, let’s create a proxy that returns the same value for hash code whatever the real object behind. The feature looks like a MethodInterceptor, so let’s implement it as such:


public class HashCodeAlwaysZeroMethodInterceptor implements MethodInterceptor {

  public Object intercept(Object object, Method method, Object[] args,
    MethodProxy methodProxy) throws Throwable {

    if ("hashCode".equals(method.getName())) {

      return 0;
    }

    return methodProxy.invokeSuper(object, args);
  }
}

Looks awfully similar to a Java invocation handler, doesn’t it? Now, in order to create the proxy itself:


Object proxy = Enhancer.create(
  Object.class,
  new HashCodeAlwaysZeroMethodInterceptor());

Likewise, the proxy creation isn’t suprising. The real differences are:

  • there’s no interface involved in the process
  • the proxy creation process also creates the proxied object. There’s no clear cut between proxy and proxied from the caller point of view
  • thus, the callback method can provide the proxied object and there’s no need to create and store it in your own code

Conclusion

This article only brushed the surface of what can be done with proxies. Anyway, I hope it let you see that Java has some interesting features and points of extension, whether out-of-the-box or coming from some third-party framework

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

To go further:

Categories: Java 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: ,