Skip to content

Add AE Datastore geo query sample. #225

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 2, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions appengine/datastore/geo/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<!--
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.
-->
<project>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<groupId>com.example.appengine</groupId>
<artifactId>appengine-datastore-geo</artifactId>

<parent>
<groupId>com.google.cloud</groupId>
<artifactId>doc-samples</artifactId>
<version>1.0.0</version>
<relativePath>../../..</relativePath>
</parent>

<dependencies>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>${appengine.sdk.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<type>jar</type>
<scope>provided</scope>
</dependency>

<!-- Test Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-testing</artifactId>
<version>${appengine.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-stubs</artifactId>
<version>${appengine.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-tools-sdk</artifactId>
<version>${appengine.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>0.28</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<!-- for hot reload of the web application -->
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>
<plugins>
<!-- Parent POM defines ${appengine.sdk.version} (updates frequently). -->
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>${appengine.sdk.version}</version>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
/*
* 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<Entity> 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<Entity> rectResults = datastore.prepare(q2).asList(FetchOptions.Builder.withDefaults());
out.printf("Got %d stations in rectangle.\n", rectResults.size());
printStations(out, rectResults);
out.println();

List<Entity> 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<Entity> 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<Entity> 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());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* 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");
}
}
21 changes: 21 additions & 0 deletions appengine/datastore/geo/src/main/webapp/WEB-INF/appengine-web.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
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.
-->
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>YOUR-PROJECT-ID</application>
<version>YOUR-VERSION-ID</version>
<threadsafe>true</threadsafe>
</appengine-web-app>
Loading