Wednesday, 4 April 2012

Publishing Java Application in Windows Azure Environment - Part 1


Windows Azure is a Platform as a Service (PaaS) environments, where we not only host .NET applications also other technology applications such as Java, php etc.,

When I had an opportunity to develop a POC for my customer by hosting Java applications on Azure, it was a challenge (as I know nothing about Java). In this post, I am taking the same learning and giving a step by step way for hosting Java application on Azure.

Note:
  1. For this exercise, I am taking a fresh AWS machine and install all the required components to develop a Java application. Finally I am going to host to Azure.
  2. This post will give a start-up for hosting a simple Java application. It may not provide a full fledged application developed in Java. I am taking a fresh system and installing all components required for this exercise.
Before going for hosting Java application on Azure, we will first create a sample application in local and test.

Preparing our system for Developing Java Application:

If you are already having a development environment for Java, you can skip this section.

Step 1: Download JDK into your system. The JDK can be found in the following location.

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Accept the license agreement. (Note: You can even download and install JRE runtime instead JDK.)


Step 2: Run the JDK file (ex: jdk-7u3-windows-x64.exe) to install Java Runtime in your system by accepting all the parameters are default.

Step 3: As we are going to create a JSP Application, we required a web server to run the application. We can use any of the following as web server for running the Java application.
  1. Apache Tomcat
  2. Glass Fish
  3. JBoss
  4. Jetty
In this exercise, I am going to use Apache Tomcat as web server. So download the Apache Tomcat from the following url.

http://tomcat.apache.org/download-70.cgi

select
Step 4: Expand the Zip file (Ex: apache-tomcat-7.0.26) and copy the apache-tomcat-7.0.x directory to local drive (I copied to c drive).
Step 5: We also require an IDE for developing Java Application. Normally we use eclipse for developing Java Application.
So, download the Zip file for eclipse IDE for Java EE development from the below link.
http://www.eclipse.org/downloads

Step 6: Extract the Zip file and run the eclipse.exe file for installing of eclipse software in to your system.
Step 7: Accept the default workspace location and install the software.

Step 8: Once eclipse installed successfully, it will open the IDE by default. Select the File -> New -> Others -> Web -> Dynamic Web Project and press Next.
Note: First time only we required to select from Others menu to create Dynamic Web Project. From the next time, it will be available from File -> New itself.

Step 9: Provide the Project name (Ex: JSPSampleApp) and press Finish. If Open Associated Perspective? Shows, accept (press Yes) to create the project.

Step 10: Right click the WebContent folder in the Project Explorer and select New -> JSP File.
Step 11: Name the file to index.jsp and press Finish.
Step 12: Add “Hello World” in the HTML file to show something on the web page while running.
Step 13: Right click the JSPSampleApp project and select RunAs -> Run on Server (or Alt+Shift+X, R).
Step 14: Select Tomcat v7.0 Server under Apache (or what server you downloaded) in the Run On Server window.
Press Next.
Step 15: Press Browse button and select the Apache installation location.
Press Finish.

The eclipse will open the site and show Hello World.

Now we had created a sample page. Let’s change the same page something meaningful.

Modifying the index.jsp Page

Let us modify the same index.jsp page something meaningful to get a feel of a working screen. For that, I am going to modify the page to send mails from gmail server by getting from and to mail ids with subject and body from user.

Step 1: For sending mails from Java, we need to import a package called javax.mail and it required mail.jar file to be included in the project.
So download mail.jar (with the latest version no, Ex: mail-1.4.jar) file from web or you can get it from the source code I included at the end of the post.

