@Override public <T extends DataModel> T findData(UUID jobId, String key, Class<T> type) { Key entityKey = getDataKey(jobId, key); Entity entity = datastore.get(entityKey); if (entity == null) { return null; } String serializedEntity = entity.getString(type.getName()); try { return objectMapper.readValue(serializedEntity, type); } catch (IOException t) { throw new RuntimeException("Failed to deserialize entity: " + serializedEntity, t); } }
private static Map<String, Object> getProperties(Entity entity) throws IOException, ClassNotFoundException { if (entity == null) { return null; } ImmutableMap.Builder<String, Object> builder = new ImmutableMap.Builder<>(); for (String property : entity.getNames()) { // builder.put(property, entity.getValue(property)); if (entity.getValue(property) instanceof StringValue) { builder.put(property, (String) entity.getString(property)); } else if (entity.getValue(property) instanceof LongValue) { // This conversion is safe because of integer to long conversion above builder.put(property, new Long(entity.getLong(property)).intValue()); } else if (entity.getValue(property) instanceof DoubleValue) { builder.put(property, (Double) entity.getDouble(property)); } else if (entity.getValue(property) instanceof BooleanValue) { builder.put(property, (Boolean) entity.getBoolean(property)); } else if (entity.getValue(property) instanceof TimestampValue) { builder.put(property, (Timestamp) entity.getTimestamp(property)); } else { Blob blob = entity.getBlob(property); Object obj = null; try (ObjectInputStream in = new ObjectInputStream(blob.asInputStream())) { obj = in.readObject(); } builder.put(property, obj); // BlobValue } } return builder.build(); }
public static void main(String... args) { Datastore datastore = DatastoreOptions.getDefaultInstance().getService(); KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind"); Key key = keyFactory.newKey("keyName"); Entity entity = datastore.get(key); if (entity != null) { System.out.println("Updating access_time for " + entity.getString("name")); entity = Entity.newBuilder(entity).set("access_time", Timestamp.now()).build(); datastore.update(entity); } } }
while (results.hasNext()) { Entity result = results.next(); sortedComments.put(result.getTimestamp("timestamp"), result.getString("content")); resultCount++;
@Test public void testEntity() throws Exception { assertTrue(ENTITY.hasKey()); assertEquals(KEY1, ENTITY.getKey()); assertEquals("bar", ENTITY.getString("foo")); }
@Test public void testGetArrayNoDeferredResults() { datastore.put(ENTITY3); Iterator<Entity> result = datastore.fetch(KEY1, Key.newBuilder(KEY1).setName("bla").build(), KEY2, KEY3).iterator(); assertEquals(ENTITY1, result.next()); assertNull(result.next()); assertEquals(ENTITY2, result.next()); Entity entity3 = result.next(); assertEquals(ENTITY3, entity3); assertTrue(entity3.isNull("null")); assertFalse(entity3.getBoolean("bool")); assertEquals(LIST_VALUE2.get(), entity3.getList("list")); FullEntity<IncompleteKey> partial1 = entity3.getEntity("partial1"); FullEntity<IncompleteKey> partial2 = entity3.getEntity("partial2"); assertEquals(PARTIAL_ENTITY2, partial1); assertEquals(ENTITY2, partial2); assertEquals(ValueType.BOOLEAN, entity3.getValue("bool").getType()); assertEquals(LAT_LNG_VALUE, entity3.getValue("latLng")); assertEquals(EMPTY_LIST_VALUE, entity3.getValue("emptyList")); assertEquals(8, entity3.getNames().size()); assertFalse(entity3.contains("bla")); try { entity3.getString("str"); fail("Expecting a failure"); } catch (DatastoreException expected) { // expected - no such property } assertFalse(result.hasNext()); }
@Test public void testGetArrayNoDeferredResults() { DATASTORE.put(ENTITY3); Iterator<Entity> result = DATASTORE.fetch(KEY1, Key.newBuilder(KEY1).setName("bla").build(), KEY2, KEY3).iterator(); assertEquals(ENTITY1, result.next()); assertNull(result.next()); assertEquals(ENTITY2, result.next()); Entity entity3 = result.next(); assertEquals(ENTITY3, entity3); assertTrue(entity3.isNull("null")); assertFalse(entity3.getBoolean("bool")); assertEquals(LIST_VALUE2.get(), entity3.getList("list")); FullEntity<IncompleteKey> partial1 = entity3.getEntity("partial1"); FullEntity<IncompleteKey> partial2 = entity3.getEntity("partial2"); assertEquals(PARTIAL_ENTITY2, partial1); assertEquals(ENTITY2, partial2); assertEquals(ValueType.BOOLEAN, entity3.getValue("bool").getType()); assertEquals(LAT_LNG_VALUE, entity3.getValue("latLng")); assertEquals(EMPTY_LIST_VALUE, entity3.getValue("emptyList")); assertEquals(8, entity3.getNames().size()); assertFalse(entity3.contains("bla")); try { entity3.getString("str"); fail("Expecting a failure"); } catch (DatastoreException expected) { // expected - no such property } assertFalse(result.hasNext()); }
/** * Return a list of all users. */ public List<User> getAllUsers() { Query<Entity> query = Query.newGqlQueryBuilder(Query.ResultType.ENTITY, "SELECT * FROM " + kind).build(); QueryResults<Entity> results = datastore.run(query); List<User> users = new ArrayList<>(); while (results.hasNext()) { Entity result = results.next(); users.add( new User(result.getString("id"), result.getString("name"), result.getString("email"))); } return users; }
/** * Converts a list of task entities to a list of formatted task strings. * * @param tasks An iterator over task entities * @return A list of tasks strings, one per entity */ static List<String> formatTasks(Iterator<Entity> tasks) { List<String> strings = new ArrayList<>(); while (tasks.hasNext()) { Entity task = tasks.next(); if (task.getBoolean("done")) { strings.add( String.format("%d : %s (done)", task.getKey().getId(), task.getString("description"))); } else { strings.add(String.format("%d : %s (created %s)", task.getKey().getId(), task.getString("description"), task.getTimestamp("created"))); } } return strings; }
while (results.hasNext()) { Entity currentEntity = results.next(); System.out.println(currentEntity.getString("name") + ", you're invited to a pizza party!");
public static void main(String... args) throws Exception { // Instantiates a client Datastore datastore = DatastoreOptions.getDefaultInstance().getService(); // The kind for the new entity String kind = "Task"; // The name/ID for the new entity String name = "sampletask1"; // The Cloud Datastore key for the new entity Key taskKey = datastore.newKeyFactory().setKind(kind).newKey(name); // Prepares the new entity Entity task = Entity.newBuilder(taskKey) .set("description", "Buy milk") .build(); // Saves the entity datastore.put(task); System.out.printf("Saved %s: %s%n", task.getKey().getName(), task.getString("description")); //Retrieve entity Entity retrieved = datastore.get(taskKey); System.out.printf("Retrieved %s: %s%n", taskKey.getName(), retrieved.getString("description")); } }
Query<Entity> query = Query.gqlQueryBuilder(Query.ResultType.ENTITY, "SELECT * FROM " + kind + " WHERE num < @num") .setBinding("num", 100) .build(); QueryResults<Entity> results = datastore.run(query); while (results.hasNext()) { Entity result = results.next(); myList.add(result.getString("num")); ...
private WorkflowInstance parseWorkflowInstance(Entity activeWorkflowInstance) { final String componentId = activeWorkflowInstance.getString(PROPERTY_COMPONENT); final String workflowId = activeWorkflowInstance.getString(PROPERTY_WORKFLOW); final String parameter = activeWorkflowInstance.getString(PROPERTY_PARAMETER); return WorkflowInstance.create(WorkflowId.create(componentId, workflowId), parameter); }
static <T> Optional<T> readOptJson(Entity entity, String property, Class<T> cls) throws IOException { return entity.contains(property) ? Optional.of(OBJECT_MAPPER.readValue(entity.getString(property), cls)) : Optional.empty(); }
static <T> Optional<T> readOptJson(Entity entity, String property, TypeReference valueTypeRef) throws IOException { return entity.contains(property) ? Optional.of(OBJECT_MAPPER.readValue(entity.getString(property), valueTypeRef)) : Optional.empty(); }
private String getStrategyId(Entity featureEntity) { if (featureEntity.contains(STRATEGY_ID)) { final String strategyId = featureEntity.getString(STRATEGY_ID); if (!Strings.isNullOrEmpty(strategyId)) { return strategyId.trim(); } } return null; }
static Workflow parseWorkflowJson(Entity entity, WorkflowId workflowId) throws IOException { try { return OBJECT_MAPPER .readValue(entity.getString(PROPERTY_WORKFLOW_JSON), Workflow.class); } catch (IOException e) { LOG.error("Failed to read workflow for {}, {}", workflowId.componentId(), workflowId.id(), e); throw e; } }
private List<Workflow> getBatchOfWorkflows(final List<WorkflowId> batch) throws IOException { final List<Key> keys = batch.stream() .map(workflowId -> workflowKey(datastore.newKeyFactory(), workflowId)) .collect(toList()); final List<Workflow> workflows = new ArrayList<>(); datastore.get(keys, entity -> { try { workflows.add(OBJECT_MAPPER.readValue(entity.getString(PROPERTY_WORKFLOW_JSON), Workflow.class)); } catch (IOException e) { LOG.warn("Failed to read workflow {}.", entity.getKey(), e); } }); return workflows; }
public Map<WorkflowId, Workflow> workflows() throws IOException { final Map<WorkflowId, Workflow> map = Maps.newHashMap(); final EntityQuery query = Query.newEntityQueryBuilder().setKind(KIND_WORKFLOW).build(); datastore.query(query, entity -> { final Workflow workflow; try { workflow = OBJECT_MAPPER.readValue(entity.getString(PROPERTY_WORKFLOW_JSON), Workflow.class); } catch (IOException e) { LOG.warn("Failed to read workflow {}.", entity.getKey(), e); return; } map.put(workflow.id(), workflow); }); return map; }