Java Code Examples for com.google.cloud.datastore.Key#getName()

The following examples show how to use com.google.cloud.datastore.Key#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GoogleJobStore.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
@Override
public <T extends DataModel> void update(UUID jobId, String key, T model) {
  Transaction transaction = datastore.newTransaction();
  Key entityKey = getDataKey(jobId, key);

  try {
    Entity previousEntity = transaction.get(entityKey);
    if (previousEntity == null) {
      throw new IOException("Could not find record for data key: " + entityKey.getName());
    }

    String serialized = objectMapper.writeValueAsString(model);
    Entity entity =
        Entity.newBuilder(entityKey)
            .set(CREATED_FIELD, Timestamp.now())
            .set(model.getClass().getName(), serialized)
            .build();

    transaction.put(entity);
    transaction.commit();
  } catch (IOException t) {
    transaction.rollback();
    throw new RuntimeException("Failed atomic update of key: " + key, t);
  }
}
 
Example 2
Source File: DefaultDatastoreMetadata.java    From catatumbo with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getKinds(boolean excludeSystemKinds) {
  try {
    String query = "SELECT __key__ FROM " + ENTITY_KINDS + " ORDER BY __key__";
    GqlQuery.Builder<Key> gqlQueryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, query);
    gqlQueryBuilder.setNamespace(entityManager.getEffectiveNamespace());
    GqlQuery<Key> gqlQuery = gqlQueryBuilder.build();
    QueryResults<Key> results = entityManager.getDatastore().run(gqlQuery);
    List<String> kinds = new ArrayList<>(50);
    while (results.hasNext()) {
      Key key = results.next();
      String kind = key.getName();
      if (excludeSystemKinds && kind.startsWith("__")) {
        continue;
      }
      kinds.add(key.getName());
    }
    return kinds;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example 3
Source File: ConceptsTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertyRunQuery() {
  setUpQueryTests();
  // [START datastore_property_run_query]
  Query<Key> query = Query.newKeyQueryBuilder().setKind("__property__").build();
  QueryResults<Key> keys = datastore.run(query);
  Map<String, Collection<String>> propertiesByKind = new HashMap<>();
  while (keys.hasNext()) {
    Key key = keys.next();
    String kind = key.getParent().getName();
    String propertyName = key.getName();
    Collection<String> properties = propertiesByKind.get(kind);
    if (properties == null) {
      properties = new HashSet<>();
      propertiesByKind.put(kind, properties);
    }
    properties.add(propertyName);
  }
  // [END datastore_property_run_query]
  Map<String, ImmutableSet<String>> expected = ImmutableMap.of("Task", ImmutableSet.of(
      "done", "category", "done", "completed", "priority", "created", "percent_complete", "tag"));
  assertEquals(expected, propertiesByKind);
}
 
Example 4
Source File: GoogleJobStore.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends DataModel> void create(UUID jobId, String key, T model) throws IOException {
  Preconditions.checkNotNull(jobId);
  Transaction transaction = datastore.newTransaction();
  Key fullKey = getDataKey(jobId, key);
  Entity shouldNotExist = transaction.get(fullKey);
  if (shouldNotExist != null) {
    transaction.rollback();
    throw new IOException(
        "Record already exists for key: " + fullKey.getName() + ". Record: " + shouldNotExist);
  }

  String serialized = objectMapper.writeValueAsString(model);
  Entity entity =
      Entity.newBuilder(fullKey)
          .set(CREATED_FIELD, Timestamp.now())
          .set(model.getClass().getName(), serialized)
          .build();

  try {
    transaction.put(entity);
  } catch (DatastoreException e) {
    throw new IOException(
        "Could not create initial record for jobID: " + jobId + ". Record: " + entity, e);
  }
  transaction.commit();
}
 
Example 5
Source File: DefaultDatastoreMetadata.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public QueryResponse<String> getNamespaces(DatastoreCursor fromCursor, int limit) {
  try {
    String query = "SELECT __key__ FROM " + ENTITY_NAMESPACES + " ORDER BY __key__";
    if (limit > 0) {
      query += " LIMIT @Limit";
    }
    query += " OFFSET @Offset";
    GqlQuery.Builder<Key> gqlQueryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, query);
    if (limit > 0) {
      gqlQueryBuilder.setBinding("Limit", limit);
    }
    gqlQueryBuilder.setBinding("Offset", Cursor.fromUrlSafe(fromCursor.getEncoded()));
    GqlQuery<Key> gqlQuery = gqlQueryBuilder.build();
    Datastore datastore = entityManager.getDatastore();
    QueryResults<Key> results = datastore.run(gqlQuery);
    DefaultQueryResponse<String> response = new DefaultQueryResponse<>();
    List<String> namespaces = new ArrayList<>(Math.max(limit, 50));
    response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    while (results.hasNext()) {
      Key key = results.next();
      String name = key.getName();
      namespaces.add(name == null ? "" : name);
    }
    response.setResults(namespaces);
    response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    return response;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example 6
Source File: ConceptsTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropertyFilteringRunQuery() {
  setUpQueryTests();
  // [START datastore_property_filtering_run_query]
  Key startKey = datastore.newKeyFactory()
      .setKind("__property__")
      .addAncestors(PathElement.of("__kind__", "Task"))
      .newKey("priority");
  Query<Key> query = Query.newKeyQueryBuilder()
      .setKind("__property__")
      .setFilter(PropertyFilter.ge("__key__", startKey))
      .build();
  Map<String, Collection<String>> propertiesByKind = new HashMap<>();
  QueryResults<Key> keys = datastore.run(query);
  while (keys.hasNext()) {
    Key key = keys.next();
    String kind = key.getParent().getName();
    String propertyName = key.getName();
    Collection<String> properties = propertiesByKind.get(kind);
    if (properties == null) {
      properties = new HashSet<String>();
      propertiesByKind.put(kind, properties);
    }
    properties.add(propertyName);
  }
  // [END datastore_property_filtering_run_query]
  Map<String, ImmutableSet<String>> expected =
      ImmutableMap.of("Task", ImmutableSet.of("priority", "tag"));
  assertEquals(expected, propertiesByKind);
}
 
Example 7
Source File: DatastoreTemplate.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
public static PathElement keyToPathElement(Key key) {
	Assert.notNull(key, "A non-null key is required");
	return (key.getName() != null)
			? PathElement.of(key.getKind(), key.getName())
			: PathElement.of(key.getKind(), key.getId());
}
 
Example 8
Source File: ITDatastoreSnippets.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
private String registerKey(String keyName, String kind) {
  Key key = datastore.newKeyFactory().setKind(kind).newKey(keyName);
  registeredKeys.add(key);
  return key.getName();
}
 
Example 9
Source File: ITTransactionSnippets.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
private String registerKey(Key key) {
  registeredKeys.add(key);
  return key.getName();
}
 
Example 10
Source File: ITTransactionSnippets.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
private String registerKey(String keyName, String kind) {
  Key key = datastore.newKeyFactory().setKind(kind).newKey(keyName);
  registeredKeys.add(key);
  return key.getName();
}