Links of the Week

Here are some interesting links of this week :

I hope you'll find this links interesting.

I just passed the SCJP exam !

I'm happy to say that I passed the Sun Certified Java Programmer for Java SE 6.0 this morning :)

I passed the exam with 93%. I'm really happy of my score.

To prepare this exam, I read the SCJP Sun Certified Programmer for Java 6 Exam 310-065 and exercise the chapters for which I wasn't good enough.

So i started my exam this morning at 8.30 (Switzerland time) and after 2 hours of work, I was happy to see my score and to rest my poor brain.

So now i'm waiting of the certificate sended by post.

Java 7 : More dynamics

Like you know (or perhaps not, nevermind), the Java bytecode doesn't support dynamic method invocation. There are three supported invocations modes : invokestatic, invokespecial, invokeinterface or invokevirtual. These modes allows to call methods with known signature. We talk of strongly typed language. This allows to to make some checks directly at compile time.

On the other side, the dynamic languages use dynamic types. So we can call a method unknown at the compile time, but that's completely impossible with the Java bytecode. The dynamic languages based on the Java Runtime must use Java Reflection to make dynamic invocations.

In Java 7, we'll see a new feature, the JSR 292. This JSR add new method invocation mode : invokedynamic. With that new bytecode keyword, we can call method only known at runtime.

Read more…

Java Links of the week

I will try to reference my personal best of links about Java, Swing, ... every week at monday.

Here is the most interesting links i found about Java Programming this week :

And just for pleasure, my favourite April fools :

I hope you will find this compilation interesting.

Java 7 : The new java.util.Objects class

In Java 7, we'll see a new class : java.util.Objects. This class contains 9 static methods to work on Objects. I found these methods really useful.

First, two really simple methods to assert non-null objects in getter/setter (or other methods, of course) :

  • T nonNull(T obj) : If obj is not null, return obj else throw a NullPointerException.
  • T nonNull(T obj, String message) : If obj is not null return obj else throw a customized NullPointerException with the given message

Some simple examples :

public void setFoo(Foo foo){
    this.foo = Objects.nonNull(foo);
}

public void setBar(Bar bar){
    this.foo = Objects.nonNull(bar, "bar cannot be null");
}

Although simple, these methods can improve the readability of code and avoid having to write the is-null check ourselves.

Then, we have two methods to compute a toString() value for Object supporting null objects :

  • String toString(Object o) : Return the toString() value of a non-null object otherwise "null".
  • String toString(Object o, String nullDefault) : Return the toString() value of a non-null object otherwise return nullDefault

Again, this is useful for code readibility :

public class Bar {
    private Foo foo;
    private Bar parent;

    @Override
    public String toString(){
        return "Bar {foo = " + Objects.toString(foo) + ", parent = " + Objects.toString(parent, "no parent, orphan") + "}";
    }
}

I think, it's a lot better than :

public class Bar {
    private Foo foo;
    private Bar parent;

    @Override
    public String toString(){
        return "Bar {foo = " + (foo == null ? "null" : foo.toString()) + ", parent = " + (parent == null ? "o parent, orphan" : parent.toString()) + "}";
    }
}

Isn't it ?

After that, we also two similar methods for hashing :

  • int hash(Object... values) : Compute a hash code for all the given values
  • int hashCode(Object o) : If 0 is null return 0 othewise return o.hashCode()

If we take again the exemple of the Bar class. If we have to write the hashCode() method without Objects, we could do that :

public class Bar {
    private Foo foo;
    private Bar parent;

    @Override
    public int hashCode(){
        int result = 17;

        result = 31 * result + (foo == null ? 0 : foo.hashCode());
        result = 31 * result + (parent == null ? 0 : parent.hashCode());

        return result;
    }
}

With Java 7, we only have to do that :

public class Bar {
    private Foo foo;
    private Bar parent;

    @Override
    public int hashCode(){
        return Objects.hash(foo, parent);
    }
}

And that's it :)

On the same model, we've also two methods for equality checks :

  • boolean equals(Object a, Object b) : Return true if the two arguments are null or they are both not null and a.equals(b) return true, otherwise false.
  • boolean deepEquals(Object a, Object b) : Almost the same as the first method except that if both a and b are arrays, the equality is evaluated using Arrays.deepEquals method.

Once again, that can really ease the coding of equals() methods :

public class Bar {
    private Foo foo;
    private Bar parent;

    @Override
    public boolean equals(Object obj){
        if (obj == this) {
            return true;
        } 

        if (obj instanceof Bar) {
            Bar other = (Bar) obj; 

            if (foo != other.foo) {
                if (foo == null || !foo.equals(other.foo)) {
                    return false;
                }
            } 

            if (parent != other.parent) {
                if (parent == null || !parent.equals(other.parent)) {
                    return false;
                }
            } 

            return true;
        } 

        return false;
    }
}

become :

public class Bar {
    private Foo foo;
    private Bar parent;

    @Override
    public boolean equals(Object obj){
        if (obj == this) {
            return true;
        } 

        if (obj instanceof Bar) {
            Bar other = (Bar) obj; 

            return Objects.equals(foo, other.foo) && Objects.equals(parent, other.parent);
        } 

        return false;
    }
}

Better, no ?

And the last one :  int compare(T a, T b, Comparator<? super T> c). This method returns 0 if a == b or if both are null otherwise c.compare(a, b). The support of null is delegated to the comparator.

We've covered all the features offered by this new class.

Of course, there is already some methods like that in librairies like Jarkarta Commons or Google Guava, but it's always better when we doesn't have to include a library for that kind of features.

I hope you found this post interesting.

NIO.2 : The new Path API in Java 7

In Java 7 we'll see a new API to manipulate file paths. This is part of the NIO.2 API.

Instead of using the class java.io.File to manipulate a file of the file system of the computer we will now use the java.nio.file.Path class to manipulate a file in any file system (FileSystem). This FileSystem can use any storage place (FileStorage). To support several implementations, this new API is based on factories. With that, you doesn't have to care about the real implementation.

Read more…

4 reasons i'm not using Osmorc anymore

After had many problems using Osmorc, the Intellij Idea plugin for OSGi support, i decided to no longer use it. Now, i make all manually.

I have several reasons to not be satisfied of this plugin.

First of all, this plugin display all the errors in OSGi configuration (Manifest, Activators and imports) but provide no way to quickly fix the problems by example by adding the imported package in the Import-Package Manifest Headers. Its a little disappointing when we are regular with Intellij Idea usage.

I find it really slow to launch OSGi Instances. Moreover, we cannot really control the osgi instance we launch. I hoped that we could at least manage the OSGi server using basic command line integration, but this is not possible.

When we make the project, all the OSGi modules are compiled and packaged and this could be a long process. During this process, when we have errors, the displayed messages aren't really understandable and there is no explanation on how to solve the problems.

And last but not least, the plugin is very unstable. I had a lot of errors using Osmorc. And i had also problem with the imports in Maven projects. All the imports we marked invalid and sometimes not recognized. Reimporting the maven projects solve occasionally the problems but it always reappears and make the compilation impossible.

I don't solved any of these problems and for that reasons i don't use Osmorc anymore.

I realized that this plugin doesn't offer me a lot of things and i could easily work without it.

OSGi 4.2 Entreprise Release is available !

Yesterday, at EclipseCon, the OSGi EEG has finished the OSGi 4.2 Entreprise Release and made it publicly available. You can downlad it here.

The news includes several new Entreprise use-cases and improves the OSGI programming model. Some JEE technologies has been add to the OSGi specification.

Here is an overview of the main new features :

  • Blueprint : This is a standard based on Spring-DM. Like this last, it adds an IOC container to OSGi. It's reallay more comfortable to develop OSGi bundles with Spring DM and now, that's the standard. I think this a great news for the OSGi developers. With that new features, the developer can use the IOC container without binding the application to a specific container.
  • Framework Launching : If you wanted to embed an OSGi framework in your application, before this release, you needed to choose one implementation and bind your launching to this implementation. Now OSGi provides a a standard way to start an OSGi Framework.
  • Remove Services (and Admin) : Previously Distributed OSGi, this functionality enables your services to be distributed to remote consumers and enables your bundles to consume remote services. Your remote services doesn't need to implement a specific interface, you just have to configure some properties to make your services remote.
  • Web Applications : This is a standard way to deploy war files in an OSGI Framework. In the past, we can already do that with PAX-Web by example, but that was not standard. This adds several Manifest Headers (context path by example) and give a way to the web application to communicate with the others bundles.
  • JDBC specification : Adds a simple DataSourceFactory class to register the drivers and APIs to get these drivers and DataSource. So you don't need anymore to use complicated private packages to make your JDBC Driver work in your OSGi bundle.
  • JPA : Describes a way to use JPA from an OSGi application. That alllows you to update JPA implementation without restarting it and you can have several JPA Providers in the same system. This specification works in pair with the JDBC specification we talked above.
  • JNDI : Simple bridge between the OSGi Service Registry and JNDI. Now you can lookup BundleContext or OSGi Service with JNDI. And you can also obtain a JNDI Initial context from OSGi. Your JTA Implementation will be discovered and also appeared in the Service Registry.
  • JMX : With this specification you can access to OSGi Framework with JMX. You can install, uninstall, start and stop a bundle and get informations about the installed bundles and services.

The main purposes of this Enterprise Release is to make the deploy of OSGi Framework in enterprise environment easier. But these features can of course also be used in not-enterprise environment.

Bundle non-OSGi dependencies with Maven

When we work with OSGi, a problem we always have is how to work with dependencies non OSGi Ready.

This is not a really great problem because there we can work with. There is essentially two solutions :

  • Embed the JAR files within the bundle. That is to say putting the JAR file into the bundle JAR and reference it in the Manifest
  • Wrap the JAR files with an OSGi Manifest. Namely, transform the JAR into an OSGi bundle.

Personnaly, i doesn't like the first solution, because for me, having a jar into a jar sounds really weird and bad and i prefer to have real OSGi Bundle. With wrapping, if i need this library in an other bundle, i doesn't have to do anything.

Read more…

Mock objects with EasyMock

1. Introduction

The mock objects allows to make unit tests on objects depending on other objects. We will replace this dependencies with mock objects. With that, we can by example verify than the method xyzzy() has been called 5 times and returned 33. That can be practical in a several cases. By exampe, if the object to mock is slow or undeterministic (depending on time, or why not on the weather). This objects are really difficult to test because we can make a lot of tests but we could never find the special cases. Test cases with mock objects enable us to test this cases.

Read more…