Java Code Examples for com.google.cloud.datastore.KeyFactory

The following examples show how to use com.google.cloud.datastore.KeyFactory. These examples are extracted from open source projects. 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
private Entity getShardCounter(final String location) {
  KeyFactory keyFactory = datastore.newKeyFactory().addAncestors(
      NXRM_ROOT,
      PathElement.of(METRICS_STORE, 1L)
  );
  Key key = keyFactory.setNamespace(namespace)
      .setKind(SHARD).newKey(location);
  Entity exists = datastore.get(key);
  if (exists != null) {
    log.trace("counter for {} already present", location);
    return exists;
  }

  log.debug("creating metrics store counter shard for {}", location);
  // otherwise make it
  Entity entity = Entity.newBuilder(key)
      .set(SIZE, LongValue.newBuilder(0L).build())
      .set(COUNT, LongValue.newBuilder(0L).build())
      .build();

  return datastore.put(entity);
}
 
Example 2
@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 3
Source Project: java-docs-samples   Source File: ConceptsTest.java    License: 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 4
Source Project: tomcat-runtime   Source File: DatastoreStore.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Save the specified Session into this Store. Any previously saved information for
 * the associated session identifier is replaced.
 *
 * <p>Attempt to serialize the session and send it to the datastore.</p>
 *
 * @throws IOException If an error occurs during the serialization of the session.
 *
 * @param session Session to be saved
 */
@Override
public void save(Session session) throws IOException {
  log.debug("Persisting session: " + session.getId());

  if (!(session instanceof DatastoreSession)) {
    throw new IOException(
        "The session must be an instance of DatastoreSession to be serialized");
  }
  DatastoreSession datastoreSession = (DatastoreSession) session;
  Key sessionKey = newKey(session.getId());
  KeyFactory attributeKeyFactory = datastore.newKeyFactory()
      .setKind(sessionKind)
      .addAncestor(PathElement.of(sessionKind, sessionKey.getName()));

  List<Entity> entities = serializeSession(datastoreSession, sessionKey, attributeKeyFactory);

  TraceContext datastoreSaveContext = startSpan("Storing the session in the Datastore");
  datastore.put(entities.toArray(new FullEntity[0]));
  datastore.delete(datastoreSession.getSuppressedAttributes().stream()
      .map(attributeKeyFactory::newKey)
      .toArray(Key[]::new));
  endSpan(datastoreSaveContext);
}
 
Example 5
Source Project: tomcat-runtime   Source File: DatastoreSession.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Serialize an attribute an embed it into an entity whose key is generated by the provided
 * KeyFactory.
 * @param attributeKeyFactory The KeyFactory to use to create the key for the entity.
 * @param name The name of the attribute to serialize.
 * @return An Entity containing the serialized attribute.
 */
private Entity serializeAttribute(KeyFactory attributeKeyFactory, String name) {
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
    oos.writeObject(getAttribute(name));
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }

  return Entity.newBuilder(attributeKeyFactory.newKey(name))
      .set(SessionMetadata.ATTRIBUTE_VALUE_NAME,
          BlobValue.newBuilder(Blob.copyFrom(bos.toByteArray()))
              .setExcludeFromIndexes(true)
              .build())
      .build();
}
 
Example 6
Source Project: tomcat-runtime   Source File: DatastoreSessionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAttributesSerializationKey() throws Exception {
  DatastoreSession session = new DatastoreSession(sessionManager);
  session.setValid(true);
  session.setAttribute("count", 2);
  session.setAttribute("map", new HashMap<>());

  KeyFactory factory = new KeyFactory("project").setKind("kind");
  List<Entity> entities = session.saveAttributesToEntity(factory);

  assertTrue(entities.stream()
      .map(BaseEntity::getKey)
      .map(Key::getName)
      .collect(Collectors.toSet())
      .containsAll(Arrays.asList("count", "map")));
}
 
Example 7
Source Project: tomcat-runtime   Source File: DatastoreSessionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializationCycle() throws Exception {
  DatastoreSession initialSession = new DatastoreSession(sessionManager);
  initialSession.setValid(true);
  initialSession.setAttribute("count", 5);
  initialSession.setAttribute("map", Collections.singletonMap("key", "value"));

  KeyFactory keyFactory = new KeyFactory("project").setKind("kind");
  List<Entity> attributes = initialSession.saveToEntities(sessionKey, keyFactory);

  DatastoreSession restoredSession = new DatastoreSession(sessionManager);
  restoredSession.restoreFromEntities(sessionKey, attributes);

  assertTrue(restoredSession.getAttribute("count") != null);
  assertTrue(restoredSession.getAttribute("map") != null);

  assertEquals(5, restoredSession.getAttribute("count"));
  assertEquals("value", ((Map)restoredSession.getAttribute("map")).get("key"));
}
 
Example 8
Source Project: tomcat-runtime   Source File: DatastoreStoreTest.java    License: 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 9
Source Project: google-cloud-java   Source File: DatastoreSnippets.java    License: 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 10
Source Project: google-cloud-java   Source File: DatastoreSnippets.java    License: 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 11
Source Project: google-cloud-java   Source File: TransactionSnippets.java    License: 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 12
Source Project: google-cloud-java   Source File: TransactionSnippets.java    License: 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 13
Source Project: google-cloud-java   Source File: TransactionSnippets.java    License: 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 14
Source Project: google-cloud-java   Source File: TransactionSnippets.java    License: Apache License 2.0 6 votes vote down vote up
/** Example of committing a transaction. */
// [TARGET commit()]
public Key commit() {
  Datastore datastore = transaction.getDatastore();
  // [START commit]
  // create an entity
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
  Key key = datastore.allocateId(keyFactory.newKey());
  Entity entity = Entity.newBuilder(key).set("description", "commit()").build();

  // add the entity and commit
  try {
    transaction.put(entity);
    transaction.commit();
  } catch (DatastoreException ex) {
    // handle exception
  }
  // [END commit]

  return key;
}
 
Example 15
Source Project: google-cloud-java   Source File: TransactionSnippets.java    License: Apache License 2.0 6 votes vote down vote up
/** Example of rolling back a transaction. */
// [TARGET rollback()]
public Key rollback() {
  Datastore datastore = transaction.getDatastore();
  // [START rollback]
  // create an entity
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
  Key key = datastore.allocateId(keyFactory.newKey());
  Entity entity = Entity.newBuilder(key).set("description", "rollback()").build();

  // add the entity and rollback
  transaction.put(entity);
  transaction.rollback();
  // calling transaction.commit() now would fail
  // [END rollback]
  return key;
}
 
Example 16
Source Project: google-cloud-java   Source File: TransactionSnippets.java    License: Apache License 2.0 6 votes vote down vote up
/** Example of verifying if a transaction is active. */
// [TARGET active()]
public Key active() {
  Datastore datastore = transaction.getDatastore();
  // [START active]
  // create an entity
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
  Key key = datastore.allocateId(keyFactory.newKey());
  Entity entity = Entity.newBuilder(key).set("description", "active()").build();
  // calling transaction.active() now would return true
  try {
    // add the entity and commit
    transaction.put(entity);
    transaction.commit();
  } finally {
    // if committing succeeded
    // then transaction.isActive() will be false
    if (transaction.isActive()) {
      // otherwise it's true and we need to rollback
      transaction.rollback();
    }
  }
  // [END active]
  return key;
}
 
Example 17
Source Project: google-cloud-java   Source File: TransactionSnippets.java    License: Apache License 2.0 6 votes vote down vote up
/** Example of verifying if a transaction is active. */
// [TARGET isActive()]
public Key isActive() {
  Datastore datastore = transaction.getDatastore();
  // [START isActive]
  // create an entity
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
  Key key = datastore.allocateId(keyFactory.newKey());
  Entity entity = Entity.newBuilder(key).set("description", "active()").build();
  // calling transaction.active() now would return true
  try {
    // add the entity and commit
    transaction.put(entity);
    transaction.commit();
  } finally {
    // if committing succeeded
    // then transaction.active() will be false
    if (transaction.isActive()) {
      // otherwise it's true and we need to rollback
      transaction.rollback();
    }
  }
  // [END isActive]
  return key;
}
 
Example 18
@Override
public Key allocateKeyForObject(Object entity,
		DatastorePersistentEntity datastorePersistentEntity, Key... ancestors) {
	Assert.notNull(entity, "Cannot get key for null entity object.");
	Assert.notNull(datastorePersistentEntity, "Persistent entity must not be null.");
	PersistentProperty idProp = datastorePersistentEntity.getIdPropertyOrFail();

	Class idPropType = idProp.getType();

	if (!idPropType.equals(Key.class) && !idPropType.equals(Long.class)) {
		throw new DatastoreDataException("Cloud Datastore can only allocate IDs for Long and Key properties. " +
				"Cannot allocate for type: " + idPropType);
	}

	KeyFactory keyFactory = getKeyFactory().setKind(datastorePersistentEntity.kindName());
	if (ancestors != null && ancestors.length > 0) {
		if (!idPropType.equals(Key.class)) {
			throw new DatastoreDataException("Only Key types are allowed for descendants id");
		}
		for (Key ancestor : ancestors) {
			keyFactory.addAncestor(DatastoreTemplate.keyToPathElement(ancestor));
		}
	}
	Key allocatedKey = this.datastore.get().allocateId(keyFactory.newKey());

	Object value;
	if (idPropType.equals(Key.class)) {
		value = allocatedKey;
	}
	else if (idPropType.equals(Long.class)) {
		value = allocatedKey.getId();
	}
	else {
		value = allocatedKey.getId().toString();
	}

	datastorePersistentEntity.getPropertyAccessor(entity).setProperty(idProp, value);
	return allocatedKey;
}
 
