Java Code Examples for com.google.cloud.datastore.KeyFactory#newKey()

The following examples show how to use com.google.cloud.datastore.KeyFactory#newKey() . 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: TransactionSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of running a query to find all entities with an ancestor. */
// [TARGET run(Query)]
// [VARIABLE "my_parent_key_name"]
public List<Entity> run(String parentKeyName) {
  Datastore datastore = transaction.getDatastore();
  // [START run]
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("ParentKind");
  Key parentKey = keyFactory.newKey(parentKeyName);
  // Build a query
  Query<Entity> query =
      Query.newEntityQueryBuilder()
          .setKind("MyKind")
          .setFilter(PropertyFilter.hasAncestor(parentKey))
          .build();
  QueryResults<Entity> results = transaction.run(query);
  List<Entity> entities = Lists.newArrayList();
  while (results.hasNext()) {
    Entity result = results.next();
    // do something with result
    entities.add(result);
  }
  transaction.commit();
  // [END run]
  return entities;
}
 
Example 2
Source File: TransactionSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of fetching a list of entities for several keys. */
// [TARGET fetch(Key...)]
// [VARIABLE "my_first_key_name"]
// [VARIABLE "my_second_key_name"]
public List<Entity> fetchEntitiesWithKeys(String firstKeyName, String secondKeyName) {
  Datastore datastore = transaction.getDatastore();
  // [START fetchEntitiesWithKeys]
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
  Key firstKey = keyFactory.newKey(firstKeyName);
  Key secondKey = keyFactory.newKey(secondKeyName);
  List<Entity> entities = transaction.fetch(firstKey, secondKey);
  for (Entity entity : entities) {
    // do something with the entity
  }
  transaction.commit();
  // [END fetchEntitiesWithKeys]
  return entities;
}
 
Example 3
Source File: TransactionSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of getting entities for several keys. */
// [TARGET get(Key...)]
// [VARIABLE "my_first_key_name"]
// [VARIABLE "my_second_key_name"]
public List<Entity> getMultiple(String firstKeyName, String secondKeyName) {
  Datastore datastore = transaction.getDatastore();
  // TODO change so that it's not necessary to hold the entities in a list for integration testing
  // [START getMultiple]
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
  Key firstKey = keyFactory.newKey(firstKeyName);
  Key secondKey = keyFactory.newKey(secondKeyName);
  Iterator<Entity> entitiesIterator = transaction.get(firstKey, secondKey);
  List<Entity> entities = Lists.newArrayList();
  while (entitiesIterator.hasNext()) {
    Entity entity = entitiesIterator.next();
    // do something with the entity
    entities.add(entity);
  }
  transaction.commit();
  // [END getMultiple]
  return entities;
}
 
Example 4
Source File: DatastoreSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of fetching a list of Entity objects. */
// [TARGET fetch(Iterable, ReadOption...)]
// [VARIABLE "my_first_key_name"]
// [VARIABLE "my_second_key_name"]
public List<Entity> fetchEntitiesWithKeys(String firstKeyName, String secondKeyName) {
  // [START fetchEntitiesWithKeys]
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
  Key firstKey = keyFactory.newKey(firstKeyName);
  Key secondKey = keyFactory.newKey(secondKeyName);
  List<Entity> entities = datastore.fetch(Lists.newArrayList(firstKey, secondKey));
  for (Entity entity : entities) {
    // do something with the entity
  }
  // [END fetchEntitiesWithKeys]
  return entities;
}
 
Example 5
Source File: ConceptsTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void testNamespaceRunQuery() {
  setUpQueryTests();
  // [START datastore_namespace_run_query]
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("__namespace__");
  Key startNamespace = keyFactory.newKey("g");
  Key endNamespace = keyFactory.newKey("h");
  Query<Key> query = Query.newKeyQueryBuilder()
      .setKind("__namespace__")
      .setFilter(CompositeFilter.and(
          PropertyFilter.gt("__key__", startNamespace),
          PropertyFilter.lt("__key__", endNamespace)))
      .build();
  List<String> namespaces = new ArrayList<>();
  QueryResults<Key> results = datastore.run(query);
  while (results.hasNext()) {
    namespaces.add(results.next().getName());
  }
  // [END datastore_namespace_run_query]
  assertEquals(ImmutableList.of("ghijklmnop"), namespaces);
}
 
