WildFly Swarm Project Generator

A few days ago, the WldFly Swarm team announced the release of the WildFly Swarm Project Generator.

WildFly Swarm Project Generator
WildFly Swarm Project Generator

The project generator allows you to select basic project properties (Maven Group ID and Artifact ID) and a list of dependencies for the project before creating a Maven project that can be downloaded and used from within your favorite IDE.

The list of dependencies is what makes this generator most useful to me. If you know the name of the dependency to add, or even a few letters from it, you can enter that in the dependencies field and the generator will automatically show the matching dependencies. For example, entering rs shows all the JAX-RS related dependencies.

WildFly Swarm Project Generator Dependencies
WildFly Swarm Project Generator Dependencies

Once you’ve configured the name and dependencies for the project, selecting the Generate Project button downloads a zipped Maven project that’s ready for use and which can be run via maven by executing

mvn wildfly-swarm:run

The WildFly Swarm Generator is an excellent tool that reduces the barrier to developing with WildFly Swarm. If you’re a Swarm user, I’d recommend trying this out.

Generating Random Numbers In Java

A stream of pseudorandom numbers can be generated in Java using the java.util.Random class. To generate a random integer, an instance of this class can be created and the the nextInt(int n) method returned as shown below:

import java.util.Random;

public class RandomGenerator {
  public static void main(String args[]) {

    Random random = new Random();
    for (int i = 0; i < 5; i++) {
      System.out.println(random.nextInt(10));
    }
  }
}
$ java RandomGenerator
2
9
5
8
4

In this code, the nextInt(int n) method takes a parameter as the upperbound for the random generated number. The random number is generated beyween 0 and n-1.
In addition to the nextInt(int n) methods, the Random class also has methods to return other primitives:

nextBoolean() – return the next random boolean
nextFloat() – returns the next random float in the range 0.0 to 1.0
nextDouble() – returns the next double in the range 0.0 to 1.0

When generating random numbers, it is good practice to instantiate the Random class as few times as possible as this helps to ensure that random numbers do not follow a pattern. The above code example shows this where the Random class is instanced outside of the for loop.

The Java 8 documentation for the java.util.Random class is available here.
The java.util.Random class is not considered secure for cryptographic work. Instead, the java.security.SecureRandom class is recommended for these scenarios.
Although the java.util.Random class is thread safe, it may have performance issues when used in a multi-threaded environment. To overcome these issues, it is recommended to use the java.util.concurrent.ThreadLocalRandom class instead.

Encoding / Decoding Java Classes as JSON Using Gson

With the rise in popularity of JavaScript client side frameworks such as AngularJS and Ember.js, returning and accepting JSON data from Java applications has become a much more common process. The Gson library allows conversion between Java objects and JSON in a very simple fashion.

Installing Gson

If you’re a Maven user, installing Gson is simply a matter of adding the appropriate dependency into your pom.xml file. If you’re not a Maven user, the Gson library can be downloaded from the project’s site.
To add the dependency to Maven, add the folllowing into your pom.xml:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.4</version>
</dependency>

A Simple Domain Object

To see how Gson can convert to and from JSON, we’ll use a simple Java class that represents a simple Blog post. The blog post has a title, a post date and an array of tags.

public class BlogPost {
    private String title;
    private Date postDate;
    private ArrayList&lt;String&gt;tags = new ArrayList();

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Date getPostDate() {
        return postDate;
    }

    public void setPostDate(Date postDate) {
        this.postDate = postDate;
    }

    public void addTag(String tag) {
        tags.add(tag);
    }

    @Override
    public String toString() {
        return "BlogPost{"
            + "title=" + title
            + ", postDate=" + postDate
            + ", tags=" + tags + '}';
    }
}

There’s nothing special about this class. There are no annotations required or interfaces that need to be implemented. The class is a basic POJO.

Serializing to JSON

To serialize an object to JSON, we need to instantiate an instance of the Gson object and invoke the .toJson() method of it.

