Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Automate development and management of cloud virtual machines

Learn how to automate build and deployment on IBM SmartCloud Enterprise with Apache Maven

Alex Amies (aamies@cn.ibm.com), Senior Software Engineer, IBM
Alex Amies photo
Alex Amies is a senior software engineer in the IBM GTS Development Lab in the China development lab. He is currently an architect working on the design of the IBM SmartCloud Enterprise. Previously, he acted as an architect and a developer on cloud and security products in other groups within IBM.
Pan Xia Zou (zoupx@cn.ibm.com), Staff Software Engineer, IBM
Pan Xia Zou is staff software engineer at IBM and works as a build and deployment automation architect for IBM SmartCloud Enterprise.
Yi Shuai Wang (wangyis@cn.ibm.com), Advisory Architect, IBM
Yi Shuai Wang is an Advisory Architect at IBM and lead developer for the development of the business support services of IBM SmartCloud Enterprise.

Summary:  A recent trend has been to build a strong connection between cloud application and service development and operations; in particular, this trend is leading to a tighter, more efficient integration of application life cycle management (ALM) tools with cloud computing. In this article, the authors will show you how to use the open source Apache Maven build management tool to automate build and deployment projects on IBM® SmartCloud Enterprise. They will also demonstrate how to integrate the management of virtual machines on the cloud into the build and deployment life cycle by developing an Apache Maven plug-in that looks up and creates virtual machines that run a J2EE application server on the cloud. You'll also discover best practices for development and deployment on the cloud and how to use IBM Cloud API's and Maven to implement these practices.

Date:  29 Oct 2011
Level:  Intermediate PDF:  A4 and Letter (622 KB | 22 pages)Get Adobe® Reader®
Also available in:   Chinese  Japanese  Vietnamese  Portuguese

Activity:  49372 views
Comments:  

Build and deployment automation is critical for the smooth execution of any development project. As projects become bigger, it becomes more important. A recent trend in application life cycle management tools (ALM) is building a better connection between development and operations and, in particular, integration of these tools with clouds.

One of the neat things about cloud resources compared with physical resources is that you can create cloud resources on demand with APIs. ALM tools can be run on the cloud, leverage the cloud in some way, or be used to develop applications for the cloud.

IBM Rational® Application Developer and integrated development tools are ideal for code development, including performing local builds and unit testing, but creating a repeatable build process is critical for application development in a team greater than one person.

There are a number of tasks that are often included in build and deployment life cycle, including:

  • compilation
  • packaging
  • validation
  • unit testing
  • middleware configuration
  • deployment

In cloud computing, you can take deployment automation a step further by creating virtual machines with pre-installed software.

There are a number of open source and commercial build tools that are capable for build and deployment automation, including Ant, Maven, and IBM Build Forge. In this article, we focus on the Apache Maven open source tool; it has definitions for the phases of build and deployment that we are interested in and it includes an extensible framework. In addition, it contains patterns for a number of best practices and plug-ins for a number of build tasks that are useful.

Sample J2EE project

The IBM SmartCloud Enterprise catalog includes instances of IBM WebSphere® Application Server 7.0. With this, you can use a J2EE environment without having to install any software and also enjoy the extra features that WebSphere Application Server provides above other J2EE environments.

When requesting a WebSphere Application Server server you are prompt for a username and password for the WebSphere Application Server administration console. Note these down because you will need them later. In addition, you are prompt to choose the profile, as shown here.


Figure 1. WebSphere image provisioning wizard Additional Parameters Screen
WebSphere image provisioning wizard Additional Parameters Screen

A WebSphere profile defines a runtime environment, including all the files that the server processes to determine and store configuration information. Choose the Development profile. It will make WebSphere Application Server more convenient to manage through IBM Rational Software Architect, as discussed later.

The WebSphere Application Server is started a short time after the instance is provisioned and has booted up. You can bring up the administration console with this URL: https://host:9043/ibm/console/logon.jsp.

