The Double Curly Braces Idiom – a Poisoned Gift

Lukas Eder has an interesting story: The popular double braces idiom is a poisoned gift. It causes memory leaks.

Let me start with a quick note on my article. Originally, I simply wanted to provide a link to the article written by Lukas. However, there are several points I disagree with him. You need some background to understand my contradictions, so I ended up with an article that covers almost the same story as the original article. That said, I recommend to read The Double Curly Braces Anti Pattern as well as reading my article. There’s a lot of shared content, but there are also differences.
Continue reading “The Double Curly Braces Idiom – a Poisoned Gift” »

How to Modify JSF Library Load Order

Why ordering matters

Every once in a while it’s important to control the order in which JSF libraries are loaded1. For instance, loading the LiferayFacesBridge 6.1 before PrimeFaces 5.x breaks the AJAX features of PrimeFaces. Both libraries replace the same Mojarra or MyFaces base class by their own, improved implementation. Unfortunately Liferay doesn’t cope with the implementation of PrimeFaces. Loading PrimeFaces first fixes the problem.

There are many more examples. JSF libraries such as OmniFaces, AngularFaces and BabbageFaces don’t provide widgets. Instead, they modify the way JSF requests are processed2. Those processors stack behind each other like a pipeline. It’s easy to imagine situations in which the reordering the pipeline makes a difference. For instance, it’s important that BabbageFaces is the last stage of the pipeline: it optimizes the HTML code generated by the previous stages.

This article shows how to modify the load order of JSF libraries.


Continue reading “How to Modify JSF Library Load Order” »

  1. more precisely: the order in which the libraries are configured and activated. However, the difference isn’t important for this article, so I’ll stick with the more common notion of “load ordering”.
  2. At this point, I deliberately oversimplify things a bit to keep language simple

Build Your Own Dependency Injection Framework!

Let’s bust a myth. There are very good reasons to use CDI or Spring, but dependency injection isn’t one of them. There are a lot of alternatives. And I’m not talking about Google Guice, although that’s a very fine DI framework indeed. Why don’t we write our own DI framework? Can’t be difficult, can it?

It’s true: today’s open source libraries make writing your own DI framework incredibly simple. But even without such a library writing a DI framework isn’t difficult (at least if you’re ready to learn something about class loaders). I’ll develop a sketchy DI framework in this article. In theory, you could finish my work to implement a full-blown DI container and put it into production. Even if you don’t, you’ll understand how CDI and Spring work after reading this article.

But first I’d like to present you an alternative you’re probably not aware of.
Continue reading “Build Your Own Dependency Injection Framework!” »

Newsflash: OmniFaces 2.0 released

OmniFaces 2.0 has been released today (Nov 24, 2014).

What is OmniFaces?

For those who don’t know OmniFaces yet: OmniFaces is… different. It’s a JSF library that doesn’t focus on providing GUI widgets. Instead, it integrates into your existing JSF ecosystem and adds functions lacking in JSF. OmniFaces 2.0 offers 90 components, give or take a few, most of them dedicated to non-GUI components. My favorite OmniFaces features are the CombinedResourceHandler, which accelerates the delivery of most JSF pages tremendously, the SelectItemsConverter which makes JSF comboboxes a lot less scary and the FullAjaxExceptionHandler, which make exceptions occurring during an AJAX request visible.

What’s new in OmniFaces 2.0?

Many things. In this article I’ll focus on two interesting new features: Bean validation at class level and simplified display of images.

JSF 2.0 added support for the Bean Validation API (aka JSR 303). Sad thing it didn’t support the API completely. Neither does the current version, JSF 2.2. To fill the gap OmniFaces adds <o:validateBean />. Among other things, this allows you to implement cross-field validations. Add <o:validateBean value="#{myBean}"> to your form to have the bean validated. In my opinion, this solution still doesn’t fulfill the promise of JSR 303 (which says a simple annotation to the class does the trick), but to be fair, it’s not easy to meet the requirements of the JSF lifecycle. The JSF specification requires that invalid values are not written to the bean. Therefore framework developers have to copy the bean to implement things like class level or cross field validation. By this measure OmniFaces does a pretty good job. Read the full story here.

