Archive

Archive for the ‘Technical’ Category

Adapters in JAXB

January 29th, 2012 1 comment

Java XML Binding (aka JAXB) is part of many applications since it provides a convenient API to marshall/unmarshall Java to/from XML.

Like so many area, the devil is in the detail, like when one has to unmarshall a JAXB-incompatible class. Such classes come across one’s code for a variety of reasons: design, legacy, third-party… Suffice to say that such a sand grain can be a blocker for any project.

Luckily, JAXB designers must have had this use-case in mind when they crafted their API, because an adapter is provided to bypass such problems. In this case, a JAXB-compatible class is made available and JAXB bridges between it and the incompatible one. This is easily done through the use of the XmlJavaTypeAdapter annotation: it accepts a class parameter which bridges between the JAXB-friendly and -unfriendly worlds. In other words, it must implement the XmlAdapter<OriginalType, CompatibleType> contract. The annotation can then be put on the field which is of incompatible type.

This is all well, and many resources on the web tells how to do it. Alas, most examples stay on the safe side and completely forget to address the following:

  • My class to be marshalled (and back) has a field of type A
  • Type A has an associations of type B, which in turn has an association of type C, etc
  • All of these types are third-party
  • Type A through Y are JAXB-compatible, type Z is not

Now things get interesting… Creating the adapter for type A is out of the question, since I would have to create the structure for the whole tree, which would be a huge time sink.

The solution I’ve found so far is to create a package-info.java in the third-party package and annotate it with my adapter. It’s not clean in that it may come in conflict with the real package-info (i.e. the one coming from the third-party library), but it was not the case for me (none was provided). Btw, I’m amazed how few providers are creating this object in their library.

Anyone having faced this problem and found a more elegant solution?

Categories: Java Tags:

Shoud you change your design for testing purposes?

January 22nd, 2012 1 comment

As Dependency Injection frameworks go, the standard is currently CDI. When switching from Spring, one has to consider the following problem: how do you unit test your injected classes?

In Spring, DI is achieved through either constructor injection or setter injection. Both allow for simple unit testing by providing the dependencies and calling either the constructor or the desired setter. Now, how do you unit test the following code, which uses field injection:

public class MyMainClass {

  @Inject
  private MyDependencyClass dependency;

  // dependency is used somewhere else
  ...
}

Of course, there are some available options:

  1. you can provide a setter for the dependency field, just as you did in Spring
  2. you can use reflection to access the field
  3. you can use a testing framework that does the reflection for you (PrivateAccessor from JUnit addons or Powermock come to mind)
  4. you can increase the field visibility to package (i.e. default) and put the test case in the same package

Amazingly enough, when Googling through the web, the vast majority of unit testing field-injected classes code demonstrate the increased visibility. Do a check if you do not believe me: they do not display the private visibility (here, here and here for example). Granted, it’s a rather rethorical question, but what annoys me is that it’s implicit, whereas IMHO it should be a deeply thought-out decision.

My point is, changing design for testing purpose is like shooting yourself in the foot. Design shouldn’t be cheaply sold. Else, what will be the next step, changing your design for build purposes? Feels like a broken window to me. As long as it’s possible, I would rather stick to using the testing framework that enable private field-access. It achieves exactly the same purpose but at least it keeps my initial design.

Categories: Development Tags:

Properly closing Swing windows

January 8th, 2012 No comments

There are many subjects one has to know when working with Swing and one of them is window closing. A beginner pass through some steps (and yes, I consider myself a beginner in Swing) and here are those I experienced myself.

Hiding is default

In the first step, you realize that by clicking the cross in the title bar, the window only disappears. It’s not disposed of, and if it’s your main application’s window, that’s bad because it means you’ve lost any handle on the underlying running JVM. It means users just keep spawning new JVMs when launching the application and do not close them, using more and more of the platform memory.

The basics

By then, you learn that any Swing JFrame can be set the right close operation by calling its setDefaultCloseOperation() method. This let you choose the behavior when closing the window: for example, WindowConstants.EXIT_ON_CLOSE exits the JVM when closing the window. This should be set of course on your main window.

Shutdown hook

This method has a slight disadvantage, however. What if we need to do some cleaning operations before exiting the JVM? There’s something called shutdown hooks that the JVM calls just before exiting. It already is explained in this post and fits our needs… provided what we need to do is related to the entire application.