Example 19
@Test
public void getKeyFromIdExceptionTest() {
	this.expectedEx.expect(DatastoreDataException.class);
	this.expectedEx.expectMessage("Keys can only be created using String or long values.");
	when(this.datastore.newKeyFactory()).thenReturn(new KeyFactory("p").setKind("k"));
	this.datastoreServiceObjectToKeyFactory.getKeyFromId(true, "custom_test_kind");
}
 
Example 20
@Test
public void getKeyTest() {
	when(this.datastore.newKeyFactory()).thenReturn(new KeyFactory("p").setKind("k"));
	TestEntityWithId testEntity = new TestEntityWithId();
	testEntity.id = 1L;

	Key actual = this.datastoreServiceObjectToKeyFactory.getKeyFromObject(
			testEntity, this.datastoreMappingContext.getPersistentEntity(TestEntityWithId.class));
	Key expectedKey = new KeyFactory("p").setKind("custom_test_kind").newKey(1L);

	assertThat(actual).isEqualTo(expectedKey);
}
 
Example 21
@Test
public void allocateIdForObjectTest() {
	TestEntityWithKeyId testEntityWithKeyId = new TestEntityWithKeyId();

	doAnswer((invocation) -> {
		IncompleteKey incompleteKey = (IncompleteKey) invocation.getArguments()[0];
		long id = 123L;
		if (incompleteKey.getAncestors().size() > 0) {
			id = 456L;
		}
		return Key.newBuilder(incompleteKey, id).build();
	}).when(this.datastore).allocateId((IncompleteKey) any());

	when(this.datastore.newKeyFactory()).thenReturn(new KeyFactory("project"));
	Key allocatedKey = this.datastoreServiceObjectToKeyFactory
			.allocateKeyForObject(testEntityWithKeyId, this.datastoreMappingContext
					.getPersistentEntity(testEntityWithKeyId.getClass()));
	Key key = new KeyFactory("project").setKind("custom_test_kind").newKey(123L);
	assertThat(allocatedKey).isEqualTo(key);
	assertThat(testEntityWithKeyId.id).isEqualTo(key);

	Key allocatedKeyWithAncestor = this.datastoreServiceObjectToKeyFactory
			.allocateKeyForObject(testEntityWithKeyId, this.datastoreMappingContext
					.getPersistentEntity(testEntityWithKeyId.getClass()), allocatedKey);
	Key keyWithAncestor = new KeyFactory("project").setKind("custom_test_kind")
			.addAncestor(PathElement.of(key.getKind(), key.getId()))
			.newKey(456L);
	assertThat(allocatedKeyWithAncestor).isEqualTo(keyWithAncestor);
	assertThat(testEntityWithKeyId.id).isEqualTo(keyWithAncestor);
}
 
Example 22
@Test
public void allocateIdForObjectNonKeyIdTest() {
	this.expectedEx.expect(DatastoreDataException.class);
	this.expectedEx.expectMessage("Only Key types are allowed for descendants id");

	TestEntityWithId testEntityWithId = new TestEntityWithId();
	KeyFactory keyFactory = new KeyFactory("project").setKind("kind");
	when(this.datastore.newKeyFactory()).thenReturn(keyFactory);
	this.datastoreServiceObjectToKeyFactory
			.allocateKeyForObject(testEntityWithId, this.datastoreMappingContext
					.getPersistentEntity(testEntityWithId.getClass()),
					keyFactory.newKey("ancestor"));
}
 
Example 23
@Test
public void allocateIdForObjectUnsupportedKeyTypeIdTest() {
	this.expectedEx.expect(DatastoreDataException.class);
	this.expectedEx.expectMessage("Cloud Datastore can only allocate IDs for Long and Key properties. " +
			"Cannot allocate for type: class java.lang.String");

	TestEntityWithStringId testEntityWithStringId = new TestEntityWithStringId();
	KeyFactory keyFactory = new KeyFactory("project").setKind("kind");
	when(this.datastore.newKeyFactory()).thenReturn(keyFactory);
	this.datastoreServiceObjectToKeyFactory
			.allocateKeyForObject(testEntityWithStringId, this.datastoreMappingContext
					.getPersistentEntity(testEntityWithStringId.getClass()),
					keyFactory.newKey("key"));
}
 
Example 24
Source Project: catatumbo   Source File: DefaultDatastoreReader.java    License: 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 25
Source Project: catatumbo   Source File: DefaultDatastoreReader.java    License: 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 26
Source Project: catatumbo   Source File: DefaultEntityManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates and returns a new native KeyFactory. If a namespace was specified using {@link Tenant},
 * the returned KeyFactory will have the specified namespace.
 * 
 * @return a {@link KeyFactory}
 */
KeyFactory newNativeKeyFactory() {
  KeyFactory keyFactory = datastore.newKeyFactory();
  String namespace = Tenant.getNamespace();
  if (namespace != null) {
    keyFactory.setNamespace(namespace);
  }
  return keyFactory;
}
 
Example 27
Source Project: styx   Source File: DatastoreStorageTransaction.java    License: Apache License 2.0 5 votes vote down vote up
private WorkflowId storeWorkflow(Workflow workflow, WorkflowState state, Optional<Entity> existing)
    throws IOException {
  final Supplier<KeyFactory> keyFactory = tx.getDatastore()::newKeyFactory;

  var key = workflowKey(keyFactory, workflow.id());
  var entity = DatastoreStorage.workflowToEntity(workflow, state, existing, key);
  tx.put(entity);

  return workflow.id();
}
 
Example 28
Source Project: styx   Source File: DatastoreStorage.java    License: Apache License 2.0 5 votes vote down vote up
static Entity runStateToEntity(KeyFactory keyFactory, WorkflowInstance wfi, RunState state)
    throws JsonProcessingException {
  final Key key = activeWorkflowInstanceKey(keyFactory, wfi);
  final Entity.Builder entity = Entity.newBuilder(key)
      .set(PROPERTY_COMPONENT, wfi.workflowId().componentId())
      .set(PROPERTY_WORKFLOW, wfi.workflowId().id())
      .set(PROPERTY_PARAMETER, wfi.parameter())
      .set(PROPERTY_COUNTER, state.counter());

  entity
      .set(PROPERTY_STATE, state.state().toString())
      .set(PROPERTY_STATE_TIMESTAMP, state.timestamp())
      .set(PROPERTY_STATE_TRIES, state.data().tries())
      .set(PROPERTY_STATE_CONSECUTIVE_FAILURES, state.data().consecutiveFailures())
      .set(PROPERTY_STATE_RETRY_COST, state.data().retryCost())
      // TODO: consider making this list bounded or not storing it here to avoid exceeding entity size limit
      .set(PROPERTY_STATE_MESSAGES, jsonValue(state.data().messages()));

  state.data().retryDelayMillis().ifPresent(v -> entity.set(PROPERTY_STATE_RETRY_DELAY_MILLIS, v));
  state.data().lastExit().ifPresent(v -> entity.set(PROPERTY_STATE_LAST_EXIT, v));
  state.data().trigger().ifPresent(trigger -> {
    entity.set(PROPERTY_STATE_TRIGGER_TYPE, TriggerUtil.triggerType(trigger));
    entity.set(PROPERTY_STATE_TRIGGER_ID, TriggerUtil.triggerId(trigger));
  });
  state.data().executionId().ifPresent(v -> entity.set(PROPERTY_STATE_EXECUTION_ID, v));
  state.data().runnerId().ifPresent(v -> entity.set(PROPERTY_STATE_RUNNER_ID, v));
  if (state.data().triggerParameters().isPresent()) {
    entity.set(PROPERTY_STATE_TRIGGER_PARAMETERS, jsonValue(state.data().triggerParameters().get()));
  }

  if (state.data().executionDescription().isPresent()) {
    entity.set(PROPERTY_STATE_EXECUTION_DESCRIPTION, jsonValue(state.data().executionDescription().get()));
  }
  if (state.data().resourceIds().isPresent()) {
    entity.set(PROPERTY_STATE_RESOURCE_IDS, jsonValue(state.data().resourceIds().get()));
  }

  return entity.build();
}
 
Example 29
Source Project: java-docs-samples   Source File: ConceptsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIncompleteKey() {
  // [START datastore_incomplete_key]
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("Task");
  Key taskKey = datastore.allocateId(keyFactory.newKey());
  // [END datastore_incomplete_key]
  assertValidKey(taskKey);
}
 
Example 30
Source Project: java-docs-samples   Source File: ConceptsTest.java    License: 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);
}