Have you ever tried to display an image stored in a database? That’s one of those things that are simple using basic servlets, but horrendously difficult using JSF. <o:graphicImage> saves you from learning about ResourceHandlers. All you have to do is do define a CDI bean returning the image as a byte array:

@Named
@ApplicationScoped
public class MyImage {
    public byte[] getImage() {
        return /* the image as byte array */;
    }
}
<o:graphicImage value="#{myImage.getImage()}" />

See more details explanations and examples at the OmniFaces showcase on o:graphicImage.

Increased requirements

Talking of which – yes, I said you need a CDI bean, and I meant it. OmniFaces 2.0 requires Java 1.7, JSF 2.2, EL 2.2, Servlet 3.0 and CDI 1.1. Spring users have to stick with CDI 1.10. The good news is OmniFaces is going to supports the 1.x branch for a while, but they don’t intend to implement the new features into the 1.x branch.

Dig deeper

OmniFaces 2.0 released! by Arjan Tijms
OmniFaces 2.0 released! by OmniFaces lead Bauke Scholz (aka BalusC)
OmniFaces showcase

Eclipse Compiler Surprises

I guess you know exactly what the class file of this Java source code looks like:

public class MyClass {
   public void myMethod() {
     I do not compile
   }
}

You don’t have to know anything about byte code to know this class doesn’t compile. Asking for the byte code is a moot point: obviously there’s no class file. Let’s have a look at the binaries folder, just for the fun of it:

Oops. Eclipse does a clever trick: it generates class files of invalid classes.
Continue reading “Eclipse Compiler Surprises” »

AngularJS 2.0: Sneak Preview on Data Binding

The AngularJS team presented a straw-man’s proposal for AngularJS 2.0 syntax one or two weeks ago. According to the proposal, AngularJS 2.0 is going to look substantially different from what we used to consider Angular, and nothing shows this better than the overhauled core of AngularJS: data binding. It’s a fresh new take on AngularJS, or, like Cagatay Civici tweeted, it’s almost like a new framework that just happens to have the same name.

He isn’t the only one to think so. Developers protested against the changes, and soon discovered several issues with the syntax. This article shows the original ideas nonetheless – I consider them interesting, even if they’re likely not to come.

Evolving W3C standards open new opportunities

So they decided to make a new start, dropping compatibility to AngularJS 1.x. And why not? I suppose the Angular team learned a lot about HTML and Javascript along the way, so they now know how to make things better. Who might have envisioned the flexibility of HTML concerning attribute names? Back in 2000, valid HTML attribute names were basically characters, digits, underscores and colons. By 2009, the W3C organization had added a lot of flexibility. Now, almost every Unicode character can be used in attribute names – this even includes Chinese and Devenagari characters (such as क्तु):

<div myAttribute[index] = ""
     ^[myAttribute]     = ""
     seño(ra|rita|r)    = ""
     क्तु                 = ""
     你好               = "">

AngularJS 2.0 makes a lot of use of this flexibility. The team invented a new system of data bindings that’s more logical than the previous system. It uses special characters to distinguish between different types of attributes. We learned from several Scala frameworks that ran havoc that using special characters tends to be a bad thing because special characters don’t do much in the way of explaining their meaning. I hope the AngularJS team has learnt the lesson and uses special characters carefully and sparsely. Changing the data binding syntax and dropping compatibility is a bold decision that may or may not work out. However, the current drafts look fascinating enough.

Update Nov 23, 2014