Window listeners

But how can we release resources that are needed by a popup window before the JVM exits? The last way I found was to use window listeners: by implementing WindowListener (or better, by extending WindowAdapter), one can code the desired behavior easily in the windowClosed() method.

Categories: Java Tags:

Managing unmanaged beans in CDI

January 1st, 2012 No comments

During these (much deserved) vacations, I worked on a pet project of mine which uses CDI with the Weld implementation and SLF4J with the Logback implementation.

The terms of the problem were very simple:  Iwanted the logs of my application to be displayed in a Swing table, i.e. a Logback appender had to write in a table. The table was managed in CDI but the appender was not: this was no surprise since many older-generation frameworks have a lifecycle management on their own. Prior-to-JEE6 Servlets, Log4J appenders, Struts actions all have their own lifecycle management, completely unrelated to CDI. Worse, dependency injection frameworks are in large part incompatible with one another (Spring comes to mind) and need an adapter to bridge between their contexts, so this use-case is a common one.

My first lead was to bootstrap Logback myself but since Weld uses SLF4J under the cover, I found no way. After some time, the conclusion was that CDI provided no means to inject my managed table into the Logback appender. That was a sad conclusion, but I didn’t stop there: when the specification doesn’t address your needs, jump to the implementation (but with remorse…).

There’s a nice complementary module to Weld called Weld Extensions, that provide additional features not mentioned in the JSR. Note that Weld Extensions seems to have been replaced by Seam Solder, but the logic stays the same: obtain a reference to the BeanManager and forcibly inject the table in the appender through it.

In Extension, the callback is made through the Extension marker interface. Such extensions are looked up by Weld using the service provider mechanism. If you’re not familiar with it, have a look at it, it’s elegant and useful in many use-cases. So, I created my META-INF/services/javax.enterprise.inject.spi.Extension file.

Now, let’s have a look at the extension itself:

import java.util.List;

import javax.annotation.PostConstruct;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.InjectionTarget;

import org.jboss.weld.environment.se.events.ContainerInitialized;
import org.slf4j.impl.StaticLoggerBinder;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;

public class LogbackWeldExtension implements Extension {

  public void bind(@Observes ContainerInitialized event, BeanManager manager) {

    LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory();

    List loggers = loggerContext.getLoggerList();

    for (Logger logger : loggers) {

      Appender appender = logger.getAppender("Table");

      if (appender != null) {

        AnnotatedType type = manager.createAnnotatedType(appender.getClass());

        InjectionTarget target = manager.createInjectionTarget(type);

        CreationalContext creationalContext = manager.createCreationalContext(null);

        target.inject(appender, creationalContext);
      }
    }
  }
}
  • At line 19, we inherit from Extension
  • At line 21, we observe the container initialized event, meaning the method is called when the Weld context is initialized. Note the BeanManager is the second parameter and is injected automatically by the framework!
  • From line 23 to 31, we use Logback’s API to get the handle on the unmanaged appender. Note that we get the reference by name, which I did because I was lazy at the time… The future version will browse through all appenders and get the correct one by class name.
  • Frome line 33 to 39, we use Weld’s API to inject the unmanaged logger into the beans that needs it. Note there’s no reference to the injected table bean, it’s just standard DI if the managed beans are correctly annotated. If you use this code, also note the compiler will warn you about the unused generics (those are a pain to work with!).

That’s it!

To go further:

Categories: Java Tags: ,

Java, Scala, complexity and aardvarks

December 4th, 2011 2 comments

This week saw another flame war from some of the Scala crowd. This time, it was toward Stephen Colebourne, the man behind Joda time.

The article in question can be found here, and Stephen’s answer here.

To be frank, I tend to agree to Stephen’s predicat but for very different reasons. Now, if you’re a Scala user, there are basically 2 options:

  • either you react like some did before, telling me I’m too stupid or too lazy to really learn the language and stop reading at this point. In this case, I’m afraid there’s nothing I can say apart from ‘Please, don’t harm me’ because it has a feeling of religion war coming from supposedly scientific-minded people.
  • Or you can read on and we’ll debate like educated people.

