├── .gitignore ├── LICENSE ├── README.md ├── eclipse-launch-profiles ├── DevAppServer.launch └── UpdateApplication.launch ├── geoEngine.iml ├── nbactions.xml ├── pom.xml └── src └── main ├── java └── com │ └── google │ └── appengine │ └── geo │ └── fencing │ ├── Constants.java │ ├── GeoFencingAPI.java │ ├── MyFence.java │ ├── MyIndex.java │ ├── MyPolyLine.java │ └── MyPolygon.java └── webapp ├── WEB-INF ├── appengine-web.xml ├── logging.properties └── web.xml ├── addFence.html ├── index.html ├── js └── GEOJSON.js └── query.html /.gitignore: -------------------------------------------------------------------------------- 1 | #java specific 2 | *.class 3 | 4 | #netbeans ignore personal stuff 5 | nbproject/private/ 6 | 7 | 8 | ## generic files to ignore 9 | *~ 10 | *.lock 11 | *.DS_Store 12 | *.swp 13 | *.out 14 | 15 | .idea 16 | target -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Scalable geofencing API for Google App Engine 2 | 3 | An architecture proposal for a geofencing API on Google's [App Engine][1] using [Google Cloud Endpoints][3]. 4 | This API is able to geofence complex polygons at a large throughput using App Engine, Cloud Datastore and Memcache. 5 | It uses the [Java Topology Suite][7] to create a spatial index which is stored in Memcache for fast querying access. 6 | You can download, build and deploy the project as is using the [Google App Engine Maven plugin][4]. 7 | For a detailed explanation of the architecture please refer to this [Google Developers Blogpost][8]. 8 | 9 | ## Endpoints 10 | 11 | - __add__: Add a fence to a certain group. 12 | - __buildIndex__: Build the spatial index and write it to Memcache. 13 | - __getById__: Get a fence's metadata by it's id. 14 | - __list__: List all fences in a certain group. 15 | - __point__: Get all fences that contain a certain point. 16 | - __polygon__: Get all fences that aren't disjoint with a certain polygon. 17 | - __polyline__: Get all fences that intersect with a certain polyline. 18 | 19 | ## Test & Deploy to App Engine 20 | 21 | 1. Update the value of `application` in `src/main/webapp/WEB-INF/appengine-web.xml` to the app 22 | ID you have registered in the App Engine admin console and would 23 | like to use to host your instance of this sample. 24 | 25 | 1. **__Optional step:__** These sub steps are not required but you need this 26 | if you want to have auth protected methods. 27 | 28 | 2. Update the values in `src/main/java/com/google/appengine/geo/fencing/Constants.java` 29 | to reflect the respective client IDs you have registered in the 30 | [APIs Console][6]. 31 | 32 | 2. You also need to supply the web client ID you have registered 33 | in the [APIs Console][4] to your client of choice (web, Android, 34 | iOS). 35 | 36 | 1. Run the application with `mvn appengine:devserver`, and ensure it's 37 | running by visiting your local server (by 38 | default [localhost:8080][5].) 39 | 40 | 1. **__Optional step:__** Get the client library with 41 | 42 | `$ mvn appengine:endpoints_get_client_lib` 43 | 44 | It will generate a client library jar file under the 45 | `target/endpoints-client-libs//target` directory of your 46 | project, as well as install the artifact into your local maven 47 | repository. 48 | 49 | For more information on client libraries see: 50 | 51 | - [Generating Cleint Libraries][11] 52 | - [Client Library for JavaScript][10] 53 | 54 | 1. Deploy your application to Google App Engine with 55 | 56 | `$ mvn appengine:update` 57 | 58 | *Please note that you should always first test on the development server since that creates indexes for our datastore queries. Also after the first deployment App Engine takes a while to create the necessary indexes and connections, so if you get errors, just wait for a bit.* 59 | 60 | ## Example of using the [JavaScript Google Client Library with this API][10] 61 | 62 | - `src/main/webapp/addFence.html` is an example of how to use the Google Maps JavaScript API [Drawing Layer][9] 63 | to draw fences to the map and store them to your App Engines Datastore using the __add__ endpoint. 64 | 65 | - `src/main/webapp/query.html` shows you how to query your API for points, polylines and polygons. 66 | 67 | These examples can also be used to test your API. You should always first test on the devserver (`mvn appengine:devserver`), 68 | since this automatically creates indexes that are needed for our Datastore queries. 69 | 70 | [1]: https://developers.google.com/appengine 71 | [2]: http://java.com/en/ 72 | [3]: https://developers.google.com/appengine/docs/java/endpoints/ 73 | [4]: https://developers.google.com/appengine/docs/java/tools/maven 74 | [5]: http://localhost:8080/ 75 | [6]: https://console.developers.google.com/ 76 | [7]: http://www.vividsolutions.com/jts/JTSHome.htm 77 | [8]: http://googledevelopers.blogspot.com/2014/12/building-scalable-geofencing-api-on.html 78 | [9]: https://developers.google.com/maps/documentation/javascript/drawinglayer 79 | [10]: https://developers.google.com/api-client-library/javascript/start/start-js 80 | [11]: https://cloud.google.com/appengine/docs/java/endpoints/gen_clients -------------------------------------------------------------------------------- /eclipse-launch-profiles/DevAppServer.launch: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /eclipse-launch-profiles/UpdateApplication.launch: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /geoEngine.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | $MAVEN_REPOSITORY$/com/google/appengine/appengine-java-sdk/1.9.15/appengine-java-sdk/appengine-java-sdk-1.9.15 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /nbactions.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CUSTOM-appengine:devserver 5 | appengine:devserver 6 | 7 | appengine:devserver 8 | 9 | 10 | 11 | CUSTOM-appengine:update 12 | appengine:update 13 | 14 | appengine:update 15 | 16 | 17 | 18 | CUSTOM-appengine:rollback 19 | appengine:rollback 20 | 21 | appengine:rollback 22 | 23 | 24 | 25 | CUSTOM-appengine:update_cron 26 | appengine:update_cron 27 | 28 | appengine:update_cron 29 | 30 | 31 | 32 | CUSTOM-appengine:update_dos 33 | appengine:update_dos 34 | 35 | appengine:update_dos 36 | 37 | 38 | 39 | CUSTOM-appengine:update_indexes 40 | appengine:update_indexes 41 | 42 | appengine:update_indexes 43 | 44 | 45 | 46 | CUSTOM-appengine:update_queues 47 | appengine:update_queues 48 | 49 | appengine:update_queues 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 4.0.0 5 | war 6 | 1.0-SNAPSHOT 7 | 8 | com.google.appengine.geo.fencing 9 | geoEngine 10 | 11 | 12 | 1 13 | UTF-8 14 | 15 | 16 | 17 | 3.1.0 18 | 19 | 20 | 21 | 22 | 23 | com.google.appengine 24 | appengine-api-1.0-sdk 25 | 1.9.15 26 | 27 | 28 | com.google.appengine 29 | appengine-endpoints 30 | 1.9.15 31 | 32 | 33 | javax.servlet 34 | servlet-api 35 | 2.5 36 | provided 37 | 38 | 39 | javax.inject 40 | javax.inject 41 | 1 42 | 43 | 44 | 45 | 46 | com.vividsolutions 47 | jts 48 | 1.13 49 | 50 | 51 | 52 | 53 | com.google.code.gson 54 | gson 55 | 2.3.1 56 | 57 | 58 | 59 | 60 | junit 61 | junit 62 | 4.11 63 | test 64 | 65 | 66 | org.mockito 67 | mockito-all 68 | 1.9.5 69 | test 70 | 71 | 72 | com.google.appengine 73 | appengine-testing 74 | 1.9.15 75 | test 76 | 77 | 78 | com.google.appengine 79 | appengine-api-stubs 80 | 1.9.15 81 | test 82 | 83 | 84 | 85 | 86 | 87 | ${project.build.directory}/${project.build.finalName}/WEB-INF/classes 88 | 89 | 90 | org.codehaus.mojo 91 | versions-maven-plugin 92 | 2.1 93 | 94 | 95 | compile 96 | 97 | display-dependency-updates 98 | display-plugin-updates 99 | 100 | 101 | 102 | 103 | 104 | org.apache.maven.plugins 105 | 3.1 106 | maven-compiler-plugin 107 | 108 | 1.7 109 | 1.7 110 | 111 | 112 | 113 | org.apache.maven.plugins 114 | maven-war-plugin 115 | 2.4 116 | 117 | ${project.build.directory}/generated-sources/appengine-endpoints/WEB-INF/web.xml 118 | 119 | 120 | 121 | ${project.build.directory}/generated-sources/appengine-endpoints 122 | 123 | 124 | WEB-INF/*.discovery 125 | WEB-INF/*.api 126 | 127 | 128 | 129 | 130 | 131 | 132 | com.google.appengine 133 | appengine-maven-plugin 134 | 1.9.15 135 | 136 | false 137 | 138 | 140 | 142 | 145 | 146 | 147 | 148 | 149 | endpoints_get_discovery_doc 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | -------------------------------------------------------------------------------- /src/main/java/com/google/appengine/geo/fencing/Constants.java: -------------------------------------------------------------------------------- 1 | package com.google.appengine.geo.fencing; 2 | 3 | /** 4 | * Contains the client IDs and scopes for allowed clients consuming your API. 5 | */ 6 | public class Constants { 7 | public static final String WEB_CLIENT_ID = "replace this with your web client ID"; 8 | public static final String ANDROID_CLIENT_ID = "replace this with your Android client ID"; 9 | public static final String IOS_CLIENT_ID = "replace this with your iOS client ID"; 10 | public static final String ANDROID_AUDIENCE = WEB_CLIENT_ID; 11 | public static final String API_EXPLORER_CLIENT_ID = com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID; 12 | 13 | public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email"; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/google/appengine/geo/fencing/GeoFencingAPI.java: -------------------------------------------------------------------------------- 1 | package com.google.appengine.geo.fencing; 2 | 3 | import com.google.api.server.spi.config.Api; 4 | import com.google.api.server.spi.config.ApiMethod; 5 | import com.google.appengine.api.datastore.DatastoreService; 6 | import com.google.appengine.api.datastore.DatastoreServiceFactory; 7 | import com.google.appengine.api.datastore.Entity; 8 | import com.google.appengine.api.datastore.Key; 9 | import com.google.appengine.api.datastore.KeyFactory; 10 | import com.google.appengine.api.datastore.FetchOptions; 11 | import com.google.appengine.api.datastore.Query; 12 | import com.google.appengine.api.datastore.Query.Filter; 13 | import com.google.appengine.api.datastore.Query.FilterOperator; 14 | import com.google.appengine.api.datastore.Query.FilterPredicate; 15 | import com.google.appengine.api.datastore.Text; 16 | import com.google.appengine.api.memcache.MemcacheService; 17 | import com.google.appengine.api.memcache.MemcacheServiceFactory; 18 | 19 | import java.io.IOException; 20 | import java.util.ArrayList; 21 | import java.util.List; 22 | 23 | import com.google.gson.Gson; 24 | import com.vividsolutions.jts.geom.Coordinate; 25 | import com.vividsolutions.jts.geom.GeometryFactory; 26 | import com.vividsolutions.jts.geom.Point; 27 | import com.vividsolutions.jts.geom.Polygon; 28 | import com.vividsolutions.jts.index.strtree.STRtree; 29 | import com.vividsolutions.jts.geom.LinearRing; 30 | import com.vividsolutions.jts.geom.LineString; 31 | 32 | import javax.inject.Named; 33 | 34 | /** 35 | * API annotation, see: 36 | * https://cloud.google.com/appengine/docs/java/endpoints/annotations 37 | */@Api( 38 | name = "geofencing", 39 | version = "v1", 40 | description = "Store geofences and query them", 41 | clientIds = { 42 | Constants.WEB_CLIENT_ID 43 | }) 44 | 45 | public class GeoFencingAPI { 46 | /** 47 | * Endpoint for adding fences to the DataStore collection. 48 | */@ApiMethod(name = "add", httpMethod = "post", path = "add") 49 | public MyFence addFence(@Named("group") String group, @Named("index") boolean buildIndex, MyFence fence) { 50 | //Get the last fences' id. 51 | DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); 52 | Key fenceKey = KeyFactory.createKey("Geofence", group); 53 | 54 | long nextId; 55 | if (fence.getId() != -1) { 56 | nextId = fence.getId(); 57 | } else { 58 | long lastId; 59 | Query query = new Query("Fence", fenceKey).addSort("id", Query.SortDirection.DESCENDING); 60 | List < Entity > lastFence = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)); 61 | 62 | if (lastFence.isEmpty()) { 63 | lastId = -1; 64 | } else { 65 | lastId = (long) lastFence.get(0).getProperty("id"); 66 | } 67 | nextId = lastId + 1; 68 | } 69 | 70 | //Create new Entity with nextId. 71 | Entity fenceEntity = new Entity("Fence", fenceKey); 72 | fenceEntity.setProperty("id", nextId); 73 | fenceEntity.setProperty("name", fence.getName()); 74 | fenceEntity.setProperty("description", fence.getDescription()); 75 | 76 | Gson gson = new Gson(); 77 | String jsonString = gson.toJson(fence.getVertices()); 78 | //Convert to DataStore-Text-Object to store the vertices. 79 | Text jsonText = new Text(jsonString); 80 | fenceEntity.setProperty("vertices", jsonText); 81 | //Write to DataStore. 82 | datastore.put(fenceEntity); 83 | 84 | MyFence newFence = new MyFence(); 85 | newFence.setId(nextId); 86 | 87 | //Rebuild the Index. 88 | if (buildIndex) { 89 | try { 90 | MyIndex.buildIndex(group); 91 | } catch (IOException e) { 92 | e.printStackTrace(); 93 | } 94 | } 95 | 96 | return newFence; 97 | } 98 | 99 | /** 100 | * Endpoint for listing all fences from the DataStore collection. 101 | */@ApiMethod(name = "list", httpMethod = "get", path = "list") 102 | public ArrayList < MyFence > listFences(@Named("group") String group) { 103 | ArrayList < MyFence > fences = new ArrayList < MyFence > (); 104 | 105 | DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); 106 | Key fenceKey = KeyFactory.createKey("Geofence", group); 107 | 108 | Query query = new Query("Fence", fenceKey).addSort("id", Query.SortDirection.DESCENDING); 109 | List < Entity > fencesFromStore = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults()); 110 | 111 | if (fencesFromStore.isEmpty()) { 112 | return fences; 113 | } else { 114 | for (Entity fenceFromStore: fencesFromStore) { 115 | long id = (long) fenceFromStore.getProperty("id"); 116 | String name = (String) fenceFromStore.getProperty("name"); 117 | String description = (String) fenceFromStore.getProperty("description"); 118 | Gson gson = new Gson(); 119 | Text vText = (Text) fenceFromStore.getProperty("vertices"); 120 | String vString = vText.getValue(); 121 | double[][] vertices = gson.fromJson(vString, double[][].class); 122 | 123 | MyFence tempFence = new MyFence(id, name, group, description, vertices); 124 | fences.add(tempFence); 125 | } 126 | return fences; 127 | } 128 | } 129 | 130 | /** 131 | * Endpoint for finding the fences a certain point is in. 132 | */@ApiMethod(name = "point", httpMethod = "get", path = "point") 133 | public ArrayList < MyFence > queryPoint(@Named("group") String group, @Named("lng") double lng, @Named("lat") double lat) { 134 | ArrayList < MyFence > fences = new ArrayList < MyFence > (); 135 | 136 | //Get the Index from Memcache. 137 | MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); 138 | GeometryFactory gf = new GeometryFactory(); 139 | STRtree index = (STRtree) syncCache.get(group); // read from cache 140 | if (index != null) { 141 | Coordinate coord = new Coordinate(lng, lat); 142 | Point point = gf.createPoint(coord); 143 | List < MyPolygon > items = index.query(point.getEnvelopeInternal()); 144 | if (!items.isEmpty()) { 145 | for (MyPolygon poly: items) { 146 | if (poly.contains(point)) { 147 | long id = poly.getID(); 148 | MyFence newFence = new MyFence(); 149 | newFence.setId(id); 150 | fences.add(newFence); 151 | } 152 | } 153 | } 154 | } else { 155 | try { 156 | MyIndex.buildIndex(group); 157 | } catch (IOException e) { 158 | e.printStackTrace(); 159 | } 160 | } 161 | return fences; 162 | } 163 | 164 | /** 165 | * Endpoint for getting a fence's metadata by its id. 166 | */@ApiMethod(name = "getById", httpMethod = "get", path = "getById") 167 | public ArrayList < MyFence > getFenceById(@Named("group") String group, @Named("id") long id) { 168 | DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); 169 | Key fenceKey = KeyFactory.createKey("Geofence", group); 170 | Filter propertyFilter = new FilterPredicate("id", FilterOperator.EQUAL, id); 171 | Query query = new Query("Fence", fenceKey).setFilter(propertyFilter); 172 | Entity fenceFromStore = datastore.prepare(query).asSingleEntity(); 173 | 174 | ArrayList < MyFence > fences = new ArrayList < MyFence > (); 175 | if (fenceFromStore != null) { 176 | String name = (String) fenceFromStore.getProperty("name"); 177 | String description = (String) fenceFromStore.getProperty("description"); 178 | Gson gson = new Gson(); 179 | Text vText = (Text) fenceFromStore.getProperty("vertices"); 180 | String vString = vText.getValue(); 181 | double[][] vertices = gson.fromJson(vString, double[][].class); 182 | 183 | MyFence tempFence = new MyFence(id, name, group, description, vertices); 184 | fences.add(tempFence); 185 | } 186 | return fences; 187 | } 188 | 189 | /** 190 | * Endpoint for finding the fences that intersect with a polyline. 191 | */@ApiMethod(name = "polyline", httpMethod = "post", path = "polyline") 192 | public ArrayList < MyFence > queryPolyLine(@Named("group") String group, MyPolyLine polyline) { 193 | ArrayList < MyFence > fences = new ArrayList < MyFence > (); 194 | 195 | //Get the index from Memcache. 196 | MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); 197 | GeometryFactory gf = new GeometryFactory(); 198 | STRtree index = (STRtree) syncCache.get(group); // read from cache 199 | if (index != null) { 200 | //Create coordinate array. 201 | double[][] points = polyline.getCoordinates(); 202 | Coordinate[] coordinates = new Coordinate[points.length]; 203 | int i = 0; 204 | for (double[] point: points) { 205 | Coordinate coordinate = new Coordinate(point[0], point[1]); 206 | coordinates[i++] = coordinate; 207 | } 208 | //Create polyline. 209 | GeometryFactory fact = new GeometryFactory(); 210 | LineString linestring = new GeometryFactory().createLineString(coordinates); 211 | 212 | List < MyPolygon > items = index.query(linestring.getEnvelopeInternal()); 213 | if (!items.isEmpty()) { 214 | for (MyPolygon poly: items) { 215 | if (linestring.crosses(poly) || poly.contains(linestring)) { 216 | long id = poly.getID(); 217 | MyFence newFence = new MyFence(); 218 | newFence.setId(id); 219 | fences.add(newFence); 220 | } 221 | } 222 | } 223 | } else { 224 | try { 225 | MyIndex.buildIndex(group); 226 | } catch (IOException e) { 227 | e.printStackTrace(); 228 | } 229 | } 230 | 231 | return fences; 232 | } 233 | 234 | /** 235 | * Endpoint for finding the fences that intersect with a polygon. 236 | */@ApiMethod(name = "polygon", httpMethod = "post", path = "polygon") 237 | public ArrayList < MyFence > queryPolygon(@Named("group") String group, MyPolyLine polyline) { 238 | ArrayList < MyFence > fences = new ArrayList < MyFence > (); 239 | 240 | //Get index from Memcache 241 | MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); 242 | STRtree index = (STRtree) syncCache.get(group); // read from cache 243 | if (index != null) { 244 | //Create coordinate array. 245 | double[][] points = polyline.getCoordinates(); 246 | Coordinate[] coordinates = new Coordinate[points.length]; 247 | int i = 0; 248 | for (double[] point: points) { 249 | Coordinate coordinate = new Coordinate(point[0], point[1]); 250 | coordinates[i++] = coordinate; 251 | } 252 | //Create polygon. 253 | GeometryFactory fact = new GeometryFactory(); 254 | LinearRing linear = new GeometryFactory().createLinearRing(coordinates); 255 | Polygon polygon = new Polygon(linear, null, fact); 256 | 257 | List < MyPolygon > items = index.query(polygon.getEnvelopeInternal()); 258 | if (!items.isEmpty()) { 259 | for (MyPolygon poly: items) { 260 | if (polygon.contains(poly) || !polygon.disjoint(poly)) { 261 | long id = poly.getID(); 262 | MyFence newFence = new MyFence(); 263 | newFence.setId(id); 264 | fences.add(newFence); 265 | } 266 | } 267 | } 268 | } else { 269 | try { 270 | MyIndex.buildIndex(group); 271 | } catch (IOException e) { 272 | e.printStackTrace(); 273 | } 274 | } 275 | 276 | return fences; 277 | } 278 | 279 | /** 280 | * Endpoint for building and storing the index for a certain group to Memcache. 281 | */@ApiMethod(name = "buildIndex", httpMethod = "get", path = "buildIndex") 282 | public MyFence buildIndex(@Named("group") String group) { 283 | MyFence fence = new MyFence(); 284 | 285 | long id; 286 | try { 287 | id = (long) MyIndex.buildIndex(group); 288 | fence.setId(id); 289 | } catch (IOException e) { 290 | e.printStackTrace(); 291 | } 292 | 293 | return fence; 294 | } 295 | 296 | //TODO delete group 297 | } -------------------------------------------------------------------------------- /src/main/java/com/google/appengine/geo/fencing/MyFence.java: -------------------------------------------------------------------------------- 1 | package com.google.appengine.geo.fencing; 2 | 3 | /** The object model for the data we are sending through endpoints */ 4 | public class MyFence { 5 | 6 | private long id = -1; 7 | public String name; 8 | public String entityGroup; 9 | public String description; 10 | public double[][] vertices; 11 | 12 | public MyFence() {}; 13 | 14 | public MyFence(long id, String name, String entityGroup, String description, double[][] vertices) { 15 | this.id = id; 16 | this.name = name; 17 | this.entityGroup = entityGroup; 18 | this.description = description; 19 | this.vertices = vertices; 20 | } 21 | 22 | public long getId() { 23 | return id; 24 | } 25 | 26 | public void setId(long id) { 27 | this.id = id; 28 | } 29 | 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public void setName(String name) { 35 | this.name = name; 36 | } 37 | 38 | public String getEntityGroup() { 39 | return entityGroup; 40 | } 41 | 42 | public void setEntityGroup(String entityGroup) { 43 | this.entityGroup = entityGroup; 44 | } 45 | 46 | public String getDescription() { 47 | return description; 48 | } 49 | 50 | public void setDescription(String description) { 51 | this.description = description; 52 | } 53 | 54 | public double[][] getVertices() { 55 | return vertices; 56 | } 57 | 58 | public void setVertices(double[][] vertices) { 59 | this.vertices = vertices; 60 | } 61 | } -------------------------------------------------------------------------------- /src/main/java/com/google/appengine/geo/fencing/MyIndex.java: -------------------------------------------------------------------------------- 1 | package com.google.appengine.geo.fencing; 2 | 3 | import com.google.appengine.api.datastore.DatastoreService; 4 | import com.google.appengine.api.datastore.DatastoreServiceFactory; 5 | import com.google.appengine.api.datastore.Entity; 6 | import com.google.appengine.api.datastore.Key; 7 | import com.google.appengine.api.datastore.KeyFactory; 8 | import com.google.appengine.api.datastore.FetchOptions; 9 | import com.google.appengine.api.datastore.Query; 10 | import com.google.appengine.api.datastore.Text; 11 | 12 | 13 | 14 | import com.google.appengine.api.memcache.MemcacheService; 15 | import com.google.appengine.api.memcache.MemcacheServiceFactory; 16 | 17 | import java.io.IOException; 18 | import java.util.List; 19 | 20 | import com.google.gson.Gson; 21 | import com.vividsolutions.jts.geom.Coordinate; 22 | import com.vividsolutions.jts.geom.GeometryFactory; 23 | import com.vividsolutions.jts.geom.Polygon; 24 | import com.vividsolutions.jts.index.strtree.STRtree; 25 | import com.vividsolutions.jts.geom.LinearRing; 26 | 27 | 28 | public class MyIndex { 29 | //Create the index and store it in Memcache. 30 | public static int buildIndex(String group) throws IOException{ 31 | //Get all fences of group from DataStore. 32 | DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); 33 | Key fenceKey = KeyFactory.createKey("Geofence", group); 34 | 35 | Query query = new Query("Fence", fenceKey).addSort("id", Query.SortDirection.DESCENDING); 36 | List fencesFromStore = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults()); 37 | 38 | if (!fencesFromStore.isEmpty()) { 39 | //Create STRTree-Index. 40 | STRtree index = new STRtree(); 41 | //Loop through the fences from DataStore. 42 | for (Entity fenceFromStore : fencesFromStore) { 43 | long id = (long) fenceFromStore.getProperty("id"); 44 | Gson gson = new Gson(); 45 | Text vText = (Text) fenceFromStore.getProperty("vertices"); 46 | String vString = vText.getValue(); 47 | double[][] vertices = gson.fromJson(vString, double[][].class); 48 | 49 | //Store coordinates in an array. 50 | Coordinate[] coordinates = new Coordinate[vertices.length]; 51 | int i = 0; 52 | for(double[] point : vertices){ 53 | Coordinate coordinate = new Coordinate(point[0],point[1]); 54 | coordinates[i++] = coordinate; 55 | } 56 | //Create polygon from the coordinates. 57 | GeometryFactory fact = new GeometryFactory(); 58 | LinearRing linear = new GeometryFactory().createLinearRing(coordinates); 59 | MyPolygon polygon = new MyPolygon(linear, null, fact, id); 60 | //Add polygon to index. 61 | index.insert(polygon.getEnvelopeInternal(), polygon); 62 | } 63 | //Build the index. 64 | index.build(); 65 | //Write the index to Memcache. 66 | MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); 67 | //Last param is expiration date. Set to null to keep it in Memcache forever. 68 | syncCache.put(group, index, null); 69 | } 70 | return fencesFromStore.size(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/google/appengine/geo/fencing/MyPolyLine.java: -------------------------------------------------------------------------------- 1 | package com.google.appengine.geo.fencing; 2 | 3 | /** 4 | * Bean for Polylines. 5 | */ 6 | public class MyPolyLine { 7 | public double[][] coordinates; 8 | 9 | public MyPolyLine() {}; 10 | 11 | public MyPolyLine(double[][] coordinates){ 12 | this.coordinates = coordinates; 13 | } 14 | 15 | public double[][] getCoordinates() { 16 | return coordinates; 17 | } 18 | 19 | public void setCoordinates(double[][] coordinates) { 20 | this.coordinates = coordinates; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/google/appengine/geo/fencing/MyPolygon.java: -------------------------------------------------------------------------------- 1 | package com.google.appengine.geo.fencing; 2 | 3 | import com.vividsolutions.jts.geom.GeometryFactory; 4 | import com.vividsolutions.jts.geom.LinearRing; 5 | import com.vividsolutions.jts.geom.Polygon; 6 | 7 | public class MyPolygon extends Polygon { 8 | private long ID; 9 | 10 | public MyPolygon(LinearRing shell, LinearRing[] holes, GeometryFactory factory, long ID) { 11 | super(shell, holes, factory); 12 | this.ID = ID; 13 | } 14 | 15 | public long getID() { 16 | return ID; 17 | } 18 | 19 | public void setID(long ID) { 20 | this.ID = ID; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/appengine-web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | YOUR-PROJECT-ID 4 | 1 5 | true 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/logging.properties: -------------------------------------------------------------------------------- 1 | # A default java.util.logging configuration. 2 | # (All App Engine logging is through java.util.logging by default). 3 | # 4 | # To use this configuration, copy it into your application's WEB-INF 5 | # folder and add the following to your appengine-web.xml: 6 | # 7 | # 8 | # 9 | # 10 | # 11 | 12 | # Set the default logging level for all loggers to WARNING 13 | .level = WARNING 14 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | SystemServiceServlet 4 | com.google.api.server.spi.SystemServiceServlet 5 | 6 | services 7 | com.google.appengine.geo.fencing.GeoFencingAPI 8 | 9 | 10 | 11 | SystemServiceServlet 12 | /_ah/spi/* 13 | 14 | 15 | index.html 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/main/webapp/addFence.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | AddFence 6 | 7 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 125 | 126 | 127 | 128 | 129 |
130 |
131 | 132 |
133 | 136 |
137 | 138 |
139 | 140 |
141 | 144 |
145 |
146 | 147 | -------------------------------------------------------------------------------- /src/main/webapp/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | GeoFencing API 6 | 7 | 8 |

GeoFencing API

9 | 14 | 15 | -------------------------------------------------------------------------------- /src/main/webapp/js/GEOJSON.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by schaeff on 9/25/14. 3 | */ 4 | 5 | var GEOJSON = (function(gj){ 6 | gj.Polygon = function(properties, inner, outer){ 7 | this.type = "Feature"; 8 | this.properties = properties; 9 | this.geometry = { 10 | "type": "Polygon", 11 | "coordinates": outer ? [inner,outer] : [inner] 12 | } 13 | }; 14 | 15 | //EXPORT 16 | return gj; 17 | }(GEOJSON || {})); -------------------------------------------------------------------------------- /src/main/webapp/query.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Query 6 | 7 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 176 | 177 | 178 | 179 | 180 |
181 |
182 | 183 |
184 | 187 |
188 | 189 |
190 | 191 |
192 | 195 |
196 |
197 | 198 | --------------------------------------------------------------------------------