All the management of WebSphere Application Server except for starting and stopping the server itself can be done from the web administration console. You can use IBM Rational Application Developer, Eclipse, or a number of other IDEs to create J2EE applications that can run in WebSphere Application Server. For Eclipse, use the J2EE Standard Tools, also known as the J2EE Developer Tools version. You can also use the IBM Rational Application Developer images in the IBM Cloud catalog to take advantage of a pre-built environment.

To try it out in Rational Application Developer or Rational Software Architect, start a new enterprise application in Eclipse using the EAR Application Project wizard:


Figure 2. Eclipse EAR Application Project wizard
Eclipse EAR Application Project wizard

Call the project CloudAPIClientEAR. Click the Finish button. Next, create a dynamic web project; call it CloudAPIClientWeb. Add the dynamic web project to the CloudAPIClientEAR project:


Figure 3. Eclipse Dynamic Web Project Wizard
Eclipse Dynamic Web Project Wizard

Now let's create a HTML file and a servlet to test out the application. Add a file called index.html to the web content directory with some text like "My web application." Also, add a servlet with code like the class TestServlet:


Listing 1. Adding a servlet

package com.ibm.cloud.examples.servlet;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class TestServlet
 */
public class TestServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;

     protected void doGet(HttpServletRequest request, HttpServletResponse response) 
       throws ServletException, IOException {
          Writer writer = response.getWriter();
          writer.write("My web application");
     }
}

If you used Rational Software Architect or Eclipse, your web application archive web.xml file should be already configured for you. If not, make it look like this:


Listing 2. Your web application archive file should look like this

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" 
 xmlns="http://java.sun.com/xml/ns/javaee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
     <display-name>CloudAPIClientWeb</display-name>
     <servlet>
          <display-name>TestServlet</display-name>
          <servlet-name>TestServlet</servlet-name>
          <servlet-class>com.ibm.cloud.examples.servlet.TestServlet</servlet-class>
     </servlet>
     <servlet-mapping>
          <servlet-name>TestServlet</servlet-name>
          <url-pattern>/TestServlet</url-pattern>
     </servlet-mapping>
     <welcome-file-list>
          <welcome-file>index.html</welcome-file>
     </welcome-file-list>
</web-app>

Next, export the file. Right-click on the EAR project and choose Export to EAR. Name the file CloudAPIClientEAR.ear:


Figure 4. Rational Software Architect EAR Export Wizard
Rational Software Architect EAR Export Wizard

To add your enterprise application EAR file:

  1. Go to the WebSphere administration console in your browser.
  2. Navigate to Applications > New Application > New Enterprise Application and choose Upload from Local file system. Upload the EAR file and click Next.
  3. Choose the Fast Path option.
  4. Choose any directory to install the application.
  5. In the Map Modules to Servers panel, select CloudAPIClientWeb.
  6. Save the changes.
  7. Go to Applications > Application Types > WebSphere enterprise applications. Start the application.

Navigate to this URL to view the HTML page: http://host:9080/CloudAPIClientWeb/. You should see the text "My web application" that you added to the HTML page above. To see the servlet, enter this URL: http://host:9080/CloudAPIClientWeb/TestServlet. You should see the text that you emitted from the Writer in the TestServlet code.

Deploying in this way can become tiresome if you do it more than a few times. You can save a lot of time by using the remote deployment capabilities in Eclipse or IBM Rational Application Developer. It will automatically publish your J2EE application to the server instead of requiring you to step through all the screens in the WebSphere administration console. Use the New Server wizard to add the remote server, supplying the hostname or IP address and administration user id and password.

Now let's look at setting up and using Apache Maven to facilitate build automation.


Build automation with Maven

To set up Apache Maven, download it from the project website and define the environment variables as shown.


Listing 3. Define Maven's environment variables

set M2_HOME=D:\opt\apache-maven-3.0.3
set JAVA_HOME=D:\Program Files\IBM\SDP\jdk
set PATH=%JAVA_HOME%;%PATH%;%M2_HOME%\bin