Truth is, I’m interested in Scala. I try to program in Scala for personal projects. So far, I’ve gotten the hold on traits (what I would do to have them in Java) and closures and I’ve understood some of the generics concepts (so long as it’s not too complex). I plan on diving in the Collections API to better use closures next.

I think that Scala, like EJB2, was designed by smart, even brilliant people, but with a different experience than mine.

In real life, projects are full of developpers of heterogeneous levels: good developers, average developers and bad developers. And please don’t blame it on the HR department, the CEO or the global strategy of the company: it’s just Gaussian distribution, just like in any population.

In effect, that makes Scala a no-go in most contexts. Take Java as an example. What did it make it so successful, even with all its lackings? The compile-once, run-everywhere motto? Perhaps, but IMHO, the first and foremost reason behind Java success is the change of responsibility in memory management, from developers (like in C/C++) to system administrators. Before, the worse the developer, the higher the probability of a bug in memory management but Java changed all this: it’s not perfect, but much simpler.

Like Freddy Mallet, I’m sure a technology has to be simple to become mainstream and Scala has not taken this road. As a consequence, it’s fated to stay in a niche market… Stating this should raise no reactions from anybody, it’s just a fact.

Note: aardvarks will be a point for a future blog post.

Categories: Java Tags: ,

‘Learning Vaadin’ contest winners

November 28th, 2011 3 comments

Dear readers,

Thanks for your participation in the ‘Learning Vaadin’ contest. It’s my pleasure to announce the winners:

  • Adolfo Benedetti who commented on the integration side of ‘Learning Vaadin’
  • Sebastian who also commented about integration
  • A. Jansenn who noted the Vaadin team is very positive about ‘Learning Vaadin’ and that it’s a good complement to the available documentation

The winners will be contacted by a Packt representative about the details.

The choice was hard and I know there will be some deception for not having won a copy. Nevertheless, you can always purchase the book at Packt or Amazon.

Categories: JEE Tags:

Win Free Copies of Learning Vaadin book

November 20th, 2011 18 comments

To celebrate the release of my new book, Learning Vaadin, Packt is giving away 3 copies especially to my blog readers. Keep reading to find out how you can be one of the lucky winners.

Overview of Learning Vaadin

  • Discover the Vaadin framework in a progressive and structured way
  • Learn about components, events, layouts, containers, and bindings

Read more about this book and download a free sample chapter.

How to Enter?

Head on over to the book page and look through the product description and drop a line via the comments below to let us know what interests you the most about this book and why you would recommend it to your friends.

Winners

Winners will be choosed from the commenters, based on the interest and relevance of the comments. Winners from the U.S. and Europe will be able to either choose a physical copy of the book or the eBook. Users from other locales are limited to the eBook only.

The contest will close on Friday, the 25th of November at midnight (Central European Time). Winners will be contacted by email, so be sure to use your real email address when you comment!

Categories: JEE Tags:

Apache Maven 3 Cookbook

November 13th, 2011 No comments

This review is about Apache Maven 3 Cookbook from Srirangan from Packt Publishing.

Facts

  1. 9 chapters, 208 pages, $35.99
  2. This book covers Apache Maven 3

Pros

Each recipe is structured in 3 steps:

  1. “Getting ready”
  2. “How to do it”
  3. “See also” for references on associated recipes

Cons

  1. The scope of the book is too large for only 200 pages. It spans from Java to Scala and Groovy through Android, GWT and Flex.
  2. Most products installation processes (Sonatype Nexus, Hudson) are documented with a few screenshots. It would have been better to reference the product installation on the Web or to go in detail. In the current state of thing, most readers are left wondering what to do with it.
  3. The recipe structure is well adapted for… recipes. When talking about general Maven principles like compiling a project, it feels convoluted and artificial.
  4. Writing a whole chapter about native Maven reporting when there’s Sonar? Come on…

Conclusion

I was expecting much from this book, because I’m a daily Maven user and because Maven is regularly misused (see here and here for a start). I’m sorry to say I’m disappointed: there’s not much regarding how to resolve daily Maven problems provided. The concept is a good idea but IMHO the result is a failure.

Disclaimer: I was provided the book freely, courtesy of Packt Publishing

Categories: Book review Tags: ,

Configuring Maven to use SLF4J

November 6th, 2011 6 comments