During the last couple of weeks the AngularJS team dropped the idea of using special characters. There were many obstacles: using special characters may be valid HTML, but that doesn’t mean browsers can deal with them. Even worse, many third-party tools don’t cope with special characters. However, it’s clear that the syntax will change. At the moment, there’s no agreement on the new syntax, so this article sticks with the straw man’s proposal. The details may change, but the ideas remain the same.
Continue reading “AngularJS 2.0: Sneak Preview on Data Binding” »

Newsflash: BootsFaces Now is Open Source

The BootsFaces team have published the source code of the BootsFaces JSF library on GitHub.

BootsFaces is a JSF widget library that translates Bootstrap code to a dialect more familiar to JSF programmers. For instance, a navigation bar is written like so:

<b:navBar brand="Brand" brandHref="#" inverse="true">
    <b:navbarLinks>
        <b:navLink value="Home" href="#"></b:navLink>
        <b:navLink value="Link" href="#"></b:navLink>
        <b:navLink value="Link" href="#"></b:navLink>
    </b:navbarLinks>
</b:navBar>

Source code and screen shot copied from the Bootstrap documentation.

This converts to the NavBar component familiar from many Bootstrap pages:

BootsFaces offers widgets for the basic tool set of web applications: apart from the NavBar there are menus, panels, buttons, button groups (aka tool bars), input texts, date pickers, modal dialogs, sliders and several more. While the tool set isn’t complete yet, the BootsFaces project seems to be very active, so chances are missing components such as check boxes and combo boxes (aka editable drop down menus) are added soon. In any case, it’s possible to use a standard JSF check box and use some CSS to align it with the bootstrap look and feel, so this shouldn’t be to much of a problem.

At first glance, BootsFaces seems to be an interesting framework for everybody who wants to use both Bootstrap and JSF.

What is AngularJS 2.0 Going to Look Like?

At last week’s ng-conference in Paris the AngularJS team gave us an early impression of how AngularJS 2.0 is going to look like.

Maybe you remember me writing in an earlier article that AngularDart is a preview on AngularJS 2.0. It wasn’t my own claim. I found it at the AngularDart web site. When I was jotting it down I couldn’t help but wonder how this might be done. AngularDart benefits largely from classes, annotations and an optional type system. This can’t be ported to Javascript, I thought?
Continue reading “What is AngularJS 2.0 Going to Look Like?” »

Java 8 Named Method Parameters

I was very surprised when I read Adam Bien’s blog post on named parameters in Java 8.

Named parameters? Well… not quite. At least not the kind of named parameters we know from languages such as Visual Basic, Groovy and many others. But it turned out to be an interesting read nonetheless. The article is about the Java 8 improvements of the reflection API.
Continue reading “Java 8 Named Method Parameters” »

Newsflash: AngularJS 1.3 Released

Oct 15, 2014. AngularJS 1.3 aka “superluminal-nudge” has been released two days ago. AngularFaces will support AngularJS 1.3 starting with the next version (AngularFaces 2.1).

According to the AngularJS blog, AngularJS 1.3 contains 400 bug fixes, a lot of performance improvements – both concerning speed and memory consumption – better support for users with a handicap and much more. An improvement I particularly like is ng-messages, a directive that simplifies the tedious chore of adding error messages (even if it’s still a far cry from the ease of use of <pui-message /> of AngularFaces):

<form name="myForm">
<input type="text" ng-model="field" name="myField" required minlength="5" />
<div ng-messages="myForm.myField.$error" ng-messages-multiple>
  <div ng-message="required">You did not enter a field</div>
  <div ng-message="minlength">The value entered is too short</div>
</div>
</form>

Code cited from the documentation of ng-messages

AngularJS also contains an improved model binding engine. For instance, AngularJS 1.3 supports one-time binding, a feature that’s already familiar from AngularDart. If you don’t want to update a value once the page has been loaded, one-time binding improves performance considerably. Another nice feature ng-model-options, which allows you to fine-tune the model updates. For instance, you can restrict model updates to certain events, such as leaving the field:

<input type="text" 
       ng-model="user.name"
       ng-model-options="{ updateOn: 'blur' }" />