You can perform the equivalent task for Linux®. To verify that Maven is available, execute the following command:


Listing 4. Verify Maven is available

>mvn --version
Apache Maven 3.0.3 (r1075438; 2011-03-01 01:31:09+0800)
Maven home: D:\opt\apache-maven-3.0.3
Java version: 1.6.0, vendor: IBM Corporation
Java home: D:\Program Files\IBM\SDP\jdk\jre
Default locale: en_US, platform encoding: GB18030
OS name: "windows xp", version: "5.1 build 2600 service pack 3", 
 arch: "x86", family: "windows"

You should see something like the information that shows up after the command in Listing 4.

In Maven, an archetype is a template for a project which includes a standard project structure that can be generated. That is good thing to know; in our previous example, you already have your own project created in your IDE and you were creating web and enterprise applications. Let's see how to address that and learn a little more about Maven in the process.

In Maven, a dependency, like a Java™ library packaged in a JAR, includes at least a groupId, an artifactId, a version, and a scope. To process dependencies, Maven looks in your local repository. If the dependency does not exist in your local repository, it will download it from an external repository into your local repository. The default external repository is at http://repo1.maven.org/maven2/. You can set up your own remote repository as well and the cloud would be a good place to do that.

Suppose that you have a dependency on a third-party JAR file. You can add that to your pom.xml with a stanza like:


Listing 5. Adding a dependency to a third-party JAR file

<dependency>
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.12</version>
  <scope>compile</scope>
</dependency>

This example is for the log4j library.

For licensing reasons, the J2EE and related libraries are not automatically available. You will need to go to the relevant website, agree to the terms and conditions, and download the JAR files yourself. Then use this command:


Listing 6. Installing the third-party dependencies

> mvn install:install-file -Dfile=/opt/apache-tomcat70/lib/servlet-api.jar 
  -DgroupId=javax -DartifactId=servlet-api -Dversion=3.0 -Dpackaging=jar

This example is the servlet APIs that are needed to compile a J2EE web project. To create a web application with the standard project structure, type the command:


Listing 7. Create a web app with the standard project structure type

> mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes 
  -DarchetypeArtifactId=maven-archetype-webapp 
  -DgroupId=com.iotdata -DartifactId=my-webapp

Maven creates the project tree in the directory my-webapp, including the pom.xml file. Let's not do that; instead, let's use the project that you already created in the previous section. Add the pom.xml file to the top directory of your web application project:


Listing 8. Adding the pom.xml file to web app project's top directory

<project xmlns="http://maven.apache.org/POM/4.0.0" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
   http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.iotdata</groupId>
  <artifactId>CloudAPIClientWeb</artifactId>
  <packaging>war</packaging>
  <version>1.0</version>
  <name>IoT Data Cloud API Client Web</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>javax</groupId>
      <artifactId>servlet-api</artifactId>
      <version>3.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>${pom.artifactId}</finalName>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Notice that the package is a WAR package. The pom.xml file uses the Maven WAR plug-in which creates the WAR package. Your directory structure is a little different from the standard structure, so add the sourceDirectory tag, which is a property of the build element. Notice that you used the dependency for the servlet API described earlier. The scope is set to provided so that you do not copy the servlet API JAR to your web application.

To build it, change directories to my-webapp and type this command:


Listing 9. Starting the build

> mvn package

You should find the output in the file CloudAPIClientWeb.war in the target directory. Deploy this to your application server, point your browser at http://host:8080/CloudAPIClientWeb, and you should see a page with the text "Hello World!"

You can manage multiple projects from within a single Maven file structure by using multiple pom.xml files. You will want to do this because the web application will be included in an enterprise application.

Create a pom.xml file like the one shown in Listing 10 above the CloudAPIClientEAR and CloudAPIClientWeb directories.