I mainly write articles for two reasons: to understand something that is new to me or to document something I regularly have to explain to others. This article definitely falls in the second category: in order to celebrate the new 1.0.0 version of Logback, I’ve decided to write down once and for all how to properly use SLF4J with Maven since it seems there’s no shortage of questions about it.

Basics

The basis of SLF4J is to have two separate components, one API and one implementation. That means that your code should solely be dependent on the API thus the implementation can be changed at your convenience. Remember that decoupling code from implementations by introducing an interface should be your first concern: at the library level, it’s the role of an API.

This is easily done like this in your POM:

<project ...>
	<dependencies>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.6.4</version>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<scope>runtime</scope>
			<version>1.0.0</version>
		</dependency>
	<dependencies>
</project>

The runtime scope prevents us from using Logback’s implementation classes when coding, which achieves decoupling.

Note: if you’re using a parent POM for your project (because you have modules), it goes without saying the above dependencies should be under the dependencyManagement section.

Bridging

Since an application with only logging features is a bit limited, it’s highly likely we’ll need other dependencies. Of course, some of those dependencies may use other logging frameworks, such as Commons Logging or Log4J.

For example, Spring uses Commons Logging: thus, logs produced by our application would use logback while those produced by Spring would use Commons Logging. This strategy needs two different configurations files (as well as knowledge of both) which is not very intuitive. Moreover, this would be unwieldly when reading twothe flow on two different sources. Note that this could be mitigated by using logging targets other than files (which I haven’t seen yet).

Fortunately, SLF4J provides bridging components that let us wire third-party API calls directly to SLF4J. For Spring, that means removing all dependencies to Commons Logging and replacing them with a single dependency to the Commons Logging to SLF4 bridge.

<project ...>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.0.0</version>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>3.0.0</version>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.0.0</version>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>1.6.2</version>
		</dependency>
	<dependencies>
</project>

Like in the section above, you should preferably use the

Note: although this knowledge is by no means necessary, know that since API and implementation are both packages together in the commons-logging.jar, the jcl-over-slf4.jar bridge completely replaces the API classes provided by Commons Logging. That means you shouldn’t have both JAR in your classpath!

Troubleshooting

Remember the Highlander rule: “there can be only one”. In this case, there can be only one implementation available on the classpath since SLF4J uses the Java Services Provider. If its the case, SLF4J will display a “Multiple bindings were found on the class path” warning and uses the first it finds (first on the classpath). Since classpaths are ordered by Maven, there’s little chance it will be the thing we want. Thus, take care of not putting slf4j-simple in the test scope along with logback or be prepared to face undetermined side-effects.

To go further:

Categories: Java Tags: ,

‘Learning Vaadin’ is out

October 30th, 2011 8 comments

This is it! After 10 monts of work, my first book is out: ‘Learning Vaadin’ is now available at Packt and Amazon.

First things first, what’s is Vaadin? Vaadin is a presentation-layer web framework that let you easily develop Rich Internet Applications. It does so by provding an abstraction over the Servlet API and by letting developers assemble components to design screens (as opposed to pages as in previous generation web frameworks). If you got 5 minutes to spare, you can go try the tutorial and be convinced yourself. Note that I do not hold Vaadin for a golden hammer, but in most contexts, it just is the right tool.

Now, why write a book? An imperative prerequisite is to believe in the subject. For me, it was love at first sight… I already wrote on Vaadin and used it in real pre-sales demos. During a conversation with Joonas Lehtinen, Vaadin’s CEO, he mentioned he had been approached by Pack to write a book on the subject. My brain processed the information and mere minutes later, I proposed myself.

Although writing a book is like coding in a project in many ways: there’s a schedule, limited time, reviewing (testing), rewriting (bug fixing), ups and downs, it has not been easy for me. I’m admirative of people who regularly write books in their spare time. They need discipline, of course, but also a supportive family and the right publisher. Fortunately, I had these assets this time and I’m now proud to have finished the book.

But is it finished? The strangest is that I do not realize yet. I’m waiting to hold a hard-copy in my hands to really think ‘I’ve done it’. Once received, I believe I will be entitled to some much-deserved R&R :-)

‘Learning Vaadin’ in the news:

You’re welcome to mention other references I may have missed.

Categories: JEE Tags: