Google App Engine (GAE) Java API Part 3: Getting started with APIs

Tweet

In a long break between posts, I hope you have setup your Eclipse environment and are excited to start learning about GAE APIs. There were some unavoidable delays, but now we will start and zoom into GAE! So let’s get our hand dirty with some code :)

The approach we’re going to follow is learning about APIs with sample code. I will also provide links to demo and source code where applicable.

Before we get started on subject that we are interested in, let’s create the application we are going to work with. Login to https://appengine.google.com/ with your credentials and “Create Application”. In the following screen, fill in the app name and description, also choose “Master/Slave” by editing Storage options. High replication datastore would be ideal for scenarios where the data backup has to be immediate and consistency guarantee has to be higher.

If you have installed the Eclipse plugin correctly, you should see Google icon like below in Eclipse, click on “New web application project.” This can also be done through the menu, File → New → Web application project.

Google Menu in Eclipse after successful plugin installation

In the new window that comes up, choose a name and base package name for your project. Make sure you uncheck “Use Google Web Toolkit” option before you proceed (Google Web Toolkit – GWT is an exciting new way of writing super clean and responsive web pages in Java, the GWT compiler turns Java into HTML & JavaScript). Also, enable “Generate sample code” so that you can use a sample project to begin with.

Creating new GAE project in Eclipse

In case you have issues with the GAE SDK not being found, you can click on “Configure SDKs” next to “Use Google App Engine” and point to directory where the SDK is placed. In my case, the Eclipse plugin directory has the required SDK bundle, as seen in screen below

Now that your sample app is created locally, let’s deploy that to Google’s infrastructure. With the same menu that we used to create the app, choose “Deploy to App Engine”. Alternatively, right click on project and in “Google” choose to “Deploy to App Engine”. If you aren’t signed into Google, in Eclipse, it will ask for your credentials, and you can choose the same ID that we used to create our app earlier. Next, you will have to configure the “App name” which you created earlier by clicking on “App Engine project settings”. This isn’t required in subsequent deploys, unless you want to change the version to which app is deployed. As you can see, we are deploying the application to “app-name” . The app-name should be the one you chose when you created your application using “Create Application” at appengine.google.com

Once you deploy, your application is be ready to serve at APP_NAME.appspot.com – So we’ve deployed our first GAE app to the cloud. You can also run the same app locally by right clicking on project in Eclipse and choosing “Run as → Web Application”. The console will show the URL at which you can access locally. The app we have deployed by creating sample project has link to a simple servlet which prints “Hello, world” to your browser. You can check locally as well as on server to cross check you are on the right path so far. If you see a “Hello, World” Servlet as a result, continue otherwise I strongly suggest to have setup done appropriately to best understand rest of tutorials. In case of questions, Ask!

Users & Authentication

As you might have noticed on the screen where we created our app on AppEngine, Google provides three mechanisms for authentication: Google Account, Google Apps domain, and OpenID. For purpose of this tutorial we are going to look at Google accounts only, but of course the API supports all three mechanisms. More on Google Apps and OpenID

API for authentication is fairly simple, UserServiceFactory is used to get an instance of UserService. UserService is used to log the user in, and to retrieve User in addition to creating login and logout URLs. User object itself can be used to get User related information. Let’s look at a servlet:

//  CloudSpringAuthServlet .java
import java.io.IOException;
import javax.servlet.http.*;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class CloudSpringAuthServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		resp.setContentType("text/plain");
		String baseURL = req.getRequestURI();
		String loginURL="";
		String logOutURL="";
		UserService userService = UserServiceFactory.getUserService();
                // By user service we are checking if the user is logged in, and if he is logged in
                // we are getting the information of user along with a link which can be sued to sign out
		if(userService.isUserLoggedIn()) {
			logOutURL = userService.createLogoutURL(baseURL);
			resp.getWriter().println("Hello CloudSpring-er, your email ID as detected by us is: "+ userService.getCurrentUser().getEmail());
			resp.getWriter().println("To log out click on below link");
			resp.getWriter().println("<a href=""+logOutURL+"">Log out</a>");
		}
                // If the user is not logged in, we are redirecting him to Google login screen, which will
                // redirect user to original URL after authentication
		else{
			resp.getWriter().println("<a href=""+userService.createLoginURL(baseURL)+"">Please sign in to proceed</a>");
		}

	}
}

You can copy the above servlet in a locally created app in Eclipse, be sure to make appropriate changes for package name and mappings in web.xml, and run locally or remote.

For purpose of local development with Eclipse, GAE SDK simulates the user authentication. User is presented with a login screen, without password. One can enter any email address and that email address will behave like a real user. While logging in, you can tick the checkbox if you would like to sign in as administrator.

Mail

GAE supports JavaMail for sending email messages. You don’t need to add an additional library for this. Let’s look at a simple example for sending messages using Google App Engine, before talking about receiving emails. As an exercise, create a servlet with the code snippet below by changing email ID to ID of the application user, configure the servlet for a URL in web.xml, and hit the URL, which will invoke this servlet.

//CloudSpringMailServlet.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// Notice that out of all imports we have used -none of them is a GAE class
public class CloudSpringMailServlet extends HttpServlet{
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
				String recipientEmailAddress = "your_emailId@gmail.com";
				Properties props = new Properties();
				Session session = Session.getDefaultInstance(props, null);
				Message msg = new MimeMessage(session);
				// We are creating multipart so that we can send multiple parts to Email
                                Multipart mp = new MimeMultipart();
				try {
					msg.setFrom(new InternetAddress("your_emailId@gmail.com", "Test Name"));
					msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
							recipientEmailAddress, "Hello"));
					msg.setSubject("CloudSpring test");
					MimeBodyPart htmlPart = new MimeBodyPart();
					htmlPart.setContent("This is just a test email from CloudSpring!", "text/html");
					// We are composing multipart with various parts of email, before we send
                                        mp.addBodyPart(htmlPart);
					msg.setContent(mp);
					Transport.send(msg);
				} catch (MessagingException e) {
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				resp.getWriter().println("Email has been sent");

	}

}

On the local development environment, the mail is not actually sent, but the documentation states that they are shown in logs ( Somehow I could not see the mail in logs on local system, but it worked fine on GAE server, let me know if you get that right!).

Incoming mail

Incoming mail works a little differently. As mentioned in the previous article, the inbound service has to be enabled. Secondly all incoming emails are received as HTTP POST request at  /_ah/mail/<address> where address can be any_string@app-name.appspotmail.com.

From an application perspective, you will have to configure one or more servlet for URL pattern “/_ah/mail/*”. The servlet can use MimeMessage as shown below. The line number 3 gets the POST data from request object. Further operations for getting data from email follow JavaMail APIs

        Properties props = new Properties();
        Session sess = Session.getDefaultInstance(props, null);
        MimeMessage mailMessage = new MimeMessage(sess, req.getInputStream());

We have created our basic GAE app and deployed to cloud with click of a button. We have also used authentication and mail APIs to do few basic tasks in our mini project. We have set the ground, and are ready to take a deep dive into other areas of GAE! Keep watching for the next part in this series.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments