Using the ShrinkWrap Maven Resolver for Arquillian Tests

This 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.

Share

Hosting on OpenShift

I’ve recently moved this blog to run on WordPress running on RedHat’s OpenShift Express.

If you’ve not heard of OpenShift, it’s:

“a free, cloud-based application platform for Java, Perl, PHP, Python, and Ruby applications.”

OpenShift uses git to publish files to your site, so the general approach is to make your application locally, commit files to git and then push them to OpenShift. In practice this works very well, but there are a couple of gotcha’s that I encountered – I’ll explain those later.

OpenShift express supports Java (with full AS7 support), Ruby, PHP, Perl and Python apps.

In this post, I’m going to show the steps needed to host WordPress at OpenShift Express.

Installing the client tools
So, the first stage in setting up on OpenShift is to install the OpenShift client tools. On Ubuntu, this is achieved with apt-get

$ sudo apt-get install ruby
$ sudo apt-get install rubygems
$ sudo apt-get install rhc

Creating a domain and an application
After installing the OpenShift tools, the next stage is to create a domain name to host the application in and the applicaition itself.

Creating a domain is achieved with the rhc domain create command.

$ rhc domain create -n <domain> -l <emailaddress>

Where domain is the OpenShift unique domain name for your application and emailaddress is your login email address for OpenShift.

Next, you need to create an application. This is essentially a remote git repository which is cloned onto your local filesystem. When creating an application, you need to specify which “cartridges” you want to use. For WordPress, you will need to use the php-5.3 cartridge.

$rhc app create -a <appname> -t php-5.3

Where appname is your application name.

If all goes well, your application will now be created and available on the internet at:

http://<appname>-<domain>.rhcloud.com

MySQL Support
The next stage of hosting WordPress on OpenShift is to create a MySQL database. This is again achieved using the OpenShift command tools:

$ rhc-ctl-app -a "appname" -e add-mysql-5.1

This will give you MySQL support for your application. After running this command, you’ll be supplied details to your MySQL database. To help manage the database, the easiest way I found was to add PHPMyAdmin

$ rhc-ctl-app -e add-phpmyadmin-3.4 -a "appname"

Now that you’ve got PHPMyAdmin installed, a good security practice is to create a MySQL user with the approprate access rights for accessing WordPress. We don’t really want WordPress running aganst the admin MySQL account.

Install WordPress
At this point, you’ve created a basic OpenShift PHP application with MySQL support. The next stage is to install WordPress. To install, simply download the latest archive of WordPress and unzip it into the php folder that has been created underneath your appname folder.

After unziping, its tempting to just access the OpenShift application and run the WordPress wizard to create the standard wp-config.php file. Unfortunately if you do this, when you next push your local code to OpenShift, any modifications made on the server will be lost. So, the general procedure is to always make changes locally and then push them to the server. This also applies for installing plugins to WordPress – always install them locally, commit them to git and then push them to OpenShift.

So, to get WordPress up and running, create a wp-config.php file locally within the WordPress installation folder. Its a very straightforward file to create, but check out the WordPress docs for more info.

Pushing to OpenShift
Having created the database configuration file, you can now commit everything to git and push it to OpenShift.

$ git commit -a -m "Initial installation of WordPress"
$ git push

Again, assuming everything has gone OK with no errors, you should be able to access your WordPress site at:

http://<appname>-<domain>.rhcloud.com

Publishing to a custom domain
OpenShift has recently added support to allow applications to be hosted at their own domain names rather than as a subdomain of rhcloud.com

To publish to a custom domain, you need to add an alias in OpenShift for your application to the domain name you want it hosted at.

$ rhc-ctl-app -c add-alias --alias www.somedomain.com -a <appname>

To complete the process, you need to edit your DNS records and add a cname pointing your domain (e.g. www.somedomain.com) to <appname>-<domain>.rhcloud.com

You should not have a working WordPress installation running on OpenShift

