From 0540a80a31c0af386765f4e009a0c1251f4de5fc Mon Sep 17 00:00:00 2001 From: Tim Swast Date: Wed, 16 Mar 2016 15:45:41 -0700 Subject: [PATCH] Checkstyle fixes for async-rest sample. Tested manually by deploying to http://async-rest-test-dot-java-docs-samples-swast-1.appspot.com/. When doing so, I noticed that the `mvn gcloud:deploy` command would not run, so I updated the POM to the latest version of the gcloud maven plugin, too. --- managed_vms/async-rest/pom.xml | 58 +++++++---- .../google/appengine/demos/DumpServlet.java | 58 +++++++++-- .../demos/asyncrest/AbstractRestServlet.java | 75 +++++++++------ .../demos/asyncrest/AsyncRestServlet.java | 96 ++++++++++++------- .../demos/asyncrest/SerialRestServlet.java | 62 ++++++++---- 5 files changed, 238 insertions(+), 111 deletions(-) diff --git a/managed_vms/async-rest/pom.xml b/managed_vms/async-rest/pom.xml index 25d44b5775f..123f588b58f 100644 --- a/managed_vms/async-rest/pom.xml +++ b/managed_vms/async-rest/pom.xml @@ -1,50 +1,66 @@ - + + + 4.0.0 com.google.appengine.demos managed-vms-async-rest 1.0.0-SNAPSHOT war - Example Async Rest Webapp + + + doc-samples + com.google.cloud + 1.0.0 + ../.. + + - YOUR_PLACES_APP_KEY - 9.3.7.v20160115 async- + 9.3.7.v20160115 + 1.8 + 1.8 + YOUR_PLACES_APP_KEY - - maven-compiler-plugin - 3.3 - - 1.8 - 1.8 - - 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.96.v20160203 + 2.0.9.95.v20160203 - /usr/local/google-cloud-sdk - debug - debug - false - remote + debug + debug + false + remote - + org.apache.maven.plugins maven-war-plugin diff --git a/managed_vms/async-rest/src/main/java/com/google/appengine/demos/DumpServlet.java b/managed_vms/async-rest/src/main/java/com/google/appengine/demos/DumpServlet.java index 87012af49cd..6d0541adceb 100644 --- a/managed_vms/async-rest/src/main/java/com/google/appengine/demos/DumpServlet.java +++ b/managed_vms/async-rest/src/main/java/com/google/appengine/demos/DumpServlet.java @@ -1,3 +1,19 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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. + */ + package com.google.appengine.demos; import java.io.IOException; @@ -13,9 +29,8 @@ public class DumpServlet extends HttpServlet { @Override - protected void doGet(HttpServletRequest request, - HttpServletResponse response) throws ServletException, - IOException { + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); @@ -28,19 +43,42 @@ protected void doGet(HttpServletRequest request, 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.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(
+        "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.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("
");
diff --git a/managed_vms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AbstractRestServlet.java b/managed_vms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AbstractRestServlet.java
index 07956c2dc3d..51a3e49b096 100644
--- a/managed_vms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AbstractRestServlet.java
+++ b/managed_vms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AbstractRestServlet.java
@@ -1,3 +1,19 @@
+/*
+ * Copyright 2016 Google Inc. All Rights Reserved.
+ *
+ * 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.
+ */
+
 package com.google.appengine.demos.asyncrest;
 
 import java.io.IOException;
