Skip to content

Instantly share code, notes, and snippets.

@thorwebdev
Created December 7, 2014 16:02
Show Gist options
  • Save thorwebdev/02840865b7a25f75f014 to your computer and use it in GitHub Desktop.
Save thorwebdev/02840865b7a25f75f014 to your computer and use it in GitHub Desktop.
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.
datastore.put(fenceEntity);
MyFence newFence = new MyFence();
newFence.setId(nextId);
//Rebuild the Index.
if (buildIndex) {
try {
MyIndex.buildIndex(group);
} catch (IOException e) {
e.printStackTrace();
}
}
return newFence;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment