Java Code Examples for com.google.cloud.datastore.Transaction#get()

The following examples show how to use com.google.cloud.datastore.Transaction#get() . 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: DatastoreExample.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
@Override
public void run(Transaction tx, Key userKey, Void arg) {
  Entity user = tx.get(userKey);
  if (user == null) {
    System.out.println("Nothing to delete, user does not exist.");
    return;
  }
  Query<Key> query =
      Query.newKeyQueryBuilder()
          .setNamespace(NAMESPACE)
          .setKind(COMMENT_KIND)
          .setFilter(PropertyFilter.hasAncestor(userKey))
          .build();
  QueryResults<Key> comments = tx.run(query);
  int count = 0;
  while (comments.hasNext()) {
    tx.delete(comments.next());
    count++;
  }
  tx.delete(userKey);
  System.out.printf("Deleting user '%s' and %d comment[s].%n", userKey.getName(), count);
}
 
Example 2
Source File: GoogleJobStore.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
/**
 * Inserts a new {@link PortabilityJob} keyed by {@code jobId} in Datastore.
 *
 * <p>To update an existing {@link PortabilityJob} instead, use {@link JobStore#update}.
 *
 * @throws IOException if a job already exists for {@code jobId}, or if there was a different
 *     problem inserting the job.
 */
@Override
public void createJob(UUID jobId, PortabilityJob job) throws IOException {
  Preconditions.checkNotNull(jobId);
  Transaction transaction = datastore.newTransaction();
  Entity shouldNotExist = transaction.get(getJobKey(jobId));
  if (shouldNotExist != null) {
    transaction.rollback();
    throw new IOException(
        "Record already exists for jobID: " + jobId + ". Record: " + shouldNotExist);
  }
  Entity entity = createNewEntity(jobId, job.toMap());
  try {
    transaction.put(entity);
  } catch (DatastoreException e) {
    transaction.rollback();
    throw new IOException(
        "Could not create initial record for jobID: " + jobId + ". Record: " + entity, e);
  }
  transaction.commit();
}
 
Example 3
Source File: DatastoreExample.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
@Override
public void run(Transaction tx, Key userKey, Contact contact) {
  Entity user = tx.get(userKey);
  if (user == null) {
    System.out.println("Adding a new user.");
    user = Entity.newBuilder(userKey).set("count", 0L).build();
    tx.add(user);
  }
  FullEntity<IncompleteKey> contactEntity =
      FullEntity.newBuilder()
          .set("email", contact.email())
          .set("phone", contact.phone())
          .build();
  tx.update(Entity.newBuilder(user).set("contact", contactEntity).build());
  System.out.printf("Setting contact for user '%s'.%n", userKey.getName());
}
 
