| Java, Eclipse and Web programming Tutorials |
Version 1.2
Copyright © 2009 - 2010 Lars Vogel
22.02.2010
| Revision History | ||
|---|---|---|
| Revision 0.1 | 08.04.2009 | Lars Vogel |
| First version created, based on the Google Tutorial | ||
| Revision 0.2 | 25.04.2009 | Lars Vogel |
| Added link to GAE issues | ||
| Revision 0.3 | 12.06.2009 | Lars Vogel |
| Updated quotas | ||
| Revision 0.4 | 21.07.2009 | Lars Vogel |
| Link to Groovy for the App Engine | ||
| Revision 0.5 | 30.07.2009 | Lars Vogel |
| Added update site for Eclipse 3.5 | ||
| Revision 0.6 | 14.08.2009 | Lars Vogel |
| Added Bigtable | ||
| Revision 0.7 | 17.08.2009 | Lars Vogel |
| Minor rework | ||
| Revision 0.8 | 24.08.2009 | Lars Vogel |
| Added info that GAE supports standard Java API's. | ||
| Revision 0.9 | 15.09.2009 | Lars Vogel |
| Reworked article | ||
| Revision 1.0 | 13.10.2009 | Lars Vogel |
| Improved english based on user (rebuild) feedback | ||
| Revision 1.1 | 02.01.2010 | Lars Vogel |
| How to see log files on GAE/J | ||
| Revision 1.2 | 22.02.2010 | Lars Vogel |
| Finished Todo example | ||
Google App Engine - Java (GAE/J) with Eclipse
This article describes the creation of a Java web application on the Google App Engine.
The article demonstrates also the usage of Google Eclipse Plugin for developing, running and debugging the Google App Engine application. The tutorial is based on Java 1.6 and GAE version 1.3.
Table of Contents
Google offers a cloud computing infrastructure for creating and running web applications which is called "Google App Engine" (GAE). GAE allows the dynamic allocation of system resources for an application based on the actual demand. Currently Google supports as Python and Java based applications. This includes Java Virtual Machine (JVM) based languages, e.g. Groovy. GAE for Java is called GAE/J.
GAE/J applications are based on the servlet standard and allow you to use standard Java API, this way your application can run either on the GAE or on any other Java enabled server environment, e.g. Tomcat or Jetty. GAE/J does not allow all Java classes to be used, for example Swing and AWT are not supported and you cannot use Threads. Google provides a full list of supported classes on the Java Whitelist .
The GAE/J uses the Jetty servlet container to serve applications and supports the Java Servlet API in version 2.4. It provides access to databases via Java Data Objects (JDO) and the Java Persistence API (JPA) . The GAE/J uses Google Bigtable as the distributed storage system for persisting application data. .
Google provides Memcache as a caching mechanism. Developers who want to code against the standard Java API can use the JCache implementation (based on JSR 107).
Google offers free hosting for websites which are not highly frequented, e.g. 5 Millions page views. The price model for the websites that exceed thier daily quota is listed on the Google billing documentation pages . The usage quotas of the App Engine are constantly changing but, at the time of this writing, are around 5 millions pages views per month, which translates approx. in 6.5 CPU hours and 1 gigabyte of outbound traffic.
Currently a user can create a maximum of 10 applications on the Google App Engine.
For an introduction into Eclipse please see Eclipse Introduction .
Google offers a Eclipse plugin that provides both Google App Engine and GWT development capabilities. Install the plugins from http://dl.google.com/eclipse/plugin/3.5 via the update manager of eclipse (please see Using the update manager of Eclipse for details).
Install all available features from the Google update site.
The installation will install the Google App Engine Server to your Eclipse plugin directory into "plugins/com.google.appengine.eclipse.sdkbundle_VERSION/". In this directory you find another directory "appengine-java-sdk_VERSION" which contains the server a in directory bin and several demos. To start the server with the guestbook demo simply type the following on the command line in the bin directory.
dev_appserver.cmd ..\demos\guestbook\war
To stop the server use "Cntr+C".
To deploy your application to the Google cloud you need a GAE/J account. To get such an account you need a Google email account.
Open the following URL http://appengine.google.com/ and login with your Google account information. Press the button "Create an application".
You will then need then to verify your account. After providing your phone number, Google will text you a verification code via SMS. You will then type the verification code into the verification box online.
Create an application name. You have to choose one which is still available.
The following will create a small "Todo" application using servlets and JSP's. For an introduction into servlet and JSP programming please see Servlet and JSP development - Tutorial

Create a new project "de.vogella.gae.java.todo" via File > New > Web Application Project. Package name is "de.vogella.gae.java.todo".

The created project can already run. Right click on your application, select run as-> Web Application

