Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Now we need to create an endpoint called add. This endpoint expects a string for the group name, a boolean indicating whether to rebuild our index, and a JSON object representing our fence’s object model. From this we create a new fence and write it to Cloud Datastore.
@ApiMethod(name = "add", httpMethod = "post", path = "add")
public MyFence addFence(@Named("group") String group, @Named("index") boolean buildIndex, MyFence fence) {
//Get the last fences' id.
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key fenceKey = KeyFactory.createKey("Geofence", group);
long nextId;
if (fence.getId() != -1) {
nextId = fence.getId();
} else {
long lastId;
Query query = new Query("Fence", fenceKey).addSort("id", Query.SortDirection.DESCENDING);
List < Entity > lastFence = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1));
if (lastFence.isEmpty()) {
lastId = -1;
} else {
lastId = (long) lastFence.get(0).getProperty("id");
nextId = lastId + 1;
//Create new Entity with nextId.
Entity fenceEntity = new Entity("Fence", fenceKey);
fenceEntity.setProperty("id", nextId);
fenceEntity.setProperty("name", fence.getName());
fenceEntity.setProperty("description", fence.getDescription());
Gson gson = new Gson();
String jsonString = gson.toJson(fence.getVertices());
//Convert to DataStore-Text-Object to store the vertices.
Text jsonText = new Text(jsonString);
fenceEntity.setProperty("vertices", jsonText);
//Write to DataStore.
MyFence newFence = new MyFence();
//Rebuild the Index.
if (buildIndex) {
try {
} catch (IOException e) {
return newFence;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.