azure-and-java

Deploying a Java application to Windows Azure with Command-line Ant

Recommended Reading

Whether you are building a brand new application, or already have something built and wish to take advantage of the high availability and scalability of the Windows Azure cloud, this tutorial will show you how to package and deploy your application and runtime elements.

Download the Windows Azure Starter Kit for Java

To start things out we need to go download the Windows Azure Starter Kit for Java from the CodePlex project page.

The files can be found at: http://wastarterkit4java.codeplex.com/

The Windows Azure Starter Kit for Java uses Apache Ant as part of the build process. If you are not familiar with Ant, go check the installation manual which can be found at http://ant.apache.org/manual/index.html. Ant can be downloaded from the Apache project page at http://ant.apache.org

Note: Ant requires several environment variables to be set, ANT_HOME, CLASSPATH, and JAVA_HOME. Ensure these are set correctly. See http://ant.apache.org/manual/install.html#setup

Inside the Windows Azure Starter Kit for Java

The file you just downloaded is a Zip file that contains a template project. You need to first extract the project. This is a pretty straight forward process. Right click on the archive, choose “Extract All…” and select the destination to extract the project to.

If you look inside this archive you will find the typical files that constitute a Java project, as well as several files we built that will help you test, package and deploy your application to Windows Azure.

The main elements of the template are:

  • .cspack.jar: Contains that java implementation of windowsazurepackage ant task.
  • ServiceConfiguration.cscfg: This is Azure service configuration file. See the “What next?” section for more details.
  • ServiceDefinition.csdef This is Azure service definition file. See the “What next?” section for more details.
  • Helloworld.zip: This Zip is provided as a very simple sample application. Since we want to build a snazzy web application we can safely delete this file.

    Note: Do not delete the util folder! This folder contains needed project files.

  • startup.cmd: This script is run each time your Worker Role starts. Here you will define anything that needs to take place on startup, such as starting a Java server, or firing off a background service.
  • unzip.vbs: Simple script we provided to make it easy to unzip zipped archives.
  • download.vbs – a simple utility script for downloading files from URL locations into the approot as part of the startup. This helps avoid the need to embed certain types of files, for example large and rarely changing files (such as the Java runtime, or a server distribution) into the deployment package itself, making it much smaller and faster to upload. The URL could point to any download that does not require additional authentication (such as public websites, or Windows Azure blobs with anonymous access enabled) or one where all the authentication information needed is embedded in the URL (such as Windows Azure blobs with shared access signature authentication enabled.)

Select the Java server environment

The project template is designed to work with multiple Java server environments.

As we progress through this tutorial I will show you how to setup two servers, Tomcat and Jetty. You are definitely not limited to using only these two servers.

Download the server distribution and copy it into the approot folder of the project. We do not need to extract the server from the archive file. The startup.cmd script will take care of the extraction for us.

The packages I am using can be found at

Using Tomcat Server

Using Jetty Server

Author note: I have placed each archive in it’s own directory because I feel it is easier to quickly find files in the file tree this way. You are not forced to repeat this in your project. You may place the files wherever you like in your approot folder, just be sure to update the startup.cmd script with the correct paths.

Select the Java Runtime Environment

As with the server, feel free to choose whatever Java runtime environment you are comfortable with using. For this sample, I will be using the Java Runtime Environment (JRE) shipped by Oracle. Download the JRE and copy it in the approot folder. You do not have to extract the JRE.

The Oracle JRE can be found at http://www.oracle.com/technetwork/java/javase/downloads/index.html

Unfortunately there is not a Zip version of the JRE, only the installer. The solution therefore seems to be creating your own Zip. I created mine by zipping C:Program FilesJavajre6

Note: For more information on this issue see this stackoverflow article http://stackoverflow.com/questions/1619662/where-can-i-get-the-latest-jre-jdk-as-a-zip-file-i-mean-no-exe-installer

Prepare your Java application

Go ahead and delete the HelloWorld.zip file.

Note: Do not delete the util folder! This folder contains needed project files.

Start off by creating a simple HelloWorld.jsp in the approot folder. Later you can expand the application by copying in your current application, or creating the application code directly in the approot folder.