@@ -16,32 +32,31 @@
 import javax.servlet.http.HttpServletResponse;
 
 /**
- * AbstractRestServlet.
- *
+ * Abstract base class for REST servlets.
  */
 public class AbstractRestServlet extends HttpServlet {
 
-  protected final static int MAX_RESULTS = 5;
+  protected static final 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 static final String APPKEY = "com.google.appengine.demos.asyncrest.appKey";
+  protected static final String APPKEY_ENV = "PLACES_APPKEY";
+  protected static final String LOC_PARAM = "loc";
+  protected static final String ITEMS_PARAM = "items";
+  protected static final String LATITUDE_PARAM = "lat";
+  protected static final String LONGITUDE_PARAM = "long";
+  protected static final String RADIUS_PARAM = "radius";
   protected String key;
 
   @Override
   public void init(ServletConfig servletConfig) throws ServletException {
-    //first try the servlet context init-param
+    // First try the servlet context init-param.
     String source = "InitParameter";
     key = servletConfig.getInitParameter(APPKEY);
     if (key == null || key.startsWith("${")) {
@@ -60,18 +75,19 @@ public void init(ServletConfig servletConfig) throws ServletException {
     }
   }
 
-  public static String sanitize(String s) {
-    if (s == null) {
+  public static String sanitize(String str) {
+    if (str == null) {
       return null;
     }
-    return s.replace("<", "?").replace("&", "?").replace("\n", "?");
+    return str.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");
+      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);
@@ -84,21 +100,22 @@ public String generateResults(Queue> results) {
     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");
+      Map map = (Map) itor.next();
+      String name = (String) map.get("name");
+      Object[] photos = (Object[]) map.get("photos");
       if (photos != null && photos.length > 0) {
         resultCount++;
-        thumbs.append("");
+        thumbs.append(
+            "");
         thumbs.append(" ");
       }
     }
     return thumbs.toString();
   }
 
-  public String getPhotoURL(String photoref) {
+  public String getPhotoUrl(String photoref) {
     return "https://maps.googleapis.com/maps/api/place/photo?key=" + key + "&photoreference=" + photoref
             + "&maxheight=40";
   }
@@ -109,11 +126,11 @@ protected String ms(long nano) {
   }
 
   protected int width(long nano) {
-    int w = (int) ((nano + 999999L) / 5000000L);
-    if (w == 0) {
-      w = 2;
+    int width = (int) ((nano + 999999L) / 5000000L);
+    if (width == 0) {
+      width = 2;
     }
-    return w;
+    return width;
   }
 
   @Override
diff --git a/managed_vms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AsyncRestServlet.java b/managed_vms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AsyncRestServlet.java
index 0bee71ec433..571752ea08d 100644
--- a/managed_vms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AsyncRestServlet.java
+++ b/managed_vms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/AsyncRestServlet.java
@@ -1,5 +1,30 @@
+/*
+ * Copyright 2016 Google Inc. All Rights Reserved.
+ *
+ * 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.
+ */
+
 package com.google.appengine.demos.asyncrest;
 
+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;
+
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.nio.ByteBuffer;
@@ -14,17 +39,10 @@
 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:
+ * Servlet which makes REST calls asynchronously.
+ *
+ * 

May be configured with init parameters: *

*
appid
*
The Google app key to use
@@ -33,9 +51,9 @@ */ 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"; + static final String RESULTS_ATTR = "com.google.appengine.demos.asyncrest.client"; + static final String DURATION_ATTR = "com.google.appengine.demos.asyncrest.duration"; + static final String START_ATTR = "com.google.appengine.demos.asyncrest.start"; HttpClient client; @@ -64,22 +82,22 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) Long start = System.nanoTime(); // Do we have results yet? - Queue> results = (Queue>) request.getAttribute(RESULTS_ATTR); + Queue> results = + (Queue>) request.getAttribute(RESULTS_ATTR); - // If no results, this must be the first dispatch, so send the REST - // request(s) + // 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 + // 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 + // 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)); @@ -87,17 +105,19 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) final AtomicInteger outstanding = new AtomicInteger(keywords.length); - // Send request each keyword + // Send request each keyword. for (final String item : keywords) { - client.newRequest(restQuery(lat + "," + longitude, radius, item)).method(HttpMethod.GET) - .send(new AsyncRestRequest() { + client.newRequest(restQuery(lat + "," + longitude, radius, item)) + .method(HttpMethod.GET) + .send( + new AsyncRestRequest() { @Override void onLocationFound(Map result) { resultsQueue.add(result); } @Override - void onComplete() { + void doComplete() { if (outstanding.decrementAndGet() <= 0) { async.dispatch(); } @@ -131,20 +151,28 @@ void onComplete() { long thread = initial + generate; String loc = sanitize(request.getParameter(LOC_PARAM)); - out.print("Asynchronous: Requesting " + sanitize(request.getParameter(ITEMS_PARAM)) + " near " + 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( + "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.println("
"); out.print("First 5 results of " + results.size() + ":
"); @@ -161,7 +189,7 @@ void onComplete() { private abstract class AsyncRestRequest extends Response.Listener.Adapter { - final Utf8StringBuilder _content = new Utf8StringBuilder(); + final Utf8StringBuilder utf8Content = new Utf8StringBuilder(); AsyncRestRequest() { } @@ -169,13 +197,13 @@ private abstract class AsyncRestRequest extends Response.Listener.Adapter { @Override public void onContent(Response response, ByteBuffer content) { byte[] bytes = BufferUtil.toArray(content); - _content.append(bytes, 0, bytes.length); + utf8Content.append(bytes, 0, bytes.length); } @Override public void onComplete(Result result) { - // extract results - Map data = (Map) JSON.parse(_content.toString()); + // Extract results. + Map data = (Map) JSON.parse(utf8Content.toString()); if (data != null) { Object[] results = (Object[]) data.get("results"); if (results != null) { @@ -184,13 +212,13 @@ public void onComplete(Result result) { } } } - onComplete(); + doComplete(); } abstract void onLocationFound(Map details); - abstract void onComplete(); + abstract void doComplete(); } diff --git a/managed_vms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/SerialRestServlet.java b/managed_vms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/SerialRestServlet.java index 359fd1f3ec1..19d3bed254b 100644 --- a/managed_vms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/SerialRestServlet.java +++ b/managed_vms/async-rest/src/main/java/com/google/appengine/demos/asyncrest/SerialRestServlet.java @@ -1,5 +1,23 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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. + */ + package com.google.appengine.demos.asyncrest; +import org.eclipse.jetty.util.ajax.JSON; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -11,16 +29,13 @@ 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 + * Servlet which makes REST calls serially. * - * May be configured with init parameters: + *

May be configured with init parameters: *

*
appid
*
The Google app key to use
@@ -29,7 +44,8 @@ public class SerialRestServlet extends AbstractRestServlet { @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { if (key == null) { response.sendError(500, APPKEY + " not set"); return; @@ -44,26 +60,28 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) t String[] keywords = sanitize(request.getParameter(ITEMS_PARAM)).split(","); Queue> results = new LinkedList>(); - // make all requests serially + // 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())); + BufferedReader reader = + new BufferedReader(new InputStreamReader(connection.getInputStream())); - Map query = (Map) JSON.parse(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); + Map map = (Map) o; + results.add(map); } } } - // Generate the response + // Generate the response. String thumbs = generateResults(results); response.setContentType("text/html"); @@ -75,11 +93,19 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) t 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( + "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.println("
"); out.print("First 5 results of " + results.size() + ":
"); @@ -94,11 +120,13 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) t } /** - * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse - * response) + * Handle HTTP POST request. + * + * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { doGet(request, response); }