This should start Jetty on http://localhost:8888/ . Open the url in the browser and you should the possibility to select your servlet and to start it. If you select it you should see a "Hello, world" message.

Create the following class which will be our model.
package de.vogella.gae.java.todo.model;
import java.util.Calendar;
/**
* Model class which will store the Todo Items
*
* @author Lars Vogel
*
*/
public class Todo {
private final long id;
private String author;
private String shortDescription;
private String longDescription;
private String url;
private Calendar dueDate;
boolean finished;
public Todo(long id, String author, String shortDescription, String longDescription, String url, Calendar dueDate) {
this.id= id;
this.author = author;
this.shortDescription = shortDescription;
this.longDescription = longDescription;
this.url = url;
this.dueDate = dueDate;
finished = false;
}
public long getId() {
return id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getLongDescription() {
return longDescription;
}
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Calendar getDueDate() {
return dueDate;
}
public void setDueDate(Calendar dueDate) {
this.dueDate = dueDate;
}
public boolean isFinished() {
return finished;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
}
Create the following class which will serve as a content provider. This class is a Singleton which stores the data in memory.
package de.vogella.gae.java.todo.dao;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.datanucleus.sco.simple.GregorianCalendar;
import de.vogella.gae.java.todo.model.Todo;
public enum Dao {
INSTANCE;
private static long number=1;
private final List<Todo> todos = new ArrayList<Todo>();
private Dao(){
// Create a test Todo
// Image that I read the data from bigtables
Todo todo = new Todo(1, "vogella", "Issue number 1", "Detailed Description of everything", "", GregorianCalendar.getInstance());
todos.add(todo);
}
public void add(String author, String summery, String description, String url, Calendar dueDate){
synchronized (this) {
number ++;
todos.add(new Todo(number, author, summery, description, url, dueDate));
}
}
public List<Todo> getTodos(@SuppressWarnings("unused") String user){
// For testing we will always return the same data no matter what the user is
return todos;
}
public void remove(long id) {
Todo remove = null;
for (Todo todo: todos){
if (todo.getId() == id){
remove = todo;
}
}
if (remove!=null){
todos.remove(remove);
}
}
}
Create the following two servlets. The first will be called if a new Todo is created the second one if a Todo is finished.
package de.vogella.gae.java.todo;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.datanucleus.sco.simple.GregorianCalendar;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import de.vogella.gae.java.todo.dao.Dao;
@SuppressWarnings("serial")
public class ServletCreateTodo extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
String summery = checkNull(req.getParameter("summary"));
String longDescription = checkNull(req.getParameter("description"));
String url = checkNull(req.getParameter("url"));
// Not yet used
String dueDate = req.getParameter("dueDate");
Dao.INSTANCE.add(user.getNickname(), summery, longDescription, url,
GregorianCalendar.getInstance());
resp.sendRedirect("/TodoApplication.jsp");
}
private String checkNull(String s) {
if (s == null) {
return "";
}
return s;
}
}
package de.vogella.gae.java.todo;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import de.vogella.gae.java.todo.dao.Dao;
public class ServletRemoveTodo extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String id = req.getParameter("id");
Dao.INSTANCE.remove(Long.parseLong(id));
resp.sendRedirect("/TodoApplication.jsp");
}
}
In the folder "war" create the following JSP "TodoApplication.jsp".
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List" %>
<%@ page import="javax.jdo.PersistenceManager" %>
<%@ page import="javax.jdo.Query" %>
<%@ page import="com.google.appengine.api.users.User" %>
<%@ page import="com.google.appengine.api.users.UserService" %>
<%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
<%@ page import="de.vogella.gae.java.todo.model.Todo" %>
<%@ page import="de.vogella.gae.java.todo.dao.Dao" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@page import="java.util.ArrayList"%>
<html>
<head>
<title>Todos</title>
<link rel="stylesheet" type="text/css" href="css/main.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
</head>
<body>
<%
Dao dao = Dao.INSTANCE;
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
String url = userService.createLoginURL(request.getRequestURI());
String urlLinktext = "Login";
List<Todo> todos = new ArrayList<Todo>();
if (user != null){
url = userService.createLogoutURL(request.getRequestURI());
urlLinktext = "Logout";
todos = dao.getTodos(user.getNickname());
}
%>
<div style="width: 100%;">
<div class="line"></div>
<div class="topLine">
<div style="float: left;"><img src="images/todo.png" /></div>
<div style="float: left;" class="headline">Todos</div>
<div style="float: right;"><a href="<%=url%>"><%=urlLinktext%></a> <%=(user==null? "" : user.getNickname())%></div>
</div>
</div>
<div style="clear: both;"/>
You have a total number of <%= todos.size() %> Todos.
<table>
<tr>
<th>Short description </th>
<th>Due Date</th>
<th>Long Description</th>
<th>URL</th>
<th>Done</th>
</tr>
<% for (Todo todo : todos) {%>
<tr>
<td>
<%=todo.getShortDescription()%>
</td>
<td>
2009.11.10
</td>
<td>
<%=todo.getLongDescription()%>
</td>
<td>
<%=todo.getUrl()%>
</td>
<td>
<a class="done" href="/done?id=<%=todo.getId()%>" >Done</a>
</td>
</tr>
<%}
%>
</table>
<hr />
<div class="main">
<div class="headline">New todo</div>
<% if (user != null){ %>
<form action="/new" method="post" accept-charset="utf-8">
<table>
<tr>
<td><label for="summery">Summary</label></td>
<td><input type="text" name="summery" id="summery" size="65"/></td>
</tr>
<tr>
<td><label for="dueDate">Due Date</label></td>
<td><input type="text" name="dueDate" id="dueDate"/></td>
</tr>
<tr>
<td valign="description"><label for="description">Description</label></td>
<td><textarea rows="4" cols="50" name="description" id="description"></textarea></td>
</tr>
<tr>
<td valign="top"><label for="url">URL</label></td>
<td><input type="text" name="url" id="url" size="65" /></td>
</tr>
<tr>
<td colspan="2" align="right"><input type="submit" value="Create"/></td>
</tr>
</table>
</form>
<% }else{ %>
Please login with your Google account
<% } %>
</div>
</body>
</html>
The JSP refers to a css file. Create a folder "war/css" and create the following file "main.css".
body {
margin: 5px;
font-family: Arial, Helvetica, sans-serif;
}
hr {
border: 0;
background-color: #DDDDDD;
height: 1px;
margin: 5px;
}
table th {
background:#EFEFEF none repeat scroll 0 0;
border-top:1px solid #CCCCCC;
font-size:small;
padding-left:5px;
padding-right:4px;
padding-top:4px;
vertical-align:top;
text-align:left;
}
table tr {
background-color: #e5ecf9;
font-size:small;
}
.topLine {
height: 1.25em;
background-color: #e5ecf9;
padding-left: 4px;
padding-right: 4px;
padding-bottom: 3px;
padding-top: 2px;
}
.headline {
font-weight: bold;
color: #3366cc;
}
.done {
font-size: x-small;
vertical-align: top;
}
.email {
font-size: x-small;
vertical-align: top;
}
form td {
font-size: smaller;
}
Change "web.xml" in folder /war/WEB-INF" to the following. It will create the right servlet mapping and will set the JSP as start page.
<?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>CreateNewTodo</servlet-name> <servlet-class>de.vogella.gae.java.todo.ServletCreateTodo</servlet-class> </servlet> <servlet> <servlet-name>RemoveTodo</servlet-name> <servlet-class>de.vogella.gae.java.todo.ServletRemoveTodo</servlet-class> </servlet> <servlet-mapping> <servlet-name>RemoveTodo</servlet-name> <url-pattern>/done</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>CreateNewTodo</servlet-name> <url-pattern>/new</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/TodoApplication.jsp</welcome-file> </welcome-file-list> </web-app>
You should be able to run your application locally, login and create and delete "Todos".