HelloWorld.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"



pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

    <title>Insert title here</title>

</head>

<body>



<%!

public String GetString() {

return ""Look! I work!"";

}

%>



The Java Server is Running = <%= GetString() %>



</body>

</html>

Configure project files startup.cmd and ServiceDefinition.csdef:

The next step is to edit the startup.cmd and ServiceDefinition.csdef files with the appropriate commands relative to the server environment.

Open startup.cmd inside the approotutil folder and replace the content with the following commands, for either Jetty or Tomcat.

Tomcat


@REM unzip Tomcat

cscript /B /Nologo utilunzip.vbs Tomcatapache-tomcat-7.0.6-windows-x64.zip .

@REM unzip JRE

cscript /B /Nologo utilunzip.vbs JREjre6.zip .



@REM copy project files to server

md apache-tomcat-7.0.6webappsmyapp

copy HelloWorld.jsp apache-tomcat-7.0.6webappsmyapp



@REM start the server

cd apache-tomcat-7.0.6bin

set JRE_HOME=....jre6

startup.bat

Jetty


@REM unzip Jetty

cscript /B /Nologo utilunzip.vbs Jettyjetty-distribution-7.2.2.v20101205.zip .



@REM unzip JRE

cscript /B /Nologo utilunzip.vbs JREjre6.zip .



@REM copy project files to server

md jetty-distribution-7.2.2.v20101205webappsmyapp

copy HelloWorld.jsp jetty-distribution-7.2.2.v20101205webappsmyapp



@REM start the server

cd jetty-distribution-7.2.2.v20101205

start ..jre6binjava.exe -jar start.jar

I referenced specific file names above. Be sure you change the file names to match your own version.

Save startup.cmd and open ServiceDefinition.csdef in your main project folder. We need to add an endpoint so we can get to our application in the browser later. Add the following line right before the closing <WorkerRole> tag. This tag tells the Windows Azure load balancer to forward port 80 traffic to port 8080 on the machine running the Azure instance.The configuration is the same for either Jetty or Tomcat.


<Endpoints>

      <InputEndpoint name="Http" protocol="tcp" port="80" localPort="8080" />

</Endpoints>

Your ServiceDefinition.csdef should now look similar too:


<?xml version="1.0" encoding="utf-8"?>

<ServiceDefinition name="WindowsAzureCloudServiceProject" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition">

  <WorkerRole name="WorkerRole1">

    <Startup>

      <!-- Sample startup task calling startup.cmd from the role's approotutil folder -->

      <Task commandLine="utilstartup.cmd" executionContext="elevated" taskType="simple"/>

    </Startup>

    <Endpoints>

      <InputEndpoint name="Http" protocol="tcp" port="80" localPort="8080" />

    </Endpoints>

  </WorkerRole>

</ServiceDefinition>

Starting the local Windows Azure cloud platform

There are two options for starting the local Windows Azure cloud platform, via the GUI or via the command-line. The GUI is simple and easy to use, while the command-line is useful in scripts and automation.

Starting the local Windows Azure cloud platform via the GUI

In the Start Menu you will to find the “Windows Azure SDK”, click on it. Click on “Compute Emulator”. You may also start the Storage Emulator from the Start Menu.

You will now have an icon in you system tray. From that icon you can open the Compute Emulator UI, Storage Emulator UI, Start/Stop Compute Emulator, and Start/Stop Storage Emulator (Storage Emulator is not needed for this sample).

Starting the local Windows Azure cloud platform via the command-line

To start the local Windows Azure cloud platform via the command-line ensure you have a Windows Azure SDK Command Prompt open. You can get to the command prompt via the Start Menu (see image above):

Type the following command to start the emulator.

csrun /devfabricsc:start

[Optional] If your sample application is using any of the Windows Azure Storage features (Blogs, Tables, Queues), then type the following command to start the storage emulator

csrun /devstore:start

If you would like to see all the options available to csrun type the following command

csrun /?

Build the package

Still inside the Windows Azure SDK Environment prompt, navigate to your project directory. Building the application is as simple as running the following command.

