GDocx 3.0.0 released

GDocx, the fluent interface to the Docx4J library, version 3.0.0 has been released.

What’s new ?

GDocx now uses the latest (3.0.1) Docx4j version.

Other changes includes replacement of Fest Assert with the AssertJ library which is more flexible and powerful.

All files, including source and javadoc can be downloaded from the project home at the https://java.net/projects/gdocx

Review: Jboss as 7 Development

Jboss as 7 Development
Jboss as 7 Development by Francesco Marchioni
My rating: 4 of 5 stars

Good introduction and overview of Java EE 6 development using JBoss as application server.

Some chapters are dedicated to the installation, management, clustering and
security configuration of a JBoss application server.

The rest of the book (the greater part) is dedicated to Java EE6 development
topics: EJB, CDI, JMS, Soap and RESTful web-services.

There is also a chapter on unit and integration testing (with Arquillian).

The book is well written and with good explanations, even if some topics are only mentioned.

Suggested to everybody interested in starting to work with Java EE6 and JBoss AS 7.

View all my reviews

Tutorial: how to create a JUnit test method template in NetBeans

NetBeans has a very nice feature: code templates.

Let me show how I use it to add a new JUnit test method in the test classes.

Go to Tools → Options → Editor → Code Templates and add the following template:

Abbreviation: te (this is only my proposal)

Expanded text:

@${baseType type="org.junit.Test" default="Test" editable="false"}
public void ${cursor}() {
    // given

    // when

    // then

}

2014-03-05_pic01Then go to a test class, type “te” (our template abbreviation) and press the TAB key.

See what’s happen:

2014-03-05_pic022014-03-05_pic03

First, the org.junit.Test include has been added (if not already in). This is thanks to the ${baseType} instruction we added in the template.

Second, the prompt is waiting for you for the method name. See ${cursor} instruction in the template.

Just write the name and we have complete test method template in our class.

2014-03-05_pic04

Of course, the template can be adjusted to your needs and habits.

Benefits:

  • we code faster
  • we have more uniform code style

NetBeans code template syntax is (partially) documented here.

Tutorial: using Lombok to reduce boilerplate code in Java