BlogPost post = new BlogPost();
post.setTitle("A new blog post");
post.setPostDate(new Date());
post.addTag("Json");
post.addTag("Gson");
Gson gson = new Gson();
String json = gson.toJson(post);
System.out.println(json);

Executing this code shows the JSON generated for the class

{
  "title":"A new blog post",
  "postDate":"Jul 2, 2014 23:24:41 AM",
  "tags":["Json","Gson"]
}

Looking at this output, we can see that Gson has successfully serialized our class into JSON converting all the class members (including the array) into valid JSON.

Deserializing from JSON to Java Object

Deserializing from JSON into a Java object is similarly straightforward and requires calling the fromJson() method of the Gson class passing in the JSON data and the class name of the object to construct. For example:

BlogPost newPost = gson.fromJson(json, BlogPost.class);
System.out.println(newPost.toString());

Outputs:

BlogPost{title=A new blog post, postDate=Thu Jul 02 23:24:41 BST 2014, tags=[Json, Gson]}

Custom Serializers

Sometimes, Gson doesn’t de/serialize objects in exactly the format required by an application, as can be seen in the above example where the postDate field is serialized as a simple string. In a real application, it would more more likely that dates would need to be formatted in an ISO-8601 date format.
This can be achieved by creating a JsonSerializer, for example:

public class DateSerializer implements JsonSerializer&lt;Date&gt; {
    @Override
    public JsonElement serialize(Date date, Type type, JsonSerializationContext jsc) {
        TimeZone tz = TimeZone.getTimeZone("UTC");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        sdf.setTimeZone(tz);
        return new JsonPrimitive(sdf.format(date));
    }
}

This deserializer could then be called from Gson as follows:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
Gson dateGson = gsonBuilder.create();
String dateJson = dateGson.toJson(post);
System.out.println(dateJson);
{
  "title":"A new blog post",
  "postDate":"2014-07-02T22:24:41+0000",
  "tags":["Json","Gson"]
}

Creating Maven Projects for WildFly

The JBoss/WildFly way to configure Maven projects makes developing Java EE 7 applications with WildFly very straightforward.

Configuring a project to use the JBoss Java EE 7 Bill Of Materials (BOM) removes the difficulty of specifying what version of dependencies are required as these are already defined within the BOM.

So, to configure a WildFly project, we need to first define the BOM in the project’s pom.xml file.

<properties>
    <version.jboss.bom>8.0.0.Final</version.jboss.bom>
</properties>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.wildfly.bom</groupId>
            <artifactId>jboss-javaee-7.0-with-tools</artifactId>
            <version>${version.jboss.bom}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Once we’ve defined the BOM, we can easily add Maven dependencies without worrying about versions.

<dependencies>
    <dependency>
        <groupId>org.jboss.spec.javax.ejb</groupId>
        <artifactId>jboss-ejb-api_3.2_spec</artifactId>
        <scope>provided</scope>
    </dependency>
</dependencies>

Simple !

Installing a Jar File Into a Local Maven Repository

Sometimes when a file is not in the Central Maven Repository, it can be necessary to install files into your local Maven Repository. (Note, if you are working in more than a very small team, it’s probably beneficial to install a Nexus repository so that all members of the team get the benefits of any locally deployed artifacts)

To deploy a jar into the local maven repository, issue the mvn install:install-file command as shown below.

mvn install:install-file -DgroupId=your.group.id \
-DartifactId=yourArtifactId \
-Dversion=yourVersionNumber \
-Dpackaging=jar
-Dfile=\path\to\jar\file.jar
-DgeneratePom=true 

Once the jar has been added to the local maven repository, it can be added as a dependency within a project’s pom.xml as follows:

<dependency>
  <groupId>your.group.id</groupId>
  <artifactId>yourArtifactId</artifactId>
  <version>yourVersionNumber</version>
</dependency>

Configuring a Proxy Server in Maven

To configure a proxy server in Maven 2 or Maven 3, edit the settings.xml file and configure the <proxies> section.

