Category Archives: Java

JAVA_OPTS, how to use them

For most of you this is probably a very silly post, but after five years of experience I was still shocked by something about the infamous JAVA_OPTS, also known as the “-D” system properties… -Dkey=value

JAVA_OPTS is only the name under which some applications, servers, etc… group a few of these -Dkey=value properties to be passed into Java when it gets executed.

You can always pass them directly from the command-line or whatever script you’re using to trigger the execution of your program. Even combine some of them inside a JAVA_OPTS environment variable and some others outside of it.

But there are certain rules you must respect when using them, as I learnt today. I wrote a silly Java class which prints out the values for three properties that it expects with certain names, and I called this class on many different manners.

This is the (simplest) class (ever):

public class JavaOpts101 {
    public static void main(String[] args) {
        System.out.println("Property 2: " + System.getProperty("property1"));
        System.out.println("Property 2: " + System.getProperty("property2"));
        System.out.println("Property 3: " + System.getProperty("property3"));
    }
}

These are the results:

Doing it right, using JAVA_OPTS:

computer$ JAVA_OPTS="-Dproperty1=value1 -Dproperty2=value2 -Dproperty3=value3"
computer$ java $JAVA_OPTS JavaOpts101
Property 1: value1
Property 2: value2
Property 3: value3

Doing it right, without grouping them in JAVA_OPTS:

computer$ java -Dproperty1=value1 -Dproperty2=value2 -Dproperty3=value3 JavaOpts101
Property 1: value1
Property 2: value2
Property 3: value3

Doing it right, grouping two and passing the third one:

computer$ JAVA_OPTS="-Dproperty1=value1 -Dproperty2=value2"
computer$ java $JAVA_OPTS -Dproperty3=value3 JavaOpts101
Property 1: value1
Property 2: value2
Property 3: value3

So how do you do it wrong?
Basically, you need to be passing the properties in the wrong place, like this:

computer$ JAVA_OPTS="-Dproperty1=value1 -Dproperty2=value2"
computer$ java $JAVA_OPTS JavaOpts101 -Dproperty3=value3
Property 1: value1
Property 2: value2
Property 3: null

Even if they are grouped on JAVA_OPTS, they won’t be correctly passed unless they go before the class name…

computer$ JAVA_OPTS="-Dproperty1=value1 -Dproperty2=value2 -Dproperty3=value3"
computer$ java JavaOpts101 $JAVA_OPTS
Property 1: null
Property 2: null
Property 3: null

A little bit of documentation:

If you do man java on your command-line and have a read, apart from discovering a new spelling for impletmentations (sic), you’ll get something along this:

SYNOPSIS
  java [ options ] class [ argument... ]

  java [ options ] -jar file.jar
    [ argument... ]
...
...
OPTIONS
...
...
  -Dproperty=value
    Sets a system property value.

A couple of caveats:

Notice that you only need to use the quotes when you group the system properties under an environment variable (in these examples, JAVA_OPTS), but you don’t need to use the quotes when the properties are passed directly on the command line.
It may be worthy to note here: the order in which the properties are passed among themselves is irrelevant.

The code is on Github, even if it’s completely silly :/

Ceki Gulku on SLF4J and logback

I suppose you all know who Ceki Gulku is, but you may not have seen him explaining some aspects about some of his creations. I quite liked this talk, even if it’s five years old… after all, it’s not like logging frameworks have evolved too much anyway since then.

Log4j 2.0 seems to be gaining followers even if it’s still a beta… but for me, SLF4J with Logback still makes the trick, and this guy was massively involved on both projects.

If you feel like the topic deserves an hour of your time, don’t think it twice. Enjoy.

 

Updating your old SCJP X to the new shiny OCPJP 7

As you can read here, the only thing you need to do (if you have one of the old SCJP’s) is an upgrade exam (1Z0-805), focused mostly on the new bits added on Java 7. I’ve created a repository on Github with code examples that I’ve been gathering during my preparation.

upgrade Path

upgrade Path

I’ll upload as well at some point a pdf with some study annotations that I think may be useful to others.

I know plenty of you are very sceptical about certifications but I still think they are quite useful. If not per se, the process (meaning the study + work) you need to go through to get them it certainly is. I’ll be writing a post on this at some point as well.

Java 7 try-with-resources explained

While it is widely accepted than checked exceptions on Java wasn’t the brightest idea, when Java 7 came out there were a couple of things added regarding them that supposedly were going to make our lives easier. Catching multiple exceptions at the same time is easy enough, and I definitely think it is a straight forward and direct improvement. The other bit added, try-with-resources, looked like a good idea to me too, but I didn’t really know much about it until very recently, when I had a more careful look at the existent documentation an tried to get my head over it. In order to do that, I quickly wrote a few classes to illustrate the different possible scenarios depending on the place where an exception can be thrown.

Let’s have a look at the simplest scenario, where no exceptions are thrown.

public class NoExceptionsThrown {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, false, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

As you see, now you can declare and initialize some resource when writing your try. In this case, I am creating a resource of a custom class MyResource (which we’ll see in a moment), doing something with it, anyGivenAction(), and closing it. Before we get into many details, let me tell you the first bit I didn’t like about this: it was easier to refer to the different elements of an exception code snippet before… you could say the try, the catch or the finally and everybody would know what you’re talking about. Now it is a little bit more complicated: whereas the catch and the finally remain unaltered, the try now has two different “locations”: the resource area and the body of the try, the classic try, let’s say… no big deal, really, but still, old way of naming comes a bit short. For example, the connotations of an exception being thrown on the resource initialization area or on the body of the try are quite different.

But it gets worse. Let’s have a closer look to the resource area of the try…

   ...
        try (MyResource resource = new MyResource(false, false, false)) {
            resource.anyGivenAction();
        }
   ...

The only requisite for a resource to be declared there, as described on official Oracle documentation:

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Let’s have a look at MyResource class:

class MyResource implements AutoCloseable {

    private boolean throwOnInitResource;
    private boolean throwOnAction;
    private boolean throwOnCloseResource;

    MyResource(boolean throwOnInitResource, boolean throwOnAction, boolean throwOnCloseResource) throws InitResourceException {
        this.throwOnInitResource = throwOnInitResource;
        this.throwOnAction = throwOnAction;
        this.throwOnCloseResource = throwOnCloseResource;
        if (this.throwOnInitResource) throw new InitResourceException();
        System.out.println("Resource opening, no exception.");
    }

    public void anyGivenAction() throws ActionException {
        if (this.throwOnAction) throw new ActionException();
        System.out.println("Any given action happening, no exception.");
    }

    public void close() throws CloseResourceException {
        if (this.throwOnCloseResource) throw new CloseResourceException();
        System.out.println("Resource closing, no exception.");
    }
}

It implements AutoCloseable interface as it implements the close() method specified by it. The other methods on the class are the constructor and anyGivenAction(), a dummy example of specific business logic for the class. The three boolean flags received on the constructor will control if an exception is thrown on any of the three methods of the class: while constructing, while executing anyGivenAction() or while closing the resource respectively. Every exception thrown is named after the place where it is thrown. This will be useful later on.

So why did I say it gets worse?… well, the finally section is intended to be used to close any resource open after the code that can thrown an exception uses it. But in the new try-with-resource, closing the resources happen automatically if they were declared on the resource area. So the resource area contains an implicit finally now, apart from being used to declare and initialized the resources to be used on the body of the try. You can have, also, an explicit finally in which wrap up anything not explicitly declared or initialized on the resource area of the try. See?, it got worse.

Let’s revisit the simplest case, where no exception is thrown anywhere:

public class NoExceptionsThrown {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, false, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

As the class is initialized with three false flags, no exception will be thrown within any of the three methods of MyResource. Let’s see the output of this program when run:

Resource opening, no exception.
Any given action happening, no exception.
Resource closing, no exception.
At the finally

The catch is not visited, obviously, and the explicit finally is happening in the end, as expected. MyResource object declared on the resource area gets initialized and closed automatically, and in between, anything on the body of the try will happen. In this case, anyGivenAction(). Expected behaviour so far, nothing strange.

If an exception is thrown now by the code inside the catch, it would make no difference, since that section wouldn’t be visited. What happens if an exception is thrown inside the explicit finally, though?

public class OnlyFinally {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, false, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
            throw new FinallyException();
        }
    }
}

Output would be:

Resource opening, no exception.
Any given action happening, no exception.
Resource closing, no exception.
At the finally
Exception in thread “main” trywithresources.exceptions.FinallyException
at trywithresources.OnlyFinally.main(OnlyFinally.java:17)

Nothing unexpected here either. But let’s have a look at the different cases of an exception being thrown while inside MyResource, and see how they combine with exceptions being thrown on the catch and the explicit finally. It can get really funny, bear with me here…

The simplest case is when we get an exception while initializing MyResource:

public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(true, false, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

The first true argument when building MyResource will trigger the exception on construction. In that case the exception is caught in the catch:

Catching class trywithresources.exceptions.InitResourceException
At the finally

What happens if the exception is thrown within the body of the try, though?

public class OnlyAction {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, true, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

In this case an exception is thrown on anyGivenAction(), have a look at the second argument true on MyResource construction. The output would be:

Resource opening, no exception.
Resource closing, no exception.
Catching class trywithresources.exceptions.ActionException
At the finally

Before we get into the catch code that will handle the exception, try-with-resource ensures that the resource is closed. The implicit finally code has executed before the catch, as expected, same as in Java 6.

What if an exception is thrown on the implicit finally, when closing the resource then?

public class ActionAndClosing {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, true, true)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

When run, the output would be:

Resource opening, no exception.
Catching class trywithresources.exceptions.ActionException
At the finally

Wait, what?! Didn’t you just say that we were going to throw an exception while closing the resource?, yes. Doesn’t that happen after we throw the exception on the body of the try, but before it gets treated on the catch?, yes. Isn’t it supposed to be treated on the catch, instead of the ActionException thrown on anyGivenAction() then?, well, you would think so… but no. The CloseResourceException thrown on the implicit finally gets suppressed. When confronted with more than one exception being thrown, the compiler is able to distinguish the important one, let’s say… the one that happened during the business logic being executed within the body of the try, instead of the one being thrown within the implicit finally of the try-with-resources, where you are just closing the resource. If you still want to know about the suppressed exceptions, you can get them from the one that was finally thrown:

public class ActionAndClosingSuppressedInfo {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, true, true)) {
            resource.anyGivenAction();
        }
        catch (Exception exceptionThrown) {
            System.out.println("Catching " + exceptionThrown.getClass());
            for (Throwable exceptionSuppressed: exceptionThrown.getSuppressed()) {
                System.out.println("Suppressed: " + exceptionSuppressed);
            }
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

Output of this:

Resource opening, no exception.
Catching class trywithresources.exceptions.ActionException
Suppressed: trywithresources.exceptions.CloseResourceException
At the finally

It kind of makes sense than the exception officially being thrown is the one happening on the body of the try, instead of the one happening on the implicit finally. The problem is that this behaviour is completely opposed to the one we got if the exception is being thrown on the explicit finally area. As you may remember from Java 6 lost exception problem, when an exception is thrown in there, it doesn’t really matter if you had an exception or not being thrown in the body of the try, or even in the catch for what it’s worth, the only and final exception being thrown would be the one on the explicit finally. So, for example, in the scenario where you have an exception being thrown on anyGivenAction(), while closing the resource, even when catching the exception and on the explicit finally:

public class AllButOpening {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, true, true)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
            throw new CatchException();
        }
        finally {
            System.out.println("At the finally");
            throw new FinallyException();
        }
    }
}

Output is:

Resource opening, no exception.
Catching class trywithresources.exceptions.ActionException
At the finally
Exception in thread “main” trywithresources.exceptions.FinallyException
at trywithresources.AllButOpening.main(AllButOpening.java:19)

A behaviour which is consistent with the Java 6 exception treatment but it’s opposed to what Java 7 does on try-with-resources implicit finally.

I suppose that what they’ve tried to do with the suppressed exceptions is precisely fix Java 6 problem when you literally lose an exception if another is thrown on the explicit finally.

It seems to me a half-way solution for a problem that should never has been there anyway, quite incoherent with the previous version of the language to say the least.