This feature comes in handy if you’ve got a circular dependency of fields containing calculated values that can be modified by the user (just think of three input fields, displaying a simple equation such as a = b + c).

According to the blog, using a short-hand dependency syntax often blocks minification. To notice such errors during development time, AngularJS 1.3 introduces an optional strict DI mode.

Dig deeper:

Announcement on the AngularJS blog

Newsflash: Ceylon 1.1 published

Yesterday (Oct 9, 2014) Ceylon 1.1 has been published.

For those who don’t know Ceylon yet: Ceylon is one of the interesting emerging JVM languages introducing many interesting features. For example I reported about Ceylon’s interesting approach to get rid of NullPointerExceptions some time ago. Ceylon is developed by Red Hat’s Gavin King, who’s already well-known from his work on Hibernate and Seam.

As far as I can see, the language itself hasn’t changed much. Instead the team concentrated on performance, the SDK, the Eclipse IDE and the libraries.

Dig deeper:

Gavin King’s Ceylon 1.1 announcement
Reddit discussion on Ceylon 1.1

Newsflash: Java Decompilers

Nowadays everybody seems to pull their libraries from Maven Central, which encourages to upload both the binaries and the source code of a library. Most developers follow the guidelines, so nowadays it has become painless to read the source code of the open source libraries you use. Debugging such a library usually is pretty simple. You don’t have to look for the source code, it’s just there.

Still, every once in a while you’re looking for a bug occurring in a library without source code. In such a situation a Java decompiler comes in handy. It analyzes the Java byte code and tries to reconstruct the original source code.

This article covers three decompilers in some (limited) detail and provides a link to an article covering a dozen more decompilers.
Continue reading “Newsflash: Java Decompilers” »

What’s New in PrimeFaces 5.1?

After two consecutive major, quite revolutionary releases it’s time for consolidation. Çağatay Çivici and his team seem to think the same and call the new release of PrimeFaces a minor version (5.1). It’s not that small, by the way: I’ve counted 660 commits, Granted, many commits deal with the new showcase, some deal with PrimeUI, but what remains is still impressive. According to the PrimeFaces blog the new version brings 225 filed improvements and more than 140 bug fixes.

So what’s new in PrimeFaces 5.1?
Continue reading “What’s New in PrimeFaces 5.1?” »

TomEE-Based JavaEE Counterpart to Spring Boot

Spring Boot stirred up the Java world. Developers always put up stoically with slow server start-ups, long deployment times and difficult server configurations. Those times seem to come to an end. There’s only so much coffee you can drink during the breaks.

The disadvantage of Spring Boot is it uses Spring, excluding roughly half of the Java community. As far as I know you can’t use CDI on Spring Boot. Even if you were to find a way how to do it, it’s questionable if it’s wise to use two different dependency injection frameworks simultaneously.

So what about the JavaEE world? The TomEE team are currently exploring what needs to be done to implement a JavaEE counterpart to Spring Boot. These days Alex Soto published a surprisingly simple prototype (complete source code here).

At the moment it’s only a sketch which can run servlets and REST services. Spring Boot goes far beyond that: just think of the amount of effort that went into monitoring. Alex Soto’s prototype has a long way to go yet to become a real competitor. In any case he has announce to publish more source code soon on GitHub.

Be that as it may, even the current prototype can already be useful. In an earlier article (Application Servers are dead!) I’ve sketched how to embed Jetty or Tomcat in a JAR file. TomEE is much more complete. Embedded TomEE also brings CDI, EJBs, JSF and the rest of the JavaEE stack. Of course documentation is still sparse, but an adventurous developer should be able to implement a full-blown JavaEE application on the 70-lines prototype.

By the way, this isn’t the only project inspired by Spring Boot. After finishing the article I stumbled about a similar, less ambitious project. If you’re interested only in CDI and REST services, forseti may be worth a look. It’s a tiny project running on Jetty.

