From a6d18b3e1649d6e3de5bb31905cadee007e9746d Mon Sep 17 00:00:00 2001 From: Les Vogel Date: Mon, 21 Aug 2017 19:08:57 -0700 Subject: [PATCH] First pass of many formatting fixes Update to new plugin, fix formatting for GAE J8 Std --- .editorconfig | 19 ++ .../appengine/analytics/AnalyticsServlet.java | 7 +- .../appidentity/IdentityServlet.java | 9 +- .../appidentity/SignForAppServlet.java | 15 +- .../appengine/appidentity/UrlShortener.java | 16 +- .../appidentity/UrlShortenerServlet.java | 9 +- .../appidentity/IdentityServletTest.java | 20 +- .../appidentity/SignForAppServletTest.java | 26 +- .../example/bigtable/BigtableHelloWorld.java | 27 ++- .../com/example/bigtable/BigtableHelper.java | 46 ++-- .../bigtable/ITBigtableHelloWorld.java | 21 +- .../appengine/cloudsql/CloudSqlServlet.java | 2 +- .../com/example/appengine/IndexesServlet.java | 3 +- .../example/appengine/IndexesServletTest.java | 25 +- .../com/example/appengine/IndexesServlet.java | 6 +- .../example/appengine/IndexesServletTest.java | 14 +- .../com/example/appengine/IndexesServlet.java | 6 +- .../example/appengine/IndexesServletTest.java | 14 +- .../example/appengine/AbstractGuestbook.java | 11 +- .../appengine/AbstractGuestbookServlet.java | 3 +- .../java/com/example/appengine/Greeting.java | 7 +- .../java/com/example/appengine/Guestbook.java | 19 +- .../example/appengine/GuestbookServlet.java | 1 + .../example/appengine/GuestbookStrong.java | 13 +- .../appengine/GuestbookStrongServlet.java | 1 + .../example/appengine/ListPeopleServlet.java | 4 +- .../example/appengine/ProjectionServlet.java | 3 +- .../com/example/appengine/StartupServlet.java | 3 +- .../com/example/appengine/StatsServlet.java | 3 +- .../src/main/java/com/example/time/Clock.java | 1 + .../java/com/example/time/SystemClock.java | 9 +- .../com/example/time/testing/FakeClock.java | 47 ++-- .../com/example/appengine/EntitiesTest.java | 22 +- .../appengine/GuestbookStrongTest.java | 24 +- .../com/example/appengine/GuestbookTest.java | 20 +- .../com/example/appengine/IndexesTest.java | 7 +- .../appengine/ListPeopleServletTest.java | 21 +- .../appengine/MetadataEntityGroupTest.java | 12 +- .../example/appengine/MetadataKindsTest.java | 13 +- .../appengine/MetadataNamespacesTest.java | 13 +- .../appengine/MetadataPropertiesTest.java | 15 +- .../appengine/ProjectionServletTest.java | 29 +-- .../com/example/appengine/ProjectionTest.java | 11 +- .../com/example/appengine/QueriesTest.java | 25 +- .../com/example/appengine/ReadPolicyTest.java | 8 +- .../example/appengine/StartupServletTest.java | 20 +- .../example/appengine/TransactionsTest.java | 8 +- .../src/main/java/com/example/echo/Echo.java | 56 +++-- .../src/main/java/com/example/echo/Email.java | 5 +- .../main/java/com/example/echo/Message.java | 4 +- .../FirebaseEventProxy.java | 100 ++++---- .../ServletContextListenerImpl.java | 4 +- .../appengine/firetactoe/DeleteServlet.java | 4 +- .../appengine/firetactoe/FirebaseChannel.java | 99 +++++--- .../example/appengine/firetactoe/Game.java | 61 +++-- .../appengine/firetactoe/MoveServlet.java | 10 +- .../appengine/firetactoe/ObjectifyHelper.java | 15 +- .../appengine/firetactoe/OpenedServlet.java | 8 +- .../firetactoe/TicTacToeServlet.java | 20 +- .../firetactoe/DeleteServletTest.java | 74 +++--- .../firetactoe/FirebaseChannelTest.java | 224 ++++++++++-------- .../appengine/firetactoe/MoveServletTest.java | 74 +++--- .../firetactoe/OpenedServletTest.java | 76 +++--- .../firetactoe/TicTacToeServletTest.java | 110 ++++----- .../appengine/standard/GaeInfoServlet.java | 73 +++--- .../java/com/example/guestbook/Greeting.java | 4 +- .../java/com/example/guestbook/Guestbook.java | 4 +- .../com/example/guestbook/Persistence.java | 8 +- .../guestbook/SignGuestbookServlet.java | 3 +- .../com/example/guestbook/GreetingTest.java | 4 +- .../guestbook/SignGuestbookServletTest.java | 15 +- .../java/com/example/guestbook/TestUtils.java | 11 +- .../java/com/example/guestbook/Greeting.java | 52 ++-- .../java/com/example/guestbook/Guestbook.java | 25 +- .../java/com/example/guestbook/OfyHelper.java | 23 +- .../guestbook/SignGuestbookServlet.java | 27 +-- .../com/example/guestbook/GreetingTest.java | 14 +- .../guestbook/GuestbookTestUtilities.java | 10 +- .../guestbook/SignGuestbookServletTest.java | 33 +-- .../example/appengine/logs/LogsServlet.java | 19 +- .../appengine/mailgun/MailgunServlet.java | 34 +-- .../appengine/mailjet/MailjetServlet.java | 53 +++-- .../java/com/example/appengine/Greeting.java | 56 +++-- .../java/com/example/appengine/Guestbook.java | 25 +- .../appengine/MultitenancyServlet.java | 25 +- .../example/appengine/NamespaceFilter.java | 6 +- .../java/com/example/appengine/OfyHelper.java | 25 +- .../appengine/SignGuestbookServlet.java | 24 +- .../example/appengine/SomeRequestServlet.java | 20 +- .../appengine/UpdateCountsServlet.java | 20 +- .../com/example/appengine/GreetingTest.java | 14 +- .../appengine/GuestbookTestUtilities.java | 10 +- .../appengine/SignGuestbookServletTest.java | 33 +-- .../com/example/appengine/HelloServlet.java | 23 +- .../com/example/appengine/Oauth2Filter.java | 40 ++-- appengine-java8/pom.xml | 2 +- .../appengine/remote/RemoteApiExample.java | 26 +- .../appengine/requests/LoggingServlet.java | 14 +- .../appengine/requests/RequestsServlet.java | 10 +- .../requests/LoggingServletTest.java | 22 +- .../requests/RequestsServletTest.java | 17 +- .../appengine/search/DeleteServlet.java | 44 ++-- .../appengine/search/DocumentServlet.java | 63 ++--- .../appengine/search/IndexServlet.java | 50 ++-- .../appengine/search/SchemaServlet.java | 63 +++-- .../appengine/search/SearchOptionServlet.java | 101 ++++---- .../appengine/search/SearchServlet.java | 55 ++--- .../com/example/appengine/search/Utils.java | 18 +- .../appengine/search/DeleteServletTest.java | 32 +-- .../appengine/search/DocumentServletTest.java | 48 ++-- .../appengine/search/IndexServletTest.java | 32 +-- .../appengine/search/SchemaServletTest.java | 48 ++-- .../search/SearchOptionServletTest.java | 30 +-- .../appengine/search/SearchServletTest.java | 40 ++-- .../example/appengine/search/UtilsTest.java | 27 +-- .../appengine/sendgrid/SendEmailServlet.java | 16 +- .../appengine/spanner/SpannerClient.java | 2 +- .../appengine/spanner/SpannerTasks.java | 9 +- .../spanner/SpannerTasksServlet.java | 15 +- .../taskqueue/samples/DeferSampleServlet.java | 55 ++--- .../example/taskqueue/TaskqueueServlet.java | 62 ++--- .../appengine/taskqueue/push/Enqueue.java | 19 +- .../appengine/taskqueue/push/Worker.java | 12 +- .../appengine/taskqueue/push/WorkerTest.java | 15 +- .../appengine/twilio/ReceiveCallServlet.java | 20 +- .../appengine/twilio/ReceiveSmsServlet.java | 20 +- .../appengine/twilio/SendSmsServlet.java | 24 +- .../example/appengine/UrlFetchServlet.java | 25 +- .../example/appengine/users/UsersServlet.java | 8 +- .../appengine/users/UsersServletTest.java | 14 +- .../example/analytics/AnalyticsServlet.java | 34 ++- pom.xml | 2 +- 132 files changed, 1774 insertions(+), 1655 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000000..29ef41ac3d6 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,19 @@ +[*] +charset=utf-8 +end_of_line=lf +insert_final_newline=false +indent_style=space +indent_size=2 + +[{*.gson,*.gradle,*.groovy,*.gant,*.gdsl,*.gy}] +indent_style=space +indent_size=4 + +[{*.xjsp,*.tag,*.jsf,*.jsp,*.jspf,*.tagf}] +indent_style=space +indent_size=4 + +[{*.yml,*.yaml}] +indent_style=space +indent_size=2 + diff --git a/appengine-java8/analytics/src/main/java/com/example/appengine/analytics/AnalyticsServlet.java b/appengine-java8/analytics/src/main/java/com/example/appengine/analytics/AnalyticsServlet.java index d4153212ffc..99ab9e1649e 100644 --- a/appengine-java8/analytics/src/main/java/com/example/appengine/analytics/AnalyticsServlet.java +++ b/appengine-java8/analytics/src/main/java/com/example/appengine/analytics/AnalyticsServlet.java @@ -11,6 +11,7 @@ * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.appengine.analytics; import com.google.appengine.api.urlfetch.URLFetchService; @@ -30,9 +31,9 @@ @SuppressWarnings("serial") // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. @WebServlet( - name = "analytics", - description = "Analytics: Send Analytics Event to Google Analytics", - urlPatterns = "/analytics" + name = "analytics", + description = "Analytics: Send Analytics Event to Google Analytics", + urlPatterns = "/analytics" ) public class AnalyticsServlet extends HttpServlet { diff --git a/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/IdentityServlet.java b/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/IdentityServlet.java index 51668f2d4d9..d8054c9f450 100644 --- a/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/IdentityServlet.java +++ b/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/IdentityServlet.java @@ -17,9 +17,7 @@ package com.example.appengine.appidentity; import com.google.apphosting.api.ApiProxy; - import java.io.IOException; - import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -27,8 +25,11 @@ @SuppressWarnings("serial") // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. -@WebServlet(name = "appidentity", description = "AppIdentity: Get the Host Name", - urlPatterns = "/appidentity/identity") +@WebServlet( + name = "appidentity", + description = "AppIdentity: Get the Host Name", + urlPatterns = "/appidentity/identity" +) public class IdentityServlet extends HttpServlet { // [START versioned_hostnames] diff --git a/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/SignForAppServlet.java b/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/SignForAppServlet.java index 328684349c7..8c5ba72ebbe 100644 --- a/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/SignForAppServlet.java +++ b/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/SignForAppServlet.java @@ -19,7 +19,6 @@ import com.google.appengine.api.appidentity.AppIdentityService; import com.google.appengine.api.appidentity.AppIdentityServiceFactory; import com.google.appengine.api.appidentity.PublicCertificate; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -35,7 +34,6 @@ import java.util.Arrays; import java.util.Calendar; import java.util.Collection; - import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -43,9 +41,13 @@ @SuppressWarnings("serial") // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. -@WebServlet(name = "signforapp", description = "AppIdentity: Sign 'abcdefg'", - urlPatterns = "/appidentity/sign") +@WebServlet( + name = "signforapp", + description = "AppIdentity: Sign 'abcdefg'", + urlPatterns = "/appidentity/sign" +) public class SignForAppServlet extends HttpServlet { + private final AppIdentityService appIdentity; public SignForAppServlet() { @@ -98,10 +100,7 @@ private String simulateIdentityAssertion() return String.format( "isValid=%b for message: %s\n\tsignature: %s\n\tpublic cert: %s", - isValid, - message, - Arrays.toString(blobSignature), - Arrays.toString(publicCert)); + isValid, message, Arrays.toString(blobSignature), Arrays.toString(publicCert)); } // [END asserting_identity_to_other_services] diff --git a/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/UrlShortener.java b/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/UrlShortener.java index 4ef26aa135a..7aed43d3dfe 100644 --- a/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/UrlShortener.java +++ b/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/UrlShortener.java @@ -19,10 +19,6 @@ import com.google.appengine.api.appidentity.AppIdentityService; import com.google.appengine.api.appidentity.AppIdentityServiceFactory; import com.google.common.io.CharStreams; - -import org.json.JSONObject; -import org.json.JSONTokener; - import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; @@ -30,10 +26,13 @@ import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import org.json.JSONObject; +import org.json.JSONTokener; @SuppressWarnings("serial") class UrlShortener { // [START asserting_identity_to_Google_APIs] + /** * Returns a shortened URL by calling the Google URL Shortener API. * @@ -68,11 +67,10 @@ public String createShortUrl(String longUrl) throws Exception { } else { try (InputStream s = connection.getErrorStream(); InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) { - throw new RuntimeException(String.format( - "got error (%d) response %s from %s", - connection.getResponseCode(), - CharStreams.toString(r), - connection.toString())); + throw new RuntimeException( + String.format( + "got error (%d) response %s from %s", + connection.getResponseCode(), CharStreams.toString(r), connection.toString())); } } } diff --git a/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/UrlShortenerServlet.java b/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/UrlShortenerServlet.java index 319c73ebc37..8e622793479 100644 --- a/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/UrlShortenerServlet.java +++ b/appengine-java8/appidentity/src/main/java/com/example/appengine/appidentity/UrlShortenerServlet.java @@ -18,7 +18,6 @@ import java.io.IOException; import java.io.PrintWriter; - import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -26,9 +25,13 @@ @SuppressWarnings("serial") // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. -@WebServlet(name = "UrlShortener", description = "AppIdentity: Url Shortener", - urlPatterns = "/appidentity/shorten") +@WebServlet( + name = "UrlShortener", + description = "AppIdentity: Url Shortener", + urlPatterns = "/appidentity/shorten" +) public class UrlShortenerServlet extends HttpServlet { + private final UrlShortener shortener; public UrlShortenerServlet() { diff --git a/appengine-java8/appidentity/src/test/java/com/example/appengine/appidentity/IdentityServletTest.java b/appengine-java8/appidentity/src/test/java/com/example/appengine/appidentity/IdentityServletTest.java index 74041b24cd3..06252f0e2f9 100644 --- a/appengine-java8/appidentity/src/test/java/com/example/appengine/appidentity/IdentityServletTest.java +++ b/appengine-java8/appidentity/src/test/java/com/example/appengine/appidentity/IdentityServletTest.java @@ -20,7 +20,10 @@ import static org.mockito.Mockito.when; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; - +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -29,12 +32,6 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * Unit tests for {@link IdentityServlet}. */ @@ -44,8 +41,10 @@ public class IdentityServletTest { // Set up a helper so that the ApiProxy returns a valid environment for local testing. private final LocalServiceTestHelper helper = new LocalServiceTestHelper(); - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private IdentityServlet servletUnderTest; @@ -61,7 +60,8 @@ public void setUp() throws Exception { servletUnderTest = new IdentityServlet(); } - @After public void tearDown() { + @After + public void tearDown() { helper.tearDown(); } diff --git a/appengine-java8/appidentity/src/test/java/com/example/appengine/appidentity/SignForAppServletTest.java b/appengine-java8/appidentity/src/test/java/com/example/appengine/appidentity/SignForAppServletTest.java index 7cc1fa5411b..ab1b62d1205 100644 --- a/appengine-java8/appidentity/src/test/java/com/example/appengine/appidentity/SignForAppServletTest.java +++ b/appengine-java8/appidentity/src/test/java/com/example/appengine/appidentity/SignForAppServletTest.java @@ -20,7 +20,10 @@ import static org.mockito.Mockito.when; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; - +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -29,12 +32,6 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * Unit tests for {@link SignForAppServlet}. */ @@ -43,12 +40,15 @@ public class SignForAppServletTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper(); - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private SignForAppServlet servletUnderTest; - @Before public void setUp() throws Exception { + @Before + public void setUp() throws Exception { MockitoAnnotations.initMocks(this); helper.setUp(); @@ -59,11 +59,13 @@ public class SignForAppServletTest { servletUnderTest = new SignForAppServlet(); } - @After public void tearDown() { + @After + public void tearDown() { helper.tearDown(); } - @Test public void doGet_defaultEnvironment_successfullyVerifiesSignature() throws Exception { + @Test + public void doGet_defaultEnvironment_successfullyVerifiesSignature() throws Exception { servletUnderTest.doGet(mockRequest, mockResponse); assertThat(responseWriter.toString()) diff --git a/appengine-java8/bigtable/src/main/java/com/example/bigtable/BigtableHelloWorld.java b/appengine-java8/bigtable/src/main/java/com/example/bigtable/BigtableHelloWorld.java index ad2057beb65..21aa1805e57 100644 --- a/appengine-java8/bigtable/src/main/java/com/example/bigtable/BigtableHelloWorld.java +++ b/appengine-java8/bigtable/src/main/java/com/example/bigtable/BigtableHelloWorld.java @@ -16,6 +16,7 @@ package com.example.bigtable; +import java.io.IOException; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; @@ -28,12 +29,11 @@ import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.util.Bytes; - -import java.io.IOException; // [START example] + /** - * A minimal application that connects to Cloud Bigtable using the native HBase API - * and performs some basic operations. + * A minimal application that connects to Cloud Bigtable using the native HBase API and performs + * some basic operations. */ public class BigtableHelloWorld { @@ -43,13 +43,18 @@ public class BigtableHelloWorld { private static final byte[] COLUMN_NAME = Bytes.toBytes("greeting"); // Write some friendly greetings to Cloud Bigtable - private static final String[] GREETINGS = - { "Hello World!", "Hello Cloud Bigtable!", "Hello HBase!" }; - + private static final String[] GREETINGS = { + "Hello World!", "Hello Cloud Bigtable!", "Hello HBase!" + }; + /** + * Create a table -- first time only. + * @param connection to Bigtable + * @return the status + */ public static String create(Connection connection) { try { - // The admin API lets us create, manage and delete tables + // The admin API lets us create, manage and delete tables Admin admin = connection.getAdmin(); // [END connecting_to_bigtable] @@ -66,9 +71,7 @@ public static String create(Connection connection) { return "Create table " + Bytes.toString(TABLE_NAME); } - /** - * Connects to Cloud Bigtable, runs some basic operations and prints the results. - */ + /** Connects to Cloud Bigtable, runs some basic operations and prints the results. */ public static String doHelloWorld() { StringBuilder result = new StringBuilder(); @@ -141,7 +144,5 @@ public static String doHelloWorld() { return result.toString(); } - - } // [END example] diff --git a/appengine-java8/bigtable/src/main/java/com/example/bigtable/BigtableHelper.java b/appengine-java8/bigtable/src/main/java/com/example/bigtable/BigtableHelper.java index 07b43359237..a67482ccc5c 100644 --- a/appengine-java8/bigtable/src/main/java/com/example/bigtable/BigtableHelper.java +++ b/appengine-java8/bigtable/src/main/java/com/example/bigtable/BigtableHelper.java @@ -1,55 +1,49 @@ /** * Copyright 2015 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 + *

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 + *

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 + *

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.example.bigtable; import com.google.cloud.bigtable.hbase.BigtableConfiguration; -import org.apache.hadoop.hbase.client.Connection; - import java.io.IOException; - import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; +import org.apache.hadoop.hbase.client.Connection; /** - * BigtableHelper, a ServletContextListener, is setup in web.xml to run before a JSP is run. - * Project / Instance settings can be passed as an Environment Variable, a System Property, or set - * in web.xml from a context-param - * - **/ + * BigtableHelper, a ServletContextListener, is setup in web.xml to run before a jsp is run. Project + * / Instance settings can be passed as an Environment Variable, a System Property, or set in + * web.xml from a context-param + */ @WebListener public class BigtableHelper implements ServletContextListener { private static String PROJECT_ID; private static String INSTANCE_ID; -// The initial connection to Cloud Bigtable is an expensive operation -- We cache this Connection -// to speed things up. For this sample, keeping them here is a good idea, for -// your application, you may wish to keep this somewhere else. - private static Connection connection = null; // The authenticated connection + // The initial connection to Cloud Bigtable is an expensive operation -- We cache this Connection + // to speed things up. For this sample, keeping them here is a good idea, for + // your application, you may wish to keep this somewhere else. + private static Connection connection = null; // The authenticated connection private static ServletContext sc; -/** - * Connect will establish the connection to Cloud Bigtable. - **/ + /** Connect will establish the connection to Cloud Bigtable. */ public static void connect() throws IOException { - if (PROJECT_ID == null || INSTANCE_ID == null ) { + if (PROJECT_ID == null || INSTANCE_ID == null) { if (sc != null) { sc.log("environment variables BIGTABLE_PROJECT, and BIGTABLE_INSTANCE need to be defined."); } @@ -59,6 +53,10 @@ public static void connect() throws IOException { connection = BigtableConfiguration.connect(PROJECT_ID, INSTANCE_ID); } + /** + * Get the shared connection to Cloud Bigtable. + * @return the connection + */ public static Connection getConnection() { if (connection == null) { try { diff --git a/appengine-java8/bigtable/src/test/java/com/example/bigtable/ITBigtableHelloWorld.java b/appengine-java8/bigtable/src/test/java/com/example/bigtable/ITBigtableHelloWorld.java index abce9adcb26..f3dea2f7305 100644 --- a/appengine-java8/bigtable/src/test/java/com/example/bigtable/ITBigtableHelloWorld.java +++ b/appengine-java8/bigtable/src/test/java/com/example/bigtable/ITBigtableHelloWorld.java @@ -1,16 +1,14 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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. */ @@ -23,13 +21,11 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** - * Unit tests for {@link HelloAppEngine}. - */ - +/** Unit tests for {@link HelloAppEngine}. */ @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") public class ITBigtableHelloWorld { + private BigtableHelper helper; @Before @@ -47,5 +43,4 @@ public void bigtable_test() { assertThat(result).contains("Hello Cloud Bigtable!"); assertThat(result).contains("Hello HBase!"); } - } diff --git a/appengine-java8/cloudsql/src/main/java/com/example/appengine/cloudsql/CloudSqlServlet.java b/appengine-java8/cloudsql/src/main/java/com/example/appengine/cloudsql/CloudSqlServlet.java index cd198495215..5eeb03b6bf4 100644 --- a/appengine-java8/cloudsql/src/main/java/com/example/appengine/cloudsql/CloudSqlServlet.java +++ b/appengine-java8/cloudsql/src/main/java/com/example/appengine/cloudsql/CloudSqlServlet.java @@ -19,8 +19,8 @@ import com.google.apphosting.api.ApiProxy; import com.google.common.base.Stopwatch; - import java.io.IOException; + import java.io.PrintWriter; import java.net.Inet4Address; import java.net.Inet6Address; diff --git a/appengine-java8/datastore-indexes-exploding/src/main/java/com/example/appengine/IndexesServlet.java b/appengine-java8/datastore-indexes-exploding/src/main/java/com/example/appengine/IndexesServlet.java index 04d4fe018d4..9cd2ec3437d 100644 --- a/appengine-java8/datastore-indexes-exploding/src/main/java/com/example/appengine/IndexesServlet.java +++ b/appengine-java8/datastore-indexes-exploding/src/main/java/com/example/appengine/IndexesServlet.java @@ -24,11 +24,9 @@ import com.google.appengine.api.datastore.Query.CompositeFilterOperator; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Query.FilterPredicate; - import java.io.IOException; import java.io.PrintWriter; import java.util.List; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -38,6 +36,7 @@ * A servlet to demonstrate the use of Cloud Datastore indexes. */ public class IndexesServlet extends HttpServlet { + private final DatastoreService datastore; public IndexesServlet() { diff --git a/appengine-java8/datastore-indexes-exploding/src/test/java/com/example/appengine/IndexesServletTest.java b/appengine-java8/datastore-indexes-exploding/src/test/java/com/example/appengine/IndexesServletTest.java index ea86f530fef..b1eae0d9380 100644 --- a/appengine-java8/datastore-indexes-exploding/src/test/java/com/example/appengine/IndexesServletTest.java +++ b/appengine-java8/datastore-indexes-exploding/src/test/java/com/example/appengine/IndexesServletTest.java @@ -24,6 +24,12 @@ import com.google.appengine.api.datastore.Entity; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Arrays; +import java.util.Date; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -32,14 +38,6 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Arrays; -import java.util.Date; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * Unit tests for {@link IndexesServlet}. */ @@ -49,12 +47,16 @@ public class IndexesServletTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0)); - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private IndexesServlet servletUnderTest; @@ -84,6 +86,7 @@ public void doGet_emptyDatastore_writesNoWidgets() throws Exception { .isEqualTo("Got 0 widgets.\n"); } + @SuppressWarnings(VariableDeclarationUsageDistance) @Test public void doGet_repeatedPropertyEntities_writesWidgets() throws Exception { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); diff --git a/appengine-java8/datastore-indexes-perfect/src/main/java/com/example/appengine/IndexesServlet.java b/appengine-java8/datastore-indexes-perfect/src/main/java/com/example/appengine/IndexesServlet.java index 5a01f1a53e5..407c5ce6238 100644 --- a/appengine-java8/datastore-indexes-perfect/src/main/java/com/example/appengine/IndexesServlet.java +++ b/appengine-java8/datastore-indexes-perfect/src/main/java/com/example/appengine/IndexesServlet.java @@ -24,19 +24,15 @@ import com.google.appengine.api.datastore.Query.CompositeFilterOperator; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Query.FilterPredicate; - import java.io.IOException; import java.io.PrintWriter; import java.util.List; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -/** - * A servlet to demonstrate the use of Cloud Datastore indexes. - */ +/** A servlet to demonstrate the use of Cloud Datastore indexes. */ public class IndexesServlet extends HttpServlet { private final DatastoreService datastore; diff --git a/appengine-java8/datastore-indexes-perfect/src/test/java/com/example/appengine/IndexesServletTest.java b/appengine-java8/datastore-indexes-perfect/src/test/java/com/example/appengine/IndexesServletTest.java index d1816a7034d..388fed1b90b 100644 --- a/appengine-java8/datastore-indexes-perfect/src/test/java/com/example/appengine/IndexesServletTest.java +++ b/appengine-java8/datastore-indexes-perfect/src/test/java/com/example/appengine/IndexesServletTest.java @@ -21,6 +21,10 @@ import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -29,15 +33,7 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Unit tests for {@link IndexesServlet}. - */ +/** Unit tests for {@link IndexesServlet}. */ @RunWith(JUnit4.class) public class IndexesServletTest { diff --git a/appengine-java8/datastore-indexes/src/main/java/com/example/appengine/IndexesServlet.java b/appengine-java8/datastore-indexes/src/main/java/com/example/appengine/IndexesServlet.java index 5493ce1f1a9..9defeab31bf 100644 --- a/appengine-java8/datastore-indexes/src/main/java/com/example/appengine/IndexesServlet.java +++ b/appengine-java8/datastore-indexes/src/main/java/com/example/appengine/IndexesServlet.java @@ -24,19 +24,15 @@ import com.google.appengine.api.datastore.Query.CompositeFilterOperator; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Query.FilterPredicate; - import java.io.IOException; import java.io.PrintWriter; import java.util.List; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -/** - * A servlet to demonstrate the use of Cloud Datastore indexes. - */ +/** A servlet to demonstrate the use of Cloud Datastore indexes. */ public class IndexesServlet extends HttpServlet { private final DatastoreService datastore; diff --git a/appengine-java8/datastore-indexes/src/test/java/com/example/appengine/IndexesServletTest.java b/appengine-java8/datastore-indexes/src/test/java/com/example/appengine/IndexesServletTest.java index 83575239136..6460483e745 100644 --- a/appengine-java8/datastore-indexes/src/test/java/com/example/appengine/IndexesServletTest.java +++ b/appengine-java8/datastore-indexes/src/test/java/com/example/appengine/IndexesServletTest.java @@ -21,6 +21,10 @@ import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -29,15 +33,7 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Unit tests for {@link IndexesServlet}. - */ +/** Unit tests for {@link IndexesServlet}. */ @RunWith(JUnit4.class) public class IndexesServletTest { diff --git a/appengine-java8/datastore/src/main/java/com/example/appengine/AbstractGuestbook.java b/appengine-java8/datastore/src/main/java/com/example/appengine/AbstractGuestbook.java index b87edf7eeba..e0710a2279a 100644 --- a/appengine-java8/datastore/src/main/java/com/example/appengine/AbstractGuestbook.java +++ b/appengine-java8/datastore/src/main/java/com/example/appengine/AbstractGuestbook.java @@ -17,7 +17,6 @@ package com.example.appengine; import com.example.time.Clock; - import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; @@ -25,7 +24,6 @@ import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import com.google.common.collect.ImmutableList; - import java.util.Date; import java.util.List; @@ -35,6 +33,7 @@ *

This is meant to be subclassed to demonstrate different storage structures in Datastore. */ abstract class AbstractGuestbook { + private final DatastoreService datastore; private final UserService userService; private final Clock clock; @@ -47,15 +46,11 @@ abstract class AbstractGuestbook { /** * Appends a new greeting to the guestbook and returns the {@link Entity} that was created. - */ + **/ public Greeting appendGreeting(String content) { Greeting greeting = Greeting.create( - createGreeting( - datastore, - userService.getCurrentUser(), - clock.now().toDate(), - content)); + createGreeting(datastore, userService.getCurrentUser(), clock.now().toDate(), content)); return greeting; } diff --git a/appengine-java8/datastore/src/main/java/com/example/appengine/AbstractGuestbookServlet.java b/appengine-java8/datastore/src/main/java/com/example/appengine/AbstractGuestbookServlet.java index e77231497c6..219259d022c 100644 --- a/appengine-java8/datastore/src/main/java/com/example/appengine/AbstractGuestbookServlet.java +++ b/appengine-java8/datastore/src/main/java/com/example/appengine/AbstractGuestbookServlet.java @@ -17,13 +17,13 @@ package com.example.appengine; import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; abstract class AbstractGuestbookServlet extends HttpServlet { + private final AbstractGuestbook guestbook; public AbstractGuestbookServlet(AbstractGuestbook guestbook) { @@ -56,4 +56,3 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) renderGuestbook(req, resp); } } - diff --git a/appengine-java8/datastore/src/main/java/com/example/appengine/Greeting.java b/appengine-java8/datastore/src/main/java/com/example/appengine/Greeting.java index 352aa0a1dde..2a9d92979fe 100644 --- a/appengine-java8/datastore/src/main/java/com/example/appengine/Greeting.java +++ b/appengine-java8/datastore/src/main/java/com/example/appengine/Greeting.java @@ -19,18 +19,17 @@ import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.users.User; import com.google.auto.value.AutoValue; -import org.joda.time.Instant; - import java.util.Date; - import javax.annotation.Nullable; +import org.joda.time.Instant; @AutoValue public abstract class Greeting { + static Greeting create(Entity entity) { User user = (User) entity.getProperty("user"); Instant date = new Instant((Date) entity.getProperty("date")); - String content = (String) entity.getProperty("content"); + String content = (String) entity.getProperty("content"); return new AutoValue_Greeting(user, date, content); } diff --git a/appengine-java8/datastore/src/main/java/com/example/appengine/Guestbook.java b/appengine-java8/datastore/src/main/java/com/example/appengine/Guestbook.java index 83e984818c4..fbea3a072ba 100644 --- a/appengine-java8/datastore/src/main/java/com/example/appengine/Guestbook.java +++ b/appengine-java8/datastore/src/main/java/com/example/appengine/Guestbook.java @@ -17,25 +17,23 @@ package com.example.appengine; import com.example.time.Clock; - import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.users.User; - import java.util.Date; import java.util.List; /** * A log of notes left by users. * - *

This demonstrates the use of Google Cloud Datastore using the App Engine - * APIs. See the - * documentation - * for more information. + *

This demonstrates the use of Google Cloud Datastore using the App Engine APIs. See the documentation for more + * information. */ class Guestbook extends AbstractGuestbook { + Guestbook(Clock clock) { super(clock); } @@ -55,12 +53,7 @@ protected Entity createGreeting( @Override protected List listGreetingEntities(DatastoreService datastore) { - Query query = - new Query("Greeting") - .addSort("date", Query.SortDirection.DESCENDING); - return datastore.prepare(query) - .asList(FetchOptions.Builder.withLimit(10)); + Query query = new Query("Greeting").addSort("date", Query.SortDirection.DESCENDING); + return datastore.prepare(query).asList(FetchOptions.Builder.withLimit(10)); } - - } diff --git a/appengine-java8/datastore/src/main/java/com/example/appengine/GuestbookServlet.java b/appengine-java8/datastore/src/main/java/com/example/appengine/GuestbookServlet.java index 5ebab796530..fa8d6f4e2d0 100644 --- a/appengine-java8/datastore/src/main/java/com/example/appengine/GuestbookServlet.java +++ b/appengine-java8/datastore/src/main/java/com/example/appengine/GuestbookServlet.java @@ -19,6 +19,7 @@ import com.example.time.SystemClock; public class GuestbookServlet extends AbstractGuestbookServlet { + public GuestbookServlet() { super(new Guestbook(new SystemClock())); } diff --git a/appengine-java8/datastore/src/main/java/com/example/appengine/GuestbookStrong.java b/appengine-java8/datastore/src/main/java/com/example/appengine/GuestbookStrong.java index 5f3ad23b91d..c6a26d9dab7 100644 --- a/appengine-java8/datastore/src/main/java/com/example/appengine/GuestbookStrong.java +++ b/appengine-java8/datastore/src/main/java/com/example/appengine/GuestbookStrong.java @@ -17,7 +17,6 @@ package com.example.appengine; import com.example.time.Clock; - import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.FetchOptions; @@ -25,19 +24,18 @@ import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.users.User; - import java.util.Date; import java.util.List; /** * A log of notes left by users. * - *

This demonstrates the use of Google Cloud Datastore using the App Engine - * APIs. See the - * documentation - * for more information. + *

This demonstrates the use of Google Cloud Datastore using the App Engine APIs. See the documentation for more + * information. */ class GuestbookStrong extends AbstractGuestbook { + private final String guestbookName; GuestbookStrong(String guestbookName, Clock clock) { @@ -68,7 +66,6 @@ protected List listGreetingEntities(DatastoreService datastore) { new Query("Greeting", guestbookKey) .setAncestor(guestbookKey) .addSort("date", Query.SortDirection.DESCENDING); - return datastore.prepare(query) - .asList(FetchOptions.Builder.withLimit(10)); + return datastore.prepare(query).asList(FetchOptions.Builder.withLimit(10)); } } diff --git a/appengine-java8/datastore/src/main/java/com/example/appengine/GuestbookStrongServlet.java b/appengine-java8/datastore/src/main/java/com/example/appengine/GuestbookStrongServlet.java index e73ae1e0fcc..f799821832f 100644 --- a/appengine-java8/datastore/src/main/java/com/example/appengine/GuestbookStrongServlet.java +++ b/appengine-java8/datastore/src/main/java/com/example/appengine/GuestbookStrongServlet.java @@ -19,6 +19,7 @@ import com.example.time.SystemClock; public class GuestbookStrongServlet extends AbstractGuestbookServlet { + public static final String GUESTBOOK_ID = "my guestbook"; public GuestbookStrongServlet() { diff --git a/appengine-java8/datastore/src/main/java/com/example/appengine/ListPeopleServlet.java b/appengine-java8/datastore/src/main/java/com/example/appengine/ListPeopleServlet.java index b59aaab3aa0..637f9885fca 100644 --- a/appengine-java8/datastore/src/main/java/com/example/appengine/ListPeopleServlet.java +++ b/appengine-java8/datastore/src/main/java/com/example/appengine/ListPeopleServlet.java @@ -17,6 +17,7 @@ package com.example.appengine; // [START cursors] + import com.google.appengine.api.datastore.Cursor; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; @@ -26,16 +27,15 @@ import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.SortDirection; import com.google.appengine.api.datastore.QueryResultList; - import java.io.IOException; import java.io.PrintWriter; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ListPeopleServlet extends HttpServlet { + static final int PAGE_SIZE = 15; private final DatastoreService datastore; diff --git a/appengine-java8/datastore/src/main/java/com/example/appengine/ProjectionServlet.java b/appengine-java8/datastore/src/main/java/com/example/appengine/ProjectionServlet.java index 81bdaf6cf9b..6942403d3e4 100644 --- a/appengine-java8/datastore/src/main/java/com/example/appengine/ProjectionServlet.java +++ b/appengine-java8/datastore/src/main/java/com/example/appengine/ProjectionServlet.java @@ -24,12 +24,10 @@ import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PropertyProjection; import com.google.appengine.api.datastore.Query; - import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.List; - import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -43,6 +41,7 @@ */ @SuppressWarnings("serial") public class ProjectionServlet extends HttpServlet { + private static final String GUESTBOOK_ID = GuestbookStrongServlet.GUESTBOOK_ID; private final DatastoreService datastore; diff --git a/appengine-java8/datastore/src/main/java/com/example/appengine/StartupServlet.java b/appengine-java8/datastore/src/main/java/com/example/appengine/StartupServlet.java index 2c523f3db15..6eb51403c61 100644 --- a/appengine-java8/datastore/src/main/java/com/example/appengine/StartupServlet.java +++ b/appengine-java8/datastore/src/main/java/com/example/appengine/StartupServlet.java @@ -23,9 +23,7 @@ import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.common.collect.ImmutableList; - import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -35,6 +33,7 @@ * A startup handler to populate the datastore with example entities. */ public class StartupServlet extends HttpServlet { + static final String IS_POPULATED_ENTITY = "IsPopulated"; static final String IS_POPULATED_KEY_NAME = "is-populated"; diff --git a/appengine-java8/datastore/src/main/java/com/example/appengine/StatsServlet.java b/appengine-java8/datastore/src/main/java/com/example/appengine/StatsServlet.java index b6d6925fc12..b15e11ddd0b 100644 --- a/appengine-java8/datastore/src/main/java/com/example/appengine/StatsServlet.java +++ b/appengine-java8/datastore/src/main/java/com/example/appengine/StatsServlet.java @@ -20,16 +20,15 @@ import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Query; - import java.io.IOException; import java.io.PrintWriter; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class StatsServlet extends HttpServlet { + @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { diff --git a/appengine-java8/datastore/src/main/java/com/example/time/Clock.java b/appengine-java8/datastore/src/main/java/com/example/time/Clock.java index 7d75e2b62d4..c6954f13057 100644 --- a/appengine-java8/datastore/src/main/java/com/example/time/Clock.java +++ b/appengine-java8/datastore/src/main/java/com/example/time/Clock.java @@ -28,6 +28,7 @@ * framework such as Mockito. */ public interface Clock { + /** * Returns the current, absolute time according to this clock. */ diff --git a/appengine-java8/datastore/src/main/java/com/example/time/SystemClock.java b/appengine-java8/datastore/src/main/java/com/example/time/SystemClock.java index 032230bd0c4..2e4097f4c04 100644 --- a/appengine-java8/datastore/src/main/java/com/example/time/SystemClock.java +++ b/appengine-java8/datastore/src/main/java/com/example/time/SystemClock.java @@ -21,15 +21,16 @@ /** * Clock implementation that returns the "real" system time. * - *

This class exists so that we can use a fake implementation for unit - * testing classes that need the current time value. See {@link Clock} for - * general information about clocks. + *

This class exists so that we can use a fake implementation for unit testing classes that need + * the current time value. See {@link Clock} for general information about clocks. */ public class SystemClock implements Clock { + /** * Creates a new instance. All {@code SystemClock} instances function identically. */ - public SystemClock() {} + public SystemClock() { + } @Override public Instant now() { diff --git a/appengine-java8/datastore/src/main/java/com/example/time/testing/FakeClock.java b/appengine-java8/datastore/src/main/java/com/example/time/testing/FakeClock.java index 7ede635d762..c2208d962e5 100644 --- a/appengine-java8/datastore/src/main/java/com/example/time/testing/FakeClock.java +++ b/appengine-java8/datastore/src/main/java/com/example/time/testing/FakeClock.java @@ -17,25 +17,24 @@ package com.example.time.testing; import com.example.time.Clock; - +import java.util.concurrent.atomic.AtomicLong; import org.joda.time.Instant; import org.joda.time.ReadableDuration; import org.joda.time.ReadableInstant; -import java.util.concurrent.atomic.AtomicLong; - /** - * A Clock that returns a fixed Instant value as the current clock time. The - * fixed Instant is settable for testing. Test code should hold a reference to - * the FakeClock, while code under test should hold a Clock reference. + * A Clock that returns a fixed Instant value as the current clock time. The fixed Instant is + * settable for testing. Test code should hold a reference to the FakeClock, while code under test + * should hold a Clock reference. * - *

The clock time can be incremented/decremented manually, with - * {@link #incrementTime} and {@link #decrementTime} respectively. + *

The clock time can be incremented/decremented manually, with {@link #incrementTime} and {@link + * #decrementTime} respectively. * - *

The clock can also be configured so that the time is incremented whenever - * {@link #now()} is called: see {@link #setAutoIncrementStep}. + *

The clock can also be configured so that the time is incremented whenever {@link #now()} is + * called: see {@link #setAutoIncrementStep}. */ public class FakeClock implements Clock { + private static final Instant DEFAULT_TIME = new Instant(1000000000L); private final long baseTimeMs; private final AtomicLong fakeNowMs; @@ -72,16 +71,16 @@ public Instant now() { } /** - * Returns the current time without applying an auto increment, if configured. - * The default behavior of {@link #now()} is the same as this method. + * Returns the current time without applying an auto increment, if configured. The default + * behavior of {@link #now()} is the same as this method. */ public Instant peek() { return new Instant(fakeNowMs.get()); } /** - * Reset the given clock back to the base time with which the FakeClock was - * initially constructed. + * Reset the given clock back to the base time with which the FakeClock was initially + * constructed. * * @return this */ @@ -104,8 +103,7 @@ public FakeClock incrementTime(ReadableDuration duration) { /** * Increments the clock time by the given duration. * - * @param durationMs the duration to increment the clock time by, - * in milliseconds + * @param durationMs the duration to increment the clock time by, in milliseconds * @return this */ public FakeClock incrementTime(long durationMs) { @@ -127,8 +125,7 @@ public FakeClock decrementTime(ReadableDuration duration) { /** * Decrements the clock time by the given duration. * - * @param durationMs the duration to decrement the clock time by, - * in milliseconds + * @param durationMs the duration to decrement the clock time by, in milliseconds * @return this */ public FakeClock decrementTime(long durationMs) { @@ -137,8 +134,8 @@ public FakeClock decrementTime(long durationMs) { } /** - * Sets the increment applied to the clock whenever it is queried. - * The increment is zero by default: the clock is left unchanged when queried. + * Sets the increment applied to the clock whenever it is queried. The increment is zero by + * default: the clock is left unchanged when queried. * * @param autoIncrementStep the new auto increment duration * @return this @@ -149,8 +146,8 @@ public FakeClock setAutoIncrementStep(ReadableDuration autoIncrementStep) { } /** - * Sets the increment applied to the clock whenever it is queried. - * The increment is zero by default: the clock is left unchanged when queried. + * Sets the increment applied to the clock whenever it is queried. The increment is zero by + * default: the clock is left unchanged when queried. * * @param autoIncrementStepMs the new auto increment duration, in milliseconds * @return this @@ -163,10 +160,9 @@ public FakeClock setAutoIncrementStep(long autoIncrementStepMs) { /** * Atomically adds the given value to the current time. * - * @see AtomicLong#addAndGet - * * @param durationMs the duration to add, in milliseconds * @return the updated current time + * @see AtomicLong#addAndGet */ protected final Instant addAndGet(long durationMs) { return new Instant(fakeNowMs.addAndGet(durationMs)); @@ -175,10 +171,9 @@ protected final Instant addAndGet(long durationMs) { /** * Atomically adds the given value to the current time. * - * @see AtomicLong#getAndAdd - * * @param durationMs the duration to add, in milliseconds * @return the previous time + * @see AtomicLong#getAndAdd */ protected final Instant getAndAdd(long durationMs) { return new Instant(fakeNowMs.getAndAdd(durationMs)); diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/EntitiesTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/EntitiesTest.java index c9b7640efe4..a9579d51632 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/EntitiesTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/EntitiesTest.java @@ -29,17 +29,16 @@ import com.google.appengine.api.datastore.KeyRange; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Unit tests to demonstrate App Engine Datastore entities. @@ -50,7 +49,9 @@ public class EntitiesTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0)); @@ -70,14 +71,13 @@ public void tearDown() { @Test public void kindExample_writesEntity() throws Exception { // [START kind_example] - DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); - Entity employee = new Entity("Employee", "asalieri"); employee.setProperty("firstName", "Antonio"); employee.setProperty("lastName", "Salieri"); employee.setProperty("hireDate", new Date()); employee.setProperty("attendedHrTraining", true); + DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.put(employee); // [END kind_example] @@ -212,12 +212,14 @@ public void repeatedProperties_storesList() throws Exception { // Sometime later employee = datastore.get(employee.getKey()); @SuppressWarnings("unchecked") // Cast can't verify generic type. - ArrayList retrievedFruits = (ArrayList) employee.getProperty("favoriteFruit"); + ArrayList retrievedFruits = (ArrayList) employee + .getProperty("favoriteFruit"); // [END repeated_properties] assertThat(retrievedFruits).containsExactlyElementsIn(favoriteFruit).inOrder(); } + @SuppressWarnings(VariableDeclarationUsageDistance) @Test public void embeddedEntity_fromEmbedded_embedsProperties() throws Exception { Entity employee = new Entity("Employee"); diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/GuestbookStrongTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/GuestbookStrongTest.java index dcff5595dab..fd7a73990c7 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/GuestbookStrongTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/GuestbookStrongTest.java @@ -19,10 +19,10 @@ import static com.google.common.truth.Truth.assertThat; import com.example.time.testing.FakeClock; - import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; import com.google.appengine.tools.development.testing.LocalUserServiceTestConfig; +import java.util.List; import org.joda.time.Instant; import org.junit.After; import org.junit.Before; @@ -30,27 +30,28 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.List; - /** * Unit tests for {@link GuestbookStrong}. */ @RunWith(JUnit4.class) public class GuestbookStrongTest { + private static final Instant FAKE_NOW = new Instant(1234567890L); private static final String GUESTBOOK_ID = "my guestbook"; private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set maximum eventual consistency. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(100), // Make sure there is a user logged in. We enforce this in web.xml. new LocalUserServiceTestConfig()) - .setEnvIsLoggedIn(true) - .setEnvEmail("test@example.com") - .setEnvAuthDomain("gmail.com"); + .setEnvIsLoggedIn(true) + .setEnvEmail("test@example.com") + .setEnvAuthDomain("gmail.com"); private FakeClock clock; private GuestbookStrong guestbookUnderTest; @@ -71,18 +72,14 @@ public void tearDown() { public void appendGreeting_normalData_setsContentProperty() { Greeting got = guestbookUnderTest.appendGreeting("Hello, Datastore!"); - assertThat(got.getContent()) - .named("content property") - .isEqualTo("Hello, Datastore!"); + assertThat(got.getContent()).named("content property").isEqualTo("Hello, Datastore!"); } @Test public void appendGreeting_normalData_setsDateProperty() { Greeting got = guestbookUnderTest.appendGreeting("Hello, Datastore!"); - assertThat(got.getDate()) - .named("date property") - .isEqualTo(FAKE_NOW); + assertThat(got.getDate()).named("date property").isEqualTo(FAKE_NOW); } @Test @@ -100,4 +97,3 @@ public void listGreetings_maximumEventualConsistency_returnsAllGreetings() { assertThat(got).hasSize(3); } } - diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/GuestbookTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/GuestbookTest.java index 82d5fd11204..96836357318 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/GuestbookTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/GuestbookTest.java @@ -19,26 +19,26 @@ import static com.google.common.truth.Truth.assertThat; import com.example.time.testing.FakeClock; - import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.dev.HighRepJobPolicy; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; import com.google.appengine.tools.development.testing.LocalUserServiceTestConfig; +import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.List; - /** * Unit tests for {@link Guestbook}. */ @RunWith(JUnit4.class) public class GuestbookTest { + private static final class CustomHighRepJobPolicy implements HighRepJobPolicy { + static int newJobCounter = 0; static int existingJobCounter = 0; @@ -58,14 +58,16 @@ public boolean shouldRollForwardExistingJob(Key entityGroup) { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set custom, deterministic, eventual consistency. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setAlternateHighRepJobPolicyClass(CustomHighRepJobPolicy.class), // Make sure there is a user logged in. We enforce this in web.xml. new LocalUserServiceTestConfig()) - .setEnvIsLoggedIn(true) - .setEnvEmail("test@example.com") - .setEnvAuthDomain("gmail.com"); + .setEnvIsLoggedIn(true) + .setEnvEmail("test@example.com") + .setEnvAuthDomain("gmail.com"); private FakeClock clock; private Guestbook guestbookUnderTest; @@ -86,9 +88,7 @@ public void tearDown() { public void appendGreeting_normalData_setsContentProperty() { Greeting got = guestbookUnderTest.appendGreeting("Hello, Datastore!"); - assertThat(got.getContent()) - .named("content property") - .isEqualTo("Hello, Datastore!"); + assertThat(got.getContent()).named("content property").isEqualTo("Hello, Datastore!"); } @Test diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/IndexesTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/IndexesTest.java index 2a9284f3809..b0a491d43f3 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/IndexesTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/IndexesTest.java @@ -30,14 +30,13 @@ import com.google.appengine.api.datastore.Query.FilterPredicate; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.List; - /** * Unit tests to demonstrate App Engine Datastore queries. */ @@ -47,7 +46,9 @@ public class IndexesTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0)); diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/ListPeopleServletTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/ListPeopleServletTest.java index 5ea0920a153..4652c475fe2 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/ListPeopleServletTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/ListPeopleServletTest.java @@ -31,6 +31,10 @@ import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; import com.google.common.collect.ImmutableList; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -39,17 +43,12 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * Unit tests for {@link ListPeopleServlet}. */ @RunWith(JUnit4.class) public class ListPeopleServletTest { + private static final ImmutableList TEST_NAMES = // Keep in alphabetical order, so this is the same as the query order. ImmutableList.builder() @@ -78,12 +77,16 @@ public class ListPeopleServletTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0)); - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private DatastoreService datastore; diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataEntityGroupTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataEntityGroupTest.java index 89545c3e208..701fa4b151d 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataEntityGroupTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataEntityGroupTest.java @@ -33,16 +33,15 @@ import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalMemcacheServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.PrintWriter; +import java.io.Serializable; +import java.io.StringWriter; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.io.PrintWriter; -import java.io.Serializable; -import java.io.StringWriter; - /** * Unit tests to demonstrate App Engine Datastore entity group metadata. */ @@ -52,7 +51,9 @@ public class MetadataEntityGroupTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig().setDefaultHighRepJobPolicyUnappliedJobPercentage(0), new LocalMemcacheServiceTestConfig()); @@ -114,6 +115,7 @@ public void printEntityGroupVersions_printsVersions() throws Exception { // [START entity_group_2] // A simple class for tracking consistent entity group counts. private static class EntityGroupCount implements Serializable { + long version; // Version of the entity group whose count we are tracking int count; diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataKindsTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataKindsTest.java index 16f3d7026d3..d542a1bb794 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataKindsTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataKindsTest.java @@ -29,17 +29,16 @@ import com.google.appengine.api.datastore.Query.FilterPredicate; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.List; - /** * Unit tests to demonstrate App Engine Datastore kinds metadata. */ @@ -49,7 +48,9 @@ public class MetadataKindsTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0)); diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataNamespacesTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataNamespacesTest.java index 98c09d64954..d7f68654bad 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataNamespacesTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataNamespacesTest.java @@ -30,17 +30,16 @@ import com.google.appengine.api.datastore.Query.FilterPredicate; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.List; - /** * Unit tests to demonstrate App Engine Datastore namespaces metadata. */ @@ -50,7 +49,9 @@ public class MetadataNamespacesTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0)); diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataPropertiesTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataPropertiesTest.java index 64b32c6dc38..3853cece038 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataPropertiesTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/MetadataPropertiesTest.java @@ -28,12 +28,6 @@ import com.google.appengine.api.datastore.Query.SortDirection; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; @@ -41,6 +35,11 @@ import java.util.Collection; import java.util.Date; import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Unit tests to demonstrate App Engine Datastore properties metadata. @@ -51,7 +50,9 @@ public class MetadataPropertiesTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0)); diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/ProjectionServletTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/ProjectionServletTest.java index 101abf06052..a3f24e52072 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/ProjectionServletTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/ProjectionServletTest.java @@ -20,9 +20,12 @@ import static org.mockito.Mockito.when; import com.example.time.testing.FakeClock; - import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -31,12 +34,6 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * Unit tests for {@link ProjectionServlet}. */ @@ -46,8 +43,10 @@ public class ProjectionServletTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()); - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private ProjectionServlet servletUnderTest; @@ -91,14 +90,8 @@ public void doGet_manyGreetings_writesLatestGreetings() throws Exception { servletUnderTest.doGet(mockRequest, mockResponse); String output = responseWriter.toString(); - assertThat(output) - .named("ProjectionServlet response") - .contains("Message Hello."); - assertThat(output) - .named("ProjectionServlet response") - .contains("Message Güten Tag!"); - assertThat(output) - .named("ProjectionServlet response") - .contains("Message Hola."); + assertThat(output).named("ProjectionServlet response").contains("Message Hello."); + assertThat(output).named("ProjectionServlet response").contains("Message Güten Tag!"); + assertThat(output).named("ProjectionServlet response").contains("Message Hola."); } } diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/ProjectionTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/ProjectionTest.java index e8f3e81533b..84e92da2cc4 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/ProjectionTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/ProjectionTest.java @@ -26,14 +26,13 @@ import com.google.appengine.api.datastore.Query; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.List; - /** * Unit tests to demonstrate App Engine Datastore projection queries. */ @@ -43,7 +42,9 @@ public class ProjectionTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0)); @@ -60,7 +61,6 @@ public void tearDown() { helper.tearDown(); } - @Test public void projectionQuery_grouping_filtersDuplicates() { putTestData("some duplicate", 0L); @@ -77,8 +77,7 @@ public void projectionQuery_grouping_filtersDuplicates() { q.addSort("A"); // [END grouping] - List entities = - datastore.prepare(q).asList(FetchOptions.Builder.withLimit(5)); + List entities = datastore.prepare(q).asList(FetchOptions.Builder.withLimit(5)); assertThat(entities).hasSize(1); Entity entity = entities.get(0); assertThat((String) entity.getProperty("A")).named("entity.A").isEqualTo("some duplicate"); diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/QueriesTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/QueriesTest.java index d8a2e61dd5c..dc0948b0aca 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/QueriesTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/QueriesTest.java @@ -36,17 +36,16 @@ import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; import com.google.common.collect.ImmutableList; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Arrays; +import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Arrays; -import java.util.List; - /** * Unit tests to demonstrate App Engine Datastore queries. */ @@ -56,7 +55,9 @@ public class QueriesTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0)); @@ -682,7 +683,8 @@ public void queryRestrictions_surprisingMultipleValuesAllMustMatch_returnsNoEnti // Entity "a" will not match because no individual value matches all filters. // See the documentation for more details: - // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions#properties_with_multiple_values_can_behave_in_surprising_ways + // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions + // #properties_with_multiple_values_can_behave_in_surprising_ways List results = datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults()); assertThat(results).named("query results").isEmpty(); @@ -714,7 +716,8 @@ public void queryRestrictions_surprisingMultipleValuesEquals_returnsMatchedEntit // Only "a" and "e" have both 1 and 2 in the "x" array-valued property. // See the documentation for more details: - // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions#properties_with_multiple_values_can_behave_in_surprising_ways + // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions + // #properties_with_multiple_values_can_behave_in_surprising_ways List results = datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults()); assertThat(results).named("query results").containsExactly(a, e); @@ -741,7 +744,8 @@ public void queryRestrictions_surprisingMultipleValuesNotEquals_returnsMatchedEn // The query matches any entity that has a some value other than 1. Only // entity "e" is not matched. See the documentation for more details: - // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions#properties_with_multiple_values_can_behave_in_surprising_ways + // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions + // #properties_with_multiple_values_can_behave_in_surprising_ways List results = datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults()); assertThat(results).named("query results").containsExactly(a, b, c, d); @@ -771,7 +775,8 @@ public void queryRestrictions_surprisingMultipleValuesTwoNotEquals_returnsMatche // Only "b" has some value which matches the "x > 2" portion of this query. // // See the documentation for more details: - // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions#properties_with_multiple_values_can_behave_in_surprising_ways + // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions + // #properties_with_multiple_values_can_behave_in_surprising_ways List results = datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults()); assertThat(results).named("query results").containsExactly(b); diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/ReadPolicyTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/ReadPolicyTest.java index 054088cd863..79ce4dccdca 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/ReadPolicyTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/ReadPolicyTest.java @@ -28,23 +28,25 @@ import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; import com.google.common.collect.ImmutableList; +import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.List; - /** * Unit tests for {@link ReadPolicy}. */ @RunWith(JUnit4.class) public class ReadPolicyTest { + private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set 100% eventual consistency, so we can test with other job policies. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(100)); diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/StartupServletTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/StartupServletTest.java index c6876701c1a..7d8ddf453e7 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/StartupServletTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/StartupServletTest.java @@ -28,6 +28,10 @@ import com.google.appengine.api.datastore.Query.FilterPredicate; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -36,12 +40,6 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * Unit tests for {@link StartupServlet}. */ @@ -51,12 +49,16 @@ public class StartupServletTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0)); - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private DatastoreService datastore; diff --git a/appengine-java8/datastore/src/test/java/com/example/appengine/TransactionsTest.java b/appengine-java8/datastore/src/test/java/com/example/appengine/TransactionsTest.java index 0b958cbf0da..2dc5a1bc116 100644 --- a/appengine-java8/datastore/src/test/java/com/example/appengine/TransactionsTest.java +++ b/appengine-java8/datastore/src/test/java/com/example/appengine/TransactionsTest.java @@ -35,16 +35,15 @@ import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.util.ConcurrentModificationException; +import java.util.Date; +import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.ConcurrentModificationException; -import java.util.Date; -import java.util.List; - /** * Unit tests to demonstrate App Engine Datastore transactions. */ @@ -141,6 +140,7 @@ public void entityGroups() throws Exception { } } + @SuppressWarnings(VariableDeclarationUsageDistance) @Test public void creatingAnEntityInASpecificEntityGroup() throws Exception { String boardName = "my-message-board"; diff --git a/appengine-java8/endpoints-v2-backend/src/main/java/com/example/echo/Echo.java b/appengine-java8/endpoints-v2-backend/src/main/java/com/example/echo/Echo.java index 5804e86dfca..fd3bc8e41bd 100644 --- a/appengine-java8/endpoints-v2-backend/src/main/java/com/example/echo/Echo.java +++ b/appengine-java8/endpoints-v2-backend/src/main/java/com/example/echo/Echo.java @@ -28,36 +28,43 @@ import com.google.api.server.spi.config.Nullable; import com.google.api.server.spi.response.UnauthorizedException; -/** The Echo API which Endpoints will be exposing. */ +/** + * The Echo API which Endpoints will be exposing. + */ // [START echo_api_annotation] @Api( name = "echo", version = "v1", namespace = - @ApiNamespace( + @ApiNamespace( ownerDomain = "echo.example.com", ownerName = "echo.example.com", packagePath = "" - ), + ), // [START_EXCLUDE] issuers = { - @ApiIssuer( - name = "firebase", - issuer = "https://securetoken.google.com/YOUR-PROJECT-ID", - jwksUri = "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com") + @ApiIssuer( + name = "firebase", + issuer = "https://securetoken.google.com/YOUR-PROJECT-ID", + jwksUri = + "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system" + + ".gserviceaccount.com" + ) } - // [END_EXCLUDE] - ) +// [END_EXCLUDE] +) // [END echo_api_annotation] + public class Echo { + /** * Echoes the received message back. If n is a non-negative integer, the message is copied that * many times in the returned message. * - * Note that name is specified and will override the default name of "{class name}.{method + *

Note that name is specified and will override the default name of "{class name}.{method * name}". For example, the default is "echo.echo". * - * Note that httpMethod is not specified. This will default to a reasonable HTTP method + *

Note that httpMethod is not specified. This will default to a reasonable HTTP method * depending on the API method name. In this case, the HTTP method will default to POST. */ // [START echo_method] @@ -71,10 +78,10 @@ public Message echo(Message message, @Named("n") @Nullable Integer n) { * Echoes the received message back. If n is a non-negative integer, the message is copied that * many times in the returned message. * - * Note that name is specified and will override the default name of "{class name}.{method + *

Note that name is specified and will override the default name of "{class name}.{method * name}". For example, the default is "echo.echo". * - * Note that httpMethod is not specified. This will default to a reasonable HTTP method + *

Note that httpMethod is not specified. This will default to a reasonable HTTP method * depending on the API method name. In this case, the HTTP method will default to POST. */ // [START echo_path] @@ -88,10 +95,10 @@ public Message echoPathParameter(Message message, @Named("n") int n) { * Echoes the received message back. If n is a non-negative integer, the message is copied that * many times in the returned message. * - * Note that name is specified and will override the default name of "{class name}.{method + *

Note that name is specified and will override the default name of "{class name}.{method * name}". For example, the default is "echo.echo". * - * Note that httpMethod is not specified. This will default to a reasonable HTTP method + *

Note that httpMethod is not specified. This will default to a reasonable HTTP method * depending on the API method name. In this case, the HTTP method will default to POST. */ // [START echo_api_key] @@ -119,10 +126,10 @@ private Message doEcho(Message message, Integer n) { * Gets the authenticated user's email. If the user is not authenticated, this will return an HTTP * 401. * - * Note that name is not specified. This will default to "{class name}.{method name}". For + *

Note that name is not specified. This will default to "{class name}.{method name}". For * example, the default is "echo.getUserEmail". * - * Note that httpMethod is not required here. Without httpMethod, this will default to GET due + *

Note that httpMethod is not required here. Without httpMethod, this will default to GET due * to the API method name. httpMethod is added here for example purposes. */ // [START google_id_token_auth] @@ -131,7 +138,7 @@ private Message doEcho(Message message, Integer n) { authenticators = {EspAuthenticator.class}, audiences = {"YOUR_OAUTH_CLIENT_ID"}, clientIds = {"YOUR_OAUTH_CLIENT_ID"} - ) + ) public Email getUserEmail(User user) throws UnauthorizedException { if (user == null) { throw new UnauthorizedException("Invalid credentials"); @@ -147,10 +154,10 @@ public Email getUserEmail(User user) throws UnauthorizedException { * Gets the authenticated user's email. If the user is not authenticated, this will return an HTTP * 401. * - * Note that name is not specified. This will default to "{class name}.{method name}". For + *

Note that name is not specified. This will default to "{class name}.{method name}". For * example, the default is "echo.getUserEmail". * - * Note that httpMethod is not required here. Without httpMethod, this will default to GET due + *

Note that httpMethod is not required here. Without httpMethod, this will default to GET due * to the API method name. httpMethod is added here for example purposes. */ // [START firebase_auth] @@ -158,8 +165,13 @@ public Email getUserEmail(User user) throws UnauthorizedException { path = "firebase_user", httpMethod = ApiMethod.HttpMethod.GET, authenticators = {EspAuthenticator.class}, - issuerAudiences = {@ApiIssuerAudience(name = "firebase", audiences = {"YOUR-PROJECT-ID"})} - ) + issuerAudiences = { + @ApiIssuerAudience( + name = "firebase", + audiences = {"YOUR-PROJECT-ID"} + ) + } + ) public Email getUserEmailFirebase(User user) throws UnauthorizedException { if (user == null) { throw new UnauthorizedException("Invalid credentials"); diff --git a/appengine-java8/endpoints-v2-backend/src/main/java/com/example/echo/Email.java b/appengine-java8/endpoints-v2-backend/src/main/java/com/example/echo/Email.java index e7725a9d9cc..b7b0fbc999e 100644 --- a/appengine-java8/endpoints-v2-backend/src/main/java/com/example/echo/Email.java +++ b/appengine-java8/endpoints-v2-backend/src/main/java/com/example/echo/Email.java @@ -16,8 +16,11 @@ package com.example.echo; -/** The email bean that will be used in the getUserEmail response. */ +/** + * The email bean that will be used in the getUserEmail response. + */ public class Email { + private String email; public String getEmail() { diff --git a/appengine-java8/endpoints-v2-backend/src/main/java/com/example/echo/Message.java b/appengine-java8/endpoints-v2-backend/src/main/java/com/example/echo/Message.java index 64c043c8857..cda377f0add 100644 --- a/appengine-java8/endpoints-v2-backend/src/main/java/com/example/echo/Message.java +++ b/appengine-java8/endpoints-v2-backend/src/main/java/com/example/echo/Message.java @@ -16,7 +16,9 @@ package com.example.echo; -/** The message bean that will be used in the echo request and response. */ +/** + * The message bean that will be used in the echo request and response. + */ public class Message { private String message; diff --git a/appengine-java8/firebase-event-proxy/src/main/java/com/example/GaeFirebaseEventProxy/FirebaseEventProxy.java b/appengine-java8/firebase-event-proxy/src/main/java/com/example/GaeFirebaseEventProxy/FirebaseEventProxy.java index 4a115b74c5d..5934f9f6de3 100644 --- a/appengine-java8/firebase-event-proxy/src/main/java/com/example/GaeFirebaseEventProxy/FirebaseEventProxy.java +++ b/appengine-java8/firebase-event-proxy/src/main/java/com/example/GaeFirebaseEventProxy/FirebaseEventProxy.java @@ -26,7 +26,6 @@ import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; - import java.io.FileInputStream; import java.io.IOException; import java.net.HttpURLConnection; @@ -40,6 +39,9 @@ public class FirebaseEventProxy { private static final Logger log = Logger.getLogger(FirebaseEventProxy.class.getName()); + /** + * FirebaseEventProxy. + */ public FirebaseEventProxy() { String firebaseLocation = "https://crackling-torch-392.firebaseio.com"; Map databaseAuthVariableOverride = new HashMap(); @@ -47,68 +49,76 @@ public FirebaseEventProxy() { databaseAuthVariableOverride.put("uid", "gae-firebase-event-proxy"); databaseAuthVariableOverride.put("provider", "com.example"); try { - FirebaseOptions options = new FirebaseOptions.Builder() - .setServiceAccount(new FileInputStream("gae-firebase-secrets.json")) - .setDatabaseUrl(firebaseLocation) - .setDatabaseAuthVariableOverride(databaseAuthVariableOverride).build(); + FirebaseOptions options = + new FirebaseOptions.Builder() + .setServiceAccount(new FileInputStream("gae-firebase-secrets.json")) + .setDatabaseUrl(firebaseLocation) + .setDatabaseAuthVariableOverride(databaseAuthVariableOverride) + .build(); FirebaseApp.initializeApp(options); } catch (IOException e) { throw new RuntimeException( "Error reading firebase secrets from file: src/main/webapp/gae-firebase-secrets.json: " - + e.getMessage()); + + e.getMessage()); } } + /** + * start the proxy. + */ + @SuppressWarnings(VariableDeclarationUsageDistance) public void start() { DatabaseReference firebase = FirebaseDatabase.getInstance().getReference(); // Subscribe to value events. Depending on use case, you may want to subscribe to child events // through childEventListener. - firebase.addValueEventListener(new ValueEventListener() { - @Override - public void onDataChange(DataSnapshot snapshot) { - if (snapshot.exists()) { - try { - // Convert value to JSON using Jackson - String json = new ObjectMapper().writeValueAsString(snapshot.getValue(false)); + firebase.addValueEventListener( + new ValueEventListener() { + @Override + public void onDataChange(DataSnapshot snapshot) { + if (snapshot.exists()) { + try { + // Convert value to JSON using Jackson + String json = new ObjectMapper().writeValueAsString(snapshot.getValue(false)); - // Replace the URL with the url of your own listener app. - URL dest = new URL("http://gae-firebase-listener-python.appspot.com/log"); - HttpURLConnection connection = (HttpURLConnection) dest.openConnection(); - connection.setRequestMethod("POST"); - connection.setDoOutput(true); + // Replace the URL with the url of your own listener app. + URL dest = new URL("http://gae-firebase-listener-python.appspot.com/log"); + HttpURLConnection connection = (HttpURLConnection) dest.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); - // Rely on X-Appengine-Inbound-Appid to authenticate. Turning off redirects is - // required to enable. - connection.setInstanceFollowRedirects(false); + // Rely on X-Appengine-Inbound-Appid to authenticate. Turning off redirects is + // required to enable. + connection.setInstanceFollowRedirects(false); - // Fill out header if in dev environment - if (SystemProperty.environment.value() != SystemProperty.Environment.Value.Production) { - connection.setRequestProperty("X-Appengine-Inbound-Appid", "dev-instance"); - } + // Fill out header if in dev environment + if (SystemProperty.environment.value() + != SystemProperty.Environment.Value.Production) { + connection.setRequestProperty("X-Appengine-Inbound-Appid", "dev-instance"); + } - // Put Firebase data into http request - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("&fbSnapshot="); - stringBuilder.append(URLEncoder.encode(json, "UTF-8")); - connection.getOutputStream().write(stringBuilder.toString().getBytes()); - if (connection.getResponseCode() != 200) { - log.severe("Forwarding failed"); - } else { - log.info("Sent: " + json); + // Put Firebase data into http request + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("&fbSnapshot="); + stringBuilder.append(URLEncoder.encode(json, "UTF-8")); + connection.getOutputStream().write(stringBuilder.toString().getBytes()); + if (connection.getResponseCode() != 200) { + log.severe("Forwarding failed"); + } else { + log.info("Sent: " + json); + } + } catch (JsonProcessingException e) { + log.severe("Unable to convert Firebase response to JSON: " + e.getMessage()); + } catch (IOException e) { + log.severe("Error in connecting to app engine: " + e.getMessage()); + } } - } catch (JsonProcessingException e) { - log.severe("Unable to convert Firebase response to JSON: " + e.getMessage()); - } catch (IOException e) { - log.severe("Error in connecting to app engine: " + e.getMessage()); } - } - } - @Override - public void onCancelled(DatabaseError error) { - log.severe("Firebase connection cancelled: " + error.getMessage()); - } - }); + @Override + public void onCancelled(DatabaseError error) { + log.severe("Firebase connection cancelled: " + error.getMessage()); + } + }); } } diff --git a/appengine-java8/firebase-event-proxy/src/main/java/com/example/GaeFirebaseEventProxy/ServletContextListenerImpl.java b/appengine-java8/firebase-event-proxy/src/main/java/com/example/GaeFirebaseEventProxy/ServletContextListenerImpl.java index ca11ec2ba9a..6ace6c05687 100644 --- a/appengine-java8/firebase-event-proxy/src/main/java/com/example/GaeFirebaseEventProxy/ServletContextListenerImpl.java +++ b/appengine-java8/firebase-event-proxy/src/main/java/com/example/GaeFirebaseEventProxy/ServletContextListenerImpl.java @@ -17,7 +17,6 @@ package com.example.gaefirebaseeventproxy; import java.util.logging.Logger; - import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; @@ -29,7 +28,8 @@ public class ServletContextListenerImpl implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent event) { log.info("Starting ...."); - FirebaseEventProxy proxy = new FirebaseEventProxy(); + com.example.gaefirebaseeventproxy.FirebaseEventProxy proxy = new com.example + .gaefirebaseeventproxy.FirebaseEventProxy(); proxy.start(); } diff --git a/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/DeleteServlet.java b/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/DeleteServlet.java index 1988424fbb6..f368a528bd9 100644 --- a/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/DeleteServlet.java +++ b/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/DeleteServlet.java @@ -20,7 +20,6 @@ import com.google.appengine.api.users.UserServiceFactory; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyService; - import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -32,8 +31,7 @@ */ public class DeleteServlet extends HttpServlet { @Override - public void doPost(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String gameId = request.getParameter("gameKey"); Objectify ofy = ObjectifyService.ofy(); Game game = ofy.load().type(Game.class).id(gameId).safe(); diff --git a/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/FirebaseChannel.java b/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/FirebaseChannel.java index 5c859d65dbe..76a992319af 100644 --- a/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/FirebaseChannel.java +++ b/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/FirebaseChannel.java @@ -29,7 +29,6 @@ import com.google.common.io.BaseEncoding; import com.google.common.io.CharStreams; import com.google.gson.Gson; - import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; @@ -41,18 +40,18 @@ import java.util.Map; /** - * Utility functions for communicating with the realtime communication channel using Firebase. - * In this app, we use Firebase as a communication bus to push the state of the board to all clients - * - that is, players of the game. This class contains the methods used to communicate with - * Firebase. + * Utility functions for communicating with the realtime communication channel using Firebase. In + * this app, we use Firebase as a communication bus to push the state of the board to all clients - + * that is, players of the game. This class contains the methods used to communicate with Firebase. */ public class FirebaseChannel { + private static final String FIREBASE_SNIPPET_PATH = "WEB-INF/view/firebase_config.jspf"; static InputStream firebaseConfigStream = null; - private static final Collection FIREBASE_SCOPES = Arrays.asList( - "https://www.googleapis.com/auth/firebase.database", - "https://www.googleapis.com/auth/userinfo.email" - ); + private static final Collection FIREBASE_SCOPES = + Arrays.asList( + "https://www.googleapis.com/auth/firebase.database", + "https://www.googleapis.com/auth/userinfo.email"); private static final String IDENTITY_ENDPOINT = "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit"; @@ -64,8 +63,8 @@ public class FirebaseChannel { private static FirebaseChannel instance; /** - * FirebaseChannel is a singleton, since it's just utility functions. - * The class derives auth information when first instantiated. + * FirebaseChannel is a singleton, since it's just utility functions. The class derives auth + * information when first instantiated. */ public static FirebaseChannel getInstance() { if (instance == null) { @@ -88,8 +87,8 @@ private FirebaseChannel() { firebaseConfigStream = new FileInputStream(FIREBASE_SNIPPET_PATH); } - String firebaseSnippet = CharStreams.toString(new InputStreamReader( - firebaseConfigStream, StandardCharsets.UTF_8)); + String firebaseSnippet = + CharStreams.toString(new InputStreamReader(firebaseConfigStream, StandardCharsets.UTF_8)); firebaseDbUrl = parseFirebaseUrl(firebaseSnippet); credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES); @@ -100,9 +99,9 @@ private FirebaseChannel() { } /** - * Parses out the Firebase database url from the client-side code snippet. - * The code snippet is a piece of javascript that defines an object with the key 'databaseURL'. So - * look for that key, then parse out its quote-surrounded value. + * Parses out the Firebase database url from the client-side code snippet. The code snippet is a + * piece of javascript that defines an object with the key 'databaseURL'. So look for that key, + * then parse out its quote-surrounded value. */ private static String parseFirebaseUrl(String firebaseSnippet) { int idx = firebaseSnippet.indexOf("databaseURL"); @@ -116,12 +115,17 @@ private static String parseFirebaseUrl(String firebaseSnippet) { return firebaseSnippet.substring(openQuote + 1, closeQuote); } - public void sendFirebaseMessage(String channelKey, Game game) - throws IOException { + /** + * sendFirebaseMessage. + * @param channelKey . + * @param game . + * @throws IOException . + */ + public void sendFirebaseMessage(String channelKey, Game game) throws IOException { // Make requests auth'ed using Application Default Credentials HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential); - GenericUrl url = new GenericUrl( - String.format("%s/channels/%s.json", firebaseDbUrl, channelKey)); + GenericUrl url = + new GenericUrl(String.format("%s/channels/%s.json", firebaseDbUrl, channelKey)); HttpResponse response = null; try { @@ -129,8 +133,11 @@ public void sendFirebaseMessage(String channelKey, Game game) response = requestFactory.buildDeleteRequest(url).execute(); } else { String gameJson = new Gson().toJson(game); - response = requestFactory.buildPatchRequest( - url, new ByteArrayContent("application/json", gameJson.getBytes())).execute(); + response = + requestFactory + .buildPatchRequest( + url, new ByteArrayContent("application/json", gameJson.getBytes())) + .execute(); } if (response.getStatusCode() != 200) { @@ -177,6 +184,13 @@ public String createFirebaseToken(Game game, String userId) { // The following methods are to illustrate making various calls to Firebase from App Engine // Standard + /** + * firebasePut. + * @param path . + * @param object . + * @return . + * @throws IOException . + */ public HttpResponse firebasePut(String path, Object object) throws IOException { // Make requests auth'ed using Application Default Credentials Credential credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES); @@ -185,10 +199,18 @@ public HttpResponse firebasePut(String path, Object object) throws IOException { String json = new Gson().toJson(object); GenericUrl url = new GenericUrl(path); - return requestFactory.buildPutRequest( - url, new ByteArrayContent("application/json", json.getBytes())).execute(); + return requestFactory + .buildPutRequest(url, new ByteArrayContent("application/json", json.getBytes())) + .execute(); } + /** + * firebasePatch. + * @param path . + * @param object . + * @return . + * @throws IOException . + */ public HttpResponse firebasePatch(String path, Object object) throws IOException { // Make requests auth'ed using Application Default Credentials Credential credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES); @@ -197,10 +219,18 @@ public HttpResponse firebasePatch(String path, Object object) throws IOException String json = new Gson().toJson(object); GenericUrl url = new GenericUrl(path); - return requestFactory.buildPatchRequest( - url, new ByteArrayContent("application/json", json.getBytes())).execute(); + return requestFactory + .buildPatchRequest(url, new ByteArrayContent("application/json", json.getBytes())) + .execute(); } + /** + * firebasePost. + * @param path . + * @param object . + * @return . + * @throws IOException . + */ public HttpResponse firebasePost(String path, Object object) throws IOException { // Make requests auth'ed using Application Default Credentials Credential credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES); @@ -209,10 +239,17 @@ public HttpResponse firebasePost(String path, Object object) throws IOException String json = new Gson().toJson(object); GenericUrl url = new GenericUrl(path); - return requestFactory.buildPostRequest( - url, new ByteArrayContent("application/json", json.getBytes())).execute(); + return requestFactory + .buildPostRequest(url, new ByteArrayContent("application/json", json.getBytes())) + .execute(); } + /** + * firebaseGet. + * @param path . + * @return . + * @throws IOException . + */ public HttpResponse firebaseGet(String path) throws IOException { // Make requests auth'ed using Application Default Credentials Credential credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES); @@ -223,6 +260,12 @@ public HttpResponse firebaseGet(String path) throws IOException { return requestFactory.buildGetRequest(url).execute(); } + /** + * firebaseDelete. + * @param path . + * @return . + * @throws IOException . + */ public HttpResponse firebaseDelete(String path) throws IOException { // Make requests auth'ed using Application Default Credentials Credential credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES); diff --git a/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/Game.java b/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/Game.java index 7f6a1e84135..b142ba6629b 100644 --- a/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/Game.java +++ b/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/Game.java @@ -18,7 +18,6 @@ import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; - import java.io.IOException; import java.util.UUID; import java.util.logging.Level; @@ -29,21 +28,32 @@ * The datastore-persisted Game object. This holds the entire game state - from a representation of * the board, to the players are and whose turn it is, and who the winner is and how they won. * - * It also contains some convenience functions for communicating updates to the board to the + *

It also contains some convenience functions for communicating updates to the board to the * clients, via Firebase. */ @Entity public class Game { - static final Pattern[] XWins = - {Pattern.compile("XXX......"), Pattern.compile("...XXX..."), Pattern.compile("......XXX"), - Pattern.compile("X..X..X.."), Pattern.compile(".X..X..X."), - Pattern.compile("..X..X..X"), Pattern.compile("X...X...X"), - Pattern.compile("..X.X.X..")}; - static final Pattern[] OWins = - {Pattern.compile("OOO......"), Pattern.compile("...OOO..."), Pattern.compile("......OOO"), - Pattern.compile("O..O..O.."), Pattern.compile(".O..O..O."), - Pattern.compile("..O..O..O"), Pattern.compile("O...O...O"), - Pattern.compile("..O.O.O..")}; + + static final Pattern[] XWins = { + Pattern.compile("XXX......"), + Pattern.compile("...XXX..."), + Pattern.compile("......XXX"), + Pattern.compile("X..X..X.."), + Pattern.compile(".X..X..X."), + Pattern.compile("..X..X..X"), + Pattern.compile("X...X...X"), + Pattern.compile("..X.X.X..") + }; + static final Pattern[] OWins = { + Pattern.compile("OOO......"), + Pattern.compile("...OOO..."), + Pattern.compile("......OOO"), + Pattern.compile("O..O..O.."), + Pattern.compile(".O..O..O."), + Pattern.compile("..O..O..O"), + Pattern.compile("O...O...O"), + Pattern.compile("..O.O.O..") + }; @Id public String id; @@ -109,29 +119,38 @@ public String getChannelKey(String userId) { return userId + id; } - public void deleteChannel(String userId) - throws IOException { + /** + * deleteChannel. + * @param userId . + * @throws IOException . + */ + public void deleteChannel(String userId) throws IOException { if (userId != null) { String channelKey = getChannelKey(userId); FirebaseChannel.getInstance().sendFirebaseMessage(channelKey, null); } } - private void sendUpdateToUser(String userId) - throws IOException { + private void sendUpdateToUser(String userId) throws IOException { if (userId != null) { String channelKey = getChannelKey(userId); FirebaseChannel.getInstance().sendFirebaseMessage(channelKey, this); } } - public void sendUpdateToClients() - throws IOException { + /** + * sendUpdateToClients. + * @throws IOException if we had some kind of network issue. + */ + public void sendUpdateToClients() throws IOException { sendUpdateToUser(userX); sendUpdateToUser(userO); } // [END send_updates] + /** + * checkWin - has anyone won. + */ public void checkWin() { final Pattern[] wins; if (moveX) { @@ -152,6 +171,12 @@ public void checkWin() { } } + /** + * makeMove for user. + * @param position . + * @param userId . + * @return true if successful. + */ public boolean makeMove(int position, String userId) { String currentMovePlayer; char value; diff --git a/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/MoveServlet.java b/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/MoveServlet.java index 4911d22bc37..fb92141556b 100644 --- a/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/MoveServlet.java +++ b/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/MoveServlet.java @@ -20,21 +20,19 @@ import com.google.appengine.api.users.UserServiceFactory; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyService; - import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** - * Handler for a user making a move in a game. - * Updates the game board with the requested move (if it's legal), and communicate the updated board - * to the clients. + * Handler for a user making a move in a game. Updates the game board with the requested move (if + * it's legal), and communicate the updated board to the clients. */ public class MoveServlet extends HttpServlet { + @Override - public void doPost(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String gameId = request.getParameter("gameKey"); Objectify ofy = ObjectifyService.ofy(); Game game = ofy.load().type(Game.class).id(gameId).safe(); diff --git a/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/ObjectifyHelper.java b/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/ObjectifyHelper.java index abc1a28e33c..a6501944dc5 100644 --- a/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/ObjectifyHelper.java +++ b/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/ObjectifyHelper.java @@ -13,21 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.appengine.firetactoe; import com.googlecode.objectify.ObjectifyService; - import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** - * ObjectifyHelper, a ServletContextListener, is setup in web.xml to run before a JSP is run. This + * ObjectifyHelper, a ServletContextListener, is setup in web.xml to run before a JSP is run. This * is required to let JSP's access Ofy. - **/ + */ public class ObjectifyHelper implements ServletContextListener { + + /** + * This will be invoked as part of a warmup request, or the first user request if no warmup + * request. + * @param event ServletContextEvent. + */ public void contextInitialized(ServletContextEvent event) { - // This will be invoked as part of a warmup request, or the first user request if no warmup - // request. + // ObjectifyService.register(Game.class); } diff --git a/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/OpenedServlet.java b/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/OpenedServlet.java index 2e71f9391cb..e05b84ba776 100644 --- a/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/OpenedServlet.java +++ b/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/OpenedServlet.java @@ -18,19 +18,15 @@ import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyService; - import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -/** - * Handler that signals to all players of a game that the game has started. - */ +/** Handler that signals to all players of a game that the game has started. */ public class OpenedServlet extends HttpServlet { @Override - public void doPost(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { // TODO(you): In practice, you should validate the user has permission to post to the given Game String gameId = request.getParameter("gameKey"); Objectify ofy = ObjectifyService.ofy(); diff --git a/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/TicTacToeServlet.java b/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/TicTacToeServlet.java index 8b248577971..2b0fda3ffcf 100644 --- a/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/TicTacToeServlet.java +++ b/appengine-java8/firebase-tictactoe/src/main/java/com/example/appengine/firetactoe/TicTacToeServlet.java @@ -20,7 +20,6 @@ import com.google.gson.Gson; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyService; - import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; @@ -30,10 +29,9 @@ import javax.servlet.http.HttpServletResponse; /** - * Base handler for the Tic Tac Toe game. - * This handler serves up the initial jsp page that is the game, and also creates the persistent - * game in the datastore, as well as the Firebase database to serve as the communication channel to - * the clients. + * Base handler for the Tic Tac Toe game. This handler serves up the initial jsp page that is the + * game, and also creates the persistent game in the datastore, as well as the Firebase database to + * serve as the communication channel to the clients. */ @SuppressWarnings("serial") public class TicTacToeServlet extends HttpServlet { @@ -45,9 +43,15 @@ private String getGameUriWithGameParam(HttpServletRequest request, String gameKe query = "gameKey=" + gameKey; } URI thisUri = new URI(request.getRequestURL().toString()); - URI uriWithOptionalGameParam = new URI( - thisUri.getScheme(), thisUri.getUserInfo(), thisUri.getHost(), - thisUri.getPort(), thisUri.getPath(), query, ""); + URI uriWithOptionalGameParam = + new URI( + thisUri.getScheme(), + thisUri.getUserInfo(), + thisUri.getHost(), + thisUri.getPort(), + thisUri.getPath(), + query, + ""); return uriWithOptionalGameParam.toString(); } catch (URISyntaxException e) { // This should never happen, since we're constructing the URI from a valid URI. diff --git a/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/DeleteServletTest.java b/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/DeleteServletTest.java index 0df68aaaefc..bfd03a23a37 100644 --- a/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/DeleteServletTest.java +++ b/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/DeleteServletTest.java @@ -38,6 +38,11 @@ import com.googlecode.objectify.ObjectifyFactory; import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.util.Closeable; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.HashMap; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; @@ -48,15 +53,7 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.HashMap; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Unit tests for {@link DeleteServlet}. - */ +/** Unit tests for {@link DeleteServlet}. */ @RunWith(JUnit4.class) public class DeleteServletTest { private static final String USER_EMAIL = "whisky@tangofoxtr.ot"; @@ -65,16 +62,18 @@ public class DeleteServletTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( - // Set no eventual consistency, that way queries return all results. - // http://g.co/cloud/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests - new LocalDatastoreServiceTestConfig().setDefaultHighRepJobPolicyUnappliedJobPercentage(0), - new LocalUserServiceTestConfig(), - new LocalURLFetchServiceTestConfig() - ) - .setEnvEmail(USER_EMAIL) - .setEnvAuthDomain("gmail.com") - .setEnvAttributes(new HashMap( - ImmutableMap.of("com.google.appengine.api.users.UserService.user_id_key", USER_ID))); + // Set no eventual consistency, that way queries return all results. + // http://g.co/cloud/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + new LocalDatastoreServiceTestConfig() + .setDefaultHighRepJobPolicyUnappliedJobPercentage(0), + new LocalUserServiceTestConfig(), + new LocalURLFetchServiceTestConfig()) + .setEnvEmail(USER_EMAIL) + .setEnvAuthDomain("gmail.com") + .setEnvAttributes( + new HashMap( + ImmutableMap.of( + "com.google.appengine.api.users.UserService.user_id_key", USER_ID))); @Mock private HttpServletRequest mockRequest; @Mock private HttpServletResponse mockResponse; @@ -88,8 +87,8 @@ public static void setUpBeforeClass() { ObjectifyService.setFactory(new ObjectifyFactory()); ObjectifyService.register(Game.class); // Mock out the firebase config - FirebaseChannel.firebaseConfigStream = new ByteArrayInputStream( - String.format("databaseURL: \"%s\"", FIREBASE_DB_URL).getBytes()); + FirebaseChannel.firebaseConfigStream = + new ByteArrayInputStream(String.format("databaseURL: \"%s\"", FIREBASE_DB_URL).getBytes()); } @Before @@ -132,24 +131,27 @@ public void doPost_deleteGame() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing - MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { - @Override - public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { - return new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); - response.setStatusCode(200); - return response; - } - }; - } - }); + MockHttpTransport mockHttpTransport = + spy( + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) + throws IOException { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); + response.setStatusCode(200); + return response; + } + }; + } + }); FirebaseChannel.getInstance().httpTransport = mockHttpTransport; servletUnderTest.doPost(mockRequest, mockResponse); - verify(mockHttpTransport, times(1)).buildRequest( - eq("DELETE"), Matchers.matches(FIREBASE_DB_URL + "/channels/[\\w-]+.json$")); + verify(mockHttpTransport, times(1)) + .buildRequest(eq("DELETE"), Matchers.matches(FIREBASE_DB_URL + "/channels/[\\w-]+.json$")); } } diff --git a/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/FirebaseChannelTest.java b/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/FirebaseChannelTest.java index 0c92863f77e..fc424b31981 100644 --- a/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/FirebaseChannelTest.java +++ b/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/FirebaseChannelTest.java @@ -28,6 +28,8 @@ import com.google.api.client.testing.http.MockLowLevelHttpResponse; import com.google.appengine.tools.development.testing.LocalAppIdentityServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.ByteArrayInputStream; +import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; @@ -36,12 +38,7 @@ import org.junit.runners.JUnit4; import org.mockito.MockitoAnnotations; -import java.io.ByteArrayInputStream; -import java.io.IOException; - -/** - * Unit tests for {@link FirebaseChannel}. - */ +/** Unit tests for {@link FirebaseChannel}. */ @RunWith(JUnit4.class) public class FirebaseChannelTest { private static final String FIREBASE_DB_URL = "http://firebase.com/dburl"; @@ -53,8 +50,8 @@ public class FirebaseChannelTest { @BeforeClass public static void setUpBeforeClass() { // Mock out the firebase config - FirebaseChannel.firebaseConfigStream = new ByteArrayInputStream( - String.format("databaseURL: \"%s\"", FIREBASE_DB_URL).getBytes()); + FirebaseChannel.firebaseConfigStream = + new ByteArrayInputStream(String.format("databaseURL: \"%s\"", FIREBASE_DB_URL).getBytes()); firebaseChannel = FirebaseChannel.getInstance(); } @@ -74,50 +71,56 @@ public void tearDown() { public void sendFirebaseMessage_create() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing - MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { - @Override - public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { - return new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); - response.setStatusCode(200); - return response; - } - }; - } - }); + MockHttpTransport mockHttpTransport = + spy( + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) + throws IOException { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); + response.setStatusCode(200); + return response; + } + }; + } + }); FirebaseChannel.getInstance().httpTransport = mockHttpTransport; firebaseChannel.sendFirebaseMessage("my_key", new Game()); - verify(mockHttpTransport, times(1)).buildRequest( - "PATCH", FIREBASE_DB_URL + "/channels/my_key.json"); + verify(mockHttpTransport, times(1)) + .buildRequest("PATCH", FIREBASE_DB_URL + "/channels/my_key.json"); } @Test public void sendFirebaseMessage_delete() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing - MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { - @Override - public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { - return new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); - response.setStatusCode(200); - return response; - } - }; - } - }); + MockHttpTransport mockHttpTransport = + spy( + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) + throws IOException { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); + response.setStatusCode(200); + return response; + } + }; + } + }); FirebaseChannel.getInstance().httpTransport = mockHttpTransport; firebaseChannel.sendFirebaseMessage("my_key", null); - verify(mockHttpTransport, times(1)).buildRequest( - "DELETE", FIREBASE_DB_URL + "/channels/my_key.json"); + verify(mockHttpTransport, times(1)) + .buildRequest("DELETE", FIREBASE_DB_URL + "/channels/my_key.json"); } @Test @@ -133,19 +136,22 @@ public void createFirebaseToken() throws Exception { public void firebasePut() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing - MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { - @Override - public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { - return new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); - response.setStatusCode(200); - return response; - } - }; - } - }); + MockHttpTransport mockHttpTransport = + spy( + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) + throws IOException { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); + response.setStatusCode(200); + return response; + } + }; + } + }); FirebaseChannel.getInstance().httpTransport = mockHttpTransport; Game game = new Game(); @@ -158,19 +164,22 @@ public LowLevelHttpResponse execute() throws IOException { public void firebasePatch() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing - MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { - @Override - public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { - return new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); - response.setStatusCode(200); - return response; - } - }; - } - }); + MockHttpTransport mockHttpTransport = + spy( + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) + throws IOException { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); + response.setStatusCode(200); + return response; + } + }; + } + }); FirebaseChannel.getInstance().httpTransport = mockHttpTransport; Game game = new Game(); @@ -183,19 +192,22 @@ public LowLevelHttpResponse execute() throws IOException { public void firebasePost() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing - MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { - @Override - public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { - return new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); - response.setStatusCode(200); - return response; - } - }; - } - }); + MockHttpTransport mockHttpTransport = + spy( + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) + throws IOException { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); + response.setStatusCode(200); + return response; + } + }; + } + }); FirebaseChannel.getInstance().httpTransport = mockHttpTransport; Game game = new Game(); @@ -208,19 +220,22 @@ public LowLevelHttpResponse execute() throws IOException { public void firebaseGet() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing - MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { - @Override - public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { - return new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); - response.setStatusCode(200); - return response; - } - }; - } - }); + MockHttpTransport mockHttpTransport = + spy( + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) + throws IOException { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); + response.setStatusCode(200); + return response; + } + }; + } + }); FirebaseChannel.getInstance().httpTransport = mockHttpTransport; firebaseChannel.firebaseGet(FIREBASE_DB_URL + "/my/path"); @@ -232,19 +247,22 @@ public LowLevelHttpResponse execute() throws IOException { public void firebaseDelete() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing - MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { - @Override - public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { - return new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); - response.setStatusCode(200); - return response; - } - }; - } - }); + MockHttpTransport mockHttpTransport = + spy( + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) + throws IOException { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); + response.setStatusCode(200); + return response; + } + }; + } + }); FirebaseChannel.getInstance().httpTransport = mockHttpTransport; firebaseChannel.firebaseDelete(FIREBASE_DB_URL + "/my/path"); diff --git a/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/MoveServletTest.java b/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/MoveServletTest.java index fd1f3c13862..714df81207e 100644 --- a/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/MoveServletTest.java +++ b/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/MoveServletTest.java @@ -37,6 +37,11 @@ import com.googlecode.objectify.ObjectifyFactory; import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.util.Closeable; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.HashMap; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; @@ -48,15 +53,7 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.HashMap; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Unit tests for {@link MoveServlet}. - */ +/** Unit tests for {@link MoveServlet}. */ @RunWith(JUnit4.class) public class MoveServletTest { private static final String USER_EMAIL = "whisky@tangofoxtr.ot"; @@ -65,16 +62,18 @@ public class MoveServletTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( - // Set no eventual consistency, that way queries return all results. - // http://g.co/cloud/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests - new LocalDatastoreServiceTestConfig().setDefaultHighRepJobPolicyUnappliedJobPercentage(0), - new LocalUserServiceTestConfig(), - new LocalURLFetchServiceTestConfig() - ) - .setEnvEmail(USER_EMAIL) - .setEnvAuthDomain("gmail.com") - .setEnvAttributes(new HashMap( - ImmutableMap.of("com.google.appengine.api.users.UserService.user_id_key", USER_ID))); + // Set no eventual consistency, that way queries return all results. + // http://g.co/cloud/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + new LocalDatastoreServiceTestConfig() + .setDefaultHighRepJobPolicyUnappliedJobPercentage(0), + new LocalUserServiceTestConfig(), + new LocalURLFetchServiceTestConfig()) + .setEnvEmail(USER_EMAIL) + .setEnvAuthDomain("gmail.com") + .setEnvAttributes( + new HashMap( + ImmutableMap.of( + "com.google.appengine.api.users.UserService.user_id_key", USER_ID))); @Mock private HttpServletRequest mockRequest; @Mock private HttpServletResponse mockResponse; @@ -88,8 +87,8 @@ public static void setUpBeforeClass() { ObjectifyService.setFactory(new ObjectifyFactory()); ObjectifyService.register(Game.class); // Mock out the firebase config - FirebaseChannel.firebaseConfigStream = new ByteArrayInputStream( - String.format("databaseURL: \"%s\"", FIREBASE_DB_URL).getBytes()); + FirebaseChannel.firebaseConfigStream = + new ByteArrayInputStream(String.format("databaseURL: \"%s\"", FIREBASE_DB_URL).getBytes()); } @Before @@ -124,19 +123,22 @@ public void doPost_myTurn_move() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing - MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { - @Override - public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { - return new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); - response.setStatusCode(200); - return response; - } - }; - } - }); + MockHttpTransport mockHttpTransport = + spy( + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) + throws IOException { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); + response.setStatusCode(200); + return response; + } + }; + } + }); FirebaseChannel.getInstance().httpTransport = mockHttpTransport; servletUnderTest.doPost(mockRequest, mockResponse); @@ -144,8 +146,8 @@ public LowLevelHttpResponse execute() throws IOException { game = ofy.load().type(Game.class).id(gameKey).safe(); assertThat(game.board).isEqualTo(" X "); - verify(mockHttpTransport, times(2)).buildRequest( - eq("PATCH"), Matchers.matches(FIREBASE_DB_URL + "/channels/[\\w-]+.json$")); + verify(mockHttpTransport, times(2)) + .buildRequest(eq("PATCH"), Matchers.matches(FIREBASE_DB_URL + "/channels/[\\w-]+.json$")); } @Ignore // TODO: this wasn't running, and I've turned it off. diff --git a/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/OpenedServletTest.java b/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/OpenedServletTest.java index 9b2990196f6..5b3b12df76e 100644 --- a/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/OpenedServletTest.java +++ b/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/OpenedServletTest.java @@ -36,6 +36,11 @@ import com.googlecode.objectify.ObjectifyFactory; import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.util.Closeable; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.HashMap; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; @@ -46,17 +51,12 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.HashMap; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * Unit tests for {@link OpenedServlet}. */ @RunWith(JUnit4.class) public class OpenedServletTest { + private static final String USER_EMAIL = "whisky@tangofoxtr.ot"; private static final String USER_ID = "whiskytangofoxtrot"; private static final String FIREBASE_DB_URL = "http://firebase.com/dburl"; @@ -64,18 +64,23 @@ public class OpenedServletTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // http://g.co/cloud/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests - new LocalDatastoreServiceTestConfig().setDefaultHighRepJobPolicyUnappliedJobPercentage(0), + // http://g.co/cloud/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests + new LocalDatastoreServiceTestConfig() + .setDefaultHighRepJobPolicyUnappliedJobPercentage(0), new LocalUserServiceTestConfig(), - new LocalURLFetchServiceTestConfig() - ) - .setEnvEmail(USER_EMAIL) - .setEnvAuthDomain("gmail.com") - .setEnvAttributes(new HashMap( - ImmutableMap.of("com.google.appengine.api.users.UserService.user_id_key", USER_ID))); - - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + new LocalURLFetchServiceTestConfig()) + .setEnvEmail(USER_EMAIL) + .setEnvAuthDomain("gmail.com") + .setEnvAttributes( + new HashMap( + ImmutableMap.of( + "com.google.appengine.api.users.UserService.user_id_key", USER_ID))); + + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; protected Closeable dbSession; private OpenedServlet servletUnderTest; @@ -86,8 +91,8 @@ public static void setUpBeforeClass() { ObjectifyService.setFactory(new ObjectifyFactory()); ObjectifyService.register(Game.class); // Mock out the firebase config - FirebaseChannel.firebaseConfigStream = new ByteArrayInputStream( - String.format("databaseURL: \"%s\"", FIREBASE_DB_URL).getBytes()); + FirebaseChannel.firebaseConfigStream = + new ByteArrayInputStream(String.format("databaseURL: \"%s\"", FIREBASE_DB_URL).getBytes()); } @Before @@ -121,24 +126,27 @@ public void doPost_open() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing - MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { - @Override - public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { - return new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); - response.setStatusCode(200); - return response; - } - }; - } - }); + MockHttpTransport mockHttpTransport = + spy( + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) + throws IOException { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); + response.setStatusCode(200); + return response; + } + }; + } + }); FirebaseChannel.getInstance().httpTransport = mockHttpTransport; servletUnderTest.doPost(mockRequest, mockResponse); - verify(mockHttpTransport, times(2)).buildRequest( - eq("PATCH"), Matchers.matches(FIREBASE_DB_URL + "/channels/[\\w-]+.json$")); + verify(mockHttpTransport, times(2)) + .buildRequest(eq("PATCH"), Matchers.matches(FIREBASE_DB_URL + "/channels/[\\w-]+.json$")); } } diff --git a/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/TicTacToeServletTest.java b/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/TicTacToeServletTest.java index 7f5fdf90150..3be84b41f21 100644 --- a/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/TicTacToeServletTest.java +++ b/appengine-java8/firebase-tictactoe/src/test/java/com/example/appengine/firetactoe/TicTacToeServletTest.java @@ -38,6 +38,12 @@ import com.googlecode.objectify.ObjectifyFactory; import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.util.Closeable; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.HashMap; +import javax.servlet.RequestDispatcher; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; @@ -48,17 +54,7 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.lang.StringBuffer; -import java.util.HashMap; -import javax.servlet.RequestDispatcher; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Unit tests for {@link TicTacToeServlet}. - */ +/** Unit tests for {@link TicTacToeServlet}. */ @RunWith(JUnit4.class) public class TicTacToeServletTest { private static final String USER_EMAIL = "whisky@tangofoxtr.ot"; @@ -67,16 +63,18 @@ public class TicTacToeServletTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( - // Set no eventual consistency, that way queries return all results. - // http://g.co/cloud/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests - new LocalDatastoreServiceTestConfig().setDefaultHighRepJobPolicyUnappliedJobPercentage(0), - new LocalUserServiceTestConfig(), - new LocalURLFetchServiceTestConfig() - ) - .setEnvEmail(USER_EMAIL) - .setEnvAuthDomain("gmail.com") - .setEnvAttributes(new HashMap( - ImmutableMap.of("com.google.appengine.api.users.UserService.user_id_key", USER_ID))); + // Set no eventual consistency, that way queries return all results. + // http://g.co/cloud/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + new LocalDatastoreServiceTestConfig() + .setDefaultHighRepJobPolicyUnappliedJobPercentage(0), + new LocalUserServiceTestConfig(), + new LocalURLFetchServiceTestConfig()) + .setEnvEmail(USER_EMAIL) + .setEnvAuthDomain("gmail.com") + .setEnvAttributes( + new HashMap( + ImmutableMap.of( + "com.google.appengine.api.users.UserService.user_id_key", USER_ID))); @Mock private HttpServletRequest mockRequest; @Mock private HttpServletResponse mockResponse; @@ -91,8 +89,8 @@ public static void setUpBeforeClass() { ObjectifyService.setFactory(new ObjectifyFactory()); ObjectifyService.register(Game.class); // Mock out the firebase config - FirebaseChannel.firebaseConfigStream = new ByteArrayInputStream( - String.format("databaseURL: \"%s\"", FIREBASE_DB_URL).getBytes()); + FirebaseChannel.firebaseConfigStream = + new ByteArrayInputStream(String.format("databaseURL: \"%s\"", FIREBASE_DB_URL).getBytes()); } @Before @@ -120,19 +118,22 @@ public void tearDown() { public void doGet_noGameKey() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing - MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { - @Override - public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { - return new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); - response.setStatusCode(200); - return response; - } - }; - } - }); + MockHttpTransport mockHttpTransport = + spy( + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) + throws IOException { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); + response.setStatusCode(200); + return response; + } + }; + } + }); FirebaseChannel.getInstance().httpTransport = mockHttpTransport; servletUnderTest.doGet(mockRequest, mockResponse); @@ -142,8 +143,8 @@ public LowLevelHttpResponse execute() throws IOException { Game game = ofy.load().type(Game.class).first().safe(); assertThat(game.userX).isEqualTo(USER_ID); - verify(mockHttpTransport, times(1)).buildRequest( - eq("PATCH"), Matchers.matches(FIREBASE_DB_URL + "/channels/[\\w-]+.json$")); + verify(mockHttpTransport, times(1)) + .buildRequest(eq("PATCH"), Matchers.matches(FIREBASE_DB_URL + "/channels/[\\w-]+.json$")); verify(requestDispatcher).forward(mockRequest, mockResponse); verify(mockRequest).setAttribute(eq("token"), anyString()); verify(mockRequest).setAttribute("game_key", game.id); @@ -157,19 +158,22 @@ public LowLevelHttpResponse execute() throws IOException { public void doGet_existingGame() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing - MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { - @Override - public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { - return new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); - response.setStatusCode(200); - return response; - } - }; - } - }); + MockHttpTransport mockHttpTransport = + spy( + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) + throws IOException { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); + response.setStatusCode(200); + return response; + } + }; + } + }); FirebaseChannel.getInstance().httpTransport = mockHttpTransport; // Insert a game @@ -187,8 +191,8 @@ public LowLevelHttpResponse execute() throws IOException { assertThat(game.userX).isEqualTo("some-other-user-id"); assertThat(game.userO).isEqualTo(USER_ID); - verify(mockHttpTransport, times(2)).buildRequest( - eq("PATCH"), Matchers.matches(FIREBASE_DB_URL + "/channels/[\\w-]+.json$")); + verify(mockHttpTransport, times(2)) + .buildRequest(eq("PATCH"), Matchers.matches(FIREBASE_DB_URL + "/channels/[\\w-]+.json$")); verify(requestDispatcher).forward(mockRequest, mockResponse); verify(mockRequest).setAttribute(eq("token"), anyString()); verify(mockRequest).setAttribute("game_key", game.id); diff --git a/appengine-java8/gaeinfo/src/main/java/com/example/appengine/standard/GaeInfoServlet.java b/appengine-java8/gaeinfo/src/main/java/com/example/appengine/standard/GaeInfoServlet.java index 1cfdabe74f8..3ef89f7bcac 100644 --- a/appengine-java8/gaeinfo/src/main/java/com/example/appengine/standard/GaeInfoServlet.java +++ b/appengine-java8/gaeinfo/src/main/java/com/example/appengine/standard/GaeInfoServlet.java @@ -1,15 +1,15 @@ /** * Copyright 2017 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 + *

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 + *

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. + *

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.example.appengine.standard; @@ -39,12 +39,14 @@ import org.thymeleaf.context.WebContext; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; - // [START example] @SuppressWarnings({"serial"}) // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. -@WebServlet(name = "GAEInfo", description = "GAEInfo: Write info about GAE Standard", - urlPatterns = "/gaeinfo") +@WebServlet( + name = "GAEInfo", + description = "GAEInfo: Write info about GAE Standard", + urlPatterns = "/gaeinfo" +) public class GaeInfoServlet extends HttpServlet { private final String[] metaPath = { @@ -54,16 +56,16 @@ public class GaeInfoServlet extends HttpServlet { "/computeMetadata/v1/instance/service-accounts/default/aliases", "/computeMetadata/v1/instance/service-accounts/default/", "/computeMetadata/v1/instance/service-accounts/default/scopes", -// Tokens work - but are a security risk to display -// "/computeMetadata/v1/instance/service-accounts/default/token" + // Tokens work - but are a security risk to display + // "/computeMetadata/v1/instance/service-accounts/default/token" }; final String[] metaServiceAcct = { "/computeMetadata/v1/instance/service-accounts/{account}/aliases", "/computeMetadata/v1/instance/service-accounts/{account}/email", "/computeMetadata/v1/instance/service-accounts/{account}/scopes", -// Tokens work - but are a security risk to display -// "/computeMetadata/v1/instance/service-accounts/{account}/token" + // Tokens work - but are a security risk to display + // "/computeMetadata/v1/instance/service-accounts/{account}/token" }; private final String metadata = "http://metadata.google.internal"; @@ -71,35 +73,36 @@ public class GaeInfoServlet extends HttpServlet { private TemplateEngine templateEngine; // Use OkHttp from Square as it's quite easy to use for simple fetches. - private final OkHttpClient ok = new OkHttpClient.Builder() - .readTimeout(500, TimeUnit.MILLISECONDS) // Don't dawdle - .writeTimeout(500, TimeUnit.MILLISECONDS) - .build(); + private final OkHttpClient ok = + new OkHttpClient.Builder() + .readTimeout(500, TimeUnit.MILLISECONDS) // Don't dawdle + .writeTimeout(500, TimeUnit.MILLISECONDS) + .build(); // Setup to pretty print returned json - private final Gson gson = new GsonBuilder() - .setPrettyPrinting() - .create(); + private final Gson gson = new GsonBuilder().setPrettyPrinting().create(); private final JsonParser jp = new JsonParser(); // Fetch Metadata String fetchMetadata(String key) throws IOException { - Request request = new Request.Builder() - .url(metadata + key) - .addHeader("Metadata-Flavor", "Google") - .get() - .build(); - + Request request = + new Request.Builder() + .url(metadata + key) + .addHeader("Metadata-Flavor", "Google") + .get() + .build(); + Response response = ok.newCall(request).execute(); return response.body().string(); } String fetchJsonMetadata(String prefix) throws IOException { - Request request = new Request.Builder() - .url(metadata + prefix ) - .addHeader("Metadata-Flavor", "Google") - .get() - .build(); + Request request = + new Request.Builder() + .url(metadata + prefix) + .addHeader("Metadata-Flavor", "Google") + .get() + .build(); Response response = ok.newCall(request).execute(); @@ -125,10 +128,9 @@ public void init() { templateEngine.setTemplateResolver(templateResolver); } - @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - String key =""; + String key = ""; final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService(); WebContext ctx = new WebContext(req, resp, getServletContext(), req.getLocale()); @@ -207,7 +209,8 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc ctx.setVariable("sam", m.descendingMap()); // Recursivly get all info about service accounts -- Note tokens are leftout by default. - ctx.setVariable("rsa", + ctx.setVariable( + "rsa", fetchJsonMetadata("/computeMetadata/v1/instance/service-accounts/?recursive=true")); // Recursivly get all data on Metadata server. ctx.setVariable("ram", fetchJsonMetadata("/?recursive=true")); diff --git a/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/Greeting.java b/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/Greeting.java index c4ae6783399..1165a793d23 100644 --- a/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/Greeting.java +++ b/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/Greeting.java @@ -13,6 +13,7 @@ */ //[START all] + package com.example.guestbook; import static com.example.guestbook.Persistence.getDatastore; @@ -24,11 +25,12 @@ import com.google.cloud.datastore.IncompleteKey; import com.google.cloud.datastore.Key; import com.google.common.base.MoreObjects; - import java.util.Date; import java.util.Objects; +@SuppressWarnings(JavadocMethod) public class Greeting { + private Guestbook book; public Key key; diff --git a/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/Guestbook.java b/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/Guestbook.java index 4f2aeb69a5d..a827b998c12 100644 --- a/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/Guestbook.java +++ b/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/Guestbook.java @@ -11,6 +11,7 @@ * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.guestbook; import static com.example.guestbook.Persistence.getDatastore; @@ -27,12 +28,13 @@ import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; - import java.util.List; import java.util.Objects; //[START all] +@SuppressWarnings(JavadocMethod) public class Guestbook { + private static final KeyFactory keyFactory = getKeyFactory(Guestbook.class); private final Key key; diff --git a/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/Persistence.java b/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/Persistence.java index 1b68b8541e9..e144e113279 100644 --- a/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/Persistence.java +++ b/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/Persistence.java @@ -11,22 +11,24 @@ * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.guestbook; import com.google.cloud.datastore.Datastore; import com.google.cloud.datastore.DatastoreOptions; import com.google.cloud.datastore.KeyFactory; - import java.util.concurrent.atomic.AtomicReference; //[START all] public class Persistence { + private static AtomicReference datastore = new AtomicReference<>(); + @SuppressWarnings(JavadocMethod) public static Datastore getDatastore() { if (datastore.get() == null) { - datastore.set(DatastoreOptions.newBuilder().setProjectId("your-project-id-here") - .build().getService()); + datastore.set( + DatastoreOptions.newBuilder().setProjectId("your-project-id-here").build().getService()); } return datastore.get(); diff --git a/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/SignGuestbookServlet.java b/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/SignGuestbookServlet.java index 2c95c5c3aee..c7ae2673532 100644 --- a/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/SignGuestbookServlet.java +++ b/appengine-java8/guestbook-cloud-datastore/src/main/java/com/example/guestbook/SignGuestbookServlet.java @@ -13,12 +13,12 @@ */ //[START all] + package com.example.guestbook; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; - import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -26,6 +26,7 @@ //[START all] public class SignGuestbookServlet extends HttpServlet { + // Process the HTTP POST of the form @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { diff --git a/appengine-java8/guestbook-cloud-datastore/src/test/java/com/example/guestbook/GreetingTest.java b/appengine-java8/guestbook-cloud-datastore/src/test/java/com/example/guestbook/GreetingTest.java index a91390569ad..bbfb3ac3734 100644 --- a/appengine-java8/guestbook-cloud-datastore/src/test/java/com/example/guestbook/GreetingTest.java +++ b/appengine-java8/guestbook-cloud-datastore/src/test/java/com/example/guestbook/GreetingTest.java @@ -11,19 +11,19 @@ * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.guestbook; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.List; - @RunWith(JUnit4.class) public class GreetingTest { diff --git a/appengine-java8/guestbook-cloud-datastore/src/test/java/com/example/guestbook/SignGuestbookServletTest.java b/appengine-java8/guestbook-cloud-datastore/src/test/java/com/example/guestbook/SignGuestbookServletTest.java index 4a5435eafe7..4b476584787 100644 --- a/appengine-java8/guestbook-cloud-datastore/src/test/java/com/example/guestbook/SignGuestbookServletTest.java +++ b/appengine-java8/guestbook-cloud-datastore/src/test/java/com/example/guestbook/SignGuestbookServletTest.java @@ -11,12 +11,16 @@ * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.guestbook; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -25,16 +29,15 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.util.List; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @RunWith(JUnit4.class) public class SignGuestbookServletTest { + private final LocalServiceTestHelper helper = new LocalServiceTestHelper(); - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private SignGuestbookServlet signGuestbookServlet; diff --git a/appengine-java8/guestbook-cloud-datastore/src/test/java/com/example/guestbook/TestUtils.java b/appengine-java8/guestbook-cloud-datastore/src/test/java/com/example/guestbook/TestUtils.java index 0c4225ce96c..ee18bec19a3 100644 --- a/appengine-java8/guestbook-cloud-datastore/src/test/java/com/example/guestbook/TestUtils.java +++ b/appengine-java8/guestbook-cloud-datastore/src/test/java/com/example/guestbook/TestUtils.java @@ -8,13 +8,10 @@ import com.google.cloud.datastore.QueryResults; import com.google.cloud.datastore.testing.LocalDatastoreHelper; import com.google.common.collect.Lists; - -import org.threeten.bp.Duration; - import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.TimeoutException; - +import org.threeten.bp.Duration; public class TestUtils { static LocalDatastoreHelper datastore = LocalDatastoreHelper.create(); @@ -30,7 +27,7 @@ public static void startDatastore() { public static void stopDatastore() { try { - datastore.stop(Duration.ofSeconds(20 )); + datastore.stop(Duration.ofSeconds(20)); Persistence.setDatastore(null); } catch (TimeoutException | IOException | InterruptedException e) { throw new RuntimeException(e); @@ -39,8 +36,8 @@ public static void stopDatastore() { public static void wipeDatastore() { Datastore datastore = getDatastore(); - QueryResults guestbooks = datastore.run(Query.newKeyQueryBuilder().setKind("Greeting") - .build()); + QueryResults guestbooks = + datastore.run(Query.newKeyQueryBuilder().setKind("Greeting").build()); ArrayList keys = Lists.newArrayList(guestbooks); if (!keys.isEmpty()) { diff --git a/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/Greeting.java b/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/Greeting.java index 8067cd3fce7..1373cb2866c 100644 --- a/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/Greeting.java +++ b/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/Greeting.java @@ -1,20 +1,19 @@ /** * Copyright 2014-2015 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 + *

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 + *

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 + *

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. */ //[START all] + package com.example.guestbook; import com.googlecode.objectify.Key; @@ -22,45 +21,47 @@ import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Index; import com.googlecode.objectify.annotation.Parent; - -import java.lang.String; import java.util.Date; /** - * The @Entity tells Objectify about our entity. We also register it in {@link OfyHelper} - * Our primary key @Id is set automatically by the Google Datastore for us. + * The @Entity tells Objectify about our entity. We also register it in {@link OfyHelper} Our + * primary key @Id is set automatically by the Google Datastore for us. * - * We add a @Parent to tell the object about its ancestor. We are doing this to support many - * guestbooks. Objectify, unlike the AppEngine library requires that you specify the fields you - * want to index using @Index. Only indexing the fields you need can lead to substantial gains in + *

We add a @Parent to tell the object about its ancestor. We are doing this to support many + * guestbooks. Objectify, unlike the AppEngine library requires that you specify the fields you want + * to index using @Index. Only indexing the fields you need can lead to substantial gains in * performance -- though if not indexing your data from the start will require indexing it later. * - * NOTE - all the properties are PUBLIC so that can keep the code simple. - **/ + *

NOTE - all the properties are PUBLIC so that can keep the code simple. + */ @Entity public class Greeting { - @Parent Key theBook; - @Id public Long id; + + @Parent + Key theBook; + @Id + public Long id; public String authorEmail; public String authorId; public String content; - @Index public Date date; + @Index + public Date date; /** * Simple constructor just sets the date. - **/ + */ public Greeting() { date = new Date(); } /** * A convenience constructor. - **/ + */ public Greeting(String book, String content) { this(); - if ( book != null ) { - theBook = Key.create(Guestbook.class, book); // Creating the Ancestor key + if (book != null) { + theBook = Key.create(Guestbook.class, book); // Creating the Ancestor key } else { theBook = Key.create(Guestbook.class, "default"); } @@ -69,12 +70,11 @@ public Greeting(String book, String content) { /** * Takes all important fields. - **/ + */ public Greeting(String book, String content, String id, String email) { this(book, content); authorEmail = email; authorId = id; } - } //[END all] diff --git a/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/Guestbook.java b/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/Guestbook.java index 2b490aeff79..0f0083fd265 100644 --- a/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/Guestbook.java +++ b/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/Guestbook.java @@ -1,33 +1,34 @@ /** * Copyright 2014-2015 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 + *

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 + *

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 + *

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. */ //[START all] + package com.example.guestbook; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; /** - * The @Entity tells Objectify about our entity. We also register it in - * OfyHelper.java -- very important. + * The @Entity tells Objectify about our entity. We also register it in OfyHelper.java -- very + * important. * - * This is never actually created, but gives a hint to Objectify about our Ancestor key. + *

This is never actually created, but gives a hint to Objectify about our Ancestor key. */ @Entity public class Guestbook { - @Id public String book; + + @Id + public String book; } //[END all] diff --git a/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/OfyHelper.java b/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/OfyHelper.java index 3d34612007c..a16b854ca65 100644 --- a/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/OfyHelper.java +++ b/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/OfyHelper.java @@ -1,28 +1,33 @@ /** * Copyright 2014-2015 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 + *

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. + *

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. */ //[START all] + package com.example.guestbook; import com.googlecode.objectify.ObjectifyService; - import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** - * OfyHelper, a ServletContextListener, is setup in web.xml to run before a JSP is run. This is + * OfyHelper, a ServletContextListener, is setup in web.xml to run before a JSP is run. This is * required to let JSP's access Ofy. - **/ + */ public class OfyHelper implements ServletContextListener { + + /** + * Initialize a ServletContextListener. + * @param event . + */ public void contextInitialized(ServletContextEvent event) { // This will be invoked as part of a warmup request, or the first user request if no warmup // request. diff --git a/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/SignGuestbookServlet.java b/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/SignGuestbookServlet.java index e32912cb933..aa92c2cd7c8 100644 --- a/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/SignGuestbookServlet.java +++ b/appengine-java8/guestbook-objectify/src/main/java/com/example/guestbook/SignGuestbookServlet.java @@ -1,48 +1,43 @@ /** * Copyright 2014-2015 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 + *

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 + *

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 + *

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. */ //[START all] + package com.example.guestbook; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; - import com.googlecode.objectify.ObjectifyService; - import java.io.IOException; - import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** - * Form Handling Servlet - most of the action for this sample is in webapp/guestbook.jsp, - * which displays the {@link Greeting}'s. + * Form Handling Servlet - most of the action for this sample is in webapp/guestbook.jsp, which + * displays the {@link Greeting}'s. */ public class SignGuestbookServlet extends HttpServlet { // Process the http POST of the form @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Greeting greeting; UserService userService = UserServiceFactory.getUserService(); - User user = userService.getCurrentUser(); // Find out who the user is. + User user = userService.getCurrentUser(); // Find out who the user is. String guestbookName = req.getParameter("guestbookName"); String content = req.getParameter("content"); diff --git a/appengine-java8/guestbook-objectify/src/test/java/com/example/guestbook/GreetingTest.java b/appengine-java8/guestbook-objectify/src/test/java/com/example/guestbook/GreetingTest.java index 27d3030149d..71c62dffbf5 100644 --- a/appengine-java8/guestbook-objectify/src/test/java/com/example/guestbook/GreetingTest.java +++ b/appengine-java8/guestbook-objectify/src/test/java/com/example/guestbook/GreetingTest.java @@ -11,6 +11,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.guestbook; import static com.example.guestbook.GuestbookTestUtilities.cleanDatastore; @@ -24,7 +25,6 @@ import com.google.appengine.api.datastore.Query; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; - import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.util.Closeable; import org.junit.After; @@ -33,15 +33,17 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; - @RunWith(JUnit4.class) public class GreetingTest { + private static final String TEST_CONTENT = "The world is Blue today"; private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0)); @@ -75,10 +77,10 @@ public void createSaveObject() throws Exception { Greeting g = new Greeting("default", TEST_CONTENT); ObjectifyService.ofy().save().entity(g).now(); - Query query = new Query("Greeting") - .setAncestor(new KeyFactory.Builder("Guestbook", "default").getKey()); + Query query = + new Query("Greeting").setAncestor(new KeyFactory.Builder("Guestbook", "default").getKey()); PreparedQuery pq = ds.prepare(query); - Entity greeting = pq.asSingleEntity(); // Should only be one at this point. + Entity greeting = pq.asSingleEntity(); // Should only be one at this point. assertEquals(greeting.getProperty("content"), TEST_CONTENT); } } diff --git a/appengine-java8/guestbook-objectify/src/test/java/com/example/guestbook/GuestbookTestUtilities.java b/appengine-java8/guestbook-objectify/src/test/java/com/example/guestbook/GuestbookTestUtilities.java index cbd72b57b28..e5b8d9ece04 100644 --- a/appengine-java8/guestbook-objectify/src/test/java/com/example/guestbook/GuestbookTestUtilities.java +++ b/appengine-java8/guestbook-objectify/src/test/java/com/example/guestbook/GuestbookTestUtilities.java @@ -11,6 +11,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.guestbook; import com.google.appengine.api.datastore.DatastoreService; @@ -20,16 +21,16 @@ import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; - import java.util.ArrayList; import java.util.List; public class GuestbookTestUtilities { public static void cleanDatastore(DatastoreService ds, String book) { - Query query = new Query("Greeting") - .setAncestor(new KeyFactory.Builder("Guestbook", book) - .getKey()).setKeysOnly(); + Query query = + new Query("Greeting") + .setAncestor(new KeyFactory.Builder("Guestbook", book).getKey()) + .setKeysOnly(); PreparedQuery pq = ds.prepare(query); List entities = pq.asList(FetchOptions.Builder.withDefaults()); ArrayList keys = new ArrayList<>(entities.size()); @@ -39,5 +40,4 @@ public static void cleanDatastore(DatastoreService ds, String book) { } ds.delete(keys); } - } diff --git a/appengine-java8/guestbook-objectify/src/test/java/com/example/guestbook/SignGuestbookServletTest.java b/appengine-java8/guestbook-objectify/src/test/java/com/example/guestbook/SignGuestbookServletTest.java index 1c01ab37f8d..95ffbc2435e 100644 --- a/appengine-java8/guestbook-objectify/src/test/java/com/example/guestbook/SignGuestbookServletTest.java +++ b/appengine-java8/guestbook-objectify/src/test/java/com/example/guestbook/SignGuestbookServletTest.java @@ -28,9 +28,12 @@ import com.google.appengine.api.datastore.Query; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; - import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.util.Closeable; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -39,30 +42,28 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * Unit tests for {@link com.example.guestbook.SignGuestbookServlet}. */ @RunWith(JUnit4.class) public class SignGuestbookServletTest { + private static final String FAKE_URL = "fakey.org/sign"; private static final String FAKE_NAME = "Fake"; private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0)); private final String testPhrase = "Noew is the time"; - @Mock private HttpServletRequest mockRequest; + @Mock + private HttpServletRequest mockRequest; @Mock private HttpServletResponse mockResponse; @@ -81,8 +82,8 @@ public void setUp() throws Exception { // Set up some fake HTTP requests when(mockRequest.getRequestURI()).thenReturn(FAKE_URL); - when(mockRequest.getParameter("guestbookName")).thenReturn( "default" ); - when(mockRequest.getParameter("content")).thenReturn( testPhrase ); + when(mockRequest.getParameter("guestbookName")).thenReturn("default"); + when(mockRequest.getParameter("content")).thenReturn(testPhrase); stringWriter = new StringWriter(); when(mockResponse.getWriter()).thenReturn(new PrintWriter(stringWriter)); @@ -97,7 +98,8 @@ public void setUp() throws Exception { cleanDatastore(ds, "default"); } - @After public void tearDown() { + @After + public void tearDown() { cleanDatastore(ds, "default"); helper.tearDown(); closeable.close(); @@ -107,12 +109,11 @@ public void setUp() throws Exception { public void doPost_userNotLoggedIn() throws Exception { servletUnderTest.doPost(mockRequest, mockResponse); - Query query = new Query("Greeting") - .setAncestor(new KeyFactory.Builder("Guestbook", "default").getKey()); + Query query = + new Query("Greeting").setAncestor(new KeyFactory.Builder("Guestbook", "default").getKey()); PreparedQuery pq = ds.prepare(query); - Entity greeting = pq.asSingleEntity(); // Should only be one at this point. + Entity greeting = pq.asSingleEntity(); // Should only be one at this point. assertEquals(greeting.getProperty("content"), testPhrase); } - } diff --git a/appengine-java8/logs/src/main/java/com/example/appengine/logs/LogsServlet.java b/appengine-java8/logs/src/main/java/com/example/appengine/logs/LogsServlet.java index 30aa00e2176..8b45542fb26 100644 --- a/appengine-java8/logs/src/main/java/com/example/appengine/logs/LogsServlet.java +++ b/appengine-java8/logs/src/main/java/com/example/appengine/logs/LogsServlet.java @@ -13,33 +13,33 @@ * limitations under the License. */ // [START logs_API_example] + package com.example.appengine.logs; import com.google.appengine.api.log.AppLogLine; import com.google.appengine.api.log.LogQuery; import com.google.appengine.api.log.LogServiceFactory; import com.google.appengine.api.log.RequestLogs; - -import org.joda.time.DateTime; - import java.io.IOException; import java.io.PrintWriter; - import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import org.joda.time.DateTime; // Get request logs along with their app log lines and display them 5 at // a time, using a Next link to cycle through to the next 5. // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. -@WebServlet(name = "logs", description = "Logs: Display 5 lines of the request log", - urlPatterns = "/logs") +@WebServlet( + name = "logs", + description = "Logs: Display 5 lines of the request log", + urlPatterns = "/logs" +) public class LogsServlet extends HttpServlet { + @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter writer = resp.getWriter(); @@ -98,4 +98,3 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) } } // [END logs_API_example] - diff --git a/appengine-java8/mailgun/src/main/java/com/example/appengine/mailgun/MailgunServlet.java b/appengine-java8/mailgun/src/main/java/com/example/appengine/mailgun/MailgunServlet.java index ad30b5e983a..f946b1929f8 100644 --- a/appengine-java8/mailgun/src/main/java/com/example/appengine/mailgun/MailgunServlet.java +++ b/appengine-java8/mailgun/src/main/java/com/example/appengine/mailgun/MailgunServlet.java @@ -1,16 +1,14 @@ /** * Copyright 2015 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 + *

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 + *

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 + *

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. */ @@ -23,10 +21,8 @@ import com.sun.jersey.core.util.MultivaluedMapImpl; import com.sun.jersey.multipart.FormDataMultiPart; import com.sun.jersey.multipart.file.FileDataBodyPart; - import java.io.File; import java.io.IOException; - import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -55,27 +51,30 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOEx } // [START simple] + @SuppressWarnings(VariableDeclarationUsageDistance) private ClientResponse sendSimpleMessage(String recipient) { Client client = Client.create(); client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY)); - WebResource webResource = client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME - + "/messages"); + WebResource webResource = + client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages"); MultivaluedMapImpl formData = new MultivaluedMapImpl(); formData.add("from", "Mailgun User "); formData.add("to", recipient); formData.add("subject", "Simple Mailgun Example"); formData.add("text", "Plaintext content"); - return webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, - formData); + return webResource + .type(MediaType.APPLICATION_FORM_URLENCODED) + .post(ClientResponse.class, formData); } // [END simple] // [START complex] + @SuppressWarnings(VariableDeclarationUsageDistance) private ClientResponse sendComplexMessage(String recipient) { Client client = Client.create(); client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY)); - WebResource webResource = client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME - + "/messages"); + WebResource webResource = + client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages"); FormDataMultiPart formData = new FormDataMultiPart(); formData.field("from", "Mailgun User "); formData.field("to", recipient); @@ -84,7 +83,8 @@ private ClientResponse sendComplexMessage(String recipient) { ClassLoader classLoader = getClass().getClassLoader(); File txtFile = new File(classLoader.getResource("example-attachment.txt").getFile()); formData.bodyPart(new FileDataBodyPart("attachment", txtFile, MediaType.TEXT_PLAIN_TYPE)); - return webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE) + return webResource + .type(MediaType.MULTIPART_FORM_DATA_TYPE) .post(ClientResponse.class, formData); } // [END complex] diff --git a/appengine-java8/mailjet/src/main/java/com/example/appengine/mailjet/MailjetServlet.java b/appengine-java8/mailjet/src/main/java/com/example/appengine/mailjet/MailjetServlet.java index e9922a71438..ebee1c53216 100644 --- a/appengine-java8/mailjet/src/main/java/com/example/appengine/mailjet/MailjetServlet.java +++ b/appengine-java8/mailjet/src/main/java/com/example/appengine/mailjet/MailjetServlet.java @@ -1,19 +1,18 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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. */ // [START mailjet_imports] + package com.example.appengine.mailjet; import com.mailjet.client.MailjetClient; @@ -22,40 +21,44 @@ import com.mailjet.client.errors.MailjetException; import com.mailjet.client.errors.MailjetSocketTimeoutException; import com.mailjet.client.resource.Email; -// [END mailjet_imports] - -import org.json.JSONArray; -import org.json.JSONObject; - import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.json.JSONArray; +import org.json.JSONObject; + +// [END mailjet_imports] // [START app] @SuppressWarnings("serial") public class MailjetServlet extends HttpServlet { + private static final String MAILJET_API_KEY = System.getenv("MAILJET_API_KEY"); private static final String MAILJET_SECRET_KEY = System.getenv("MAILJET_SECRET_KEY"); private MailjetClient client = new MailjetClient(MAILJET_API_KEY, MAILJET_SECRET_KEY); @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, - ServletException { + public void doPost(HttpServletRequest req, HttpServletResponse resp) + throws IOException, ServletException { String recipient = req.getParameter("to"); String sender = req.getParameter("from"); - MailjetRequest email = new MailjetRequest(Email.resource) - .property(Email.FROMEMAIL, sender) - .property(Email.FROMNAME, "pandora") - .property(Email.SUBJECT, "Your email flight plan!") - .property(Email.TEXTPART, - "Dear passenger, welcome to Mailjet! May the delivery force be with you!") - .property(Email.HTMLPART, - "

Dear passenger, welcome to Mailjet!


May the delivery force be with you!") - .property(Email.RECIPIENTS, new JSONArray().put(new JSONObject().put("Email", recipient))); + MailjetRequest email = + new MailjetRequest(Email.resource) + .property(Email.FROMEMAIL, sender) + .property(Email.FROMNAME, "pandora") + .property(Email.SUBJECT, "Your email flight plan!") + .property( + Email.TEXTPART, + "Dear passenger, welcome to Mailjet! May the delivery force be with you!") + .property( + Email.HTMLPART, + "

Dear passenger, welcome to Mailjet!


May the delivery force be with " + + "you!") + .property( + Email.RECIPIENTS, new JSONArray().put(new JSONObject().put("Email", recipient))); try { // trigger the API call diff --git a/appengine-java8/multitenancy/src/main/java/com/example/appengine/Greeting.java b/appengine-java8/multitenancy/src/main/java/com/example/appengine/Greeting.java index c0645fc4fd8..e3406d63728 100644 --- a/appengine-java8/multitenancy/src/main/java/com/example/appengine/Greeting.java +++ b/appengine-java8/multitenancy/src/main/java/com/example/appengine/Greeting.java @@ -1,20 +1,19 @@ /** * Copyright 2014-2015 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 + *

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 + *

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 + *

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. */ //[START all] + package com.example.appengine; import com.googlecode.objectify.Key; @@ -22,55 +21,64 @@ import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Index; import com.googlecode.objectify.annotation.Parent; - import java.util.Date; /** - * The @Entity tells Objectify about our entity. We also register it in {@link OfyHelper} - * Our primary key @Id is set automatically by the Google Datastore for us. + * The @Entity tells Objectify about our entity. We also register it in {@link OfyHelper} Our + * primary key @Id is set automatically by the Google Datastore for us. * - * We add a @Parent to tell the object about its ancestor. We are doing this to support many - * guestbooks. Objectify, unlike the AppEngine library requires that you specify the fields you - * want to index using @Index. Only indexing the fields you need can lead to substantial gains in + *

We add a @Parent to tell the object about its ancestor. We are doing this to support many + * guestbooks. Objectify, unlike the AppEngine library requires that you specify the fields you want + * to index using @Index. Only indexing the fields you need can lead to substantial gains in * performance -- though if not indexing your data from the start will require indexing it later. * - * NOTE - all the properties are PUBLIC so that can keep the code simple. - **/ + *

NOTE - all the properties are PUBLIC so that can keep the code simple. + */ @Entity public class Greeting { - @Parent Key theBook; - @Id public Long id; + + @Parent + Key theBook; + @Id + public Long id; public String authorEmail; public String authorId; public String content; - @Index public Date date; + @Index + public Date date; /** * Simple constructor just sets the date. - **/ + */ public Greeting() { date = new Date(); } /** * A convenience constructor. - **/ + */ public Greeting(String book, String content) { this(); - if ( book != null ) { - theBook = Key.create(Guestbook.class, book); // Creating the Ancestor key + if (book != null) { + theBook = Key.create(Guestbook.class, book); // Creating the Ancestor key } else { theBook = Key.create(Guestbook.class, "default"); } this.content = content; } + /** + * Construct a Greeting with all params. + * @param book . + * @param content . + * @param id . + * @param email . + */ public Greeting(String book, String content, String id, String email) { this(book, content); authorEmail = email; authorId = id; } - } //[END all] diff --git a/appengine-java8/multitenancy/src/main/java/com/example/appengine/Guestbook.java b/appengine-java8/multitenancy/src/main/java/com/example/appengine/Guestbook.java index 1da82bc5b7f..265c10aeaa2 100644 --- a/appengine-java8/multitenancy/src/main/java/com/example/appengine/Guestbook.java +++ b/appengine-java8/multitenancy/src/main/java/com/example/appengine/Guestbook.java @@ -1,33 +1,34 @@ /** * Copyright 2014-2015 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 + *

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 + *

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 + *

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. */ //[START all] + package com.example.appengine; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; /** - * The @Entity tells Objectify about our entity. We also register it in - * OfyHelper.java -- very important. + * The @Entity tells Objectify about our entity. We also register it in OfyHelper.java -- very + * important. * - * This is never actually created, but gives a hint to Objectify about our Ancestor key. + *

This is never actually created, but gives a hint to Objectify about our Ancestor key. */ @Entity public class Guestbook { - @Id public String book; + + @Id + public String book; } //[END all] diff --git a/appengine-java8/multitenancy/src/main/java/com/example/appengine/MultitenancyServlet.java b/appengine-java8/multitenancy/src/main/java/com/example/appengine/MultitenancyServlet.java index ad206f06496..d9829c159d2 100644 --- a/appengine-java8/multitenancy/src/main/java/com/example/appengine/MultitenancyServlet.java +++ b/appengine-java8/multitenancy/src/main/java/com/example/appengine/MultitenancyServlet.java @@ -23,10 +23,8 @@ import com.google.appengine.api.search.SearchServiceConfig; import com.google.appengine.api.search.SearchServiceFactory; import com.google.appengine.api.users.UserServiceFactory; - import java.io.IOException; import java.io.PrintWriter; - import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -43,15 +41,15 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc out.println("Code Snippets -- not yet fully runnable as an app"); // [START temp_namespace] -// Set the namepace temporarily to "abc" + // Set the namepace temporarily to "abc" String oldNamespace = NamespaceManager.get(); NamespaceManager.set("abc"); try { -// ... perform operation using current namespace ... + // ... perform operation using current namespace ... } finally { NamespaceManager.set(oldNamespace); } -// [END temp_namespace] + // [END temp_namespace] // [START per_user_namespace] if (com.google.appengine.api.NamespaceManager.get() == null) { @@ -59,7 +57,7 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc namespace = UserServiceFactory.getUserService().getCurrentUser().getUserId(); NamespaceManager.set(namespace); } -// [END per_user_namespace] + // [END per_user_namespace] String value = "something here"; // [START ns_memcache] @@ -71,16 +69,16 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc oldNamespace = NamespaceManager.get(); NamespaceManager.set("abc"); try { - current.put("key", value); // stores value in namespace “abc” + current.put("key", value); // stores value in namespace “abc” } finally { NamespaceManager.set(oldNamespace); } -// [END ns_memcache] + // [END ns_memcache] // [START specific_memcache] // Create a MemcacheService that uses the namespace "abc". MemcacheService explicit = MemcacheServiceFactory.getMemcacheService("abc"); - explicit.put("key", value); // stores value in namespace "abc" + explicit.put("key", value); // stores value in namespace "abc" // [END specific_memcache] //[START searchns] @@ -96,19 +94,16 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc // [START searchns_2] // Create a SearchServiceConfig, specifying the namespace "anotherSpace" - SearchServiceConfig config = SearchServiceConfig.newBuilder() - .setNamespace("anotherSpace").build(); + SearchServiceConfig config = + SearchServiceConfig.newBuilder().setNamespace("anotherSpace").build(); // Create a SearchService with the namespace "anotherSpace" searchService = SearchServiceFactory.getSearchService(config); // Create an IndexSpec indexSpec = IndexSpec.newBuilder().setName("myindex").build(); // Create an Index with the namespace "anotherSpace" index = searchService.getIndex(indexSpec); - // [END searchns_2] + // [END searchns_2] } - - - } // [END example] diff --git a/appengine-java8/multitenancy/src/main/java/com/example/appengine/NamespaceFilter.java b/appengine-java8/multitenancy/src/main/java/com/example/appengine/NamespaceFilter.java index ed412169c99..0c48123a913 100644 --- a/appengine-java8/multitenancy/src/main/java/com/example/appengine/NamespaceFilter.java +++ b/appengine-java8/multitenancy/src/main/java/com/example/appengine/NamespaceFilter.java @@ -15,7 +15,6 @@ package com.example.appengine; import com.google.appengine.api.NamespaceManager; - import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; @@ -27,6 +26,7 @@ // [START nsfilter] // Filter to set the Google Apps domain as the namespace. public class NamespaceFilter implements Filter { + @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { @@ -38,15 +38,13 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) } chain.doFilter(req, res); // Pass request back down the filter chain } -// [END nsfilter] + // [END nsfilter] @Override public void init(FilterConfig filterConfig) throws ServletException { - } @Override public void destroy() { - } } diff --git a/appengine-java8/multitenancy/src/main/java/com/example/appengine/OfyHelper.java b/appengine-java8/multitenancy/src/main/java/com/example/appengine/OfyHelper.java index 8dcd38e8d1f..a9355860e50 100644 --- a/appengine-java8/multitenancy/src/main/java/com/example/appengine/OfyHelper.java +++ b/appengine-java8/multitenancy/src/main/java/com/example/appengine/OfyHelper.java @@ -1,31 +1,34 @@ /** * Copyright 2014-2015 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 + *

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 + *

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 + *

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. */ //[START all] + package com.example.appengine; import com.googlecode.objectify.ObjectifyService; - import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** - * OfyHelper, a ServletContextListener, is setup in web.xml to run before a JSP is run. This is + * OfyHelper, a ServletContextListener, is setup in web.xml to run before a JSP is run. This is * required to let JSP's access Ofy. - **/ + */ public class OfyHelper implements ServletContextListener { + + /** + * A ServletContextListener initializer. + * @param event . + */ public void contextInitialized(ServletContextEvent event) { // This will be invoked as part of a warmup request, or the first user request if no warmup // request. diff --git a/appengine-java8/multitenancy/src/main/java/com/example/appengine/SignGuestbookServlet.java b/appengine-java8/multitenancy/src/main/java/com/example/appengine/SignGuestbookServlet.java index 8726c91ce24..306366801f8 100644 --- a/appengine-java8/multitenancy/src/main/java/com/example/appengine/SignGuestbookServlet.java +++ b/appengine-java8/multitenancy/src/main/java/com/example/appengine/SignGuestbookServlet.java @@ -1,37 +1,33 @@ /** * Copyright 2014-2015 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 + *

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 + *

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 + *

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. */ //[START all] + package com.example.appengine; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; - import com.googlecode.objectify.ObjectifyService; - import java.io.IOException; - import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** - * Form Handling Servlet - most of the action for this sample is in webapp/guestbook.jsp. - * It displays {@link Greeting}'s. + * Form Handling Servlet - most of the action for this sample is in webapp/guestbook.jsp. It + * displays {@link Greeting}'s. */ public class SignGuestbookServlet extends HttpServlet { @@ -41,7 +37,7 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOEx Greeting greeting; UserService userService = UserServiceFactory.getUserService(); - User user = userService.getCurrentUser(); // Find out who the user is. + User user = userService.getCurrentUser(); // Find out who the user is. String guestbookName = req.getParameter("guestbookName"); String content = req.getParameter("content"); diff --git a/appengine-java8/multitenancy/src/main/java/com/example/appengine/SomeRequestServlet.java b/appengine-java8/multitenancy/src/main/java/com/example/appengine/SomeRequestServlet.java index 4157164a1f4..ace077f095b 100644 --- a/appengine-java8/multitenancy/src/main/java/com/example/appengine/SomeRequestServlet.java +++ b/appengine-java8/multitenancy/src/main/java/com/example/appengine/SomeRequestServlet.java @@ -11,30 +11,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.appengine; import com.google.appengine.api.NamespaceManager; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; - import java.io.IOException; - import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; // [START tq_3] public class SomeRequestServlet extends HttpServlet { + // Handler for URL get requests. @Override - protected void doGet(HttpServletRequest req, - HttpServletResponse resp) - throws IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Increment the count for the current namespace asynchronously. - QueueFactory.getDefaultQueue().add( - TaskOptions.Builder.withUrl("/_ah/update_count") - .param("countName", "SomeRequest")); + QueueFactory.getDefaultQueue() + .add(TaskOptions.Builder.withUrl("/_ah/update_count").param("countName", "SomeRequest")); // Increment the global count and set the // namespace locally. The namespace is // transferred to the invoked request and @@ -42,9 +39,8 @@ protected void doGet(HttpServletRequest req, String namespace = NamespaceManager.get(); try { NamespaceManager.set("-global-"); - QueueFactory.getDefaultQueue().add( - TaskOptions.Builder.withUrl("/_ah/update_count") - .param("countName", "SomeRequest")); + QueueFactory.getDefaultQueue() + .add(TaskOptions.Builder.withUrl("/_ah/update_count").param("countName", "SomeRequest")); } finally { NamespaceManager.set(namespace); } @@ -52,4 +48,4 @@ protected void doGet(HttpServletRequest req, resp.getWriter().println("Counts are being updated."); } } -// [END tq_3] \ No newline at end of file +// [END tq_3] diff --git a/appengine-java8/multitenancy/src/main/java/com/example/appengine/UpdateCountsServlet.java b/appengine-java8/multitenancy/src/main/java/com/example/appengine/UpdateCountsServlet.java index cb1fbe8a3e3..d9fec18b5a1 100644 --- a/appengine-java8/multitenancy/src/main/java/com/example/appengine/UpdateCountsServlet.java +++ b/appengine-java8/multitenancy/src/main/java/com/example/appengine/UpdateCountsServlet.java @@ -11,16 +11,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.appengine; import static com.googlecode.objectify.ObjectifyService.ofy; import com.google.appengine.api.NamespaceManager; - import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Index; - import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -28,11 +27,16 @@ // [START datastore] // [START tq_1] public class UpdateCountsServlet extends HttpServlet { + private static final int NUM_RETRIES = 10; - @Entity public class CounterPojo { - @Id public Long id; - @Index public String name; + @Entity + public class CounterPojo { + + @Id + public Long id; + @Index + public String name; public Long count; public CounterPojo() { @@ -49,7 +53,9 @@ public void increment() { } } - // Increment the count in a Counter datastore entity. + /** + * Increment the count in a Counter datastore entity. + **/ public long updateCount(String countName) { CounterPojo cp = ofy().load().type(CounterPojo.class).filter("name", countName).first().now(); @@ -61,7 +67,7 @@ public long updateCount(String countName) { return cp.count; } -// [END tq_1] + // [END tq_1] @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) diff --git a/appengine-java8/multitenancy/src/test/java/com/example/appengine/GreetingTest.java b/appengine-java8/multitenancy/src/test/java/com/example/appengine/GreetingTest.java index b58b2f3d9f6..f38eaaf868e 100644 --- a/appengine-java8/multitenancy/src/test/java/com/example/appengine/GreetingTest.java +++ b/appengine-java8/multitenancy/src/test/java/com/example/appengine/GreetingTest.java @@ -11,6 +11,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.appengine; import static com.example.appengine.GuestbookTestUtilities.cleanDatastore; @@ -24,7 +25,6 @@ import com.google.appengine.api.datastore.Query; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; - import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.util.Closeable; import org.junit.After; @@ -33,15 +33,17 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; - @RunWith(JUnit4.class) public class GreetingTest { + private static final String TEST_CONTENT = "The world is Blue today"; private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0)); @@ -75,10 +77,10 @@ public void createSaveObject() throws Exception { Greeting g = new Greeting("default", TEST_CONTENT); ObjectifyService.ofy().save().entity(g).now(); - Query query = new Query("Greeting") - .setAncestor(new KeyFactory.Builder("Guestbook", "default").getKey()); + Query query = + new Query("Greeting").setAncestor(new KeyFactory.Builder("Guestbook", "default").getKey()); PreparedQuery pq = ds.prepare(query); - Entity greeting = pq.asSingleEntity(); // Should only be one at this point. + Entity greeting = pq.asSingleEntity(); // Should only be one at this point. assertEquals(greeting.getProperty("content"), TEST_CONTENT); } } diff --git a/appengine-java8/multitenancy/src/test/java/com/example/appengine/GuestbookTestUtilities.java b/appengine-java8/multitenancy/src/test/java/com/example/appengine/GuestbookTestUtilities.java index 6b2c41761d0..796303a4373 100644 --- a/appengine-java8/multitenancy/src/test/java/com/example/appengine/GuestbookTestUtilities.java +++ b/appengine-java8/multitenancy/src/test/java/com/example/appengine/GuestbookTestUtilities.java @@ -11,6 +11,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.appengine; import com.google.appengine.api.datastore.DatastoreService; @@ -20,16 +21,16 @@ import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; - import java.util.ArrayList; import java.util.List; public class GuestbookTestUtilities { public static void cleanDatastore(DatastoreService ds, String book) { - Query query = new Query("Greeting") - .setAncestor(new KeyFactory.Builder("Guestbook", book) - .getKey()).setKeysOnly(); + Query query = + new Query("Greeting") + .setAncestor(new KeyFactory.Builder("Guestbook", book).getKey()) + .setKeysOnly(); PreparedQuery pq = ds.prepare(query); List entities = pq.asList(FetchOptions.Builder.withDefaults()); ArrayList keys = new ArrayList<>(entities.size()); @@ -39,5 +40,4 @@ public static void cleanDatastore(DatastoreService ds, String book) { } ds.delete(keys); } - } diff --git a/appengine-java8/multitenancy/src/test/java/com/example/appengine/SignGuestbookServletTest.java b/appengine-java8/multitenancy/src/test/java/com/example/appengine/SignGuestbookServletTest.java index 7a532ca9d3f..c28a9524e15 100644 --- a/appengine-java8/multitenancy/src/test/java/com/example/appengine/SignGuestbookServletTest.java +++ b/appengine-java8/multitenancy/src/test/java/com/example/appengine/SignGuestbookServletTest.java @@ -28,9 +28,12 @@ import com.google.appengine.api.datastore.Query; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; - import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.util.Closeable; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -39,30 +42,28 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * Unit tests for {@link com.example.appengine.SignGuestbookServlet}. */ @RunWith(JUnit4.class) public class SignGuestbookServletTest { + private static final String FAKE_URL = "fakey.org/sign"; private static final String FAKE_NAME = "Fake"; private final LocalServiceTestHelper helper = new LocalServiceTestHelper( // Set no eventual consistency, that way queries return all results. - // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests + // https://cloud.google + // .com/appengine/docs/java/tools/localunittesting + // #Java_Writing_High_Replication_Datastore_tests new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0)); private final String testPhrase = "Noew is the time"; - @Mock private HttpServletRequest mockRequest; + @Mock + private HttpServletRequest mockRequest; @Mock private HttpServletResponse mockResponse; @@ -81,8 +82,8 @@ public void setUp() throws Exception { // Set up some fake HTTP requests when(mockRequest.getRequestURI()).thenReturn(FAKE_URL); - when(mockRequest.getParameter("guestbookName")).thenReturn( "default" ); - when(mockRequest.getParameter("content")).thenReturn( testPhrase ); + when(mockRequest.getParameter("guestbookName")).thenReturn("default"); + when(mockRequest.getParameter("content")).thenReturn(testPhrase); stringWriter = new StringWriter(); when(mockResponse.getWriter()).thenReturn(new PrintWriter(stringWriter)); @@ -97,7 +98,8 @@ public void setUp() throws Exception { cleanDatastore(ds, "default"); } - @After public void tearDown() { + @After + public void tearDown() { cleanDatastore(ds, "default"); helper.tearDown(); closeable.close(); @@ -107,12 +109,11 @@ public void setUp() throws Exception { public void doPost_userNotLoggedIn() throws Exception { servletUnderTest.doPost(mockRequest, mockResponse); - Query query = new Query("Greeting") - .setAncestor(new KeyFactory.Builder("Guestbook", "default").getKey()); + Query query = + new Query("Greeting").setAncestor(new KeyFactory.Builder("Guestbook", "default").getKey()); PreparedQuery pq = ds.prepare(query); - Entity greeting = pq.asSingleEntity(); // Should only be one at this point. + Entity greeting = pq.asSingleEntity(); // Should only be one at this point. assertEquals(greeting.getProperty("content"), testPhrase); } - } diff --git a/appengine-java8/oauth2/src/main/java/com/example/appengine/HelloServlet.java b/appengine-java8/oauth2/src/main/java/com/example/appengine/HelloServlet.java index 9139840ce9b..fafd2f7c059 100644 --- a/appengine-java8/oauth2/src/main/java/com/example/appengine/HelloServlet.java +++ b/appengine-java8/oauth2/src/main/java/com/example/appengine/HelloServlet.java @@ -1,16 +1,14 @@ /** * Copyright 2015 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 + *

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 + *

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 + *

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. */ @@ -20,10 +18,8 @@ import com.google.appengine.api.oauth.OAuthService; import com.google.appengine.api.oauth.OAuthServiceFactory; import com.google.appengine.api.users.User; - import java.io.IOException; import java.io.PrintWriter; - import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -32,8 +28,11 @@ // [START example] @SuppressWarnings("serial") // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. -@WebServlet(name = "oauth2", description = "Oauth2: restricted helloWorld", - urlPatterns = "/oauth2hello") +@WebServlet( + name = "oauth2", + description = "Oauth2: restricted helloWorld", + urlPatterns = "/oauth2hello" +) public class HelloServlet extends HttpServlet { @Override diff --git a/appengine-java8/oauth2/src/main/java/com/example/appengine/Oauth2Filter.java b/appengine-java8/oauth2/src/main/java/com/example/appengine/Oauth2Filter.java index 38d60a43c71..f9395222658 100644 --- a/appengine-java8/oauth2/src/main/java/com/example/appengine/Oauth2Filter.java +++ b/appengine-java8/oauth2/src/main/java/com/example/appengine/Oauth2Filter.java @@ -11,6 +11,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.appengine; import com.google.appengine.api.oauth.OAuthRequestException; @@ -19,9 +20,7 @@ import com.google.appengine.api.oauth.OAuthServiceFailureException; import com.google.appengine.api.utils.SystemProperty; import com.google.common.collect.ImmutableSet; - import java.io.IOException; - import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -33,11 +32,11 @@ import javax.servlet.http.HttpServletResponse; /** - * Filter to verify that request has a "Authorization: Bearer xxxx" header, - * and check if xxxx is authorized to use this app. + * Filter to verify that request has a "Authorization: Bearer xxxx" header, and check if xxxx is + * authorized to use this app. * - *

Note - this is to demonstrate the OAuth2 APIs, as it is possible to lockdown some - * of your app's URL's using cloud console by adding service accounts to the project.

+ *

Note - this is to demonstrate the OAuth2 APIs, as it is possible to lockdown some of your + * app's URL's using cloud console by adding service accounts to the project. */ // With @WebFilter annotation the webapp/WEB-INF/web.xml is no longer required. @WebFilter(urlPatterns = "/oauth2hello") @@ -53,13 +52,14 @@ public void init(final FilterConfig config) throws ServletException { // [START oauth2] @Override public void doFilter( - final ServletRequest servletReq, final ServletResponse servletResp, final FilterChain chain) + final ServletRequest servletReq, final ServletResponse servletResp, final FilterChain chain) throws IOException, ServletException { final String scope = "https://www.googleapis.com/auth/userinfo.email"; - ImmutableSet allowedClients = new ImmutableSet.Builder() - .add("407408718192.apps.googleusercontent.com") - .add("755878275993-j4k7emq6rlupctce1c28enpcrr50vfo1.apps.googleusercontent.com") - .build(); + ImmutableSet allowedClients = + new ImmutableSet.Builder() + .add("407408718192.apps.googleusercontent.com") + .add("755878275993-j4k7emq6rlupctce1c28enpcrr50vfo1.apps.googleusercontent.com") + .build(); HttpServletResponse resp = (HttpServletResponse) servletResp; @@ -71,27 +71,27 @@ public void doFilter( try { String tokenAudience = oauth.getClientId(scope); - // The line below is commented out for privacy. -// context.log("tokenAudience: " + tokenAudience); // Account we match + // The line below is commented out for privacy. + // context.log("tokenAudience: " + tokenAudience); // Account we match if (!allowedClients.contains(tokenAudience)) { - throw new OAuthRequestException("audience of token '" + tokenAudience - + "' is not in allowed list " + allowedClients); + throw new OAuthRequestException( + "audience of token '" + tokenAudience + "' is not in allowed list " + allowedClients); } } catch (OAuthRequestException ex) { - resp.sendError(HttpServletResponse.SC_NOT_FOUND); // Not allowed + resp.sendError(HttpServletResponse.SC_NOT_FOUND); // Not allowed return; } catch (OAuthServiceFailureException ex) { - resp.sendError(HttpServletResponse.SC_NOT_FOUND); // some failure - reject + resp.sendError(HttpServletResponse.SC_NOT_FOUND); // some failure - reject context.log("oauth2 failure", ex); return; } } - chain.doFilter(servletReq, servletResp); // continue processing + chain.doFilter(servletReq, servletResp); // continue processing } // [END oauth2] @Override - public void destroy() { } - + public void destroy() { + } } diff --git a/appengine-java8/pom.xml b/appengine-java8/pom.xml index 9c203faf31c..e78823f79b2 100644 --- a/appengine-java8/pom.xml +++ b/appengine-java8/pom.xml @@ -37,7 +37,7 @@ analytics appidentity - + bigtable cloudsql datastore diff --git a/appengine-java8/remote-client/src/main/java/com/example/appengine/remote/RemoteApiExample.java b/appengine-java8/remote-client/src/main/java/com/example/appengine/remote/RemoteApiExample.java index 97131664214..bea44ca66e1 100644 --- a/appengine-java8/remote-client/src/main/java/com/example/appengine/remote/RemoteApiExample.java +++ b/appengine-java8/remote-client/src/main/java/com/example/appengine/remote/RemoteApiExample.java @@ -1,16 +1,14 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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. */ @@ -21,21 +19,23 @@ import com.google.appengine.api.datastore.Entity; import com.google.appengine.tools.remoteapi.RemoteApiInstaller; import com.google.appengine.tools.remoteapi.RemoteApiOptions; - import java.io.IOException; // [START example] public class RemoteApiExample { + /** + * A simple API client. + * @param args . + * @throws IOException . + */ public static void main(String[] args) throws IOException { String serverString = args[0]; RemoteApiOptions options; if (serverString.equals("localhost")) { - options = new RemoteApiOptions().server(serverString, - 8080).useDevelopmentServerCredential(); + options = new RemoteApiOptions().server(serverString, 8080).useDevelopmentServerCredential(); } else { - options = new RemoteApiOptions().server(serverString, - 443).useApplicationDefaultCredential(); + options = new RemoteApiOptions().server(serverString, 443).useApplicationDefaultCredential(); } RemoteApiInstaller installer = new RemoteApiInstaller(); installer.install(options); diff --git a/appengine-java8/requests/src/main/java/com/example/appengine/requests/LoggingServlet.java b/appengine-java8/requests/src/main/java/com/example/appengine/requests/LoggingServlet.java index 10013344656..50d97b4a3dd 100644 --- a/appengine-java8/requests/src/main/java/com/example/appengine/requests/LoggingServlet.java +++ b/appengine-java8/requests/src/main/java/com/example/appengine/requests/LoggingServlet.java @@ -12,11 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.appengine.requests; import java.io.IOException; import java.util.logging.Logger; - import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -24,14 +24,17 @@ // [START simple_logging_example] // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. -@WebServlet(name = "RequestLogging", description = "Requests: Logging example", - urlPatterns = "/requests/log") +@WebServlet( + name = "RequestLogging", + description = "Requests: Logging example", + urlPatterns = "/requests/log" +) public class LoggingServlet extends HttpServlet { + private static final Logger log = Logger.getLogger(LoggingServlet.class.getName()); @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.info("An informational message."); log.warning("A warning message."); log.severe("An error message."); @@ -42,4 +45,3 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) } } // [END simple_logging_example] - diff --git a/appengine-java8/requests/src/main/java/com/example/appengine/requests/RequestsServlet.java b/appengine-java8/requests/src/main/java/com/example/appengine/requests/RequestsServlet.java index 878aeaeb70f..bf575133b85 100644 --- a/appengine-java8/requests/src/main/java/com/example/appengine/requests/RequestsServlet.java +++ b/appengine-java8/requests/src/main/java/com/example/appengine/requests/RequestsServlet.java @@ -12,10 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.appengine.requests; import java.io.IOException; - import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -23,15 +23,13 @@ // [START simple_request_example] // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. -@WebServlet(name = "requests", description = "Requests: Trivial request", - urlPatterns = "/requests") +@WebServlet(name = "requests", description = "Requests: Trivial request", urlPatterns = "/requests") public class RequestsServlet extends HttpServlet { + @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/plain"); resp.getWriter().println("Hello, world"); } } // [END simple_request_example] - diff --git a/appengine-java8/requests/src/test/java/com/example/appengine/requests/LoggingServletTest.java b/appengine-java8/requests/src/test/java/com/example/appengine/requests/LoggingServletTest.java index 6f3469e6b5c..a093ee147ed 100644 --- a/appengine-java8/requests/src/test/java/com/example/appengine/requests/LoggingServletTest.java +++ b/appengine-java8/requests/src/test/java/com/example/appengine/requests/LoggingServletTest.java @@ -19,6 +19,12 @@ import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.when; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -27,25 +33,20 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * Unit tests for {@link LoggingServlet}. */ @RunWith(JUnit4.class) public class LoggingServletTest { + // To capture and restore stderr private final ByteArrayOutputStream stderr = new ByteArrayOutputStream(); private static final PrintStream REAL_ERR = System.err; - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private LoggingServlet servletUnderTest; @@ -81,5 +82,4 @@ public void testListLogs() throws Exception { assertThat(out).contains("A warning message."); assertThat(out).contains("An error message."); } - } diff --git a/appengine-java8/requests/src/test/java/com/example/appengine/requests/RequestsServletTest.java b/appengine-java8/requests/src/test/java/com/example/appengine/requests/RequestsServletTest.java index 639aa0a6a2a..5c655e48167 100644 --- a/appengine-java8/requests/src/test/java/com/example/appengine/requests/RequestsServletTest.java +++ b/appengine-java8/requests/src/test/java/com/example/appengine/requests/RequestsServletTest.java @@ -19,6 +19,10 @@ import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.when; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,19 +30,16 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * Unit tests for {@link RequestsServlet}. */ @RunWith(JUnit4.class) public class RequestsServletTest { - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private RequestsServlet servletUnderTest; diff --git a/appengine-java8/search/src/main/java/com/example/appengine/search/DeleteServlet.java b/appengine-java8/search/src/main/java/com/example/appengine/search/DeleteServlet.java index dbe869e263b..136b86fd044 100644 --- a/appengine-java8/search/src/main/java/com/example/appengine/search/DeleteServlet.java +++ b/appengine-java8/search/src/main/java/com/example/appengine/search/DeleteServlet.java @@ -1,16 +1,14 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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. */ @@ -19,37 +17,39 @@ // @formatter:off // [START delete_import] import com.google.appengine.api.search.Document; +import com.google.appengine.api.search.Field; import com.google.appengine.api.search.GetRequest; import com.google.appengine.api.search.GetResponse; -// [END delete_import] - -// CHECKSTYLE:OFF -import com.google.appengine.api.search.Field; import com.google.appengine.api.search.Index; import com.google.appengine.api.search.IndexSpec; import com.google.appengine.api.search.SearchServiceFactory; -// @formatter:on -// CHECKSTYLE:ON - import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; - import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +// [END delete_import] +// CHECKSTYLE:OFF +// @formatter:on +// CHECKSTYLE:ON + /** * Code snippet for deleting documents from an Index. */ @SuppressWarnings("serial") -@WebServlet(name = "searchDelete", description = "Search: Delete a document from the index", - urlPatterns = "/search/delete") +@WebServlet( + name = "searchDelete", + description = "Search: Delete a document from the index", + urlPatterns = "/search/delete" +) public class DeleteServlet extends HttpServlet { + private static final Logger LOG = Logger.getLogger(DeleteServlet.class.getSimpleName()); private static final String SEARCH_INDEX = "searchIndexForDelete"; @@ -61,12 +61,10 @@ private Index getIndex() { } @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Put one document to avoid an error - Document document = Document.newBuilder() - .addField(Field.newBuilder().setName("f").setText("v")) - .build(); + Document document = + Document.newBuilder().addField(Field.newBuilder().setName("f").setText("v")).build(); try { Utils.indexADocument(SEARCH_INDEX, document); } catch (InterruptedException e) { diff --git a/appengine-java8/search/src/main/java/com/example/appengine/search/DocumentServlet.java b/appengine-java8/search/src/main/java/com/example/appengine/search/DocumentServlet.java index 8a3404a2439..ff377363657 100644 --- a/appengine-java8/search/src/main/java/com/example/appengine/search/DocumentServlet.java +++ b/appengine-java8/search/src/main/java/com/example/appengine/search/DocumentServlet.java @@ -1,47 +1,49 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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.example.appengine.search; // [START document_import] + import com.google.appengine.api.search.Document; import com.google.appengine.api.search.Field; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserServiceFactory; -// [END document_import] - import java.io.IOException; import java.io.PrintWriter; import java.util.Date; - import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +// [END document_import] + /** * A servlet for creating Search API Document. */ @SuppressWarnings("serial") -@WebServlet(name = "searchCreate", description = "Search: Create the Search API document.", - urlPatterns = "/search") +@WebServlet( + name = "searchCreate", + description = "Search: Create the Search API document.", + urlPatterns = "/search" +) public class DocumentServlet extends HttpServlet { /** * Code snippet for creating a Document. + * * @return Document Created document. */ public Document createDocument() { @@ -50,29 +52,30 @@ public Document createDocument() { String userEmail = currentUser == null ? "" : currentUser.getEmail(); String userDomain = currentUser == null ? "" : currentUser.getAuthDomain(); String myDocId = "PA6-5000"; - Document doc = Document.newBuilder() - // Setting the document identifer is optional. - // If omitted, the search service will create an identifier. - .setId(myDocId) - .addField(Field.newBuilder().setName("content").setText("the rain in spain")) - .addField(Field.newBuilder().setName("email").setText(userEmail)) - .addField(Field.newBuilder().setName("domain").setAtom(userDomain)) - .addField(Field.newBuilder().setName("published").setDate(new Date())) - .build(); + Document doc = + Document.newBuilder() + // Setting the document identifer is optional. + // If omitted, the search service will create an identifier. + .setId(myDocId) + .addField(Field.newBuilder().setName("content").setText("the rain in spain")) + .addField(Field.newBuilder().setName("email").setText(userEmail)) + .addField(Field.newBuilder().setName("domain").setAtom(userDomain)) + .addField(Field.newBuilder().setName("published").setDate(new Date())) + .build(); // [END create_document] return doc; } @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); - Document document = Document.newBuilder() - .addField(Field.newBuilder().setName("coverLetter").setText("CoverLetter")) - .addField(Field.newBuilder().setName("resume").setHTML("")) - .addField(Field.newBuilder().setName("fullName").setAtom("Foo Bar")) - .addField(Field.newBuilder().setName("submissionDate").setDate(new Date())) - .build(); + Document document = + Document.newBuilder() + .addField(Field.newBuilder().setName("coverLetter").setText("CoverLetter")) + .addField(Field.newBuilder().setName("resume").setHTML("")) + .addField(Field.newBuilder().setName("fullName").setAtom("Foo Bar")) + .addField(Field.newBuilder().setName("submissionDate").setDate(new Date())) + .build(); // [START access_document] String coverLetter = document.getOnlyField("coverLetter").getText(); String resume = document.getOnlyField("resume").getHTML(); diff --git a/appengine-java8/search/src/main/java/com/example/appengine/search/IndexServlet.java b/appengine-java8/search/src/main/java/com/example/appengine/search/IndexServlet.java index 8e53c150fa5..e4135b63df3 100644 --- a/appengine-java8/search/src/main/java/com/example/appengine/search/IndexServlet.java +++ b/appengine-java8/search/src/main/java/com/example/appengine/search/IndexServlet.java @@ -1,16 +1,14 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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. */ @@ -19,33 +17,33 @@ // @formatter:off import com.google.appengine.api.search.Document; import com.google.appengine.api.search.Field; +import com.google.appengine.api.search.GetRequest; +import com.google.appengine.api.search.GetResponse; import com.google.appengine.api.search.Index; import com.google.appengine.api.search.IndexSpec; import com.google.appengine.api.search.SearchServiceFactory; - -// CHECKSTYLE:OFF -// [START get_document_import] -import com.google.appengine.api.search.GetRequest; -import com.google.appengine.api.search.GetResponse; -// [END get_document_import] -// @formatter:on -// CHECKSTYLE:ON - import java.io.IOException; import java.io.PrintWriter; - import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +// CHECKSTYLE:OFF +// [START get_document_import] +// [END get_document_import] +// @formatter:on +// CHECKSTYLE:ON /** * Code snippet for getting a document from Index. */ @SuppressWarnings("serial") -@WebServlet(name = "searchIndex", description = "Search: Index a new document", - urlPatterns = "/search/index") +@WebServlet( + name = "searchIndex", + description = "Search: Index a new document", + urlPatterns = "/search/index" +) public class IndexServlet extends HttpServlet { private static final String INDEX = "testIndex"; @@ -53,9 +51,11 @@ public class IndexServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); - Document document = Document.newBuilder() - .setId("AZ125") - .addField(Field.newBuilder().setName("myField").setText("myValue")).build(); + Document document = + Document.newBuilder() + .setId("AZ125") + .addField(Field.newBuilder().setName("myField").setText("myValue")) + .build(); try { Utils.indexADocument(INDEX, document); } catch (InterruptedException e) { @@ -71,8 +71,8 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc Document doc = index.get("AZ125"); // Fetch a range of documents by their doc_ids - GetResponse docs = index.getRange( - GetRequest.newBuilder().setStartId("AZ125").setLimit(100).build()); + GetResponse docs = + index.getRange(GetRequest.newBuilder().setStartId("AZ125").setLimit(100).build()); // [END get_document] out.println("myField: " + docs.getResults().get(0).getOnlyField("myField").getText()); } diff --git a/appengine-java8/search/src/main/java/com/example/appengine/search/SchemaServlet.java b/appengine-java8/search/src/main/java/com/example/appengine/search/SchemaServlet.java index a4487147aeb..9233b5f081a 100644 --- a/appengine-java8/search/src/main/java/com/example/appengine/search/SchemaServlet.java +++ b/appengine-java8/search/src/main/java/com/example/appengine/search/SchemaServlet.java @@ -1,16 +1,14 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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. */ @@ -18,56 +16,57 @@ import com.google.appengine.api.search.Document; import com.google.appengine.api.search.Field; -import com.google.appengine.api.search.SearchServiceFactory; - -// @formatter:off -// CHECKSTYLE:OFF -// [START schema_import] import com.google.appengine.api.search.Field.FieldType; -import com.google.appengine.api.search.Index; import com.google.appengine.api.search.GetIndexesRequest; import com.google.appengine.api.search.GetResponse; +import com.google.appengine.api.search.Index; import com.google.appengine.api.search.Schema; -// [END schema_import] -// @formatter:on -// CHECKSTYLE:ON - +import com.google.appengine.api.search.SearchServiceFactory; import java.io.IOException; import java.io.PrintWriter; import java.util.List; - import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +// @formatter:off +// CHECKSTYLE:OFF +// [START schema_import] +// [END schema_import] +// @formatter:on +// CHECKSTYLE:ON @SuppressWarnings("serial") -@WebServlet(name = "searchSchema", description = "Search: List the schema for a document.", - urlPatterns = "/search/schema") +@WebServlet( + name = "searchSchema", + description = "Search: List the schema for a document.", + urlPatterns = "/search/schema" +) public class SchemaServlet extends HttpServlet { private static final String SEARCH_INDEX = "schemaIndex"; @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); - Document doc = Document.newBuilder() - .setId("theOnlyCar") - .addField(Field.newBuilder().setName("maker").setText("Toyota")) - .addField(Field.newBuilder().setName("price").setNumber(300000)) - .addField(Field.newBuilder().setName("color").setText("lightblue")) - .addField(Field.newBuilder().setName("model").setText("Prius")) - .build(); + Document doc = + Document.newBuilder() + .setId("theOnlyCar") + .addField(Field.newBuilder().setName("maker").setText("Toyota")) + .addField(Field.newBuilder().setName("price").setNumber(300000)) + .addField(Field.newBuilder().setName("color").setText("lightblue")) + .addField(Field.newBuilder().setName("model").setText("Prius")) + .build(); try { Utils.indexADocument(SEARCH_INDEX, doc); } catch (InterruptedException e) { // ignore } // [START list_schema] - GetResponse response = SearchServiceFactory.getSearchService().getIndexes( - GetIndexesRequest.newBuilder().setSchemaFetched(true).build()); + GetResponse response = + SearchServiceFactory.getSearchService() + .getIndexes(GetIndexesRequest.newBuilder().setSchemaFetched(true).build()); // List out elements of each Schema for (Index index : response) { diff --git a/appengine-java8/search/src/main/java/com/example/appengine/search/SearchOptionServlet.java b/appengine-java8/search/src/main/java/com/example/appengine/search/SearchOptionServlet.java index 15a8eb0a628..0edc90337b1 100644 --- a/appengine-java8/search/src/main/java/com/example/appengine/search/SearchOptionServlet.java +++ b/appengine-java8/search/src/main/java/com/example/appengine/search/SearchOptionServlet.java @@ -1,58 +1,57 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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.example.appengine.search; import com.google.appengine.api.search.Document; -import com.google.appengine.api.search.Index; - -// CHECKSTYLE:OFF -// @formatter:off -// [START search_option_import] import com.google.appengine.api.search.Field; +import com.google.appengine.api.search.Index; import com.google.appengine.api.search.IndexSpec; -import com.google.appengine.api.search.SearchServiceFactory; import com.google.appengine.api.search.Query; import com.google.appengine.api.search.QueryOptions; import com.google.appengine.api.search.Results; +import com.google.appengine.api.search.ScoredDocument; import com.google.appengine.api.search.SearchException; +import com.google.appengine.api.search.SearchServiceFactory; import com.google.appengine.api.search.SortExpression; import com.google.appengine.api.search.SortOptions; -import com.google.appengine.api.search.ScoredDocument; -// [END search_option_import] -// @formatter:on -// CHECKSTYLE:ON - import java.io.IOException; import java.io.PrintWriter; import java.util.logging.Logger; - import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +// CHECKSTYLE:OFF +// @formatter:off +// [START search_option_import] +// [END search_option_import] +// @formatter:on +// CHECKSTYLE:ON /** * Code snippet for searching with query options. */ @SuppressWarnings("serial") -@WebServlet(name = "searchOption", description = "Search: Get the Host Name", - urlPatterns = "/search/option") +@WebServlet( + name = "searchOption", + description = "Search: Get the Host Name", + urlPatterns = "/search/option" +) public class SearchOptionServlet extends HttpServlet { + private static final Logger LOG = Logger.getLogger(SearchOptionServlet.class.getSimpleName()); private static final String SEARCH_INDEX = "searchOptionIndex"; @@ -68,24 +67,28 @@ private Results doSearch() { // [START search_with_options] try { // Build the SortOptions with 2 sort keys - SortOptions sortOptions = SortOptions.newBuilder() - .addSortExpression(SortExpression.newBuilder() - .setExpression("price") - .setDirection(SortExpression.SortDirection.DESCENDING) - .setDefaultValueNumeric(0)) - .addSortExpression(SortExpression.newBuilder() - .setExpression("brand") - .setDirection(SortExpression.SortDirection.DESCENDING) - .setDefaultValue("")) - .setLimit(1000) - .build(); + SortOptions sortOptions = + SortOptions.newBuilder() + .addSortExpression( + SortExpression.newBuilder() + .setExpression("price") + .setDirection(SortExpression.SortDirection.DESCENDING) + .setDefaultValueNumeric(0)) + .addSortExpression( + SortExpression.newBuilder() + .setExpression("brand") + .setDirection(SortExpression.SortDirection.DESCENDING) + .setDefaultValue("")) + .setLimit(1000) + .build(); // Build the QueryOptions - QueryOptions options = QueryOptions.newBuilder() - .setLimit(25) - .setFieldsToReturn("model", "price", "description") - .setSortOptions(sortOptions) - .build(); + QueryOptions options = + QueryOptions.newBuilder() + .setLimit(25) + .setFieldsToReturn("model", "price", "description") + .setSortOptions(sortOptions) + .build(); // A query string String queryString = "product: coffee roaster AND price < 500"; @@ -104,18 +107,18 @@ private Results doSearch() { } @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Put one document to avoid an error - Document document = Document.newBuilder() - .setId("theOnlyCoffeeRoaster") - .addField(Field.newBuilder().setName("price").setNumber(200)) - .addField(Field.newBuilder().setName("model").setText("TZ4000")) - .addField(Field.newBuilder().setName("brand").setText("MyBrand")) - .addField(Field.newBuilder().setName("product").setText("coffee roaster")) - .addField(Field.newBuilder() - .setName("description").setText("A coffee bean roaster at home")) - .build(); + Document document = + Document.newBuilder() + .setId("theOnlyCoffeeRoaster") + .addField(Field.newBuilder().setName("price").setNumber(200)) + .addField(Field.newBuilder().setName("model").setText("TZ4000")) + .addField(Field.newBuilder().setName("brand").setText("MyBrand")) + .addField(Field.newBuilder().setName("product").setText("coffee roaster")) + .addField( + Field.newBuilder().setName("description").setText("A coffee bean roaster at home")) + .build(); try { Utils.indexADocument(SEARCH_INDEX, document); } catch (InterruptedException e) { diff --git a/appengine-java8/search/src/main/java/com/example/appengine/search/SearchServlet.java b/appengine-java8/search/src/main/java/com/example/appengine/search/SearchServlet.java index dd6197a0743..03df78995f9 100644 --- a/appengine-java8/search/src/main/java/com/example/appengine/search/SearchServlet.java +++ b/appengine-java8/search/src/main/java/com/example/appengine/search/SearchServlet.java @@ -1,16 +1,14 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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. */ @@ -20,32 +18,31 @@ // [START search_document_import] import com.google.appengine.api.search.Document; import com.google.appengine.api.search.Field; +import com.google.appengine.api.search.Index; +import com.google.appengine.api.search.IndexSpec; import com.google.appengine.api.search.Results; import com.google.appengine.api.search.ScoredDocument; import com.google.appengine.api.search.SearchException; -import com.google.appengine.api.search.StatusCode; -// [END search_document_import] - -// CHECKSTYLE:OFF -import com.google.appengine.api.search.Index; -import com.google.appengine.api.search.IndexSpec; import com.google.appengine.api.search.SearchServiceFactory; -// @formatter:on -// CHECKSTYLE:ON - +import com.google.appengine.api.search.StatusCode; import java.io.IOException; import java.io.PrintWriter; - import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +// [END search_document_import] +// CHECKSTYLE:OFF +// @formatter:on +// CHECKSTYLE:ON @SuppressWarnings("serial") -@WebServlet(name = "search", description = "Search: Search for a document", - urlPatterns = "/search/search") +@WebServlet( + name = "search", + description = "Search: Search for a document", + urlPatterns = "/search/search" +) public class SearchServlet extends HttpServlet { private static final String SEARCH_INDEX = "searchIndex"; @@ -57,15 +54,15 @@ private Index getIndex() { } @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); - Document doc = Document.newBuilder() - .setId("theOnlyPiano") - .addField(Field.newBuilder().setName("product").setText("piano")) - .addField(Field.newBuilder().setName("maker").setText("Yamaha")) - .addField(Field.newBuilder().setName("price").setNumber(4000)) - .build(); + Document doc = + Document.newBuilder() + .setId("theOnlyPiano") + .addField(Field.newBuilder().setName("product").setText("piano")) + .addField(Field.newBuilder().setName("maker").setText("Yamaha")) + .addField(Field.newBuilder().setName("price").setNumber(4000)) + .build(); try { Utils.indexADocument(SEARCH_INDEX, doc); } catch (InterruptedException e) { diff --git a/appengine-java8/search/src/main/java/com/example/appengine/search/Utils.java b/appengine-java8/search/src/main/java/com/example/appengine/search/Utils.java index 4fab0159303..93b93463b66 100644 --- a/appengine-java8/search/src/main/java/com/example/appengine/search/Utils.java +++ b/appengine-java8/search/src/main/java/com/example/appengine/search/Utils.java @@ -1,21 +1,21 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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.example.appengine.search; // [START index_import] + import com.google.appengine.api.search.Document; import com.google.appengine.api.search.Index; import com.google.appengine.api.search.IndexSpec; @@ -28,8 +28,10 @@ * A utility class for the search API sample. */ public class Utils { + /** * Put a given document into an index with the given indexName. + * * @param indexName The name of the index. * @param document A document to add. * @throws InterruptedException When Thread.sleep is interrupted. diff --git a/appengine-java8/search/src/test/java/com/example/appengine/search/DeleteServletTest.java b/appengine-java8/search/src/test/java/com/example/appengine/search/DeleteServletTest.java index 15b9deec1fb..f5f98061e2f 100644 --- a/appengine-java8/search/src/test/java/com/example/appengine/search/DeleteServletTest.java +++ b/appengine-java8/search/src/test/java/com/example/appengine/search/DeleteServletTest.java @@ -1,16 +1,14 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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. */ @@ -20,22 +18,24 @@ import static org.mockito.Mockito.when; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - public class DeleteServletTest { + private final LocalServiceTestHelper helper = new LocalServiceTestHelper(); - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private DeleteServlet servletUnderTest; @@ -63,4 +63,4 @@ public void doGet_successfulyInvoked() throws Exception { .named("DeleteServlet response") .contains("Deleted documents."); } -} \ No newline at end of file +} diff --git a/appengine-java8/search/src/test/java/com/example/appengine/search/DocumentServletTest.java b/appengine-java8/search/src/test/java/com/example/appengine/search/DocumentServletTest.java index 55bb6ed5350..995c5a9030c 100644 --- a/appengine-java8/search/src/test/java/com/example/appengine/search/DocumentServletTest.java +++ b/appengine-java8/search/src/test/java/com/example/appengine/search/DocumentServletTest.java @@ -1,16 +1,14 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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. */ @@ -21,22 +19,24 @@ import com.google.appengine.api.search.Document; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - public class DocumentServletTest { + private final LocalServiceTestHelper helper = new LocalServiceTestHelper(); - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private DocumentServlet servletUnderTest; @@ -64,12 +64,8 @@ public void doGet_successfulyInvoked() throws Exception { assertThat(content) .named("DocumentServlet response: coverLetter") .contains("coverLetter: CoverLetter"); - assertThat(content) - .named("DocumentServlet response: resume") - .contains("resume: "); - assertThat(content) - .named("DocumentServlet response: fullName") - .contains("fullName: Foo Bar"); + assertThat(content).named("DocumentServlet response: resume").contains("resume: "); + assertThat(content).named("DocumentServlet response: fullName").contains("fullName: Foo Bar"); assertThat(content) .named("DocumentServlet response: submissionDate") .contains("submissionDate: "); @@ -86,9 +82,7 @@ public void createDocument_withSignedInUser() throws Exception { assertThat(doc.getOnlyField("content").getText()) .named("content") .contains("the rain in spain"); - assertThat(doc.getOnlyField("email").getText()) - .named("email") - .isEqualTo(email); + assertThat(doc.getOnlyField("email").getText()).named("email").isEqualTo(email); } @Test @@ -98,8 +92,6 @@ public void createDocument_withoutSignedIn() throws Exception { assertThat(doc.getOnlyField("content").getText()) .named("content") .contains("the rain in spain"); - assertThat(doc.getOnlyField("email").getText()) - .named("email") - .isEmpty(); + assertThat(doc.getOnlyField("email").getText()).named("email").isEmpty(); } -} \ No newline at end of file +} diff --git a/appengine-java8/search/src/test/java/com/example/appengine/search/IndexServletTest.java b/appengine-java8/search/src/test/java/com/example/appengine/search/IndexServletTest.java index ce3a3eee55c..707d19e1c35 100644 --- a/appengine-java8/search/src/test/java/com/example/appengine/search/IndexServletTest.java +++ b/appengine-java8/search/src/test/java/com/example/appengine/search/IndexServletTest.java @@ -1,16 +1,14 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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. */ @@ -20,22 +18,24 @@ import static org.mockito.Mockito.when; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - public class IndexServletTest { + private final LocalServiceTestHelper helper = new LocalServiceTestHelper(); - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private IndexServlet servletUnderTest; @@ -63,4 +63,4 @@ public void doGet_successfulyInvoked() throws Exception { .named("IndexServlet response") .contains("myField: myValue"); } -} \ No newline at end of file +} diff --git a/appengine-java8/search/src/test/java/com/example/appengine/search/SchemaServletTest.java b/appengine-java8/search/src/test/java/com/example/appengine/search/SchemaServletTest.java index c5c459c55fa..ab556413714 100644 --- a/appengine-java8/search/src/test/java/com/example/appengine/search/SchemaServletTest.java +++ b/appengine-java8/search/src/test/java/com/example/appengine/search/SchemaServletTest.java @@ -1,16 +1,14 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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. */ @@ -20,22 +18,24 @@ import static org.mockito.Mockito.when; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - public class SchemaServletTest { + private final LocalServiceTestHelper helper = new LocalServiceTestHelper(); - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private SchemaServlet servletUnderTest; @@ -60,17 +60,9 @@ public void tearDown() { public void doGet_successfulyInvoked() throws Exception { servletUnderTest.doGet(mockRequest, mockResponse); String content = responseWriter.toString(); - assertThat(content) - .named("SchemaServlet response") - .contains("schemaIndex:maker:TEXT"); - assertThat(content) - .named("SchemaServlet response") - .contains("schemaIndex:price:NUMBER"); - assertThat(content) - .named("SchemaServlet response") - .contains("schemaIndex:color:TEXT"); - assertThat(content) - .named("SchemaServlet response") - .contains("schemaIndex:model:TEXT"); + assertThat(content).named("SchemaServlet response").contains("schemaIndex:maker:TEXT"); + assertThat(content).named("SchemaServlet response").contains("schemaIndex:price:NUMBER"); + assertThat(content).named("SchemaServlet response").contains("schemaIndex:color:TEXT"); + assertThat(content).named("SchemaServlet response").contains("schemaIndex:model:TEXT"); } -} \ No newline at end of file +} diff --git a/appengine-java8/search/src/test/java/com/example/appengine/search/SearchOptionServletTest.java b/appengine-java8/search/src/test/java/com/example/appengine/search/SearchOptionServletTest.java index ae055868e9e..851d8d076f3 100644 --- a/appengine-java8/search/src/test/java/com/example/appengine/search/SearchOptionServletTest.java +++ b/appengine-java8/search/src/test/java/com/example/appengine/search/SearchOptionServletTest.java @@ -1,16 +1,14 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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. */ @@ -20,22 +18,24 @@ import static org.mockito.Mockito.when; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - public class SearchOptionServletTest { + private final LocalServiceTestHelper helper = new LocalServiceTestHelper(); - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private SearchOptionServlet servletUnderTest; diff --git a/appengine-java8/search/src/test/java/com/example/appengine/search/SearchServletTest.java b/appengine-java8/search/src/test/java/com/example/appengine/search/SearchServletTest.java index a405b5a8693..2f7c3184235 100644 --- a/appengine-java8/search/src/test/java/com/example/appengine/search/SearchServletTest.java +++ b/appengine-java8/search/src/test/java/com/example/appengine/search/SearchServletTest.java @@ -1,16 +1,14 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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. */ @@ -20,22 +18,24 @@ import static org.mockito.Mockito.when; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; +import java.io.PrintWriter; +import java.io.StringWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.PrintWriter; -import java.io.StringWriter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - public class SearchServletTest { + private final LocalServiceTestHelper helper = new LocalServiceTestHelper(); - @Mock private HttpServletRequest mockRequest; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequest; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private SearchServlet servletUnderTest; @@ -60,11 +60,7 @@ public void tearDown() { public void doGet_successfulyInvoked() throws Exception { servletUnderTest.doGet(mockRequest, mockResponse); String content = responseWriter.toString(); - assertThat(content) - .named("SearchServlet response") - .contains("maker: Yamaha"); - assertThat(content) - .named("SearchServlet response") - .contains("price: 4000.0"); + assertThat(content).named("SearchServlet response").contains("maker: Yamaha"); + assertThat(content).named("SearchServlet response").contains("price: 4000.0"); } -} \ No newline at end of file +} diff --git a/appengine-java8/search/src/test/java/com/example/appengine/search/UtilsTest.java b/appengine-java8/search/src/test/java/com/example/appengine/search/UtilsTest.java index e3a3e58cf2a..5ff98c8dca7 100644 --- a/appengine-java8/search/src/test/java/com/example/appengine/search/UtilsTest.java +++ b/appengine-java8/search/src/test/java/com/example/appengine/search/UtilsTest.java @@ -1,16 +1,14 @@ /** * Copyright 2016 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 + *

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 + *

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 + *

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. */ @@ -28,8 +26,8 @@ import org.junit.Before; import org.junit.Test; - public class UtilsTest { + private static final String INDEX = "UtilsTestIndex"; private final LocalServiceTestHelper helper = new LocalServiceTestHelper(); @@ -46,10 +44,11 @@ public void tearDown() { @Test public void indexADocument_successfullyInvoked() throws Exception { String id = "test"; - Document doc = Document.newBuilder() - .setId(id) - .addField(Field.newBuilder().setName("f").setText("v")) - .build(); + Document doc = + Document.newBuilder() + .setId(id) + .addField(Field.newBuilder().setName("f").setText("v")) + .build(); Utils.indexADocument(INDEX, doc); // get the document by id IndexSpec indexSpec = IndexSpec.newBuilder().setName(INDEX).build(); @@ -59,4 +58,4 @@ public void indexADocument_successfullyInvoked() throws Exception { .named("A value of the fetched document") .isEqualTo("v"); } -} \ No newline at end of file +} diff --git a/appengine-java8/sendgrid/src/main/java/com/example/appengine/sendgrid/SendEmailServlet.java b/appengine-java8/sendgrid/src/main/java/com/example/appengine/sendgrid/SendEmailServlet.java index db086c739eb..0b918e89752 100644 --- a/appengine-java8/sendgrid/src/main/java/com/example/appengine/sendgrid/SendEmailServlet.java +++ b/appengine-java8/sendgrid/src/main/java/com/example/appengine/sendgrid/SendEmailServlet.java @@ -1,26 +1,22 @@ /** * Copyright 2015 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 + * 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. + * 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.example.appengine.sendgrid; import com.sendgrid.SendGrid; import com.sendgrid.SendGridException; - import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; diff --git a/appengine-java8/spanner/src/main/java/com/example/appengine/spanner/SpannerClient.java b/appengine-java8/spanner/src/main/java/com/example/appengine/spanner/SpannerClient.java index 8aa20f207d8..fc2b2becc87 100644 --- a/appengine-java8/spanner/src/main/java/com/example/appengine/spanner/SpannerClient.java +++ b/appengine-java8/spanner/src/main/java/com/example/appengine/spanner/SpannerClient.java @@ -11,6 +11,7 @@ * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.appengine.spanner; import com.google.cloud.spanner.DatabaseAdminClient; @@ -18,7 +19,6 @@ import com.google.cloud.spanner.DatabaseId; import com.google.cloud.spanner.Spanner; import com.google.cloud.spanner.SpannerOptions; - import java.io.IOException; import java.util.UUID; import javax.servlet.ServletContext; diff --git a/appengine-java8/spanner/src/main/java/com/example/appengine/spanner/SpannerTasks.java b/appengine-java8/spanner/src/main/java/com/example/appengine/spanner/SpannerTasks.java index 877cfdfcebd..b34637e2e0e 100644 --- a/appengine-java8/spanner/src/main/java/com/example/appengine/spanner/SpannerTasks.java +++ b/appengine-java8/spanner/src/main/java/com/example/appengine/spanner/SpannerTasks.java @@ -28,7 +28,6 @@ import com.google.cloud.spanner.Struct; import com.google.common.base.Stopwatch; import com.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata; - import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; @@ -54,7 +53,9 @@ enum Task { readOnlyTransaction } - /** Class to contain singer sample data. */ + /** + * Class to contain singer sample data. + */ static class Singer { final long singerId; @@ -68,7 +69,9 @@ static class Singer { } } - /** Class to contain album sample data. */ + /** + * Class to contain album sample data. + */ static class Album { final long singerId; diff --git a/appengine-java8/spanner/src/main/java/com/example/appengine/spanner/SpannerTasksServlet.java b/appengine-java8/spanner/src/main/java/com/example/appengine/spanner/SpannerTasksServlet.java index a8408771845..b684ef8c561 100644 --- a/appengine-java8/spanner/src/main/java/com/example/appengine/spanner/SpannerTasksServlet.java +++ b/appengine-java8/spanner/src/main/java/com/example/appengine/spanner/SpannerTasksServlet.java @@ -17,7 +17,6 @@ package com.example.appengine.spanner; import com.example.appengine.spanner.SpannerTasks.Task; - import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; @@ -33,21 +32,17 @@ * Example code for using the Cloud Spanner API. This example demonstrates all the common operations * that can be done on Cloud Spanner. These are: * - *

- * - *

+ *

* - * Individual tasks can be run using "tasks" query parameter. {@link SpannerTasks.Task} lists + *

Individual tasks can be run using "tasks" query parameter. {@link SpannerTasks.Task} lists * supported tasks. All tasks are run in order if no parameter or "tasks=all" is provided. */ // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. @WebServlet(value = "/spanner") public class SpannerTasksServlet extends HttpServlet { + @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { diff --git a/appengine-java8/taskqueues-deferred/src/main/java/com/google/cloud/taskqueue/samples/DeferSampleServlet.java b/appengine-java8/taskqueues-deferred/src/main/java/com/google/cloud/taskqueue/samples/DeferSampleServlet.java index 6e30e2c82eb..5f3cf3c880a 100644 --- a/appengine-java8/taskqueues-deferred/src/main/java/com/google/cloud/taskqueue/samples/DeferSampleServlet.java +++ b/appengine-java8/taskqueues-deferred/src/main/java/com/google/cloud/taskqueue/samples/DeferSampleServlet.java @@ -1,56 +1,51 @@ /** * Copyright 2015 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 + *

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 + *

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. + *

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. This package demonstrates how to use the task queue with Java. */ -/** - * This package demonstrates how to use the task queue with Java. - */ +/** This package demonstrates how to use the task queue with Java. */ + package com.google.cloud.taskqueue.samples; import com.google.appengine.api.taskqueue.DeferredTask; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; - import java.io.IOException; - import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** - * This small servlet demonstrates how to use the DeferredTask - * interface to background a task on the AppEngine task queues, - * without needing to create a separate URL handler. + * This small servlet demonstrates how to use the DeferredTask interface to background a task on the + * AppEngine task queues, without needing to create a separate URL handler. */ // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. -@WebServlet(name = "TasksDefer", description = "TaskQueues: Defer a task", - urlPatterns = "/taskqueues/defer") +@WebServlet( + name = "TasksDefer", + description = "TaskQueues: Defer a task", + urlPatterns = "/taskqueues/defer" +) public class DeferSampleServlet extends HttpServlet { - /** - * Number of ms long we will arbitrarily delay. - */ + /** Number of ms long we will arbitrarily delay. */ static final int DELAY_MS = 5000; //[START defer] - /** - * A hypothetical expensive operation we want to defer on a background task. - */ + + /** A hypothetical expensive operation we want to defer on a background task. */ public static class ExpensiveOperation implements DeferredTask { + @Override public void run() { System.out.println("Doing an expensive operation..."); @@ -60,18 +55,20 @@ public void run() { /** * Basic demonstration of adding a deferred task. + * * @param request servlet request * @param resp servlet response */ @Override - public void doGet(final HttpServletRequest request, - final HttpServletResponse resp) throws IOException { + public void doGet(final HttpServletRequest request, final HttpServletResponse resp) + throws IOException { // Add the task to the default queue. Queue queue = QueueFactory.getDefaultQueue(); // Wait 5 seconds to run for demonstration purposes - queue.add(TaskOptions.Builder.withPayload(new ExpensiveOperation()) - .etaMillis(System.currentTimeMillis() + DELAY_MS)); + queue.add( + TaskOptions.Builder.withPayload(new ExpensiveOperation()) + .etaMillis(System.currentTimeMillis() + DELAY_MS)); resp.setContentType("text/plain"); resp.getWriter().println("Task is backgrounded on queue!"); diff --git a/appengine-java8/taskqueues-pull/src/main/java/com/example/taskqueue/TaskqueueServlet.java b/appengine-java8/taskqueues-pull/src/main/java/com/example/taskqueue/TaskqueueServlet.java index 6055cd5e3de..a0a06d25656 100644 --- a/appengine-java8/taskqueues-pull/src/main/java/com/example/taskqueue/TaskqueueServlet.java +++ b/appengine-java8/taskqueues-pull/src/main/java/com/example/taskqueue/TaskqueueServlet.java @@ -1,16 +1,14 @@ /** * Copyright 2015 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 + *

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 + *

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 + *

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. */ @@ -20,7 +18,6 @@ import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskHandle; import com.google.appengine.api.taskqueue.TaskOptions; - import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; @@ -36,9 +33,13 @@ * add and delete tasks. */ // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. -@WebServlet(name = "TaskPull", description = "TaskQueues: Process some queues", - urlPatterns = "/taskqueues/queue") +@WebServlet( + name = "TaskPull", + description = "TaskQueues: Process some queues", + urlPatterns = "/taskqueues/queue" +) public class TaskqueueServlet extends HttpServlet { + private static final Logger log = Logger.getLogger(TaskqueueServlet.class.getName()); private static final int numberOfTasksToAdd = 100; private static final int numberOfTasksToLease = 100; @@ -48,12 +49,14 @@ public class TaskqueueServlet extends HttpServlet { // Process the http POST of the form @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, - ServletException { + public void doPost(HttpServletRequest req, HttpServletResponse resp) + throws IOException, ServletException { if (req.getParameter("addTask") != null) { String content = req.getParameter("content"); - String output = String.format("Adding %d Tasks to the Task Queue with a payload of '%s'", - numberOfTasksToAdd, content.toString()); + String output = + String.format( + "Adding %d Tasks to the Task Queue with a payload of '%s'", + numberOfTasksToAdd, content.toString()); log.info(output.toString()); // Add Tasks to Task Queue @@ -63,23 +66,24 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOEx if (!useTaggedTasks) { for (int i = 0; i < numberOfTasksToAdd; i++) { // [START add_task] - q.add(TaskOptions.Builder.withMethod(TaskOptions.Method.PULL) - .payload(content.toString())); + q.add( + TaskOptions.Builder.withMethod(TaskOptions.Method.PULL).payload(content.toString())); // [END add_task] } } else { for (int i = 0; i < numberOfTasksToAdd; i++) { // [START add_task_w_tag] - q.add(TaskOptions.Builder.withMethod(TaskOptions.Method.PULL) - .payload(content.toString()) - .tag("process".getBytes())); + q.add( + TaskOptions.Builder.withMethod(TaskOptions.Method.PULL) + .payload(content.toString()) + .tag("process".getBytes())); // [END add_task_w_tag] } } try { message = "Added " + numberOfTasksToAdd + " tasks to the task queue."; req.setAttribute("message", message); - req.getRequestDispatcher("taskqueues-pull.jsp").forward(req,resp); + req.getRequestDispatcher("taskqueues-pull.jsp").forward(req, resp); } catch (ServletException e) { throw new ServletException("ServletException error: ", e); } @@ -98,14 +102,14 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOEx } else { // [START lease_tasks_by_tag] // Lease only tasks tagged with "process" - List tasks = q.leaseTasksByTag(3600, TimeUnit.SECONDS, numberOfTasksToLease, - "process"); + List tasks = + q.leaseTasksByTag(3600, TimeUnit.SECONDS, numberOfTasksToLease, "process"); // You can also specify a tag to lease via LeaseOptions passed to leaseTasks. // [END lease_tasks_by_tag] message = processTasks(tasks, q); } req.setAttribute("message", message); - req.getRequestDispatcher("taskqueues-pull.jsp").forward(req,resp); + req.getRequestDispatcher("taskqueues-pull.jsp").forward(req, resp); } else { resp.sendRedirect("/"); } @@ -118,8 +122,10 @@ private static String processTasks(List tasks, Queue q) { int numberOfDeletedTasks = 0; for (TaskHandle task : tasks) { payload = new String(task.getPayload()); - output = String.format("Processing: taskName='%s' payload='%s'", task.getName() - .toString(), payload.toString()); + output = + String.format( + "Processing: taskName='%s' payload='%s'", + task.getName().toString(), payload.toString()); log.info(output.toString()); output = String.format("Deleting taskName='%s'", task.getName().toString()); log.info(output.toString()); @@ -129,8 +135,8 @@ private static String processTasks(List tasks, Queue q) { numberOfDeletedTasks++; } if (numberOfDeletedTasks > 0) { - message = "Processed and deleted " + numberOfTasksToLease + " tasks from the " - + " task queue."; + message = + "Processed and deleted " + numberOfTasksToLease + " tasks from the " + " task queue."; } else { message = "Task Queue has no tasks available for lease."; } diff --git a/appengine-java8/taskqueues-push/src/main/java/com/example/appengine/taskqueue/push/Enqueue.java b/appengine-java8/taskqueues-push/src/main/java/com/example/appengine/taskqueue/push/Enqueue.java index 4039e05c0c5..e52bb584f1d 100644 --- a/appengine-java8/taskqueues-push/src/main/java/com/example/appengine/taskqueue/push/Enqueue.java +++ b/appengine-java8/taskqueues-push/src/main/java/com/example/appengine/taskqueue/push/Enqueue.java @@ -12,34 +12,39 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.appengine.taskqueue.push; // [START import] + import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; -// [END import] - import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +// [END import] + // [START enqueue] // The Enqueue servlet should be mapped to the "/enqueue" URL. // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. -@WebServlet(name = "TaskEnque", description = "taskqueue: Enqueue a job with a key", - urlPatterns = "/taskqueues/enqueue") +@WebServlet( + name = "TaskEnque", + description = "taskqueue: Enqueue a job with a key", + urlPatterns = "/taskqueues/enqueue" +) public class Enqueue extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { String key = request.getParameter("key"); // Add the task to the default queue. - // [START addQueue] + // [START addQueue] Queue queue = QueueFactory.getDefaultQueue(); queue.add(TaskOptions.Builder.withUrl("/worker").param("key", key)); // [END addQueue] diff --git a/appengine-java8/taskqueues-push/src/main/java/com/example/appengine/taskqueue/push/Worker.java b/appengine-java8/taskqueues-push/src/main/java/com/example/appengine/taskqueue/push/Worker.java index 9902ee5f66a..76e12d75caf 100644 --- a/appengine-java8/taskqueues-push/src/main/java/com/example/appengine/taskqueue/push/Worker.java +++ b/appengine-java8/taskqueues-push/src/main/java/com/example/appengine/taskqueue/push/Worker.java @@ -12,11 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.appengine.taskqueue.push; import java.io.IOException; import java.util.logging.Logger; - import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @@ -26,13 +26,17 @@ // [START worker] // The Worker servlet should be mapped to the "/worker" URL. // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. -@WebServlet(name = "TaskWorker", description = "TaskQueues: worker", - urlPatterns = "/taskqueues/worker") +@WebServlet( + name = "TaskWorker", + description = "TaskQueues: worker", + urlPatterns = "/taskqueues/worker" +) public class Worker extends HttpServlet { + private static final Logger log = Logger.getLogger(Worker.class.getName()); protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { String key = request.getParameter("key"); // Do something with key. diff --git a/appengine-java8/taskqueues-push/src/test/java/com/example/appengine/taskqueue/push/WorkerTest.java b/appengine-java8/taskqueues-push/src/test/java/com/example/appengine/taskqueue/push/WorkerTest.java index 2d82e3ee69d..43a60cf2207 100644 --- a/appengine-java8/taskqueues-push/src/test/java/com/example/appengine/taskqueue/push/WorkerTest.java +++ b/appengine-java8/taskqueues-push/src/test/java/com/example/appengine/taskqueue/push/WorkerTest.java @@ -12,11 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.example.appengine.taskqueue.push; import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.when; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -25,18 +30,13 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * Unit tests for {@link Worker}. */ @RunWith(JUnit4.class) public class WorkerTest { - private static final String FAKE_KEY_VALUE = "KEY"; + + private static final String FAKE_KEY_VALUE = "KEY"; // To capture and restore stderr private final ByteArrayOutputStream stderr = new ByteArrayOutputStream(); @@ -74,6 +74,5 @@ public void doPost_writesResponse() throws Exception { // We expect a log message to be created // with the following message. assertThat(out).contains("Worker is processing " + FAKE_KEY_VALUE); - } } diff --git a/appengine-java8/twilio/src/main/java/com/example/appengine/twilio/ReceiveCallServlet.java b/appengine-java8/twilio/src/main/java/com/example/appengine/twilio/ReceiveCallServlet.java index 1e5aabda0cf..d3cfd1109ca 100644 --- a/appengine-java8/twilio/src/main/java/com/example/appengine/twilio/ReceiveCallServlet.java +++ b/appengine-java8/twilio/src/main/java/com/example/appengine/twilio/ReceiveCallServlet.java @@ -1,16 +1,14 @@ /** * Copyright 2015 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 + *

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 + *

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 + *

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. */ @@ -19,9 +17,7 @@ import com.twilio.sdk.verbs.Say; import com.twilio.sdk.verbs.TwiMLException; import com.twilio.sdk.verbs.TwiMLResponse; - import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -32,8 +28,8 @@ public class ReceiveCallServlet extends HttpServlet { @Override - public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException, - ServletException { + public void service(HttpServletRequest req, HttpServletResponse resp) + throws IOException, ServletException { TwiMLResponse twiml = new TwiMLResponse(); Say say = new Say("Hello from Twilio!"); try { diff --git a/appengine-java8/twilio/src/main/java/com/example/appengine/twilio/ReceiveSmsServlet.java b/appengine-java8/twilio/src/main/java/com/example/appengine/twilio/ReceiveSmsServlet.java index aa7bb6db308..7d889acf85b 100644 --- a/appengine-java8/twilio/src/main/java/com/example/appengine/twilio/ReceiveSmsServlet.java +++ b/appengine-java8/twilio/src/main/java/com/example/appengine/twilio/ReceiveSmsServlet.java @@ -1,16 +1,14 @@ /** * Copyright 2015 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 + *

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 + *

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 + *

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. */ @@ -19,9 +17,7 @@ import com.twilio.sdk.verbs.Message; import com.twilio.sdk.verbs.TwiMLException; import com.twilio.sdk.verbs.TwiMLResponse; - import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -32,8 +28,8 @@ public class ReceiveSmsServlet extends HttpServlet { @Override - public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, - ServletException { + public void service(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { String fromNumber = request.getParameter("From"); String body = request.getParameter("Body"); String message = String.format("Hello, %s, you said %s", fromNumber, body); diff --git a/appengine-java8/twilio/src/main/java/com/example/appengine/twilio/SendSmsServlet.java b/appengine-java8/twilio/src/main/java/com/example/appengine/twilio/SendSmsServlet.java index 6cb0c30a46e..5af258fdaaa 100644 --- a/appengine-java8/twilio/src/main/java/com/example/appengine/twilio/SendSmsServlet.java +++ b/appengine-java8/twilio/src/main/java/com/example/appengine/twilio/SendSmsServlet.java @@ -1,16 +1,14 @@ /** * Copyright 2015 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 + *

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 + *

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 + *

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. */ @@ -21,25 +19,23 @@ import com.twilio.sdk.resource.factory.MessageFactory; import com.twilio.sdk.resource.instance.Account; import com.twilio.sdk.resource.instance.Message; -import org.apache.http.NameValuePair; -import org.apache.http.message.BasicNameValuePair; - import java.io.IOException; import java.util.ArrayList; import java.util.List; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.http.NameValuePair; +import org.apache.http.message.BasicNameValuePair; // [START example] @SuppressWarnings("serial") public class SendSmsServlet extends HttpServlet { @Override - public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException, - ServletException { + public void service(HttpServletRequest req, HttpServletResponse resp) + throws IOException, ServletException { final String twilioAccountSid = System.getenv("TWILIO_ACCOUNT_SID"); final String twilioAuthToken = System.getenv("TWILIO_AUTH_TOKEN"); final String twilioNumber = System.getenv("TWILIO_NUMBER"); diff --git a/appengine-java8/urlfetch/src/main/java/com/example/appengine/UrlFetchServlet.java b/appengine-java8/urlfetch/src/main/java/com/example/appengine/UrlFetchServlet.java index 2419d7999e5..6ff3f0d0f0b 100644 --- a/appengine-java8/urlfetch/src/main/java/com/example/appengine/UrlFetchServlet.java +++ b/appengine-java8/urlfetch/src/main/java/com/example/appengine/UrlFetchServlet.java @@ -14,8 +14,6 @@ package com.example.appengine; -import org.json.JSONObject; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -23,24 +21,27 @@ import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; - import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.json.JSONObject; @SuppressWarnings("serial") // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. -@WebServlet(name = "URLFetch", description = "URLFetch: Write low order IP address to Cloud SQL", - urlPatterns = "/urlfetch") +@WebServlet( + name = "URLFetch", + description = "URLFetch: Write low order IP address to Cloud SQL", + urlPatterns = "/urlfetch" +) public class UrlFetchServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { -// [START example] + // [START example] URL url = new URL("http://api.icndb.com/jokes/random"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer json = new StringBuffer(); @@ -50,7 +51,7 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) json.append(line); } reader.close(); -// [END example] + // [END example] JSONObject jo = new JSONObject(json.toString()); req.setAttribute("joke", jo.getJSONObject("value").getString("joke")); @@ -70,11 +71,8 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) return; } - JSONObject jsonObj = new JSONObject() - .put("userId", 1) - .put("id", id) - .put("title", text) - .put("body", text); + JSONObject jsonObj = + new JSONObject().put("userId", 1).put("id", id).put("title", text).put("body", text); // [START complex] URL url = new URL("http://jsonplaceholder.typicode.com/posts/" + id); @@ -86,7 +84,7 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) writer.write(URLEncoder.encode(jsonObj.toString(), "UTF-8")); writer.close(); - int respCode = conn.getResponseCode(); // New items get NOT_FOUND on PUT + int respCode = conn.getResponseCode(); // New items get NOT_FOUND on PUT if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_NOT_FOUND) { req.setAttribute("error", ""); StringBuffer response = new StringBuffer(); @@ -104,5 +102,4 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) // [END complex] req.getRequestDispatcher("/urlfetchresult.jsp").forward(req, resp); } - } diff --git a/appengine-java8/users/src/main/java/com/example/appengine/users/UsersServlet.java b/appengine-java8/users/src/main/java/com/example/appengine/users/UsersServlet.java index a4b7e298d93..65f2aeba4a4 100644 --- a/appengine-java8/users/src/main/java/com/example/appengine/users/UsersServlet.java +++ b/appengine-java8/users/src/main/java/com/example/appengine/users/UsersServlet.java @@ -14,6 +14,7 @@ */ // [START users_API_example] + package com.example.appengine.users; import com.google.appengine.api.users.UserService; @@ -26,11 +27,12 @@ // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required. @WebServlet( - name = "UserAPI", - description = "UserAPI: Login / Logout with UserService", - urlPatterns = "/userapi" + name = "UserAPI", + description = "UserAPI: Login / Logout with UserService", + urlPatterns = "/userapi" ) public class UsersServlet extends HttpServlet { + @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { UserService userService = UserServiceFactory.getUserService(); diff --git a/appengine-java8/users/src/test/java/com/example/appengine/users/UsersServletTest.java b/appengine-java8/users/src/test/java/com/example/appengine/users/UsersServletTest.java index 5c2c7a7df31..4b001148790 100644 --- a/appengine-java8/users/src/test/java/com/example/appengine/users/UsersServletTest.java +++ b/appengine-java8/users/src/test/java/com/example/appengine/users/UsersServletTest.java @@ -33,17 +33,23 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -/** Unit tests for {@link UsersServlet}. */ +/** + * Unit tests for {@link UsersServlet}. + */ @RunWith(JUnit4.class) public class UsersServletTest { + private static final String FAKE_URL = "fakey.fake.fak"; private static final String FAKE_NAME = "Fake"; // Set up a helper so that the ApiProxy returns a valid environment for local testing. private final LocalServiceTestHelper helper = new LocalServiceTestHelper(); - @Mock private HttpServletRequest mockRequestNotLoggedIn; - @Mock private HttpServletRequest mockRequestLoggedIn; - @Mock private HttpServletResponse mockResponse; + @Mock + private HttpServletRequest mockRequestNotLoggedIn; + @Mock + private HttpServletRequest mockRequestLoggedIn; + @Mock + private HttpServletResponse mockResponse; private StringWriter responseWriter; private UsersServlet servletUnderTest; diff --git a/flexible/analytics/src/main/java/com/example/analytics/AnalyticsServlet.java b/flexible/analytics/src/main/java/com/example/analytics/AnalyticsServlet.java index 200b593bd31..2d0dbb4df4b 100644 --- a/flexible/analytics/src/main/java/com/example/analytics/AnalyticsServlet.java +++ b/flexible/analytics/src/main/java/com/example/analytics/AnalyticsServlet.java @@ -1,35 +1,30 @@ /** * Copyright 2015 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 + *

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 + *

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 + *

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.example.analytics; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.impl.client.HttpClientBuilder; - import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; - import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.impl.client.HttpClientBuilder; // [START example] @SuppressWarnings("serial") @@ -37,12 +32,15 @@ public class AnalyticsServlet extends HttpServlet { @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, - ServletException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) + throws IOException, ServletException { String trackingId = System.getenv("GA_TRACKING_ID"); HttpClient client = HttpClientBuilder.create().build(); URIBuilder builder = new URIBuilder(); - builder.setScheme("http").setHost("www.google-analytics.com").setPath("/collect") + builder + .setScheme("http") + .setHost("www.google-analytics.com") + .setPath("/collect") .addParameter("v", "1") // API Version. .addParameter("tid", trackingId) // Tracking ID / Property ID. // Anonymous Client Identifier. Ideally, this should be a UUID that diff --git a/pom.xml b/pom.xml index 3482228d356..8cec39abbd4 100644 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,7 @@ com.google.cloud.samples shared-configuration - 1.0.5 + 1.0.6