Java Code Examples for com.google.appengine.api.datastore.Transaction#isActive()

The following examples show how to use com.google.appengine.api.datastore.Transaction#isActive() . 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: PhotoManagerNoSql.java    From solutions-photo-sharing-demo-java with Apache License 2.0 6 votes vote down vote up
@Override
public Photo deactivePhoto(String userId, long id) {
  Utils.assertTrue(userId != null, "user id cannot be null");
  DatastoreService ds = getDatastoreService();
  Transaction txn = ds.beginTransaction();
  try {
    Entity entity = getDatastoreEntity(ds, createPhotoKey(userId, id));
    if (entity != null) {
      PhotoNoSql photo = new PhotoNoSql(entity);
      if (photo.isActive()) {
        photo.setActive(false);
        ds.put(entity);
      }
      txn.commit();

      return photo;
    }
  } catch (Exception e) {
    logger.severe("Failed to delete entity from datastore:" + e.getMessage());
  } finally {
    if (txn.isActive()) {
      txn.rollback();
    }
  }
  return null;
}
 
Example 2
Source File: MyEndpoint.java    From endpoints-codelab-android with GNU General Public License v3.0 6 votes vote down vote up
@ApiMethod(name = "clearTasks")
public void clearTasks() {
    DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
    Transaction txn = datastoreService.beginTransaction();
    try {
        Key taskBeanParentKey = KeyFactory.createKey("TaskBeanParent", "todo.txt");
        Query query = new Query(taskBeanParentKey);
        List<Entity> results = datastoreService.prepare(query).asList(FetchOptions.Builder.withDefaults());
        for (Entity result : results) {
            datastoreService.delete(result.getKey());
        }
        txn.commit();
    } finally {
        if (txn.isActive()) {
            txn.rollback();
        }
    }
}
 
Example 3
Source File: MyEndpoint.java    From endpoints-codelab-android with GNU General Public License v3.0 6 votes vote down vote up
@ApiMethod(name = "storeTask")
public void storeTask(TaskBean taskBean) {
    DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
    Transaction txn = datastoreService.beginTransaction();
    try {
        Key taskBeanParentKey = KeyFactory.createKey("TaskBeanParent", "todo.txt");
        Entity taskEntity = new Entity("TaskBean", taskBean.getId(), taskBeanParentKey);
        taskEntity.setProperty("data", taskBean.getData());
        datastoreService.put(taskEntity);
        txn.commit();
    } finally {
        if (txn.isActive()) {
            txn.rollback();
        }
    }
}
 
Example 4
Source File: DemoEntityManagerNoSql.java    From solutions-photo-sharing-demo-java with Apache License 2.0 6 votes vote down vote up
@Override
public T deleteEntity(T demoEntity) {
  Utils.assertTrue(demoEntity != null, "entity cannot be null");
  DemoEntityNoSql entityNoSql = downCastEntity(demoEntity);
  DatastoreService ds = getDatastoreService();
  Transaction txn = ds.beginTransaction();
  try {
    if (checkEntityForDelete(ds, entityNoSql)) {
      ds.delete(entityNoSql.getEntity().getKey());
      txn.commit();
      logger.info("entity deleted.");
      return demoEntity;
    }
  } catch (Exception e) {
    logger.severe("Failed to delete entity from datastore:" + e.getMessage());
  } finally {
    if (txn.isActive()) {
      txn.rollback();
    }
  }
  return null;
}
 