Dig deeper:

Alex Soto’s announcement
BeyondJava.net’s running copy of the source code
How to run JSF and PrimeFaces on Spring Boot
Application Servers are dead! (Sort of)

How to Modify the JSF 2.2 Component Tree Safely: TagDecorators, TagHandlers and PreRenderViewEvent

Earlier this week Rudy de Busscher published an interesting article about JSF TagHandlers. Today I’d like to go a step further. Let’s have a closer look at them and discuss a second class of JSF tree manipulation classes: the TagDecorators. And, while I’m at it, I’ll also cover to system events, PostRenderViewEvent and PostAddToViewEvent, that can also be used to manipulate the JSF component tree.

Putting it in a nutshell, TagDecorators create JSF tags, whereas a TagHandler can be used to modify tags that already exist. Every JSF application can implement its own TagHandlers or TagDecorators. However, you hardly ever see one of them in the wild.

Obviously most people consider these classes a fairly advanced topic. You can work a long time with JSF without ever seeing one of them. But every once in a while, they come in handy. Rudy’s example is pretty impressive in that regard: sometimes even an everyday task like enforcing user input in capital letters can be implemented simpler and more safely using a TagHandler. AngularFaces uses both TagDecorators and TagHandlers a lot, and JSF 2.2 itself made TagDecorators popular by using them to implement the new HTML5 friendly markup style.
Continue reading “How to Modify the JSF 2.2 Component Tree Safely: TagDecorators, TagHandlers and PreRenderViewEvent” »

Final Version of AngularFaces 2.0 Published

Fork me on GitHubIt was a hot summer day when I was sitting in the garden and started to dream. Wouldn’t it be nice to add AngularJS to JSF?

Today it’s a sunny day too, I’m sitting in the garden again and AngularFaces 2.0 is finished (it’s even available on Maven Central). Now it’s possible to use AngularJS without abandoning JSF. Even better: it’s very simple, and AngularFaces 2.0 has much more in store for you. It adds a couple of features beyond AngularJS, such as bringing the Bean Validation annotations to the client and helping you to target an international market by reducing the boiler plate code needed to translate an application. AngularFaces is worth a look if you don’t want to involve yourself AngularJS programming.

Continue reading “Final Version of AngularFaces 2.0 Published” »

AngularFaces 2.0 RC4 Published

Fork me on GitHubThe final release of AngularFaces 2.0 is coming near! The latest – and possibly last – release candidate RC4 has been published today. Here’s what’s new and noteworthy about the version:

  • Reduced requirements on the Java version: Java 6, 7 and 8 are supported. The binaries in the distribution folder are compiled with Java 6.
  • You can now use traditional JSF AJAX requests with AngularFaces (although it’s not advisable to do so, because AngularJS doesn’t seem to support this).
  • Improved compatibility to Internet Explorer 11 (and probably older versions as well, but since I’ve updated my PC to the latest version, I can’t really tell).
  • Several common HTML tags can now be used without preceding “h:”.
  • <input> can now be used without “type” attribute. The type is derived from the JSF bean. This isn’t exactly a new feature: AngularFaces supports the same feature for <h:inputText> since a long time. The news is that also the native HTML5 <input> is supported.
  • Client-side error messages use the PrimeFaces design in PrimeFaces views (and the simpler Mojarra design otherwise).
  • AngularFaces input fields can now display boolean JSF bean attributes (and are displayed as checkboxes).

Work on the manual on AngularFaces.com is also progressing nicely. The same applies to the demo applications.

As usual, you find the updated jar file and two demo war files on the AngularFaces dist folder on GitHub.

Java 8 Update 20: String Deduplication

Remember my last April prank? I span a yarn about the great way Oracle managed to squeeze every conceivable String into a 64-bit number. Funny thing is my vision comes sort of true. Of course, not the way I claimed. That was nonsense meant to be easily seen through (“There are only so many Strings a gal or a guy can think of – so everything you have to do is to assign them a 64-bit number”). But it’s true that a lot of work at Oracles’ is dedicated to optimize String management.