Uploading media to WordPress
One of the side effects of pushing local content to a git repository is that any changes made to the web site are lost when new code is pushed to it. For example plugins installed via the WordPress user interface are lost when you push new code to OpenShift. Also, any images uploaded to WordPress (by default stored in wp-content/uploads) are also lost when you push new code. To overcome this, edit the <appname>/.openshift/action_hooks/build file and add the following contents:

if [ ! -d $OPENSHIFT_DATA_DIR/uploads ]; then
    mkdir $OPENSHIFT_DATA_DIR/uploads
fi

ln -sf $OPENSHIFT_DATA_DIR/uploads $OPENSHIFT_REPO_DIR/php/wp-content/

Any uploaded data will now be stored outside of the OpenShift git repository and therefore won’t be overwritten each time you push to OpenShift.

Hopefully I’ve shown how straightforward is is to host applications on OpenShift Express. If you’ve got any questions, leave them as comments to the post.

Share

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 java
There are 2 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                            Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-6-openjdk/jre/bin/java         1061      auto mode
  1            /usr/lib/jvm/java-6-openjdk/jre/bin/java         1061      manual mode
* 2            /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java   1051      manual mode

Press enter to keep the current choice[*], or type selection number: 2

To choose a default javac compiler, run the following command.

$ 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

Share

Creating a Shortcut to Eclipse on the Ubuntu Unity Dock

If you use Eclipse on Ubuntu, you will probably have found that the version in the Ubuntu repositories doesn’t have all the plugins you’re used to, and will have installed Eclipse from a download at eclipse.org

If this is the case, you can create a shortcut launcher to Eclipse using the gnome-desktop-item-edit application enabling Eclipse to be pinned to the Unity Dock. gnome-desktop-item-edit isn’t installed with a clean copy of Ubuntu however. To install run the following:

$ sudo apt-get install gnome-panel

After installation, you can create a new launcher by executing the following command:

$ gnome-desktop-item-edit --create-new ~/.local/share/applications

This will cause the following window to be displayed.

Enter all the relevant details into the window (including selecting the icon) and press OK. This will create an Eclipse launcher. If you then navigate to this folder, you can drag and drop the Eclipse icon onto the Dock to create the pinned shortcut to Eclipse.

Share

Review of JBoss AS 7 Configuration, Deployment and Administration

JBoss 7 is the latest Java EE application server to be released by Red Hat. Version 7 is certified against the Java EE 6 Web Profile and has been developed with productivity and speed in mind – the current version offering significant speed enhancements over previous versions. Not only isAS7 available as a download for developers, it is also an important aspect of Red Hat’s OpenShift Platform-as-a-Service (PaaS) offering. JBoss AS 7 Configuration, Deployment and Administration explains how to use all the components that make up the application server covering (as you would expect from the title) configuration,management, deployment and administration. Many of these features are different in AS 7 from previous versions of JBoss AS so this book is in invaluable resource. The book is aimed at administrators,developers and testers, so whatever your role, chances are you will find something useful in the book.