Example 6
Source File: DatastoreStoreTest.java    From tomcat-runtime with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  store = new DatastoreStore();
  KeyFactory keyFactory = new KeyFactory("project").setKind("kind");
  key = keyFactory.newKey(keyId);
  attributeKey = keyFactory.newKey("attribute");
  QueryResults<Key> keyQueryResults = new IteratorQueryResults<>(ImmutableList.of(key).iterator());

  when(datastore.newKeyFactory()).thenAnswer((invocation) -> new KeyFactory("project"));
  when(datastore.run(any(KeyQuery.class))).thenReturn(keyQueryResults);

  when(manager.getContext()).thenReturn(new StandardContext());
  when(manager.willAttributeDistribute(anyString(), any())).thenReturn(true);
  when(manager.createEmptySession()).thenReturn(new DatastoreSession(manager));

  store.setDatastore(datastore);
  store.setClock(clock);
  store.setSessionKind("kind");
  store.setManager(manager);
}
 
Example 7
Source File: DatastoreSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of getting multiple entity objects. */
// [TARGET get(Iterable, ReadOption...)]
// [VARIABLE "my_first_key_name"]
// [VARIABLE "my_second_key_name"]
public List<Entity> getEntitiesWithKeys(String firstKeyName, String secondKeyName) {
  // TODO change so that it's not necessary to hold the entities in a list for integration testing
  // [START getEntitiesWithKeys]
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
  Key firstKey = keyFactory.newKey(firstKeyName);
  Key secondKey = keyFactory.newKey(secondKeyName);
  Iterator<Entity> entitiesIterator = datastore.get(Lists.newArrayList(firstKey, secondKey));
  List<Entity> entities = Lists.newArrayList();
  while (entitiesIterator.hasNext()) {
    Entity entity = entitiesIterator.next();
    // do something with the entity
    entities.add(entity);
  }
  // [END getEntitiesWithKeys]
  return entities;
}
 
Example 8
Source File: DatastoreServiceObjectToKeyFactory.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Override
public Key getKeyFromId(Object id, String kindName) {
	Assert.notNull(id, "Cannot get key for null ID value.");
	if (id instanceof Key) {
		return (Key) id;
	}
	KeyFactory keyFactory = getKeyFactory();
	keyFactory.setKind(kindName);
	Key key;
	if (id instanceof String) {
		key = keyFactory.newKey((String) id);
	}
	else if (id instanceof Long) {
		key = keyFactory.newKey((long) id);
	}
	else {
		// We will use configurable custom converters to try to convert other types to
		// String or long
		// in the future.
		throw new DatastoreDataException(
				"Keys can only be created using String or long values.");
	}
	return key;
}
 
Example 9
Source File: DatastoreSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/** Example of allocating an id. */
// [TARGET allocateId(IncompleteKey)]
public Key allocateIdSingle() {
  // [START allocateIdSingle]
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
  IncompleteKey incompleteKey = keyFactory.newKey();

  // let cloud datastore automatically assign an id
  Key key = datastore.allocateId(incompleteKey);
  // [END allocateIdSingle]
  return key;
}
 
Example 10
Source File: CreateEntity.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) {
  Datastore datastore = DatastoreOptions.getDefaultInstance().getService();
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind");
  Key key = keyFactory.newKey("keyName");
  Entity entity =
      Entity.newBuilder(key)
          .set("name", "John Doe")
          .set("age", 30)
          .set("access_time", Timestamp.now())
          .build();
  datastore.put(entity);
}
 
Example 11
Source File: DatastoreSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/** Example of allocating multiple ids in a single batch. */
// [TARGET allocateId(IncompleteKey...)]
public List<Key> batchAllocateId() {
  // [START batchAllocateId]
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
  IncompleteKey incompleteKey1 = keyFactory.newKey();
  IncompleteKey incompleteKey2 = keyFactory.newKey();

  // let cloud datastore automatically assign the ids
  List<Key> keys = datastore.allocateId(incompleteKey1, incompleteKey2);
  // [END batchAllocateId]
  return keys;
}
 
Example 12
Source File: UpdateEntity.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 13
Source File: ConceptsTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private List<Key> setUpTransferTests() {
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("People");
  Key from = keyFactory.newKey("from");
  Key to = keyFactory.newKey("to");
  datastore.put(Entity.newBuilder(from).set("balance", 100).build());
  datastore.put(Entity.newBuilder(to).set("balance", 0).build());
  return ImmutableList.of(from, to);
}
 
Example 14
Source File: ConceptsTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testKeyWithMultilevelParent() {
  // [START datastore_key_with_multilevel_parent]
  KeyFactory keyFactory = datastore.newKeyFactory()
      .addAncestors(PathElement.of("User", "Alice"), PathElement.of("TaskList", "default"))
      .setKind("Task");
  Key taskKey = keyFactory.newKey("sampleTask");
  // [END datastore_key_with_multilevel_parent]
  assertValidKey(taskKey);
}
 
Example 15
Source File: DefaultDatastoreReader.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the given list of identifiers into an array of native Key objects.
 * 
 * @param entityClass
 *          the entity class to which these identifiers belong to.
 * @param identifiers
 *          the list of identifiers to convert.
 * @return an array of Key objects
 */
private Key[] stringListToNativeKeys(Class<?> entityClass, List<String> identifiers) {
  if (identifiers == null || identifiers.isEmpty()) {
    return new Key[0];
  }
  EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass);
  Key[] nativeKeys = new Key[identifiers.size()];
  KeyFactory keyFactory = entityManager.newNativeKeyFactory();
  keyFactory.setKind(entityMetadata.getKind());
  for (int i = 0; i < identifiers.size(); i++) {
    String id = identifiers.get(i);
    nativeKeys[i] = keyFactory.newKey(id);
  }
  return nativeKeys;
}
 
Example 16
Source File: DefaultDatastoreReader.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the given list of identifiers into an array of native Key objects.
 * 
 * @param entityClass
 *          the entity class to which these identifiers belong to.
 * @param identifiers
 *          the list of identifiers to convert.
 * @return an array of Key objects
 */
private Key[] longListToNativeKeys(Class<?> entityClass, List<Long> identifiers) {
  if (identifiers == null || identifiers.isEmpty()) {
    return new Key[0];
  }
  EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass);
  Key[] nativeKeys = new Key[identifiers.size()];
  KeyFactory keyFactory = entityManager.newNativeKeyFactory();
  keyFactory.setKind(entityMetadata.getKind());
  for (int i = 0; i < identifiers.size(); i++) {
    long id = identifiers.get(i);
    nativeKeys[i] = keyFactory.newKey(id);
  }
  return nativeKeys;
}
 
Example 17
Source File: AddEntitiesAndRunQuery.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
public static void main(String... args) {
  // Create datastore service object.
  // By default, credentials are inferred from the runtime environment.
  Datastore datastore = DatastoreOptions.getDefaultInstance().getService();

  // Add an entity to Datastore
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("Person");
  Key key = keyFactory.newKey("[email protected]");
  Entity entity =
      Entity.newBuilder(key)
          .set("name", "John Doe")
          .set("age", 51)
          .set("favorite_food", "pizza")
          .build();
  datastore.put(entity);

  // Get an entity from Datastore
  Entity johnEntity = datastore.get(key);

  // Add a couple more entities to make the query results more interesting
  Key janeKey = keyFactory.newKey("[email protected]");
  Entity janeEntity =
      Entity.newBuilder(janeKey)
          .set("name", "Jane Doe")
          .set("age", 44)
          .set("favorite_food", "pizza")
          .build();
  Key joeKey = keyFactory.newKey("[email protected]");
  Entity joeEntity =
      Entity.newBuilder(joeKey)
          .set("name", "Joe Shmoe")
          .set("age", 27)
          .set("favorite_food", "sushi")
          .build();
  datastore.put(janeEntity, joeEntity);

  // Run a query
  Query<Entity> query =
      Query.newEntityQueryBuilder()
          .setKind("Person")
          .setFilter(PropertyFilter.eq("favorite_food", "pizza"))
          .build();
  QueryResults<Entity> results = datastore.run(query);
  while (results.hasNext()) {
    Entity currentEntity = results.next();
    System.out.println(currentEntity.getString("name") + ", you're invited to a pizza party!");
  }
}
 
