Category Archives: Development

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.

Maven

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.

Using the ShrinkWrap Maven Resolver for Arquillian Tests

arquillianThis post 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.

Choosing a Java Version on Ubuntu

When you have got multiple versions of Java installed, you can choose which one you want to use by running the update-alternatives command.

Running this command shows a list of installed Java JDKs and JREs allowing one to be selected as the default that is used when java needs to be executed.

$ sudo update-alternatives --config javac

If you prefer to use a gui instead of the command line, you can execute galternatives instead and define the default versions of software with the following dialog.

$ sudo galternatives

Getting Logged On User in a Spring-Web Application

In a web application, it can be useful to get the logged on user’s name and display it within a web page, for example as a link to allow the user to edit their profile.  In a Spring Web application the username can easily be obtained in a controller and passed via a map to the user interface.

To get the username in a controller class, we would use theSecurityContextHolder.getContext().getAuthentication().getPrincipal() method to get hold of the principal. We can then call the .getUsername() method to get the username of the currently logged on user.

@Controllerpublic class PageController {
 
  @RequestMapping(method = RequestMethod.GET)
 
  public ModelAndView handleRequest() {
    User user = (User) SecurityContextHolder.getContext()
       .getAuthentication().getPrincipal();
    Map userModel = new HashMap();
    userModel.put("username", user.getUsername());
    return new ModelAndView("page", "model", userModel);
  }
}

The username can then be displayed in an HTML page as:

<c:out value="${model.username}" />

Basic Java CRUD Operations with MongoDB

MongoDBIn this post I’d like to show how to perform basic CRUD operations against a MongoDB database using the Java driver.

For this post, lets assume that we have a todo database with a collection of todo items. Each item has a task and a priority.

In terms of JSON notation, an example item would look like:

{
  "_id" : { "$oid" : "4bffb75121eec88a67ff6ec8"} ,
  "task" : "Write Code" ,
  "priority" : "high"
}

Now that we have defined what we are storing in the database, lets have a look at how we connect to Mongo.

Connection to the database
To connect to a MongoDB database, we would use code similar to that below. In this code you can see that we are connecting to a database called todo and getting the collection called items. In MongoDB if neither of these items exist, they will be automatically created.

Mongo mongo = new Mongo();
DB db = mongo.getDB("todo");
DBCollection items = db.getCollection("items");

Creating Documents
To add a document to a collection, we use the insert() method of the collection.

BasicDBObject doc1 = new BasicDBObject();
doc1.put("task", "Write Code");
doc1.put("priority", "high");
items.insert(doc1);

Retrieving Documents
To retrieve documents from a collection, we can create a query and then iterate through it with a cursor.

BasicDBObject query = new BasicDBObject();
query.put("priority", "highest");
DBCursor cursor = items.find(query);
// Print out "highest" priority items
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

This query will find all the objects in the collection that have a priority of highest. If we wanted to get all of the items in the collection, we would create the cursor without a query as shown below.

DBCursor cursor = items.find();

Updating Documents
To update an object, we first have to get the object from the collection then we save it back into the collection.

BasicDBObject findTestItemQuery = new BasicDBObject();
findTestItemQuery.put("task", "Test Code");
DBCursor testItemsCursor = items.find(findTestItemQuery);
if(testItemsCursor.hasNext()) {
    DBObject testCodeItem = testItemsCursor.next();
    testCodeItem.put("task", "Test and Review Code");
    items.save(testCodeItem);
}

Deleting Documents
Finally, to delete a document or set of documents, we use the remove method of the collection.

BasicDBObject deleteQuery = new BasicDBObject();
deleteQuery.put("priority", "highest");
DBCursor cursor = items.find(deleteQuery);
while (cursor.hasNext()) {
    DBObject item = cursor.next();
    items.remove(item);
}