The settings.xml file is located at: ${userhome}/.m2/settings/xml

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://maven.apache.org/SETTINGS/1.0.0
  http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <proxies>
    <proxy>
      <id>defaultProxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>default.proxy.server.host</host>
      <port>8080</port>
      <username>default.proxy.user</username>
      <password>secret</password>
      <nonproxyhosts>*.acme.com|*.acme.org</nonproxyhosts>
    </proxy>
  </proxies>
</settings>

Using the ShrinkWrap Maven Resolver for Arquillian Tests

This article assumes that you’re familiar with using Arquillian for testing Java applications. If you’re not familiar with Arquillian, then I suggest you check out the guides at http://www.arquillian.org where you’ll learn how to write Java tests that can run on the server and are much easier to write and maintain.

When writing an Arquillian test, you create a deployment as in the following code sample:

@Deployment
public static Archive<?> createTestArchive() {
  return ShrinkWrap.create(JavaArchive.class, "test.jar")
    .addClasses(RandomNumberBean.class);
}

It’s not uncommon to see a lot of calls to .addClasses() or .addPackages(). When working with third party libraries, this list of classes/packages added to the archive can grow and grow (and can be a bit of a trial and error process to get a complete list of dependencies). The ShrinkWrap Maven Resolver overcomes this issue by allowing you to specify Maven dependencies in the createTestArchive() method rather than having to add each class/package at a time. To use the ShrinkWrap Maven Resolver, the first stage is to add the relevant dependency to you Maven project’s pom.xml file.

<dependency>
  <groupId>org.jboss.shrinkwrap.resolver</groupId>
  <artifactId>shrinkwrap-resolver-impl-maven</artifactId>
  <scope>test</scope>
</dependency>

Having configured Maven, you’re ready to go and add dependencies to your Arquillian archive via code as shown in the sample below. In this sample, I’ve added the Apache Commons Math library to the Arquillian archive.

@Deployment
public static Archive<?> createTestArchive() {
  MavenDependencyResolver resolver = DependencyResolvers.use(
  MavenDependencyResolver.class).loadMetadataFromPom("pom.xml");

  return ShrinkWrap
    .create(WebArchive.class, "test.war")
    .addClasses(RandomNumberBeanCommons.class)
    .addAsLibraries(
      resolver.artifact("org.apache.commons:commons-math")
     .resolveAsFiles());
}

Looking at the code, you can see that the first stage is to create a MavenDependencyResolver from the project’s pom.xml file. Then all you need to do, is invoke the .addAsLibraries() method on the arquillian deployment specifying which Maven dependency to resolve.

Hopefully, you can see that this technique allows you to create your Arquillian tests much faster and more reliably than without using the ShrinkWrap Maven Resolver.

Deploy a Maven Project to JBoss AS 7

When developing software, it can be useful to be able to deploy to a running application server immediately when a build has completed, To perform this action with JBoss AS and Maven required use of the jboss-as-maven-plugin.

To deploy to JBoss,

  • Ensure JBoss is running
  • Add the JBoss plugin to the pom.xml file.
  • Execute the jboss-as:deploy target from Maven
<plugin>
  <groupId>org.jboss.as.plugins</groupId>
  <artifactId>jboss-as-maven-plugin</artifactId>
  <version>7.0.1.Final</version>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>deploy</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Enumerating Network Interfaces and Querying Their IP Addresses