Example 18
Source File: GqlDatastoreQueryTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void compoundNameConventionTest() {

	String gql = "SELECT * FROM "
			+ "|org.springframework.cloud.gcp.data.datastore."
			+ "repository.query.GqlDatastoreQueryTests$Trade|"
			+ " WHERE price=:#{#tag6 * -1} AND price<>:#{#tag6 * -1} OR "
			+ "price<>:#{#tag7 * -1} AND " + "( action=@tag0 AND ticker=@tag1 ) OR "
			+ "( trader_id=@tag2 AND price<@tag3 ) OR ( price>=@tag4 AND id<>NULL AND "
			+ "trader_id=NULL AND trader_id LIKE %@tag5 AND price=TRUE AND price=FALSE AND "
			+ "price>@tag6 AND price<=@tag7 AND trade_ref = @tag8) ORDER BY id DESC LIMIT 3;";

	String entityResolvedGql = "SELECT * FROM trades"
			+ " WHERE price=@SpELtag1 AND price<>@SpELtag2 OR price<>@SpELtag3 AND "
			+ "( action=@tag0 AND ticker=@tag1 ) OR "
			+ "( trader_id=@tag2 AND price<@tag3 ) OR ( price>=@tag4 AND id<>NULL AND "
			+ "trader_id=NULL AND trader_id LIKE %@tag5 AND price=TRUE AND price=FALSE AND "
			+ "price>@tag6 AND price<=@tag7 AND trade_ref = @tag8) ORDER BY id DESC LIMIT 3";


	Trade trade = new Trade();
	trade.id = "tradeId1";

	Object[] paramVals = new Object[] { "BUY", "abcd",
			// this is an array param of the non-natively supported type and will need conversion
			new int[] { 1, 2 },
			new double[] { 8.88, 9.99 },
			3, // this parameter is a simple int, which is not a directly supported type and uses
				// conversions
			"blahblah", 1.11, 2.22, trade };

	String[] paramNames = new String[] { "tag0", "tag1", "tag2", "tag3", "tag4",
			"tag5", "tag6", "tag7", "tag8" };

	buildParameters(paramVals, paramNames);

	KeyFactory keyFactory = new KeyFactory("proj");
	keyFactory.setKind("kind");
	Key key = keyFactory.newKey("tradeid1-key");

	doReturn(key).when(this.datastoreTemplate).getKey(any());

	EvaluationContext evaluationContext = new StandardEvaluationContext();
	for (int i = 0; i < paramVals.length; i++) {
		evaluationContext.setVariable(paramNames[i], paramVals[i]);
	}
	when(this.evaluationContextProvider.getEvaluationContext(any(), any()))
			.thenReturn(evaluationContext);

	GqlDatastoreQuery gqlDatastoreQuery = createQuery(gql, false, false);

	doAnswer((invocation) -> {
		GqlQuery statement = invocation.getArgument(0);

		assertThat(statement.getQueryString()).isEqualTo(entityResolvedGql);

		Map<String, Value> paramMap = statement.getNamedBindings();

		assertThat(paramMap.get("tag0").get()).isEqualTo(paramVals[0]);
		assertThat(paramMap.get("tag1").get()).isEqualTo(paramVals[1]);

		// custom conversion is expected to have been used in this param
		assertThat((long) ((LongValue) (((List) paramMap.get("tag2").get()).get(0))).get()).isEqualTo(1L);
		assertThat((long) ((LongValue) (((List) paramMap.get("tag2").get()).get(1))).get()).isEqualTo(2L);

		double actual = ((DoubleValue) (((List) paramMap.get("tag3").get()).get(0))).get();
		assertThat(actual).isEqualTo(((double[]) paramVals[3])[0], DELTA);

		actual = ((DoubleValue) (((List) paramMap.get("tag3").get()).get(1))).get();
		assertThat(actual).isEqualTo(((double[]) paramVals[3])[1], DELTA);

		// 3L is expected even though 3 int was the original param due to custom conversions
		assertThat(paramMap.get("tag4").get()).isEqualTo(3L);
		assertThat(paramMap.get("tag5").get()).isEqualTo(paramVals[5]);
		assertThat(paramMap.get("tag6").get()).isEqualTo(paramVals[6]);
		assertThat(paramMap.get("tag7").get()).isEqualTo(paramVals[7]);

		assertThat((double) paramMap.get("SpELtag1").get()).isEqualTo(-1 * (double) paramVals[6],
				DELTA);
		assertThat((double) paramMap.get("SpELtag2").get()).isEqualTo(-1 * (double) paramVals[6],
				DELTA);
		assertThat((double) paramMap.get("SpELtag3").get()).isEqualTo(-1 * (double) paramVals[7],
				DELTA);

		assertThat(((KeyValue) paramMap.get("tag8")).get()).isSameAs(key);

		return null;
	}).when(this.datastoreTemplate).queryKeysOrEntities(any(), eq(Trade.class));

	doReturn(false).when(gqlDatastoreQuery).isNonEntityReturnedType(any());

	gqlDatastoreQuery.execute(paramVals);

	verify(this.datastoreTemplate, times(1))
			.queryKeysOrEntities(any(), eq(Trade.class));
}