");
-
- return;
- }
-
- Objectify ofy = ObjectifyService.ofy();
- Game game = null;
- String userId = userService.getCurrentUser().getUserId();
- if (gameKey != null) {
- game = ofy.load().type(Game.class).id(gameKey).safe();
- if (game.getUserO() == null && !userId.equals(game.getUserX())) {
- game.setUserO(userId);
- }
- ofy.save().entity(game).now();
- } else {
- game = new Game(userId, null, " ", true);
- ofy.save().entity(game).now();
- gameKey = game.getId();
- }
-
- //[START channel_service]
- ChannelService channelService = ChannelServiceFactory.getChannelService();
-
- // The 'Game' object exposes a method which creates a unique string based on the game's key
- // and the user's id.
- String token = channelService.createChannel(game.getChannelKey(userId));
-
- //[END channel_service]
-
- ofy.save().entity(game).now();
-
- req.setAttribute("game_key", gameKey);
- req.setAttribute("me", userId);
- req.setAttribute("token", token);
- req.setAttribute("initial_message", game.getMessageString());
- req.setAttribute("game_link", getGameUriWithGameParam(req, gameKey));
- getServletContext().getRequestDispatcher("/WEB-INF/view/index.jsp").forward(req, resp);
- }
-}
diff --git a/appengine/channel/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/channel/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index 9a27ea3b10c..00000000000
--- a/appengine/channel/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- YOUR-PROJECTID-HERE
- 1
- true
-
-
-
-
-
-
-
-
- channel_presence
-
-
-
-
diff --git a/appengine/channel/src/main/webapp/WEB-INF/logging.properties b/appengine/channel/src/main/webapp/WEB-INF/logging.properties
deleted file mode 100644
index f36a2ec76e0..00000000000
--- a/appengine/channel/src/main/webapp/WEB-INF/logging.properties
+++ /dev/null
@@ -1,27 +0,0 @@
-#
-# Copyright 2016 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-# A default java.util.logging configuration.
-# (All App Engine logging is through java.util.logging by default).
-#
-# To use this configuration, copy it into your application's WEB-INF
-# folder and add the following to your appengine-web.xml:
-#
-#
-#
-#
-#
-# Set the default logging level for all loggers to WARNING
-.level=WARNING
diff --git a/appengine/channel/src/main/webapp/WEB-INF/view/index.jsp b/appengine/channel/src/main/webapp/WEB-INF/view/index.jsp
deleted file mode 100644
index af33d85b7f9..00000000000
--- a/appengine/channel/src/main/webapp/WEB-INF/view/index.jsp
+++ /dev/null
@@ -1,276 +0,0 @@
-<%@ page contentType="text/html;charset=UTF-8" language="java" %>
-<%--
- Copyright 2015 Google Inc. All Rights Reserved.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
---%>
-
-
-
-
-
-
-
-
-
-
Channel-based Tic Tac Toe
-
- Waiting for another player to join.
- Send them this link to play:
-
-
-
diff --git a/appengine/channel/src/main/webapp/WEB-INF/web.xml b/appengine/channel/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index ea2d3e72f10..00000000000
--- a/appengine/channel/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,69 +0,0 @@
-
-
-
-
- TicTacToeServlet
- com.example.appengine.channel.TicTacToeServlet
-
-
- TicTacToeServlet
- /
-
-
- OpenedServlet
- com.example.appengine.channel.OpenedServlet
-
-
- OpenedServlet
- /opened
-
-
- MoveServlet
- com.example.appengine.channel.MoveServlet
-
-
- MoveServlet
- /move
-
-
- ChannelPresenceServlet
- com.example.appengine.channel.ChannelPresenceServlet
-
-
- ChannelPresenceServlet
- /_ah/channel/connected/
-
-
- ChannelPresenceServlet
- /_ah/channel/disconnected/
-
-
-
- ObjectifyFilter
- com.googlecode.objectify.ObjectifyFilter
-
-
- ObjectifyFilter
- /*
-
-
- com.example.appengine.channel.OfyHelper
-
-
diff --git a/appengine/cloudsql/README.md b/appengine/cloudsql/README.md
deleted file mode 100644
index bf8dbb101a5..00000000000
--- a/appengine/cloudsql/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Cloud SQL sample for Google App Engine
-This sample demonstrates how to use [Cloud SQL](https://cloud.google.com/sql/) on Google App Engine
-## Setup
-Before you can run or deploy the sample, you will need to create a [Cloud SQL instance](https://cloud.google.com/sql/docs/create-instance)
-1. Create a new user and database for the application. The easiest way to do this is via the [Google Developers Console](https://console.developers.google.com/project/_/sql/instances/example-instance2/access-control/users). Alternatively, you can use MySQL tools such as the command line client or workbench.
-## Running locally
-1. You will need to be running a local instance of MySQL.
-1. Update the connection string in ``appengine-web.xml`` with your local MySQL instance values.
- `$ mvn clean appengine:devserver`
-
-## Deploying
-1. Update the connection string in ``appengine-web.xml`` with your Cloud SQL instance values.
- `$ mvn clean appengine:update`
diff --git a/appengine/cloudsql/pom.xml b/appengine/cloudsql/pom.xml
deleted file mode 100644
index f1137faf70d..00000000000
--- a/appengine/cloudsql/pom.xml
+++ /dev/null
@@ -1,67 +0,0 @@
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
- com.example.appengine
- appengine-cloudsql
-
-
- doc-samples
- com.google.cloud
- 1.0.0
- ../..
-
-
-
-
- com.google.cloud.sql
- mysql-socket-factory
- 1.0.1
-
-
- javax.servlet
- javax.servlet-api
- 3.1.0
- jar
- provided
-
-
-
- mysql
- mysql-connector-java
- 6.0.3
-
-
-
- com.google.appengine
- appengine-api-1.0-sdk
-
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
-
-
diff --git a/appengine/cloudsql/src/main/java/com/example/appengine/cloudsql/CloudSqlServlet.java b/appengine/cloudsql/src/main/java/com/example/appengine/cloudsql/CloudSqlServlet.java
deleted file mode 100644
index ecd2c69f59e..00000000000
--- a/appengine/cloudsql/src/main/java/com/example/appengine/cloudsql/CloudSqlServlet.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/**
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine.cloudsql;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Timestamp;
-import java.util.Date;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-// [START example]
-@SuppressWarnings("serial")
-public class CloudSqlServlet extends HttpServlet {
-
- @Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
- ServletException {
- String path = req.getRequestURI();
- if (path.startsWith("/favicon.ico")) {
- return; // ignore the request for favicon.ico
- }
- // store only the first two octets of a users ip address
- String userIp = req.getRemoteAddr();
- InetAddress address = InetAddress.getByName(userIp);
- if (address instanceof Inet6Address) {
- // nest indexOf calls to find the second occurrence of a character in a string
- // an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf()
- userIp = userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
- } else if (address instanceof Inet4Address) {
- userIp = userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
- }
-
- final String createTableSql = "CREATE TABLE IF NOT EXISTS visits ( visit_id INT NOT NULL "
- + "AUTO_INCREMENT, user_ip VARCHAR(46) NOT NULL, timestamp DATETIME NOT NULL, "
- + "PRIMARY KEY (visit_id) )";
- final String createVisitSql = "INSERT INTO visits (user_ip, timestamp) VALUES (?, ?)";
- final String selectSql = "SELECT user_ip, timestamp FROM visits ORDER BY timestamp DESC "
- + "LIMIT 10";
- PrintWriter out = resp.getWriter();
- resp.setContentType("text/plain");
- String url;
- if (System
- .getProperty("com.google.appengine.runtime.version").startsWith("Google App Engine/")) {
- // Check the System properties to determine if we are running on appengine or not
- // Google App Engine sets a few system properties that will reliably be present on a remote
- // instance.
- url = System.getProperty("ae-cloudsql.cloudsql-database-url");
- try {
- // Load the class that provides the new "jdbc:google:mysql://" prefix.
- Class.forName("com.mysql.jdbc.GoogleDriver");
- } catch (ClassNotFoundException e) {
- throw new ServletException("Error loading Google JDBC Driver", e);
- }
- } else {
- // Set the url with the local MySQL database connection url when running locally
- url = System.getProperty("ae-cloudsql.local-database-url");
- }
- try (Connection conn = DriverManager.getConnection(url);
- PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) {
- conn.createStatement().executeUpdate(createTableSql);
- statementCreateVisit.setString(1, userIp);
- statementCreateVisit.setTimestamp(2, new Timestamp(new Date().getTime()));
- statementCreateVisit.executeUpdate();
-
- try (ResultSet rs = conn.prepareStatement(selectSql).executeQuery()) {
- out.print("Last 10 visits:\n");
- while (rs.next()) {
- String savedIp = rs.getString("user_ip");
- String timeStamp = rs.getString("timestamp");
- out.print("Time: " + timeStamp + " Addr: " + savedIp + "\n");
- }
- }
- } catch (SQLException e) {
- throw new ServletException("SQL error", e);
- }
- }
-}
-// [END example]
diff --git a/appengine/cloudsql/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/cloudsql/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index a801e60ea8a..00000000000
--- a/appengine/cloudsql/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
- YOUR-PROJECT-ID
- YOUR-VERSION-ID
- true
- true
-
-
-
-
-
-
diff --git a/appengine/cloudsql/src/main/webapp/WEB-INF/web.xml b/appengine/cloudsql/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 05375810dc6..00000000000
--- a/appengine/cloudsql/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-
-
-
-
-
-
- cloudsql
- com.example.appengine.cloudsql.CloudSqlServlet
-
-
- cloudsql
- /
-
-
diff --git a/appengine/datastore/README.md b/appengine/datastore/README.md
deleted file mode 100644
index c55fa65edb4..00000000000
--- a/appengine/datastore/README.md
+++ /dev/null
@@ -1,46 +0,0 @@
-# Google Cloud Datastore Sample
-
-This sample demonstrates how to use [Google Cloud Datastore][java-datastore]
-from [Google App Engine standard environment][ae-docs].
-
-[java-datastore]: https://cloud.google.com/appengine/docs/java/datastore/
-[ae-docs]: https://cloud.google.com/appengine/docs/java/
-
-
-## Running locally
-
-This example uses the
-[App Engine Maven plugin](https://cloud.google.com/appengine/docs/java/tools/maven).
-To run this sample locally:
-
- $ mvn appengine:devserver
-
-To see the results of the sample application, open
-[localhost:8080](http://localhost:8080) in a web browser.
-
-
-## Deploying
-
-In the following command, replace YOUR-PROJECT-ID with your
-[Google Cloud Project ID](https://developers.google.com/console/help/new/#projectnumber)
-and SOME-VERSION with a valid version number.
-
- $ mvn appengine:update -Dappengine.appId=YOUR-PROJECT-ID -Dappengine.version=SOME-VERSION
-
-
-## Setup
-
-To save your project settings so that you don't need to enter the
- parameters, you can:
-
-1. Update the `` tag in `src/main/webapp/WEB-INF/appengine-web.xml`
- with your project name.
-1. Update the `` tag in `src/main/webapp/WEB-INF/appengine-web.xml`
- with your version name.
-
-You will now be able to run
-
- $ mvn appengine:update
-
-without the need for any additional parameters.
-
diff --git a/appengine/datastore/geo/pom.xml b/appengine/datastore/geo/pom.xml
deleted file mode 100644
index c8aad9678d6..00000000000
--- a/appengine/datastore/geo/pom.xml
+++ /dev/null
@@ -1,94 +0,0 @@
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
- com.example.appengine
- appengine-datastore-geo
-
-
- com.google.cloud
- doc-samples
- 1.0.0
- ../../..
-
-
-
-
- com.google.appengine
- appengine-api-1.0-sdk
- ${appengine.sdk.version}
-
-
- javax.servlet
- servlet-api
- jar
- provided
-
-
-
-
- junit
- junit
- 4.12
- test
-
-
- org.mockito
- mockito-all
- 1.10.19
- test
-
-
- com.google.appengine
- appengine-testing
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-api-stubs
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-tools-sdk
- ${appengine.sdk.version}
- test
-
-
- com.google.truth
- truth
- 0.29
- test
-
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
-
-
diff --git a/appengine/datastore/geo/src/main/java/com/example/appengine/GeoServlet.java b/appengine/datastore/geo/src/main/java/com/example/appengine/GeoServlet.java
deleted file mode 100644
index 694e2107ef9..00000000000
--- a/appengine/datastore/geo/src/main/java/com/example/appengine/GeoServlet.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.FetchOptions;
-import com.google.appengine.api.datastore.GeoPt;
-import com.google.appengine.api.datastore.Query;
-import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
-import com.google.appengine.api.datastore.Query.Filter;
-import com.google.appengine.api.datastore.Query.FilterOperator;
-import com.google.appengine.api.datastore.Query.FilterPredicate;
-import com.google.appengine.api.datastore.Query.GeoRegion.Circle;
-import com.google.appengine.api.datastore.Query.GeoRegion.Rectangle;
-import com.google.appengine.api.datastore.Query.StContainsFilter;
-
-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 geospatial queries.
- */
-public class GeoServlet extends HttpServlet {
- static final String BRAND_PROPERTY = "brand";
- static final String LOCATION_PROPERTY = "location";
-
- static final String BRAND_PARAMETER = "brand";
- static final String LATITUDE_PARAMETER = "lat";
- static final String LONGITUDE_PARAMETER = "lon";
- static final String RADIUS_PARAMETER = "r";
-
- static final String BRAND_DEFAULT = "Ocean Ave Shell";
- static final String LATITUDE_DEFAULT = "37.7895873";
- static final String LONGITUDE_DEFAULT = "-122.3917317";
- static final String RADIUS_DEFAULT = "1000.0";
-
- // Number of meters (approximately) in 1 degree of latitude.
- // http://gis.stackexchange.com/a/2964
- private static final double DEGREE_METERS = 111111.0;
-
- private final DatastoreService datastore;
-
- public GeoServlet() {
- datastore = DatastoreServiceFactory.getDatastoreService();
- }
-
- private static String getParameterOrDefault(
- HttpServletRequest req, String parameter, String defaultValue) {
- String value = req.getParameter(parameter);
- if (value == null || value.isEmpty()) {
- value = defaultValue;
- }
- return value;
- }
-
- private static GeoPt getOffsetPoint(
- GeoPt original, double latOffsetMeters, double lonOffsetMeters) {
- // Approximate the number of degrees to offset by meters.
- // http://gis.stackexchange.com/a/2964
- // How long (approximately) is one degree of longitude?
- double lonDegreeMeters = DEGREE_METERS * Math.cos(original.getLatitude());
- return new GeoPt(
- (float) (original.getLatitude() + latOffsetMeters / DEGREE_METERS),
- // This may cause errors if given points near the north or south pole.
- (float) (original.getLongitude() + lonOffsetMeters / lonDegreeMeters));
- }
-
- @Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException, ServletException {
- resp.setContentType("text/plain");
- resp.setCharacterEncoding("UTF-8");
- PrintWriter out = resp.getWriter();
-
- String brand = getParameterOrDefault(req, BRAND_PARAMETER, BRAND_DEFAULT);
- String latStr = getParameterOrDefault(req, LATITUDE_PARAMETER, LATITUDE_DEFAULT);
- String lonStr = getParameterOrDefault(req, LONGITUDE_PARAMETER, LONGITUDE_DEFAULT);
- String radiusStr = getParameterOrDefault(req, RADIUS_PARAMETER, RADIUS_DEFAULT);
-
- float latitude;
- float longitude;
- double r;
- try {
- latitude = Float.parseFloat(latStr);
- longitude = Float.parseFloat(lonStr);
- r = Double.parseDouble(radiusStr);
- } catch (IllegalArgumentException e) {
- resp.sendError(
- HttpServletResponse.SC_BAD_REQUEST, String.format("Got bad value: %s", e.getMessage()));
- return;
- }
-
- // Get lat/lon for rectangle.
- GeoPt c = new GeoPt(latitude, longitude);
- GeoPt ne = getOffsetPoint(c, r, r);
- float neLat = ne.getLatitude();
- float neLon = ne.getLongitude();
- GeoPt sw = getOffsetPoint(c, -1 * r, -1 * r);
- float swLat = sw.getLatitude();
- float swLon = sw.getLongitude();
-
- // [START geospatial_stcontainsfilter_examples]
- // Testing for containment within a circle
- GeoPt center = new GeoPt(latitude, longitude);
- double radius = r; // Value is in meters.
- Filter f1 = new StContainsFilter("location", new Circle(center, radius));
- Query q1 = new Query("GasStation").setFilter(f1);
-
- // Testing for containment within a rectangle
- GeoPt southwest = new GeoPt(swLat, swLon);
- GeoPt northeast = new GeoPt(neLat, neLon);
- Filter f2 = new StContainsFilter("location", new Rectangle(southwest, northeast));
- Query q2 = new Query("GasStation").setFilter(f2);
- // [END geospatial_stcontainsfilter_examples]
-
- List circleResults = datastore.prepare(q1).asList(FetchOptions.Builder.withDefaults());
- out.printf("Got %d stations in %f meter radius circle.\n", circleResults.size(), radius);
- printStations(out, circleResults);
- out.println();
-
- List rectResults = datastore.prepare(q2).asList(FetchOptions.Builder.withDefaults());
- out.printf("Got %d stations in rectangle.\n", rectResults.size());
- printStations(out, rectResults);
- out.println();
-
- List brandResults = getStationsWithBrand(center, radius, brand);
- out.printf("Got %d stations in circle with brand %s.\n", brandResults.size(), brand);
- printStations(out, brandResults);
- out.println();
- }
-
- private void printStations(PrintWriter out, List stations) {
- for (Entity station : stations) {
- GeoPt location = (GeoPt) station.getProperty(LOCATION_PROPERTY);
- out.printf(
- "%s: @%f, %f\n",
- (String) station.getProperty(BRAND_PROPERTY),
- location.getLatitude(),
- location.getLongitude());
- }
- }
-
- private List getStationsWithBrand(GeoPt center, double radius, String value) {
- // [START geospatial_containment_and_equality_combination]
- Filter f =
- CompositeFilterOperator.and(
- new StContainsFilter("location", new Circle(center, radius)),
- new FilterPredicate("brand", FilterOperator.EQUAL, value));
- // [END geospatial_containment_and_equality_combination]
- Query q = new Query("GasStation").setFilter(f);
- return datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
- }
-}
diff --git a/appengine/datastore/geo/src/main/java/com/example/appengine/StartupServlet.java b/appengine/datastore/geo/src/main/java/com/example/appengine/StartupServlet.java
deleted file mode 100644
index 3a60b032730..00000000000
--- a/appengine/datastore/geo/src/main/java/com/example/appengine/StartupServlet.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.EntityNotFoundException;
-import com.google.appengine.api.datastore.GeoPt;
-import com.google.appengine.api.datastore.Key;
-import com.google.appengine.api.datastore.KeyFactory;
-
-import java.io.IOException;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * A startup handler to populate the datastore with example entities.
- */
-public class StartupServlet extends HttpServlet {
- static final String IS_POPULATED_ENTITY = "IsPopulated";
- static final String IS_POPULATED_KEY_NAME = "is-populated";
-
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- resp.setContentType("text/plain");
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
-
- Key isPopulatedKey = KeyFactory.createKey(IS_POPULATED_ENTITY, IS_POPULATED_KEY_NAME);
- boolean isAlreadyPopulated;
- try {
- datastore.get(isPopulatedKey);
- isAlreadyPopulated = true;
- } catch (EntityNotFoundException expected) {
- isAlreadyPopulated = false;
- }
- if (isAlreadyPopulated) {
- resp.getWriter().println("ok");
- return;
- }
-
- // [START create_entity_with_geopt_property]
- Entity station = new Entity("GasStation");
- station.setProperty("brand", "Ocean Ave Shell");
- station.setProperty("location", new GeoPt(37.7913156f, -122.3926051f));
- datastore.put(station);
- // [END create_entity_with_geopt_property]
-
- station = new Entity("GasStation");
- station.setProperty("brand", "Charge Point Charging Station");
- station.setProperty("location", new GeoPt(37.7909778f, -122.3929963f));
- datastore.put(station);
-
- station = new Entity("GasStation");
- station.setProperty("brand", "76");
- station.setProperty("location", new GeoPt(37.7860533f, -122.3940325f));
- datastore.put(station);
-
- datastore.put(new Entity(isPopulatedKey));
- resp.getWriter().println("ok");
- }
-}
diff --git a/appengine/datastore/geo/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/datastore/geo/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index e9d8b21cb8f..00000000000
--- a/appengine/datastore/geo/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-
-
-
- YOUR-PROJECT-ID
- YOUR-VERSION-ID
- true
-
diff --git a/appengine/datastore/geo/src/main/webapp/WEB-INF/datastore-indexes.xml b/appengine/datastore/geo/src/main/webapp/WEB-INF/datastore-indexes.xml
deleted file mode 100644
index 513b883ed78..00000000000
--- a/appengine/datastore/geo/src/main/webapp/WEB-INF/datastore-indexes.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/appengine/datastore/geo/src/main/webapp/WEB-INF/web.xml b/appengine/datastore/geo/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 12d26c6bcab..00000000000
--- a/appengine/datastore/geo/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,47 +0,0 @@
-
-
-
-
- geo
- com.example.appengine.GeoServlet
-
-
- geo
- /
-
-
- startup
- com.example.appengine.StartupServlet
-
-
- startup
- /_ah/start
-
-
-
-
- profile
- /*
-
-
- CONFIDENTIAL
-
-
-
diff --git a/appengine/datastore/geo/src/test/java/com/example/appengine/GeoServletTest.java b/appengine/datastore/geo/src/test/java/com/example/appengine/GeoServletTest.java
deleted file mode 100644
index 770126036bc..00000000000
--- a/appengine/datastore/geo/src/test/java/com/example/appengine/GeoServletTest.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-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 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 GeoServlet}.
- */
-@RunWith(JUnit4.class)
-public class GeoServletTest {
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
-
- @Mock private HttpServletRequest mockRequest;
- @Mock private HttpServletResponse mockResponse;
- private StringWriter responseWriter;
- private GeoServlet servletUnderTest;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- helper.setUp();
-
- // Set up a fake HTTP response.
- responseWriter = new StringWriter();
- when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter));
-
- servletUnderTest = new GeoServlet();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- @Test
- public void doGet_emptyDatastore_writesNoGasStations() throws Exception {
- servletUnderTest.doGet(mockRequest, mockResponse);
-
- assertThat(responseWriter.toString())
- .named("GeoServlet response")
- .contains("Got 0 stations");
- }
-
- @Test
- public void doGet_badRadius_returnsError() throws Exception {
- when(mockRequest.getParameter(GeoServlet.RADIUS_PARAMETER)).thenReturn("this-is-not-a-float");
-
- servletUnderTest.doGet(mockRequest, mockResponse);
-
- verify(mockResponse).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
- }
-}
diff --git a/appengine/datastore/geo/src/test/java/com/example/appengine/StartupServletTest.java b/appengine/datastore/geo/src/test/java/com/example/appengine/StartupServletTest.java
deleted file mode 100644
index d9c91af0efb..00000000000
--- a/appengine/datastore/geo/src/test/java/com/example/appengine/StartupServletTest.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.when;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.GeoPt;
-import com.google.appengine.api.datastore.Query;
-import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
-import com.google.appengine.api.datastore.Query.Filter;
-import com.google.appengine.api.datastore.Query.FilterOperator;
-import com.google.appengine.api.datastore.Query.FilterPredicate;
-import com.google.appengine.api.datastore.Query.GeoRegion.Circle;
-import com.google.appengine.api.datastore.Query.StContainsFilter;
-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 org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * Unit tests for {@link StartupServlet}.
- */
-@RunWith(JUnit4.class)
-public class StartupServletTest {
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(
- // Set no eventual consistency, that way queries return all results.
- // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(0));
-
- @Mock private HttpServletRequest mockRequest;
- @Mock private HttpServletResponse mockResponse;
- private StringWriter responseWriter;
- private DatastoreService datastore;
-
- private StartupServlet servletUnderTest;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- helper.setUp();
- datastore = DatastoreServiceFactory.getDatastoreService();
-
- // Set up a fake HTTP response.
- responseWriter = new StringWriter();
- when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter));
-
- servletUnderTest = new StartupServlet();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- @Test
- public void doGet_emptyDatastore_writesOkay() throws Exception {
- servletUnderTest.doGet(mockRequest, mockResponse);
- assertThat(responseWriter.toString()).named("StartupServlet response").isEqualTo("ok\n");
- }
-
- @Test
- public void doGet_emptyDatastore_writesGasStation() throws Exception {
- servletUnderTest.doGet(mockRequest, mockResponse);
-
- GeoPt center = new GeoPt(37.7895873f, -122.3917317f);
- double radius = 1000.0; // Radius in meters.
- String value = "Ocean Ave Shell";
- Filter f =
- CompositeFilterOperator.and(
- new StContainsFilter("location", new Circle(center, radius)),
- new FilterPredicate("brand", FilterOperator.EQUAL, value));
- Query q = new Query("GasStation").setFilter(f);
- Entity result = datastore.prepare(q).asSingleEntity();
- assertThat(result.getProperty("brand")).named("brand").isEqualTo("Ocean Ave Shell");
- }
-
- @Test
- public void doGet_alreadyPopulated_writesOkay() throws Exception {
- datastore.put(
- new Entity(StartupServlet.IS_POPULATED_ENTITY, StartupServlet.IS_POPULATED_KEY_NAME));
- servletUnderTest.doGet(mockRequest, mockResponse);
- assertThat(responseWriter.toString()).named("StartupServlet response").isEqualTo("ok\n");
- }
-}
diff --git a/appengine/datastore/indexes-exploding/pom.xml b/appengine/datastore/indexes-exploding/pom.xml
deleted file mode 100644
index c7798a1a994..00000000000
--- a/appengine/datastore/indexes-exploding/pom.xml
+++ /dev/null
@@ -1,94 +0,0 @@
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
- com.example.appengine
- appengine-datastore-indexes-exploding
-
-
- com.google.cloud
- doc-samples
- 1.0.0
- ../../..
-
-
-
-
- com.google.appengine
- appengine-api-1.0-sdk
- ${appengine.sdk.version}
-
-
- javax.servlet
- servlet-api
- jar
- provided
-
-
-
-
- junit
- junit
- 4.12
- test
-
-
- org.mockito
- mockito-all
- 1.10.19
- test
-
-
- com.google.appengine
- appengine-testing
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-api-stubs
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-tools-sdk
- ${appengine.sdk.version}
- test
-
-
- com.google.truth
- truth
- 0.29
- test
-
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
-
-
diff --git a/appengine/datastore/indexes-exploding/src/main/java/com/example/appengine/IndexesServlet.java b/appengine/datastore/indexes-exploding/src/main/java/com/example/appengine/IndexesServlet.java
deleted file mode 100644
index dff4396b797..00000000000
--- a/appengine/datastore/indexes-exploding/src/main/java/com/example/appengine/IndexesServlet.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-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.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.
- */
-public class IndexesServlet extends HttpServlet {
- private final DatastoreService datastore;
-
- public IndexesServlet() {
- datastore = DatastoreServiceFactory.getDatastoreService();
- }
-
- @Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException, ServletException {
- Query q =
- new Query("Widget")
- .setFilter(
- CompositeFilterOperator.and(
- new FilterPredicate("x", FilterOperator.EQUAL, 1),
- new FilterPredicate("y", FilterOperator.EQUAL, "red")))
- .addSort("date", Query.SortDirection.ASCENDING);
- List results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
-
- PrintWriter out = resp.getWriter();
- out.printf("Got %d widgets.\n", results.size());
- }
-}
diff --git a/appengine/datastore/indexes-exploding/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/datastore/indexes-exploding/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index e9d8b21cb8f..00000000000
--- a/appengine/datastore/indexes-exploding/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-
-
-
- YOUR-PROJECT-ID
- YOUR-VERSION-ID
- true
-
diff --git a/appengine/datastore/indexes-exploding/src/main/webapp/WEB-INF/datastore-indexes.xml b/appengine/datastore/indexes-exploding/src/main/webapp/WEB-INF/datastore-indexes.xml
deleted file mode 100644
index 52fb35e0520..00000000000
--- a/appengine/datastore/indexes-exploding/src/main/webapp/WEB-INF/datastore-indexes.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/appengine/datastore/indexes-exploding/src/main/webapp/WEB-INF/web.xml b/appengine/datastore/indexes-exploding/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 049fd7a05e7..00000000000
--- a/appengine/datastore/indexes-exploding/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-
-
-
-
- indexes-servlet
- com.example.appengine.IndexesServlet
-
-
- indexes-servlet
- /
-
-
-
-
- profile
- /*
-
-
- CONFIDENTIAL
-
-
-
diff --git a/appengine/datastore/indexes-exploding/src/test/java/com/example/appengine/IndexesServletTest.java b/appengine/datastore/indexes-exploding/src/test/java/com/example/appengine/IndexesServletTest.java
deleted file mode 100644
index 451f2189d34..00000000000
--- a/appengine/datastore/indexes-exploding/src/test/java/com/example/appengine/IndexesServletTest.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.when;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-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 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}.
- */
-@RunWith(JUnit4.class)
-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
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(0));
-
- @Mock private HttpServletRequest mockRequest;
- @Mock private HttpServletResponse mockResponse;
- private StringWriter responseWriter;
- private IndexesServlet servletUnderTest;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- helper.setUp();
-
- // Set up a fake HTTP response.
- responseWriter = new StringWriter();
- when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter));
-
- servletUnderTest = new IndexesServlet();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- @Test
- public void doGet_emptyDatastore_writesNoWidgets() throws Exception {
- servletUnderTest.doGet(mockRequest, mockResponse);
-
- assertThat(responseWriter.toString())
- .named("IndexesServlet response")
- .isEqualTo("Got 0 widgets.\n");
- }
-
- @Test
- public void doGet_repeatedPropertyEntities_writesWidgets() throws Exception {
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
- // [START exploding_index_example_3]
- Entity widget = new Entity("Widget");
- widget.setProperty("x", Arrays.asList(1, 2, 3, 4));
- widget.setProperty("y", Arrays.asList("red", "green", "blue"));
- widget.setProperty("date", new Date());
- datastore.put(widget);
- // [END exploding_index_example_3]
-
- servletUnderTest.doGet(mockRequest, mockResponse);
-
- assertThat(responseWriter.toString())
- .named("IndexesServlet response")
- .isEqualTo("Got 1 widgets.\n");
- }
-}
diff --git a/appengine/datastore/indexes-perfect/pom.xml b/appengine/datastore/indexes-perfect/pom.xml
deleted file mode 100644
index b3d83f59a19..00000000000
--- a/appengine/datastore/indexes-perfect/pom.xml
+++ /dev/null
@@ -1,94 +0,0 @@
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
- com.example.appengine
- appengine-datastore-indexes-perfect
-
-
- com.google.cloud
- doc-samples
- 1.0.0
- ../../..
-
-
-
-
- com.google.appengine
- appengine-api-1.0-sdk
- ${appengine.sdk.version}
-
-
- javax.servlet
- servlet-api
- jar
- provided
-
-
-
-
- junit
- junit
- 4.12
- test
-
-
- org.mockito
- mockito-all
- 1.10.19
- test
-
-
- com.google.appengine
- appengine-testing
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-api-stubs
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-tools-sdk
- ${appengine.sdk.version}
- test
-
-
- com.google.truth
- truth
- 0.29
- test
-
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
-
-
diff --git a/appengine/datastore/indexes-perfect/src/main/java/com/example/appengine/IndexesServlet.java b/appengine/datastore/indexes-perfect/src/main/java/com/example/appengine/IndexesServlet.java
deleted file mode 100644
index 0dbca3ce307..00000000000
--- a/appengine/datastore/indexes-perfect/src/main/java/com/example/appengine/IndexesServlet.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-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.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.
- */
-public class IndexesServlet extends HttpServlet {
- private final DatastoreService datastore;
-
- public IndexesServlet() {
- datastore = DatastoreServiceFactory.getDatastoreService();
- }
-
- @Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException, ServletException {
- PrintWriter out = resp.getWriter();
- // These queries should all work with the same index.
- // [START queries_and_indexes_example_1]
- Query q1 =
- new Query("Person")
- .setFilter(
- CompositeFilterOperator.and(
- new FilterPredicate("lastName", FilterOperator.EQUAL, "Smith"),
- new FilterPredicate("height", FilterOperator.EQUAL, 72)))
- .addSort("height", Query.SortDirection.DESCENDING);
- // [END queries_and_indexes_example_1]
- List r1 = datastore.prepare(q1).asList(FetchOptions.Builder.withDefaults());
- out.printf("Got %d results from query 1.\n", r1.size());
-
- // [START queries_and_indexes_example_2]
- Query q2 =
- new Query("Person")
- .setFilter(
- CompositeFilterOperator.and(
- new FilterPredicate("lastName", FilterOperator.EQUAL, "Jones"),
- new FilterPredicate("height", FilterOperator.EQUAL, 63)))
- .addSort("height", Query.SortDirection.DESCENDING);
- // [END queries_and_indexes_example_2]
- List r2 = datastore.prepare(q2).asList(FetchOptions.Builder.withDefaults());
- out.printf("Got %d results from query 2.\n", r2.size());
-
- // [START queries_and_indexes_example_3]
- Query q3 =
- new Query("Person")
- .setFilter(
- CompositeFilterOperator.and(
- new FilterPredicate("lastName", FilterOperator.EQUAL, "Friedkin"),
- new FilterPredicate("firstName", FilterOperator.EQUAL, "Damian")))
- .addSort("height", Query.SortDirection.ASCENDING);
- // [END queries_and_indexes_example_3]
- List r3 = datastore.prepare(q3).asList(FetchOptions.Builder.withDefaults());
- out.printf("Got %d results from query 3.\n", r3.size());
-
- // [START queries_and_indexes_example_4]
- Query q4 =
- new Query("Person")
- .setFilter(new FilterPredicate("lastName", FilterOperator.EQUAL, "Blair"))
- .addSort("firstName", Query.SortDirection.ASCENDING)
- .addSort("height", Query.SortDirection.ASCENDING);
- // [END queries_and_indexes_example_4]
- List r4 = datastore.prepare(q4).asList(FetchOptions.Builder.withDefaults());
- out.printf("Got %d results from query 4.\n", r4.size());
- }
-}
diff --git a/appengine/datastore/indexes-perfect/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/datastore/indexes-perfect/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index e9d8b21cb8f..00000000000
--- a/appengine/datastore/indexes-perfect/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-
-
-
- YOUR-PROJECT-ID
- YOUR-VERSION-ID
- true
-
diff --git a/appengine/datastore/indexes-perfect/src/main/webapp/WEB-INF/datastore-indexes.xml b/appengine/datastore/indexes-perfect/src/main/webapp/WEB-INF/datastore-indexes.xml
deleted file mode 100644
index bb56fb4bf50..00000000000
--- a/appengine/datastore/indexes-perfect/src/main/webapp/WEB-INF/datastore-indexes.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/appengine/datastore/indexes-perfect/src/main/webapp/WEB-INF/web.xml b/appengine/datastore/indexes-perfect/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 049fd7a05e7..00000000000
--- a/appengine/datastore/indexes-perfect/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-
-
-
-
- indexes-servlet
- com.example.appengine.IndexesServlet
-
-
- indexes-servlet
- /
-
-
-
-
- profile
- /*
-
-
- CONFIDENTIAL
-
-
-
diff --git a/appengine/datastore/indexes-perfect/src/test/java/com/example/appengine/IndexesServletTest.java b/appengine/datastore/indexes-perfect/src/test/java/com/example/appengine/IndexesServletTest.java
deleted file mode 100644
index e82f5b302ab..00000000000
--- a/appengine/datastore/indexes-perfect/src/test/java/com/example/appengine/IndexesServletTest.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.when;
-
-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 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}.
- */
-@RunWith(JUnit4.class)
-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
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(0));
-
- @Mock private HttpServletRequest mockRequest;
- @Mock private HttpServletResponse mockResponse;
- private StringWriter responseWriter;
- private IndexesServlet servletUnderTest;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- helper.setUp();
-
- // Set up a fake HTTP response.
- responseWriter = new StringWriter();
- when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter));
-
- servletUnderTest = new IndexesServlet();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- @Test
- public void doGet_emptyDatastore_writesNoWidgets() throws Exception {
- servletUnderTest.doGet(mockRequest, mockResponse);
-
- String response = responseWriter.toString();
- assertThat(response).contains("Got 0 results from query 1.");
- assertThat(response).contains("Got 0 results from query 2.");
- assertThat(response).contains("Got 0 results from query 3.");
- assertThat(response).contains("Got 0 results from query 4.");
- }
-}
diff --git a/appengine/datastore/indexes/pom.xml b/appengine/datastore/indexes/pom.xml
deleted file mode 100644
index 74ccaaabae8..00000000000
--- a/appengine/datastore/indexes/pom.xml
+++ /dev/null
@@ -1,94 +0,0 @@
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
- com.example.appengine
- appengine-datastore-indexes
-
-
- com.google.cloud
- doc-samples
- 1.0.0
- ../../..
-
-
-
-
- com.google.appengine
- appengine-api-1.0-sdk
- ${appengine.sdk.version}
-
-
- javax.servlet
- servlet-api
- jar
- provided
-
-
-
-
- junit
- junit
- 4.12
- test
-
-
- org.mockito
- mockito-all
- 1.10.19
- test
-
-
- com.google.appengine
- appengine-testing
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-api-stubs
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-tools-sdk
- ${appengine.sdk.version}
- test
-
-
- com.google.truth
- truth
- 0.29
- test
-
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
-
-
diff --git a/appengine/datastore/indexes/src/main/java/com/example/appengine/IndexesServlet.java b/appengine/datastore/indexes/src/main/java/com/example/appengine/IndexesServlet.java
deleted file mode 100644
index 78605f64bf2..00000000000
--- a/appengine/datastore/indexes/src/main/java/com/example/appengine/IndexesServlet.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-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.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.
- */
-public class IndexesServlet extends HttpServlet {
- private final DatastoreService datastore;
-
- public IndexesServlet() {
- datastore = DatastoreServiceFactory.getDatastoreService();
- }
-
- @Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException, ServletException {
- // [START exploding_index_example_1]
- Query q =
- new Query("Widget")
- .setFilter(
- CompositeFilterOperator.and(
- new FilterPredicate("x", FilterOperator.EQUAL, 1),
- new FilterPredicate("y", FilterOperator.EQUAL, 2)))
- .addSort("date", Query.SortDirection.ASCENDING);
- // [END exploding_index_example_1]
- List results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
-
- PrintWriter out = resp.getWriter();
- out.printf("Got %d widgets.\n", results.size());
- }
-}
diff --git a/appengine/datastore/indexes/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/datastore/indexes/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index e9d8b21cb8f..00000000000
--- a/appengine/datastore/indexes/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-
-
-
- YOUR-PROJECT-ID
- YOUR-VERSION-ID
- true
-
diff --git a/appengine/datastore/indexes/src/main/webapp/WEB-INF/datastore-indexes.xml b/appengine/datastore/indexes/src/main/webapp/WEB-INF/datastore-indexes.xml
deleted file mode 100644
index 2c7be706846..00000000000
--- a/appengine/datastore/indexes/src/main/webapp/WEB-INF/datastore-indexes.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/appengine/datastore/indexes/src/main/webapp/WEB-INF/web.xml b/appengine/datastore/indexes/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 049fd7a05e7..00000000000
--- a/appengine/datastore/indexes/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-
-
-
-
- indexes-servlet
- com.example.appengine.IndexesServlet
-
-
- indexes-servlet
- /
-
-
-
-
- profile
- /*
-
-
- CONFIDENTIAL
-
-
-
diff --git a/appengine/datastore/indexes/src/test/java/com/example/appengine/IndexesServletTest.java b/appengine/datastore/indexes/src/test/java/com/example/appengine/IndexesServletTest.java
deleted file mode 100644
index daf6e8f3821..00000000000
--- a/appengine/datastore/indexes/src/test/java/com/example/appengine/IndexesServletTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.when;
-
-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 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}.
- */
-@RunWith(JUnit4.class)
-public class IndexesServletTest {
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
-
- @Mock private HttpServletRequest mockRequest;
- @Mock private HttpServletResponse mockResponse;
- private StringWriter responseWriter;
- private IndexesServlet servletUnderTest;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- helper.setUp();
-
- // Set up a fake HTTP response.
- responseWriter = new StringWriter();
- when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter));
-
- servletUnderTest = new IndexesServlet();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- @Test
- public void doGet_emptyDatastore_writesNoWidgets() throws Exception {
- servletUnderTest.doGet(mockRequest, mockResponse);
-
- assertThat(responseWriter.toString())
- .named("IndexesServlet response")
- .isEqualTo("Got 0 widgets.\n");
- }
-}
diff --git a/appengine/datastore/pom.xml b/appengine/datastore/pom.xml
deleted file mode 100644
index 4c4a55607e8..00000000000
--- a/appengine/datastore/pom.xml
+++ /dev/null
@@ -1,117 +0,0 @@
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
- com.example.appengine
- appengine-datastore
-
-
- com.google.cloud
- doc-samples
- 1.0.0
- ../..
-
-
-
-
- com.google.appengine
- appengine-api-1.0-sdk
- ${appengine.sdk.version}
-
-
- com.google.auto.value
- auto-value
- 1.2
- provided
-
-
- com.google.code.findbugs
- jsr305
- 3.0.1
-
-
-
- com.google.guava
- guava
- 19.0
-
-
-
- javax.servlet
- servlet-api
- jar
- provided
-
-
- joda-time
- joda-time
- 2.9.4
-
-
-
-
- junit
- junit
- 4.12
- test
-
-
- org.mockito
- mockito-all
- 1.10.19
- test
-
-
- com.google.appengine
- appengine-testing
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-api-stubs
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-tools-sdk
- ${appengine.sdk.version}
- test
-
-
- com.google.truth
- truth
- 0.29
- test
-
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
-
-
diff --git a/appengine/datastore/src/main/java/com/example/appengine/AbstractGuestbook.java b/appengine/datastore/src/main/java/com/example/appengine/AbstractGuestbook.java
deleted file mode 100644
index a11707a8819..00000000000
--- a/appengine/datastore/src/main/java/com/example/appengine/AbstractGuestbook.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.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;
-import com.google.appengine.api.users.User;
-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;
-
-/**
- * A log of notes left by users.
- *
- *
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;
-
- AbstractGuestbook(Clock clock) {
- this.datastore = DatastoreServiceFactory.getDatastoreService();
- this.userService = UserServiceFactory.getUserService();
- this.clock = clock;
- }
-
- /**
- * 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));
- return greeting;
- }
-
- /**
- * Write a greeting to Datastore.
- */
- protected abstract Entity createGreeting(
- DatastoreService datastore, User user, Date date, String content);
-
- /**
- * Return a list of the most recent greetings.
- */
- public List listGreetings() {
- ImmutableList.Builder greetings = ImmutableList.builder();
- for (Entity entity : listGreetingEntities(datastore)) {
- greetings.add(Greeting.create(entity));
- }
- return greetings.build();
- }
-
- /**
- * Return a list of the most recent greetings.
- */
- protected abstract List listGreetingEntities(DatastoreService datastore);
-}
diff --git a/appengine/datastore/src/main/java/com/example/appengine/AbstractGuestbookServlet.java b/appengine/datastore/src/main/java/com/example/appengine/AbstractGuestbookServlet.java
deleted file mode 100644
index ba6f8c95ce9..00000000000
--- a/appengine/datastore/src/main/java/com/example/appengine/AbstractGuestbookServlet.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.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) {
- this.guestbook = guestbook;
- }
-
- private void renderGuestbook(HttpServletRequest req, HttpServletResponse resp)
- throws IOException, ServletException {
- resp.setContentType("text/html");
- resp.setCharacterEncoding("UTF-8");
- req.setAttribute("greetings", guestbook.listGreetings());
- req.getRequestDispatcher("/guestbook.jsp").forward(req, resp);
- }
-
- @Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException, ServletException {
- renderGuestbook(req, resp);
- }
-
- @Override
- public void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws IOException, ServletException {
- String content = req.getParameter("content");
- if (content == null || content.isEmpty()) {
- resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing content");
- return;
- }
- guestbook.appendGreeting(content);
- renderGuestbook(req, resp);
- }
-}
-
diff --git a/appengine/datastore/src/main/java/com/example/appengine/Greeting.java b/appengine/datastore/src/main/java/com/example/appengine/Greeting.java
deleted file mode 100644
index ad083267f05..00000000000
--- a/appengine/datastore/src/main/java/com/example/appengine/Greeting.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-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;
-
-@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");
- return new AutoValue_Greeting(user, date, content);
- }
-
- @Nullable
- public abstract User getUser();
-
- public abstract Instant getDate();
-
- public abstract String getContent();
-}
diff --git a/appengine/datastore/src/main/java/com/example/appengine/Guestbook.java b/appengine/datastore/src/main/java/com/example/appengine/Guestbook.java
deleted file mode 100644
index 36649c958fc..00000000000
--- a/appengine/datastore/src/main/java/com/example/appengine/Guestbook.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.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.
- */
-class Guestbook extends AbstractGuestbook {
- Guestbook(Clock clock) {
- super(clock);
- }
-
- @Override
- protected Entity createGreeting(
- DatastoreService datastore, User user, Date date, String content) {
- // No parent key specified, so Greeting is a root entity.
- Entity greeting = new Entity("Greeting");
- greeting.setProperty("user", user);
- greeting.setProperty("date", date);
- greeting.setProperty("content", content);
-
- datastore.put(greeting);
- return greeting;
- }
-
- @Override
- protected List listGreetingEntities(DatastoreService datastore) {
- Query query =
- new Query("Greeting")
- .addSort("date", Query.SortDirection.DESCENDING);
- return datastore.prepare(query)
- .asList(FetchOptions.Builder.withLimit(10));
- }
-
-
-}
diff --git a/appengine/datastore/src/main/java/com/example/appengine/GuestbookServlet.java b/appengine/datastore/src/main/java/com/example/appengine/GuestbookServlet.java
deleted file mode 100644
index 8c01d83cb09..00000000000
--- a/appengine/datastore/src/main/java/com/example/appengine/GuestbookServlet.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import com.example.time.SystemClock;
-
-public class GuestbookServlet extends AbstractGuestbookServlet {
- public GuestbookServlet() {
- super(new Guestbook(new SystemClock()));
- }
-}
diff --git a/appengine/datastore/src/main/java/com/example/appengine/GuestbookStrong.java b/appengine/datastore/src/main/java/com/example/appengine/GuestbookStrong.java
deleted file mode 100644
index 7c481556a81..00000000000
--- a/appengine/datastore/src/main/java/com/example/appengine/GuestbookStrong.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.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.Key;
-import com.google.appengine.api.datastore.KeyFactory;
-import com.google.appengine.api.datastore.Query;
-import com.google.appengine.api.users.User;
-
-import java.util.Date;
-import java.util.List;
-
-/**
- * A log of notes left by users.
- *
- *
This demonstrates the use of Google Cloud Datastore using the App Engine
- * APIs. See the
- * documentation
- * for more information.
- */
-class GuestbookStrong extends AbstractGuestbook {
- private final String guestbookName;
-
- GuestbookStrong(String guestbookName, Clock clock) {
- super(clock);
- this.guestbookName = guestbookName;
- }
-
- @Override
- protected Entity createGreeting(
- DatastoreService datastore, User user, Date date, String content) {
- // String guestbookName = "my guestbook"; -- Set elsewhere (injected to the constructor).
- Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName);
-
- // Place greeting in the same entity group as guestbook.
- Entity greeting = new Entity("Greeting", guestbookKey);
- greeting.setProperty("user", user);
- greeting.setProperty("date", date);
- greeting.setProperty("content", content);
-
- datastore.put(greeting);
- return greeting;
- }
-
- @Override
- protected List listGreetingEntities(DatastoreService datastore) {
- Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName);
- Query query =
- new Query("Greeting", guestbookKey)
- .setAncestor(guestbookKey)
- .addSort("date", Query.SortDirection.DESCENDING);
- return datastore.prepare(query)
- .asList(FetchOptions.Builder.withLimit(10));
- }
-}
diff --git a/appengine/datastore/src/main/java/com/example/appengine/GuestbookStrongServlet.java b/appengine/datastore/src/main/java/com/example/appengine/GuestbookStrongServlet.java
deleted file mode 100644
index 004584119fc..00000000000
--- a/appengine/datastore/src/main/java/com/example/appengine/GuestbookStrongServlet.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import com.example.time.SystemClock;
-
-public class GuestbookStrongServlet extends AbstractGuestbookServlet {
- public static final String GUESTBOOK_ID = "my guestbook";
-
- public GuestbookStrongServlet() {
- super(new GuestbookStrong(GUESTBOOK_ID, new SystemClock()));
- }
-}
diff --git a/appengine/datastore/src/main/java/com/example/appengine/ListPeopleServlet.java b/appengine/datastore/src/main/java/com/example/appengine/ListPeopleServlet.java
deleted file mode 100644
index 2da95898980..00000000000
--- a/appengine/datastore/src/main/java/com/example/appengine/ListPeopleServlet.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-// [START cursors]
-import com.google.appengine.api.datastore.Cursor;
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.FetchOptions;
-import com.google.appengine.api.datastore.PreparedQuery;
-import com.google.appengine.api.datastore.Query;
-import com.google.appengine.api.datastore.Query.SortDirection;
-import com.google.appengine.api.datastore.QueryResultList;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-public class ListPeopleServlet extends HttpServlet {
- static final int PAGE_SIZE = 15;
- private final DatastoreService datastore;
-
- public ListPeopleServlet() {
- datastore = DatastoreServiceFactory.getDatastoreService();
- }
-
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- FetchOptions fetchOptions = FetchOptions.Builder.withLimit(PAGE_SIZE);
-
- // If this servlet is passed a cursor parameter, let's use it.
- String startCursor = req.getParameter("cursor");
- if (startCursor != null) {
- fetchOptions.startCursor(Cursor.fromWebSafeString(startCursor));
- }
-
- Query q = new Query("Person").addSort("name", SortDirection.ASCENDING);
- PreparedQuery pq = datastore.prepare(q);
-
- QueryResultList results;
- try {
- results = pq.asQueryResultList(fetchOptions);
- } catch (IllegalArgumentException e) {
- // IllegalArgumentException happens when an invalid cursor is used.
- // A user could have manually entered a bad cursor in the URL or there
- // may have been an internal implementation detail change in App Engine.
- // Redirect to the page without the cursor parameter to show something
- // rather than an error.
- resp.sendRedirect("/people");
- return;
- }
-
- resp.setContentType("text/html");
- resp.setCharacterEncoding("UTF-8");
- PrintWriter w = resp.getWriter();
- w.println("");
- w.println("");
- w.println("Cloud Datastore Cursor Sample");
- w.println("
");
- for (Entity entity : results) {
- w.println("
" + entity.getProperty("name") + "
");
- }
- w.println("
");
-
- String cursorString = results.getCursor().toWebSafeString();
-
- // This servlet lives at '/people'.
- w.println("Next page");
- }
-}
-// [END cursors]
diff --git a/appengine/datastore/src/main/java/com/example/appengine/ProjectionServlet.java b/appengine/datastore/src/main/java/com/example/appengine/ProjectionServlet.java
deleted file mode 100644
index ffeff7d2d22..00000000000
--- a/appengine/datastore/src/main/java/com/example/appengine/ProjectionServlet.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.FetchOptions;
-import com.google.appengine.api.datastore.Key;
-import com.google.appengine.api.datastore.KeyFactory;
-import com.google.appengine.api.datastore.PropertyProjection;
-import com.google.appengine.api.datastore.Query;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.Date;
-import java.util.List;
-
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * Servlet to demonstrate use of Datastore projection queries.
- *
- *
See the
- * documentation
- * for using Datastore projection queries from the Google App Engine standard environment.
- */
-@SuppressWarnings("serial")
-public class ProjectionServlet extends HttpServlet {
- private static final String GUESTBOOK_ID = GuestbookStrongServlet.GUESTBOOK_ID;
- private final DatastoreService datastore;
-
- public ProjectionServlet() {
- datastore = DatastoreServiceFactory.getDatastoreService();
- }
-
- @Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
- resp.setContentType("text/plain");
- resp.setCharacterEncoding("UTF-8");
- PrintWriter out = resp.getWriter();
- out.printf("Latest entries from guestbook: \n");
-
- Key guestbookKey = KeyFactory.createKey("Guestbook", GUESTBOOK_ID);
- Query query = new Query("Greeting", guestbookKey);
- addGuestbookProjections(query);
- printGuestbookEntries(datastore, query, out);
- }
-
- private void addGuestbookProjections(Query query) {
- query.addProjection(new PropertyProjection("content", String.class));
- query.addProjection(new PropertyProjection("date", Date.class));
- }
-
- private void printGuestbookEntries(DatastoreService datastore, Query query, PrintWriter out) {
- List guests = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
- for (Entity guest : guests) {
- String content = (String) guest.getProperty("content");
- Date stamp = (Date) guest.getProperty("date");
- out.printf("Message %s posted on %s.\n", content, stamp.toString());
- }
- }
-}
diff --git a/appengine/datastore/src/main/java/com/example/appengine/StartupServlet.java b/appengine/datastore/src/main/java/com/example/appengine/StartupServlet.java
deleted file mode 100644
index 03fe99b3ea9..00000000000
--- a/appengine/datastore/src/main/java/com/example/appengine/StartupServlet.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.EntityNotFoundException;
-import com.google.appengine.api.datastore.Key;
-import com.google.appengine.api.datastore.KeyFactory;
-import com.google.common.collect.ImmutableList;
-
-import java.io.IOException;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * A startup handler to populate the datastore with example entities.
- */
-public class StartupServlet extends HttpServlet {
- static final String IS_POPULATED_ENTITY = "IsPopulated";
- static final String IS_POPULATED_KEY_NAME = "is-populated";
-
- private static final String PERSON_ENTITY = "Person";
- private static final String NAME_PROPERTY = "name";
- private static final ImmutableList US_PRESIDENTS =
- ImmutableList.builder()
- .add("George Washington")
- .add("John Adams")
- .add("Thomas Jefferson")
- .add("James Madison")
- .add("James Monroe")
- .add("John Quincy Adams")
- .add("Andrew Jackson")
- .add("Martin Van Buren")
- .add("William Henry Harrison")
- .add("John Tyler")
- .add("James K. Polk")
- .add("Zachary Taylor")
- .add("Millard Fillmore")
- .add("Franklin Pierce")
- .add("James Buchanan")
- .add("Abraham Lincoln")
- .add("Andrew Johnson")
- .add("Ulysses S. Grant")
- .add("Rutherford B. Hayes")
- .add("James A. Garfield")
- .add("Chester A. Arthur")
- .add("Grover Cleveland")
- .add("Benjamin Harrison")
- .add("Grover Cleveland")
- .add("William McKinley")
- .add("Theodore Roosevelt")
- .add("William Howard Taft")
- .add("Woodrow Wilson")
- .add("Warren G. Harding")
- .add("Calvin Coolidge")
- .add("Herbert Hoover")
- .add("Franklin D. Roosevelt")
- .add("Harry S. Truman")
- .add("Dwight D. Eisenhower")
- .add("John F. Kennedy")
- .add("Lyndon B. Johnson")
- .add("Richard Nixon")
- .add("Gerald Ford")
- .add("Jimmy Carter")
- .add("Ronald Reagan")
- .add("George H. W. Bush")
- .add("Bill Clinton")
- .add("George W. Bush")
- .add("Barack Obama")
- .build();
-
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- resp.setContentType("text/plain");
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
-
- Key isPopulatedKey = KeyFactory.createKey(IS_POPULATED_ENTITY, IS_POPULATED_KEY_NAME);
- boolean isAlreadyPopulated;
- try {
- datastore.get(isPopulatedKey);
- isAlreadyPopulated = true;
- } catch (EntityNotFoundException expected) {
- isAlreadyPopulated = false;
- }
- if (isAlreadyPopulated) {
- resp.getWriter().println("ok");
- return;
- }
-
- ImmutableList.Builder people = ImmutableList.builder();
- for (String name : US_PRESIDENTS) {
- Entity person = new Entity(PERSON_ENTITY);
- person.setProperty(NAME_PROPERTY, name);
- people.add(person);
- }
- datastore.put(people.build());
- datastore.put(new Entity(isPopulatedKey));
- resp.getWriter().println("ok");
- }
-}
diff --git a/appengine/datastore/src/main/java/com/example/appengine/StatsServlet.java b/appengine/datastore/src/main/java/com/example/appengine/StatsServlet.java
deleted file mode 100644
index 0b3585fd7b9..00000000000
--- a/appengine/datastore/src/main/java/com/example/appengine/StatsServlet.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.Query;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-public class StatsServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- // [START stat_example]
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
- Entity globalStat = datastore.prepare(new Query("__Stat_Total__")).asSingleEntity();
- Long totalBytes = (Long) globalStat.getProperty("bytes");
- Long totalEntities = (Long) globalStat.getProperty("count");
- // [END stat_example]
-
- resp.setContentType("text/plain");
- resp.setCharacterEncoding("UTF-8");
- PrintWriter w = resp.getWriter();
- w.printf("%d bytes\n%d entities\n", totalBytes, totalEntities);
- }
-}
-// [END cursors]
diff --git a/appengine/datastore/src/main/java/com/example/time/Clock.java b/appengine/datastore/src/main/java/com/example/time/Clock.java
deleted file mode 100644
index 60ee9a49d0c..00000000000
--- a/appengine/datastore/src/main/java/com/example/time/Clock.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.time;
-
-import org.joda.time.Instant;
-
-/**
- * Provides the current value of "now." To preserve testability, avoid all other libraries that
- * access the system clock (whether {@linkplain System#currentTimeMillis directly} or {@linkplain
- * org.joda.time.DateTime#DateTime() indirectly}).
- *
- *
In production, use the {@link SystemClock} implementation to return the "real" system time. In
- * tests, either use {@link com.example.time.testing.FakeClock}, or get an instance from a mocking
- * framework such as Mockito.
- */
-public interface Clock {
- /**
- * Returns the current, absolute time according to this clock.
- */
- Instant now();
-}
diff --git a/appengine/datastore/src/main/java/com/example/time/SystemClock.java b/appengine/datastore/src/main/java/com/example/time/SystemClock.java
deleted file mode 100644
index ecf15c34207..00000000000
--- a/appengine/datastore/src/main/java/com/example/time/SystemClock.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.time;
-
-import org.joda.time.Instant;
-
-/**
- * Clock implementation that returns the "real" system time.
- *
- *
This class exists so that we can use a fake implementation for unit
- * testing classes that need the current time value. See {@link Clock} for
- * general information about clocks.
- */
-public class SystemClock implements Clock {
- /**
- * Creates a new instance. All {@code SystemClock} instances function identically.
- */
- public SystemClock() {}
-
- @Override
- public Instant now() {
- return new Instant();
- }
-}
diff --git a/appengine/datastore/src/main/java/com/example/time/testing/FakeClock.java b/appengine/datastore/src/main/java/com/example/time/testing/FakeClock.java
deleted file mode 100644
index 5b05841e439..00000000000
--- a/appengine/datastore/src/main/java/com/example/time/testing/FakeClock.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.time.testing;
-
-import com.example.time.Clock;
-
-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.
- *
- *
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}.
- */
-public class FakeClock implements Clock {
- private static final Instant DEFAULT_TIME = new Instant(1000000000L);
- private final long baseTimeMs;
- private final AtomicLong fakeNowMs;
- private volatile long autoIncrementStepMs;
-
- /**
- * Creates a FakeClock instance initialized to an arbitrary constant.
- */
- public FakeClock() {
- this(DEFAULT_TIME);
- }
-
- /**
- * Creates a FakeClock instance initialized to the given time.
- */
- public FakeClock(ReadableInstant now) {
- baseTimeMs = now.getMillis();
- fakeNowMs = new AtomicLong(baseTimeMs);
- }
-
- /**
- * Sets the value of the underlying instance for testing purposes.
- *
- * @return this
- */
- public FakeClock setNow(ReadableInstant now) {
- fakeNowMs.set(now.getMillis());
- return this;
- }
-
- @Override
- public Instant now() {
- return getAndAdd(autoIncrementStepMs);
- }
-
- /**
- * 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.
- *
- * @return this
- */
- public FakeClock resetTime() {
- fakeNowMs.set(baseTimeMs);
- return this;
- }
-
- /**
- * Increments the clock time by the given duration.
- *
- * @param duration the duration to increment the clock time by
- * @return this
- */
- public FakeClock incrementTime(ReadableDuration duration) {
- incrementTime(duration.getMillis());
- return this;
- }
-
- /**
- * Increments the clock time by the given duration.
- *
- * @param durationMs the duration to increment the clock time by,
- * in milliseconds
- * @return this
- */
- public FakeClock incrementTime(long durationMs) {
- fakeNowMs.addAndGet(durationMs);
- return this;
- }
-
- /**
- * Decrements the clock time by the given duration.
- *
- * @param duration the duration to decrement the clock time by
- * @return this
- */
- public FakeClock decrementTime(ReadableDuration duration) {
- incrementTime(-duration.getMillis());
- return this;
- }
-
- /**
- * Decrements the clock time by the given duration.
- *
- * @param durationMs the duration to decrement the clock time by,
- * in milliseconds
- * @return this
- */
- public FakeClock decrementTime(long durationMs) {
- incrementTime(-durationMs);
- return this;
- }
-
- /**
- * 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
- */
- public FakeClock setAutoIncrementStep(ReadableDuration autoIncrementStep) {
- setAutoIncrementStep(autoIncrementStep.getMillis());
- return this;
- }
-
- /**
- * 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
- */
- public FakeClock setAutoIncrementStep(long autoIncrementStepMs) {
- this.autoIncrementStepMs = autoIncrementStepMs;
- return this;
- }
-
- /**
- * 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
- */
- protected final Instant addAndGet(long durationMs) {
- return new Instant(fakeNowMs.addAndGet(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
- */
- protected final Instant getAndAdd(long durationMs) {
- return new Instant(fakeNowMs.getAndAdd(durationMs));
- }
-}
diff --git a/appengine/datastore/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/datastore/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index c322e7d016e..00000000000
--- a/appengine/datastore/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
-
- YOUR-PROJECT-ID
- YOUR-VERSION-ID
- true
-
diff --git a/appengine/datastore/src/main/webapp/WEB-INF/datastore-indexes.xml b/appengine/datastore/src/main/webapp/WEB-INF/datastore-indexes.xml
deleted file mode 100644
index 662ebb0c35e..00000000000
--- a/appengine/datastore/src/main/webapp/WEB-INF/datastore-indexes.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
diff --git a/appengine/datastore/src/main/webapp/WEB-INF/web.xml b/appengine/datastore/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index babf6d1eeb6..00000000000
--- a/appengine/datastore/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,97 +0,0 @@
-
-
-
-
- guestbook-strong
- com.example.appengine.GuestbookStrongServlet
-
-
- guestbook-strong
- /
-
-
- guestbook
- com.example.appengine.GuestbookServlet
-
-
- guestbook
- /guestbook
-
-
- people
- com.example.appengine.ListPeopleServlet
-
-
- people
- /people
-
-
- projection
- com.example.appengine.ProjectionServlet
-
-
- projection
- /projection
-
-
- stats
- com.example.appengine.StatsServlet
-
-
- stats
- /stats
-
-
-
-
- startup
- com.example.appengine.StartupServlet
-
-
- startup
- /_ah/start
-
-
-
-
- profile
- /*
-
-
- CONFIDENTIAL
-
-
- *
-
-
-
-
-
- profile
- /stats
-
-
- CONFIDENTIAL
-
-
- admin
-
-
-
diff --git a/appengine/datastore/src/main/webapp/guestbook.jsp b/appengine/datastore/src/main/webapp/guestbook.jsp
deleted file mode 100644
index 0be736e697e..00000000000
--- a/appengine/datastore/src/main/webapp/guestbook.jsp
+++ /dev/null
@@ -1,45 +0,0 @@
-
-
-<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
-<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
-
-
-
-
-
-
diff --git a/appengine/datastore/src/test/java/com/example/appengine/EntitiesTest.java b/appengine/datastore/src/test/java/com/example/appengine/EntitiesTest.java
deleted file mode 100644
index 769b229491e..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/EntitiesTest.java
+++ /dev/null
@@ -1,364 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.fail;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.EmbeddedEntity;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.EntityNotFoundException;
-import com.google.appengine.api.datastore.Key;
-import com.google.appengine.api.datastore.KeyFactory;
-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;
-
-/**
- * Unit tests to demonstrate App Engine Datastore entities.
- */
-@RunWith(JUnit4.class)
-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
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(0));
-
- private DatastoreService datastore;
-
- @Before
- public void setUp() {
- helper.setUp();
- datastore = DatastoreServiceFactory.getDatastoreService();
- }
-
- @After
- public void tearDown() {
- helper.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);
-
- datastore.put(employee);
- // [END kind_example]
-
- Entity got = datastore.get(employee.getKey());
- assertThat((String) got.getProperty("firstName")).named("got.firstName").isEqualTo("Antonio");
- assertThat((String) got.getProperty("lastName")).named("got.lastName").isEqualTo("Salieri");
- assertThat((Date) got.getProperty("hireDate")).named("got.hireDate").isNotNull();
- assertThat((boolean) got.getProperty("attendedHrTraining"))
- .named("got.attendedHrTraining")
- .isTrue();
- }
-
- @Test
- public void identifiers_keyName_setsKeyName() throws Exception {
- // [START identifiers_1]
- Entity employee = new Entity("Employee", "asalieri");
- // [END identifiers_1]
- datastore.put(employee);
-
- assertThat(employee.getKey().getName()).named("key name").isEqualTo("asalieri");
- }
-
- @Test
- public void identifiers_autoId_setsUnallocatedId() throws Exception {
- KeyRange keys = datastore.allocateIds("Employee", 1);
- long usedId = keys.getStart().getId();
-
- // [START identifiers_2]
- Entity employee = new Entity("Employee");
- // [END identifiers_2]
- datastore.put(employee);
-
- assertThat(employee.getKey().getId()).named("key id").isNotEqualTo(usedId);
- }
-
- @Test
- public void parent_withinEntityConstructor_setsParent() throws Exception {
- // [START parent_1]
- Entity employee = new Entity("Employee");
- datastore.put(employee);
-
- Entity address = new Entity("Address", employee.getKey());
- datastore.put(address);
- // [END parent_1]
-
- assertThat(address.getParent()).named("address parent").isEqualTo(employee.getKey());
- }
-
- @Test
- public void parent_withKeyName_setsKeyName() throws Exception {
- Entity employee = new Entity("Employee");
- datastore.put(employee);
-
- // [START parent_2]
- Entity address = new Entity("Address", "addr1", employee.getKey());
- // [END parent_2]
- datastore.put(address);
-
- assertThat(address.getKey().getName()).named("address key name").isEqualTo("addr1");
- }
-
- @Test
- public void datastoreServiceFactory_returnsDatastoreService() throws Exception {
- // [START working_with_entities]
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
- // [END working_with_entities]
- assertThat(datastore).named("datastore").isNotNull();
- }
-
- @Test
- public void creatingAnEntity_withKeyName_writesEntity() throws Exception {
- // [START creating_an_entity_1]
- Entity employee = new Entity("Employee", "asalieri");
- // Set the entity properties.
- // ...
- datastore.put(employee);
- // [END creating_an_entity_1]
-
- assertThat(employee.getKey().getName()).named("employee key name").isEqualTo("asalieri");
- }
-
- private Key writeEmptyEmployee() {
- // [START creating_an_entity_2]
- Entity employee = new Entity("Employee");
- // Set the entity properties.
- // ...
- datastore.put(employee);
- // [END creating_an_entity_2]
- return employee.getKey();
- }
-
- @Test
- public void creatingAnEntity_withoutKeyName_writesEntity() throws Exception {
- Key employeeKey = writeEmptyEmployee();
- // [START retrieving_an_entity]
- // Key employeeKey = ...;
- Entity employee = datastore.get(employeeKey);
- // [END retrieving_an_entity]
-
- assertThat(employee.getKey().getId()).named("retrieved key ID").isEqualTo(employeeKey.getId());
- }
-
- @Test
- public void deletingAnEntity_deletesAnEntity() throws Exception {
- Entity employee = new Entity("Employee", "asalieri");
- datastore.put(employee);
-
- Key employeeKey = KeyFactory.createKey("Employee", "asalieri");
- // [START deleting_an_entity]
- // Key employeeKey = ...;
- datastore.delete(employeeKey);
- // [END deleting_an_entity]
-
- try {
- Entity got = datastore.get(employeeKey);
- fail("Expected EntityNotFoundException");
- } catch (EntityNotFoundException expected) {
- assertThat(expected.getKey().getName()).named("exception key name").isEqualTo("asalieri");
- }
- }
-
- @Test
- public void repeatedProperties_storesList() throws Exception {
- // [START repeated_properties]
- Entity employee = new Entity("Employee");
- ArrayList favoriteFruit = new ArrayList();
- favoriteFruit.add("Pear");
- favoriteFruit.add("Apple");
- employee.setProperty("favoriteFruit", favoriteFruit);
- datastore.put(employee);
-
- // Sometime later
- employee = datastore.get(employee.getKey());
- @SuppressWarnings("unchecked") // Cast can't verify generic type.
- ArrayList retrievedFruits = (ArrayList) employee.getProperty("favoriteFruit");
- // [END repeated_properties]
-
- assertThat(retrievedFruits).containsExactlyElementsIn(favoriteFruit).inOrder();
- }
-
- @Test
- public void embeddedEntity_fromEmbedded_embedsProperties() throws Exception {
- Entity employee = new Entity("Employee");
- // [START embedded_entities_1]
- // Entity employee = ...;
- EmbeddedEntity embeddedContactInfo = new EmbeddedEntity();
-
- embeddedContactInfo.setProperty("homeAddress", "123 Fake St, Made, UP 45678");
- embeddedContactInfo.setProperty("phoneNumber", "555-555-5555");
- embeddedContactInfo.setProperty("emailAddress", "test@example.com");
-
- employee.setProperty("contactInfo", embeddedContactInfo);
- // [END embedded_entities_1]
- datastore.put(employee);
-
- Entity gotEmployee = datastore.get(employee.getKey());
- EmbeddedEntity got = (EmbeddedEntity) gotEmployee.getProperty("contactInfo");
- assertThat((String) got.getProperty("homeAddress"))
- .named("got.homeAddress")
- .isEqualTo("123 Fake St, Made, UP 45678");
- }
-
- private Key putEmployeeWithContactInfo(Entity contactInfo) {
- Entity employee = new Entity("Employee");
- // [START embedded_entities_2]
- // Entity employee = ...;
- // Entity contactInfo = ...;
- EmbeddedEntity embeddedContactInfo = new EmbeddedEntity();
-
- embeddedContactInfo.setKey(contactInfo.getKey()); // Optional, used so we can recover original.
- embeddedContactInfo.setPropertiesFrom(contactInfo);
-
- employee.setProperty("contactInfo", embeddedContactInfo);
- // [END embedded_entities_2]
- datastore.put(employee);
- return employee.getKey();
- }
-
- @Test
- public void embeddedEntity_fromExisting_canRecover() throws Exception {
- Entity initialContactInfo = new Entity("Contact");
- initialContactInfo.setProperty("homeAddress", "123 Fake St, Made, UP 45678");
- initialContactInfo.setProperty("phoneNumber", "555-555-5555");
- initialContactInfo.setProperty("emailAddress", "test@example.com");
- datastore.put(initialContactInfo);
- Key employeeKey = putEmployeeWithContactInfo(initialContactInfo);
-
- // [START embedded_entities_3]
- Entity employee = datastore.get(employeeKey);
- EmbeddedEntity embeddedContactInfo = (EmbeddedEntity) employee.getProperty("contactInfo");
-
- Key infoKey = embeddedContactInfo.getKey();
- Entity contactInfo = new Entity(infoKey);
- contactInfo.setPropertiesFrom(embeddedContactInfo);
- // [END embedded_entities_3]
- datastore.put(contactInfo);
-
- Entity got = datastore.get(infoKey);
- assertThat(got.getKey()).isEqualTo(initialContactInfo.getKey());
- assertThat((String) got.getProperty("homeAddress"))
- .named("got.homeAddress")
- .isEqualTo("123 Fake St, Made, UP 45678");
- }
-
- @Test
- public void batchOperations_putsEntities() {
- // [START batch_operations]
- Entity employee1 = new Entity("Employee");
- Entity employee2 = new Entity("Employee");
- Entity employee3 = new Entity("Employee");
- // [START_EXCLUDE]
- employee1.setProperty("firstName", "Bill");
- employee2.setProperty("firstName", "Jane");
- employee3.setProperty("firstName", "Alex");
- // [END_EXCLUDE]
-
- List employees = Arrays.asList(employee1, employee2, employee3);
- datastore.put(employees);
- // [END batch_operations]
-
- Map got =
- datastore.get(Arrays.asList(employee1.getKey(), employee2.getKey(), employee3.getKey()));
- assertThat((String) got.get(employee1.getKey()).getProperty("firstName"))
- .named("employee1.firstName")
- .isEqualTo("Bill");
- assertThat((String) got.get(employee2.getKey()).getProperty("firstName"))
- .named("employee2.firstName")
- .isEqualTo("Jane");
- assertThat((String) got.get(employee3.getKey()).getProperty("firstName"))
- .named("employee3.firstName")
- .isEqualTo("Alex");
- }
-
- @Test
- public void createKey_makesKey() {
- // [START generating_keys_1]
- Key k1 = KeyFactory.createKey("Person", "GreatGrandpa");
- Key k2 = KeyFactory.createKey("Person", 74219);
- // [END generating_keys_1]
-
- assertThat(k1).isNotNull();
- assertThat(k2).isNotNull();
- }
-
- @Test
- public void keyFactoryBuilder_makeKeyWithParents() {
- Key greatKey = KeyFactory.createKey("Person", "GreatGrandpa");
- Key grandKey = KeyFactory.createKey(greatKey, "Person", "Grandpa");
- Key dadKey = KeyFactory.createKey(grandKey, "Person", "Dad");
- Key meKey = KeyFactory.createKey(dadKey, "Person", "Me");
-
- // [START generating_keys_2]
- Key k =
- new KeyFactory.Builder("Person", "GreatGrandpa")
- .addChild("Person", "Grandpa")
- .addChild("Person", "Dad")
- .addChild("Person", "Me")
- .getKey();
- // [END generating_keys_2]
-
- assertThat(k).isEqualTo(meKey);
- }
-
- @Test
- public void keyToString_getsPerson() throws Exception {
- Entity p = new Entity("Person");
- p.setProperty("relationship", "Me");
- datastore.put(p);
- Key k = p.getKey();
-
- // [START generating_keys_3]
- String personKeyStr = KeyFactory.keyToString(k);
-
- // Some time later (for example, after using personKeyStr in a link).
- Key personKey = KeyFactory.stringToKey(personKeyStr);
- Entity person = datastore.get(personKey);
- // [END generating_keys_3]
-
- assertThat(personKey).isEqualTo(k);
- assertThat((String) person.getProperty("relationship"))
- .named("person.relationship")
- .isEqualTo("Me");
- }
-}
diff --git a/appengine/datastore/src/test/java/com/example/appengine/GuestbookStrongTest.java b/appengine/datastore/src/test/java/com/example/appengine/GuestbookStrongTest.java
deleted file mode 100644
index abb845cacd4..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/GuestbookStrongTest.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.example.time.testing.FakeClock;
-
-import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
-import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
-import com.google.appengine.tools.development.testing.LocalUserServiceTestConfig;
-import org.joda.time.Instant;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-import java.util.List;
-
-/**
- * Unit tests for {@link GuestbookStrong}.
- */
-@RunWith(JUnit4.class)
-public class GuestbookStrongTest {
- private static final Instant FAKE_NOW = new Instant(1234567890L);
- private static final String GUESTBOOK_ID = "my guestbook";
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(
- // Set maximum eventual consistency.
- // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(100),
- // Make sure there is a user logged in. We enforce this in web.xml.
- new LocalUserServiceTestConfig())
- .setEnvIsLoggedIn(true)
- .setEnvEmail("test@example.com")
- .setEnvAuthDomain("gmail.com");
-
- private FakeClock clock;
- private GuestbookStrong guestbookUnderTest;
-
- @Before
- public void setUp() throws Exception {
- helper.setUp();
- clock = new FakeClock(FAKE_NOW);
- guestbookUnderTest = new GuestbookStrong(GUESTBOOK_ID, clock);
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- @Test
- public void appendGreeting_normalData_setsContentProperty() {
- Greeting got = guestbookUnderTest.appendGreeting("Hello, Datastore!");
-
- assertThat(got.getContent())
- .named("content property")
- .isEqualTo("Hello, Datastore!");
- }
-
- @Test
- public void appendGreeting_normalData_setsDateProperty() {
- Greeting got = guestbookUnderTest.appendGreeting("Hello, Datastore!");
-
- assertThat(got.getDate())
- .named("date property")
- .isEqualTo(FAKE_NOW);
- }
-
- @Test
- public void listGreetings_maximumEventualConsistency_returnsAllGreetings() {
- // Arrange
- guestbookUnderTest.appendGreeting("Hello, Datastore!");
- guestbookUnderTest.appendGreeting("Hello, Eventual Consistency!");
- guestbookUnderTest.appendGreeting("Hello, World!");
-
- // Act
- List got = guestbookUnderTest.listGreetings();
-
- // Assert
- // Since we use an ancestor query, all greetings should be available.
- assertThat(got).hasSize(3);
- }
-}
-
diff --git a/appengine/datastore/src/test/java/com/example/appengine/GuestbookTest.java b/appengine/datastore/src/test/java/com/example/appengine/GuestbookTest.java
deleted file mode 100644
index bc9d1de4afd..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/GuestbookTest.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.example.time.testing.FakeClock;
-
-import com.google.appengine.api.datastore.Key;
-import com.google.appengine.api.datastore.dev.HighRepJobPolicy;
-import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
-import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
-import com.google.appengine.tools.development.testing.LocalUserServiceTestConfig;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-import java.util.List;
-
-/**
- * Unit tests for {@link Guestbook}.
- */
-@RunWith(JUnit4.class)
-public class GuestbookTest {
- private static final class CustomHighRepJobPolicy implements HighRepJobPolicy {
- static int newJobCounter = 0;
- static int existingJobCounter = 0;
-
- @Override
- public boolean shouldApplyNewJob(Key entityGroup) {
- // Every other new job fails to apply.
- return newJobCounter++ % 2 == 0;
- }
-
- @Override
- public boolean shouldRollForwardExistingJob(Key entityGroup) {
- // Existing jobs always apply after every Get and every Query.
- return true;
- }
- }
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(
- // Set custom, deterministic, eventual consistency.
- // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests
- new LocalDatastoreServiceTestConfig()
- .setAlternateHighRepJobPolicyClass(CustomHighRepJobPolicy.class),
- // Make sure there is a user logged in. We enforce this in web.xml.
- new LocalUserServiceTestConfig())
- .setEnvIsLoggedIn(true)
- .setEnvEmail("test@example.com")
- .setEnvAuthDomain("gmail.com");
-
- private FakeClock clock;
- private Guestbook guestbookUnderTest;
-
- @Before
- public void setUp() throws Exception {
- helper.setUp();
- clock = new FakeClock();
- guestbookUnderTest = new Guestbook(clock);
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- @Test
- public void appendGreeting_normalData_setsContentProperty() {
- Greeting got = guestbookUnderTest.appendGreeting("Hello, Datastore!");
-
- assertThat(got.getContent())
- .named("content property")
- .isEqualTo("Hello, Datastore!");
- }
-
- @Test
- public void listGreetings_eventualConsistency_returnsPartialGreetings() {
- // Arrange
- guestbookUnderTest.appendGreeting("Hello, Datastore!");
- guestbookUnderTest.appendGreeting("Hello, Eventual Consistency!");
- guestbookUnderTest.appendGreeting("Hello, World!");
- guestbookUnderTest.appendGreeting("Güten Tag!");
-
- // Act
- List got = guestbookUnderTest.listGreetings();
-
- // The first time we query we should half of the results due to the fact that we simulate
- // eventual consistency by applying every other write.
- assertThat(got).hasSize(2);
- }
-
- @Test
- public void listGreetings_groomedDatastore_returnsAllGreetings() {
- // Arrange
- guestbookUnderTest.appendGreeting("Hello, Datastore!");
- guestbookUnderTest.appendGreeting("Hello, Eventual Consistency!");
- guestbookUnderTest.appendGreeting("Hello, World!");
-
- // Act
- guestbookUnderTest.listGreetings();
- // Second global query sees both Entities because we "groom" (attempt to
- // apply unapplied jobs) after every query.
- List got = guestbookUnderTest.listGreetings();
-
- assertThat(got).hasSize(3);
- }
-}
diff --git a/appengine/datastore/src/test/java/com/example/appengine/IndexesTest.java b/appengine/datastore/src/test/java/com/example/appengine/IndexesTest.java
deleted file mode 100644
index a12912c43d0..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/IndexesTest.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.FetchOptions;
-import com.google.appengine.api.datastore.Key;
-import com.google.appengine.api.datastore.KeyFactory;
-import com.google.appengine.api.datastore.Query;
-import com.google.appengine.api.datastore.Query.Filter;
-import com.google.appengine.api.datastore.Query.FilterOperator;
-import com.google.appengine.api.datastore.Query.FilterPredicate;
-import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
-import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-import java.util.List;
-
-/**
- * Unit tests to demonstrate App Engine Datastore queries.
- */
-@RunWith(JUnit4.class)
-public class IndexesTest {
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(
- // Set no eventual consistency, that way queries return all results.
- // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(0));
-
- private DatastoreService datastore;
-
- @Before
- public void setUp() {
- helper.setUp();
- datastore = DatastoreServiceFactory.getDatastoreService();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- @Test
- public void propertyFilterExample_returnsMatchingEntities() throws Exception {
- // [START unindexed_properties_1]
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
-
- Key acmeKey = KeyFactory.createKey("Company", "Acme");
-
- Entity tom = new Entity("Person", "Tom", acmeKey);
- tom.setProperty("name", "Tom");
- tom.setProperty("age", 32);
- datastore.put(tom);
-
- Entity lucy = new Entity("Person", "Lucy", acmeKey);
- lucy.setProperty("name", "Lucy");
- lucy.setUnindexedProperty("age", 29);
- datastore.put(lucy);
-
- Filter ageFilter = new FilterPredicate("age", FilterOperator.GREATER_THAN, 25);
-
- Query q = new Query("Person").setAncestor(acmeKey).setFilter(ageFilter);
-
- // Returns tom but not lucy, because her age is unindexed
- List results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
- // [END unindexed_properties_1]
-
- assertThat(results).named("query results").containsExactly(tom);
- }
-}
diff --git a/appengine/datastore/src/test/java/com/example/appengine/ListPeopleServletTest.java b/appengine/datastore/src/test/java/com/example/appengine/ListPeopleServletTest.java
deleted file mode 100644
index b1f33bbf3f9..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/ListPeopleServletTest.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.FetchOptions;
-import com.google.appengine.api.datastore.PreparedQuery;
-import com.google.appengine.api.datastore.Query;
-import com.google.appengine.api.datastore.Query.SortDirection;
-import com.google.appengine.api.datastore.QueryResultList;
-import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
-import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
-import com.google.common.collect.ImmutableList;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * Unit tests for {@link ListPeopleServlet}.
- */
-@RunWith(JUnit4.class)
-public class ListPeopleServletTest {
- private static final ImmutableList TEST_NAMES =
- // Keep in alphabetical order, so this is the same as the query order.
- ImmutableList.builder()
- .add("Alpha")
- .add("Bravo")
- .add("Charlie")
- .add("Delta")
- .add("Echo")
- .add("Foxtrot")
- .add("Golf")
- .add("Hotel")
- .add("India")
- .add("Juliett")
- .add("Kilo")
- .add("Lima")
- .add("Mike")
- .add("November")
- .add("Oscar")
- .add("Papa")
- .add("Quebec")
- .add("Romeo")
- .add("Sierra")
- .add("Tango")
- .build();
-
- 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
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(0));
-
- @Mock private HttpServletRequest mockRequest;
- @Mock private HttpServletResponse mockResponse;
- private StringWriter responseWriter;
- private DatastoreService datastore;
-
- private ListPeopleServlet servletUnderTest;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- helper.setUp();
- datastore = DatastoreServiceFactory.getDatastoreService();
-
- // Add test data.
- ImmutableList.Builder people = ImmutableList.builder();
- for (String name : TEST_NAMES) {
- people.add(createPerson(name));
- }
- datastore.put(people.build());
-
- // Set up a fake HTTP response.
- responseWriter = new StringWriter();
- when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter));
-
- servletUnderTest = new ListPeopleServlet();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- private Entity createPerson(String name) {
- Entity person = new Entity("Person");
- person.setProperty("name", name);
- return person;
- }
-
- @Test
- public void doGet_noCursor_writesNames() throws Exception {
- servletUnderTest.doGet(mockRequest, mockResponse);
-
- String response = responseWriter.toString();
- for (int i = 0; i < ListPeopleServlet.PAGE_SIZE; i++) {
- assertThat(response).named("ListPeopleServlet response").contains(TEST_NAMES.get(i));
- }
- }
-
- private String getFirstCursor() {
- Query q = new Query("Person").addSort("name", SortDirection.ASCENDING);
- PreparedQuery pq = datastore.prepare(q);
- FetchOptions fetchOptions = FetchOptions.Builder.withLimit(ListPeopleServlet.PAGE_SIZE);
- QueryResultList results = pq.asQueryResultList(fetchOptions);
- return results.getCursor().toWebSafeString();
- }
-
- @Test
- public void doGet_withValidCursor_writesNames() throws Exception {
- when(mockRequest.getParameter("cursor")).thenReturn(getFirstCursor());
-
- servletUnderTest.doGet(mockRequest, mockResponse);
-
- String response = responseWriter.toString();
- int i = 0;
- while (i + ListPeopleServlet.PAGE_SIZE < TEST_NAMES.size() && i < ListPeopleServlet.PAGE_SIZE) {
- assertThat(response)
- .named("ListPeopleServlet response")
- .contains(TEST_NAMES.get(i + ListPeopleServlet.PAGE_SIZE));
- i++;
- }
- }
-
- @Test
- public void doGet_withInvalidCursor_writesRedirect() throws Exception {
- when(mockRequest.getParameter("cursor")).thenReturn("ThisCursorIsTotallyInvalid");
- servletUnderTest.doGet(mockRequest, mockResponse);
- verify(mockResponse).sendRedirect("/people");
- }
-}
diff --git a/appengine/datastore/src/test/java/com/example/appengine/MetadataEntityGroupTest.java b/appengine/datastore/src/test/java/com/example/appengine/MetadataEntityGroupTest.java
deleted file mode 100644
index a39f4af36ca..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/MetadataEntityGroupTest.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entities;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.EntityNotFoundException;
-import com.google.appengine.api.datastore.FetchOptions;
-import com.google.appengine.api.datastore.Key;
-import com.google.appengine.api.datastore.PreparedQuery;
-import com.google.appengine.api.datastore.Query;
-import com.google.appengine.api.datastore.Transaction;
-import com.google.appengine.api.memcache.MemcacheService;
-import com.google.appengine.api.memcache.MemcacheServiceFactory;
-import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
-import com.google.appengine.tools.development.testing.LocalMemcacheServiceTestConfig;
-import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-import java.io.PrintWriter;
-import java.io.Serializable;
-import java.io.StringWriter;
-
-/**
- * Unit tests to demonstrate App Engine Datastore entity group metadata.
- */
-@RunWith(JUnit4.class)
-public class MetadataEntityGroupTest {
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(
- // Set no eventual consistency, that way queries return all results.
- // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests
- new LocalDatastoreServiceTestConfig().setDefaultHighRepJobPolicyUnappliedJobPercentage(0),
- new LocalMemcacheServiceTestConfig());
-
- private DatastoreService datastore;
-
- @Before
- public void setUp() {
- helper.setUp();
- datastore = DatastoreServiceFactory.getDatastoreService();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- // [START entity_group_1]
- private static long getEntityGroupVersion(DatastoreService ds, Transaction tx, Key entityKey) {
- try {
- return Entities.getVersionProperty(ds.get(tx, Entities.createEntityGroupKey(entityKey)));
- } catch (EntityNotFoundException e) {
- // No entity group information, return a value strictly smaller than any
- // possible version
- return 0;
- }
- }
-
- private static void printEntityGroupVersions(DatastoreService ds, PrintWriter writer) {
- Entity entity1 = new Entity("Simple");
- Key key1 = ds.put(entity1);
- Key entityGroupKey = Entities.createEntityGroupKey(key1);
-
- // Print entity1's entity group version
- writer.println("version " + getEntityGroupVersion(ds, null, key1));
-
- // Write to a different entity group
- Entity entity2 = new Entity("Simple");
- ds.put(entity2);
-
- // Will print the same version, as entity1's entity group has not changed
- writer.println("version " + getEntityGroupVersion(ds, null, key1));
-
- // Change entity1's entity group by adding a new child entity
- Entity entity3 = new Entity("Simple", entity1.getKey());
- ds.put(entity3);
-
- // Will print a higher version, as entity1's entity group has changed
- writer.println("version " + getEntityGroupVersion(ds, null, key1));
- }
- // [END entity_group_1]
-
- @Test
- public void printEntityGroupVersions_printsVersions() throws Exception {
- StringWriter responseWriter = new StringWriter();
- printEntityGroupVersions(datastore, new PrintWriter(responseWriter));
- assertThat(responseWriter.toString()).contains("version");
- }
-
- // [START entity_group_2]
- // A simple class for tracking consistent entity group counts.
- private static class EntityGroupCount implements Serializable {
- long version; // Version of the entity group whose count we are tracking
- int count;
-
- EntityGroupCount(long version, int count) {
- this.version = version;
- this.count = count;
- }
-
- // Display count of entities in an entity group, with consistent caching
- void showEntityGroupCount(
- DatastoreService ds, MemcacheService cache, PrintWriter writer, Key entityGroupKey) {
- EntityGroupCount egCount = (EntityGroupCount) cache.get(entityGroupKey);
- // Reuses getEntityGroupVersion method from the previous example.
- if (egCount != null && egCount.version == getEntityGroupVersion(ds, null, entityGroupKey)) {
- // Cached value matched current entity group version, use that
- writer.println(egCount.count + " entities (cached)");
- } else {
- // Need to actually count entities. Using a transaction to get a consistent count
- // and entity group version.
- Transaction tx = ds.beginTransaction();
- PreparedQuery pq = ds.prepare(tx, new Query(entityGroupKey));
- int count = pq.countEntities(FetchOptions.Builder.withLimit(5000));
- cache.put(
- entityGroupKey,
- new EntityGroupCount(getEntityGroupVersion(ds, tx, entityGroupKey), count));
- tx.rollback();
- writer.println(count + " entities");
- }
- }
- }
- // [END entity_group_2]
-
- @Test
- public void entityGroupCount_printsCount() throws Exception {
- StringWriter responseWriter = new StringWriter();
- MemcacheService cache = MemcacheServiceFactory.getMemcacheService();
- Entity entity1 = new Entity("Simple");
- Key key1 = datastore.put(entity1);
- Key entityGroupKey = Entities.createEntityGroupKey(key1);
-
- EntityGroupCount groupCount = new EntityGroupCount(0, 0);
- groupCount.showEntityGroupCount(
- datastore, cache, new PrintWriter(responseWriter), entityGroupKey);
-
- assertThat(responseWriter.toString()).contains(" entities");
- }
-}
diff --git a/appengine/datastore/src/test/java/com/example/appengine/MetadataKindsTest.java b/appengine/datastore/src/test/java/com/example/appengine/MetadataKindsTest.java
deleted file mode 100644
index 998d2ab33cf..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/MetadataKindsTest.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entities;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.Query;
-import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
-import com.google.appengine.api.datastore.Query.Filter;
-import com.google.appengine.api.datastore.Query.FilterOperator;
-import com.google.appengine.api.datastore.Query.FilterPredicate;
-import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
-import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Unit tests to demonstrate App Engine Datastore kinds metadata.
- */
-@RunWith(JUnit4.class)
-public class MetadataKindsTest {
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(
- // Set no eventual consistency, that way queries return all results.
- // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(0));
-
- private StringWriter responseWriter;
- private DatastoreService datastore;
-
- @Before
- public void setUp() {
- helper.setUp();
- datastore = DatastoreServiceFactory.getDatastoreService();
- responseWriter = new StringWriter();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- // [START kind_query_example]
- void printLowercaseKinds(DatastoreService ds, PrintWriter writer) {
-
- // Start with unrestricted kind query
- Query q = new Query(Entities.KIND_METADATA_KIND);
-
- List subFils = new ArrayList();
-
- // Limit to lowercase initial letters
- subFils.add(
- new FilterPredicate(
- Entity.KEY_RESERVED_PROPERTY,
- FilterOperator.GREATER_THAN_OR_EQUAL,
- Entities.createKindKey("a")));
-
- String endChar = Character.toString((char) ('z' + 1)); // Character after 'z'
-
- subFils.add(
- new FilterPredicate(
- Entity.KEY_RESERVED_PROPERTY,
- FilterOperator.LESS_THAN,
- Entities.createKindKey(endChar)));
-
- q.setFilter(CompositeFilterOperator.and(subFils));
-
- // Print heading
- writer.println("Lowercase kinds:");
-
- // Print query results
- for (Entity e : ds.prepare(q).asIterable()) {
- writer.println(" " + e.getKey().getName());
- }
- }
- // [END kind_query_example]
-
- @Test
- public void printLowercaseKinds_printsKinds() throws Exception {
- datastore.put(new Entity("alpha"));
- datastore.put(new Entity("beta"));
- datastore.put(new Entity("NotIncluded"));
- datastore.put(new Entity("zed"));
-
- printLowercaseKinds(datastore, new PrintWriter(responseWriter));
-
- String response = responseWriter.toString();
- assertThat(response).contains("alpha");
- assertThat(response).contains("beta");
- assertThat(response).contains("zed");
- assertThat(response).doesNotContain("NotIncluded");
- }
-}
diff --git a/appengine/datastore/src/test/java/com/example/appengine/MetadataNamespacesTest.java b/appengine/datastore/src/test/java/com/example/appengine/MetadataNamespacesTest.java
deleted file mode 100644
index e31f7a14852..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/MetadataNamespacesTest.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.google.appengine.api.NamespaceManager;
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entities;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.Query;
-import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
-import com.google.appengine.api.datastore.Query.Filter;
-import com.google.appengine.api.datastore.Query.FilterOperator;
-import com.google.appengine.api.datastore.Query.FilterPredicate;
-import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
-import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Unit tests to demonstrate App Engine Datastore namespaces metadata.
- */
-@RunWith(JUnit4.class)
-public class MetadataNamespacesTest {
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(
- // Set no eventual consistency, that way queries return all results.
- // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(0));
-
- private StringWriter responseWriter;
- private DatastoreService datastore;
-
- @Before
- public void setUp() {
- helper.setUp();
- datastore = DatastoreServiceFactory.getDatastoreService();
- responseWriter = new StringWriter();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- // [START queries_intro_example]
- void printAllNamespaces(DatastoreService ds, PrintWriter writer) {
- Query q = new Query(Entities.NAMESPACE_METADATA_KIND);
-
- for (Entity e : ds.prepare(q).asIterable()) {
- // A nonzero numeric id denotes the default namespace;
- // see Namespace Queries, below
- if (e.getKey().getId() != 0) {
- writer.println("");
- } else {
- writer.println(e.getKey().getName());
- }
- }
- }
- // [END queries_intro_example]
-
- @Test
- public void printAllNamespaces_printsNamespaces() throws Exception {
- datastore.put(new Entity("Simple"));
- NamespaceManager.set("another-namespace");
- datastore.put(new Entity("Simple"));
-
- printAllNamespaces(datastore, new PrintWriter(responseWriter));
-
- String response = responseWriter.toString();
- assertThat(response).contains("");
- assertThat(response).contains("another-namespace");
- }
-
- // [START namespace_query_example]
- List getNamespaces(DatastoreService ds, String start, String end) {
-
- // Start with unrestricted namespace query
- Query q = new Query(Entities.NAMESPACE_METADATA_KIND);
- List subFilters = new ArrayList();
- // Limit to specified range, if any
- if (start != null) {
- subFilters.add(
- new FilterPredicate(
- Entity.KEY_RESERVED_PROPERTY,
- FilterOperator.GREATER_THAN_OR_EQUAL,
- Entities.createNamespaceKey(start)));
- }
- if (end != null) {
- subFilters.add(
- new FilterPredicate(
- Entity.KEY_RESERVED_PROPERTY,
- FilterOperator.LESS_THAN_OR_EQUAL,
- Entities.createNamespaceKey(end)));
- }
-
- q.setFilter(CompositeFilterOperator.and(subFilters));
-
- // Initialize result list
- List results = new ArrayList();
-
- // Build list of query results
- for (Entity e : ds.prepare(q).asIterable()) {
- results.add(Entities.getNamespaceFromNamespaceKey(e.getKey()));
- }
-
- // Return result list
- return results;
- }
- // [END namespace_query_example]
-
- @Test
- public void getNamespaces_returnsNamespaces() throws Exception {
- NamespaceManager.set("alpha");
- datastore.put(new Entity("Simple"));
- NamespaceManager.set("bravo");
- datastore.put(new Entity("Simple"));
- NamespaceManager.set("charlie");
- datastore.put(new Entity("Simple"));
- NamespaceManager.set("zed");
- datastore.put(new Entity("Simple"));
-
- List results = getNamespaces(datastore, "bravo", "echo");
-
- assertThat(results).containsExactly("bravo", "charlie");
- }
-}
diff --git a/appengine/datastore/src/test/java/com/example/appengine/MetadataPropertiesTest.java b/appengine/datastore/src/test/java/com/example/appengine/MetadataPropertiesTest.java
deleted file mode 100644
index 88ba79008ab..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/MetadataPropertiesTest.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entities;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.Query;
-import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
-import com.google.appengine.api.datastore.Query.FilterPredicate;
-import com.google.appengine.api.datastore.Query.SortDirection;
-import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
-import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-
-/**
- * Unit tests to demonstrate App Engine Datastore properties metadata.
- */
-@RunWith(JUnit4.class)
-public class MetadataPropertiesTest {
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(
- // Set no eventual consistency, that way queries return all results.
- // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(0));
-
- private StringWriter responseWriter;
- private DatastoreService datastore;
-
- @Before
- public void setUp() {
- helper.setUp();
- datastore = DatastoreServiceFactory.getDatastoreService();
- responseWriter = new StringWriter();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- // [START property_query_example]
- void printProperties(DatastoreService ds, PrintWriter writer) {
-
- // Create unrestricted keys-only property query
- Query q = new Query(Entities.PROPERTY_METADATA_KIND).setKeysOnly();
-
- // Print query results
- for (Entity e : ds.prepare(q).asIterable()) {
- writer.println(e.getKey().getParent().getName() + ": " + e.getKey().getName());
- }
- }
- // [END property_query_example]
-
- @Test
- public void printProperties_printsProperties() throws Exception {
- Entity a = new Entity("Widget");
- a.setProperty("combobulators", 2);
- a.setProperty("oscillatorState", "harmonzing");
- Entity b = new Entity("Ship");
- b.setProperty("sails", 2);
- b.setProperty("captain", "Blackbeard");
- Entity c = new Entity("Ship");
- c.setProperty("captain", "Redbeard");
- c.setProperty("motor", "outboard");
- datastore.put(Arrays.asList(a, b, c));
-
- printProperties(datastore, new PrintWriter(responseWriter));
-
- String response = responseWriter.toString();
- assertThat(response).contains("Widget: combobulators");
- assertThat(response).contains("Widget: oscillatorState");
- assertThat(response).contains("Ship: sails");
- assertThat(response).contains("Ship: captain");
- assertThat(response).contains("Ship: motor");
- }
-
- // [START property_filtering_example]
- void printPropertyRange(DatastoreService ds, PrintWriter writer) {
-
- // Start with unrestricted keys-only property query
- Query q = new Query(Entities.PROPERTY_METADATA_KIND).setKeysOnly();
-
- // Limit range
- q.setFilter(
- CompositeFilterOperator.and(
- new FilterPredicate(
- Entity.KEY_RESERVED_PROPERTY,
- Query.FilterOperator.GREATER_THAN_OR_EQUAL,
- Entities.createPropertyKey("Employee", "salary")),
- new FilterPredicate(
- Entity.KEY_RESERVED_PROPERTY,
- Query.FilterOperator.LESS_THAN_OR_EQUAL,
- Entities.createPropertyKey("Manager", "salary"))));
- q.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING);
-
- // Print query results
- for (Entity e : ds.prepare(q).asIterable()) {
- writer.println(e.getKey().getParent().getName() + ": " + e.getKey().getName());
- }
- }
- // [END property_filtering_example]
-
- @Test
- public void printPropertyRange_printsProperties() throws Exception {
- Entity account = new Entity("Account");
- account.setProperty("balance", "10.30");
- account.setProperty("company", "General Company");
- Entity employee = new Entity("Employee");
- employee.setProperty("name", "John Doe");
- employee.setProperty("ssn", "987-65-4321");
- Entity invoice = new Entity("Invoice");
- invoice.setProperty("date", new Date());
- invoice.setProperty("amount", "99.98");
- Entity manager = new Entity("Manager");
- manager.setProperty("name", "Jane Doe");
- manager.setProperty("title", "Technical Director");
- Entity product = new Entity("Product");
- product.setProperty("description", "Widget to re-ionize an oscillator");
- product.setProperty("price", "19.97");
- datastore.put(Arrays.asList(account, employee, invoice, manager, product));
-
- printPropertyRange(datastore, new PrintWriter(responseWriter));
-
- String response = responseWriter.toString();
- assertThat(response)
- .isEqualTo("Employee: ssn\nInvoice: amount\nInvoice: date\nManager: name\n");
- }
-
- // [START property_ancestor_query_example]
- List propertiesOfKind(DatastoreService ds, String kind) {
-
- // Start with unrestricted keys-only property query
- Query q = new Query(Entities.PROPERTY_METADATA_KIND).setKeysOnly();
-
- // Limit to specified kind
- q.setAncestor(Entities.createKindKey(kind));
-
- // Initialize result list
- ArrayList results = new ArrayList();
-
- //Build list of query results
- for (Entity e : ds.prepare(q).asIterable()) {
- results.add(e.getKey().getName());
- }
-
- // Return result list
- return results;
- }
- // [END property_ancestor_query_example]
-
- @Test
- public void propertiesOfKind_returnsProperties() throws Exception {
- Entity a = new Entity("Alpha");
- a.setProperty("beta", 12);
- a.setProperty("charlie", "misc.");
- Entity b = new Entity("Alpha");
- b.setProperty("charlie", "assorted");
- b.setProperty("delta", new Date());
- Entity c = new Entity("Charlie");
- c.setProperty("charlie", "some");
- c.setProperty("echo", new Date());
- datastore.put(Arrays.asList(a, b, c));
-
- List properties = propertiesOfKind(datastore, "Alpha");
-
- assertThat(properties).containsExactly("beta", "charlie", "delta");
- }
-
- // [START property_representation_query_example]
- Collection representationsOfProperty(DatastoreService ds, String kind, String property) {
-
- // Start with unrestricted non-keys-only property query
- Query q = new Query(Entities.PROPERTY_METADATA_KIND);
-
- // Limit to specified kind and property
- q.setFilter(
- new FilterPredicate(
- "__key__", Query.FilterOperator.EQUAL, Entities.createPropertyKey(kind, property)));
-
- // Get query result
- Entity propInfo = ds.prepare(q).asSingleEntity();
-
- // Return collection of property representations
- return (Collection) propInfo.getProperty("property_representation");
- }
- // [END property_representation_query_example]
-
- @Test
- public void representationsOfProperty_returnsRepresentations() throws Exception {
- Entity a = new Entity("Alpha");
- a.setProperty("beta", 12);
- Entity b = new Entity("Alpha");
- b.setProperty("beta", true);
- Entity c = new Entity("Alpha");
- c.setProperty("beta", new Date());
- datastore.put(Arrays.asList(a, b, c));
-
- Collection results = representationsOfProperty(datastore, "Alpha", "beta");
-
- assertThat(results).containsExactly("INT64", "BOOLEAN");
- }
-}
diff --git a/appengine/datastore/src/test/java/com/example/appengine/ProjectionServletTest.java b/appengine/datastore/src/test/java/com/example/appengine/ProjectionServletTest.java
deleted file mode 100644
index 7e71cfee7a5..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/ProjectionServletTest.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.when;
-
-import com.example.time.testing.FakeClock;
-
-import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
-import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * Unit tests for {@link ProjectionServlet}.
- */
-@RunWith(JUnit4.class)
-public class ProjectionServletTest {
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
-
- @Mock private HttpServletRequest mockRequest;
- @Mock private HttpServletResponse mockResponse;
- private StringWriter responseWriter;
- private ProjectionServlet servletUnderTest;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- helper.setUp();
-
- // Set up a fake HTTP response.
- responseWriter = new StringWriter();
- when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter));
-
- servletUnderTest = new ProjectionServlet();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- @Test
- public void doGet_emptyDatastore_writesNoGreetings() throws Exception {
- servletUnderTest.doGet(mockRequest, mockResponse);
-
- assertThat(responseWriter.toString())
- .named("ProjectionServlet response")
- .doesNotContain("Message");
- }
-
- @Test
- public void doGet_manyGreetings_writesLatestGreetings() throws Exception {
- // Arrange
- GuestbookStrong guestbook =
- new GuestbookStrong(GuestbookStrongServlet.GUESTBOOK_ID, new FakeClock());
- guestbook.appendGreeting("Hello.");
- guestbook.appendGreeting("Güten Tag!");
- guestbook.appendGreeting("Hi.");
- guestbook.appendGreeting("Hola.");
-
- // Act
- servletUnderTest.doGet(mockRequest, mockResponse);
- String output = responseWriter.toString();
-
- assertThat(output)
- .named("ProjectionServlet response")
- .contains("Message Hello.");
- assertThat(output)
- .named("ProjectionServlet response")
- .contains("Message Güten Tag!");
- assertThat(output)
- .named("ProjectionServlet response")
- .contains("Message Hola.");
- }
-}
diff --git a/appengine/datastore/src/test/java/com/example/appengine/ProjectionTest.java b/appengine/datastore/src/test/java/com/example/appengine/ProjectionTest.java
deleted file mode 100644
index 494f1577ce4..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/ProjectionTest.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.FetchOptions;
-import com.google.appengine.api.datastore.PropertyProjection;
-import com.google.appengine.api.datastore.Query;
-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.List;
-
-/**
- * Unit tests to demonstrate App Engine Datastore projection queries.
- */
-@RunWith(JUnit4.class)
-public class ProjectionTest {
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(
- // Set no eventual consistency, that way queries return all results.
- // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(0));
-
- private DatastoreService datastore;
-
- @Before
- public void setUp() throws Exception {
- helper.setUp();
- datastore = DatastoreServiceFactory.getDatastoreService();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
-
- @Test
- public void projectionQuery_grouping_filtersDuplicates() {
- putTestData("some duplicate", 0L);
- putTestData("some duplicate", 0L);
- putTestData("too big", 1L);
-
- // [START grouping]
- Query q = new Query("TestKind");
- q.addProjection(new PropertyProjection("A", String.class));
- q.addProjection(new PropertyProjection("B", Long.class));
- q.setDistinct(true);
- q.setFilter(Query.FilterOperator.LESS_THAN.of("B", 1L));
- q.addSort("B", Query.SortDirection.DESCENDING);
- q.addSort("A");
- // [END grouping]
-
- List entities =
- datastore.prepare(q).asList(FetchOptions.Builder.withLimit(5));
- assertThat(entities).hasSize(1);
- Entity entity = entities.get(0);
- assertThat((String) entity.getProperty("A")).named("entity.A").isEqualTo("some duplicate");
- assertThat((long) entity.getProperty("B")).named("entity.B").isEqualTo(0L);
- }
-
- private void putTestData(String a, long b) {
- Entity entity = new Entity("TestKind");
- entity.setProperty("A", a);
- entity.setProperty("B", b);
- datastore.put(entity);
- }
-}
diff --git a/appengine/datastore/src/test/java/com/example/appengine/QueriesTest.java b/appengine/datastore/src/test/java/com/example/appengine/QueriesTest.java
deleted file mode 100644
index 07c3dd13c60..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/QueriesTest.java
+++ /dev/null
@@ -1,856 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.fail;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.FetchOptions;
-import com.google.appengine.api.datastore.Key;
-import com.google.appengine.api.datastore.PreparedQuery;
-import com.google.appengine.api.datastore.PreparedQuery.TooManyResultsException;
-import com.google.appengine.api.datastore.Query;
-import com.google.appengine.api.datastore.Query.CompositeFilter;
-import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
-import com.google.appengine.api.datastore.Query.Filter;
-import com.google.appengine.api.datastore.Query.FilterOperator;
-import com.google.appengine.api.datastore.Query.FilterPredicate;
-import com.google.appengine.api.datastore.Query.SortDirection;
-import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
-import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
-import com.google.common.collect.ImmutableList;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * Unit tests to demonstrate App Engine Datastore queries.
- */
-@RunWith(JUnit4.class)
-public class QueriesTest {
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(
- // Set no eventual consistency, that way queries return all results.
- // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(0));
-
- private DatastoreService datastore;
-
- @Before
- public void setUp() {
- helper.setUp();
- datastore = DatastoreServiceFactory.getDatastoreService();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- @Test
- public void propertyFilterExample_returnsMatchingEntities() throws Exception {
- // Arrange
- Entity p1 = new Entity("Person");
- p1.setProperty("height", 120);
- Entity p2 = new Entity("Person");
- p2.setProperty("height", 180);
- Entity p3 = new Entity("Person");
- p3.setProperty("height", 160);
- datastore.put(ImmutableList.of(p1, p2, p3));
-
- // Act
- long minHeight = 160;
- // [START property_filter_example]
- Filter propertyFilter =
- new FilterPredicate("height", FilterOperator.GREATER_THAN_OR_EQUAL, minHeight);
- Query q = new Query("Person").setFilter(propertyFilter);
- // [END property_filter_example]
-
- // Assert
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").containsExactly(p2, p3);
- }
-
- @Test
- public void keyFilterExample_returnsMatchingEntities() throws Exception {
- // Arrange
- Entity a = new Entity("Person", "a");
- Entity b = new Entity("Person", "b");
- Entity c = new Entity("Person", "c");
- Entity aa = new Entity("Person", "aa", b.getKey());
- Entity bb = new Entity("Person", "bb", b.getKey());
- Entity aaa = new Entity("Person", "aaa", bb.getKey());
- Entity bbb = new Entity("Person", "bbb", bb.getKey());
- datastore.put(ImmutableList.of(a, b, c, aa, bb, aaa, bbb));
-
- // Act
- Key lastSeenKey = bb.getKey();
- // [START key_filter_example]
- Filter keyFilter =
- new FilterPredicate(Entity.KEY_RESERVED_PROPERTY, FilterOperator.GREATER_THAN, lastSeenKey);
- Query q = new Query("Person").setFilter(keyFilter);
- // [END key_filter_example]
-
- // Assert
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results)
- .named("query results")
- .containsExactly(
- aaa, // Ancestor path "b/bb/aaa" is greater than "b/bb".
- bbb, // Ancestor path "b/bb/bbb" is greater than "b/bb".
- c); // Key name identifier "c" is greater than b.
- }
-
- @Test
- public void keyFilterExample_kindless_returnsMatchingEntities() throws Exception {
- // Arrange
- Entity a = new Entity("Child", "a");
- Entity b = new Entity("Child", "b");
- Entity c = new Entity("Child", "c");
- Entity aa = new Entity("Child", "aa", b.getKey());
- Entity bb = new Entity("Child", "bb", b.getKey());
- Entity aaa = new Entity("Child", "aaa", bb.getKey());
- Entity bbb = new Entity("Child", "bbb", bb.getKey());
- Entity adult = new Entity("Adult", "a");
- Entity zooAnimal = new Entity("ZooAnimal", "a");
- datastore.put(ImmutableList.of(a, b, c, aa, bb, aaa, bbb, adult, zooAnimal));
-
- // Act
- Key lastSeenKey = bb.getKey();
- // [START kindless_query_example]
- Filter keyFilter =
- new FilterPredicate(Entity.KEY_RESERVED_PROPERTY, FilterOperator.GREATER_THAN, lastSeenKey);
- Query q = new Query().setFilter(keyFilter);
- // [END kindless_query_example]
-
- // Assert
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results)
- .named("query results")
- .containsExactly(
- aaa, // Ancestor path "b/bb/aaa" is greater than "b/bb".
- bbb, // Ancestor path "b/bb/bbb" is greater than "b/bb".
- zooAnimal, // Kind "ZooAnimal" is greater than "Child"
- c); // Key name identifier "c" is greater than b.
- }
-
- @Test
- public void ancestorFilterExample_returnsMatchingEntities() throws Exception {
- Entity a = new Entity("Person", "a");
- Entity b = new Entity("Person", "b");
- Entity aa = new Entity("Person", "aa", a.getKey());
- Entity ab = new Entity("Person", "ab", a.getKey());
- Entity bb = new Entity("Person", "bb", b.getKey());
- datastore.put(ImmutableList.of(a, b, aa, ab, bb));
-
- Key ancestorKey = a.getKey();
- // [START ancestor_filter_example]
- Query q = new Query("Person").setAncestor(ancestorKey);
- // [END ancestor_filter_example]
-
- // Assert
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").containsExactly(a, aa, ab);
- }
-
- @Test
- public void ancestorQueryExample_returnsMatchingEntities() throws Exception {
- // [START ancestor_query_example]
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
-
- Entity tom = new Entity("Person", "Tom");
- Key tomKey = tom.getKey();
- datastore.put(tom);
-
- Entity weddingPhoto = new Entity("Photo", tomKey);
- weddingPhoto.setProperty("imageURL", "http://domain.com/some/path/to/wedding_photo.jpg");
-
- Entity babyPhoto = new Entity("Photo", tomKey);
- babyPhoto.setProperty("imageURL", "http://domain.com/some/path/to/baby_photo.jpg");
-
- Entity dancePhoto = new Entity("Photo", tomKey);
- dancePhoto.setProperty("imageURL", "http://domain.com/some/path/to/dance_photo.jpg");
-
- Entity campingPhoto = new Entity("Photo");
- campingPhoto.setProperty("imageURL", "http://domain.com/some/path/to/camping_photo.jpg");
-
- List photoList = Arrays.asList(weddingPhoto, babyPhoto, dancePhoto, campingPhoto);
- datastore.put(photoList);
-
- Query photoQuery = new Query("Photo").setAncestor(tomKey);
-
- // This returns weddingPhoto, babyPhoto, and dancePhoto,
- // but not campingPhoto, because tom is not an ancestor
- List results =
- datastore.prepare(photoQuery).asList(FetchOptions.Builder.withDefaults());
- // [END ancestor_query_example]
-
- assertThat(results).named("query results").containsExactly(weddingPhoto, babyPhoto, dancePhoto);
- }
-
- @Test
- public void ancestorQueryExample_kindlessKeyFilter_returnsMatchingEntities() throws Exception {
- // Arrange
- Entity a = new Entity("Grandparent", "a");
- Entity b = new Entity("Grandparent", "b");
- Entity c = new Entity("Grandparent", "c");
- Entity aa = new Entity("Parent", "aa", a.getKey());
- Entity ba = new Entity("Parent", "ba", b.getKey());
- Entity bb = new Entity("Parent", "bb", b.getKey());
- Entity bc = new Entity("Parent", "bc", b.getKey());
- Entity cc = new Entity("Parent", "cc", c.getKey());
- Entity aaa = new Entity("Child", "aaa", aa.getKey());
- Entity bbb = new Entity("Child", "bbb", bb.getKey());
- datastore.put(ImmutableList.of(a, b, c, aa, ba, bb, bc, cc, aaa, bbb));
-
- // Act
- Key ancestorKey = b.getKey();
- Key lastSeenKey = bb.getKey();
- // [START kindless_ancestor_key_query_example]
- Filter keyFilter =
- new FilterPredicate(Entity.KEY_RESERVED_PROPERTY, FilterOperator.GREATER_THAN, lastSeenKey);
- Query q = new Query().setAncestor(ancestorKey).setFilter(keyFilter);
- // [END kindless_ancestor_key_query_example]
-
- // Assert
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").containsExactly(bc, bbb);
- }
-
- @Test
- public void ancestorQueryExample_kindlessKeyFilterFull_returnsMatchingEntities()
- throws Exception {
- // [START kindless_ancestor_query_example]
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
-
- Entity tom = new Entity("Person", "Tom");
- Key tomKey = tom.getKey();
- datastore.put(tom);
-
- Entity weddingPhoto = new Entity("Photo", tomKey);
- weddingPhoto.setProperty("imageURL", "http://domain.com/some/path/to/wedding_photo.jpg");
-
- Entity weddingVideo = new Entity("Video", tomKey);
- weddingVideo.setProperty("videoURL", "http://domain.com/some/path/to/wedding_video.avi");
-
- List mediaList = Arrays.asList(weddingPhoto, weddingVideo);
- datastore.put(mediaList);
-
- // By default, ancestor queries include the specified ancestor itself.
- // The following filter excludes the ancestor from the query results.
- Filter keyFilter =
- new FilterPredicate(Entity.KEY_RESERVED_PROPERTY, FilterOperator.GREATER_THAN, tomKey);
-
- Query mediaQuery = new Query().setAncestor(tomKey).setFilter(keyFilter);
-
- // Returns both weddingPhoto and weddingVideo,
- // even though they are of different entity kinds
- List results =
- datastore.prepare(mediaQuery).asList(FetchOptions.Builder.withDefaults());
- // [END kindless_ancestor_query_example]
-
- assertThat(results).named("query result keys").containsExactly(weddingPhoto, weddingVideo);
- }
-
- @Test
- public void keysOnlyExample_returnsMatchingEntities() throws Exception {
- // Arrange
- Entity a = new Entity("Person", "a");
- Entity b = new Entity("Building", "b");
- Entity c = new Entity("Person", "c");
- datastore.put(ImmutableList.of(a, b, c));
-
- // [START keys_only_example]
- Query q = new Query("Person").setKeysOnly();
- // [END keys_only_example]
-
- // Assert
- List results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").containsExactly(a, c);
- }
-
- @Test
- public void sortOrderExample_returnsSortedEntities() throws Exception {
- // Arrange
- Entity a = new Entity("Person", "a");
- a.setProperty("lastName", "Alpha");
- a.setProperty("height", 100);
- Entity b = new Entity("Person", "b");
- b.setProperty("lastName", "Bravo");
- b.setProperty("height", 200);
- Entity c = new Entity("Person", "c");
- c.setProperty("lastName", "Charlie");
- c.setProperty("height", 300);
- datastore.put(ImmutableList.of(a, b, c));
-
- // Act
- // [START sort_order_example]
- // Order alphabetically by last name:
- Query q1 = new Query("Person").addSort("lastName", SortDirection.ASCENDING);
-
- // Order by height, tallest to shortest:
- Query q2 = new Query("Person").addSort("height", SortDirection.DESCENDING);
- // [END sort_order_example]
-
- // Assert
- List lastNameResults =
- datastore.prepare(q1.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(lastNameResults).named("last name query results").containsExactly(a, b, c).inOrder();
- List heightResults =
- datastore.prepare(q2.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(heightResults).named("height query results").containsExactly(c, b, a).inOrder();
- }
-
- @Test
- public void sortOrderExample_multipleSortOrders_returnsSortedEntities() throws Exception {
- // Arrange
- Entity a = new Entity("Person", "a");
- a.setProperty("lastName", "Alpha");
- a.setProperty("height", 100);
- Entity b1 = new Entity("Person", "b1");
- b1.setProperty("lastName", "Bravo");
- b1.setProperty("height", 150);
- Entity b2 = new Entity("Person", "b2");
- b2.setProperty("lastName", "Bravo");
- b2.setProperty("height", 200);
- Entity c = new Entity("Person", "c");
- c.setProperty("lastName", "Charlie");
- c.setProperty("height", 300);
- datastore.put(ImmutableList.of(a, b1, b2, c));
-
- // Act
- // [START multiple_sort_orders_example]
- Query q =
- new Query("Person")
- .addSort("lastName", SortDirection.ASCENDING)
- .addSort("height", SortDirection.DESCENDING);
- // [END multiple_sort_orders_example]
-
- // Assert
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").containsExactly(a, b2, b1, c).inOrder();
- }
-
- @Test
- public void queryInterface_multipleFilters_printsMatchedEntities() throws Exception {
- // Arrange
- Entity a = new Entity("Person", "a");
- a.setProperty("firstName", "Alph");
- a.setProperty("lastName", "Alpha");
- a.setProperty("height", 60);
- Entity b = new Entity("Person", "b");
- b.setProperty("firstName", "Bee");
- b.setProperty("lastName", "Bravo");
- b.setProperty("height", 70);
- Entity c = new Entity("Person", "c");
- c.setProperty("firstName", "Charles");
- c.setProperty("lastName", "Charlie");
- c.setProperty("height", 100);
- datastore.put(ImmutableList.of(a, b, c));
-
- StringWriter buf = new StringWriter();
- PrintWriter out = new PrintWriter(buf);
- long minHeight = 60;
- long maxHeight = 72;
-
- // Act
- // [START interface_1]
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
-
- Filter heightMinFilter =
- new FilterPredicate("height", FilterOperator.GREATER_THAN_OR_EQUAL, minHeight);
-
- Filter heightMaxFilter =
- new FilterPredicate("height", FilterOperator.LESS_THAN_OR_EQUAL, maxHeight);
-
- // Use CompositeFilter to combine multiple filters
- CompositeFilter heightRangeFilter =
- CompositeFilterOperator.and(heightMinFilter, heightMaxFilter);
-
- // Use class Query to assemble a query
- Query q = new Query("Person").setFilter(heightRangeFilter);
-
- // Use PreparedQuery interface to retrieve results
- PreparedQuery pq = datastore.prepare(q);
-
- for (Entity result : pq.asIterable()) {
- String firstName = (String) result.getProperty("firstName");
- String lastName = (String) result.getProperty("lastName");
- Long height = (Long) result.getProperty("height");
-
- out.println(firstName + " " + lastName + ", " + height + " inches tall");
- }
- // [END interface_1]
-
- // Assert
- assertThat(buf.toString()).contains("Alph Alpha, 60 inches tall");
- assertThat(buf.toString()).contains("Bee Bravo, 70 inches tall");
- assertThat(buf.toString()).doesNotContain("Charlie");
- }
-
- @Test
- public void queryInterface_singleFilter_returnsMatchedEntities() throws Exception {
- // Arrange
- Entity a = new Entity("Person", "a");
- a.setProperty("height", 100);
- Entity b = new Entity("Person", "b");
- b.setProperty("height", 150);
- Entity c = new Entity("Person", "c");
- c.setProperty("height", 300);
- datastore.put(ImmutableList.of(a, b, c));
-
- // Act
- long minHeight = 150;
- // [START interface_2]
- Filter heightMinFilter =
- new FilterPredicate("height", FilterOperator.GREATER_THAN_OR_EQUAL, minHeight);
-
- Query q = new Query("Person").setFilter(heightMinFilter);
- // [END interface_2]
-
- // Assert
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").containsExactly(b, c);
- }
-
- @Test
- public void queryInterface_orFilter_printsMatchedEntities() throws Exception {
- // Arrange
- Entity a = new Entity("Person", "a");
- a.setProperty("height", 100);
- Entity b = new Entity("Person", "b");
- b.setProperty("height", 150);
- Entity c = new Entity("Person", "c");
- c.setProperty("height", 200);
- datastore.put(ImmutableList.of(a, b, c));
-
- StringWriter buf = new StringWriter();
- PrintWriter out = new PrintWriter(buf);
- long minHeight = 125;
- long maxHeight = 175;
-
- // Act
- // [START interface_3]
- Filter tooShortFilter = new FilterPredicate("height", FilterOperator.LESS_THAN, minHeight);
-
- Filter tooTallFilter = new FilterPredicate("height", FilterOperator.GREATER_THAN, maxHeight);
-
- Filter heightOutOfRangeFilter = CompositeFilterOperator.or(tooShortFilter, tooTallFilter);
-
- Query q = new Query("Person").setFilter(heightOutOfRangeFilter);
- // [END interface_3]
-
- // Assert
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").containsExactly(a, c);
- }
-
- @Test
- public void queryRestrictions_compositeFilter_returnsMatchedEntities() throws Exception {
- // Arrange
- Entity a = new Entity("Person", "a");
- a.setProperty("birthYear", 1930);
- Entity b = new Entity("Person", "b");
- b.setProperty("birthYear", 1960);
- Entity c = new Entity("Person", "c");
- c.setProperty("birthYear", 1990);
- datastore.put(ImmutableList.of(a, b, c));
-
- // Act
- long minBirthYear = 1940;
- long maxBirthYear = 1980;
- // [START inequality_filters_one_property_valid_example_1]
- Filter birthYearMinFilter =
- new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);
-
- Filter birthYearMaxFilter =
- new FilterPredicate("birthYear", FilterOperator.LESS_THAN_OR_EQUAL, maxBirthYear);
-
- Filter birthYearRangeFilter =
- CompositeFilterOperator.and(birthYearMinFilter, birthYearMaxFilter);
-
- Query q = new Query("Person").setFilter(birthYearRangeFilter);
- // [END inequality_filters_one_property_valid_example_1]
-
- // Assert
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").containsExactly(b);
- }
-
- @Test
- public void queryRestrictions_compositeFilter_isInvalid() throws Exception {
- long minBirthYear = 1940;
- long maxHeight = 200;
- // [START inequality_filters_one_property_invalid_example]
- Filter birthYearMinFilter =
- new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);
-
- Filter heightMaxFilter =
- new FilterPredicate("height", FilterOperator.LESS_THAN_OR_EQUAL, maxHeight);
-
- Filter invalidFilter = CompositeFilterOperator.and(birthYearMinFilter, heightMaxFilter);
-
- Query q = new Query("Person").setFilter(invalidFilter);
- // [END inequality_filters_one_property_invalid_example]
-
- // Note: The local devserver behavior is different than the production
- // version of Cloud Datastore, so there aren't any assertions we can make
- // in this test. The query appears to work with the local test runner,
- // but will fail in production.
- }
-
- @Test
- public void queryRestrictions_compositeEqualFilter_returnsMatchedEntities() throws Exception {
- // Arrange
- Entity a = new Entity("Person", "a");
- a.setProperty("birthYear", 1930);
- a.setProperty("city", "Somewhere");
- a.setProperty("lastName", "Someone");
- Entity b = new Entity("Person", "b");
- b.setProperty("birthYear", 1960);
- b.setProperty("city", "Somewhere");
- b.setProperty("lastName", "Someone");
- Entity c = new Entity("Person", "c");
- c.setProperty("birthYear", 1990);
- c.setProperty("city", "Somewhere");
- c.setProperty("lastName", "Someone");
- Entity d = new Entity("Person", "d");
- d.setProperty("birthYear", 1960);
- d.setProperty("city", "Nowhere");
- d.setProperty("lastName", "Someone");
- Entity e = new Entity("Person", "e");
- e.setProperty("birthYear", 1960);
- e.setProperty("city", "Somewhere");
- e.setProperty("lastName", "Noone");
- datastore.put(ImmutableList.of(a, b, c, d, e));
- long minBirthYear = 1940;
- long maxBirthYear = 1980;
- String targetCity = "Somewhere";
- String targetLastName = "Someone";
-
- // [START inequality_filters_one_property_valid_example_2]
- Filter lastNameFilter = new FilterPredicate("lastName", FilterOperator.EQUAL, targetLastName);
-
- Filter cityFilter = new FilterPredicate("city", FilterOperator.EQUAL, targetCity);
-
- Filter birthYearMinFilter =
- new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);
-
- Filter birthYearMaxFilter =
- new FilterPredicate("birthYear", FilterOperator.LESS_THAN_OR_EQUAL, maxBirthYear);
-
- Filter validFilter =
- CompositeFilterOperator.and(
- lastNameFilter, cityFilter, birthYearMinFilter, birthYearMaxFilter);
-
- Query q = new Query("Person").setFilter(validFilter);
- // [END inequality_filters_one_property_valid_example_2]
-
- // Assert
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").containsExactly(b);
- }
-
- @Test
- public void queryRestrictions_inequalitySortedFirst_returnsMatchedEntities() throws Exception {
- // Arrange
- Entity a = new Entity("Person", "a");
- a.setProperty("birthYear", 1930);
- a.setProperty("lastName", "Someone");
- Entity b = new Entity("Person", "b");
- b.setProperty("birthYear", 1990);
- b.setProperty("lastName", "Bravo");
- Entity c = new Entity("Person", "c");
- c.setProperty("birthYear", 1960);
- c.setProperty("lastName", "Charlie");
- Entity d = new Entity("Person", "d");
- d.setProperty("birthYear", 1960);
- d.setProperty("lastName", "Delta");
- datastore.put(ImmutableList.of(a, b, c, d));
- long minBirthYear = 1940;
-
- // [START inequality_filters_sort_orders_valid_example]
- Filter birthYearMinFilter =
- new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);
-
- Query q =
- new Query("Person")
- .setFilter(birthYearMinFilter)
- .addSort("birthYear", SortDirection.ASCENDING)
- .addSort("lastName", SortDirection.ASCENDING);
- // [END inequality_filters_sort_orders_valid_example]
-
- // Assert
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").containsExactly(c, d, b).inOrder();
- }
-
- @Test
- public void queryRestrictions_missingSortOnInequality_isInvalid() throws Exception {
- long minBirthYear = 1940;
- // [START inequality_filters_sort_orders_invalid_example_1]
- Filter birthYearMinFilter =
- new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);
-
- // Not valid. Missing sort on birthYear.
- Query q =
- new Query("Person")
- .setFilter(birthYearMinFilter)
- .addSort("lastName", SortDirection.ASCENDING);
- // [END inequality_filters_sort_orders_invalid_example_1]
-
- // Note: The local devserver behavior is different than the production
- // version of Cloud Datastore, so there aren't any assertions we can make
- // in this test. The query appears to work with the local test runner,
- // but will fail in production.
- }
-
- @Test
- public void queryRestrictions_sortWrongOrderOnInequality_isInvalid() throws Exception {
- long minBirthYear = 1940;
- // [START inequality_filters_sort_orders_invalid_example_2]
- Filter birthYearMinFilter =
- new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);
-
- // Not valid. Sort on birthYear needs to be first.
- Query q =
- new Query("Person")
- .setFilter(birthYearMinFilter)
- .addSort("lastName", SortDirection.ASCENDING)
- .addSort("birthYear", SortDirection.ASCENDING);
- // [END inequality_filters_sort_orders_invalid_example_2]
-
- // Note: The local devserver behavior is different than the production
- // version of Cloud Datastore, so there aren't any assertions we can make
- // in this test. The query appears to work with the local test runner,
- // but will fail in production.
- }
-
- @Test
- public void queryRestrictions_surprisingMultipleValuesAllMustMatch_returnsNoEntities()
- throws Exception {
- Entity a = new Entity("Widget", "a");
- List xs = Arrays.asList(1L, 2L);
- a.setProperty("x", xs);
- datastore.put(a);
-
- // [START surprising_behavior_example_1]
- Query q =
- new Query("Widget")
- .setFilter(
- CompositeFilterOperator.and(
- new FilterPredicate("x", FilterOperator.GREATER_THAN, 1),
- new FilterPredicate("x", FilterOperator.LESS_THAN, 2)));
- // [END surprising_behavior_example_1]
-
- // Entity "a" will not match because no individual value matches all filters.
- // See the documentation for more details:
- // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions#properties_with_multiple_values_can_behave_in_surprising_ways
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").isEmpty();
- }
-
- @Test
- public void queryRestrictions_surprisingMultipleValuesEquals_returnsMatchedEntities()
- throws Exception {
- Entity a = new Entity("Widget", "a");
- a.setProperty("x", ImmutableList.of(1L, 2L));
- Entity b = new Entity("Widget", "b");
- b.setProperty("x", ImmutableList.of(1L, 3L));
- Entity c = new Entity("Widget", "c");
- c.setProperty("x", ImmutableList.of(-6L, 2L));
- Entity d = new Entity("Widget", "d");
- d.setProperty("x", ImmutableList.of(-6L, 4L));
- Entity e = new Entity("Widget", "e");
- e.setProperty("x", ImmutableList.of(1L, 2L, 3L));
- datastore.put(ImmutableList.of(a, b, c, d, e));
-
- // [START surprising_behavior_example_2]
- Query q =
- new Query("Widget")
- .setFilter(
- CompositeFilterOperator.and(
- new FilterPredicate("x", FilterOperator.EQUAL, 1),
- new FilterPredicate("x", FilterOperator.EQUAL, 2)));
- // [END surprising_behavior_example_2]
-
- // Only "a" and "e" have both 1 and 2 in the "x" array-valued property.
- // See the documentation for more details:
- // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions#properties_with_multiple_values_can_behave_in_surprising_ways
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").containsExactly(a, e);
- }
-
- @Test
- public void queryRestrictions_surprisingMultipleValuesNotEquals_returnsMatchedEntities()
- throws Exception {
- Entity a = new Entity("Widget", "a");
- a.setProperty("x", ImmutableList.of(1L, 2L));
- Entity b = new Entity("Widget", "b");
- b.setProperty("x", ImmutableList.of(1L, 3L));
- Entity c = new Entity("Widget", "c");
- c.setProperty("x", ImmutableList.of(-6L, 2L));
- Entity d = new Entity("Widget", "d");
- d.setProperty("x", ImmutableList.of(-6L, 4L));
- Entity e = new Entity("Widget", "e");
- e.setProperty("x", ImmutableList.of(1L));
- datastore.put(ImmutableList.of(a, b, c, d, e));
-
- // [START surprising_behavior_example_3]
- Query q = new Query("Widget").setFilter(new FilterPredicate("x", FilterOperator.NOT_EQUAL, 1));
- // [END surprising_behavior_example_3]
-
- // The query matches any entity that has a some value other than 1. Only
- // entity "e" is not matched. See the documentation for more details:
- // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions#properties_with_multiple_values_can_behave_in_surprising_ways
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").containsExactly(a, b, c, d);
- }
-
- @Test
- public void queryRestrictions_surprisingMultipleValuesTwoNotEquals_returnsMatchedEntities()
- throws Exception {
- Entity a = new Entity("Widget", "a");
- a.setProperty("x", ImmutableList.of(1L, 2L));
- Entity b = new Entity("Widget", "b");
- b.setProperty("x", ImmutableList.of(1L, 2L, 3L));
- datastore.put(ImmutableList.of(a, b));
-
- // [START surprising_behavior_example_4]
- Query q =
- new Query("Widget")
- .setFilter(
- CompositeFilterOperator.and(
- new FilterPredicate("x", FilterOperator.NOT_EQUAL, 1),
- new FilterPredicate("x", FilterOperator.NOT_EQUAL, 2)));
- // [END surprising_behavior_example_4]
-
- // The two NOT_EQUAL filters in the query become like the combination of queries:
- // x < 1 OR (x > 1 AND x < 2) OR x > 2
- //
- // Only "b" has some value which matches the "x > 2" portion of this query.
- //
- // See the documentation for more details:
- // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions#properties_with_multiple_values_can_behave_in_surprising_ways
- List results =
- datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").containsExactly(b);
- }
-
- private Entity retrievePersonWithLastName(String targetLastName) {
- // [START single_retrieval_example]
- Query q =
- new Query("Person")
- .setFilter(new FilterPredicate("lastName", FilterOperator.EQUAL, targetLastName));
-
- PreparedQuery pq = datastore.prepare(q);
- Entity result = pq.asSingleEntity();
- // [END single_retrieval_example]
- return result;
- }
-
- @Test
- public void singleRetrievalExample_singleEntity_returnsEntity() throws Exception {
- Entity a = new Entity("Person", "a");
- a.setProperty("lastName", "Johnson");
- Entity b = new Entity("Person", "b");
- b.setProperty("lastName", "Smith");
- datastore.put(ImmutableList.of(a, b));
-
- Entity result = retrievePersonWithLastName("Johnson");
-
- assertThat(result).named("result").isEqualTo(a); // Note: Entity.equals() only checks the Key.
- }
-
- @Test
- public void singleRetrievalExample_multitpleEntities_throwsException() throws Exception {
- Entity a = new Entity("Person", "a");
- a.setProperty("lastName", "Johnson");
- Entity b = new Entity("Person", "b");
- b.setProperty("lastName", "Johnson");
- datastore.put(ImmutableList.of(a, b));
-
- try {
- Entity result = retrievePersonWithLastName("Johnson");
- fail("Expected TooManyResultsException");
- } catch (TooManyResultsException expected) {
- // TooManyResultsException does not provide addition details.
- }
- }
-
- // [START query_limit_example]
- private List getTallestPeople() {
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
-
- Query q = new Query("Person").addSort("height", SortDirection.DESCENDING);
-
- PreparedQuery pq = datastore.prepare(q);
- return pq.asList(FetchOptions.Builder.withLimit(5));
- }
- // [END query_limit_example]
-
- @Test
- public void queryLimitExample_returnsLimitedEntities() throws Exception {
- Entity a = new Entity("Person", "a");
- a.setProperty("height", 200);
- Entity b = new Entity("Person", "b");
- b.setProperty("height", 199);
- Entity c = new Entity("Person", "c");
- c.setProperty("height", 201);
- Entity d = new Entity("Person", "d");
- d.setProperty("height", 198);
- Entity e = new Entity("Person", "e");
- e.setProperty("height", 202);
- Entity f = new Entity("Person", "f");
- f.setProperty("height", 197);
- Entity g = new Entity("Person", "g");
- g.setProperty("height", 203);
- Entity h = new Entity("Person", "h");
- h.setProperty("height", 196);
- datastore.put(ImmutableList.of(a, b, c, d, e, f, g, h));
-
- List results = getTallestPeople();
-
- assertThat(results).named("results").containsExactly(g, e, c, a, b).inOrder();
- }
-}
diff --git a/appengine/datastore/src/test/java/com/example/appengine/ReadPolicyTest.java b/appengine/datastore/src/test/java/com/example/appengine/ReadPolicyTest.java
deleted file mode 100644
index 0742a37acd1..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/ReadPolicyTest.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceConfig;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-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.datastore.ReadPolicy;
-import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
-import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
-import com.google.common.collect.ImmutableList;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-import java.util.List;
-
-/**
- * Unit tests for {@link ReadPolicy}.
- */
-@RunWith(JUnit4.class)
-public class ReadPolicyTest {
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(
- // Set 100% eventual consistency, so we can test with other job policies.
- // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(100));
-
- @Before
- public void setUp() {
- helper.setUp();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- @Test
- public void readPolicy_eventual_returnsNoResults() {
- // [START data_consistency]
- double deadline = 5.0;
-
- // Construct a read policy for eventual consistency
- ReadPolicy policy = new ReadPolicy(ReadPolicy.Consistency.EVENTUAL);
-
- // Set the read policy
- DatastoreServiceConfig eventuallyConsistentConfig =
- DatastoreServiceConfig.Builder.withReadPolicy(policy);
-
- // Set the call deadline
- DatastoreServiceConfig deadlineConfig = DatastoreServiceConfig.Builder.withDeadline(deadline);
-
- // Set both the read policy and the call deadline
- DatastoreServiceConfig datastoreConfig =
- DatastoreServiceConfig.Builder.withReadPolicy(policy).deadline(deadline);
-
- // Get Datastore service with the given configuration
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(datastoreConfig);
- // [END data_consistency]
-
- Entity parent = new Entity("Person", "a");
- Entity child = new Entity("Person", "b", parent.getKey());
- datastore.put(ImmutableList.of(parent, child));
-
- // Even though we are using an ancestor query, the policy is set to
- // eventual, so we should get eventually-consistent results. Since the
- // local data store test config is set to 100% unapplied jobs, there
- // should be no results.
- Query q = new Query("Person").setAncestor(parent.getKey());
- List results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").isEmpty();
- }
-
- @Test
- public void readPolicy_strong_returnsAllResults() {
- double deadline = 5.0;
- ReadPolicy policy = new ReadPolicy(ReadPolicy.Consistency.STRONG);
- DatastoreServiceConfig datastoreConfig =
- DatastoreServiceConfig.Builder.withReadPolicy(policy).deadline(deadline);
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(datastoreConfig);
-
- Entity parent = new Entity("Person", "a");
- Entity child = new Entity("Person", "b", parent.getKey());
- datastore.put(ImmutableList.of(parent, child));
-
- Query q = new Query("Person").setAncestor(parent.getKey());
- List results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
- assertThat(results).named("query results").hasSize(2);
- }
-}
diff --git a/appengine/datastore/src/test/java/com/example/appengine/StartupServletTest.java b/appengine/datastore/src/test/java/com/example/appengine/StartupServletTest.java
deleted file mode 100644
index cf54f983097..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/StartupServletTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.when;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.Query;
-import com.google.appengine.api.datastore.Query.Filter;
-import com.google.appengine.api.datastore.Query.FilterOperator;
-import com.google.appengine.api.datastore.Query.FilterPredicate;
-import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
-import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * Unit tests for {@link StartupServlet}.
- */
-@RunWith(JUnit4.class)
-public class StartupServletTest {
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(
- // Set no eventual consistency, that way queries return all results.
- // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(0));
-
- @Mock private HttpServletRequest mockRequest;
- @Mock private HttpServletResponse mockResponse;
- private StringWriter responseWriter;
- private DatastoreService datastore;
-
- private StartupServlet servletUnderTest;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- helper.setUp();
- datastore = DatastoreServiceFactory.getDatastoreService();
-
- // Set up a fake HTTP response.
- responseWriter = new StringWriter();
- when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter));
-
- servletUnderTest = new StartupServlet();
- }
-
- @After
- public void tearDown() {
- helper.tearDown();
- }
-
- @Test
- public void doGet_emptyDatastore_writesOkay() throws Exception {
- servletUnderTest.doGet(mockRequest, mockResponse);
- assertThat(responseWriter.toString()).named("StartupServlet response").isEqualTo("ok\n");
- }
-
- @Test
- public void doGet_emptyDatastore_writesPresidents() throws Exception {
- servletUnderTest.doGet(mockRequest, mockResponse);
-
- Filter nameFilter = new FilterPredicate("name", FilterOperator.EQUAL, "George Washington");
- Query q = new Query("Person").setFilter(nameFilter);
- Entity result = datastore.prepare(q).asSingleEntity();
- assertThat(result.getProperty("name")).named("name").isEqualTo("George Washington");
- }
-
- @Test
- public void doGet_alreadyPopulated_writesOkay() throws Exception {
- datastore.put(
- new Entity(StartupServlet.IS_POPULATED_ENTITY, StartupServlet.IS_POPULATED_KEY_NAME));
- servletUnderTest.doGet(mockRequest, mockResponse);
- assertThat(responseWriter.toString()).named("StartupServlet response").isEqualTo("ok\n");
- }
-}
diff --git a/appengine/datastore/src/test/java/com/example/appengine/TransactionsTest.java b/appengine/datastore/src/test/java/com/example/appengine/TransactionsTest.java
deleted file mode 100644
index 6247f3fe06c..00000000000
--- a/appengine/datastore/src/test/java/com/example/appengine/TransactionsTest.java
+++ /dev/null
@@ -1,309 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.fail;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.EntityNotFoundException;
-import com.google.appengine.api.datastore.FetchOptions;
-import com.google.appengine.api.datastore.Key;
-import com.google.appengine.api.datastore.KeyFactory;
-import com.google.appengine.api.datastore.PreparedQuery;
-import com.google.appengine.api.datastore.Query;
-import com.google.appengine.api.datastore.Transaction;
-import com.google.appengine.api.datastore.TransactionOptions;
-import com.google.appengine.api.taskqueue.Queue;
-import com.google.appengine.api.taskqueue.QueueFactory;
-import com.google.appengine.api.taskqueue.TaskOptions;
-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.ConcurrentModificationException;
-import java.util.Date;
-import java.util.List;
-
-/**
- * Unit tests to demonstrate App Engine Datastore transactions.
- */
-@RunWith(JUnit4.class)
-public class TransactionsTest {
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(
- // Use High Rep job policy to allow cross group transactions in tests.
- new LocalDatastoreServiceTestConfig().setApplyAllHighRepJobPolicy());
-
- private DatastoreService datastore;
-
- @Before
- public void setUp() {
- helper.setUp();
- datastore = DatastoreServiceFactory.getDatastoreService();
- }
-
- @After
- public void tearDown() {
- // Clean up any dangling transactions.
- Transaction txn = datastore.getCurrentTransaction(null);
- if (txn != null && txn.isActive()) {
- txn.rollback();
- }
- helper.tearDown();
- }
-
- @Test
- public void usingTransactions() throws Exception {
- Entity joe = new Entity("Employee", "Joe");
- datastore.put(joe);
-
- // [START using_transactions]
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
- Transaction txn = datastore.beginTransaction();
- try {
- Key employeeKey = KeyFactory.createKey("Employee", "Joe");
- Entity employee = datastore.get(employeeKey);
- employee.setProperty("vacationDays", 10);
-
- datastore.put(txn, employee);
-
- txn.commit();
- } finally {
- if (txn.isActive()) {
- txn.rollback();
- }
- }
- // [END using_transactions]
- }
-
- @Test
- public void entityGroups() throws Exception {
- try {
- // [START entity_groups]
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
- Entity person = new Entity("Person", "tom");
- datastore.put(person);
-
- // Transactions on root entities
- Transaction txn = datastore.beginTransaction();
-
- Entity tom = datastore.get(person.getKey());
- tom.setProperty("age", 40);
- datastore.put(txn, tom);
- txn.commit();
-
- // Transactions on child entities
- txn = datastore.beginTransaction();
- tom = datastore.get(person.getKey());
- Entity photo = new Entity("Photo", tom.getKey());
-
- // Create a Photo that is a child of the Person entity named "tom"
- photo.setProperty("photoUrl", "http://domain.com/path/to/photo.jpg");
- datastore.put(txn, photo);
- txn.commit();
-
- // Transactions on entities in different entity groups
- txn = datastore.beginTransaction();
- tom = datastore.get(person.getKey());
- Entity photoNotAChild = new Entity("Photo");
- photoNotAChild.setProperty("photoUrl", "http://domain.com/path/to/photo.jpg");
- datastore.put(txn, photoNotAChild);
-
- // Throws IllegalArgumentException because the Person entity
- // and the Photo entity belong to different entity groups.
- txn.commit();
- // [END entity_groups]
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- // We expect to get an exception that complains that we don't have a XG-transaction.
- }
- }
-
- @Test
- public void creatingAnEntityInASpecificEntityGroup() throws Exception {
- String boardName = "my-message-board";
-
- // [START creating_an_entity_in_a_specific_entity_group]
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
-
- String messageTitle = "Some Title";
- String messageText = "Some message.";
- Date postDate = new Date();
-
- Transaction txn = datastore.beginTransaction();
-
- Key messageBoardKey = KeyFactory.createKey("MessageBoard", boardName);
-
- Entity message = new Entity("Message", messageBoardKey);
- message.setProperty("message_title", messageTitle);
- message.setProperty("message_text", messageText);
- message.setProperty("post_date", postDate);
- datastore.put(txn, message);
-
- txn.commit();
- // [END creating_an_entity_in_a_specific_entity_group]
- }
-
- @Test
- public void crossGroupTransactions() throws Exception {
- // [START cross-group_XG_transactions_using_the_Java_low-level_API]
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
- TransactionOptions options = TransactionOptions.Builder.withXG(true);
- Transaction txn = datastore.beginTransaction(options);
-
- Entity a = new Entity("A");
- a.setProperty("a", 22);
- datastore.put(txn, a);
-
- Entity b = new Entity("B");
- b.setProperty("b", 11);
- datastore.put(txn, b);
-
- txn.commit();
- // [END cross-group_XG_transactions_using_the_Java_low-level_API]
- }
-
- @Test
- public void usesForTransactions_relativeUpdates() throws Exception {
- String boardName = "my-message-board";
- Entity b = new Entity("MessageBoard", boardName);
- b.setProperty("count", 41);
- datastore.put(b);
-
- // [START uses_for_transactions_1]
- int retries = 3;
- while (true) {
- Transaction txn = datastore.beginTransaction();
- try {
- Key boardKey = KeyFactory.createKey("MessageBoard", boardName);
- Entity messageBoard = datastore.get(boardKey);
-
- long count = (Long) messageBoard.getProperty("count");
- ++count;
- messageBoard.setProperty("count", count);
- datastore.put(txn, messageBoard);
-
- txn.commit();
- break;
- } catch (ConcurrentModificationException e) {
- if (retries == 0) {
- throw e;
- }
- // Allow retry to occur
- --retries;
- } finally {
- if (txn.isActive()) {
- txn.rollback();
- }
- }
- }
- // [END uses_for_transactions_1]
-
- b = datastore.get(KeyFactory.createKey("MessageBoard", boardName));
- assertThat((long) b.getProperty("count")).named("board.count").isEqualTo(42L);
- }
-
- private Entity fetchOrCreate(String boardName) {
- // [START uses_for_transactions_2]
- Transaction txn = datastore.beginTransaction();
- Entity messageBoard;
- Key boardKey;
- try {
- boardKey = KeyFactory.createKey("MessageBoard", boardName);
- messageBoard = datastore.get(boardKey);
- } catch (EntityNotFoundException e) {
- messageBoard = new Entity("MessageBoard", boardName);
- messageBoard.setProperty("count", 0L);
- boardKey = datastore.put(txn, messageBoard);
- }
- txn.commit();
- // [END uses_for_transactions_2]
-
- return messageBoard;
- }
-
- @Test
- public void usesForTransactions_fetchOrCreate_fetchesExisting() throws Exception {
- Entity b = new Entity("MessageBoard", "my-message-board");
- b.setProperty("count", 7);
- datastore.put(b);
-
- Entity board = fetchOrCreate("my-message-board");
-
- assertThat((long) board.getProperty("count")).named("board.count").isEqualTo(7L);
- }
-
- @Test
- public void usesForTransactions_fetchOrCreate_createsNew() throws Exception {
- Entity board = fetchOrCreate("my-message-board");
- assertThat((long) board.getProperty("count")).named("board.count").isEqualTo(0L);
- }
-
- @Test
- public void usesForTransactions_readSnapshot() throws Exception {
- String boardName = "my-message-board";
- Entity b = new Entity("MessageBoard", boardName);
- b.setProperty("count", 13);
- datastore.put(b);
-
- // [START uses_for_transactions_3]
- DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
-
- // Display information about a message board and its first 10 messages.
- Key boardKey = KeyFactory.createKey("MessageBoard", boardName);
-
- Transaction txn = datastore.beginTransaction();
-
- Entity messageBoard = datastore.get(boardKey);
- long count = (Long) messageBoard.getProperty("count");
-
- Query q = new Query("Message", boardKey);
-
- // This is an ancestor query.
- PreparedQuery pq = datastore.prepare(txn, q);
- List messages = pq.asList(FetchOptions.Builder.withLimit(10));
-
- txn.commit();
- // [END uses_for_transactions_3]
-
- assertThat(count).named("board.count").isEqualTo(13L);
- }
-
- @Test
- public void transactionalTaskEnqueuing() throws Exception {
- // [START transactional_task_enqueuing]
- DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
- Queue queue = QueueFactory.getDefaultQueue();
- Transaction txn = datastore.beginTransaction();
- // ...
-
- queue.add(TaskOptions.Builder.withUrl("/path/to/handler"));
-
- // ...
-
- txn.commit();
- // [END transactional_task_enqueuing]
- }
-}
diff --git a/appengine/firebase-event-proxy/README.md b/appengine/firebase-event-proxy/README.md
deleted file mode 100644
index eeb8b4ac107..00000000000
--- a/appengine/firebase-event-proxy/README.md
+++ /dev/null
@@ -1,49 +0,0 @@
-# App Engine Firebase Event Proxy
-
-An example app that illustrates how to create a Java App Engine Standard Environment
-app that proxies Firebase events to another App Engine app.
-
-# Java Firebase Event Proxy
-Illustrates how to authenticate and subscribe to Firebase from Java App Engine.
-
-# Python App Engine Listener
-Illustrates how to authenticate messages received from the proxy app.
-
-## Setup
-
-### Java Firebase Event Proxy
-Firebase Secret
-Put your Firebase secret in the file:
-gae-firebase-event-proxy/src/main/webapp/firebase-secret.properties
-```
-firebaseSecret=
-```
-
-* Billing must be enabled from Cloud console.
-* Manual scaling should turned on and configured to 1 instance in appengine-web.xml
-
-## Running locally
-### Java Firebase Event Proxy
-```
-cd gae-firebase-event-proxy
-mvn appengine:devserver
-```
-
-### Python App Engine Listener
-```
-cd gae-firebase-listener-python
-dev_appserver .
-```
-
-## Deploying
-
-### Java Firebase Event Proxy
-```
-cd gae-firebase-event-proxy
-mvn appengine:upload
-```
-
-### Python App Engine Listener
-```
-appcfg.py -A -V v1 update gae-firebase-listener-python
-```
diff --git a/appengine/firebase-event-proxy/gae-firebase-event-proxy/pom.xml b/appengine/firebase-event-proxy/gae-firebase-event-proxy/pom.xml
deleted file mode 100644
index 9f062705dce..00000000000
--- a/appengine/firebase-event-proxy/gae-firebase-event-proxy/pom.xml
+++ /dev/null
@@ -1,103 +0,0 @@
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
-
- com.example.gaefirebaseeventproxy
- gaefirebaseeventproxy
-
-
- com.google.cloud
- doc-samples
- 1.0.0
- ../../..
-
-
-
- gae-firebase-event-proxy
- 1
- UTF-8
- true
-
-
-
- 3.1.0
-
-
-
-
-
- com.google.appengine
- appengine-api-1.0-sdk
- ${appengine.sdk.version}
-
-
- javax.servlet
- servlet-api
- 2.5
- provided
-
-
- jstl
- jstl
- 1.2
-
-
- com.google.firebase
- firebase-server-sdk
- 3.0.1
-
-
- com.fasterxml.jackson.core
- jackson-core
- 2.8.1
-
-
- com.fasterxml.jackson.core
- jackson-databind
- 2.8.1
-
-
-
-
- com.google.appengine
- appengine-testing
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-api-stubs
- ${appengine.sdk.version}
- test
-
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
- false
- ${app.version}
-
-
-
-
-
diff --git a/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/java/com/example/GaeFirebaseEventProxy/FirebaseEventProxy.java b/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/java/com/example/GaeFirebaseEventProxy/FirebaseEventProxy.java
deleted file mode 100644
index bd706ba03e4..00000000000
--- a/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/java/com/example/GaeFirebaseEventProxy/FirebaseEventProxy.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.gaefirebaseeventproxy;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.appengine.api.utils.SystemProperty;
-import com.google.firebase.FirebaseApp;
-import com.google.firebase.FirebaseOptions;
-import com.google.firebase.database.DataSnapshot;
-import com.google.firebase.database.DatabaseError;
-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;
-import java.net.URL;
-import java.net.URLEncoder;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.logging.Logger;
-
-public class FirebaseEventProxy {
-
- private static final Logger log = Logger.getLogger(FirebaseEventProxy.class.getName());
-
- public FirebaseEventProxy() {
- String firebaseLocation = "https://crackling-torch-392.firebaseio.com";
- Map databaseAuthVariableOverride = new HashMap();
- // uid and provider will have to match what you have in your firebase security rules
- databaseAuthVariableOverride.put("uid", "gae-firebase-event-proxy");
- databaseAuthVariableOverride.put("provider", "com.example");
- try {
- FirebaseOptions options = new FirebaseOptions.Builder()
- .setServiceAccount(new FileInputStream("gae-firebase-secrets.json"))
- .setDatabaseUrl(firebaseLocation)
- .setDatabaseAuthVariableOverride(databaseAuthVariableOverride).build();
- FirebaseApp.initializeApp(options);
- } catch (IOException e) {
- throw new RuntimeException(
- "Error reading firebase secrets from file: src/main/webapp/gae-firebase-secrets.json: "
- + e.getMessage());
- }
- }
-
- public void start() {
- DatabaseReference firebase = FirebaseDatabase.getInstance().getReference();
-
- // Subscribe to value events. Depending on use case, you may want to subscribe to child events
- // through childEventListener.
- firebase.addValueEventListener(new ValueEventListener() {
- @Override
- public void onDataChange(DataSnapshot snapshot) {
- if (snapshot.exists()) {
- try {
- // Convert value to JSON using Jackson
- String json = new ObjectMapper().writeValueAsString(snapshot.getValue(false));
-
- // Replace the URL with the url of your own listener app.
- URL dest = new URL("http://gae-firebase-listener-python.appspot.com/log");
- HttpURLConnection connection = (HttpURLConnection) dest.openConnection();
- connection.setRequestMethod("POST");
- connection.setDoOutput(true);
-
- // Rely on X-Appengine-Inbound-Appid to authenticate. Turning off redirects is
- // required to enable.
- connection.setInstanceFollowRedirects(false);
-
- // Fill out header if in dev environment
- if (SystemProperty.environment.value() != SystemProperty.Environment.Value.Production) {
- connection.setRequestProperty("X-Appengine-Inbound-Appid", "dev-instance");
- }
-
- // Put Firebase data into http request
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append("&fbSnapshot=");
- stringBuilder.append(URLEncoder.encode(json, "UTF-8"));
- connection.getOutputStream().write(stringBuilder.toString().getBytes());
- if (connection.getResponseCode() != 200) {
- log.severe("Forwarding failed");
- } else {
- log.info("Sent: " + json);
- }
- } catch (JsonProcessingException e) {
- log.severe("Unable to convert Firebase response to JSON: " + e.getMessage());
- } catch (IOException e) {
- log.severe("Error in connecting to app engine: " + e.getMessage());
- }
- }
- }
-
- @Override
- public void onCancelled(DatabaseError error) {
- log.severe("Firebase connection cancelled: " + error.getMessage());
- }
- });
- }
-}
diff --git a/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/java/com/example/GaeFirebaseEventProxy/ServletContextListenerImpl.java b/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/java/com/example/GaeFirebaseEventProxy/ServletContextListenerImpl.java
deleted file mode 100644
index ffee0cee769..00000000000
--- a/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/java/com/example/GaeFirebaseEventProxy/ServletContextListenerImpl.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.gaefirebaseeventproxy;
-
-import java.util.logging.Logger;
-
-import javax.servlet.ServletContextEvent;
-import javax.servlet.ServletContextListener;
-
-// ServletContextListener that is called whenever your App Engine app starts up.
-public class ServletContextListenerImpl implements ServletContextListener {
-
- private static final Logger log = Logger.getLogger(ServletContextListener.class.getName());
-
- @Override
- public void contextInitialized(ServletContextEvent event) {
- log.info("Starting ....");
- FirebaseEventProxy proxy = new FirebaseEventProxy();
- proxy.start();
- }
-
- @Override
- public void contextDestroyed(ServletContextEvent event) {
- // App Engine does not currently invoke this method.
- }
-}
diff --git a/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index dcf0932551f..00000000000
--- a/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-
- ${app.id}
- ${app.version}
- true
-
-
- 1
-
-
-
-
-
-
diff --git a/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/webapp/WEB-INF/logging.properties b/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/webapp/WEB-INF/logging.properties
deleted file mode 100644
index e325f6cb079..00000000000
--- a/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/webapp/WEB-INF/logging.properties
+++ /dev/null
@@ -1,27 +0,0 @@
-# Copyright 2016 Google Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# A default java.util.logging configuration.
-# (All App Engine logging is through java.util.logging by default).
-#
-# To use this configuration, copy it into your application's WEB-INF
-# folder and add the following to your appengine-web.xml:
-#
-#
-#
-#
-#
-
-# Set the default logging level for all loggers to WARNING
-.level = INFO
diff --git a/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/webapp/WEB-INF/web.xml b/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 427fd14c909..00000000000
--- a/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
-
- com.example.gaefirebaseeventproxy.ServletContextListenerImpl
-
-
- index.jsp
-
-
diff --git a/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/webapp/index.jsp b/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/webapp/index.jsp
deleted file mode 100644
index ffc7d85f599..00000000000
--- a/appengine/firebase-event-proxy/gae-firebase-event-proxy/src/main/webapp/index.jsp
+++ /dev/null
@@ -1,25 +0,0 @@
-<%--
-Copyright 2015 Google Inc. All Rights Reserved.
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
---%>
-
-<%@ page contentType="text/html;charset=UTF-8" language="java" %>
-
-
-
-
-
-
-
-
Status: up
-
-
-
diff --git a/appengine/firebase-event-proxy/gae-firebase-listener-python/.gitignore b/appengine/firebase-event-proxy/gae-firebase-listener-python/.gitignore
deleted file mode 100644
index 0d20b6487c6..00000000000
--- a/appengine/firebase-event-proxy/gae-firebase-listener-python/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-*.pyc
diff --git a/appengine/firebase-event-proxy/gae-firebase-listener-python/app.yaml b/appengine/firebase-event-proxy/gae-firebase-listener-python/app.yaml
deleted file mode 100644
index f041d384c05..00000000000
--- a/appengine/firebase-event-proxy/gae-firebase-listener-python/app.yaml
+++ /dev/null
@@ -1,7 +0,0 @@
-runtime: python27
-api_version: 1
-threadsafe: true
-
-handlers:
-- url: /.*
- script: main.app
diff --git a/appengine/firebase-event-proxy/gae-firebase-listener-python/main.py b/appengine/firebase-event-proxy/gae-firebase-listener-python/main.py
deleted file mode 100644
index 49145bbd749..00000000000
--- a/appengine/firebase-event-proxy/gae-firebase-listener-python/main.py
+++ /dev/null
@@ -1,38 +0,0 @@
-# Copyright 2016 Google Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import os
-import webapp2
-
-IS_DEV = os.environ["SERVER_SOFTWARE"][:3] == "Dev"
-allowed_users = set()
-if IS_DEV:
- allowed_users.add("dev-instance")
-else:
- # Add your Java App Engine proxy App Id here
- allowed_users.add("your-java-appengine-proxy-app-id")
-
-class LoggingHandler(webapp2.RequestHandler):
-
- def post(self):
- user = self.request.headers.get('X-Appengine-Inbound-Appid', None)
- if user and user in allowed_users:
- firebaseSnapshot = self.request.params['fbSnapshot']
- print firebaseSnapshot
- else:
- print "Got unauthenticated user: %s" % user
-
-app = webapp2.WSGIApplication([
- webapp2.Route('/log', LoggingHandler),
-])
diff --git a/appengine/guestbook-objectify/README.md b/appengine/guestbook-objectify/README.md
deleted file mode 100644
index 2a7ee9cd289..00000000000
--- a/appengine/guestbook-objectify/README.md
+++ /dev/null
@@ -1,17 +0,0 @@
-# appengine/guestbook-objectify
-
-An App Engine guestbook using Java, Maven, and Objectify.
-
-Data access using [Objectify](https://github.com/objectify/objectify)
-
-Please ask questions on [Stackoverflow](http://stackoverflow.com/questions/tagged/google-app-engine)
-
-## Running Locally
-
-How do I, as a developer, start working on the project?
-
-1. `mvn clean appengine:devserver`
-
-## Deploying
-
-1. `mvn clean appengine:update -Dappengine.appId=PROJECT -Dappengine.version=VERSION`
diff --git a/appengine/guestbook-objectify/pom.xml b/appengine/guestbook-objectify/pom.xml
deleted file mode 100644
index 12946aace0d..00000000000
--- a/appengine/guestbook-objectify/pom.xml
+++ /dev/null
@@ -1,121 +0,0 @@
-
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
-
- com.example.appengine
- appengine-guestbook-objectify
-
- 5.1.5
- 18.0
-
-
- com.google.cloud
- doc-samples
- 1.0.0
- ../..
-
-
-
-
- 3.3.9
-
-
-
-
-
-
- com.google.appengine
- appengine-api-1.0-sdk
- ${appengine.sdk.version}
-
-
- javax.servlet
- servlet-api
- 2.5
- provided
-
-
- jstl
- jstl
- 1.2
-
-
-
-
- com.google.guava
- guava
- ${guava.version}
-
-
- com.googlecode.objectify
- objectify
- ${objectify.version}
-
-
-
-
-
- junit
- junit
- 4.12
- test
-
-
- org.mockito
- mockito-all
- 1.10.19
- test
-
-
- com.google.appengine
- appengine-testing
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-api-stubs
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-tools-sdk
- ${appengine.sdk.version}
- test
-
-
- com.google.truth
- truth
- 0.29
- test
-
-
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
- false
-
-
-
-
-
-
-
-
-
diff --git a/appengine/guestbook-objectify/src/main/java/com/example/guestbook/Greeting.java b/appengine/guestbook-objectify/src/main/java/com/example/guestbook/Greeting.java
deleted file mode 100644
index 29c37d066ce..00000000000
--- a/appengine/guestbook-objectify/src/main/java/com/example/guestbook/Greeting.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- * Copyright 2014-2015 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//[START all]
-package com.example.guestbook;
-
-import com.googlecode.objectify.Key;
-import com.googlecode.objectify.annotation.Entity;
-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.
- *
- * 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.
- **/
-@Entity
-public class Greeting {
- @Parent Key theBook;
- @Id public Long id;
-
- public String authorEmail;
- public String authorId;
- public String content;
- @Index public Date date;
-
- /**
- * Simple constructor just sets the date.
- **/
- public Greeting() {
- date = new Date();
- }
-
- /**
- * A convenience constructor.
- **/
- public Greeting(String book, String content) {
- this();
- if ( book != null ) {
- theBook = Key.create(Guestbook.class, book); // Creating the Ancestor key
- } else {
- theBook = Key.create(Guestbook.class, "default");
- }
- this.content = content;
- }
-
- /**
- * Takes all important fields.
- **/
- public Greeting(String book, String content, String id, String email) {
- this(book, content);
- authorEmail = email;
- authorId = id;
- }
-
-}
-//[END all]
diff --git a/appengine/guestbook-objectify/src/main/java/com/example/guestbook/Guestbook.java b/appengine/guestbook-objectify/src/main/java/com/example/guestbook/Guestbook.java
deleted file mode 100644
index 73786e00249..00000000000
--- a/appengine/guestbook-objectify/src/main/java/com/example/guestbook/Guestbook.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * Copyright 2014-2015 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//[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.
- *
- * This is never actually created, but gives a hint to Objectify about our Ancestor key.
- */
-@Entity
-public class Guestbook {
- @Id public String book;
-}
-//[END all]
diff --git a/appengine/guestbook-objectify/src/main/java/com/example/guestbook/OfyHelper.java b/appengine/guestbook-objectify/src/main/java/com/example/guestbook/OfyHelper.java
deleted file mode 100644
index a5837295656..00000000000
--- a/appengine/guestbook-objectify/src/main/java/com/example/guestbook/OfyHelper.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * Copyright 2014-2015 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
- * in compliance with the License. You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-//[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
- * required to let JSP's access Ofy.
- **/
-public class OfyHelper implements ServletContextListener {
- 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(Guestbook.class);
- ObjectifyService.register(Greeting.class);
- }
-
- public void contextDestroyed(ServletContextEvent event) {
- // App Engine does not currently invoke this method.
- }
-}
-//[END all]
diff --git a/appengine/guestbook-objectify/src/main/java/com/example/guestbook/SignGuestbookServlet.java b/appengine/guestbook-objectify/src/main/java/com/example/guestbook/SignGuestbookServlet.java
deleted file mode 100644
index 2b7d368642a..00000000000
--- a/appengine/guestbook-objectify/src/main/java/com/example/guestbook/SignGuestbookServlet.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * Copyright 2014-2015 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//[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.
- */
-public class SignGuestbookServlet extends HttpServlet {
-
- // Process the http POST of the form
- @Override
- 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.
-
- String guestbookName = req.getParameter("guestbookName");
- String content = req.getParameter("content");
- if (user != null) {
- greeting = new Greeting(guestbookName, content, user.getUserId(), user.getEmail());
- } else {
- greeting = new Greeting(guestbookName, content);
- }
-
- // Use Objectify to save the greeting and now() is used to make the call synchronously as we
- // will immediately get a new page using redirect and we want the data to be present.
- ObjectifyService.ofy().save().entity(greeting).now();
-
- resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
- }
-}
-//[END all]
diff --git a/appengine/guestbook-objectify/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/guestbook-objectify/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index 8bf645d1013..00000000000
--- a/appengine/guestbook-objectify/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
- your-app-id
- ${appengine.app.version}
- true
-
-
-
-
-
diff --git a/appengine/guestbook-objectify/src/main/webapp/WEB-INF/logging.properties b/appengine/guestbook-objectify/src/main/webapp/WEB-INF/logging.properties
deleted file mode 100644
index a17206681f0..00000000000
--- a/appengine/guestbook-objectify/src/main/webapp/WEB-INF/logging.properties
+++ /dev/null
@@ -1,13 +0,0 @@
-# A default java.util.logging configuration.
-# (All App Engine logging is through java.util.logging by default).
-#
-# To use this configuration, copy it into your application's WEB-INF
-# folder and add the following to your appengine-web.xml:
-#
-#
-#
-#
-#
-
-# Set the default logging level for all loggers to WARNING
-.level = WARNING
diff --git a/appengine/guestbook-objectify/src/main/webapp/WEB-INF/web.xml b/appengine/guestbook-objectify/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index d5a23626f0c..00000000000
--- a/appengine/guestbook-objectify/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
-
-
- sign
- com.example.guestbook.SignGuestbookServlet
-
-
-
- sign
- /sign
-
-
-
- guestbook.jsp
-
-
-
-
-
- ObjectifyFilter
- com.googlecode.objectify.ObjectifyFilter
-
-
- ObjectifyFilter
- /*
-
-
- com.example.guestbook.OfyHelper
-
-
-
diff --git a/appengine/guestbook-objectify/src/main/webapp/guestbook.jsp b/appengine/guestbook-objectify/src/main/webapp/guestbook.jsp
deleted file mode 100644
index 481274ceb84..00000000000
--- a/appengine/guestbook-objectify/src/main/webapp/guestbook.jsp
+++ /dev/null
@@ -1,106 +0,0 @@
-<%-- //[START all]--%>
-<%@ page contentType="text/html;charset=UTF-8" language="java" %>
-<%@ page import="com.google.appengine.api.users.User" %>
-<%@ page import="com.google.appengine.api.users.UserService" %>
-<%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
-
-<%-- //[START imports]--%>
-<%@ page import="com.example.guestbook.Greeting" %>
-<%@ page import="com.example.guestbook.Guestbook" %>
-<%@ page import="com.googlecode.objectify.Key" %>
-<%@ page import="com.googlecode.objectify.ObjectifyService" %>
-<%-- //[END imports]--%>
-
-<%@ page import="java.util.List" %>
-<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
-
-
-
-
-
-
-
-
-<%
- String guestbookName = request.getParameter("guestbookName");
- if (guestbookName == null) {
- guestbookName = "default";
- }
- pageContext.setAttribute("guestbookName", guestbookName);
- UserService userService = UserServiceFactory.getUserService();
- User user = userService.getCurrentUser();
- if (user != null) {
- pageContext.setAttribute("user", user);
-%>
-
-
Hello, ${fn:escapeXml(user.nickname)}! (You can
- sign out.)
-<%
- } else {
-%>
-
Hello!
- Sign in
- to include your name with greetings you post.
-<%
- }
-%>
-
-<%-- //[START datastore]--%>
-<%
- // Create the correct Ancestor key
- Key theBook = Key.create(Guestbook.class, guestbookName);
-
- // Run an ancestor query to ensure we see the most up-to-date
- // view of the Greetings belonging to the selected Guestbook.
- List greetings = ObjectifyService.ofy()
- .load()
- .type(Greeting.class) // We want only Greetings
- .ancestor(theBook) // Anyone in this book
- .order("-date") // Most recent first - date is indexed.
- .limit(5) // Only show 5 of them.
- .list();
-
- if (greetings.isEmpty()) {
-%>
-
Guestbook '${fn:escapeXml(guestbookName)}' has no messages.
-<%
- } else {
-%>
-
Messages in Guestbook '${fn:escapeXml(guestbookName)}'.
-<%
- }
- }
-%>
-
-
-<%-- //[END datastore]--%>
-
-
-
-
-<%-- //[END all]--%>
diff --git a/appengine/guestbook-objectify/src/main/webapp/stylesheets/main.css b/appengine/guestbook-objectify/src/main/webapp/stylesheets/main.css
deleted file mode 100644
index 05d72d5536d..00000000000
--- a/appengine/guestbook-objectify/src/main/webapp/stylesheets/main.css
+++ /dev/null
@@ -1,4 +0,0 @@
-body {
- font-family: Verdana, Helvetica, sans-serif;
- background-color: #FFFFCC;
-}
diff --git a/appengine/guestbook-objectify/src/test/java/com/example/guestbook/GreetingTest.java b/appengine/guestbook-objectify/src/test/java/com/example/guestbook/GreetingTest.java
deleted file mode 100644
index 085c1778275..00000000000
--- a/appengine/guestbook-objectify/src/test/java/com/example/guestbook/GreetingTest.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.example.guestbook;
-
-import static com.example.guestbook.GuestbookTestUtilities.cleanDatastore;
-import static org.junit.Assert.assertEquals;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.KeyFactory;
-import com.google.appengine.api.datastore.PreparedQuery;
-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;
-import org.junit.Before;
-import org.junit.Test;
-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
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(0));
-
- private Closeable closeable;
- private DatastoreService ds;
-
- @Before
- public void setUp() throws Exception {
-
- helper.setUp();
- ds = DatastoreServiceFactory.getDatastoreService();
-
- ObjectifyService.register(Guestbook.class);
- ObjectifyService.register(Greeting.class);
-
- closeable = ObjectifyService.begin();
-
- cleanDatastore(ds, "default");
- }
-
- @After
- public void tearDown() {
- cleanDatastore(ds, "default");
- helper.tearDown();
- closeable.close();
- }
-
- @Test
- 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());
- PreparedQuery pq = ds.prepare(query);
- Entity greeting = pq.asSingleEntity(); // Should only be one at this point.
- assertEquals(greeting.getProperty("content"), TEST_CONTENT);
- }
-}
diff --git a/appengine/guestbook-objectify/src/test/java/com/example/guestbook/GuestbookTestUtilities.java b/appengine/guestbook-objectify/src/test/java/com/example/guestbook/GuestbookTestUtilities.java
deleted file mode 100644
index 4480fd111bd..00000000000
--- a/appengine/guestbook-objectify/src/test/java/com/example/guestbook/GuestbookTestUtilities.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.example.guestbook;
-
-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.Key;
-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();
- PreparedQuery pq = ds.prepare(query);
- List entities = pq.asList(FetchOptions.Builder.withDefaults());
- ArrayList keys = new ArrayList<>(entities.size());
-
- for (Entity e : entities) {
- keys.add(e.getKey());
- }
- ds.delete(keys);
- }
-
-}
diff --git a/appengine/guestbook-objectify/src/test/java/com/example/guestbook/SignGuestbookServletTest.java b/appengine/guestbook-objectify/src/test/java/com/example/guestbook/SignGuestbookServletTest.java
deleted file mode 100644
index 1c762be9511..00000000000
--- a/appengine/guestbook-objectify/src/test/java/com/example/guestbook/SignGuestbookServletTest.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright 2015 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.guestbook;
-
-import static com.example.guestbook.GuestbookTestUtilities.cleanDatastore;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.when;
-
-import com.google.appengine.api.datastore.DatastoreService;
-import com.google.appengine.api.datastore.DatastoreServiceFactory;
-import com.google.appengine.api.datastore.Entity;
-import com.google.appengine.api.datastore.KeyFactory;
-import com.google.appengine.api.datastore.PreparedQuery;
-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;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * Unit tests for {@link com.example.guestbook.SignGuestbookServlet}.
- */
-@RunWith(JUnit4.class)
-public class SignGuestbookServletTest {
- private static final String FAKE_URL = "fakey.org/sign";
- private static final String FAKE_NAME = "Fake";
-
- private final LocalServiceTestHelper helper =
- new LocalServiceTestHelper(
- // Set no eventual consistency, that way queries return all results.
- // https://cloud.google.com/appengine/docs/java/tools/localunittesting#Java_Writing_High_Replication_Datastore_tests
- new LocalDatastoreServiceTestConfig()
- .setDefaultHighRepJobPolicyUnappliedJobPercentage(0));
-
- private final String testPhrase = "Noew is the time";
-
- @Mock private HttpServletRequest mockRequest;
-
- @Mock
- private HttpServletResponse mockResponse;
-
- private StringWriter stringWriter;
- private SignGuestbookServlet servletUnderTest;
- private Closeable closeable;
- private DatastoreService ds;
-
- @Before
- public void setUp() throws Exception {
-
- MockitoAnnotations.initMocks(this);
- helper.setUp();
- ds = DatastoreServiceFactory.getDatastoreService();
-
- // Set up some fake HTTP requests
- when(mockRequest.getRequestURI()).thenReturn(FAKE_URL);
- when(mockRequest.getParameter("guestbookName")).thenReturn( "default" );
- when(mockRequest.getParameter("content")).thenReturn( testPhrase );
-
- stringWriter = new StringWriter();
- when(mockResponse.getWriter()).thenReturn(new PrintWriter(stringWriter));
-
- servletUnderTest = new SignGuestbookServlet();
-
- ObjectifyService.register(Guestbook.class);
- ObjectifyService.register(Greeting.class);
-
- closeable = ObjectifyService.begin();
-
- cleanDatastore(ds, "default");
- }
-
- @After public void tearDown() {
- cleanDatastore(ds, "default");
- helper.tearDown();
- closeable.close();
- }
-
- @Test
- public void doPost_userNotLoggedIn() throws Exception {
- servletUnderTest.doPost(mockRequest, mockResponse);
-
- 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.
- assertEquals(greeting.getProperty("content"), testPhrase);
- }
-
-}
diff --git a/appengine/helloworld/README.md b/appengine/helloworld/README.md
deleted file mode 100644
index 9cdb309b185..00000000000
--- a/appengine/helloworld/README.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# Google App Engine Standard Environment Hello World Sample
-
-This sample demonstrates how to deploy an application on Google App Engine.
-
-See the [Google App Engine standard environment documentation][ae-docs] for more
-detailed instructions.
-
-[ae-docs]: https://cloud.google.com/appengine/docs/java/
-
-## Setup
-1. Update the `` tag in `src/main/webapp/WEB-INF/appengine-web.xml`
- with your project name.
-1. Update the `` tag in `src/main/webapp/WEB-INF/appengine-web.xml`
- with your version name.
-
-## Running locally
- $ mvn appengine:devserver
-
-## Deploying
- $ mvn appengine:update
diff --git a/appengine/helloworld/pom.xml b/appengine/helloworld/pom.xml
deleted file mode 100644
index af1b1b5899f..00000000000
--- a/appengine/helloworld/pom.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
- com.example.appengine
- appengine-helloworld
-
- com.google.cloud
- doc-samples
- 1.0.0
- ../..
-
-
-
- javax.servlet
- servlet-api
- jar
- provided
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
- org.apache.maven.plugins
- 3.3
- maven-compiler-plugin
-
-
- 1.7
-
-
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
-
-
-
diff --git a/appengine/helloworld/src/main/java/com/example/appengine/helloworld/HelloServlet.java b/appengine/helloworld/src/main/java/com/example/appengine/helloworld/HelloServlet.java
deleted file mode 100644
index d9135a0ce63..00000000000
--- a/appengine/helloworld/src/main/java/com/example/appengine/helloworld/HelloServlet.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * Copyright 2015 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine.helloworld;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-// [START example]
-@SuppressWarnings("serial")
-public class HelloServlet extends HttpServlet {
-
- @Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
- PrintWriter out = resp.getWriter();
- out.println("Hello, world");
- }
-}
-// [END example]
diff --git a/appengine/helloworld/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/helloworld/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index 468b6d0430a..00000000000
--- a/appengine/helloworld/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
- YOUR-PROJECT-ID
- YOUR-VERSION-ID
- true
-
-
diff --git a/appengine/helloworld/src/main/webapp/WEB-INF/web.xml b/appengine/helloworld/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 1a1704104a2..00000000000
--- a/appengine/helloworld/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-
- hello
- com.example.appengine.helloworld.HelloServlet
-
-
- hello
- /
-
-
diff --git a/appengine/images/README.md b/appengine/images/README.md
deleted file mode 100644
index 88edaa825f2..00000000000
--- a/appengine/images/README.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# Google App Engine Standard Environment Images Sample
-
-This sample demonstrates how to use the Images Java API.
-
-See the [Google App Engine standard environment documentation][ae-docs] for more
-detailed instructions.
-
-[ae-docs]: https://cloud.google.com/appengine/docs/java/
-
-## Modify the app
-
-Using the [Google Cloud SDK](https://cloud.google.com/sdk/) create a bucket
-
- $ gsutil mb YOUR-PROJECT-ID.appspot.com
-
-* Edit `src/main/java/com/example/appengine/images/ImageServlet.java` and set your `bucket` name.
-
-## Running locally
-
- This example uses the
- [App Engine maven plugin](https://cloud.google.com/appengine/docs/java/tools/maven).
- To run this sample locally:
-
- $ mvn appengine:devserver
-
- To see the results of the sample application, open
- [localhost:8080](http://localhost:8080) in a web browser.
-
-
-## Deploying
-
- In the following command, replace YOUR-PROJECT-ID with your
- [Google Cloud Project ID](https://developers.google.com/console/help/new/#projectnumber)
- and SOME-VERSION with a valid version number.
-
- $ mvn appengine:update -Dappengine.appId=YOUR-PROJECT-ID -Dappengine.version=SOME-VERSION
diff --git a/appengine/images/pom.xml b/appengine/images/pom.xml
deleted file mode 100644
index 8a977b97768..00000000000
--- a/appengine/images/pom.xml
+++ /dev/null
@@ -1,73 +0,0 @@
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
- com.example.appengine
- appengine-images
-
-
- 1.9.24
-
-
-
- com.google.cloud
- doc-samples
- 1.0.0
- ../..
-
-
-
-
- com.google.appengine
- appengine-api-1.0-sdk
- ${appengine.sdk.version}
-
-
- com.google.appengine.tools
- appengine-gcs-client
- 0.6
-
-
- javax.servlet
- servlet-api
- jar
- provided
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
- org.apache.maven.plugins
- 3.3
- maven-compiler-plugin
-
-
- 1.7
-
-
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
-
-
diff --git a/appengine/images/src/main/java/com/example/appengine/images/ImagesServlet.java b/appengine/images/src/main/java/com/example/appengine/images/ImagesServlet.java
deleted file mode 100644
index b7c9d853447..00000000000
--- a/appengine/images/src/main/java/com/example/appengine/images/ImagesServlet.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/**
- * Copyright 2015 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine.images;
-import com.google.appengine.api.blobstore.BlobKey;
-import com.google.appengine.api.blobstore.BlobstoreService;
-import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
-import com.google.appengine.api.images.Image;
-import com.google.appengine.api.images.ImagesService;
-import com.google.appengine.api.images.ImagesServiceFactory;
-import com.google.appengine.api.images.Transform;
-import com.google.appengine.tools.cloudstorage.GcsFileOptions;
-import com.google.appengine.tools.cloudstorage.GcsFilename;
-import com.google.appengine.tools.cloudstorage.GcsService;
-import com.google.appengine.tools.cloudstorage.GcsServiceFactory;
-import com.google.appengine.tools.cloudstorage.RetryParams;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.nio.ByteBuffer;
-import java.nio.channels.FileChannel;
-
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-// [START example]
-@SuppressWarnings("serial")
-public class ImagesServlet extends HttpServlet {
- final String bucket = "YOUR-BUCKETNAME-HERE";
-
- // [START gcs]
- private final GcsService gcsService = GcsServiceFactory.createGcsService(new RetryParams.Builder()
- .initialRetryDelayMillis(10)
- .retryMaxAttempts(10)
- .totalRetryPeriodMillis(15000)
- .build());
- // [END gcs]
-
- @Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-
- //[START original_image]
- // Read the image.jpg resource into a ByteBuffer.
- FileInputStream fileInputStream = new FileInputStream(new File("WEB-INF/image.jpg"));
- FileChannel fileChannel = fileInputStream.getChannel();
- ByteBuffer byteBuffer = ByteBuffer.allocate((int)fileChannel.size());
- fileChannel.read(byteBuffer);
-
- byte[] imageBytes = byteBuffer.array();
-
- // Write the original image to Cloud Storage
- gcsService.createOrReplace(
- new GcsFilename(bucket, "image.jpeg"),
- new GcsFileOptions.Builder().mimeType("image/jpeg").build(),
- ByteBuffer.wrap(imageBytes));
- //[END original_image]
-
- //[START resize]
- // Get an instance of the imagesService we can use to transform images.
- ImagesService imagesService = ImagesServiceFactory.getImagesService();
-
- // Make an image directly from a byte array, and transform it.
- Image image = ImagesServiceFactory.makeImage(imageBytes);
- Transform resize = ImagesServiceFactory.makeResize(100, 50);
- Image resizedImage = imagesService.applyTransform(resize, image);
-
- // Write the transformed image back to a Cloud Storage object.
- gcsService.createOrReplace(
- new GcsFilename(bucket, "resizedImage.jpeg"),
- new GcsFileOptions.Builder().mimeType("image/jpeg").build(),
- ByteBuffer.wrap(resizedImage.getImageData()));
- //[END resize]
-
- //[START rotate]
- // Make an image from a Cloud Storage object, and transform it.
- BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
- BlobKey blobKey = blobstoreService.createGsBlobKey("/gs/" + bucket + "/image.jpeg");
- Image blobImage = ImagesServiceFactory.makeImageFromBlob(blobKey);
- Transform rotate = ImagesServiceFactory.makeRotate(90);
- Image rotatedImage = imagesService.applyTransform(rotate, blobImage);
-
- // Write the transformed image back to a Cloud Storage object.
- gcsService.createOrReplace(
- new GcsFilename(bucket, "rotatedImage.jpeg"),
- new GcsFileOptions.Builder().mimeType("image/jpeg").build(),
- ByteBuffer.wrap(rotatedImage.getImageData()));
- //[END rotate]
-
- // Output some simple HTML to display the images we wrote to Cloud Storage
- // in the browser.
- PrintWriter out = resp.getWriter();
- out.println("\n");
- out.println("");
- out.println("");
- out.println("");
- out.println("\n");
- }
-}
-// [END example]
diff --git a/appengine/images/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/images/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index 07bb4d7de99..00000000000
--- a/appengine/images/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
-
- YOUR-PROJECT-ID
- YOUR-VERSION
- true
-
diff --git a/appengine/images/src/main/webapp/WEB-INF/image.jpg b/appengine/images/src/main/webapp/WEB-INF/image.jpg
deleted file mode 100644
index 3a60da2619d..00000000000
Binary files a/appengine/images/src/main/webapp/WEB-INF/image.jpg and /dev/null differ
diff --git a/appengine/images/src/main/webapp/WEB-INF/web.xml b/appengine/images/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 8ccba622877..00000000000
--- a/appengine/images/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-
- images
- com.example.appengine.images.ImagesServlet
-
-
- images
- /
-
-
diff --git a/appengine/logs/README.md b/appengine/logs/README.md
deleted file mode 100644
index 0d07745e5e8..00000000000
--- a/appengine/logs/README.md
+++ /dev/null
@@ -1,39 +0,0 @@
-# Users Authentication sample for Google App Engine
-
-This sample demonstrates how to use the [Logs API][log-docs] on [Google App
-Engine][ae-docs].
-
-[log-docs]: https://cloud.google.com/appengine/docs/java/logs/
-[ae-docs]: https://cloud.google.com/appengine/docs/java/
-
-## Running locally
-
-The Logs API only generates output for deployed apps, so this program should not be run locally.
-
-## Deploying
-
-This example uses the
-[Maven gcloud plugin](https://cloud.google.com/appengine/docs/java/managed-vms/maven).
-
-In the following command, replace YOUR-PROJECT-ID with your
-[Google Cloud Project ID](https://support.google.com/cloud/answer/6158840) and SOME-VERSION with the desired version number.
-
- $ mvn appengine:update -Dappengine.appId=YOUR-PROJECT-ID -Dappengine.version=SOME-VERSION
-
-## Setup
-To save your project settings so that you don't need to enter the
- parameters, you can:
-
-1. Update the tag in src/main/webapp/WEB-INF/appengine-web.xml
- with your project name.
-
-2. Update the tag in src/main/webapp/WEB-INF/appengine-web.xml
- with a valid version number.
-
-
-You will now be able to run
-
- $ mvn appengine:update
-
-without the need for any additional parameters.
-
diff --git a/appengine/logs/pom.xml b/appengine/logs/pom.xml
deleted file mode 100644
index f76565189d9..00000000000
--- a/appengine/logs/pom.xml
+++ /dev/null
@@ -1,79 +0,0 @@
-
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
- com.example.appengine
- appengine-logs
-
-
- com.google.cloud
- doc-samples
- 1.0.0
- ../..
-
-
-
- com.google.appengine
- appengine-api-1.0-sdk
- ${appengine.sdk.version}
-
-
- com.google.guava
- guava
- 19.0
-
-
- javax.servlet
- servlet-api
- 2.5
- jar
- provided
-
-
- org.json
- json
- 20160810
-
-
- joda-time
- joda-time
- 2.9.4
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
- org.apache.maven.plugins
- 3.3
- maven-compiler-plugin
-
-
- 1.7
-
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
-
-
diff --git a/appengine/logs/src/main/java/com/example/appengine/logs/LogsServlet.java b/appengine/logs/src/main/java/com/example/appengine/logs/LogsServlet.java
deleted file mode 100644
index 6ab30b504bd..00000000000
--- a/appengine/logs/src/main/java/com/example/appengine/logs/LogsServlet.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/* Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// [START logs_API_example]
-package com.example.appengine.logs;
-
-import com.google.appengine.api.log.AppLogLine;
-import com.google.appengine.api.log.LogQuery;
-import com.google.appengine.api.log.LogServiceFactory;
-import com.google.appengine.api.log.RequestLogs;
-
-import org.joda.time.DateTime;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-
-// Get request logs along with their app log lines and display them 5 at
-// a time, using a Next link to cycle through to the next 5.
-public class LogsServlet extends HttpServlet {
- @Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
-
- resp.setContentType("text/html");
- PrintWriter writer = resp.getWriter();
- writer.println("");
- writer.println("");
- writer.println("App Engine Logs Sample");
-
- // We use this to break out of our iteration loop, limiting record
- // display to 5 request logs at a time.
- int limit = 5;
-
- // This retrieves the offset from the Next link upon user click.
- String offset = req.getParameter("offset");
-
- // We want the App logs for each request log
- LogQuery query = LogQuery.Builder.withDefaults();
- query.includeAppLogs(true);
-
- // Set the offset value retrieved from the Next link click.
- if (offset != null) {
- query.offset(offset);
- }
-
- // This gets filled from the last request log in the iteration
- String lastOffset = null;
- int count = 0;
-
- // Display a few properties of each request log.
- for (RequestLogs record : LogServiceFactory.getLogService().fetch(query)) {
- writer.println(" REQUEST LOG ");
- DateTime reqTime = new DateTime(record.getStartTimeUsec() / 1000);
- writer.println("IP: " + record.getIp() + " ");
- writer.println("Method: " + record.getMethod() + " ");
- writer.println("Resource " + record.getResource() + " ");
- writer.println(String.format(" Date: %s", reqTime.toString()));
-
- lastOffset = record.getOffset();
-
- // Display all the app logs for each request log.
- for (AppLogLine appLog : record.getAppLogLines()) {
- writer.println(" " + "APPLICATION LOG" + " ");
- DateTime appTime = new DateTime(appLog.getTimeUsec() / 1000);
- writer.println(String.format(" Date: %s", appTime.toString()));
- writer.println(" Level: " + appLog.getLogLevel() + " ");
- writer.println("Message: " + appLog.getLogMessage() + "
");
- }
-
- if (++count >= limit) {
- break;
- }
- }
-
- // When the user clicks this link, the offset is processed in the
- // GET handler and used to cycle through to the next 5 request logs.
- writer.println(String.format(" Next", lastOffset));
- }
-}
-// [END logs_API_example]
-
diff --git a/appengine/logs/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/logs/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index 73eefaee076..00000000000
--- a/appengine/logs/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
- YOUR-PROJECT-ID
- YOUR-VERSION-NUMBER
- true
-
-
-
-
diff --git a/appengine/logs/src/main/webapp/WEB-INF/logging.properties b/appengine/logs/src/main/webapp/WEB-INF/logging.properties
deleted file mode 100644
index 3e7f85b9dc1..00000000000
--- a/appengine/logs/src/main/webapp/WEB-INF/logging.properties
+++ /dev/null
@@ -1,14 +0,0 @@
-# A default java.util.logging configuration.
-# (All App Engine logging is through java.util.logging by default).
-#
-# To use this configuration, copy it into your application's WEB-INF
-# folder and add the following to your appengine-web.xml:
-#
-#
-#
-#
-#
-
-# Set the default logging level for all loggers to WARNING
-.level = WARNING
-
diff --git a/appengine/logs/src/main/webapp/WEB-INF/web.xml b/appengine/logs/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index fa2cb4457c4..00000000000
--- a/appengine/logs/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-
-
-
-
-
-
- logs
- com.example.appengine.logs.LogsServlet
-
-
- logs
- /
-
-
diff --git a/appengine/mail/pom.xml b/appengine/mail/pom.xml
index 19318a04121..0aa14fa0080 100644
--- a/appengine/mail/pom.xml
+++ b/appengine/mail/pom.xml
@@ -43,6 +43,11 @@ Copyright 2016 Google Inc. All Rights Reserved.
javax.mailmail1.4.7
+
+
+ com.google.cloud
+ gcloud-java
+ 0.2.7
diff --git a/appengine/mail/src/main/java/com/example/appengine/mail/MailServlet.java b/appengine/mail/src/main/java/com/example/appengine/mail/SendEmail.java
similarity index 100%
rename from appengine/mail/src/main/java/com/example/appengine/mail/MailServlet.java
rename to appengine/mail/src/main/java/com/example/appengine/mail/SendEmail.java
diff --git a/appengine/mail/src/main/java/com/example/appengine/mail/SpreadsheetInfo.java b/appengine/mail/src/main/java/com/example/appengine/mail/SpreadsheetInfo.java
new file mode 100644
index 00000000000..2fb68a2d2a1
--- /dev/null
+++ b/appengine/mail/src/main/java/com/example/appengine/mail/SpreadsheetInfo.java
@@ -0,0 +1,202 @@
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import com.google.gdata.client.spreadsheet.CellQuery;
+import com.google.gdata.client.spreadsheet.FeedURLFactory;
+import com.google.gdata.client.spreadsheet.SpreadsheetService;
+import com.google.gdata.data.spreadsheet.Cell;
+import com.google.gdata.data.spreadsheet.CellEntry;
+import com.google.gdata.data.spreadsheet.CellFeed;
+import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
+import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
+import com.google.gdata.data.spreadsheet.WorksheetEntry;
+import com.google.gdata.util.AuthenticationException;
+import com.google.gdata.util.ServiceException;
+
+public class SpreadsheetInfo {
+ private static final FeedURLFactory urlFactory = FeedURLFactory.getDefault();
+
+ private SpreadsheetService service;
+
+
+ // ==========================================================================
+ // CONNECT to Google Spreadsheet API
+
+ /** Opens a connection to Google spreadsheet API. */
+ public void connect() {
+ SpreadsheetService newService = new SpreadsheetService("application_name");
+ // Google account login and passwords to access your spreadsheet.
+ // Password is in plain text. For sure there are better ways to do that
+ // so the passwords does not have to be in the code, but the simplest.
+ String email = "user@example.com";
+ String password = "password";
+ try {
+ newService.setUserCredentials(email, password);
+ } catch (AuthenticationException e) {
+ throw new RuntimeException("Cannot authenticate, invalid user/password", e);
+ }
+ this.service = newService;
+ }
+
+
+ // ==========================================================================
+ // Load data
+
+ /**
+ * Loads data from the sheet.
+ * @returns List of all non empty values in the first sheet column as
+ * 'row_number:value', where row_number=1,2,...
+ */
+ public List loadExampleData() {
+ CellFeed cellFeed = getCellFeed();
+ List result = new ArrayList();
+ for (CellEntry entry : cellFeed.getEntries()) {
+ Cell cell = entry.getCell();
+ if (cell.getCol() == 1) {
+ String value = cell.getRow() + cell.getValue();
+ result.add(value);
+ }
+ }
+ return result;
+ }
+
+
+ // ==========================================================================
+ // Save data
+
+ /**
+ * Sets new cell value for column=1 in given row.
+ * @param row Row number, if the sheet does not have so many row, new empty
+ * rows will be added.
+ * @param value New cell value as a text
+ */
+ public void setExampleValue(int row, String value) {
+ extendSheetIfTooShort(row);
+ CellFeed cellFeed = getCellFeedForUpdate(row, row, 1, 1);
+ updateCell(cellFeed.getEntries().get(0), value);
+ }
+
+
+ // ==========================================================================
+ // Access a worksheet in CELL mode
+
+ /**
+ * Returns CellFeed connected to predefined, existing spreadsheet and a
+ * sheet inside it.
+ * Provided CellFeed will include only non empty cells.
+ * This method is convenient for reading, but not always so good for updating
+ * (you do not see all cells).
+ */
+ private CellFeed getCellFeed() {
+ try {
+ return service.getFeed(findWorksheet().getCellFeedUrl(), CellFeed.class);
+ } catch (ServiceException e) {
+ throw new RuntimeException("Service error when loading data", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Connection with server broken", e);
+ }
+ }
+
+ /**
+ * Returns CellFeed for update connected to predefined, existing spreadsheet
+ * and a sheet inside it.
+ * Provided CellFeed will include all existing cells within given row and
+ * column range. Note that sheet can be smaller than specified ranges, then
+ * provided CellFeed will only include ranges up to the sheet size.
+ * This method is convenient for updating, but not always so good for reading
+ * (you can have a lot of empty cells).
+ * @param minRow Min row number (inclusive) - 1,2,...
+ * @param maxRow Max row number (inclusive) - 1,2,...
+ * @param minCol Min column number (inclusive) - 1,2,...
+ * @param maxCol Max column number (inclusive) - 1,2,...
+ */
+ private CellFeed getCellFeedForUpdate(int minRow, int maxRow, int minCol, int maxCol) {
+ CellQuery cellQuery;
+ try {
+ cellQuery = new CellQuery(findWorksheet().getCellFeedUrl());
+ cellQuery.setMinimumCol(minCol);
+ cellQuery.setMaximumCol(maxCol);
+ cellQuery.setMinimumRow(minRow);
+ cellQuery.setMaximumRow(maxRow);
+ cellQuery.setReturnEmpty(true);
+ return service.query(cellQuery, CellFeed.class);
+ } catch (ServiceException e) {
+ throw new RuntimeException("Service error when getting data to edit", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Connection with server broken", e);
+ }
+ }
+
+ private WorksheetEntry findWorksheet() throws IOException, ServiceException {
+ // Spreadsheet KEY is an unique identifier of a spreadsheet document.
+ // The KEY is part of spreadsheet document URL. To find it, just open the
+ // spreadsheet document in your browser and take the 'key' param value.
+ // For example:
+ // URL=https://docs.google.com/spreadsheet/ccc?key=0AuhY-asdcrtr123bc#gid=1
+ // => KEY=0AuhY-asdcrtr123bc
+ // (the real keys are usually much longer)
+ //
+ // Other approach to find spreadsheetKey could be to list all spreadsheets
+ // documents that belong the user and the select one by name. It would require
+ // more code and in particular one more call to API. Then it would stop working
+ // as soon as you name another spreadsheet documents with the same name.
+ // Thus, I think it is not worth the effort.
+ //
+ String spreadsheetKey = "0AuhY-asdcrtr123bc";
+
+ // Worksheet name is the name of a sheet inside the spreadsheet document.
+ // It is a name given by the user as seen in the spreadsheet. In particular
+ // it does not have to be unique, but this is the simplest way I found to
+ // identify a sheet.
+ // Note that this work only if your worksheet has unique name (within
+ // the spreadsheet document, not globally).
+ //
+ // Other approach to find a worksheet is to use worksheet position (1,2, ...)
+ // but I find it less convenient.
+ //
+ String worksheetName = "sheet1";
+
+ SpreadsheetFeed feed = service.getFeed(
+ urlFactory.getSpreadsheetsFeedUrl(),
+ SpreadsheetFeed.class);
+ for (SpreadsheetEntry se : feed.getEntries()) {
+ if (se.getSpreadsheetLink().getHref().endsWith(spreadsheetKey)) {
+ for (WorksheetEntry we : se.getWorksheets()) {
+ if (we.getTitle().getPlainText().equalsIgnoreCase(worksheetName)) {
+ return we;
+ }
+ }
+ }
+ }
+ throw new RuntimeException("Cannot find worksheet=" + worksheetName);
+ }
+
+ /** Adds more rows to the sheet if it is too short. */
+ private void extendSheetIfTooShort(int minRows) {
+ try {
+ WorksheetEntry ws = findWorksheet();
+ if (ws.getRowCount() < minRows) {
+ ws.setRowCount(minRows);
+ ws.getRowCount();
+ ws.update();
+ }
+ } catch (ServiceException e) {
+ throw new RuntimeException("Service error when extending worksheet", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Connection error when extending worksheet", e);
+ }
+ }
+
+ /** Updates cell value. */
+ private void updateCell(CellEntry entry, String newValue) {
+ entry.changeInputValueLocal(newValue);
+ try {
+ // Commit changes - send changes to Google spreadsheet API
+ entry.update();
+ } catch (ServiceException e) {
+ throw new RuntimeException("Service error when updating data", e);
+ } catch (IOException e) {
+ throw new RuntimeException("Connection error when updating data", e);
+ }
+ }
+}
\ No newline at end of file
diff --git a/appengine/mailgun/README.md b/appengine/mailgun/README.md
deleted file mode 100644
index 582771ddb34..00000000000
--- a/appengine/mailgun/README.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# Java Mailgun Email Sample for Google App Engine Standard Environment
-
-This sample demonstrates how to use [Mailgun][mailgun-api] on [Google App Engine
-standard environment][ae-docs].
-
-See the [sample application documentaion][sample-docs] for more detailed
-instructions.
-
-[ae-docs]: https://cloud.google.com/appengine/docs/java/
-[mailgun-api]: https://documentation.mailgun.com/
-[sample-docs]: https://cloud.google.com/appengine/docs/java/mail/mailgun
diff --git a/appengine/mailgun/pom.xml b/appengine/mailgun/pom.xml
deleted file mode 100644
index 0e9066ad68c..00000000000
--- a/appengine/mailgun/pom.xml
+++ /dev/null
@@ -1,65 +0,0 @@
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
- com.example.appengine
- appengine-mailgun
-
- com.google.cloud
- doc-samples
- 1.0.0
- ../..
-
-
-
- javax.servlet
- servlet-api
- 2.5
- jar
- provided
-
-
-
- com.sun.jersey
- jersey-core
- 1.19.1
-
-
- com.sun.jersey
- jersey-client
- 1.19.1
-
-
- com.sun.jersey.contribs
- jersey-multipart
- 1.19.1
-
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
-
-
diff --git a/appengine/mailgun/src/main/java/com/example/appengine/mailgun/MailgunServlet.java b/appengine/mailgun/src/main/java/com/example/appengine/mailgun/MailgunServlet.java
deleted file mode 100644
index 899d983a0b0..00000000000
--- a/appengine/mailgun/src/main/java/com/example/appengine/mailgun/MailgunServlet.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/**
- * Copyright 2015 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine.mailgun;
-
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource;
-import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
-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;
-import javax.ws.rs.core.MediaType;
-
-// [START example]
-@SuppressWarnings("serial")
-public class MailgunServlet extends HttpServlet {
-
- private static final String MAILGUN_DOMAIN_NAME = System.getenv("MAILGUN_DOMAIN_NAME");
- private static final String MAILGUN_API_KEY = System.getenv("MAILGUN_API_KEY");
-
- @Override
- public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
- String type = req.getParameter("submit");
- String recipient = req.getParameter("to");
- ClientResponse clientResponse;
- if (type.equals("Send simple email")) {
- clientResponse = sendSimpleMessage(recipient);
- } else {
- clientResponse = sendComplexMessage(recipient);
- }
- if (clientResponse.getStatus() == 200) {
- resp.getWriter().print("Email sent.");
- }
- }
-
- // [START simple]
- 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");
- MultivaluedMapImpl formData = new MultivaluedMapImpl();
- formData.add("from", "Mailgun User ");
- formData.add("to", recipient);
- formData.add("subject", "Simple Mailgun Example");
- formData.add("text", "Plaintext content");
- return webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class,
- formData);
- }
- // [END simple]
-
- // [START complex]
- private ClientResponse sendComplexMessage(String recipient) {
- Client client = Client.create();
- client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY));
- WebResource webResource = client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME
- + "/messages");
- FormDataMultiPart formData = new FormDataMultiPart();
- formData.field("from", "Mailgun User ");
- formData.field("to", recipient);
- formData.field("subject", "Complex Mailgun Example");
- formData.field("html", "HTML content");
- ClassLoader classLoader = getClass().getClassLoader();
- File txtFile = new File(classLoader.getResource("example-attachment.txt").getFile());
- formData.bodyPart(new FileDataBodyPart("attachment", txtFile, MediaType.TEXT_PLAIN_TYPE));
- return webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE)
- .post(ClientResponse.class, formData);
- }
- // [END complex]
-}
-// [END example]
diff --git a/appengine/mailgun/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/mailgun/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index f720d147b74..00000000000
--- a/appengine/mailgun/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
-
- YOUR-PROJECT-ID
- YOUR-VERSION-ID
- true
-
-
-
-
-
-
diff --git a/appengine/mailgun/src/main/webapp/WEB-INF/web.xml b/appengine/mailgun/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 26e63250cbe..00000000000
--- a/appengine/mailgun/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
-
-
- mailgun
- com.example.appengine.mailgun.MailgunServlet
-
-
- mailgun
- /send/email
-
-
-
diff --git a/appengine/mailgun/src/main/webapp/index.html b/appengine/mailgun/src/main/webapp/index.html
deleted file mode 100644
index 6049c6945e7..00000000000
--- a/appengine/mailgun/src/main/webapp/index.html
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
- Mailgun on Google App Engine Managed VMs
-
-
-
-
-
-
-
diff --git a/appengine/mailjet/README.md b/appengine/mailjet/README.md
deleted file mode 100644
index 0a9bddaaac7..00000000000
--- a/appengine/mailjet/README.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# Mailjet sample for Google App Engine
-This sample demonstrates how to use [Mailjet](https://www.mailjet.com/) on Google Managed VMs to
-send emails from a verified sender you own.
-
-## Setup
-1. Before using, ensure the address you plan to send from has been verified in Mailjet.
-
-## Running locally
- $ export MAILJET_API_KEY=[your mailjet api key]
- $ export MAILJET_SECRET_KEY=[your mailjet secret key]
- $ mvn clean appengine:devserver
-
-## Deploying
-1. Edit the environment variables in the appengine-web.xml with the appropriate Mailjet values.
- $ mvn clean appengine:update
diff --git a/appengine/mailjet/pom.xml b/appengine/mailjet/pom.xml
deleted file mode 100644
index 2b47778132d..00000000000
--- a/appengine/mailjet/pom.xml
+++ /dev/null
@@ -1,72 +0,0 @@
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
- com.example.appengine
- appengine-mailjet
-
- com.google.cloud
- doc-samples
- 1.0.0
- ../..
-
-
-
- com.mailjet
- mailjet-client
- 4.0.4
- system
- ${project.basedir}/src/main/webapp/WEB-INF/lib/client-3.1.1-jar-with-dependencies.jar
-
-
- javax.servlet
- servlet-api
- 2.5
- jar
- provided
-
-
-
- com.sun.jersey
- jersey-core
- 1.19.1
-
-
- com.sun.jersey
- jersey-client
- 1.19.1
-
-
- com.sun.jersey.contribs
- jersey-multipart
- 1.19.1
-
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
-
-
diff --git a/appengine/mailjet/src/main/java/com/example/appengine/mailjet/MailjetServlet.java b/appengine/mailjet/src/main/java/com/example/appengine/mailjet/MailjetServlet.java
deleted file mode 100644
index a63e44073ab..00000000000
--- a/appengine/mailjet/src/main/java/com/example/appengine/mailjet/MailjetServlet.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// [START mailjet_imports]
-package com.example.appengine.mailjet;
-
-import com.mailjet.client.MailjetClient;
-import com.mailjet.client.MailjetRequest;
-import com.mailjet.client.MailjetResponse;
-import com.mailjet.client.errors.MailjetException;
-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;
-
-// [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 {
- String recipient = req.getParameter("to");
- String sender = req.getParameter("from");
-
- MailjetRequest email = new MailjetRequest(Email.resource)
- .property(Email.FROMEMAIL, sender)
- .property(Email.FROMNAME, "pandora")
- .property(Email.SUBJECT, "Your email flight plan!")
- .property(Email.TEXTPART,
- "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
- .property(Email.HTMLPART,
- "
Dear passenger, welcome to Mailjet!
May the delivery force be with you!")
- .property(Email.RECIPIENTS, new JSONArray().put(new JSONObject().put("Email", recipient)));
-
- try {
- // trigger the API call
- MailjetResponse response = client.post(email);
- // Read the response data and status
- resp.getWriter().print(response.getStatus());
- resp.getWriter().print(response.getData());
- } catch (MailjetException e) {
- throw new ServletException("Mailjet Exception", e);
- }
- }
-}
-// [END app]
diff --git a/appengine/mailjet/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/mailjet/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index 653950db1c9..00000000000
--- a/appengine/mailjet/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-
-
-
- YOUR-PROJECT-ID
- YOUR-VERSION-ID
- true
-// [START env_variables]
-
-
-
-
-// [END env_variables]
-
diff --git a/appengine/mailjet/src/main/webapp/WEB-INF/lib/client-3.1.1-jar-with-dependencies.jar b/appengine/mailjet/src/main/webapp/WEB-INF/lib/client-3.1.1-jar-with-dependencies.jar
deleted file mode 100644
index e3b58094cf6..00000000000
Binary files a/appengine/mailjet/src/main/webapp/WEB-INF/lib/client-3.1.1-jar-with-dependencies.jar and /dev/null differ
diff --git a/appengine/mailjet/src/main/webapp/WEB-INF/web.xml b/appengine/mailjet/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index e0d543ad029..00000000000
--- a/appengine/mailjet/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-
-
-
-
-
-
- mailjet
- com.example.appengine.mailjet.MailjetServlet
-
-
- mailjet
- /send/email
-
-
diff --git a/appengine/mailjet/src/main/webapp/index.html b/appengine/mailjet/src/main/webapp/index.html
deleted file mode 100644
index 037fddcea91..00000000000
--- a/appengine/mailjet/src/main/webapp/index.html
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
- Mailgun on Google App Engine Managed VMs
-
-
-
-
-
-
-
diff --git a/appengine/memcache/pom.xml b/appengine/memcache/pom.xml
deleted file mode 100644
index d42990edbbf..00000000000
--- a/appengine/memcache/pom.xml
+++ /dev/null
@@ -1,73 +0,0 @@
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
- com.example.appengine
- appengine-memcache
-
-
- doc-samples
- com.google.cloud
- 1.0.0
- ../..
-
-
-
-
- javax.servlet
- servlet-api
- 2.5
- jar
- provided
-
-
-
-
-
- com.google.appengine
- appengine-api-1.0-sdk
-
-
- com.googlecode.xmemcached
- xmemcached
- 2.0.1
-
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- 3.3
-
-
- 1.7
-
-
-
-
-
diff --git a/appengine/memcache/src/main/java/com/example/appengine/memcache/MemcacheAsyncCacheServlet.java b/appengine/memcache/src/main/java/com/example/appengine/memcache/MemcacheAsyncCacheServlet.java
deleted file mode 100644
index 802777e8481..00000000000
--- a/appengine/memcache/src/main/java/com/example/appengine/memcache/MemcacheAsyncCacheServlet.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine.memcache;
-
-import com.google.appengine.api.memcache.AsyncMemcacheService;
-import com.google.appengine.api.memcache.ErrorHandlers;
-import com.google.appengine.api.memcache.MemcacheServiceFactory;
-
-import java.io.IOException;
-import java.math.BigInteger;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import java.util.logging.Level;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-@SuppressWarnings("serial")
-public class MemcacheAsyncCacheServlet extends HttpServlet {
-
- @Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
- ServletException {
- String path = req.getRequestURI();
- if (path.startsWith("/favicon.ico")) {
- return; // ignore the request for favicon.ico
- }
-
- // [START example]
- AsyncMemcacheService asyncCache = MemcacheServiceFactory.getAsyncMemcacheService();
- asyncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
- String key = "count-async";
- byte[] value;
- long count = 1;
- Future
-
-
-
-
-
-
\ No newline at end of file
diff --git a/appengine/users/README.md b/appengine/users/README.md
deleted file mode 100644
index 4d6d60a6a02..00000000000
--- a/appengine/users/README.md
+++ /dev/null
@@ -1,37 +0,0 @@
-# Users Authentication sample for Google App Engine
-
-This sample demonstrates how to use the [Users API][appid] on [Google App
-Engine][ae-docs].
-
-[appid]: https://cloud.google.com/appengine/docs/java/users/
-[ae-docs]: https://cloud.google.com/appengine/docs/java/
-
-## Running locally
-This example uses the
-[Maven gcloud plugin](https://cloud.google.com/appengine/docs/java/managed-vms/maven).
-To run this sample locally:
-
- $ mvn appengine:devserver
-
-## Deploying
-In the following command, replace YOUR-PROJECT-ID with your
-[Google Cloud Project ID](https://developers.google.com/console/help/new/#projectnumber).
-
- $ mvn appengine:update -Dappengine.appId=YOUR-PROJECT-ID -Dappengine.version=SOME-VERSION
-
-## Setup
-To save your project settings so that you don't need to enter the
- parameters, you can:
-
-1. Update the tag in src/main/webapp/WEB-INF/appengine-web.xml
- with your project name.
-
-2. Update the tag in src/main/webapp/WEB-INF/appengine-web.xml
- with a valid version number.
-
-
-You will now be able to run
-
- $ mvn appengine:update
-
-without the need for any additional parameters.
diff --git a/appengine/users/pom.xml b/appengine/users/pom.xml
deleted file mode 100644
index 94aec92ab3d..00000000000
--- a/appengine/users/pom.xml
+++ /dev/null
@@ -1,113 +0,0 @@
-
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
- com.example.appengine
- appengine-users
-
-
- com.google.cloud
- doc-samples
- 1.0.0
- ../..
-
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
- com.google.guava
- guava
- 19.0
-
-
- javax.servlet
- servlet-api
- 2.5
- jar
- provided
-
-
- org.json
- json
- 20160810
-
-
-
- junit
- junit
- 4.12
- test
-
-
- org.mockito
- mockito-all
- 1.10.19
- test
-
-
- com.google.appengine
- appengine-testing
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-api-stubs
- ${appengine.sdk.version}
- test
-
-
- com.google.appengine
- appengine-tools-sdk
- ${appengine.sdk.version}
- test
-
-
- com.google.truth
- truth
- 0.29
- test
-
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
- org.apache.maven.plugins
- 3.3
- maven-compiler-plugin
-
-
- 1.7
-
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
-
-
diff --git a/appengine/users/src/main/java/com/example/appengine/users/UsersServlet.java b/appengine/users/src/main/java/com/example/appengine/users/UsersServlet.java
deleted file mode 100644
index cd976a1820c..00000000000
--- a/appengine/users/src/main/java/com/example/appengine/users/UsersServlet.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// [START users_API_example]
-package com.example.appengine.users;
-
-import com.google.appengine.api.users.UserService;
-import com.google.appengine.api.users.UserServiceFactory;
-
-import java.io.IOException;
-
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-public class UsersServlet extends HttpServlet {
- @Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
- UserService userService = UserServiceFactory.getUserService();
-
- String thisUrl = req.getRequestURI();
-
- resp.setContentType("text/html");
- if (req.getUserPrincipal() != null) {
- resp.getWriter().println("
Hello, "
- + req.getUserPrincipal().getName()
- + "! You can sign out.
");
- }
- }
-}
-// [END users_API_example]
-
diff --git a/appengine/users/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/users/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index c9e245399bf..00000000000
--- a/appengine/users/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
- YOUR-PROJECT-ID
- YOUR-VERSION-ID
- true
-
diff --git a/appengine/users/src/main/webapp/WEB-INF/web.xml b/appengine/users/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 4b2b77234dc..00000000000
--- a/appengine/users/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-
- users
- com.example.appengine.users.UsersServlet
-
-
- users
- /
-
-
diff --git a/appengine/users/src/test/java/com/example/appengine/users/UsersServletTest.java b/appengine/users/src/test/java/com/example/appengine/users/UsersServletTest.java
deleted file mode 100644
index b710ae737d0..00000000000
--- a/appengine/users/src/test/java/com/example/appengine/users/UsersServletTest.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright 2015 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine.users;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.when;
-
-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 org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import javax.management.remote.JMXPrincipal;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * 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;
- private StringWriter responseWriter;
- private UsersServlet servletUnderTest;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- helper.setUp();
-
- // Set up some fake HTTP requests
- // If the user isn't logged in, use this request
- when(mockRequestNotLoggedIn.getRequestURI()).thenReturn(FAKE_URL);
- when(mockRequestNotLoggedIn.getUserPrincipal()).thenReturn(null);
-
- // If the user is logged in, use this request
- when(mockRequestLoggedIn.getRequestURI()).thenReturn(FAKE_URL);
- // Most of the classes that implement Principal have been
- // deprecated. JMXPrincipal seems like a safe choice.
- when(mockRequestLoggedIn.getUserPrincipal()).thenReturn(new JMXPrincipal(FAKE_NAME));
-
- // Set up a fake HTTP response.
- responseWriter = new StringWriter();
- when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter));
-
- servletUnderTest = new UsersServlet();
- }
-
- @After public void tearDown() {
- helper.tearDown();
- }
-
- @Test
- public void doGet_userNotLoggedIn_writesResponse() throws Exception {
- servletUnderTest.doGet(mockRequestNotLoggedIn, mockResponse);
-
- // If a user isn't logged in, we expect a prompt
- // to login to be returned.
- assertThat(responseWriter.toString())
- .named("UsersServlet response")
- .contains("
");
- }
-
- @Test
- public void doGet_userLoggedIn_writesResponse() throws Exception {
- servletUnderTest.doGet(mockRequestLoggedIn, mockResponse);
-
- // If a user is logged in, we expect a prompt
- // to logout to be returned.
- assertThat(responseWriter.toString())
- .named("UsersServlet response")
- .contains("
Hello, " + FAKE_NAME + "!");
- assertThat(responseWriter.toString())
- .named("UsersServlet response")
- .contains("sign out");
- }
-}
diff --git a/appengine/xmpp/README.md b/appengine/xmpp/README.md
deleted file mode 100644
index 7ca936b5f0c..00000000000
--- a/appengine/xmpp/README.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# Google App Engine Standard Environment XMPP Java API Overview
-
-This sample demonstrates how to use XMPP Java API on Google App Engine.
-
-See the [Google App Engine standard environment documentation][ae-docs] for more
-detailed instructions.
-
-[ae-docs]: https://cloud.google.com/appengine/docs/java/
-
-## Setup
-1. Update the `` tag in `src/main/webapp/WEB-INF/appengine-web.xml`
- with your project name.
-1. Update the `` tag in `src/main/webapp/WEB-INF/appengine-web.xml`
- with your version name.
-
-## Running locally
- $ mvn appengine:devserver
-
-## Deploying
- $ mvn appengine:update
diff --git a/appengine/xmpp/pom.xml b/appengine/xmpp/pom.xml
deleted file mode 100644
index c7c90b8fce8..00000000000
--- a/appengine/xmpp/pom.xml
+++ /dev/null
@@ -1,72 +0,0 @@
-
-
- 4.0.0
- war
- 1.0-SNAPSHOT
- com.example.appengine
- appengine-xmpp
-
- com.google.cloud
- doc-samples
- 1.0.0
- ../..
-
-
-
- javax.servlet
- servlet-api
- jar
- provided
-
-
-
-
-
- com.google.appengine
- appengine-api-1.0-sdk
-
-
-
-
- com.google.guava
- guava
- 19.0
-
-
-
-
-
- ${project.build.directory}/${project.build.finalName}/WEB-INF/classes
-
-
- org.apache.maven.plugins
- 3.3
- maven-compiler-plugin
-
-
- 1.7
-
-
-
-
- com.google.appengine
- appengine-maven-plugin
- ${appengine.sdk.version}
-
-
-
-
diff --git a/appengine/xmpp/src/main/java/com/example/appengine/xmpp/ErrorServlet.java b/appengine/xmpp/src/main/java/com/example/appengine/xmpp/ErrorServlet.java
deleted file mode 100644
index 20a6779207c..00000000000
--- a/appengine/xmpp/src/main/java/com/example/appengine/xmpp/ErrorServlet.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine.xmpp;
-
-import com.google.common.io.ByteStreams;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.logging.Logger;
-
-import javax.servlet.ServletInputStream;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-// [START example]
-@SuppressWarnings("serial")
-public class ErrorServlet extends HttpServlet {
- private static final Logger log = Logger.getLogger(ErrorServlet.class.getName());
-
- @Override
- public void doPost(HttpServletRequest req, HttpServletResponse res)
- throws IOException {
- // Parse the POST data, which is sent as a MIME stream containing the stanza.
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ServletInputStream inputStream = req.getInputStream();
- ByteStreams.copy(inputStream, baos);
-
- // Log the error
- log.warning("Error stanza received: " + baos.toString());
- }
-}
-// [END example]
diff --git a/appengine/xmpp/src/main/java/com/example/appengine/xmpp/MessageReceiverServlet.java b/appengine/xmpp/src/main/java/com/example/appengine/xmpp/MessageReceiverServlet.java
deleted file mode 100644
index d43754048a2..00000000000
--- a/appengine/xmpp/src/main/java/com/example/appengine/xmpp/MessageReceiverServlet.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine.xmpp;
-
-import com.google.appengine.api.xmpp.JID;
-import com.google.appengine.api.xmpp.Message;
-import com.google.appengine.api.xmpp.XMPPService;
-import com.google.appengine.api.xmpp.XMPPServiceFactory;
-
-import java.io.IOException;
-import java.util.logging.Logger;
-
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-// [START example]
-@SuppressWarnings("serial")
-public class MessageReceiverServlet extends HttpServlet {
- private static final Logger log = Logger.getLogger(MessageReceiverServlet.class.getName());
-
- @Override
- public void doPost(HttpServletRequest req, HttpServletResponse res)
- throws IOException {
-
- XMPPService xmpp = XMPPServiceFactory.getXMPPService();
- Message message = xmpp.parseMessage(req);
-
- JID fromJid = message.getFromJid();
- String body = message.getBody();
-
- log.info("Received a message with id: " + fromJid + " and body: " + body);
- // ...
- }
-}
-// [END example]
diff --git a/appengine/xmpp/src/main/java/com/example/appengine/xmpp/MessageSenderServlet.java b/appengine/xmpp/src/main/java/com/example/appengine/xmpp/MessageSenderServlet.java
deleted file mode 100644
index 05461091698..00000000000
--- a/appengine/xmpp/src/main/java/com/example/appengine/xmpp/MessageSenderServlet.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine.xmpp;
-
-import com.google.appengine.api.xmpp.JID;
-import com.google.appengine.api.xmpp.Message;
-import com.google.appengine.api.xmpp.MessageBuilder;
-import com.google.appengine.api.xmpp.SendResponse;
-import com.google.appengine.api.xmpp.XMPPService;
-import com.google.appengine.api.xmpp.XMPPServiceFactory;
-
-import java.io.IOException;
-import java.util.logging.Logger;
-
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-// [START example]
-@SuppressWarnings("serial")
-public class MessageSenderServlet extends HttpServlet {
- private static final Logger log = Logger.getLogger(MessageSenderServlet.class.getName());
-
- @Override
- public void doGet(HttpServletRequest req, HttpServletResponse res)
- throws IOException {
-
- JID jid = new JID("example@gmail.com");
- String msgBody = "Someone has sent you a gift on Example.com. To view: http://example.com/gifts/";
- Message msg =
- new MessageBuilder()
- .withRecipientJids(jid)
- .withBody(msgBody)
- .build();
-
- boolean messageSent = false;
- XMPPService xmpp = XMPPServiceFactory.getXMPPService();
- SendResponse status = xmpp.sendMessage(msg);
- messageSent = (status.getStatusMap().get(jid) == SendResponse.Status.SUCCESS);
-
- log.info("Message sent? " + messageSent);
-
- if (!messageSent) {
- // Send an email message instead...
- }
- }
-}
-// [END example]
diff --git a/appengine/xmpp/src/main/java/com/example/appengine/xmpp/PresenceServlet.java b/appengine/xmpp/src/main/java/com/example/appengine/xmpp/PresenceServlet.java
deleted file mode 100644
index 1af7e0bea5a..00000000000
--- a/appengine/xmpp/src/main/java/com/example/appengine/xmpp/PresenceServlet.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine.xmpp;
-
-import com.google.appengine.api.xmpp.Presence;
-import com.google.appengine.api.xmpp.PresenceType;
-import com.google.appengine.api.xmpp.XMPPService;
-import com.google.appengine.api.xmpp.XMPPServiceFactory;
-
-import java.io.IOException;
-import java.util.logging.Logger;
-
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-// [START example]
-@SuppressWarnings("serial")
-public class PresenceServlet extends HttpServlet {
- private static final Logger log = Logger.getLogger(PresenceServlet.class.getName());
-
- @Override
- public void doPost(HttpServletRequest req, HttpServletResponse res)
- throws IOException {
-
- XMPPService xmpp = XMPPServiceFactory.getXMPPService();
- Presence presence = xmpp.parsePresence(req);
-
- // Split the XMPP address (e.g., user@gmail.com)
- // from the resource (e.g., gmail.CD6EBC4A)
- String from = presence.getFromJid().getId().split("/")[0];
-
- log.info("Received presence from: " + from);
-
- // Mirror the contact's presence back to them
- xmpp.sendPresence(
- presence.getFromJid(),
- PresenceType.AVAILABLE,
- presence.getPresenceShow(),
- presence.getStatus());
- }
-}
-// [END example]
diff --git a/appengine/xmpp/src/main/java/com/example/appengine/xmpp/SubscriptionServlet.java b/appengine/xmpp/src/main/java/com/example/appengine/xmpp/SubscriptionServlet.java
deleted file mode 100644
index e330006109f..00000000000
--- a/appengine/xmpp/src/main/java/com/example/appengine/xmpp/SubscriptionServlet.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright 2016 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.example.appengine.xmpp;
-
-import com.google.appengine.api.xmpp.Subscription;
-import com.google.appengine.api.xmpp.XMPPService;
-import com.google.appengine.api.xmpp.XMPPServiceFactory;
-
-import java.io.IOException;
-import java.util.logging.Logger;
-
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-// [START example]
-@SuppressWarnings("serial")
-public class SubscriptionServlet extends HttpServlet {
- private static final Logger log = Logger.getLogger(SubscriptionServlet.class.getName());
-
- @Override
- public void doPost(HttpServletRequest req, HttpServletResponse res)
- throws IOException {
- XMPPService xmppService = XMPPServiceFactory.getXMPPService();
- Subscription sub = xmppService.parseSubscription(req);
-
- // Split the bare XMPP address (e.g., user@gmail.com)
- // from the resource (e.g., gmail.CD6EBC4A)
- String from = sub.getFromJid().getId().split("/")[0];
-
- log.info("Received subscription event from: " + from);
- }
-}
-// [END example]
diff --git a/appengine/xmpp/src/main/webapp/WEB-INF/appengine-web.xml b/appengine/xmpp/src/main/webapp/WEB-INF/appengine-web.xml
deleted file mode 100644
index efe638217ee..00000000000
--- a/appengine/xmpp/src/main/webapp/WEB-INF/appengine-web.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
-
- YOUR-PROJECT-ID
- YOUR-VERSION-ID
- true
-
-
-
- xmpp_message
- xmpp_presence
- xmpp_subscribe
- xmpp_error
-
-
-
-
diff --git a/appengine/xmpp/src/main/webapp/WEB-INF/web.xml b/appengine/xmpp/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 5bbb66f21c2..00000000000
--- a/appengine/xmpp/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,67 +0,0 @@
-
-
-
-
-
-
- error
- com.example.appengine.xmpp.ErrorServlet
-
-
- error
- /_ah/xmpp/error/
-
-
-
- messagereceiver
- com.example.appengine.xmpp.MessageReceiverServlet
-
-
- messagereceiver
- /_ah/xmpp/message/chat/
-
-
-
- messagesender
- com.example.appengine.xmpp.MessageSenderServlet
-
-
- messagesender
- /messagesender
-
-
- presence
- com.example.appengine.xmpp.PresenceServlet
-
-
- presence
- /_ah/xmpp/presence/available/
- /_ah/xmpp/presence/unavailable/
- /_ah/xmpp/presence/probe/
-
-
- subscription
- com.example.appengine.xmpp.SubscriptionServlet
-
-
- subscription
- /_ah/xmpp/subscription/subscribe/
- /_ah/xmpp/subscription/subscribed/
- /_ah/xmpp/subscription/unsubscribe/
- /_ah/xmpp/subscription/unsubscribed/
-
-
diff --git a/bigquery/README.md b/bigquery/README.md
deleted file mode 100644
index fc6ec28c77c..00000000000
--- a/bigquery/README.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# Getting Started with BigQuery and the Google Java API Client library
-
-Google's BigQuery Service features a REST-based API that allows developers to create applications to run ad-hoc queries on massive datasets. These sample Java applications demonstrate how to access the BigQuery API using the Google Java API Client Libraries. For more information, read the [Getting Started with BigQuery and the Google Java API Client library][1] codelab.
-
-## Quickstart
-
-Install [Maven](http://maven.apache.org/).
-
-Build your project with:
-
- mvn package
-
-You can then run a given `ClassName` via:
-
- mvn exec:java -Dexec.mainClass=com.google.cloud.bigquery.samples.ClassName \
- -Dexec.args="any arguments to the app"
-
-## Products
-- [Google BigQuery][2]
-
-## Language
-- [Java][3]
-
-## Dependencies
-- [Google APIs Client Library for Java][4]
-
-[1]: https://cloud.google.com/bigquery/bigquery-api-quickstart
-[2]: https://developers.google.com/bigquery
-[3]: https://java.com
-[4]: http://code.google.com/p/google-api-java-client/
-
diff --git a/bigquery/pom.xml b/bigquery/pom.xml
deleted file mode 100644
index 1859b420b4b..00000000000
--- a/bigquery/pom.xml
+++ /dev/null
@@ -1,87 +0,0 @@
-
- 4.0.0
- com.google.cloud.bigquery.samples
- bigquery-samples
- jar
-
-
- doc-samples
- com.google.cloud
- 1.0.0
- ..
-
-
-
-
- googleapis
- https://google-api-client-libraries.appspot.com/mavenrepo
-
-
-
-
-
- com.google.apis
- google-api-services-bigquery
- v2-rev316-1.22.0
-
-
- com.google.oauth-client
- google-oauth-client
- ${project.oauth.version}
-
-
- com.google.http-client
- google-http-client-jackson2
- ${project.http.version}
-
-
- com.google.oauth-client
- google-oauth-client-jetty
- ${project.oauth.version}
-
-
- com.google.code.gson
- gson
- 2.7
-
-
- junit
- junit
- test
-
-
- com.google.truth
- truth
- 0.29
- test
-
-
-
-
- 1.21.0
- 1.21.0
- UTF-8
-
-
-
- src/main/java
-
-
- src/main/resources
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- 3.2
-
-
- 5
-
-
-
-
-
-
diff --git a/bigquery/src/main/java/com/google/cloud/bigquery/samples/AsyncQuerySample.java b/bigquery/src/main/java/com/google/cloud/bigquery/samples/AsyncQuerySample.java
deleted file mode 100644
index a76b9e03c51..00000000000
--- a/bigquery/src/main/java/com/google/cloud/bigquery/samples/AsyncQuerySample.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/**
- * Copyright (c) 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package com.google.cloud.bigquery.samples;
-
-
-import com.google.api.services.bigquery.Bigquery;
-import com.google.api.services.bigquery.Bigquery.Jobs.GetQueryResults;
-import com.google.api.services.bigquery.model.GetQueryResultsResponse;
-import com.google.api.services.bigquery.model.Job;
-import com.google.api.services.bigquery.model.JobConfiguration;
-import com.google.api.services.bigquery.model.JobConfigurationQuery;
-
-import java.io.IOException;
-import java.util.Iterator;
-import java.util.Scanner;
-
-
-/**
- * Example of authorizing with BigQuery and reading from a public dataset.
- */
-public class AsyncQuerySample extends BigqueryUtils {
- // [START main]
- /**
- * Prompts for all the parameters required to make a query.
- *
- * @param args Command line args
- * @throws IOException IOException
- * @throws InterruptedException InterruptedException
- */
- public static void main(final String[] args)
- throws IOException, InterruptedException {
- Scanner scanner = new Scanner(System.in);
- System.out.println("Enter your project id: ");
- String projectId = scanner.nextLine();
- System.out.println("Enter your query string: ");
- String queryString = scanner.nextLine();
- System.out.println("Run query in batch mode? [true|false] ");
- boolean batch = Boolean.valueOf(scanner.nextLine());
- System.out.println("Enter how often to check if your job is complete "
- + "(milliseconds): ");
- long waitTime = scanner.nextLong();
- scanner.close();
- Iterator pages = run(projectId, queryString,
- batch, waitTime);
- while (pages.hasNext()) {
- printRows(pages.next().getRows(), System.out);
- }
- }
- // [END main]
-
- // [START run]
- /**
- * Run the query.
- *
- * @param projectId Get this from Google Developers console
- * @param queryString Query we want to run against BigQuery
- * @param batch True if you want to batch the queries
- * @param waitTime How long to wait before retries
- * @return An interator to the result of your pages
- * @throws IOException Thrown if there's an IOException
- * @throws InterruptedException Thrown if there's an Interrupted Exception
- */
- public static Iterator run(final String projectId,
- final String queryString,
- final boolean batch,
- final long waitTime)
- throws IOException, InterruptedException {
-
- Bigquery bigquery = BigqueryServiceFactory.getService();
-
- Job query = asyncQuery(bigquery, projectId, queryString, batch);
- Bigquery.Jobs.Get getRequest = bigquery.jobs().get(
- projectId, query.getJobReference().getJobId());
-
- //Poll every waitTime milliseconds,
- //retrying at most retries times if there are errors
- pollJob(getRequest, waitTime);
-
- GetQueryResults resultsRequest = bigquery.jobs().getQueryResults(
- projectId, query.getJobReference().getJobId());
-
- return getPages(resultsRequest);
- }
- // [END run]
-
- // [START asyncQuery]
- /**
- * Inserts an asynchronous query Job for a particular query.
- *
- * @param bigquery an authorized BigQuery client
- * @param projectId a String containing the project ID
- * @param querySql the actual query string
- * @param batch True if you want to run the query as BATCH
- * @return a reference to the inserted query job
- * @throws IOException Thrown if there's a network exception
- */
- public static Job asyncQuery(final Bigquery bigquery,
- final String projectId,
- final String querySql,
- final boolean batch) throws IOException {
-
- JobConfigurationQuery queryConfig = new JobConfigurationQuery()
- .setQuery(querySql);
-
- if (batch) {
- queryConfig.setPriority("BATCH");
- }
-
- Job job = new Job().setConfiguration(
- new JobConfiguration().setQuery(queryConfig));
-
- return bigquery.jobs().insert(projectId, job).execute();
- }
- // [END asyncQuery]
-
-}
diff --git a/bigquery/src/main/java/com/google/cloud/bigquery/samples/BigqueryServiceFactory.java b/bigquery/src/main/java/com/google/cloud/bigquery/samples/BigqueryServiceFactory.java
deleted file mode 100644
index a9037ef4bd5..00000000000
--- a/bigquery/src/main/java/com/google/cloud/bigquery/samples/BigqueryServiceFactory.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (c) 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package com.google.cloud.bigquery.samples;
-
-// [START imports]
-import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
-import com.google.api.client.http.HttpTransport;
-import com.google.api.client.http.javanet.NetHttpTransport;
-import com.google.api.client.json.JsonFactory;
-import com.google.api.client.json.jackson2.JacksonFactory;
-import com.google.api.services.bigquery.Bigquery;
-import com.google.api.services.bigquery.BigqueryScopes;
-// [END imports]
-
-import java.io.IOException;
-import java.util.Collection;
-
-/**
- * This class creates our Service to connect to Bigquery including auth.
- */
-public final class BigqueryServiceFactory {
-
- /**
- * Private constructor to disable creation of this utility Factory class.
- */
- private BigqueryServiceFactory() {
-
- }
-
- /**
- * Singleton service used through the app.
- */
- private static Bigquery service = null;
-
- /**
- * Mutex created to create the singleton in thread-safe fashion.
- */
- private static Object serviceLock = new Object();
-
- /**
- * Threadsafe Factory that provides an authorized Bigquery service.
- * @return The Bigquery service
- * @throws IOException Thronw if there is an error connecting to Bigquery.
- */
- public static Bigquery getService() throws IOException {
- if (service == null) {
- synchronized (serviceLock) {
- if (service == null) {
- service = createAuthorizedClient();
- }
- }
- }
- return service;
- }
-
- /**
- * Creates an authorized client to Google Bigquery.
- *
- * @return The BigQuery Service
- * @throws IOException Thrown if there is an error connecting
- */
- // [START get_service]
- private static Bigquery createAuthorizedClient() throws IOException {
- // Create the credential
- HttpTransport transport = new NetHttpTransport();
- JsonFactory jsonFactory = new JacksonFactory();
- GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
-
- // Depending on the environment that provides the default credentials (e.g. Compute Engine, App
- // Engine), the credentials may require us to specify the scopes we need explicitly.
- // Check for this case, and inject the Bigquery scope if required.
- if (credential.createScopedRequired()) {
- Collection bigqueryScopes = BigqueryScopes.all();
- credential = credential.createScoped(bigqueryScopes);
- }
-
- return new Bigquery.Builder(transport, jsonFactory, credential)
- .setApplicationName("BigQuery Samples").build();
- }
- // [END get_service]
-
-}
diff --git a/bigquery/src/main/java/com/google/cloud/bigquery/samples/BigqueryUtils.java b/bigquery/src/main/java/com/google/cloud/bigquery/samples/BigqueryUtils.java
deleted file mode 100644
index 743c29eac79..00000000000
--- a/bigquery/src/main/java/com/google/cloud/bigquery/samples/BigqueryUtils.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- 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
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-*/
-
-package com.google.cloud.bigquery.samples;
-
-import com.google.api.client.json.GenericJson;
-import com.google.api.services.bigquery.Bigquery;
-import com.google.api.services.bigquery.Bigquery.Datasets;
-import com.google.api.services.bigquery.BigqueryRequest;
-import com.google.api.services.bigquery.model.DatasetList;
-import com.google.api.services.bigquery.model.Job;
-import com.google.api.services.bigquery.model.TableCell;
-import com.google.api.services.bigquery.model.TableFieldSchema;
-import com.google.api.services.bigquery.model.TableRow;
-import com.google.api.services.bigquery.model.TableSchema;
-import com.google.gson.Gson;
-
-import java.io.IOException;
-import java.io.PrintStream;
-import java.io.Reader;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
-
-/**
- * Helper functions for the other classes.
- */
-public class BigqueryUtils {
-
- /**
- * Private contructor to prevent creation of this class, which is just all
- * static helper methods.
- */
- protected BigqueryUtils() {
- }
-
- /**
- * Print rows to the output stream in a formatted way.
- * @param rows rows in bigquery
- * @param out Output stream we want to print to
- */
- // [START print_rows]
- public static void printRows(final List rows, final PrintStream out) {
- for (TableRow row : rows) {
- for (TableCell field : row.getF()) {
- out.printf("%-50s", field.getV());
- }
- out.println();
- }
- }
- // [END print_rows]
-
- /**
- * Polls the job for completion.
- * @param request The bigquery request to poll for completion
- * @param interval Number of milliseconds between each poll
- * @return The finished job
- * @throws IOException IOException
- * @throws InterruptedException InterruptedException
- */
- // [START poll_job]
- public static Job pollJob(final Bigquery.Jobs.Get request, final long interval)
- throws IOException, InterruptedException {
- Job job = request.execute();
- while (!job.getStatus().getState().equals("DONE")) {
- System.out.println("Job is "
- + job.getStatus().getState()
- + " waiting " + interval + " milliseconds...");
- Thread.sleep(interval);
- job = request.execute();
- }
- return job;
- }
- // [END poll_job]
-
- /**
- * Pages through the results of an arbitrary Bigquery request.
- * @param requestTemplate The object that represents the call to fetch
- * the results.
- * @param The type of the returned objects
- * @return An iterator that pages through the returned object
- */
- // [START paging]
- public static Iterator getPages(
- final BigqueryRequest requestTemplate) {
-
- /**
- * An iterator class that pages through a Bigquery request.
- */
- class PageIterator implements Iterator {
-
- private BigqueryRequest request;
- private boolean hasNext = true;
-
- /**
- * Inner class that represents our iterator to page through results.
- * @param requestTemplate The object that represents the call to fetch
- * the results.
- */
- public PageIterator(final BigqueryRequest requestTemplate) {
- this.request = requestTemplate;
- }
-
- /**
- * Checks whether there is another page of results.
- * @return True if there is another page of results.
- */
- public boolean hasNext() {
- return hasNext;
- }
-
- /**
- * Returns the next page of results.
- * @return The next page of resul.ts
- */
- public T next() {
- if (!hasNext) {
- throw new NoSuchElementException();
- }
- try {
- T response = request.execute();
- if (response.containsKey("pageToken")) {
- request = request.set("pageToken", response.get("pageToken"));
- } else {
- hasNext = false;
- }
- return response;
- } catch (IOException e) {
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * Skips the page by moving the iterator to the next page.
- */
- public void remove() {
- this.next();
- }
- }
-
- return new PageIterator(requestTemplate);
- }
- // [END paging]
-
- /**
- * Loads a Bigquery schema.
- * @param schemaSource The source of the schema
- * @return The TableSchema
- */
- // [START load_schema]
- public static TableSchema loadSchema(final Reader schemaSource) {
- TableSchema sourceSchema = new TableSchema();
-
- List fields = (new Gson())
- .>fromJson(schemaSource,
- (new ArrayList()).getClass());
-
- sourceSchema.setFields(fields);
-
- return sourceSchema;
- }
- // [END load_schema]
-
- // [START list_datasets]
- /**
- * Display all BigQuery datasets associated with a project.
- *
- * @param bigquery an authorized BigQuery client
- * @param projectId a string containing the current project ID
- * @throws IOException Thrown if there is a network error connecting to
- * Bigquery.
- */
- public static void listDatasets(final Bigquery bigquery, final String projectId)
- throws IOException {
- Datasets.List datasetRequest = bigquery.datasets().list(projectId);
- DatasetList datasetList = datasetRequest.execute();
- if (datasetList.getDatasets() != null) {
- List datasets = datasetList.getDatasets();
- System.out.println("Available datasets\n----------------");
- System.out.println(datasets.toString());
- for (DatasetList.Datasets dataset : datasets) {
- System.out.format("%s\n", dataset.getDatasetReference().getDatasetId());
- }
- }
- }
- // [END list_datasets]
-}
diff --git a/bigquery/src/main/java/com/google/cloud/bigquery/samples/ExportDataCloudStorageSample.java b/bigquery/src/main/java/com/google/cloud/bigquery/samples/ExportDataCloudStorageSample.java
deleted file mode 100644
index 736e5c31bbb..00000000000
--- a/bigquery/src/main/java/com/google/cloud/bigquery/samples/ExportDataCloudStorageSample.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- 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
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-*/
-package com.google.cloud.bigquery.samples;
-
-import com.google.api.services.bigquery.Bigquery;
-import com.google.api.services.bigquery.model.Job;
-import com.google.api.services.bigquery.model.JobConfiguration;
-import com.google.api.services.bigquery.model.JobConfigurationExtract;
-import com.google.api.services.bigquery.model.TableReference;
-
-import java.io.IOException;
-import java.util.Scanner;
-
-/**
- * Sample of how to Export Cloud Data.
- */
-public class ExportDataCloudStorageSample {
- /**
- * Protected constructor since this is a collection of static functions.
- */
- protected ExportDataCloudStorageSample() {
- super();
- }
-
- /**
- * This program can be run to demonstrate running a Bigquery query from the
- * CLI.
- * @param args Command line args
- * @throws IOException If there is an error connceting to bigquery
- * @throws InterruptedException Should never be thrown.
- */
- // [START main]
- public static void main(final String[] args)
- throws IOException, InterruptedException {
- Scanner scanner = new Scanner(System.in);
- System.out.println("Enter your project id: ");
- String projectId = scanner.nextLine();
- System.out.println("Enter your dataset id: ");
- String datasetId = scanner.nextLine();
- System.out.println("Enter your table id: ");
- String tableId = scanner.nextLine();
- System.out.println("Enter the Google Cloud Storage Path to which you'd "
- + "like to export: ");
- String cloudStoragePath = scanner.nextLine();
- System.out.println("Enter how often to check if your job is complete "
- + "(milliseconds): ");
- long interval = scanner.nextLong();
- scanner.close();
-
- run(cloudStoragePath, projectId, datasetId, tableId, interval);
- }
- // [END main]
-
- /**
- * Run the bigquery ClI.
- * @param cloudStoragePath The bucket we are using
- * @param projectId Project id
- * @param datasetId datasetid
- * @param tableId tableid
- * @param interval interval to wait between polling in milliseconds
- * @throws IOException Thrown if there is an error connecting to Bigquery.
- * @throws InterruptedException Should never be thrown
- */
- // [START run]
- public static void run(
- final String cloudStoragePath,
- final String projectId,
- final String datasetId,
- final String tableId,
- final long interval) throws IOException, InterruptedException {
-
- Bigquery bigquery = BigqueryServiceFactory.getService();
-
- Job extractJob = extractJob(
- bigquery,
- cloudStoragePath,
- new TableReference()
- .setProjectId(projectId)
- .setDatasetId(datasetId)
- .setTableId(tableId));
-
- Bigquery.Jobs.Get getJob = bigquery.jobs().get(
- extractJob.getJobReference().getProjectId(),
- extractJob.getJobReference().getJobId());
-
- BigqueryUtils.pollJob(getJob, interval);
-
- System.out.println("Export is Done!");
-
- }
- // [END run]
-
-
- /**
- * A job that extracts data from a table.
- * @param bigquery Bigquery service to use
- * @param cloudStoragePath Cloud storage bucket we are inserting into
- * @param table Table to extract from
- * @return The job to extract data from the table
- * @throws IOException Thrown if error connceting to Bigtable
- */
- // [START extract_job]
- public static Job extractJob(
- final Bigquery bigquery,
- final String cloudStoragePath,
- final TableReference table) throws IOException {
-
- JobConfigurationExtract extract = new JobConfigurationExtract()
- .setSourceTable(table)
- .setDestinationUri(cloudStoragePath);
-
- return bigquery.jobs().insert(table.getProjectId(),
- new Job().setConfiguration(new JobConfiguration().setExtract(extract)))
- .execute();
- }
- // [END extract_job]
-}
diff --git a/bigquery/src/main/java/com/google/cloud/bigquery/samples/GettingStarted.java b/bigquery/src/main/java/com/google/cloud/bigquery/samples/GettingStarted.java
deleted file mode 100644
index 8cdb96a6489..00000000000
--- a/bigquery/src/main/java/com/google/cloud/bigquery/samples/GettingStarted.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Copyright (c) 2012 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
- * in compliance with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package com.google.cloud.bigquery.samples;
-
-// [START all]
-import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
-import com.google.api.client.http.HttpTransport;
-import com.google.api.client.http.javanet.NetHttpTransport;
-import com.google.api.client.json.JsonFactory;
-import com.google.api.client.json.jackson2.JacksonFactory;
-import com.google.api.services.bigquery.Bigquery;
-import com.google.api.services.bigquery.BigqueryScopes;
-import com.google.api.services.bigquery.model.GetQueryResultsResponse;
-import com.google.api.services.bigquery.model.QueryRequest;
-import com.google.api.services.bigquery.model.QueryResponse;
-import com.google.api.services.bigquery.model.TableCell;
-import com.google.api.services.bigquery.model.TableRow;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.Scanner;
-
-
-/**
- * Example of authorizing with Bigquery and reading from a public dataset.
- *
- * Specifically, this queries the shakespeare dataset to fetch the 10 of Shakespeare's works with
- * the greatest number of distinct words.
- */
-public class GettingStarted {
- // [START build_service]
- /**
- * Creates an authorized Bigquery client service using Application Default Credentials.
- *
- * @return an authorized Bigquery client
- * @throws IOException if there's an error getting the default credentials.
- */
- public static Bigquery createAuthorizedClient() throws IOException {
- // Create the credential
- HttpTransport transport = new NetHttpTransport();
- JsonFactory jsonFactory = new JacksonFactory();
- GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
-
- // Depending on the environment that provides the default credentials (e.g. Compute Engine, App
- // Engine), the credentials may require us to specify the scopes we need explicitly.
- // Check for this case, and inject the Bigquery scope if required.
- if (credential.createScopedRequired()) {
- credential = credential.createScoped(BigqueryScopes.all());
- }
-
- return new Bigquery.Builder(transport, jsonFactory, credential)
- .setApplicationName("Bigquery Samples").build();
- }
- // [END build_service]
-
- // [START run_query]
- /**
- * Executes the given query synchronously.
- *
- * @param querySql the query to execute.
- * @param bigquery the Bigquery service object.
- * @param projectId the id of the project under which to run the query.
- * @return a list of the results of the query.
- * @throws IOException if there's an error communicating with the API.
- */
- private static List executeQuery(String querySql, Bigquery bigquery, String projectId)
- throws IOException {
- QueryResponse query = bigquery.jobs().query(
- projectId,
- new QueryRequest().setQuery(querySql))
- .execute();
-
- // Execute it
- GetQueryResultsResponse queryResult = bigquery.jobs().getQueryResults(
- query.getJobReference().getProjectId(),
- query.getJobReference().getJobId()).execute();
-
- return queryResult.getRows();
- }
- // [END run_query]
-
- // [START print_results]
- /**
- * Prints the results to standard out.
- *
- * @param rows the rows to print.
- */
- private static void printResults(List rows) {
- System.out.print("\nQuery Results:\n------------\n");
- for (TableRow row : rows) {
- for (TableCell field : row.getF()) {
- System.out.printf("%-50s", field.getV());
- }
- System.out.println();
- }
- }
- // [END print_results]
-
- /**
- * Exercises the methods defined in this class.
- *
- * In particular, it creates an authorized Bigquery service object using Application Default
- * Credentials, then executes a query against the public Shakespeare dataset and prints out the
- * results.
- *
- * @param args the first argument, if it exists, should be the id of the project to run the test
- * under. If no arguments are given, it will prompt for it.
- * @throws IOException if there's an error communicating with the API.
- */
- public static void main(String[] args) throws IOException {
- Scanner sc;
- if (args.length == 0) {
- // Prompt the user to enter the id of the project to run the queries under
- System.out.print("Enter the project ID: ");
- sc = new Scanner(System.in);
- } else {
- sc = new Scanner(args[0]);
- }
- String projectId = sc.nextLine();
-
- // Create a new Bigquery client authorized via Application Default Credentials.
- Bigquery bigquery = createAuthorizedClient();
-
- List rows = executeQuery("SELECT TOP(corpus, 10) as title, COUNT(*) as unique_words "
- + "FROM [publicdata:samples.shakespeare]", bigquery, projectId);
-
- printResults(rows);
- }
-
-}
-// [END all]
diff --git a/bigquery/src/main/java/com/google/cloud/bigquery/samples/ListDatasetsProjects.java b/bigquery/src/main/java/com/google/cloud/bigquery/samples/ListDatasetsProjects.java
deleted file mode 100644
index 854e1b6e6ca..00000000000
--- a/bigquery/src/main/java/com/google/cloud/bigquery/samples/ListDatasetsProjects.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Copyright (c) 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package com.google.cloud.bigquery.samples;
-
-import com.google.api.client.util.Data;
-import com.google.api.services.bigquery.Bigquery;
-import com.google.api.services.bigquery.Bigquery.Datasets;
-import com.google.api.services.bigquery.model.DatasetList;
-import com.google.api.services.bigquery.model.GetQueryResultsResponse;
-import com.google.api.services.bigquery.model.ProjectList;
-import com.google.api.services.bigquery.model.QueryRequest;
-import com.google.api.services.bigquery.model.QueryResponse;
-import com.google.api.services.bigquery.model.TableCell;
-import com.google.api.services.bigquery.model.TableRow;
-
-import java.io.IOException;
-import java.io.PrintStream;
-import java.lang.Thread;
-import java.util.List;
-
-/**
- * Invokes the BigQuery basic APIs for the given project id specified.
- *
- * Samples used in this page:
- *
- * https://cloud.google.com/bigquery/bigquery-api-quickstart
- */
-public class ListDatasetsProjects {
- /**
- * Run the sample.
- */
- public static void main(String[] args) throws IOException, InterruptedException {
- if (args.length != 1) {
- System.err.println("Usage: QuickStart ");
- return;
- }
- String projectId = args[0];
-
- Bigquery bigquery = BigqueryServiceFactory.getService();
- String query = "SELECT TOP( title, 10) as title, COUNT(*) as revision_count "
- + "FROM [publicdata:samples.wikipedia] WHERE wp_namespace = 0;";
-
- System.out.println();
- System.out.println("----- Running the asynchronous query and printing it to stdout.");
- runQueryRpcAndPrint(bigquery, projectId, query, System.out);
-
- System.out.println();
- System.out.println("----- Listing all the Datasets in the projectId");
- listDatasets(bigquery, projectId);
-
- System.out.println();
- System.out.println("----- Listing all the Projects");
- listProjects(bigquery);
- }
-
- /**
- * Lists all Datasets in a project specified by the projectId.
- *
- * @param bigquery The BigQuery object.
- * @param projectId The projectId from which lists the existing Datasets.
- * @throws IOException if there's trouble with the network request.
- */
- // [START listDatasets]
- public static void listDatasets(Bigquery bigquery, String projectId) throws IOException {
- Datasets.List datasetRequest = bigquery.datasets().list(projectId);
- DatasetList datasetList = datasetRequest.execute();
-
- if (datasetList.getDatasets() != null) {
- List datasets = datasetList.getDatasets();
- System.out.println("Dataset list:");
-
- for (DatasetList.Datasets dataset : datasets) {
- System.out.format("%s\n", dataset.getDatasetReference().getDatasetId());
- }
- }
- }
- // [END listDatasets]
-
- /**
- * Lists all Projects.
- *
- * @param bigquery The BigQuery object.
- * @throws IOException if there's trouble with the network request.
- */
- // [START listProjects]
- public static void listProjects(Bigquery bigquery) throws IOException {
- Bigquery.Projects.List projectListRequest = bigquery.projects().list();
- ProjectList projectList = projectListRequest.execute();
-
- if (projectList.getProjects() != null) {
- List projects = projectList.getProjects();
- System.out.println("Project list:");
-
- for (ProjectList.Projects project : projects) {
- System.out.format("%s\n", project.getFriendlyName());
- }
- }
- }
- // [END listProjects]
-
- /**
- * Runs a synchronous BigQuery query and displays the result.
- *
- * @param bigquery An authorized BigQuery client
- * @param projectId The current project id
- * @param query A String containing a BigQuery SQL statement
- * @param out A PrintStream for output, normally System.out
- */
- static void runQueryRpcAndPrint(Bigquery bigquery, String projectId, String query,
- PrintStream out) throws IOException, InterruptedException {
- QueryRequest queryRequest = new QueryRequest().setQuery(query);
- QueryResponse queryResponse = bigquery.jobs().query(projectId, queryRequest).execute();
- if (queryResponse.getJobComplete()) {
- printRows(queryResponse.getRows(), out);
- if (null == queryResponse.getPageToken()) {
- return;
- }
- }
- // This loop polls until results are present, then loops over result pages.
- String pageToken = null;
- while (true) {
- GetQueryResultsResponse queryResults = bigquery.jobs()
- .getQueryResults(projectId, queryResponse.getJobReference().getJobId())
- .setPageToken(pageToken).execute();
- if (queryResults.getJobComplete()) {
- printRows(queryResults.getRows(), out);
- pageToken = queryResults.getPageToken();
- if (null == pageToken) {
- return;
- }
- }
- Thread.sleep(500);
- }
- }
-
- /**
- * Print the given rows.
- *
- * @param rows the rows to print.
- * @param out the place to print them.
- */
- private static void printRows(java.util.List rows, PrintStream out) {
- if (rows != null) {
- for (TableRow row : rows) {
- for (TableCell cell : row.getF()) {
- // Data.isNull() is the recommended way to check for the 'null object' in TableCell.
- out.printf("%s, ", Data.isNull(cell.getV()) ? "null" : cell.getV().toString());
- }
- out.println();
- }
- }
- }
-}
diff --git a/bigquery/src/main/java/com/google/cloud/bigquery/samples/LoadDataCsvSample.java b/bigquery/src/main/java/com/google/cloud/bigquery/samples/LoadDataCsvSample.java
deleted file mode 100644
index 28367529a68..00000000000
--- a/bigquery/src/main/java/com/google/cloud/bigquery/samples/LoadDataCsvSample.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- 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
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-*/
-
-package com.google.cloud.bigquery.samples;
-
-import com.google.api.services.bigquery.Bigquery;
-import com.google.api.services.bigquery.model.Job;
-import com.google.api.services.bigquery.model.JobConfiguration;
-import com.google.api.services.bigquery.model.JobConfigurationLoad;
-import com.google.api.services.bigquery.model.TableReference;
-import com.google.api.services.bigquery.model.TableSchema;
-
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.Reader;
-import java.util.Collections;
-import java.util.Scanner;
-
-/**
- * Cli tool to load data from a CSV into Bigquery.
- */
-public class LoadDataCsvSample {
-
- /**
- * Protected constructor since this is a collection of static methods.
- */
- protected LoadDataCsvSample() {
- }
-
- /**
- * Cli tool to load data from a CSV into Bigquery.
- * @param args Command line args, should be empty
- * @throws IOException IOException
- * @throws InterruptedException InterruptedException
- */
- // [START main]
- public static void main(final String[] args)
- throws IOException, InterruptedException {
- Scanner scanner = new Scanner(System.in);
- System.out.println("Enter your project id: ");
- String projectId = scanner.nextLine();
- System.out.println("Enter your dataset id: ");
- String datasetId = scanner.nextLine();
- System.out.println("Enter your table id: ");
- String tableId = scanner.nextLine();
- System.out.println("Enter the Google Cloud Storage Path to the data "
- + "you'd like to load: ");
- String cloudStoragePath = scanner.nextLine();
- System.out.println("Enter the filepath to your schema: ");
- String sourceSchemaPath = scanner.nextLine();
-
-
- System.out.println("Enter how often to check if your job is complete "
- + "(milliseconds): ");
- long interval = scanner.nextLong();
- scanner.close();
-
- run(cloudStoragePath,
- projectId,
- datasetId,
- tableId,
- new FileReader(new File(sourceSchemaPath)),
- interval);
- }
- // [END main]
-
- /**
- * Run the bigquery ClI.
- * @param cloudStoragePath The bucket we are using
- * @param projectId Project id
- * @param datasetId datasetid
- * @param tableId tableid
- * @param schemaSource Source of the schema
- * @param interval interval to wait between polling in milliseconds
- * @throws IOException Thrown if there is an error connecting to Bigquery.
- * @throws InterruptedException Should never be thrown
- */
- // [START run]
- public static void run(
- final String cloudStoragePath,
- final String projectId,
- final String datasetId,
- final String tableId,
- final Reader schemaSource,
- final long interval) throws IOException, InterruptedException {
-
- Bigquery bigquery = BigqueryServiceFactory.getService();
-
-
- Job loadJob = loadJob(
- bigquery,
- cloudStoragePath,
- new TableReference()
- .setProjectId(projectId)
- .setDatasetId(datasetId)
- .setTableId(tableId),
- BigqueryUtils.loadSchema(schemaSource));
-
- Bigquery.Jobs.Get getJob = bigquery.jobs().get(
- loadJob.getJobReference().getProjectId(),
- loadJob.getJobReference().getJobId());
-
- BigqueryUtils.pollJob(getJob, interval);
-
- System.out.println("Load is Done!");
-
- }
- // [END run]
-
- /**
- * A job that extracts data from a table.
- * @param bigquery Bigquery service to use
- * @param cloudStoragePath Cloud storage bucket we are inserting into
- * @param table Table to extract from
- * @param schema The schema of the table we are loading into
- * @return The job to extract data from the table
- * @throws IOException Thrown if error connceting to Bigtable
- */
- // [START load_job]
- public static Job loadJob(
- final Bigquery bigquery,
- final String cloudStoragePath,
- final TableReference table,
- final TableSchema schema) throws IOException {
-
- JobConfigurationLoad load = new JobConfigurationLoad()
- .setDestinationTable(table)
- .setSchema(schema)
- .setSourceUris(Collections.singletonList(cloudStoragePath));
-
- return bigquery.jobs().insert(table.getProjectId(),
- new Job().setConfiguration(new JobConfiguration().setLoad(load)))
- .execute();
- }
- // [END load_job]
-}
diff --git a/bigquery/src/main/java/com/google/cloud/bigquery/samples/StreamingSample.java b/bigquery/src/main/java/com/google/cloud/bigquery/samples/StreamingSample.java
deleted file mode 100644
index 3f2aed4b747..00000000000
--- a/bigquery/src/main/java/com/google/cloud/bigquery/samples/StreamingSample.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- 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
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-*/
-package com.google.cloud.bigquery.samples;
-
-import com.google.api.services.bigquery.Bigquery;
-import com.google.api.services.bigquery.model.TableDataInsertAllRequest;
-import com.google.api.services.bigquery.model.TableDataInsertAllResponse;
-import com.google.gson.Gson;
-import com.google.gson.JsonSyntaxException;
-import com.google.gson.stream.JsonReader;
-
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Scanner;
-
-
-/**
- * Example of Bigquery Streaming.
- */
-public class StreamingSample {
-
- /**
- * Empty constructor since this is just a collection of static methods.
- */
- protected StreamingSample() {
- }
-
-
- /**
- * Command line that demonstrates Bigquery streaming.
- *
- * @param args Command line args, should be empty
- * @throws IOException IOexception
- */
- // [START main]
- public static void main(final String[] args) throws IOException {
- final Scanner scanner = new Scanner(System.in);
- System.out.println("Enter your project id: ");
- String projectId = scanner.nextLine();
- System.out.println("Enter your dataset id: ");
- String datasetId = scanner.nextLine();
- System.out.println("Enter your table id: ");
- String tableId = scanner.nextLine();
- scanner.close();
-
- System.out.println("Enter JSON to stream to BigQuery: \n"
- + "Press End-of-stream (CTRL-D) to stop");
-
- JsonReader fromCli = new JsonReader(new InputStreamReader(System.in));
-
- Iterator responses = run(projectId,
- datasetId,
- tableId,
- fromCli);
-
- while (responses.hasNext()) {
- System.out.println(responses.next());
- }
-
- fromCli.close();
- }
- // [END main]
-
-
- /**
- * Run the bigquery ClI.
- *
- * @param projectId Project id
- * @param datasetId datasetid
- * @param tableId tableid
- * @param rows The source of the JSON rows we are streaming in.
- * @return Returns Iterates through the stream responses
- * @throws IOException Thrown if there is an error connecting to Bigquery.
- * @throws InterruptedException Should never be thrown
- */
- // [START run]
- public static Iterator run(final String projectId,
- final String datasetId,
- final String tableId,
- final JsonReader rows) throws IOException {
-
-
- final Bigquery bigquery = BigqueryServiceFactory.getService();
- final Gson gson = new Gson();
- rows.beginArray();
-
- return new Iterator() {
-
- /**
- * Check whether there is another row to stream.
- *
- * @return True if there is another row in the stream
- */
- public boolean hasNext() {
- try {
- return rows.hasNext();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return false;
- }
-
- /**
- * Insert the next row, and return the response.
- *
- * @return Next page of data
- */
- public TableDataInsertAllResponse next() {
- try {
- Map rowData = gson.