In Java, we can enumerate network interfaces using the NetworkInterface.getNetworkInterfaces() method. This returns an enumeration of NetworkInterface objects.
Each NetworkInterface object can be enumerated over using the getInetAddresses() method to obtain all the InetAddresses that are associated with the NetworkInterface.
An InetAddress object is actually instantiated as an Inet4Address or Inet6Address in this instance and can be used to indicate whether an interface supports IPv4 or IPv6.
The following code shows how to enumerate over the local network cards and print out the interface name/display name, the host address/name and whether the IP address supports IPv4 or IPv6.

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class ShowInterfaces {
  public static void main(String args[]) throws SocketException {
    Enumeration<NetworkInterface> interfaces = NetworkInterface
      .getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
      NetworkInterface ni = (NetworkInterface) interfaces.nextElement();
      Enumeration<InetAddress> addresses = ni.getInetAddresses();
      while (addresses.hasMoreElements()) {
        InetAddress inetAddress = (InetAddress) addresses.nextElement();
        System.out.println("Name:" + ni.getName());
        System.out.println("Display Name:" + ni.getDisplayName());
        System.out.println("Host Address:"
          + inetAddress.getHostAddress());
        System.out.println("Host Name:" + inetAddress.getHostName());
        if (inetAddress instanceof Inet4Address)
          System.out.println("IP Address: IPv4");
        else
          System.out.println("IP Address: IPv6");
        System.out.println("");
      }
    }
  }
}
$ java ShowInterfaces
Name:eth1
Display Name:eth1
Host Address:192.168.0.112
Host Name:beefy.local
IP Address: IPv4
Name:lo
Display Name:lo
Host Address:0:0:0:0:0:0:0:1%1
Host Name:localhost6.localdomain6
IP Address: IPv6
Name:lo
Display Name:lo
Host Address:127.0.0.1
Host Name:localhost.localdomain
IP Address: IPv4

Developing Java EE 6 Applications With TomEE and NetBeans

I’ve found that one of the most productive ways of developing Java EE applications is by using NetBeans and the TomEE application server. For those of you that haven’t used TomEE before, it’s a Java EE 6 Web Profile certified stack that sits on top of Apache Tomcat.

As TomEE is Java EE 6 web profile certified, it supports the following technologies (all via Apache products) out of the box:

  • CDI
  • EJB
  • JPA
  • JSF
  • JSP
  • JSTL
  • JTA
  • Servlet
  • Javamail
  • Bean Validation

If you want / need to use JMS or JAX-RS/WS, then there’s an additional distribution called TomEE+ that provides support for these features.

I prefer to use Maven for project management / builds / testing etc which integrates well with NetBeans.

Using NetBeans, you can easily create a TomEE compatible Maven project by creating a new Maven Project from Archetype within the NetBeans New Project wizard.

Tomee Webapp Archetype

The tomee-webapp-archetype will create a basic Web Application that’s defined and ready to deploy against TomEE.

Within the generated pom.xml file, we can see the important TomEE specific aspects are the use of OpenEJB for the EE api’s

<dependency>
  <groupId>org.apache.openejb</groupId>
  <artifactId>javaee-api</artifactId>
  <version>6.0-4</version>
  <scope>provided</scope>
</dependency>

and the use of the TomEE Maven plugin

<plugin>
  <groupId>org.apache.openejb.maven</groupId>
  <artifactId>tomee-maven-plugin</artifactId>
  <version>1.0.1</version>
</plugin>

Using the TomEE Maven plugin allows the project to be built and deployed to TomEE (without having to download TomEE!). This is useful for building and compiling from the command line. To get Maven to download TomEE, deploy your project to it and then start TomEE up, use the command

mvn tomee:run

Having said that, I prefer to use NetBeans to control running my projects as this provides more advanced features such as hot deployment of JSP/JSF, controlled execution of tests etc.

To run the project from within NetBeans, simply open up the pom.xml from the File | Open Project wizard in NetBeans.

NetBeans is clever enough to open Maven projects which then function just like a standard NetBeans project. Select the Run option and NetBeans will ask which application server to run the application on. The is no direct support for TomEE, (i.e. you don’t see an Application Server of type TomEE in the NetBeans server configuration page) but since TomEE is based on Tomcat, to define a TomEE server, you just need to create a “Apache Tomcat” server and specify the server location to that of a previously downloaded TomEE instance.

That’s pretty much all that is involved in getting up and running with TomEE and NetBeans. TomEE offers a fast Java EE 6 certified stack that provides for rapid development and deployment of applications, whereas NetBeans 7.3 provides excellent tooling to support TomEE and Java EE development.