Listing 10. Making additional pom.xml files to manage additional projects

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.iotdata</groupId>
  <version>1.0</version>
  <artifactId>app</artifactId>
  <packaging>pom</packaging>
  <modules>
    <module>CloudAPIClientWeb</module>
    <module>CloudAPIClientEAR</module>
  </modules>
</project>

This defines modules for each of the CloudAPIClientWeb and CloudAPIClientEAR projects.

Listing 11 shows how to create a pom.xml file for the EAR project:


Listing 11. Create a pom.xml file for the EAR project

<project xmlns="http://maven.apache.org/POM/4.0.0" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
       http://maven.apache.org/maven-v4_0_0.xsd">
     <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.iotdata</groupId>
    <artifactId>app</artifactId>
    <version>1.0</version>
  </parent>
  <groupId>com.iotdata</groupId>
  <artifactId>CloudAPIClientEAR</artifactId>
  <packaging>ear</packaging>
  <version>1.0</version>
  <name>IoT Data Cloud API Client EAR</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
     <groupId>com.iotdata</groupId>
     <artifactId>CloudAPIClientWeb</artifactId>
     <version>1.0</version>
     <type>war</type>
    </dependency>
  </dependencies>
  <build>
    <finalName>${pom.artifactId}</finalName>
    <plugins>
     <plugin>
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-ear-plugin</artifactId>
       <version>2.4</version>
       <configuration>
         <earSourceDirectory>
          ${basedir}
         </earSourceDirectory>
         <modules>
           <webModule>
            <groupId>com.iotdata</groupId>
            <artifactId>CloudAPIClientWeb</artifactId>
            <bundleFileName>
              CloudAPIClientWeb.war
            </bundleFileName>
           </webModule>
          </modules>
       </configuration>
      </plugin>
    </plugins>
  </build>
</project>

This pom.xml file defines a parent that refers to the top level pom.xml. You also need to add this stanza to you web pom.xml. This time the package value is ear and it uses the Maven ear plug-in. It defines the web model from the web project from earlier.

Now clean and rebuild the entire project with this command:


Listing 12. Clean and rebuild the entire project

> mvn clean install

The EAR is built and includes the WAR file from the web application.

This is how you create a reproducible build; this is important because in test and production environments, developers are not allowed to connect to the application server with their IDEs.

Now let's examine how to generate a Maven plug-in that let's you automate server creation and deployment.


Maven Plug-in for server creation and deployment automation

In the section Build automation with Maven, we described how to work with Maven to build J2EE applications. Maven provides an extensible framework using a plug-in mechanism.

This section shows how to create a Maven plug-in that looks up or creates a virtual machine on the cloud using the IBM SmartCloud API:

  1. The plug-in first tries to look up the virtual machine instance.
  2. If it is found, then it can be used for provisioning the J2EE application.
  3. Otherwise, a new virtual machine is created.

To get started, generate a sample Maven plug-in project using the command line:


Listing 13. Generate the Maven plug-in

>mvn archetype:generate -DarchetypeArtifactId=maven-archetype-mojo 
 -DgroupId=com.ibm.cloud.enterprise.example 
 -DartifactId=sce-maven-plugin -DinteractiveMode=false

This creates a plug-in project directory tree with the MOJO (Maven Old Java Object) type.

Import the project into your IDE and add the Maven core and plug-in libraries to your IDE build path. Maven plug-ins implement the Mojo interface, usually by extending the AbstractMojo class. Add the source code for the SCEMojo class:


Listing 14. Add source code for the SCEMojo class

package com.ibm.cloud.enterprise.example;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;

import com.ibm.cloud.api.rest.client.DeveloperCloud;
import com.ibm.cloud.api.rest.client.DeveloperCloudClient;
import com.ibm.cloud.api.rest.client.bean.Address;
import com.ibm.cloud.api.rest.client.bean.Instance;
import com.ibm.cloud.api.rest.client.bean.Volume;
import com.ibm.cloud.api.rest.client.exception.*;

/**
 * @goal create_instance
 */
public class SCEMojo extends AbstractMojo {
     