To deploy your application to the GAE you need to maintain your application ID in the file "web/WEB-INF/appengine-web.xml". In the tag "application" maintain the application you have created in GAE/J Registration . In my example I use the application "vogellajava".
<?xml version="1.0" encoding="utf-8"?> <appengine-web-app xmlns="http://appengine.google.com/ns/1.0"> <application>vogellajava</application> <version>1</version> <!-- Configure java.util.logging --> <system-properties> <property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/> </system-properties> </appengine-web-app>
Now deploy your application to the Google cloud. The following assumes that you have already created your account.
Right-click on your project and select Google > App Engine Settings... from the context menu. Check that the application ID is as you maintained it in "appengine-web.xml".

Right-click on your project, Select Google -> Deploy to App Engine. You need to login with your Google account information.

After the upload completes you will find your application online under http://application-id.appspot.com, e.g. in my case http://vogellajava.appspot.com.
In case of problems the GAE provides access to the log files.

You can also use standard Java Logging for creating custom logs on the GAE/J. See Java Logging Tutorial and Logging on the GAE/J .
Thank you for practicing with this tutorial.
Please note that I maintain this website in my private time. If you like the information I'm providing please help me by donating.For questions and discussion around this article please use the www.vogella.de Google Group. Also if you note an error in this article please post the error and if possible the correction to the Group.
I believe the following is a very good guideline for asking questions in general and also for the Google group How To Ask Questions The Smart Way.
http://www.vogella.de/articles/GoogleAppEngine/article.html Google App Engine Development with Python