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 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 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 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 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 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 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 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 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,
- " 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 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 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 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 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 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 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:
*
- *
- *
- * 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 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 @@
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
+ *
- *
+ *
*
- * 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
+ *