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

The following examples show how to use com.google.cloud.datastore.Key. 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
/**
 * Delete a value stored in the project's datastore.
 *
 * @param sessionId Request from which the session is extracted.
 */
protected void deleteSessionVariables(String sessionId, String... varNames) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  try {
    Entity stateEntity = transaction.get(key);
    if (stateEntity != null) {
      Entity.Builder builder = Entity.newBuilder(stateEntity);
      StringBuilder delNames = new StringBuilder();
      for (String varName : varNames) {
        delNames.append(varName + " ");
        builder = builder.remove(varName);
      }
      datastore.update(builder.build());
    }
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 2
Source Project: data-transfer-project   Source File: GoogleJobStore.java    License: 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 3
Source Project: java-docs-samples   Source File: UserService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Updates a user in Cloud Datastore.
 */
public User updateUser(String id, String name, String email) {
  failIfInvalid(name, email);
  Key key = keyFactory.newKey(id);
  Entity entity = datastore.get(key);
  if (entity == null) {
    throw new IllegalArgumentException("No user with id '" + id + "' found");
  } else {
    entity = Entity.newBuilder(entity)
        .set("id", id)
        .set("name", name)
        .set("email", email)
        .build();
    datastore.update(entity);
  }
  return new User(id, name, email);
}
 
Example 4
Source Project: tomcat-runtime   Source File: DatastoreSessionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAttributesDeserialization() throws Exception {
  Entity metadata = mock(Entity.class);
  when(metadata.getBoolean(any())).thenReturn(true);
  when(sessionKey.getName()).thenReturn("count");
  when(metadata.getKey()).thenReturn(sessionKey);
  int count = 5;
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  ObjectOutputStream oos = new ObjectOutputStream(bos);
  oos.writeObject(count);

  Entity valueEntity = Entity.newBuilder(
      (Key)when(mock(Key.class).getName()).thenReturn("count").getMock())
      .set("value", Blob.copyFrom(bos.toByteArray()))
      .build();

  DatastoreSession session = new DatastoreSession(sessionManager);
  session.restoreFromEntities(sessionKey, Arrays.asList(metadata, valueEntity));

  assertEquals(count, session.getAttribute("count"));
}
 
Example 5
Source Project: java-docs-samples   Source File: ConceptsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEntityWithParent() {
  // [START datastore_entity_with_parent]
  Key taskKey = datastore.newKeyFactory()
      .addAncestors(PathElement.of("TaskList", "default"))
      .setKind("Task")
      .newKey("sampleTask");
  Entity task = Entity.newBuilder(taskKey)
      .set("category", "Personal")
      .set("done", false)
      .set("priority", 4)
      .set("description", "Learn Cloud Datastore")
      .build();
  // [END datastore_entity_with_parent]
  assertValidEntity(task);
}
 
Example 6
/**
 * Delete a value stored in the project's datastore.
 * @param sessionId Request from which the session is extracted.
 */
protected void deleteSessionVariables(String sessionId, String... varNames) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  try {
    Entity stateEntity = transaction.get(key);
    if (stateEntity != null) {
      Entity.Builder builder = Entity.newBuilder(stateEntity);
      StringBuilder delNames = new StringBuilder();
      for (String varName : varNames) {
        delNames.append(varName + " ");
        builder = builder.remove(varName);
      }
      datastore.update(builder.build());
    }
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 7
Source Project: google-cloud-java   Source File: DatastoreExample.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run(Transaction tx, Key userKey, String content) {
  Entity user = tx.get(userKey);
  if (user == null) {
    System.out.println("Adding a new user.");
    user = Entity.newBuilder(userKey).set("count", 1).build();
    tx.add(user);
  } else {
    user = Entity.newBuilder(user).set("count", user.getLong("count") + 1L).build();
    tx.update(user);
  }
  IncompleteKey commentKey = IncompleteKey.newBuilder(userKey, COMMENT_KIND).build();
  FullEntity<IncompleteKey> comment =
      FullEntity.newBuilder(commentKey)
          .set("content", content)
          .set("timestamp", Timestamp.now())
          .build();
  tx.addWithDeferredIdAllocation(comment);
  System.out.printf("Adding a comment to user '%s'.%n", userKey.getName());
}
 
Example 8
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 9
Source Project: google-cloud-java   Source File: DatastoreSnippets.java    License: Apache License 2.0 6 votes vote down vote up
/** Example of adding multiple entities. */
// [TARGET add(FullEntity...)]
// [VARIABLE "my_key_name1"]
// [VARIABLE "my_key_name2"]
public void batchAddEntities(String keyName1, String keyName2) {
  // [START batchAddEntities]
  Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
  Entity.Builder entityBuilder1 = Entity.newBuilder(key1);
  entityBuilder1.set("propertyName", "value1");
  Entity entity1 = entityBuilder1.build();

  Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
  Entity.Builder entityBuilder2 = Entity.newBuilder(key2);
  entityBuilder2.set("propertyName", "value2");
  Entity entity2 = entityBuilder2.build();

  try {
    datastore.add(entity1, entity2);
  } catch (DatastoreException ex) {
    if ("ALREADY_EXISTS".equals(ex.getReason())) {
      // at least one of entity1.getKey() and entity2.getKey() already exists
    }
  }
  // [END batchAddEntities]
}
 
Example 10
Source Project: tomcat-runtime   Source File: DatastoreSession.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Store the metadata of the session in an entity.
 * @param sessionKey Identifier of the session on the Datastore
 * @return An entity containing the metadata.
 */
@VisibleForTesting
Entity saveMetadataToEntity(Key sessionKey) {
  Entity.Builder sessionEntity = Entity.newBuilder(sessionKey)
      .set(SessionMetadata.CREATION_TIME, getCreationTime())
      .set(SessionMetadata.LAST_ACCESSED_TIME, getLastAccessedTime())
      .set(SessionMetadata.MAX_INACTIVE_INTERVAL, getMaxInactiveInterval())
      .set(SessionMetadata.IS_NEW, isNew())
      .set(SessionMetadata.IS_VALID, isValid())
      .set(SessionMetadata.THIS_ACCESSED_TIME, getThisAccessedTime());

  // A negative time indicates that the session should never time out
  if (getMaxInactiveInterval() >= 0) {
    sessionEntity.set(SessionMetadata.EXPIRATION_TIME,
        getLastAccessedTime() + getMaxInactiveInterval() * 1000);
  }

  return sessionEntity.build();
}
 
Example 11
Source Project: java-docs-samples   Source File: MessageRepositoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void save(Message message) {
  // Save message to "messages"
  Datastore datastore = getDatastoreInstance();
  Key key = datastore.allocateId(keyFactory.newKey());

  Entity.Builder messageEntityBuilder = Entity.newBuilder(key)
      .set("messageId", message.getMessageId());

  if (message.getData() != null) {
    messageEntityBuilder = messageEntityBuilder.set("data", message.getData());
  }

  if (message.getPublishTime() != null) {
    messageEntityBuilder = messageEntityBuilder.set("publishTime", message.getPublishTime());
  }
  datastore.put(messageEntityBuilder.build());
}
 
Example 12
/**
 * Delete a value stored in the project's datastore.
 *
 * @param sessionId Request from which the session is extracted.
 */
protected void deleteSessionVariables(String sessionId, String... varNames) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  try {
    Entity stateEntity = transaction.get(key);
    if (stateEntity != null) {
      Entity.Builder builder = Entity.newBuilder(stateEntity);
      StringBuilder delNames = new StringBuilder();
      for (String varName : varNames) {
        delNames.append(varName + " ");
        builder = builder.remove(varName);
      }
      datastore.update(builder.build());
    }
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 13
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 14
Source Project: tomcat-runtime   Source File: DatastoreSession.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Restore the attributes and metadata of the session from Datastore Entities.
 *
 * @param entities An iterator of entity, containing the metadata and attributes of the session.
 * @throws ClassNotFoundException The class in attempt to be deserialized is not present in the
 *                                application.
 * @throws IOException Error during the deserialization of the object.
 */
public void restoreFromEntities(Key sessionKey, Iterable<Entity> entities) throws
    ClassNotFoundException, IOException {
  Entity metadataEntity = null;
  List<Entity> attributeEntities = new LinkedList<>();
  for (Entity entity : entities) {
    if (entity.getKey().equals(sessionKey)) {
      metadataEntity = entity;
    } else {
      attributeEntities.add(entity);
    }
  }

  if (metadataEntity == null) {
    throw new IOException("The serialized session is missing the metadata entity");
  }

  restoreMetadataFromEntity(metadataEntity);
  restoreAttributesFromEntity(attributeEntities);
  setId(sessionKey.getName());
  initialAttributes.addAll(Collections.list(getAttributeNames()));
}
 
Example 15
Source Project: google-cloud-java   Source File: DatastoreSnippets.java    License: Apache License 2.0 6 votes vote down vote up
/** Example of updating multiple entities. */
// [TARGET update(Entity...)]
// [VARIABLE "my_key_name_1"]
// [VARIABLE "my_key_name_2"]
public void batchUpdateEntities(String keyName1, String keyName2) {
  // [START batchUpdateEntities]
  Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
  Entity.Builder entityBuilder1 = Entity.newBuilder(key1);
  entityBuilder1.set("propertyName", "updatedValue1");
  Entity entity1 = entityBuilder1.build();

  Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
  Entity.Builder entityBuilder2 = Entity.newBuilder(key2);
  entityBuilder2.set("propertyName", "updatedValue2");
  Entity entity2 = entityBuilder2.build();

  datastore.update(entity1, entity2);
  // [END batchUpdateEntities]
}
 
Example 16
Source Project: google-cloud-java   Source File: TransactionSnippets.java    License: Apache License 2.0 5 votes vote down vote up
/** Example of deleting multiple entities. */
// [TARGET delete(Key...)]
// [VARIABLE "my_key_name1"]
// [VARIABLE "my_key_name2"]
public void multipleDeleteEntities(String keyName1, String keyName2) {
  Datastore datastore = transaction.getDatastore();
  // [START multipleDeleteEntities]
  Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
  Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
  transaction.delete(key1, key2);
  transaction.commit();
  // [END multipleDeleteEntities]
}
 
Example 17
Source Project: google-cloud-java   Source File: TransactionSnippets.java    License: Apache License 2.0 5 votes vote down vote up
/** Example of getting an entity for a given key. */
// [TARGET get(Key)]
// [VARIABLE "my_key_name"]
public Entity get(String keyName) {
  Datastore datastore = transaction.getDatastore();
  // [START get]
  Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
  Entity entity = transaction.get(key);
  transaction.commit();
  // Do something with the entity
  // [END get]
  return entity;
}
 
Example 18
Source Project: java-docs-samples   Source File: UserService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new user and add it to Cloud Datastore.
 */
public User createUser(String name, String email) {
  failIfInvalid(name, email);
  User user = new User(name, email);
  Key key = keyFactory.newKey(user.getId());
  Entity entity = Entity.newBuilder(key)
      .set("id", user.getId())
      .set("name", name)
      .set("email", email)
      .build();
  datastore.add(entity);
  return user;
}
 
Example 19
Source Project: data-transfer-project   Source File: GoogleJobStore.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verifies a {@code PortabilityJob} already exists for {@code jobId}, and updates the entry to
 * {@code job}, within a {@code Transaction}. If {@code validator} is non-null,
 * validator.validate() is called first in the transaction.
 *
 * @throws IOException if a job didn't already exist for {@code jobId} or there was a problem
 *     updating it @throws IllegalStateException if validator.validate() failed
 */
@Override
protected void updateJob(UUID jobId, PortabilityJob job, JobUpdateValidator validator)
    throws IOException {
  Preconditions.checkNotNull(jobId);
  Transaction transaction = datastore.newTransaction();
  Key key = getJobKey(jobId);

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

    if (validator != null) {
      PortabilityJob previousJob = PortabilityJob.fromMap(getProperties(previousEntity));
      validator.validate(previousJob, job);
    }

    Entity newEntity = createUpdatedEntity(key, job.toMap());
    transaction.put(newEntity);
    transaction.commit();
  } catch (Throwable t) {
    transaction.rollback();
    throw new IOException("Failed atomic update of jobId: " + jobId, t);
  }
}
 
Example 20
Source Project: google-cloud-java   Source File: ITTransactionSnippets.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testActive() {
  Transaction transaction = datastore.newTransaction();
  TransactionSnippets transactionSnippets = new TransactionSnippets(transaction);
  Key key = transactionSnippets.active();
  Entity result = datastore.get(key);
  assertNotNull(result);
  datastore.delete(key);
}
 
Example 21
Source Project: catatumbo   Source File: Marshaller.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CompleteKey using the given parameters. The actual ID is generated using
 * <code>UUID.randomUUID().toString()</code>.
 * 
 * @param parent
 *          the parent key, may be <code>null</code>.
 */
private void createCompleteKey(Key parent) {
  String kind = entityMetadata.getKind();
  String id = UUID.randomUUID().toString();
  if (parent == null) {
    key = entityManager.newNativeKeyFactory().setKind(kind).newKey(id);
  } else {
    key = Key.newBuilder(parent, kind, id).build();
  }
}
 
Example 22
Source Project: google-cloud-java   Source File: TransactionSnippets.java    License: Apache License 2.0 5 votes vote down vote up
/** Example of adding a single entity. */
// [TARGET add(FullEntity)]
// [VARIABLE "my_key_name"]
public void addSingleEntity(String keyName) {
  Datastore datastore = transaction.getDatastore();
  // [START addSingleEntity]
  Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
  Entity.Builder entityBuilder = Entity.newBuilder(key);
  entityBuilder.set("propertyName", "value");
  Entity entity = entityBuilder.build();
  transaction.add(entity);
  transaction.commit();
  // [END addSingleEntity]
}
 
Example 23
Source Project: spring-cloud-gcp   Source File: DatastoreTemplateTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void writeMapTest() {
	Map<String, Long> map = new HashMap<>();
	map.put("field1", 1L);
	Key keyForMap = createFakeKey("map1");

	when(this.readWriteConversions.convertOnWriteSingle(eq(1L))).thenReturn(LongValue.of(1L));

	this.datastoreTemplate.writeMap(keyForMap, map);

	Entity datastoreEntity = Entity.newBuilder(keyForMap).set("field1", 1L).build();
	verify(this.datastore, times(1)).put(eq(datastoreEntity));
}
 
Example 24
Source Project: data-transfer-project   Source File: GoogleJobStore.java    License: Apache License 2.0 5 votes vote down vote up
private Key getCountsKey(UUID jobId, String dataType) {
  // Use the main job as the ancestor to all the counts, see:
  // https://cloud.google.com/datastore/docs/concepts/entities#ancestor_paths
  return datastore
      .newKeyFactory()
      .setKind(COUNTS_KIND)
      .addAncestor(PathElement.of(JOB_KIND, jobId.toString()))
      .newKey(dataType);
}
 
Example 25
Source Project: google-cloud-java   Source File: DatastoreSnippets.java    License: Apache License 2.0 5 votes vote down vote up
/** Example of getting an entity. */
// [TARGET get(Key, ReadOption...)]
// [VARIABLE "my_key_name"]
public Entity getEntityWithKey(String keyName) {
  // [START getEntityWithKey]
  Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
  Entity entity = datastore.get(key);
  // Do something with the entity
  // [END getEntityWithKey]
  return entity;
}
 
Example 26
Source Project: google-cloud-java   Source File: ITTransactionSnippets.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCommit() {
  Transaction transaction = datastore.newTransaction();
  TransactionSnippets transactionSnippets = new TransactionSnippets(transaction);
  Key key = transactionSnippets.commit();
  Entity result = datastore.get(key);
  assertNotNull(result);
  datastore.delete(key);
}
 
Example 27
Source Project: google-cloud-java   Source File: QuerySnippets.java    License: Apache License 2.0 5 votes vote down vote up
/** Example of creating and running a key query. */
// [TARGET newKeyQueryBuilder()]
// [VARIABLE "my_kind"]
public QueryResults<Key> newKeyQuery(String kind) {
  // [START newKeyQuery]
  Query<Key> query = Query.newKeyQueryBuilder().setKind(kind).build();
  QueryResults<Key> results = datastore.run(query);
  // Use results
  // [END newKeyQuery]
  return results;
}
 
Example 28
Source Project: getting-started-java   Source File: DatastoreDao.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void updateBook(Book book) {
  Key key = keyFactory.newKey(book.getId());  // From a book, create a Key
  Entity entity = Entity.newBuilder(key)         // Convert Book to an Entity
      .set(Book.AUTHOR, book.getAuthor())
      .set(Book.DESCRIPTION, book.getDescription())
      .set(Book.PUBLISHED_DATE, book.getPublishedDate())
      .set(Book.TITLE, book.getTitle())
      .set(Book.IMAGE_URL, book.getImageUrl())
      .set(Book.CREATED_BY, book.getCreatedBy())
      .set(Book.CREATED_BY_ID, book.getCreatedById())
      .build();
  datastore.update(entity);                   // Update the Entity
}
 
Example 29
Source Project: google-cloud-java   Source File: ITTransactionSnippets.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIsActive() {
  Transaction transaction = datastore.newTransaction();
  TransactionSnippets transactionSnippets = new TransactionSnippets(transaction);
  Key key = transactionSnippets.isActive();
  Entity result = datastore.get(key);
  assertNotNull(result);
  datastore.delete(key);
}
 
Example 30
Source Project: java-docs-samples   Source File: MessageRepositoryImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void saveClaim(String claim) {
  // Save message to "messages"
  Datastore datastore = getDatastoreInstance();
  Key key = datastore.allocateId(claimsKindKeyFactory.newKey());

  Entity.Builder claimEntityBuilder = Entity.newBuilder(key).set("claim", claim);

  datastore.put(claimEntityBuilder.build());
}