Java EE7 Development and Hosting on OpenShift with Wildfly: Part 1 - Archived

This is the first blog post in a series where I will cover how to build web applications in Java using Java EE 7. Java EE 7 is the latest release of the Java Enterprise Platform, with a focus on HTML 5 and developer productivity.

Java EE 7 introduced five new specifications covering WebSockets (JSR-356), JSON Processing (JSR-353), Batch Applications (JSR-352), Concurrency Utilities (JSR-236), and Caching (JSR-107). Apart from these new specifications, three existing specifications (JAX-RS 2.0, JMS 2.0, and EL 3.0) have major updates and a few other specifications have minor updates. We will cover most of these specifications in detail in this blog post series.

Why This Blog Post Series?

Most of the Java EE 7 books on the market today do a good job of explaining Java EE basics and the features introduced in Java EE 7, but they lack a tutorial kind of approach to help developers build modern web applications. By modern web applications, I mean web applications running in the cloud that expose a RESTful back end, which is consumed by a JavaScript MV* front end.

In this blog post series, I am planning to write a simple-but-real application that implements authentication, authorization, database migration, email integration, social provider integration, NoSQL database integration, HTML 5 templates, JavaScript MV* framework, caching etc.

What This Series is Not

This blog post series is not a theoretical introduction to Java EE 7. All the posts in this series will help you build the sample application using the Java EE 7 APIs.

The Application

The application developed in this series is a simple blogging platform allowing users to write and publish blog posts. The application is built using a Java EE 7 back end with PostgreSQL as the database. The application exposes a RESTful back end that’s consumed by an AngularJS-based front end. We will also use Redis, a key-value NoSQL data store, as well.

The source code repository of the application is available on GitHub.

What We Will Cover Today

  • Create a WildFly application using the OpenShift web console
  • Add a PostgreSQL database to the OpenShift application
  • Import OpenShift application in Eclipse
  • Look at the template application source code
  • Write a JAX-RS resource
  • Deploy the application on a local machine
  • Deploy the application on OpenShift

Prerequisites

To follow along with this blog post, please make sure you have all the prerequisites covered.

  1. Basic Java knowledge is required. Install the latest Java Development Kit (JDK) on your operating system. You can either install OpenJDK 7 or Oracle JDK 7.

  2. Sign up for an OpenShift Online account. It is completely free and Red Hat gives every user three free gears on which to run applications. At the time of writing, the combined resources allocated for each user was 1.5GB of memory and 3GB of disk space.

  3. Download the latest version of the Eclipse IDE for Java EE from the official website.

  4. Basic Git knowledge is required. You can learn Git basics from http://rogerdudler.github.io/git-guide/. Once you have learned the basics, then read this awesome Git tutorial by Atlassian.

Create a WildFly Application using OpenShift Web Console

There are multiple ways developers can work with OpenShift. OpenShift offers a web console, command-line client ca;;ed RHC, and Eclipse plugin that developers can use to interact with the platform. The web console is the easiest way to create OpenShift applications as it does not require you to install any software on your machine. You can just log in to the OpenShift web console and navigate to the Java applications page https://openshift.redhat.com/app/console/application_types?tag=java. At the bottom of the Java applications page, you will see the WildFly application type as shown below. WildFly is the new name of the JBoss application server that implements the latest enterprise Java standards.

Click on the WildFly cartridge and you will be presented with a web form where you need to enter the application details.

Let’s talk about all of the options that we have to enter:

  1. Application Name: This is used to define the name of the application. The name of the application can be any sequence of alphanumeric characters. Different users can use the same application name. We will use blogger as the name of the application. You can use any other name you like but please keep in mind that I will refer to the application as blogger.
  2. Namespace: Every OpenShift account needs to have at least one namespace. Applications can be grouped logically in a namespace. Each namespace has a unique name that becomes part of the application’s public URL. On OpenShift Online’s free tier, you are only allowed to create one namespace but with the paid offerings users can have more than one namespace.

  3. Source Code: Every OpenShift application has a Git repository. By default, OpenShift uses its own set of template applications depending on the application type. If you have already written the source code of your application or you want to specify your own template Git repository then you can use this input box to specify a public Git repository.

  4. Scaling: OpenShift can horizontally scale web applications depending on the number of concurrent requests. At application creation time, you can specify whether you want to create a scalable or non-scalable application. To learn more about application scaling, you can read my blog post on this subject. In this blog post, we will create a non-scalable application so you don’t have to change the default option.