Example 4
Source File: TaskList.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Marks a task entity as done.
 *
 * @param id The ID of the task entity as given by {@link Key#id()}
 * @return true if the task was found, false if not
 * @throws DatastoreException if the transaction fails
 */
boolean markDone(long id) {
  Transaction transaction = datastore.newTransaction();
  try {
    Entity task = transaction.get(keyFactory.newKey(id));
    if (task != null) {
      transaction.put(Entity.newBuilder(task).set("done", true).build());
    }
    transaction.commit();
    return task != null;
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 5
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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 6
Source File: DatastoreExample.java    From google-cloud-java with 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 7
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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 8
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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 9
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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 10
Source File: ConceptsTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactionalSingleEntityGroupReadOnly() {
  setUpQueryTests();
  Key taskListKey = datastore.newKeyFactory().setKind("TaskList").newKey("default");
  Entity taskListEntity = Entity.newBuilder(taskListKey).build();
  datastore.put(taskListEntity);
  // [START datastore_transactional_single_entity_group_read_only]
  Entity taskList;
  QueryResults<Entity> tasks;
  Transaction txn = datastore.newTransaction(
      TransactionOptions.newBuilder()
          .setReadOnly(ReadOnly.newBuilder().build())
          .build()
  );
  try {
    taskList = txn.get(taskListKey);
    Query<Entity> query = Query.newEntityQueryBuilder()
        .setKind("Task")
        .setFilter(PropertyFilter.hasAncestor(taskListKey))
        .build();
    tasks = txn.run(query);
    txn.commit();
  } finally {
    if (txn.isActive()) {
      txn.rollback();
    }
  }
  // [END datastore_transactional_single_entity_group_read_only]
  assertEquals(taskListEntity, taskList);
  assertNotNull(tasks.next());
  assertFalse(tasks.hasNext());
}
 
Example 11
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
/**
 * Take an HttpServletRequest, and copy all of the current session variables over to it
 *
 * @param req Request from which to extract session.
 * @return a map of strings containing all the session variables loaded or an empty map.
 */
protected Map<String, String> loadSessionVariables(HttpServletRequest req)
    throws ServletException {
  Map<String, String> datastoreMap = new HashMap<>();
  String sessionId = getCookieValue(req, "bookshelfSessionId");
  if (sessionId.equals("")) {
    return datastoreMap;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  try {
    Entity stateEntity = transaction.get(key);
    StringBuilder logNames = new StringBuilder();
    if (stateEntity != null) {
      for (String varName : stateEntity.getNames()) {
        req.getSession().setAttribute(varName, stateEntity.getString(varName));
        datastoreMap.put(varName, stateEntity.getString(varName));
        logNames.append(varName + " ");
      }
    }
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
  return datastoreMap;
}
 
Example 12
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
/**
 * Stores the state value in each key-value pair in the project's datastore.
 *
 * @param sessionId Request from which to extract session.
 * @param varName   the name of the desired session variable
 * @param varValue  the value of the desired session variable
 */
protected void setSessionVariables(String sessionId, Map<String, String> setMap) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  dt.toString(dtf);
  try {
    Entity stateEntity = transaction.get(key);
    Entity.Builder seBuilder;
    if (stateEntity == null) {
      seBuilder = Entity.newBuilder(key);
    } else {
      seBuilder = Entity.newBuilder(stateEntity);
    }
    for (String varName : setMap.keySet()) {
      seBuilder.set(varName, setMap.get(varName));
    }
    transaction.put(seBuilder.set("lastModified", dt.toString(dtf)).build());
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 13
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
/**
 * Take an HttpServletRequest, and copy all of the current session variables over to it
 *
 * @param req Request from which to extract session.
 * @return a map of strings containing all the session variables loaded or an empty map.
 */
protected Map<String, String> loadSessionVariables(HttpServletRequest req)
    throws ServletException {
  Map<String, String> datastoreMap = new HashMap<>();
  String sessionId = getCookieValue(req, "bookshelfSessionId");
  if (sessionId.equals("")) {
    return datastoreMap;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  try {
    Entity stateEntity = transaction.get(key);
    StringBuilder logNames = new StringBuilder();
    if (stateEntity != null) {
      for (String varName : stateEntity.getNames()) {
        req.getSession().setAttribute(varName, stateEntity.getString(varName));
        datastoreMap.put(varName, stateEntity.getString(varName));
        logNames.append(varName + " ");
      }
    }
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
  return datastoreMap;
}
 
Example 14
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
/**
 * Stores the state value in each key-value pair in the project's datastore.
 *
 * @param sessionId Request from which to extract session.
 * @param varName   the name of the desired session variable
 * @param varValue  the value of the desired session variable
 */
protected void setSessionVariables(String sessionId, Map<String, String> setMap) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  dt.toString(dtf);
  try {
    Entity stateEntity = transaction.get(key);
    Entity.Builder seBuilder;
    if (stateEntity == null) {
      seBuilder = Entity.newBuilder(key);
    } else {
      seBuilder = Entity.newBuilder(stateEntity);
    }
    for (String varName : setMap.keySet()) {
      seBuilder.set(varName, setMap.get(varName));
    }
    transaction.put(seBuilder.set("lastModified", dt.toString(dtf)).build());
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 15
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
/**
 * Take an HttpServletRequest, and copy all of the current session variables over to it
 *
 * @param req Request from which to extract session.
 * @return a map of strings containing all the session variables loaded or an empty map.
 */
protected Map<String, String> loadSessionVariables(HttpServletRequest req)
    throws ServletException {
  Map<String, String> datastoreMap = new HashMap<>();
  String sessionId = getCookieValue(req, "bookshelfSessionId");
  if (sessionId.equals("")) {
    return datastoreMap;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  try {
    Entity stateEntity = transaction.get(key);
    StringBuilder logNames = new StringBuilder();
    if (stateEntity != null) {
      for (String varName : stateEntity.getNames()) {
        req.getSession().setAttribute(varName, stateEntity.getString(varName));
        datastoreMap.put(varName, stateEntity.getString(varName));
        logNames.append(varName + " ");
      }
    }
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
  return datastoreMap;
}
 
Example 16
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
/**
 * Stores the state value in each key-value pair in the project's datastore.
 *
 * @param sessionId Request from which to extract session.
 * @param varName   the name of the desired session variable
 * @param varValue  the value of the desired session variable
 */
protected void setSessionVariables(String sessionId, Map<String, String> setMap) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  dt.toString(dtf);
  try {
    Entity stateEntity = transaction.get(key);
    Entity.Builder seBuilder;
    if (stateEntity == null) {
      seBuilder = Entity.newBuilder(key);
    } else {
      seBuilder = Entity.newBuilder(stateEntity);
    }
    for (String varName : setMap.keySet()) {
      seBuilder.set(varName, setMap.get(varName));
    }
    transaction.put(seBuilder.set("lastModified", dt.toString(dtf)).build());
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 17
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
/**
 * Take an HttpServletRequest, and copy all of the current session variables over to it
 * @param req Request from which to extract session.
 * @return a map of strings containing all the session variables loaded or an empty map.
 */
protected Map<String, String> loadSessionVariables(HttpServletRequest req)
    throws ServletException {
  Map<String, String> datastoreMap = new HashMap<>();
  String sessionId = getCookieValue(req, "bookshelfSessionId");
  if (sessionId.equals("")) {
    return datastoreMap;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  try {
    Entity stateEntity = transaction.get(key);
    StringBuilder logNames = new StringBuilder();
    if (stateEntity != null) {
      for (String varName : stateEntity.getNames()) {
        req.getSession().setAttribute(varName, stateEntity.getString(varName));
        datastoreMap.put(varName, stateEntity.getString(varName));
        logNames.append(varName + " ");
      }
    }
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
  return datastoreMap;
}
 
Example 18
Source File: DefaultDatastoreWriter.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
/**
 * Worker method for updating the given entity with optimistic locking.
 * 
 * @param entity
 *          the entity to update
 * @param versionMetadata
 *          the metadata for optimistic locking
 * @return the updated entity
 */
@SuppressWarnings("unchecked")
protected <E> E updateWithOptimisticLockingInternal(E entity, PropertyMetadata versionMetadata) {
  Transaction transaction = null;
  try {
    entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entity);
    Entity nativeEntity = (Entity) Marshaller.marshal(entityManager, entity, Intent.UPDATE);
    transaction = datastore.newTransaction();
    Entity storedNativeEntity = transaction.get(nativeEntity.getKey());
    if (storedNativeEntity == null) {
      throw new OptimisticLockException(
          String.format("Entity does not exist: %s", nativeEntity.getKey()));
    }
    String versionPropertyName = versionMetadata.getMappedName();
    long version = nativeEntity.getLong(versionPropertyName) - 1;
    long storedVersion = storedNativeEntity.getLong(versionPropertyName);
    if (version != storedVersion) {
      throw new OptimisticLockException(
          String.format("Expecting version %d, but found %d", version, storedVersion));
    }
    transaction.update(nativeEntity);
    transaction.commit();
    E updatedEntity = (E) Unmarshaller.unmarshal(nativeEntity, entity.getClass());
    entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntity);
    return updatedEntity;
  } catch (DatastoreException exp) {
    throw DatastoreUtils.wrap(exp);
  } finally {
    rollbackIfActive(transaction);
  }
}
 
Example 19
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 20
Source File: DatastoreExample.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Transaction tx, Key userKey, Void arg) {
  Entity user = tx.get(userKey);
  if (user == null) {
    System.out.printf("User '%s' does not exist.%n", userKey.getName());
    return;
  }
  if (user.contains("contact")) {
    FullEntity<IncompleteKey> contact = user.getEntity("contact");
    String email = contact.getString("email");
    String phone = contact.getString("phone");
    System.out.printf(
        "User '%s' email is '%s', phone is '%s'.%n", userKey.getName(), email, phone);
  }
  System.out.printf("User '%s' has %d comment[s].%n", userKey.getName(), user.getLong("count"));
  int limit = 200;
  Map<Timestamp, String> sortedComments = new TreeMap<>();
  StructuredQuery<Entity> query =
      Query.newEntityQueryBuilder()
          .setNamespace(NAMESPACE)
          .setKind(COMMENT_KIND)
          .setFilter(PropertyFilter.hasAncestor(userKey))
          .setLimit(limit)
          .build();
  while (true) {
    QueryResults<Entity> results = tx.run(query);
    int resultCount = 0;
    while (results.hasNext()) {
      Entity result = results.next();
      sortedComments.put(result.getTimestamp("timestamp"), result.getString("content"));
      resultCount++;
    }
    if (resultCount < limit) {
      break;
    }
    query = query.toBuilder().setStartCursor(results.getCursorAfter()).build();
  }
  // We could have added "ORDER BY timestamp" to the query to avoid sorting, but that would
  // require adding an ancestor index for timestamp.
  // See: https://cloud.google.com/datastore/docs/tools/indexconfig
  for (Map.Entry<Timestamp, String> entry : sortedComments.entrySet()) {
    System.out.printf("\t%s: %s%n", entry.getKey(), entry.getValue());
  }
}