Step 2: Copy the mail-1.4.jar (I downloaded version 1.4) under WebContent\WEB-INF\lib folder and refresh the lib folder in the eclipse.
Step 3: We have to refer this assembly into our project. So right click the JSPSampleApp project and select Properties. Select the Java Build Path from the tree and select Libraries tab.
Step 4: Click Add JARs and select the mail-1.4.jar file. (So we can get an idea how to package with jar file also in the Azure deployment)
Click OK to close the window.
Click OK to close the Properties of JSPSampleApp window.
Step 5: Copy and paste the following JSP code in the body section.
<%@ page import="java.util.*" %>
<%@ page import="javax.mail.*" %>
<%@ page import="javax.mail.internet.*" %>
<%@ page import="javax.activation.*" %>
<form action="index.jsp" method="post">
 <table>
  <tr>
   <td>From Mail Id</td>
   <td><input id='txtFromMailId' name='fromMailId' type="text" value="" style="width:250px" /></td>
  </tr>
  <tr>
   <td>To Mail Id</td>
   <td><input id='txtToMailId' name='toMailId' type="text" value="" style="width:250px" /></td>
  </tr>
  <tr>
   <td>Subject</td>
   <td><input id='txtSubject' name='subject' type="text" value="" style="width:350px" /></td>
  </tr>
  <tr>
   <td>Body</td>
   <td><textarea id='txtBody' name='body' style="width:350px;height:100px"></textarea></td>
  </tr> 
  <tr>
   <td colspan="2" style="text-align:center">
    <input type="hidden" name="isSubmitted" value="1" width="100px" />
    <input type="submit" value="Send" >
   </td>
  </tr>
 </table>
</form>
<%
String val = request.getParameter("isSubmitted");
int isSubmitted = 0;
if (val != null) {

 isSubmitted = Integer.parseInt(val);
 if (isSubmitted == 1) {
  String host = "smtp.gmail.com";
  String to = request.getParameter("toMailId");
  String from = request.getParameter("fromMailId");
  String subject = request.getParameter("subject");
  String messageText = request.getParameter("body");
  if ((from.trim().length() > 0) &&
   (to.trim().length() > 0) &&
   (subject.trim().length() > 0) &&
   (messageText.trim().length() > 0)
  )
  {
   boolean sessionDebug = false;
   // Create some properties and get the default Session.
   Properties props = System.getProperties();
   props.put("mail.host", host);
   props.setProperty("mail.transport.protocol", "smtps");
   props.put("mail.smtp.starttls.enable", "true");
   props.put("mail.smtp.user", "mymailid@gmail.com"); // Change your mail id here
   props.put("mail.smtp.password", "pass@ord"); // Change your mail id password here
   props.put("mail.smtps.auth", "true");
   
   Session mailSession = Session.getDefaultInstance(props, null);
    
   // Set debug on the Session
   // Passing false will not echo debug info, and passing True will.
    
   mailSession.setDebug(sessionDebug);
    
   // Instantiate a new MimeMessage and fill it with the 
   // required information.
    
   Message msg = new MimeMessage(mailSession);
   msg.setFrom(new InternetAddress(from));
   InternetAddress[] address = {new InternetAddress(to)};
   msg.setRecipients(Message.RecipientType.TO, address);
   msg.setSubject(subject);
   msg.setSentDate(new Date());
   msg.setText(messageText);
    
   // Hand the message to the default transport service
   // for delivery.
   Transport transport = mailSession.getTransport("smtps");
   transport.connect(host, "mymailid@gmail.com", "pass@ord"); // Change your mail id and password here
   transport.sendMessage(msg, msg.getAllRecipients());
   transport.close();
   out.println("<b style='color:green;font-size:17px'>Mail Sent Successfully!!!</b>");
  }
  else
  {
   out.println("<b style='color:red;font-size:15px'>Please fill all the details before sending mail.</b>");
  }
 }
}
%>
Note: This code uses Gmail SMTP server and it require authentication for sending any mails. So change the any Gmail address and password in this code which need to use for authentication. It is also important to note the mail id you are using should Enable POP setting.

Step 6: Run the project by right clicking the project and selecting Run As -> Run As Server.
Select the Tomcat server (Ex: Tomcat v7.0 Server at localhost) and press Finish.
Step 7: The eclipse shows a page for inputting the From, To, Subject and Body content for sending mail.

Step 8: Provide some information and test the mails are arriving in to mail box.

The next post will talk about the remaining steps on publishing Java applications on Azure.

download the working copy of the source code here.

0 Responses to “Publishing Java Application in Windows Azure Environment - Part 1”

Post a Comment