diff --git a/managedvms/.gitignore b/managedvms/.gitignore new file mode 100644 index 00000000000..d30ea344569 --- /dev/null +++ b/managedvms/.gitignore @@ -0,0 +1,33 @@ +# Google App Engine generated folder +appengine-generated/ + +# Java +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties + +service-account.json + +#eclipse +.classpath +.settings +.project diff --git a/managedvms/async-rest/LICENSE b/managedvms/async-rest/LICENSE new file mode 100644 index 00000000000..04cb0d70775 --- /dev/null +++ b/managedvms/async-rest/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2013 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/managedvms/async-rest/README.md b/managedvms/async-rest/README.md new file mode 100644 index 00000000000..6f949bd70bc --- /dev/null +++ b/managedvms/async-rest/README.md @@ -0,0 +1,55 @@ + +# Example Web App Using Asynchronous Servlets # + +This web app demonstrates using asynchronous servlet techniques to reduce server resources. + +The code for this tutorial is here: [https://github.com/GoogleCloudPlatform/java-docs-samples/managedvms/async-rest](https://github.com/GoogleCloudPlatform/java-docs-samples/managedvms/async-rest). + + +## Initial Setup ## + +First, complete the following steps: + +- [Create your project](https://developers.google.com/appengine/docs/managed-vms/) and have it enabled for Managed VMs. +- Obtain an app key for the Google Places WebService API. +- Download and install [the Beta build of the Google Cloud SDK](https://developers.google.com/cloud/sdk/#Quick_Start). +- Install the Cloud SDK `app-engine-java` component. +- Authenticate wth the gcloud SDK: gcloud auth login. +- Install [Maven](http://maven.apache.org/download.cgi) if you haven't already. + + + +## Providing your Google Places API key ## + +You will need to edit the pom.xml file and replace YOUR_PLACES_APP_KEY with the value of your key: + + YOUR_PLACES_APP_KEY + +You then have several options of how to run it: + +## Running locally without the AppEngine environment ## + +The application does not use any AppEngine specific services, so you can run it simply on your local machine by doing: + + mvn jetty:run + +Go to http://localhost:8080 to see the webapp. + + +## Running locally using Docker ## + +The project also builds a docker image based on the jetty9 image for [Google Container Engine](https://cloud.google.com/container-engine/). The WAR file is installed in the webapps directory and the resulting image can be run locally with: + + docker run --rm -it -p 8080:8080 jetty9-async-rest --exec -Dcom.google.appengine.demos.asyncrest.appKey=YOUR_PLACES_APP_KEY + +Where you replace YOUR_PLACES_APP_KEY with the key you obtained in the initial setup. + + +## Deploying to the cloud as an AppEngine ManagedVM ## + +To automatically stage and deploy the webapp to your project in the cloud do: + + mvn gcloud:deploy + +See here for more information on the [GCloud Maven Plugin](https://github.com/GoogleCloudPlatform/gcloud-maven-plugin). + diff --git a/managedvms/async-rest/pom.xml b/managedvms/async-rest/pom.xml new file mode 100644 index 00000000000..4cb08253692 --- /dev/null +++ b/managedvms/async-rest/pom.xml @@ -0,0 +1,132 @@ + + 4.0.0 + com.google.appengine.demos + async-rest + 1.0.0-SNAPSHOT + war + Example Async Rest Webapp + + YOUR_PLACES_APP_KEY + 9.3.7.v20160115 + async- + + + + + maven-compiler-plugin + 3.3 + + 1.7 + 1.7 + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty.version} + + + + com.google.appengine.demos.asyncrest.appKey + ${places.appkey} + + + + + + com.google.appengine + gcloud-maven-plugin + 2.0.9.90.v20151210 + + /usr/local/google-cloud-sdk + debug + debug + false + remote + + + + org.apache.maven.plugins + maven-war-plugin + 2.6 + + true + false + + + ${basedir}/src/main/webapp/WEB-INF + true + WEB-INF + + + + + + com.spotify + docker-maven-plugin + 0.3.2 + + + build-docker-image + package + + build + + + jetty9:${docker.label.prefix}${jetty.version} + true + jetty9-async-rest + + ${docker.label.prefix}${project.version} + + + + /var/lib/jetty/webapps + ${project.build.directory} + ${project.build.finalName}.war + + + + + + clean-docker + clean + + removeImage + + + jetty9-async-rest + + ${docker.label.prefix}${project.version} + + + + + + + + + + org.eclipse.jetty + jetty-client + ${jetty.version} + + + org.eclipse.jetty + jetty-util-ajax + ${jetty.version} + + + org.eclipse.jetty + jetty-webapp + ${jetty.version} + test + + + javax.servlet + javax.servlet-api + provided + 3.1.0 + + + diff --git a/managedvms/async-rest/src/main/java/com/google/appengine/demos/DumpServlet.java b/managedvms/async-rest/src/main/java/com/google/appengine/demos/DumpServlet.java new file mode 100644 index 00000000000..9320c03c2b4 --- /dev/null +++ b/managedvms/async-rest/src/main/java/com/google/appengine/demos/DumpServlet.java @@ -0,0 +1,59 @@ +package com.google.appengine.demos; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collections; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@SuppressWarnings("serial") +public class DumpServlet extends HttpServlet +{ + @Override + protected void doGet( HttpServletRequest request, + HttpServletResponse response ) throws ServletException, + IOException + { + response.setContentType("text/html"); + response.setStatus(HttpServletResponse.SC_OK); + + PrintWriter out = response.getWriter(); + + out.println("

DumpServlet

"); + out.println("

Context Fields:

"); + out.println("
");
+        out.printf("serverInfo=%s%n",getServletContext().getServerInfo());
+        out.printf("getServletContextName=%s%n",getServletContext().getServletContextName());
+        out.printf("virtualServerName=%s%n",getServletContext().getVirtualServerName());
+        out.printf("contextPath=%s%n",getServletContext().getContextPath());
+        out.printf("version=%d.%d%n",getServletContext().getMajorVersion(),getServletContext().getMinorVersion());
+        out.printf("effectiveVersion=%d.%d%n",getServletContext().getEffectiveMajorVersion(),getServletContext().getEffectiveMinorVersion());
+        out.println("
"); + out.println("

Request Fields:

"); + out.println("
");
+        out.printf("remoteHost/Addr:port=%s/%s:%d%n",request.getRemoteHost(),request.getRemoteAddr(),request.getRemotePort());
+        out.printf("localName/Addr:port=%s/%s:%d%n",request.getLocalName(),request.getLocalAddr(),request.getLocalPort());
+        out.printf("scheme=%s method=%s protocol=%s%n",request.getScheme(), request.getMethod(), request.getProtocol());
+        out.printf("serverName:serverPort=%s:%d%n",request.getServerName(),request.getServerPort());
+        out.printf("requestURI=%s%n",request.getRequestURI());
+        out.printf("requestURL=%s%n",request.getRequestURL().toString());
+        out.printf("contextPath|servletPath|pathInfo=%s|%s|%s%n",request.getContextPath(),request.getServletPath(),request.getPathInfo());
+        out.printf("session/new=%s/%b%n",request.getSession(true).getId(),request.getSession().isNew());
+        out.println("
"); + out.println("

Request Headers:

"); + out.println("
");
+        for (String n : Collections.list(request.getHeaderNames()))
+            for (String v : Collections.list(request.getHeaders(n)))
+                out.printf("%s: %s%n",n,v);
+        out.println("
"); + out.println("

Response Fields:

"); + out.println("
");
+        out.printf("bufferSize=%d%n",response.getBufferSize());
+        out.printf("encodedURL(\"/foo/bar\")=%s%n",response.encodeURL("/foo/bar"));
+        out.printf("encodedRedirectURL(\"/foo/bar\")=%s%n",response.encodeRedirectURL("/foo/bar"));
+        out.println("
"); + } +} diff --git a/managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AbstractRestServlet.java b/managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AbstractRestServlet.java new file mode 100644 index 00000000000..b54d19f72d6 --- /dev/null +++ b/managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AbstractRestServlet.java @@ -0,0 +1,119 @@ +package com.google.appengine.demos.asyncrest; + +import java.io.IOException; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.net.URLEncoder; +import java.util.Iterator; +import java.util.Map; +import java.util.Queue; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.UnavailableException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * AbstractRestServlet. + * + */ +public class AbstractRestServlet extends HttpServlet { + protected final static int MAX_RESULTS = 5; + + protected final static String STYLE = ""; + + protected final static String APPKEY = "com.google.appengine.demos.asyncrest.appKey"; + protected final static String APPKEY_ENV = "PLACES_APPKEY"; + protected final static String LOC_PARAM = "loc"; + protected final static String ITEMS_PARAM = "items"; + protected final static String LATITUDE_PARAM = "lat"; + protected final static String LONGITUDE_PARAM = "long"; + protected final static String RADIUS_PARAM = "radius"; + protected String key; + + @Override + public void init(ServletConfig servletConfig) throws ServletException { + //first try the servlet context init-param + String source="InitParameter"; + key = servletConfig.getInitParameter(APPKEY); + if (key==null || key.startsWith("${")) { + source="System Property"; + key = System.getProperty(APPKEY); + } + if (key == null || key.startsWith("${")) { + source="Environment Variable"; + key = System.getenv(APPKEY_ENV); + } + if (key == null) + throw new UnavailableException("Places App Key not set"); + if (key.startsWith("${")) + throw new UnavailableException("Places App Key not expanded from "+source); + } + + public static String sanitize(String s) { + if (s == null) + return null; + return s.replace("<", "?").replace("&", "?").replace("\n", "?"); + } + + protected String restQuery(String coordinates, String radius, String item) { + try { + return "https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=" + key + "&location=" + + URLEncoder.encode(coordinates, "UTF-8") + "&types=" + URLEncoder.encode(item, "UTF-8") + + "&radius=" + URLEncoder.encode(radius, "UTF-8"); + + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public String generateResults(Queue> results) { + StringBuilder thumbs = new StringBuilder(); + int resultCount = 0; + Iterator> itor = results.iterator(); + + while (resultCount < MAX_RESULTS && itor.hasNext()) { + Map m = (Map) itor.next(); + String name = (String) m.get("name"); + Object[] photos = (Object[]) m.get("photos"); + if (photos != null && photos.length > 0) { + resultCount++; + thumbs.append(""); + thumbs.append(" "); + } + } + return thumbs.toString(); + } + + public String getPhotoURL(String photoref) { + return "https://maps.googleapis.com/maps/api/place/photo?key=" + key + "&photoreference=" + photoref + + "&maxheight=40"; + } + + protected String ms(long nano) { + BigDecimal dec = new BigDecimal(nano); + return dec.divide(new BigDecimal(1000000L)).setScale(1, RoundingMode.UP).toString(); + } + + protected int width(long nano) { + int w = (int) ((nano + 999999L) / 5000000L); + if (w == 0) + w = 2; + return w; + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + doGet(request, response); + } + +} diff --git a/managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AsyncRestServlet.java b/managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AsyncRestServlet.java new file mode 100644 index 00000000000..195226a39fa --- /dev/null +++ b/managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AsyncRestServlet.java @@ -0,0 +1,197 @@ +package com.google.appengine.demos.asyncrest; + +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.ByteBuffer; +import java.util.Map; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.servlet.AsyncContext; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.client.api.Response; +import org.eclipse.jetty.client.api.Result; +import org.eclipse.jetty.http.HttpMethod; +import org.eclipse.jetty.util.BufferUtil; +import org.eclipse.jetty.util.Utf8StringBuilder; +import org.eclipse.jetty.util.ajax.JSON; +import org.eclipse.jetty.util.ssl.SslContextFactory; + +/** + * AsyncRestServlet. May be configured with init parameters: + *
+ *
appid
+ *
The Google app key to use
+ *
+ * + */ +public class AsyncRestServlet extends AbstractRestServlet { + final static String RESULTS_ATTR = "com.google.appengine.demos.asyncrest.client"; + final static String DURATION_ATTR = "com.google.appengine.demos.asyncrest.duration"; + final static String START_ATTR = "com.google.appengine.demos.asyncrest.start"; + + HttpClient client; + + @Override + public void init(ServletConfig servletConfig) throws ServletException { + super.init(servletConfig); + SslContextFactory sslContextFactory = new SslContextFactory(); + client = new HttpClient(sslContextFactory); + + try { + client.start(); + } catch (Exception e) { + throw new ServletException(e); + } + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + if (key == null) { + response.sendError(500, APPKEY + " not set"); + return; + } + + Long start = System.nanoTime(); + + // Do we have results yet? + Queue> results = (Queue>) request.getAttribute(RESULTS_ATTR); + + // If no results, this must be the first dispatch, so send the REST + // request(s) + if (results == null) { + // define results data structures + final Queue> resultsQueue = new ConcurrentLinkedQueue<>(); + request.setAttribute(RESULTS_ATTR, results = resultsQueue); + + // suspend the request + // This is done before scheduling async handling to avoid race of + // dispatch before startAsync! + final AsyncContext async = request.startAsync(); + async.setTimeout(30000); + + // extract keywords to search for + String lat = sanitize(request.getParameter(LATITUDE_PARAM)); + String longitude = sanitize(request.getParameter(LONGITUDE_PARAM)); + String radius = sanitize(request.getParameter(RADIUS_PARAM)); + String[] keywords = sanitize(request.getParameter(ITEMS_PARAM)).split(","); + + final AtomicInteger outstanding = new AtomicInteger(keywords.length); + + // Send request each keyword + for (final String item : keywords) { + client.newRequest(restQuery(lat + "," + longitude, radius, item)).method(HttpMethod.GET) + .send(new AsyncRestRequest() { + @Override + void onLocationFound(Map result) { + resultsQueue.add(result); + } + + @Override + void onComplete() { + if (outstanding.decrementAndGet() <= 0) + async.dispatch(); + } + }); + } + + // save timing info and return + request.setAttribute(START_ATTR, start); + request.setAttribute(DURATION_ATTR, System.nanoTime() - start); + + return; + } + + // We have results! + // Generate the response + String thumbs = generateResults(results); + + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println(""); + out.println(STYLE); + out.println(""); + + long initial = (Long) request.getAttribute(DURATION_ATTR); + long start0 = (Long) request.getAttribute(START_ATTR); + + long now = System.nanoTime(); + long total = now - start0; + long generate = now - start; + long thread = initial + generate; + + String loc = sanitize(request.getParameter(LOC_PARAM)); + out.print("Asynchronous: Requesting " + sanitize(request.getParameter(ITEMS_PARAM)) + " near " + + (loc != null ? loc + : "lat=" + sanitize(request.getParameter(LATITUDE_PARAM)) + " long=" + + sanitize(request.getParameter(LONGITUDE_PARAM))) + + "
"); + out.print("Total Time: " + ms(total) + "ms
"); + + out.print("Thread held (red): " + ms(thread) + "ms (" + ms(initial) + " initial + " + + ms(generate) + " generate )
"); + out.print("Async wait (green): " + ms(total - thread) + "ms
"); + + out.println("" + + "" + + ""); + + out.println("
"); + out.print("First 5 results of "+results.size()+":
"); + if ("".equals(thumbs)) + out.print("No results. Ensure "+APPKEY+" property is set correctly."); + else + out.println(thumbs); + + out.println("
"); + out.println(""); + out.close(); + } + + private abstract class AsyncRestRequest extends Response.Listener.Adapter { + final Utf8StringBuilder _content = new Utf8StringBuilder(); + + AsyncRestRequest() { + } + + @Override + public void onContent(Response response, ByteBuffer content) { + byte[] bytes = BufferUtil.toArray(content); + _content.append(bytes, 0, bytes.length); + } + + @Override + public void onComplete(Result result) { + // extract results + Map data = (Map) JSON.parse(_content.toString()); + if (data != null) { + Object[] results = (Object[]) data.get("results"); + if (results != null) { + for (Object o : results) + onLocationFound((Map) o); + } + } + onComplete(); + + } + + abstract void onLocationFound(Map details); + + abstract void onComplete(); + + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + doGet(request, response); + } +} diff --git a/managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/SerialRestServlet.java b/managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/SerialRestServlet.java new file mode 100644 index 00000000000..e670a1282d1 --- /dev/null +++ b/managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/SerialRestServlet.java @@ -0,0 +1,110 @@ +package com.google.appengine.demos.asyncrest; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.LinkedList; +import java.util.Map; +import java.util.Queue; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.util.ajax.JSON; + +/** + * SerialRestServlet + * + * May be configured with init parameters: + *
+ *
appid
+ *
The Google app key to use
+ *
+ */ +public class SerialRestServlet extends AbstractRestServlet +{ + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + if (key == null) { + response.sendError(500, APPKEY + " not set"); + return; + } + long start = System.nanoTime(); + + String loc = sanitize(request.getParameter(LOC_PARAM)); + String lat = sanitize(request.getParameter(LATITUDE_PARAM)); + String longitude = sanitize(request.getParameter(LONGITUDE_PARAM)); + String radius = sanitize(request.getParameter(RADIUS_PARAM)); + + String[] keywords=sanitize(request.getParameter(ITEMS_PARAM)).split(","); + Queue> results = new LinkedList>(); + + // make all requests serially + for (String itemName : keywords) + { + URL url = new URL(restQuery(lat+","+longitude, radius, itemName)); + + HttpURLConnection connection = (HttpURLConnection)url.openConnection(); + connection.setRequestMethod("GET"); + + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + + Map query = (Map)JSON.parse(new BufferedReader(new InputStreamReader(connection.getInputStream()))); + Object[] tmp = (Object[]) query.get("results"); + if (tmp != null) + { + for (Object o : tmp) + { + Map m = (Map)o; + results.add(m); + } + } + } + + + // Generate the response + String thumbs = generateResults(results); + + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println(""); + out.println(STYLE); + out.println(""); + + long now = System.nanoTime(); + long total=now-start; + + out.print("Blocking: Requesting "+sanitize(request.getParameter(ITEMS_PARAM))+" near "+(loc != null?loc:"lat="+lat+" long="+longitude)+"
"); + out.print("Total Time: "+ms(total)+"ms
"); + out.print("Thread held (red): "+ms(total)+"ms
"); + + out.println(""); + + out.println("
"); + out.print("First 5 results of "+results.size()+":
"); + if ("".equals(thumbs)) + out.print("No results. Ensure "+APPKEY+" property is set correctly."); + else + out.println(thumbs); + out.println("
"); + out.println(""); + out.close(); + } + + + + /** + * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse + * response) + */ + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + doGet(request, response); + } + +} diff --git a/managedvms/async-rest/src/main/webapp/Dockerfile b/managedvms/async-rest/src/main/webapp/Dockerfile new file mode 100644 index 00000000000..d1d08b4bb8e --- /dev/null +++ b/managedvms/async-rest/src/main/webapp/Dockerfile @@ -0,0 +1,2 @@ +FROM gcr.io/google_appengine/jetty9-compat:githubheadasync +ADD . /app diff --git a/managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml b/managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml new file mode 100644 index 00000000000..85197614067 --- /dev/null +++ b/managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml @@ -0,0 +1,10 @@ + + + true + false + true + false + + + + diff --git a/managedvms/async-rest/src/main/webapp/WEB-INF/jetty-web.xml b/managedvms/async-rest/src/main/webapp/WEB-INF/jetty-web.xml new file mode 100644 index 00000000000..3322a413ee5 --- /dev/null +++ b/managedvms/async-rest/src/main/webapp/WEB-INF/jetty-web.xml @@ -0,0 +1,6 @@ + + + + + / + diff --git a/managedvms/async-rest/src/main/webapp/WEB-INF/web.xml b/managedvms/async-rest/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 00000000000..2d056388277 --- /dev/null +++ b/managedvms/async-rest/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,39 @@ + + + + Async REST Webservice Example + + SerialRestServlet + SerialRestServlet + com.google.appengine.demos.asyncrest.SerialRestServlet + + + SerialRestServlet + /testSerial + + + + AsyncRestServlet + AsyncRestServlet + com.google.appengine.demos.asyncrest.AsyncRestServlet + true + + + AsyncRestServlet + /testAsync + + + + DumpServlet + DumpServlet + com.google.appengine.demos.DumpServlet + + + DumpServlet + /dump/* + + + diff --git a/managedvms/async-rest/src/main/webapp/asyncrest/green.png b/managedvms/async-rest/src/main/webapp/asyncrest/green.png new file mode 100644 index 00000000000..d0fb8420c5d Binary files /dev/null and b/managedvms/async-rest/src/main/webapp/asyncrest/green.png differ diff --git a/managedvms/async-rest/src/main/webapp/asyncrest/red.png b/managedvms/async-rest/src/main/webapp/asyncrest/red.png new file mode 100644 index 00000000000..f2a79a07fbc Binary files /dev/null and b/managedvms/async-rest/src/main/webapp/asyncrest/red.png differ diff --git a/managedvms/async-rest/src/main/webapp/index.html b/managedvms/async-rest/src/main/webapp/index.html new file mode 100644 index 00000000000..1c4966e8185 --- /dev/null +++ b/managedvms/async-rest/src/main/webapp/index.html @@ -0,0 +1,62 @@ + + + + + +

Blocking vs Asynchronous REST

+

+This demo calls the Google Maps WebService API +to find places matching each of the search criteria passed on the query +string. +

+

The rest API is called both synchronously and asynchronously for comparison. The time the request thread is held by the servlet is +displayed in red for both. +

+Using a combination of the asynchronous servlet API and an asynchronous http client, the server is able to release the +request thread back to the thread pool (shown in green) while waiting for the response from the Google service. The thread can be reused to handle other +requests during the wait, which greatly reduces the number of threads required and server resources. +

+ + + + + + + + + + + + + + + + + + + + + + + +
Synchronous
+ + + +

Asynchronous
+ + + +
Effects of Synchronous Vs Asynchronous processing
+ + + +