The book starts by showing how to download and install AS7. The procedure here is pretty much the same as for other versions of JBoss, so if you’ve used it before, you shouldn’t experience any problems here. What is different however is the structure of the application server itself and the tools used to interact with it. The first chapter of the book explains how the new server is different from previous releases and begins to explain the basics of the server.
After introducing AS7,the book continues to go further into depth on the configuration side of the server. Configuration of thread pools, logging, datasources and EJB etc. is all covered in depth. Plenty of sample XML and diagrams are used to help with the discussions. The book also includes a chapter on configuring and managing JBoss domains which includes useful reading for those implementing and installing JBoss servers.
One of the main pieces of functionality in an enterprise application is probably handled via the Web Container. The book provides plenty of details on how to configure the JBoss Web Container and includes sample Eclipse based source code showing how to create and deploy a basic web application. Note that the emphasis throughout the book is on how the application server can be configured and maintained and not on how to develop Java EE applications. It is useful, from a developer’s perspective,to occasionally see some source code to see the interaction with the server however.
In previous versions of the JBoss Application Server, managing the application server (for example creating datasources or JMS queues) was typically performed via manually editing XML files or via the JMX console. With AS 7,both a comprehensive CLI and Web Console are provided. The book contains extensive details of these together with details of how they can be configured.
For those interested in installing JBoss AS, the next few chapters will be extremely useful. Clustering and load balancing are described in-depth with many details included, for example different caching configuration and integration with Apache HTTP Server using mod_jk.
The final chapter of the book discusses cloud computing and how this relates to JBoss AS 7in the form of OpenShift Express and OpenShift Flex. The author explains these services and then shows how to deploy and manage a simple Java EE application to the services. Given the nature of cloud computing, I believe these chapters will be essential reading for most developers.
If you’re developing Java EE applications using JBoss AS 7, or planning to upgrade to AS 7sometime soon, then I’d recommend this book. The book is useful to new users of AS 7 as well as to those that have been using the AS since it was first released as version 7 last year. Different sections of the book will appeal to different audiences(administrator, developer, tester etc.), but I think the use you’ll get from this book will be invaluable.
Recommended reading for all users of JBoss AS 7.
Thanks to Sean at Packt Publishing for sending me a copy of this book to review.
JBoss AS 7Configuration, Deployment, and Administration by Francesco Marchioni. ISBN 978-1-84951-678-5
Don’t forget you can win a free copy of this book by commenting about it on the Develop InJava Forums.
Share

Free JBoss AS 7 Book

I just wanted to remind everyone of the free competition that is going on over at developinjava.com to win a free copy of JBoss AS 7 Configuration, Deployment and Administration by Francesco Marchioni.

To enter, all you have to do is visit the competition and comment on the book.

What are you waiting for?  Go and enter now and you could be the proud winner of a copy of the book.

Share

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 the SecurityContextHolder.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<String, Object> userModel = new HashMap<String, Object>();
    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}" />
Share

Creating Calendar Based Timers in Java EE 6

Java EE 6 allows developers to create application timers that are initialized when either a Stateless Session Bean, a Singleton Bean or a Message Driven Bean are deployed to the application server.

To indicate that a method on any of these beans is to be invoked on a timed basis, the method must be annotated with either the @Schedule annotation (for single timer schedules), or the @Schedules annotation (for multiple timer schedules).

The code below shows a very simple Stateless Session Bean configured with 2 scheduled timers.  The first timer is configured with one schedule whereas the second is configured with 2 schedules.

package com.acme.timer;

import javax.ejb.Schedule;import javax.ejb.Schedules;import javax.ejb.Stateless;import javax.ejb.Timer;

@Statelesspublic class CalendarTimer {

  @SuppressWarnings("unused")  @Schedule(second = "*/10", minute = "*", hour = "8-17", dayOfWeek = "Mon-Fri", dayOfMonth = "*", month = "*", year = "*", info = "Scheduled Timer")  private void scheduledTimeout(final Timer t) {    System.out.println(t.getInfo().toString() + " called at: "        + new java.util.Date());  }

  @SuppressWarnings("unused")  @Schedules({      @Schedule(second = "15", minute = "*", hour = "8-17", dayOfWeek = "Mon-Fri", dayOfMonth = "*", month = "*", year = "*", info = "2nd Scheduled Timer"),      @Schedule(second = "45", minute = "*", hour = "8-17", dayOfWeek = "Mon-Fri", dayOfMonth = "*", month = "*", year = "*", info = "2nd Scheduled Timer") })  private void scheduledTimeout2(final Timer t) {    System.out.println(t.getInfo().toString() + " called at: "        + new java.util.Date());    System.out.println();  }}

As can be seen, the first timer is annotated with the @Schedule annotation. This annotation takes several parameters that define the timer schedule:

second Number of seconds: 0 through 59
minute Number of minutes: 0 through 59
hour Number of hours: 0 through 23
dayOfWeek Day of the week.  This can take textual values (Sun, Mon, Tue, Wed, Thu, Fri, Sat) or numerical values 0 through 7 (both 0 and 7 indicate Sunday)
dayOfMonth Day of the month. This can take textual values (1st, 2nd etc), or numeric values 1 through 31. Negative values can also be used to indicate days before the end of the month. The value Last can also be used to indicate the last day of the month.
month Month of the year. This can take textual values (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec) or numerical values 1 through 12
year The year. This can take numeric years in the format yyyy.
info Additional information passed to the timer function.

The table above shows the allowable values that can be used for each expression used to build up a schedule. These values can also be expanded into expressions to make more complex schedules.

Wildcard: A wildcard character (*) is used to indicate that the schedule will fire for every valid value of the specific operand. For example, setting the value second=”0″, minute=”*” would cause a timer to be invoked every minute at 0 seconds.

Lists: Comma separated lists of values allow timers to occur at every value in the list rather than at all valid values as specified by the wildcard character.  For example second=”0″, minute=”0, 15, 30, 45″ would cause a timer to be invoked every quarter of an hour.

Ranges: Hypen separated ranges allow timers to occur within the specified range.  For example dayOfMonth=”1-5″ would cause a timer to be invoked every day for the first 5 days of each month.

Intervals: Intervals are defined in the format start/interval and are valid only for hours, minutes and seconds.  An interval is defined as the start value for a timer and then the interval at which a timer will be invoked.  For example hour=”12/1″ would cause a timer to be invoked on the hour, every hour in an afternoon. It’s possible to combine the wildcard and interval expressions to cause a timer to be invoked every x hours, minutes or seconds.  For example  minute=”*/10″ would cause a timer to be invoked every 10 minutes.

The second method in the example above shows how 2 different schedules can be applied to a timer.  In this instance, the method is annotated with the @Schedules annotation rather than the @Schedule annotation.

Share

Using GlassFish from Eclipse

When I think of developing apps using GlassFish, I usually think of using NetBeans for the development. As you’d expect however, Oracle provides some good tooling to allow you to develop against GlassFish from within Eclipse – even to the point of installing the application server directly from within Eclipse.  So, how is this done?

Installing GlassFish Server Tools

Contrary to what you’d expect, to install GlassFish tooling, you don’t use the Eclipse Marketplace for installation.  To install, right click within the “Servers” pane and select “New | Server” to display the “Define a New Server” dialog. On this dialog, select “Download additional server adaptors” and in the resulting dialog select “Oracle GlassFish Server Tools”.

After accepting the licence conditions, the GlassFish Server tools will be downloaded upon which you’ll need to restart Eclipse to complete the installation.

Defining a GlassFish Instance

After a restart, opening the ”Define a New Server” dialog will show that GlassFish support has been added.

Choose the GlassFish server you wish to use and press the “Next” button.  On the resulting dialog, you can choose to locate an existing copy of GlassFish, or install an new instance via the “Install Server” button if you don’t already have GlassFish installed.

One point to note here is that, if you install a new instance of GlassFish, you may then need to browse through the install folder to locate the “glassfish” folder within.  You will see that this is necessary because the “Next>” button will be disabled as you’ve installed an instance of GlassFish, but not correctly identified its location to Eclipse.

When you’ve selected (and installed if necessary) a GlassFish instance, complete the wizard to define the admninistrator credentials of the server.

GlassFish Tools

After creating a GlassFish server instance in Eclipse, you can develop and test Java EE 6 applications against it.  The GlassFish tools provides additional support to assist in this.  For example, right clicking on the server in the “Servers” tab allows you to manage the server or get additional information or support.

New wizards are also installed into Eclipse to assist when creating GlassFish facets such as JMS or JDBC resources as shown below.  These wizards are available on the standard “File | New | Other” dialog under the “GlassFish” folder.

Share