Lombok (http://projectlombok.org) is a very useful Java annotation library which help us to:

  • reduce boilerplate code
  • code faster
  • avoid stupid errors like forgetting the getter and setter for a new added field.

Lombok can create getter, setters, toString, constructor, equals and hashCode methods automatically. You just need to write the class and add the fields.

Lombok provides several annotations (see http://projectlombok.org/features/index.html for the complete list) but, in my projects, I usually use few of them and, in this tutorial I will show which and why.

To better show Lombok benefits, let’s start with a very simple (Maven based) project. You can find complete project source code here.

We should first define Lombok Maven dependency in the pom.xml file:

 <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.12.4</version>
    <scope>provided</scope>
</dependency>

Important: scope should be provided because we do not want Lombok jar file to be included in our build file.

Let’s now add to a project a very basic class without using any Lombok annotations.


public class WithoutLombokAnnotations {
    private boolean flag;
    private final int number;
    private final String text;
    private List<String> strList;

    public WithoutLombokAnnotations(int number, String text) {
        this.number = number;
        this.text = text;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public List<String> getStrList() {
        if (strList == null) {
            strList = new ArrayList<>(128);
        }
        return Collections.unmodifiableList(strList);
    }

    public void setStrList(List<String> strList) {
        this.strList = strList;
    }

    public int getNumber() {
        return number;
    }

    public String getText() {
        return text;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 11 * hash + this.number;
        hash = 11 * hash + Objects.hashCode(this.text);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final WithoutLombokAnnotations other = (WithoutLombokAnnotations) obj;
        if (this.number != other.number) {
            return false;
        }
        if (!Objects.equals(this.text, other.text)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "WithoutLombokAnnotations{" + "flag=" + flag + ", number=" + number + ",
            text=" + text + '}';
    }
}

Comments on the above code:

  • The class has four fields, two of them are final so we need a constructor.
  • The flag field is a boolean so the getter is named isFlag() and not getFlag()
  • The strList getter method initialize the list if necessary
  • The strList is not included in the toString method
  • Equals and hashCode are calculated on number and text fields only.

A lot of boilerplate code for a very simple class.

Let’s reduce it with the help of Lombok annotations.

GETTER and SETTER

First step: the getters and setters (http://projectlombok.org/features/GetterSetter.html). In our example, all of them are very simple and standard except the strList getter. We can use Lombok’s @Getter and @Setter annotations to remove all standard getters and all setters from our code and have Lombok to generate them during compilation.

Our class code becames:

@lombok.Getter
@lombok.Setter
public class GettersAndSetters {
    private boolean flag;
    private final int number;
    private final String text;
    private List<String> strList;

    public GettersAndSetters(int number, String text) {
        this.number = number;
        this.text = text;
    }

    public List<String> getStrList() {
        if (strList == null) {
            strList = new ArrayList<>(128);
        }
        return Collections.unmodifiableList(strList);
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 11 * hash + this.number;
        hash = 11 * hash + Objects.hashCode(this.text);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final GettersAndSetters other = (GettersAndSetters) obj;
        if (this.number != other.number) {
            return false;
        }
        if (!Objects.equals(this.text, other.text)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "WithoutLombokAnnotations{" + "flag=" + flag + ", number=" + number + ",
            text=" + text + '}';
    }
}

Great. Same functionality and 18 lines of code removed. We left in the code the strList getter because it has non standard functionality.

By using Lombok’s @Getter and @Setter annotation at class level we ask Lombok to generate getter and setter for all non-static fields. Of course final fields will not have setters.

@Getter and @Setter annotations can be placed at class level (like in the example) and at field level.

I usually prefer to use Lombok annotations at class level for two reasons: to not forget to add proper annotations when I add new fields in the class and to avoid to clutter class code with too many annotations (at fields level; see for example when you are using Lombok in JPA entity classes).

 

CONSTRUCTORS

Second step: the constructor (http://projectlombok.org/features/Constructor.html). By adding the @lombok.RequiredArgsConstructor annotation at class level, we can remove the 4 lines of the constructor.

Lombok has three different annotations for the constructors:

  • @RequiredArgsConstructor, the one we used in the example, generates a constructor for all final fields, with parameter order same as field order
  • @NoArgsConstructor creates an empty constructor.
  • @AllArgsConstructor creates a constructor for all fields

 

HASHCODE and EQUALS

Third step: the hashCode and equals methods (http://projectlombok.org/features/EqualsAndHashCode.html). In the example we have created these methods using the number and text fields.

By adding the @lombok.EqualsAndHashCode(of = {“number”, “text”}) annotation we can remove Equals and HashCode methods, going down by other 26 lines of code. And Lombok also generates the canEqual method. See here (http://www.artima.com/lejava/articles/equality.html) for the reasons.

Important: never use @lombok.EqualsAndHashCode without specifying the fields. Always use the of parameter (or the opposite exclude parameter). Without parameters, @lombok.EqualsAndHashCode will use all fields, possibly creating heavy equals and hashCode methods.

 

TOSTRING

Last step is to use @lombok.ToString (http://projectlombok.org/features/ToString.html) to implement the toString method. While having a toString method is highly suggested (for ex. for debugging and analysis purposes), my usual approach is to avoid collections and arrays fields in the toString method to avoid cluttering logs and messages windows with too long text lines.

After all our changes, the original class is now:

@lombok.Getter
@lombok.Setter
@lombok.RequiredArgsConstructor
@lombok.EqualsAndHashCode(of = {"number", "text"})
@lombok.ToString(exclude = "strList")
public class EveryThing {
    private boolean flag;
    private final int number;
    private final String text;
    private List<String> strList;

    public List<String> getStrList() {
        if (strList == null) {
            strList = new ArrayList<>(128);
        }
        return Collections.unmodifiableList(strList);
    }
}

Very short and with just the relevant code shown: the fields and the custom getter. No boilerplate code. Exactly what we were looking for.

LOGGING

Another quite useful Lombok annotation is related to logging (http://projectlombok.org/features/Log.html): Lombok can create a Logger field, named log, in our class. There are six variations of the annotation depending on the logging framework (java, apache, log4j, slf4j,,,).

The logging annotation does not reduce the amount of code in our class (one line for the annotation vs. one line for the manual logger definition) but it can help us to guarantee that we are using the same logging framework among all project classes. In some projects with large teams, I’ve found different logging frameworks used simply because different programmers were using IDE auto-complete functions in a different way.

Having something like

@Slf4J
public class ….

help us to use the same logger on all the class files.

@DATA

The @lombok.Data annotation (http://projectlombok.org/features/Data.html) is a short version for @Getter @Setter @EqualsAndHashCode, @ToString and @RequiredArgsConstructor.

At first glance it looks very convenient (one annotation instead of five) but, unfortunately, we cannot specify the fields for @EqualsAndHashCode and @ToString so it is not a good idea to use the @Data annotation unless the class is really a very simple POJO, without complex fields.

Moreover @Data does not generated automatically a no args constructor, required by JavaBeans and XML conversions so a @NoArgsConstructor annotation is also needed.

SUGGESTIONS

Lombok is very useful to reduce boilerplate code but it is important to keep in mind what Lombok is doing on our code to avoid useless and heavy generated code.

My personal suggestions:

  1. Always specify the fields you want in @EqualsAndHashCode or, in another words, never use the default @EqualsAndHashCode behaviour (all fields). Very important if the class is a JPA entity, where generated ID field should not be used for equality.
  2. Always exclude heavy fields (collections, arrays) in @EqualsAndHashCode and @ToString unless it is really necessary.
  3. Use @NoArgsConstructor when an empty constructor is needed (like for XML conversions and in JavaBeans)
  4. Never use Lombok @Data. As mentioned before, with the @Data annotation we cannot specify the fields for @EqualsAndHashCode and @ToString (see previous suggestions).
  5. On JPA entities:
    @EqualsAndHashCode: exclude generated @Id fields (persistence equality constraint: a generated ID field is not always defined during entity life-cycle.)
    @ToString: exclude other JPA entities and relationship to reduce method weight and avoid unexpected persistence problems like lazy initialization exceptions.

 

FINDBUGS and PMD

FindBugs works well with Lombok because it analyses the compiled code, so after Lombok.

On the contrary PMD, which analyses the source code, does not work well. I suggest to add a @SuppressWarnings(“PMD”) annotation at class level to tell PMD to completely skip the class. See here (http://pmd.sourceforge.net/pmd-5.1.0/suppressing.html) for more details.

 

DELOMBOK

Lombok provides a “delombok” (http://projectlombok.org/features/delombok.html) function so we can look at the code is really compiled, after Lombok processing.

We should open a terminal window, go to the project root dir and run the following command:

java -jar <path_to_lombok.jar> delombok src -d src-del

where

  • <path_to_lombok.jar> is the path to the lombok jar file. Maven users can find it at <maven_repository>/org/projectlombok/lombok/<version>/lombok-<version>.jar
  • src is the name of source dir (Maven default)
  • src-del is a name of the dir where we want delombok to put all files.

Our delombok-ed file is

public class ToString {
    private boolean flag;
    private final int number;
    private final String text;
    private List<String> strList;

    public List<String> getStrList() {
        if (strList == null) {
            strList = new ArrayList<>(128);
        }
        return Collections.unmodifiableList(strList);
    }

    @java.lang.SuppressWarnings("all")
    public boolean isFlag() {
        return this.flag;
    }

    @java.lang.SuppressWarnings("all")
    public int getNumber() {
        return this.number;
    }

    @java.lang.SuppressWarnings("all")
    public String getText() {
        return this.text;
    }

    @java.lang.SuppressWarnings("all")
    public void setFlag(final boolean flag) {
        this.flag = flag;
    }

    @java.lang.SuppressWarnings("all")
    public void setStrList(final List<String> strList) {
        this.strList = strList;
    }

    @java.beans.ConstructorProperties({"number", "text"})
    @java.lang.SuppressWarnings("all")
    public ToString(final int number, final String text) {
        this.number = number;
        this.text = text;
    }

    @java.lang.Override
    @java.lang.SuppressWarnings("all")
    public boolean equals(final java.lang.Object o) {
        if (o == this) return true;
        if (!(o instanceof ToString)) return false;
        final ToString other = (ToString)o;
        if (!other.canEqual((java.lang.Object)this)) return false;
        if (this.getNumber() != other.getNumber()) return false;
        final java.lang.Object this$text = this.getText();
        final java.lang.Object other$text = other.getText();
        if (this$text == null ? other$text != null : !this$text.equals(other$text)) return false;
        return true;
    }

    @java.lang.SuppressWarnings("all")
    public boolean canEqual(final java.lang.Object other) {
        return other instanceof ToString;
    }

    @java.lang.Override
    @java.lang.SuppressWarnings("all")
    public int hashCode() {
        final int PRIME = 277;
        int result = 1;
        result = result * PRIME + this.getNumber();
        final java.lang.Object $text = this.getText();
        result = result * PRIME + ($text == null ? 0 : $text.hashCode());
        return result;
    }

    @java.lang.Override
    @java.lang.SuppressWarnings("all")
    public java.lang.String toString() {
        return "ToString(flag=" + this.isFlag() + ", number=" + this.getNumber() + ", text=" +
            this.getText() + ")";
    }
}

Tutorial: license headers in NetBeans (reloaded)

An alternative solution to the native NetBeans license header management (see my previous post) is the “License Changer” plugin by nhoffmann available on NetBeans plugin portal (http://plugins.netbeans.org/plugin/17960/license-changer).

The plugin is based on license template concept. NetBeans installation includes several license templates (Tools → Templates) for the most popular Open Source licenses: 2014-02-25_pic01The plugin uses one of the available templates. If you have your own license file, you have to include it in the template list (but the plugin help on this).

NOTE: all custom license files will be saved in the NetBeans User Directory. You can have a look at the beginning of View → IDE Log for your real path.

With the plugin we can do more that native NetBeans solution except for one use-case: when you have a proprietary and project specific license. In this case NetBeans let us save the license file within the project (so all team members can use it) while, with the plugin, all licenses are stored in the user NetBeans installation (which is not shared across the team).

Let’s describe now the plugin.

After plugin installation, you can select a file or a package and apply “Change License Header” (see picture below).

2014-02-25_pic02A wizard starts. On the first page we can select the files types on which the plugin should operate on (see 1). Nice added feature is the possibility to change the line endings character (see 2).

2014-02-25_pic03

 

Second page of the wizard is the following:

2014-02-25_pic04

We can select the license from the template list (see 1) or browse the disk for a custom license file (see 2) which will be included in the template list by the plugin.

IMPORTANT: The checkbox “Set as default project license” (see 3) is very important. If checked, the plugin will save the selected license in the project configuration (the same used by native NetBeans solution). All new created files (including file types not supported by the plugin) will inherit the setting and they will have the correct license header.

After license selection:

2014-02-25_pic05The rest of the wizard is very simple.

NOTE: One little annoying problem with the plugin is that the selected license is not kept for the following plugin invocations.

Typical procedure :

  1. install the plugin
  2. run the plugin on a project file or package or folder,in order to include all existing project files
  3. use standard NetBeans File → New File procedure to create new project files

Tutorial: license headers in NetBeans

NetBeans has special support for the license headers we usually add at the begin of the source files for copyright messages and references to license agreement.

In the project properties we can find a dedicated section to license headers:

2014-02-18_pic01The “Use Global license” options let us choose among popular license header: Apache, GPL, MIT, NetBeans but in this tutorial we will create a custom license header.

First step is to create a file for our project license header. Let’s create a text file on the root of the project which will contain the text of the license header.

2014-02-18_pic02

2014-02-18_pic03

In this example, the file is named mylicense.txt and it is placed in the root of the project.

Now we open the mylicense.txt file to add some contents.

2014-02-18_pic04

The text is free but it should formatted as a comment (in my case I used the Java block comment: /* */ ).

Important: actually the syntax of the license file can be more complex than in our example because it is processed by a tool during the inclusion process. I will post a new tutorial on this topic.

Save the file and close the editor window.

Now we return to the project properties window to specify the path of our project specific license header:

2014-02-18_pic05

I used the variable ${project.basedir} which is the symbolic path to the project root dir. The window shows the preview of the license header.

Now, when we create a new file (in the example a new Java Class file), we have our template header in place:

2014-02-18_pic06

For the moment, there is no option in NetBeans to add the template header to an already existing file but I filled an enhancement request on this.

NetBeans plugin for file line endings

Nowadays it is common to work in a multi-platform (Windows, Linux, Mac) development environment and that means different file line endings characters.

To terminate text files lines, Windows uses two characters, CR (Carriage Return) and LF (Line Feed), while Linux and Mac OS X use LF character only and “old” Mac OS uses CR only.

Three platform, three combinations. We are not lucky.

NetBeans can handle all combinations, while opening and saving text files (.java, .html, .css, .php,….) but this is not necessarily the case for all developments tools we are using.

Best approach is to use just one and, we are now lucky, one plugin can help us.

The “Change Line Endings on Save” plugin can be found here and on NetBeans plugin portal.

Once installed, we can decide to have NetBeans or project based setup. Development teams should use project based setup so every developer uses the same configuration.

NetBeans based setup can be found on Tools → Options → Editor → Line Endings as in the following image:

2014-02-02 fig1Project based setup is available on project Properties page:

2014-02-02 fig2Note: project setup is saved in the nb-configuration.xml file (in the project root dir).