Java 7 Update 6 improved the speed of String.substring() by sacrificing a little memory efficiency (see my article Recent Improvements of Java’s String Implementation). Java 8 Update 20 takes the opposite approach: it sacrifices a little CPU efficiency in order to reduce memory footprint. On the long run this should reduce the strain on the CPU, too. In other words: most real worlds programs should run faster.

Everybody who’s analyzing a Java program in a profiler can’t avoid noticing: Java programs create incredible quantites of character arrays. Most of them are part of String objects. Java represents its String as objects, meaning there’s a pointer to a character array. That’s not exactly the most efficient way to represent a sequence of characters. It’s just what you get if you want to represent a String as an object instead of defining it as a native primitive type. However, the developers of Java got aware of the problem a long time ago, so they invented the String.intern() method. In general, it’s a bad idea to call this method by yourself (because you’re trying to outperform the JVM’s optimization), but sometimes it reduces your application’s memory footprint tremendously.

Putting it in a nutshell, String deduplication is a clever way of calling String.intern() as part of the garbage collection. Since Java 8 U20 the garbage collector recognizes duplicates String and merges them. As mentioned above, this costs some CPU power, but it shouldn’t be much of a concern because the garbage collector runs in its own thread. Plus, on the long run the reduced memory footprint makes the garbage collector run faster.

There’s a discussion on reddit indicating String deduplication really works, but sometimes you have to adjust the JVM parameters. I suppose that’s one of the reasons why the feature isn’t activate by default yet. You have to activate manually by starting the JVM with the parameter

-XX:+UseG1GC -XX:+UseStringDeduplication

Still, I sometimes wonder why a Java String has to be an object. Back in the seventies or the eighties, when the first languages became powerful enough to represent a String by means of the language instead of defining it as a primitive type, it quickly become a fashion to do so. Probably there are other reasons, but I always had the impression language designers considers this a sign of their language’s maturity. But being able to express a String as a library object doesn’t mean to have to do so. If Java were to use zero-terminated character arrays (the way BASIC does) or if it were to use a character array with a preceding length byte1, hardly any developer would notice. But the implementation gets rid of a pointer, simplifying memory management and garbage collection. The only convincing advantage of making Strings part of the language libraries is the ability to derive custom classes. Sadly, the Java developers prohibited this very early in the Java history by making String a final class. They did it for a good reason – but still, it’s a pity. Groovy’s GStrings show what you can do when you allow to derive from Strings.

That said, I’d like to point you to Java Performance Tuning Guide. They’ve written an in-depth article about Stringdeduplication.


Dig deeper:

Java Performance Tuning Guide on String deduplication
discussion on reddit on the topic (well, one of them – possibly the most interesting one)


  1. or a 64-bit word in the age of Gigabyte memories – and the characters should be at least 16-bit to support UTF-16. I used “byte” and “character” as a figure of speech. Is there a catchy word for 16 or 32-bit integers?

JSF 2.2 HTML5 Cheat Sheet

I’ve read a lot about the new JSF 2.2 HTML5 input fields, but until today I didn’t realize I hadn’t read a comprehensive introduction about this feature. I used to be happy with the short examples I was presented at conferences. However, there’s more than just <input type="text" jsf:value="#{my.favoriteBean.attribute}" />. As it happens, the documentation hides in plain sight. The JavaEE Javadoc tells you everything you have to know about the Mapping between HTML tags and JSF components. For the sake of convenience, this article summarizes the key points.

The general idea is to enable a web designer to design your JSF page without running a server. So it’s native HTML, and it should display nicely in a browser if opened as a simple HMTL file. Putting it in a nutshell, renaming a JSF file from *.xhtml to *.html doesn’t modify the design of the page.
Continue reading “JSF 2.2 HTML5 Cheat Sheet” »