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

Share this article

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: [sourcecode language=”java”] // 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>”); } } } [/sourcecode] 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. [sourcecode language=”java”] //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”); } } [/sourcecode] 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 [sourcecode language=”java”] Properties props = new Properties(); Session sess = Session.getDefaultInstance(props, null); MimeMessage mailMessage = new MimeMessage(sess, req.getInputStream()); [/sourcecode] 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.

Frequently Asked Questions (FAQs) about Google App Engine (GAE) Java API

What is the Google App Engine (GAE) Java API and how does it work?

The Google App Engine (GAE) Java API is a set of tools provided by Google that allows developers to build and host web applications on Google’s infrastructure. It provides a platform for developers to write scalable web applications using standard Java technologies. The API provides services such as data storage, user authentication, and more. It works by providing a runtime environment where your application code runs, and a set of services that your application can call upon to perform common tasks.

How do I get started with Google App Engine (GAE) Java API?

To get started with GAE Java API, you need to first install the Google Cloud SDK, which includes the App Engine SDK for Java. Once installed, you can create a new App Engine project in your Google Cloud Console. After creating the project, you can start writing your application using the App Engine Java API. You can then deploy your application to the App Engine platform using the gcloud command-line tool.

How does the GAE Java API compare to other Java APIs?

The GAE Java API is specifically designed for developing and deploying web applications on Google’s infrastructure. It provides a set of services that are commonly used in web applications, such as data storage, user authentication, and email sending. This makes it different from other Java APIs, which may be designed for different purposes, such as developing desktop applications or performing specific tasks like XML processing or database access.

Can I send emails using the GAE Java API?

Yes, the GAE Java API includes a Mail API that allows your application to send emails. You can use this API to send emails to any email address, and you can also receive incoming emails if you have set up a mail receiving handler in your application.

What are the limitations of the GAE Java API?

While the GAE Java API provides a powerful platform for developing web applications, it does have some limitations. For example, the API does not support all Java classes and methods, and some classes are replaced with App Engine-specific versions. Also, there are restrictions on the amount of resources your application can use, such as CPU time and memory.

How can I handle data storage in GAE Java API?

The GAE Java API provides a Datastore service for storing and retrieving data. The Datastore is a NoSQL database that provides a flexible, scalable, and durable storage solution for your application. You can use the Datastore API to interact with the Datastore, performing operations such as creating, updating, and querying entities.

How can I authenticate users in my application using the GAE Java API?

The GAE Java API provides a Users API that allows you to authenticate users in your application. The Users API integrates with Google Accounts, allowing users to sign in with their Google account. You can use the Users API to determine if a user is signed in, get the user’s email address, and more.

How can I handle errors in my application using the GAE Java API?

The GAE Java API provides a Logging API that allows you to log messages and errors in your application. You can use the Logging API to log messages at different levels, such as INFO, WARNING, and ERROR. The logged messages can be viewed in the Google Cloud Console.

Can I use the GAE Java API to develop non-web applications?

The GAE Java API is primarily designed for developing web applications. However, you can use it to develop other types of applications, such as background tasks and APIs. However, keep in mind that the API has some limitations and does not support all Java classes and methods.

How can I monitor the performance of my application using the GAE Java API?

The GAE Java API provides a Monitoring API that allows you to monitor the performance of your application. You can use the Monitoring API to collect and analyze performance data, such as request latency and CPU usage. The collected data can be viewed in the Google Cloud Console.

Vishal BiyaniVishal Biyani
View Author

My name is Vishal Biyani! I am an avid developer and a cloud enthusiast! I am lucky enough to witness some very exciting changes in technology and data landscape.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week