From 07d8d116821e647c5503086f697217a7d45d07fa Mon Sep 17 00:00:00 2001 From: Jan Bartel Date: Thu, 14 Jan 2016 13:35:20 +1100 Subject: [PATCH 01/13] Commit for sample webapp using async servlets. --- managedvms/async-rest/LICENSE | 201 ++++++++++++++++++ managedvms/async-rest/pom.xml | 59 +++++ .../demos/asyncrest/AbstractRestServlet.java | 137 ++++++++++++ .../demos/asyncrest/AsyncRestServlet.java | 200 +++++++++++++++++ .../demos/asyncrest/SerialRestServlet.java | 98 +++++++++ .../src/main/webapp/WEB-INF/appengine-web.xml | 11 + .../src/main/webapp/WEB-INF/web.xml | 30 +++ .../src/main/webapp/asyncrest/green.png | Bin 0 -> 166 bytes .../src/main/webapp/asyncrest/red.png | Bin 0 -> 164 bytes .../async-rest/src/main/webapp/index.html | 62 ++++++ 10 files changed, 798 insertions(+) create mode 100644 managedvms/async-rest/LICENSE create mode 100644 managedvms/async-rest/pom.xml create mode 100644 managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AbstractRestServlet.java create mode 100644 managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AsyncRestServlet.java create mode 100644 managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/SerialRestServlet.java create mode 100644 managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml create mode 100644 managedvms/async-rest/src/main/webapp/WEB-INF/web.xml create mode 100644 managedvms/async-rest/src/main/webapp/asyncrest/green.png create mode 100644 managedvms/async-rest/src/main/webapp/asyncrest/red.png create mode 100644 managedvms/async-rest/src/main/webapp/index.html 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/pom.xml b/managedvms/async-rest/pom.xml new file mode 100644 index 00000000000..7ca7589be84 --- /dev/null +++ b/managedvms/async-rest/pom.xml @@ -0,0 +1,59 @@ + + 4.0.0 + com.google.appengine.demos + async-rest + 1.0.0-SNAPSHOT + war + Example Async Rest Webapp + + 9.3.5.v20151012 + + + + + maven-compiler-plugin + 3.3 + + 1.7 + 1.7 + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty.version} + + + com.google.appengine + gcloud-maven-plugin + 2.0.9.90.v20151210 + + + + + + + + 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/asyncrest/AbstractRestServlet.java b/managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AbstractRestServlet.java new file mode 100644 index 00000000000..1398eb78905 --- /dev/null +++ b/managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AbstractRestServlet.java @@ -0,0 +1,137 @@ +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.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * Abstract Servlet implementation class AsyncRESTServlet. + * Enquires ebay REST service for auctions by key word. + * May be configured with init parameters:
+ *
appid
The eBay application ID to use
+ *
+ * Each request examines the following request parameters:
+ *
items
The keyword to search for
+ *
+ */ +public class AbstractRestServlet extends HttpServlet +{ + protected final static int MAX_RESULTS = 5; + protected final static String GOOGLE_API_KEY_NAME = "async_example_place_key"; + protected final static String GOOGLE_API_KEY = "AIzaSyABCgUB4wc290F9LcIigNXurT6yNV92yfY"; + + protected final static String STYLE = + ""; + + + protected final static String APPID_PARAM = "appid"; + 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 + { + if (servletConfig.getInitParameter(APPID_PARAM) == null) + _key = GOOGLE_API_KEY; + else + _key = servletConfig.getInitParameter(APPID_PARAM); + } + + + 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..a710938fac6 --- /dev/null +++ b/managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AsyncRestServlet.java @@ -0,0 +1,200 @@ +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; + +/** + * Servlet implementation class AsyncRESTServlet. + * Enquires ebay REST service for auctions by key word. + * May be configured with init parameters:
+ *
appid
The eBay application ID to use
+ *
+ * Each request examines the following request parameters:
+ *
items
The keyword to search for
+ *
+ */ +public class AsyncRestServlet extends AbstractRestServlet +{ + final static String RESULTS_ATTR = "org.eclipse.jetty.demo.client"; + final static String DURATION_ATTR = "org.eclipse.jetty.demo.duration"; + final static String START_ATTR = "org.eclispe.jetty.demo.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 + { + 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:
"); + 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..30ffb72f8fe --- /dev/null +++ b/managedvms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/SerialRestServlet.java @@ -0,0 +1,98 @@ +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; + +/** + * Servlet implementation class SerialRestServlet + */ +public class SerialRestServlet extends AbstractRestServlet +{ + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + 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=generateThumbs(results); + 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:
"); + 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/WEB-INF/appengine-web.xml b/managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml new file mode 100644 index 00000000000..532d8cb87b5 --- /dev/null +++ b/managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml @@ -0,0 +1,11 @@ + + + async-rest-demo + async-rest-demo + true + 1 + /static + false + true + false + 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..4dacc521c5d --- /dev/null +++ b/managedvms/async-rest/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,30 @@ + + + + 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 + + + + 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 0000000000000000000000000000000000000000..d0fb8420c5dbe9403c699c66f0d173cf09f5dbac GIT binary patch literal 166 zcmeAS@N?(olHy`uVBq!ia0vp^93afW1SGw4HSYi^#^NA%Cx&(BWL^R}oCO|{#S9GG z!XV7ZFl&wkP>{XE)7O>#CW{cGp=NP}b`?-avcxr_#5q4VH#M(>!MP|ku_QG`p**uB zL&4qCHz2%`PaLR7*we)^gyVX0%8&C6q6UTrJgS@wXPg-MB`*Gc1C(a)boFyt=akR{ E01^u){XE)7O>#CW{cGA&0%8wF*#3vcxr_#5q4VH#M(>!MP|ku_QG`p**uB zL&4qCHz2%`PaLR7(9^{+gyVYhpYsi}28KMEoD63j8TqfZ?P>r@GI+ZBxvX + + + + +

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
+ + + + From 1c2ed49ded3a2fef72bbbb0193057261dbab9436 Mon Sep 17 00:00:00 2001 From: Jan Bartel Date: Thu, 14 Jan 2016 13:36:54 +1100 Subject: [PATCH 02/13] Add gitignore --- managedvms/.gitignore | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 managedvms/.gitignore 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 From fb9f67b32eca61276c9c00e811cfb3654d272482 Mon Sep 17 00:00:00 2001 From: Jan Bartel Date: Thu, 14 Jan 2016 16:54:06 +1100 Subject: [PATCH 03/13] Reformat src, delete incorrect javadoc and comments. --- .../demos/asyncrest/AbstractRestServlet.java | 169 ++++------ .../demos/asyncrest/AsyncRestServlet.java | 305 +++++++++--------- .../demos/asyncrest/SerialRestServlet.java | 9 +- 3 files changed, 223 insertions(+), 260 deletions(-) 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 index 1398eb78905..a33db900f02 100644 --- 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 @@ -14,124 +14,95 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -/** - * Abstract Servlet implementation class AsyncRESTServlet. - * Enquires ebay REST service for auctions by key word. - * May be configured with init parameters:
- *
appid
The eBay application ID to use
- *
- * Each request examines the following request parameters:
- *
items
The keyword to search for
- *
+/** + * AbstractRestServlet. + * */ -public class AbstractRestServlet extends HttpServlet -{ - protected final static int MAX_RESULTS = 5; - protected final static String GOOGLE_API_KEY_NAME = "async_example_place_key"; - protected final static String GOOGLE_API_KEY = "AIzaSyABCgUB4wc290F9LcIigNXurT6yNV92yfY"; - - protected final static String STYLE = - ""; +public class AbstractRestServlet extends HttpServlet { + protected final static int MAX_RESULTS = 5; + protected final static String GOOGLE_API_KEY = "AIzaSyABCgUB4wc290F9LcIigNXurT6yNV92yfY"; + + protected final static String STYLE = ""; protected final static String APPID_PARAM = "appid"; 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; + protected final static String RADIUS_PARAM = "radius"; + protected String key; @Override - public void init(ServletConfig servletConfig) throws ServletException - { - if (servletConfig.getInitParameter(APPID_PARAM) == null) - _key = GOOGLE_API_KEY; - else - _key = servletConfig.getInitParameter(APPID_PARAM); + public void init(ServletConfig servletConfig) throws ServletException { + if (servletConfig.getInitParameter(APPID_PARAM) == null) + key = GOOGLE_API_KEY; + else + key = servletConfig.getInitParameter(APPID_PARAM); } - - public static String sanitize(String s) - { - if (s==null) - return null; - return s.replace("<","?").replace("&","?").replace("\n","?"); + 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); - } + + 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 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"; + + 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 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 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); + + 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 index a710938fac6..fab8189bafb 100644 --- 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 @@ -24,177 +24,164 @@ import org.eclipse.jetty.util.ssl.SslContextFactory; /** - * Servlet implementation class AsyncRESTServlet. - * Enquires ebay REST service for auctions by key word. - * May be configured with init parameters:
- *
appid
The eBay application ID to use
- *
- * Each request examines the following request parameters:
- *
items
The keyword to search for
+ * AsyncRestServlet. May be configured with init parameters: + *
+ *
appid
+ *
The Google app key to use
*
+ * */ -public class AsyncRestServlet extends AbstractRestServlet -{ - final static String RESULTS_ATTR = "org.eclipse.jetty.demo.client"; - final static String DURATION_ATTR = "org.eclipse.jetty.demo.duration"; - final static String START_ATTR = "org.eclispe.jetty.demo.start"; +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; + 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); - } + 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 - { - 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:
"); - out.println(thumbs); - out.println("
"); - out.println(""); - out.close(); + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + 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:
"); + 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(); + + 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); + 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 index 30ffb72f8fe..62a4f7dc785 100644 --- 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 @@ -18,7 +18,13 @@ import org.eclipse.jetty.util.ajax.JSON; /** - * Servlet implementation class SerialRestServlet + * SerialRestServlet + * + * May be configured with init parameters: + *
+ *
appid
+ *
The Google app key to use
+ *
*/ public class SerialRestServlet extends AbstractRestServlet { @@ -58,7 +64,6 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) t // Generate the response - //String thumbs=generateThumbs(results); String thumbs = generateResults(results); response.setContentType("text/html"); From 5f8515467a39798af66211e2bf93469fbd38d323 Mon Sep 17 00:00:00 2001 From: Jan Bartel Date: Fri, 15 Jan 2016 11:18:26 +1100 Subject: [PATCH 04/13] Update appengine-web.xml and add Dockerfile --- managedvms/async-rest/src/main/webapp/Dockerfile | 2 ++ .../async-rest/src/main/webapp/WEB-INF/appengine-web.xml | 4 +--- 2 files changed, 3 insertions(+), 3 deletions(-) create mode 100644 managedvms/async-rest/src/main/webapp/Dockerfile 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 index 532d8cb87b5..bfbb7758a62 100644 --- a/managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml +++ b/managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml @@ -1,10 +1,8 @@ async-rest-demo - async-rest-demo + a1 true - 1 - /static false true false From 1ecc3bb2c2283dafff528de2db2df5d070249470 Mon Sep 17 00:00:00 2001 From: Jan Bartel Date: Fri, 15 Jan 2016 12:19:10 +1100 Subject: [PATCH 05/13] Remove application and version from appengine-web.xml --- managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml | 2 -- 1 file changed, 2 deletions(-) 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 index bfbb7758a62..54804d24ca3 100644 --- a/managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml +++ b/managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml @@ -1,7 +1,5 @@ - async-rest-demo - a1 true false true From ce3489790323c3200830997a85a682ef142ebed8 Mon Sep 17 00:00:00 2001 From: Jan Bartel Date: Fri, 15 Jan 2016 15:45:08 +1100 Subject: [PATCH 06/13] Change to using user-provided Google Places API app key --- managedvms/async-rest/pom.xml | 12 ++++++++++++ .../demos/asyncrest/AbstractRestServlet.java | 12 +++++------- .../appengine/demos/asyncrest/AsyncRestServlet.java | 6 ++++++ .../appengine/demos/asyncrest/SerialRestServlet.java | 4 ++++ .../src/main/webapp/WEB-INF/appengine-web.xml | 3 +++ 5 files changed, 30 insertions(+), 7 deletions(-) diff --git a/managedvms/async-rest/pom.xml b/managedvms/async-rest/pom.xml index 7ca7589be84..e5bab4991e1 100644 --- a/managedvms/async-rest/pom.xml +++ b/managedvms/async-rest/pom.xml @@ -7,6 +7,7 @@ Example Async Rest Webapp 9.3.5.v20151012 + YOUR_PLACES_APP_KEY @@ -22,12 +23,23 @@ 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/java/gcloud-sdk/google-cloud-sdk + debug + debug 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 index a33db900f02..d79bd556b2c 100644 --- 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 @@ -21,8 +21,6 @@ public class AbstractRestServlet extends HttpServlet { protected final static int MAX_RESULTS = 5; - protected final static String GOOGLE_API_KEY = "AIzaSyABCgUB4wc290F9LcIigNXurT6yNV92yfY"; - protected final static String STYLE = ""; - protected final static String APPID_PARAM = "appid"; + protected final static String APPKEY = "com.google.appengine.demos.asyncrest.appKey"; protected final static String LOC_PARAM = "loc"; protected final static String ITEMS_PARAM = "items"; protected final static String LATITUDE_PARAM = "lat"; @@ -40,10 +38,10 @@ public class AbstractRestServlet extends HttpServlet { @Override public void init(ServletConfig servletConfig) throws ServletException { - if (servletConfig.getInitParameter(APPID_PARAM) == null) - key = GOOGLE_API_KEY; - else - key = servletConfig.getInitParameter(APPID_PARAM); + //first try the servlet context init-param + key = servletConfig.getInitParameter(APPKEY); + if (key == null) + key = System.getProperty(APPKEY); } public static String sanitize(String s) { 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 index fab8189bafb..3b225044c1e 100644 --- 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 @@ -54,6 +54,12 @@ public void init(ServletConfig servletConfig) throws ServletException { @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? 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 index 62a4f7dc785..7446c552cb3 100644 --- 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 @@ -30,6 +30,10 @@ 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)); 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 index 54804d24ca3..eddaf972a20 100644 --- a/managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml +++ b/managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml @@ -4,4 +4,7 @@ false true false + + + From 6fdd2633bc3e77d8641b44dec33212cdd598a93c Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Fri, 15 Jan 2016 15:57:22 +1100 Subject: [PATCH 07/13] build a docker image suitable for google container engine --- managedvms/async-rest/pom.xml | 45 +++++++++++++++++++ .../src/main/webapp/WEB-INF/jetty-web.xml | 6 +++ 2 files changed, 51 insertions(+) create mode 100644 managedvms/async-rest/src/main/webapp/WEB-INF/jetty-web.xml diff --git a/managedvms/async-rest/pom.xml b/managedvms/async-rest/pom.xml index e5bab4991e1..5fab18c5b73 100644 --- a/managedvms/async-rest/pom.xml +++ b/managedvms/async-rest/pom.xml @@ -8,6 +8,8 @@ 9.3.5.v20151012 YOUR_PLACES_APP_KEY + 9.3.7.RC1 + async- @@ -42,6 +44,49 @@ debug + + + 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} + + + + + 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 @@ + + + + + / + From df017aa55a181098e0853518d757163076a91153 Mon Sep 17 00:00:00 2001 From: Jan Bartel Date: Fri, 15 Jan 2016 16:08:57 +1100 Subject: [PATCH 08/13] Add README --- managedvms/async-rest/README.md | 55 +++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 managedvms/async-rest/README.md diff --git a/managedvms/async-rest/README.md b/managedvms/async-rest/README.md new file mode 100644 index 00000000000..4944865789c --- /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. + + + +## Provding 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). + From b9b780a9581f0686fecf9b6137794e5e6586b399 Mon Sep 17 00:00:00 2001 From: Jan Bartel Date: Fri, 15 Jan 2016 16:15:38 +1100 Subject: [PATCH 09/13] Update README --- managedvms/async-rest/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/managedvms/async-rest/README.md b/managedvms/async-rest/README.md index 4944865789c..6f949bd70bc 100644 --- a/managedvms/async-rest/README.md +++ b/managedvms/async-rest/README.md @@ -19,7 +19,7 @@ First, complete the following steps: -## Provding your Google Places API key ## +## 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: From 54af32e90f4095408652500f3b4064f032a767bb Mon Sep 17 00:00:00 2001 From: Jan Bartel Date: Fri, 15 Jan 2016 16:31:14 +1100 Subject: [PATCH 10/13] Print warning in case app key is not set. --- .../appengine/demos/asyncrest/AsyncRestServlet.java | 8 ++++++-- .../appengine/demos/asyncrest/SerialRestServlet.java | 9 ++++++--- 2 files changed, 12 insertions(+), 5 deletions(-) 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 index 3b225044c1e..195226a39fa 100644 --- 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 @@ -145,8 +145,12 @@ void onComplete() { + ""); out.println("
"); - out.print("First 5 results:
"); - out.println(thumbs); + 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(); 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 index 7446c552cb3..e670a1282d1 100644 --- 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 @@ -84,10 +84,13 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) t out.print("Thread held (red): "+ms(total)+"ms
"); out.println(""); - + out.println("
"); - out.print("First 5 results:
"); - out.println(thumbs); + 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(); From 2bbcd7ea7e1c36ca1a8b4e29e7d96a153b24c986 Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Tue, 2 Feb 2016 10:44:44 +0100 Subject: [PATCH 11/13] updated jetty version --- managedvms/async-rest/pom.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/managedvms/async-rest/pom.xml b/managedvms/async-rest/pom.xml index 5fab18c5b73..76cc0f41641 100644 --- a/managedvms/async-rest/pom.xml +++ b/managedvms/async-rest/pom.xml @@ -6,9 +6,8 @@ war Example Async Rest Webapp - 9.3.5.v20151012 YOUR_PLACES_APP_KEY - 9.3.7.RC1 + 9.3.7.v20160115 async- From 4c89bf75b497bc318b3b86dfe9daac36ab118e25 Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Tue, 2 Feb 2016 17:17:57 +0100 Subject: [PATCH 12/13] Work in progress Use env vars for places.appkey Added DumpServlet for debugging --- .../google/appengine/demos/DumpServlet.java | 59 +++++++++++++++++++ .../demos/asyncrest/AbstractRestServlet.java | 15 ++++- .../src/main/webapp/WEB-INF/appengine-web.xml | 6 +- .../src/main/webapp/WEB-INF/web.xml | 9 +++ 4 files changed, 85 insertions(+), 4 deletions(-) create mode 100644 managedvms/async-rest/src/main/java/com/google/appengine/demos/DumpServlet.java 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 index d79bd556b2c..b54d19f72d6 100644 --- 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 @@ -10,6 +10,7 @@ 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; @@ -29,6 +30,7 @@ public class AbstractRestServlet extends HttpServlet { + " iframe {border: 0px}" + ""; 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"; @@ -39,9 +41,20 @@ public class AbstractRestServlet extends HttpServlet { @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) + 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) { 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 index eddaf972a20..85197614067 100644 --- a/managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml +++ b/managedvms/async-rest/src/main/webapp/WEB-INF/appengine-web.xml @@ -4,7 +4,7 @@ false true false - - - + + +
diff --git a/managedvms/async-rest/src/main/webapp/WEB-INF/web.xml b/managedvms/async-rest/src/main/webapp/WEB-INF/web.xml index 4dacc521c5d..2d056388277 100644 --- a/managedvms/async-rest/src/main/webapp/WEB-INF/web.xml +++ b/managedvms/async-rest/src/main/webapp/WEB-INF/web.xml @@ -26,5 +26,14 @@ /testAsync + + DumpServlet + DumpServlet + com.google.appengine.demos.DumpServlet + + + DumpServlet + /dump/* + From eab82b6462c37a8fc90322832e8ef8e07d00df9a Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Wed, 3 Feb 2016 12:19:52 +0100 Subject: [PATCH 13/13] Fixed places.appkey substitution --- managedvms/async-rest/pom.xml | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/managedvms/async-rest/pom.xml b/managedvms/async-rest/pom.xml index 76cc0f41641..4cb08253692 100644 --- a/managedvms/async-rest/pom.xml +++ b/managedvms/async-rest/pom.xml @@ -38,12 +38,29 @@ gcloud-maven-plugin 2.0.9.90.v20151210 - /usr/local/java/gcloud-sdk/google-cloud-sdk + /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