Example 5
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
protected void deleteSessionWithValue(String varName, String varValue) {
  Transaction transaction = datastore.beginTransaction();
  try {
    Query query = new Query(SESSION_KIND)
        .setFilter(new FilterPredicate(varName, FilterOperator.EQUAL, varValue));
    Iterator<Entity> results = datastore.prepare(transaction, query).asIterator();
    while (results.hasNext()) {
      Entity stateEntity = results.next();
      datastore.delete(transaction, stateEntity.getKey());
    }
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 6
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.createKey(SESSION_KIND, sessionId);
  Transaction transaction = datastore.beginTransaction();
  try {
    Entity stateEntity = datastore.get(transaction, key);
    for (String varName : varNames) {
      stateEntity.removeProperty(varName);
    }
    datastore.put(transaction, stateEntity);
    transaction.commit();
  } catch (EntityNotFoundException e) {
    // Ignore - if there's no session, there's nothing to delete.
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 7
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
protected void deleteSessionWithValue(String varName, String varValue) {
  Transaction transaction = datastore.beginTransaction();
  try {
    Query query = new Query(SESSION_KIND)
        .setFilter(new FilterPredicate(varName, FilterOperator.EQUAL, varValue));
    Iterator<Entity> results = datastore.prepare(transaction, query).asIterator();
    while (results.hasNext()) {
      Entity stateEntity = results.next();
      datastore.delete(transaction, stateEntity.getKey());
    }
    transaction.commit();
  } 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.createKey(SESSION_KIND, sessionId);
  Transaction transaction = datastore.beginTransaction();
  try {
    Entity stateEntity = datastore.get(transaction, key);
    for (String varName : varNames) {
      stateEntity.removeProperty(varName);
    }
    datastore.put(transaction, stateEntity);
    transaction.commit();
  } catch (EntityNotFoundException e) {
    // Ignore - if there's no session, there's nothing to delete.
  } 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
protected void deleteSessionWithValue(String varName, String varValue) {
  Transaction transaction = datastore.beginTransaction();
  try {
    Query query = new Query(SESSION_KIND)
        .setFilter(new FilterPredicate(varName, FilterOperator.EQUAL, varValue));
    Iterator<Entity> results = datastore.prepare(transaction, query).asIterator();
    while (results.hasNext()) {
      Entity stateEntity = results.next();
      datastore.delete(transaction, stateEntity.getKey());
    }
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 10
Source File: TestBase.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
protected static void deleteTempDataInTx(DatastoreService ds, Entity entity, Class<? extends TempData> type) {
    Transaction txn = ds.beginTransaction(TransactionOptions.Builder.withXG(true));
    try {
        TempData data = type.newInstance();
        data.fromProperties(entity.getProperties());
        data.preDelete(ds);
        ds.delete(txn, entity.getKey());
        data.postDelete(ds);
        txn.commit();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    } finally {
        if (txn.isActive()) {
            txn.rollback();
        }
    }
}
 
Example 11
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.createKey(SESSION_KIND, sessionId);
  Transaction transaction = datastore.beginTransaction();
  try {
    Entity stateEntity = datastore.get(transaction, key);
    for (String varName : varNames) {
      stateEntity.removeProperty(varName);
    }
    datastore.put(transaction, stateEntity);
    transaction.commit();
  } catch (EntityNotFoundException e) {
    // Ignore - if there's no session, there's nothing to delete.
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example 12
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.createKey(SESSION_KIND, sessionId);
  Transaction transaction = datastore.beginTransaction();
  try {
    Entity stateEntity = datastore.get(transaction, key);
    Map<String, Object> properties = stateEntity.getProperties();
    for (Map.Entry<String, Object> property : properties.entrySet()) {
      req.getSession().setAttribute(property.getKey(), property.getValue());
      datastoreMap.put(property.getKey(), (String)property.getValue());
    }
    transaction.commit();
  } catch (EntityNotFoundException e) {
    // Ignore - if there's no session, there's nothing to delete.
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
  return datastoreMap;
}
 
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.createKey(SESSION_KIND, sessionId);
  Transaction transaction = datastore.beginTransaction();
  try {
    Entity stateEntity = datastore.get(transaction, key);
    Map<String, Object> properties = stateEntity.getProperties();
    for (Map.Entry<String, Object> property : properties.entrySet()) {
      req.getSession().setAttribute(property.getKey(), property.getValue());
      datastoreMap.put(property.getKey(), (String)property.getValue());
    }
    transaction.commit();
  } catch (EntityNotFoundException e) {
    // Ignore - if there's no session, there's nothing to delete.
  } 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
/**
 * 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.createKey(SESSION_KIND, sessionId);
  Transaction transaction = datastore.beginTransaction();
  try {
    Entity stateEntity = datastore.get(transaction, key);
    Map<String, Object> properties = stateEntity.getProperties();
    for (Map.Entry<String, Object> property : properties.entrySet()) {
      req.getSession().setAttribute(property.getKey(), property.getValue());
      datastoreMap.put(property.getKey(), (String)property.getValue());
    }
    transaction.commit();
  } catch (EntityNotFoundException e) {
    // Ignore - if there's no session, there's nothing to delete.
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
  return datastoreMap;
}
 
Example 15
Source File: TransactionsTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() {
  // Clean up any dangling transactions.
  Transaction txn = datastore.getCurrentTransaction(null);
  if (txn != null && txn.isActive()) {
    txn.rollback();
  }
  helper.tearDown();
}
 
Example 16
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.createKey(SESSION_KIND, sessionId);
  Transaction transaction = datastore.beginTransaction();
  try {
    Entity stateEntity = datastore.get(transaction, key);
    Map<String, Object> properties = stateEntity.getProperties();
    for (Map.Entry<String, Object> property : properties.entrySet()) {
      req.getSession().setAttribute(property.getKey(), property.getValue());
      datastoreMap.put(property.getKey(), (String)property.getValue());
    }
    transaction.commit();
  } catch (EntityNotFoundException e) {
    // Ignore - if there's no session, there's nothing to delete.
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
  return datastoreMap;
}
 
Example 17
Source File: BlobManager.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Stores metadata if this is a new blob or existing blob owned by this user.
 *
 * @param bucketName Google Cloud Storage bucket for this blob.
 * @param objectPath path to the object in the bucket.
 * @param accessMode controls how the blob can be accessed.
 * @param ownerId    the id of the owner.
 * @return true if metadata was stored; false if the blob already exists but has a different
 * owner.
 */
public static boolean tryStoreBlobMetadata(
  String bucketName, String objectPath, BlobAccessMode accessMode, String ownerId) {

  Transaction tx = dataStore.beginTransaction(TransactionOptions.Builder.withXG(true));
  try {
    BlobMetadata metadata = getBlobMetadata(bucketName, objectPath);

    if (metadata != null) {
      if (!ownerId.equalsIgnoreCase(metadata.getOwnerId())) {
        // Object exists and is owned by a different owner.
        return false;
      } else if (accessMode == metadata.getAccessMode()) {
        // The new metadata is the same as the existing one. No need to update anything.
        return true;
      }
    }

    metadata =
      new BlobMetadata(getCanonicalizedResource(bucketName, objectPath), accessMode, ownerId);
    dataStore.put(metadata.getEntity());
    tx.commit();
    return true;
  } catch (ConcurrentModificationException e) {
    return false;
  } finally {
    if (tx != null && tx.isActive()) {
      tx.rollback();
    }
  }
}
 
Example 18
Source File: DatastoreUtil.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
private void saveEntity(Entity entity) {
    DatastoreService service = DatastoreServiceFactory.getDatastoreService();
    Transaction tx = service.beginTransaction();
    try {
        service.put(tx, entity);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
    }
}
 
Example 19
Source File: BlobManager.java    From solutions-mobile-backend-starter-java with Apache License 2.0 5 votes vote down vote up
/**
 * Stores metadata if this is a new blob or existing blob owned by this user.
 *
 * @param bucketName Google Cloud Storage bucket for this blob.
 * @param objectPath path to the object in the bucket.
 * @param accessMode controls how the blob can be accessed.
 * @param ownerId the id of the owner.
 * @return true if metadata was stored; false if the blob already exists but has a different
 *         owner.
 */
public static boolean tryStoreBlobMetadata(
    String bucketName, String objectPath, BlobAccessMode accessMode, String ownerId) {

  Transaction tx = dataStore.beginTransaction(TransactionOptions.Builder.withXG(true));
  try {
    BlobMetadata metadata = getBlobMetadata(bucketName, objectPath);

    if (metadata != null) {
      if (!ownerId.equalsIgnoreCase(metadata.getOwnerId())) {
        // Object exists and is owned by a different owner.
        return false;
      } else if (accessMode == metadata.getAccessMode()) {
        // The new metadata is the same as the existing one. No need to update anything.
        return true;
      }
    }

    metadata =
        new BlobMetadata(getCanonicalizedResource(bucketName, objectPath), accessMode, ownerId);
    dataStore.put(metadata.getEntity());
    tx.commit();
    return true;
  } catch (ConcurrentModificationException e) {
    return false;
  } finally {
    if (tx != null && tx.isActive()) {
      tx.rollback();
    }
  }
}
 
Example 20
Source File: AppEngineBackEnd.java    From appengine-pipelines with Apache License 2.0 4 votes vote down vote up
private boolean transactionallySaveAll(UpdateSpec.Transaction transactionSpec,
    QueueSettings queueSettings, Key rootJobKey, Key jobKey, JobRecord.State... expectedStates) {
  Transaction transaction = dataStore.beginTransaction();
  try {
    if (jobKey != null && expectedStates != null) {
      Entity entity = null;
      try {
        entity = dataStore.get(jobKey);
      } catch (EntityNotFoundException e) {
        throw new RuntimeException(
            "Fatal Pipeline corruption error. No JobRecord found with key = " + jobKey);
      }
      JobRecord jobRecord = new JobRecord(entity);
      JobRecord.State state = jobRecord.getState();
      boolean stateIsExpected = false;
      for (JobRecord.State expectedState : expectedStates) {
        if (state == expectedState) {
          stateIsExpected = true;
          break;
        }
      }
      if (!stateIsExpected) {
        logger.info("Job " + jobRecord + " is not in one of the expected states: "
            + Arrays.asList(expectedStates)
            + " and so transactionallySaveAll() will not continue.");
        return false;
      }
    }
    saveAll(transactionSpec);
    if (transactionSpec instanceof UpdateSpec.TransactionWithTasks) {
      UpdateSpec.TransactionWithTasks transactionWithTasks =
          (UpdateSpec.TransactionWithTasks) transactionSpec;
      Collection<Task> tasks = transactionWithTasks.getTasks();
      if (tasks.size() > 0) {
        byte[] encodedTasks = FanoutTask.encodeTasks(tasks);
        FanoutTaskRecord ftRecord = new FanoutTaskRecord(rootJobKey, encodedTasks);
        // Store FanoutTaskRecord outside of any transaction, but before
        // the FanoutTask is enqueued. If the put succeeds but the
        // enqueue fails then the FanoutTaskRecord is orphaned. But
        // the Pipeline is still consistent.
        dataStore.put(null, ftRecord.toEntity());
        FanoutTask fannoutTask = new FanoutTask(ftRecord.getKey(), queueSettings);
        taskQueue.enqueue(fannoutTask);
      }
    }
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
  return true;
}