     private DeveloperCloudClient client = DeveloperCloud.getClient();
     private Log log = getLog();
     
     /**
     * The user name for the cloud account
     * @parameter expression="${create_instance.user_name}"
     */
    private String user_name;
     
     /**
     * The password for the cloud account
     * @parameter expression="${create_instance.password}"
     */
    private String password;
     
     /**
     * The name of the server to lookup or create
     * @parameter expression="${create_instance.name}" default-value="app_server"
     */
    private String name;
     
     /**
     * The data center to create the server in
     * @parameter expression="${create_instance.data_center}"
     */
    private String data_center;
     
    /**
     * The image ID to create the server with
     * @parameter expression="${create_instance.image_id}"
     */
    private String image_id;
    
    /**
     * The name of the SSH key to create the server with
     * @parameter expression="${create_instance.key_name}"
     */
    private String key_name;

    /**
     * The name of the WebSphere administrative user
     * @parameter expression="${create_instance.was_admin_user}"
     */
    private String was_admin_user;
    
     /**
     * The name of the WebSphere administrative user password
     * @parameter expression="${create_instance.was_admin_password}"
     */
    private String was_admin_password;
    
}

The code already has the imports for the methods that you will add below. The class-level JavaDoc has an @goal tag. This is required and indicates the build goal which is create_instance. The private fields user_name, password, name, data_center, image_id, key_name, was_admin_user, and was_admin_password are parameters that are passed in by users of the plug-in. The parameters are:

  • user_name:The user name for the cloud account
  • password:The password for the cloud account
  • name:The name of the server to lookup or create, default value="app_server"
  • data_center:The data center to create the server in
  • image_id:The image ID to create the server with
  • key_name:The name of the SSH key to create the server with
  • was_admin_user:The name of the WebSphere administrative user
  • was_admin_password:The name of the WebSphere administrative user password

Classes implementing the Mojo interface must implement the execute method. Add the execute method:


Listing 15. Adding the execute method

public void execute() throws MojoExecutionException {
     try {
              log.info("Logging onto cloud with user name " + user_name);
              client.setRemoteCredentials(user_name, password);
              log.info("Looking for a server with name " + name);
          List<Instance> instances = client.describeInstances();
              log.info("Found " + instances.size() + " instances");
              boolean found = false;
              for (Instance instance: instances) {
                   if ((instance.getStatus() == Instance.Status.ACTIVE) &&
                        instance.getName().equals(name)) {
                        log.info("Found a server with name " + name);
                        found = true;
                   }
              }
              if (!found) {
                   log.info("No server with name " + name + " found");
                   createInstance();
              }
     } catch (Exception e) {
              log.warn(e);
          throw new MojoExecutionException(e.getMessage());
     }
}

The method first sets the user's credentials, then retrieves a list of virtual machines owned by the user. It iterates over the list of virtual machines looking for an active instance with the same name as the parameter provided by the user.

If a matching virtual machine is found, then you are done. Otherwise, you create a virtual machine with the createInstance() method by adding this method to the SCEMojo class:


Listing 16. Creating a VM with createInstance() by adding it to SCEMojo class

private void createInstance() throws InsufficientResourcesException, 
              InvalidConfigurationException, PaymentRequiredException, 
              UnauthorizedUserException, UnknownErrorException, IOException {
     Address address = null;
     Volume volume = null;
     Address[] secondaryAddresses = new Address[0];
     Map parameters = new HashMap<String,Object>();
     parameters.put("WASAdminUser", was_admin_user);
     parameters.put("WASAdminPassword", was_admin_password);
     List<Instance> newInstances = client.createInstance(
               name, // Name of instance
               data_center, // Data center ID
               image_id, // Image ID
               "COP32.1/2048/60", // Instance type
               key_name, // Key
               address, // Address
               volume, // Volume
               parameters, // Options
               null, // VLAN ID
               secondaryAddresses, // Seconday IP addresses
               true); // Minimum ephemeral
     Instance instance = newInstances.get(0);
     log.info("ID: " + instance.getID());
}