Enter the details and press the Create Application button as shown below. Please note that because I am using shekharblogs as my namespace, you can’t use it. A namespace has to be unique among all users.

This will create an application container for us, called a gear, and set up all of the required SELinux policies and cgroup configuration. OpenShift will also set up a private Git repository for your application. Finally, OpenShift will propagate the DNS entry for your app to the outside world.

After application creation, you will be shown a page with Next Steps. Click on the Continue to the application overview page link. This will direct you to the blogger application details page as shown below.

You can view the deployed application at http://blogger-{namespace}.rhcloud.com. Please replace {namespace} with your own OpenShift namespace, also sometimes called a domain.

Add PostgreSQL Database to the OpenShift Application

In the image shown above, click on the Add PostgreSQL 9.2 link to add a PostgreSQL database to the blogger application. This will direct you to a page asking you to confirm that you want to add a PostgreSQL cartridge. Press the Add Cartridge button to add the PostgreSQL database.

After installing the PostgreSQL cartridge, you will be shown the database details as pictured below.

Import OpenShift Application in Eclipse

These instructions assume that you have already installed the OpenShift Eclipse plugin. You can refer to my blog to learn how to install the plugin. Once the plugin is installed, open the Eclipse application and navigate to the project workspace. To import the OpenShift application, Go to File > Import > OpenShift > Existing OpenShift application.

Next, sign into your OpenShift account using your OpenShift Online credentials.

After successful authentication, you will be shown a view where you can import applications you have already created.

Click on the Browse button and it will open a view that lists all the existing applications. Select the blogger application and press the OK button.

Now, the Import OpenShift Application view will be prepopulated with the blogger application details.

Next we have to set up the application and configure the server adapter settings. Accept the default settings and click Next.

The next screen will ask us to specify the location where we want to clone the Git repository locally and the name of the Git remote.

Finally, press the Finish button and the OpenShift Eclipse tooling will first clone the Git repository on your local machine, and then import the application as a Maven project.

Look at the Template Application Source Code

The application imported by the OpenShift Eclipse plugin is a very simple web application with an index.html and pom.xml. The index.html file contains the static content that you see when you view the application in a browser. The pom.xml file specifies the Java EE 7 dependency so that you can work with the Java EE 7 APIs. The scope of the Maven dependency is provided because the application server will already have these libraries.

<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>

Apart from the Maven dependency, there is a profile called openshift that will be invoked by OpenShift when you push code changes to the application gear. The openshift profile does not do anything special. It just creates the WAR with the name ROOT so that your application is available over the root context, i.e. ‘/’. From Java EE 6, web.xml is optional, so the openshift profile uses failOnMissingWebXml to tell the Maven WAR Plugin not to fail if a web.xml file is not present.

<profile>
    <id>openshift</id>
    <build>
        <finalName>blogger</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <outputDirectory>deployments</outputDirectory>
                    <warName>ROOT</warName>
                </configuration>
            </plugin>
        </plugins>
    </build>
</profile>

Before we move forward, please delete the index.html, snoop.jsp, and images directory as we don’t need them.

Write Your First JAX-RS Resource

Create a new package org.blogger.rest.config and then create a new class RestConfig that will configure JAX-RS. We will cover JAX-RS in detail in future blog posts.

package org.blogger.rest.config;
 
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
 
@ApplicationPath("/")
public class RestConfig extends Application {
}

In the code shown above, we use the no web.xml approach of configuring JAX-RS. There are multiple ways to configure JAX-RS. You created a new class called RestConfig that extends the javax.ws.rs.core.Application class. This class is annotated with the @ApplicationPath annotation. The @ApplicationPath annotation is used to define the URL pattern that will be monitored by JAX-RS. In the code shown above, we have used the root URL ‘/’, which means all requests will pass through JAX-RS.

Next, create a HelloResource class as shown below.

package org.blogger.rest.resources;
 
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
 
@Path("/")
public class HelloResource {
 
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String ping(){
        return "Hello World!";
    }
}

In the code shown above, you did the following:

  1. You created a class HelloResource and annotated it with the @Path annotation. The @Path annotation defines the URL that the resource class or its methods will serve requests for. This class will serve the requests made to the ‘/’ URL.
  2. You created a method called ping that will be invoked when a user makes an HTTP GET request to the root URL, ‘/’. The method is annotated with @GET to indicate that this method should be called where there is an HTTP GET request to that URL. The @Produces annotation specifies the media type that this method will produce. The ping() method will produce the “text/plain” media type.

Deploy Your Application on Local Machine

Download the latest version of WildFly server from the official website http://wildfly.org/downloads/. The latest version at the time of writing is 8.1.0.CR1. Once downloaded, extract the binary to a convenient location.

Open the project pom.xml and define a new Maven profile as shown below. This profile will be used for local deployment. When user will build the project using mvn clean install -Plocal command, then a WAR file will be created with name blogger and placed in WildFly container standalone/deployments directory.

<profile>
    <id>local</id>
    <build>
        <finalName>blogger</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <outputDirectory>${env.WILDFLY_HOME}/standalone/deployments</outputDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
</profile>

Define a new Maven build run configuration in Eclipse. Right click on the project > Run As > Run Configurations and create a new configuration as shown below.

In the Maven profile shown above, we used WILDFLY_HOME environment variable. To create a new environment variable, click on Environment and define a new environment variable for WILDFLY_HOME. Give it the location where you extracted the WildFly server binary.

Finally apply the configuration by pressing the Apply button.

I don’t like to start and stop the server from within Eclipse. Open a new command-line terminal and go to the location where you extracted the WildFly server. To start the WildFly server on *nix machines, run the command shown below. On Windows machines, use the standalone.bat file.

$ sh bin/standalone.sh

To deploy the application, run the Eclipse Maven command. The default keyboard shortcut on a Mac is SHIFT-ALT-X M. I find it difficult to type so I defined my own key binding. Whenever I press CMD M on my Mac, it should build the project and deploy the latest WAR file. To define your own key binding, go to Preferences > General > Keys. Define your own binding and press Apply and then OK.

Now every time you press CMD M, the project will be built and then deployed on WildFly server running on local machine.

Deploy Your Application on OpenShift

To deploy the application on OpenShift, commit all the changes to your local Git repository and then do a Git push.

$ git add .
$ git commit -am "Blog 1 completed"
$ git push

The application will be built and then the new WAR will be deployed. You can test the PingResource by going to http://blogger-{namespace}.rhcloud.com/.

Next Steps

Categories
Java, JBoss, OpenShift Online
Tags

10 Responses to “Java EE7 Development and Hosting on OpenShift with Wildfly: Part 1 - Archived”

  1. Mohamed Shiyas

    Thank you admin for
    sharing this valuable post JAVA
    J2EE Training Institutes in Chennai

  2. Ravi

    This page is dedicated for our Besant Technologies Reviews by our students. Please give your reviews here,

    Besant Technologies Reviews

  3. Besant Technologies

    This page is dedicated for our Besant Technologies Reviews by our students. Please give your reviews here,

    Besant Technologies Reviews Complaints Testimonials

  4. abdallah

    Hi,

    I have some comments:
    – Can you please re-write this blog using eclipse Mars (4.5.0)
    – What exactly the value I should input in the Source Code field – can you give an example

  5. andyserrato

    Hi,
    Excellent tutorial but I couldn’t find the second part

  6. ishan sharma

    Thanks .. this blog cleared most of my doubts :)

  7. Robert Goren

    thanks for sharing such informative post….

  8. Verve Innovation

    Thanks for posting the wonderful article to us.

  9. southstar

    great information about openshift…

Comments are closed.