I’m really sorry about the extension of the post, but certain level of detail was necessary to illustrate the different outcomes of the possible cases. I hope you found it useful.

Ways to check if a String is null and if it’s not, if it’s blank

Quick clarification: the empty String is “”. ” ” is not considered an empty String, but it’s a blank one. If it contains nothing but whitespace characters, it’s a blank String.

If you don’t want to use any third-party libraries, you should do it the long way:

if((s != null) && (!s.trim().equals(""))

If you don’t mind bringing over a third party library into your project classpath, you have a couple of clear options.

With Apache Commons Library:

if(StringUtils.isEmpty(s))

Or:

if(StringUtils.isBlank(s))

The difference between the first and the second being in the fact that isEmpty(s) will return false if s is a String composed of spaces, like ”   “, whereas isBlank(s) will detect that case and return true for it. Doing isEmpty(s.trim()) would skip that problem, but it would create a new (and unnecessary) String object.

With Guava:

if(Strings.isNullOrEmpty(s.trim()))

In this case, doing trim() is necessary, since the method isNullOrEmpty does not return true if it does not receive the empty String.

Skipping tests when doing “mvn install”

First things first: you should NOT be skipping tests when building your projects. 9 out of 10 cases, you shouldn’t. But when you must / have to / want to do it: after spiking what it looked like a quick solution to a little problem and it turned out to be a massive refactoring during which you broke so many tests it would not be worthy to fix them unless the original problem is really flushed away… possibly the most typical scenario where you would want to do something like this. Well, in that case, you can do:

mvn -DskipTests=true install

or the more lazy version:

mvn -DskipTests install

Or you can do:

mvn -Dmaven.skip.test=true install

or the more lazy version:

mvn -Dmaven.skip.test install

Difference between the first and the second is that the first one is less horrible. Let me explain… both versions will not run any of your tests classes, but at least the first one won’t succeed if they don’t compile. So, if you’ve broken your tests but at least you changed your source code well enough to maintain compilation errors away on your test classes, you can get away with the first command. But if you incurred in compilation errors on your test classes while changing your code, you may want to go for the second command, which not only it will ignore your tests but it won’t even attempt to compile the test classes.

If having to run the first command is already a sign that you’ve not been doing the important things (TDD, for instance) right, running the second means you can’t even use your IDE correctly (refactoring, anyone?).

[Learnt at work, from a colleague]

[Reference]

Eclipse template to insert test methods should-given-when-then

(originally posted on StackOverflow)
I saw a similar version to this one recently while pair programming with a very a good developer and friend, and I think it could be a nice addition to this list.

This template will create a new test method on a class, following the Given – When – Then approach from BDD paradigm on the comments, as a guide for structuring the code. It will start the method name with “should” and let you replace the rest of the dummy method name “CheckThisAndThat” with the best possible description of the test method responsibility. After filling the name, TAB will take you straight to the // Given section so you can start typing your preconditions.

I have it mapped to the three letters “tst”, with description “Test methods should-given-when-then” 😉

I hope you find it as useful as I did when I saw it:

@Test
public void should${CheckThisAndThat}() {
    Assert.fail("Not yet implemented");
    // Given
    ${cursor}

    // When

    // Then

}${:import(org.junit.Test, org.junit.Assert)}

About unicode and character sets

Every single developer should read this article by Joel Spolsky. It is a bit old but still a must.

By the way, I got there browsing a bit after seeing this solution for a classical problem, retrieving Chinese characters from a form and storing them in a database. Thanks Spring for charsetFilter.

Java BigDecimal comparison

Why BigDecimal?, wasn’t it enough with all the previous numeric types to represent all the possible values?

No. When it comes to manage currency values, BigDecimal is the only class accurate enough to deal with them.

Anyway, this post is about its comparison, which may be very tricky. We’re used to the .equals method, so we may be tempted to use it to compare BigDecimal objects. Well, don’t. It does not work.

So what do we do to compare BigDecimal values a and b?, we must use the .compareTo() and .signum() methods.

 a.compareTo(b);  // returns (-1 if a < b), (0 if a == b), (1 if a > b)
 a.signum(); // returns (-1 if a < 0), (0 if a == 0), (1 if a > 0)

There you go 😉