The method creates the virtual machine with the parameters provided by the user and writes the instance ID to the log.

As shown in Listing 17, now create a pom.xml file for the plug-in:


Listing 17. Create a pom.xml file for the plug-in

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
 http://maven.apache.org/xsd/maven-4.0.0.xsd" 
 xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ibm.cloud.enterprise</groupId>
  <artifactId>sce-maven-plugin</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>maven-plugin</packaging>
  <name>sce-maven-plugin Maven Mojo</name>
  <url>http://ibm.com/cloud/enterprise</url>
  <dependencies>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-plugin-api</artifactId>
      <version>2.0</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.3</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.3</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.ibm.cloud.enterprise</groupId>
      <artifactId>DeveloperCloud_API_Client</artifactId>
      <version>1.4.1</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>
</project>

The pom.xml file uses a maven-plugin package type. It defines a maven-plugin-api dependency and dependencies on the IBM SmartCloud Enterprise Java API and its dependent libraries, Apache HTTP Client, Commons, Logging, Codec, and Lang. The Apache libraries can be downloaded automatically by Maven from the Maven central repository.

Download and install the SmartCloud API library into your local repository:


Listing 18. Download the SmartCloud API library to your local repository

mvn install:install-file -Dfile=/opt/sce/DeveloperCloud_API_Client_1.4.1.jar 
 -DgroupId=com.ibm.cloud.enterprise 
 -DartifactId=DeveloperCloud_API_Client 
 -Dversion=1.4.1 -Dpackaging=jar

Now, you should adjust the file parameter to be consistent with your local environment.

Next, build and install the plug-in into your local repository:


Listing 19. Build and install the plug-in to your local repository

>mvn package
>mvn install

Now you can use the plug-in for a project. Let's generate the project cloud-app with the Maven generate command:


Listing 20. Generate a project with the Maven generate command

mvn archetype:generate -DgroupId=com.ibm.cloud.enterprise 
 -DartifactId=cloud-app 
 -DarchetypeArtifactId=maven-archetype-quickstart 
 -DinteractiveMode=false

Import the new project into your IDE. Modify the pom.xml generated to add a dependency and plug-in configuration:


Listing 21. Modify pom.xml to add dependency and plug-in configuration

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
 http://maven.apache.org/xsd/maven-4.0.0.xsd" 
 xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ibm.cloud.enterprise</groupId>
  <artifactId>cloud-app</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>cloud-app</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.ibm.cloud.enterprise</groupId>
      <artifactId>sce-maven-plugin</artifactId>
      <version>1.0-SNAPSHOT</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>com.ibm.cloud.enterprise</groupId>
        <artifactId>sce-maven-plugin</artifactId>
        <version>1.0-SNAPSHOT</version>
        <configuration>
          <user_name>a.user@example.com</user_name>
          <password>****</password>
          <name>was</name>
          <data_center>101</data_center>
          <image_id>20015399</image_id>
          <key_name>july26</key_name>
          <was_admin_user>wasadmin</was_admin_user>
          <was_admin_password>***</was_admin_password>
        </configuration>
        <executions>
          <execution>
            <phase>compile</phase>
            <goals>
              <goal>create_instance</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

Notice the use of the parameters in the configuration section.

Now you are ready to try the plug-in. First check with a new instance and existing instance; invoke the plug-in with the Maven goal shown below.


Listing 22. Invoke the plug-in

>mvn com.ibm.cloud.enterprise:sce-maven-plugin:1.0-SNAPSHOT:create_instance

If you do not already have a virtual machine with the given name, you should see output like this:


Listing 23. Output if you DON'T have a VM with the given name

[info] Logging onto cloud with user name a.user@example.com
[info] Looking for a server with name was
[info] Found 4 instances
[info] No server with name was found
[info] ID: 112332
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] 
...

If you already have a virtual machine with the given name, you should see output like this:


Listing 24. Output if you DO have a VM with the given name