ant -buildfile package.xml

The command tells Ant to use the information contained within the package.xml file to build your application. Be patient, this could take some time depending on the size of your application and the resources available on your machine. If the build was successful you should see output similar to:

Note: If you receive a “BUILD FAILED … The package directory does not exist” message you may need to manually create the deploy directory.

(Side note: The current version of the Windows Azure Starter Kit for Java relies on Windows Azure SDK 1.4. If you’ve created Eclipse projects based on an older release of the Starter Kit and are now upgrading your Windows Azure SDK to version 1.4, those older projects will no longer build, until you make this minor adjustment to the package.xml file in those projects: find the string “v1.3” and replace it with “v1.4″.)

When your project is configured for local deployment to the emulator (packagetype=”local” in package.xml) a folder named “emulatorTools” will be created next to the “deploy” folder after you build the project. The emulatorTools folder will contain three simple scripts that make it quicker and easier to display and reset the Windows Azure compute emulator and run your service in it:

  • RunInEmulator.cmd
    • This script will start up the local Windows Azure development cloud and deploy your project to it. (If you’re familiar with the first release of the Windows Azure Starter Kit for Java, this script originally existed as “csrun.cmd” in the “deploy” folder)

      Note: If you are using development storage you will still need to start the Storage Emulator manually.

  • ResetEmulator.cmd
    • Removes any running instances of your application from the Compute Emulator and unlocks the files in use by the emulator. This is helpful when you’re about to rebuild but your previous build is still running in the emulator. Unless you remove your older deployment from the emulator, the emulator will keep a lock on the files in the “deploy” folder preventing you from a successful rebuild. This script helps you quickly get that taken care of before you rebuild.
  • DisplayEmulatorUI.cmd
    • Quick and easy way to start the Compute Emulator UI without leaving Eclipse.

Note: if you open one of these files in Eclipse with Text Editor, Eclipse will remember that and double-clicking on them will not run them but instead open them as text files again. To run them, you need to Open With | System Editor.

The final step is to descend into the emulatorTools directory and run the server in the emulator.

cd emulatorTools

RunInEmulator

Your application should now be running on port 8080. Open your web browser and type http://localhost:8080/myapp/HelloWorld.jsp into the URL bar.

Packaging the application for deployment on Windows Azure

Now I need to talk a little more about the package.xml file. If you open the package.xml file you will find a specific tag that controls whether your application is built for local development or production on the Windows Azure cloud. The tag you are looking for in package.xml is:

<windowsazurepackage

 sdkdir="${wasdkdir}"

 packagefilename="WindowsAzurePackage.cspkg"

 packagedir = "${wapackagedir}"

 packagetype="local"

 projectdir="${basedir}"

 definitionfilename="ServiceDefinition.csdef"

 configurationfilename="ServiceConfiguration.cscfg"

>

Take note of the packagetype attribute. This attribute can be set to either local or cloud. When packagetype=”local” your application will be built into the exact structure that will be on the Windows Azure cloud, however it is not archived for upload. If packagetype=”cloud” your application will be built and archived as a .cspkg file. You can then log in to the Windows Azure Portal and upload the .cspkg and .cscfg files to deploy your application in the cloud.

The package.xml is a very powerful build file with many options for customizing your application. The file contains a wealth of comments that describe many of the options available to you. Take some time and familiarize yourself with the comments as this file will be incredibly useful to you in future projects.

Note: Please do not try to change the name of your worker role until you have read the article on Changing the name of your Worker Role.

Deploying your application to the Windows Azure cloud

Deploying your application to the Windows Azure cloud is as simple as logging in to the Windows Azure Portal and uploading the .cspkg and .cscfg files creating when you built your package for the cloud.

For specific details on deploying please see the following articles:

http://msdn.microsoft.com/en-us/library/gg433027.aspx

http://msdn.microsoft.com/en-us/windowsazure/ff798117.aspx

Congratulations, you now have successfully setup and run your first Windows Azure application! Check out the links in the “What next?” section for more examples.

What next?

Reposted from Java Interoperability Bridges by Ben Lobaugh.  Used with author’s permission. —