Wednesday, 25 July 2012

Google App Engine Application (Cloud Computing)


    



    

    
Cloud computing is emerging technology in today’s world. It is basically combination of application, datastore and internet.

 Whatever application you develop interacts with datastore through internet i.e. you can store data and retrieve it via internet. Datastore is the main thing provided by cloud.
There are several cloud providers like Google, Amazon. Cloud provided by Google is free where as to use Amazon cloud we need to pay. Here I will talk about Google cloud. Google provides Google App Engine (GAE), which is a platform for “deployment” of your web application and it provides “Java Datastore Object (JDO)” .It is data storage.
1. What is Google App Engine?
2. What is JDO? 
 As Google App Engine is provided by Google, you need Google id (gmail id). You can do goggle search as “Google App Engine sign in” and you can login by using gmail id. You can create at most 10 applications on that gmail id.
 JDO is a datastore, in MySql we have tables but in JDO we have classes. So in our project we have classes with parameterized constructor, get methods and set methods. These are basically interfaces to interact with database.
Following is a step by step approach to develop your first web application.
You must have, 

1.eclipse-jee-galileo-win32.zip
2.appengine-java-sdk-1.4.0.rar
3.gpe-e35-latest-plugin.zip   Download https://sites.google.com/site/ccomputingapp/cloudsetup/3.%20gpe-e35-latest%20-%20plugin.zip?attredirects=0&d=1

Extract them wherever you want.
Following is a example project to create new account, so it will have one html page to create new account i.e. to enter new username and password, So basically there will be one html page which will take username and password and after clicking on “create” button it will call one servlet which will get the parameters and insert these details into database on cloud.
Now open eclipse, then new -> web application project.

Now configure app engine sdk, brows the path where you have extracted app engine sdk.


 Final structure of your project will look like,

Whatever database we are going to use is not local, it is remote, i.e. it is on google app engine, so java classes is the interface to interact with database. Whatever table we want to create in our project, first we must create class, e.g. I want to create table which will store username and password, so I must create class containing data members as username and password, and I must provide get and set methods and one parameterized constructor(with parameters as username and password).
For our project following is the class “Idpassword” with data members username and password, app engine will automatically generate unique id for each record, so we are not required to worry about it.

Idpassword.java:-

package firstapp;
import com.google.appengine.api.datastore.Key;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import java.util.Date;
@PersistenceCapable
public class Idpassword
{
                @PrimaryKey
                @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
                private Key key;
                @Persistent
                private String username;
                private String password;
                public Idpassword ()
                {
                }
            public Idpassword (String username, String password)
                {
                                this.username = username;
                                this.password = password;      
                }
            public Key getKey()
                {
                    return key;
                }             
                public void setUserId(String username)
                {
                    this.username=username;
                }                             
                public void setPassword(String password)
                {
                                this.password=password;
                }
                public String getUserId()
                {
                    return username;
                }                             
                public String getPassword()
                {
                                return password;
                }
                }

This is html code with two textboxes as username and password.

firstpage.html:-


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<body>
<center>
<form action="/myfirstapp" method="post">
<h1><font color=blue size=10>Create Account</h1></font>
Userid: <input type="text" name=userid><br></br>
Password: <input type="password" name=password><br></br>
<input type="submit" value="create"></input>
</form>
</center>
</body>
</html>

Persistence Manager Factory object is used to access the database, like in jdbc we must have connection object. So we will have one java class ”PMF”.

PMF.java :-

package firstapp;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;
public final class PMF
{
    private static final PersistenceManagerFactory pmfInstance = JDOHelper.getPersistenceManagerFactory("transactions-optional");
    private PMF() {}
    public static PersistenceManagerFactory get()
    {
        return pmfInstance;
    }
}
Now we will write servlet.

MyFirstAppServlet.java :-

package firstapp;
import java.io.IOException;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.logging.Logger;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory ;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Transaction;
import firstapp.PMF;

@SuppressWarnings("serial")
public class MyFirstAppServlet extends HttpServlet
{
         private static final Logger log = Logger.getLogger(MyFirstAppServlet.class.getName());
          @PrimaryKey
          @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
          private Key key;  
          String username;
          String password;
          PersistenceManager pm = null;
        public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
         {
          try
           {
            pm = PMF.get().getPersistenceManager();

            pm.currentTransaction().begin();

            username=req.getParameter("userid");           
            password=req.getParameter("password"); 
        
            Idpassword newuser=new Idpassword(username,password);   //create new object to insert into database
            pm.makePersistent(newuser);  //insert record into database
            pm.currentTransaction().commit(); 

            PrintWriter out=resp.getWriter();
            out.println("<html><body><h1>Record Inserted Successfully</h1></body></html>");
}
catch(Exception e){}
}
}

In any web application, whether it is on cloud, tomcat or websphere server, any webserver, we must do xml mappings i.e. mappings of servlet classes, we must map each servlet to specific URL, like in above html code we have “form action=”/myfirstapp””, is basically URL for the servelt “MyFirstAppServlet” which is mapped to the URL “/myfirstapp” as follows,

web.xml:-

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
                <servlet>
                                <servlet-name>MyFirstApp</servlet-name>
                                <servlet-class>firstapp.MyFirstAppServlet</servlet-class>
                </servlet>
                <servlet-mapping>
                                <servlet-name>MyFirstApp</servlet-name>
                                <url-pattern>/myfirstapp</url-pattern>
                </servlet-mapping>
                <welcome-file-list>
                                <welcome-file>firstpage.html</welcome-file>
                </welcome-file-list>
</web-app>

And in the welcome-file-list tag we give the name of html or jsp file which should be the first page of our web app.
Now you are ready to deploy your web app. But before that you must have application id for your web app, you can create it, just follow the steps,
(You must have internet connection)
Now click on the app engine symbol, which is right below the Navigate option,

Now click on “App Engine project settings…. ” link,


 Now click on the link “My Applications” , it will redirect you to the google app engine login page, you can now login by using your gmail id.



 Click on the “create application” button. For the first time it will ask you for your mobile number, provide it (mention the country code e.g. for India it is +91), it will send you some numeric code on your mobile, enter it in the provided textbox, if it is right then fill all the information such as application id, it will be prefixed by “appspot.com”, check the availability, if available then you are allocated requested id, e.g. “http://myfirstapp.appspot.com”. Now enter the application ID.


Now provide the same gmail id and password, and click on Deploy option.



 Now open web browser and enter the URL http://myfirstapp.appspot.com.


 Now sign in to google app engine, go to “my applications”, select your application, select “Datastore Viewer” option on the left side, and see your database is created.


To retrieve records use following statements:

 String uname=null,password=null;

  pm.currentTransaction().begin();
 javax.jdo.Query query1 = pm.newQuery(Idpassword.class);


 Collection<Idpassword> records = (Collection<Idpassword>) query1.execute();
 for( Idpassword r : records)
{
uname=r.getUserid();
        password=r.getPassword();
}

  pm.currentTransaction().commit();

     


10 comments:

  1. thanks for the blog...we(atleast i)hardly understood what Abhijit said that day,theory as well as the practical part

    ReplyDelete
  2. This page is very useful for installation of s/w. Total info is mentioned in this page. Gud

    ReplyDelete
  3. Replies
    1. http://linkedinczoneext.appspot.com/

      Delete
    2. This comment has been removed by the author.

      Delete
  4. Please send source code for me, email: duongfonui@gmail.com
    Thank you!

    ReplyDelete
  5. Thanks for the information.
    lfscoachingclasses.appspot.com(Tried by me :) )

    ReplyDelete