...
[INFO] --- sce-maven-plugin:1.0-SNAPSHOT:create_instance (default-cli) @ cloud-a
pp ---
[info] Logging onto cloud with user name aamies@cn.ibm.com
[info] Looking for a server with name was
[info] Found 5 instances
[info] Found a server with name was
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ----------------------------------------------------------------------
...

Remember that if you just executed the command in Listing 22 to create a server, it takes some time to create.

So far in this article, this has been a good way to see how cloud can fit into the development and deployment life cycle, but you have a few more steps to make this process even more useful in the life cycle.

We've demonstrated that it takes some time to create a server. You need a polling mechanism to wait for this to complete; however, there is an additional challenge here, to determine when the application server itself has come up which will be only after the virtual machine provisioning and the operating system has started. You can use the WebSphere wasadmin APIs for this. When you have an active server with the application server running, you can deploy our J2EE application to it. When you are done with the WebSphere server, you may want to delete it. You might want to add that into the cleaning phase of the life cycle or somewhere else.


Next steps

Some further tasks that you might want to take or include:

  • Creating a private Maven repository on the IBM Cloud. This is an important task because an enterprise will typically want to keep its unreleased, proprietary, or commercially purchased software separate from already released open source software stored in public repositories. This will simplify sharing of software within the enterprise and with business partners and keep it isolated from the public at large.
  • Creating a cloud API project template. A project template is useful to simplify creating multiple cloud projects, standardizing best practices, and eliminating repetition.

J2EE application servers have a number of features that assist with achieving performance and availability goals. One of the main features is the ability to cluster application servers to distribute load. A cluster is a group of application server nodes or individual application servers that works as a group to balance workload. In cloud computing, you have the opportunity to create virtual machines dynamically and these can act as nodes in the cluster.

WebSphere Application Server is a J2EE platform that is particularly suitable for managing large-scale clusters. All the steps that can be performed in the WebSphere administrative console can be scripted with the wsadmin tool and commands, including Java programs with the Java Management eXtensions (JMX) and Jython scripts. You can combine this knowledge of the WebSphere network deployment model with the knowledge of creating and customizing images and what you've learned about the IBM SmartCloud Enterprise REST API to automate provisioning of elements of a WebSphere cluster. You do this by:

  1. Starting with a base WebSphere Application Server image, then customize the profile with the Profile Management Tool and the application server with the administrative console.
  2. Save the virtual machine to an instance with the IBM Cloud user interface or REST API.
  3. Use the IBM Cloud REST API to provision new virtual machines.
  4. Use the wsadmin tool to join the new virtual machines to the cluster and synchronize application deployment across the nodes, including deploying your J2EE application.

In conclusion

This article introduced a sample J2EE project for you to use on the IBM Cloud; a WebSphere Application Server image that provides a J2EE environment without having to install any additional software. It outlined the steps to set up Apache Maven in your environment to get started with build automation. We described how to work with Maven to build J2EE applications. It showed you how to create a Maven plug-in that looks up or creates a virtual machine on the cloud using the IBM SmartCloud API. And as a bonus, we started you on the path to some other similar tasks you might want to do, including how to create a private Maven repository on the IBM Cloud and how to build a cloud API project template.

The only thing left for you to do is to experiment.


Resources

Learn

Get products and technologies

Discuss

About the authors

Alex Amies photo

Alex Amies is a senior software engineer in the IBM GTS Development Lab in the China development lab. He is currently an architect working on the design of the IBM SmartCloud Enterprise. Previously, he acted as an architect and a developer on cloud and security products in other groups within IBM.

Pan Xia Zou is staff software engineer at IBM and works as a build and deployment automation architect for IBM SmartCloud Enterprise.

Yi Shuai Wang is an Advisory Architect at IBM and lead developer for the development of the business support services of IBM SmartCloud Enterprise.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Cloud computing, Java technology, Open source
ArticleID=768556
ArticleTitle=Automate development and management of cloud virtual machines
publish-date=10292011