com.google.appengine.api.datastore.Transaction Java Examples

The following examples show how to use com.google.appengine.api.datastore.Transaction. 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: 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 #2
Source File: TransactionsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testAncestorIsMandatoryInQueriesInsideTransaction() {
    Transaction tx = service.beginTransaction();
    try {

        service.prepare(new Query("test"));         // no tx, ancestor not necessary
        service.prepare(null, new Query("test"));   // no tx, ancestor not necessary
        service.prepare(tx, new Query("test").setAncestor(KeyFactory.createKey("some_kind", "some_id"))); // tx + ancestor

        try {
            service.prepare(tx, new Query("test")); // tx, but no ancestor
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // pass
        }
    } finally {
        tx.rollback();
    }
}
 
Example #3
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 #4
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 #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.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 #6
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 #7
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 #8
Source File: TransactionsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetWithDifferentAncestorsInsideSameTransactionAreNotAllowed() {
    service.put(new Entity("foo", "1"));
    service.put(new Entity("foo", "2"));

    Transaction tx = service.beginTransaction();
    try {
        service.get(Arrays.asList(KeyFactory.createKey("foo", "1")));

        try {
            service.get(Arrays.asList(KeyFactory.createKey("foo", "2")));
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // pass
        }
    } finally {
        tx.rollback();
    }
}
 
Example #9
Source File: TransactionsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testMiscOps() throws Exception {
    AsyncDatastoreService service = DatastoreServiceFactory.getAsyncDatastoreService();

    DatastoreAttributes attributes = waitOnFuture(service.getDatastoreAttributes());
    Assert.assertNotNull(attributes);
    Assert.assertNotNull(attributes.getDatastoreType());

    Map<Index, Index.IndexState> indexes = waitOnFuture(service.getIndexes());
    Assert.assertNotNull(indexes);

    Transaction tx = waitOnFuture(service.beginTransaction());
    try {
        String txId = tx.getId();
        Assert.assertNotNull(txId);
        Assert.assertEquals(txId, tx.getId());

        String appId = tx.getApp();
        Assert.assertNotNull(appId);
        Assert.assertEquals(appId, tx.getApp());
    } finally {
        tx.rollback();
    }
}
 
Example #10
Source File: TransactionsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueriesWithDifferentAncestorsInsideSameTransactionNoUsage() {
    Transaction tx = service.beginTransaction();
    try {
        Key a1 = KeyFactory.createKey("ancestor", "1");
        prepareQueryWithAncestor(tx, a1).asIterator();

        Key a2 = KeyFactory.createKey("ancestor", "2");
        prepareQueryWithAncestor(tx, a2).asList(FetchOptions.Builder.withDefaults());

        Key a3 = KeyFactory.createKey("ancestor", "3");
        prepareQueryWithAncestor(tx, a3).asIterable();

        Key a4 = KeyFactory.createKey("ancestor", "4");
        prepareQueryWithAncestor(tx, a4).asQueryResultIterable();

        Key a5 = KeyFactory.createKey("ancestor", "5");
        prepareQueryWithAncestor(tx, a5).asQueryResultIterator();

        Key a6 = KeyFactory.createKey("ancestor", "6");
        prepareQueryWithAncestor(tx, a6).asQueryResultList(FetchOptions.Builder.withDefaults());
    } finally {
        tx.rollback();
    }
}
 
Example #11
Source File: TransactionsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleEntityGroupsInSingleTransactionAreNotAllowed() {
    Transaction tx = service.beginTransaction();
    try {
        Entity person = new Entity("Person", "tom");
        service.put(person);

        try {
            Entity photoNotAChild = new Entity("Photo");
            photoNotAChild.setProperty("photoUrl", "http://domain.com/path/to/photo.jpg");
            service.put(photoNotAChild);
            fail("put should have thrown IllegalArgumentException");
        } catch (IllegalArgumentException ex) {
            // pass
        }
    } finally {
        tx.rollback();
    }
}
 
Example #12
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 #13
Source File: TestBase.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
public static Key putTempData(TempData data) {
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    Transaction txn = ds.beginTransaction(TransactionOptions.Builder.withXG(true));
    try {
        Class<? extends TempData> type = data.getClass();
        String kind = getKind(type);
        Entity entity = new Entity(kind);
        for (Map.Entry<String, Object> entry : data.toProperties(ds).entrySet()) {
            entity.setProperty(entry.getKey(), entry.getValue());
        }
        entity.setProperty(TEMP_DATA_READ_PROPERTY, false);
        data.prePut(ds);
        Key key = ds.put(txn, entity);
        data.postPut(ds);
        txn.commit();
        return key;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    } finally {
        if (txn.isActive()) {
            txn.rollback();
        }
    }
}
 
Example #14
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 #15
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 #16
Source File: TransactionsTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
private void assertRollbackSucceedsWhenResultFetchedWith(ResultFetcher resultFetcher) throws EntityNotFoundException {
    String methodName = "assertRollbackSucceedsWhenResultFetchedWith";
    Entity entity = createTestEntityWithUniqueMethodNameKey(TRANSACTION_TEST_ENTITY, methodName);
    Key parentKey = entity.getKey();
    entity.setProperty("name", "original");
    Key key = service.put(entity);
    try {
        Transaction tx = service.beginTransaction();
        PreparedQuery preparedQuery = service.prepare(new Query(TRANSACTION_TEST_ENTITY).setAncestor(parentKey));
        Entity entity2 = resultFetcher.fetchResult(preparedQuery);
        entity2.setProperty("name", "modified");
        service.put(tx, entity2);
        tx.rollback();

        Entity entity3 = service.get(key);
        assertEquals("original", entity3.getProperty("name"));
    } finally {
        service.delete(entity.getKey());
    }
}
 
Example #17
Source File: TransactionsTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void creatingAnEntityInASpecificEntityGroup() throws Exception {
  String boardName = "my-message-board";

  // [START creating_an_entity_in_a_specific_entity_group]
  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

  String messageTitle = "Some Title";
  String messageText = "Some message.";
  Date postDate = new Date();

  Key messageBoardKey = KeyFactory.createKey("MessageBoard", boardName);

  Entity message = new Entity("Message", messageBoardKey);
  message.setProperty("message_title", messageTitle);
  message.setProperty("message_text", messageText);
  message.setProperty("post_date", postDate);

  Transaction txn = datastore.beginTransaction();
  datastore.put(txn, message);

  txn.commit();
  // [END creating_an_entity_in_a_specific_entity_group]
}
 
Example #18
Source File: TransactionsTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void crossGroupTransactions() throws Exception {
  // [START cross-group_XG_transactions_using_the_Java_low-level_API]
  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
  TransactionOptions options = TransactionOptions.Builder.withXG(true);
  Transaction txn = datastore.beginTransaction(options);

  Entity a = new Entity("A");
  a.setProperty("a", 22);
  datastore.put(txn, a);

  Entity b = new Entity("B");
  b.setProperty("b", 11);
  datastore.put(txn, b);

  txn.commit();
  // [END cross-group_XG_transactions_using_the_Java_low-level_API]
}
 
Example #19
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 #20
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 #21
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 #22
Source File: AsyncTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testCommitTx() throws Exception {
    AsyncDatastoreService service = DatastoreServiceFactory.getAsyncDatastoreService();
    Transaction tx = waitOnFuture(service.beginTransaction(TransactionOptions.Builder.withDefaults()));
    Key key;
    try {
        Future<Key> fKey = service.put(tx, new Entity("AsyncTx"));
        key = waitOnFuture(fKey);
        waitOnFuture(tx.commitAsync());
    } catch (Exception e) {
        waitOnFuture(tx.rollbackAsync());
        throw e;
    }

    if (key != null) {
        Assert.assertNotNull(getSingleEntity(service, key));
    }
}
 
Example #23
Source File: AsyncTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testRollbackTx() throws Exception {
    AsyncDatastoreService service = DatastoreServiceFactory.getAsyncDatastoreService();
    Transaction tx = waitOnFuture(service.beginTransaction(TransactionOptions.Builder.withDefaults()));
    Key key = null;
    try {
        Future<Key> fKey = service.put(tx, new Entity("AsyncTx"));
        key = waitOnFuture(fKey);
    } finally {
        waitOnFuture(tx.rollbackAsync());
    }

    if (key != null) {
        Assert.assertNull(getSingleEntity(service, key));
    }
}
 
Example #24
Source File: RemoteApiSharedTests.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public void run(
    DatastoreService ds, Supplier<Key> keySupplier, Supplier<Entity> entitySupplier) {
  // Put a fresh entity.
  Entity originalEntity = new Entity(getFreshKindName());
  originalEntity.setProperty("prop1", 75L);
  ds.put(originalEntity);
  Key key = originalEntity.getKey();

  // Prepare a new version of it with a different property value.
  Entity mutatedEntity = new Entity(key);
  mutatedEntity.setProperty("prop1", 76L);

  // Test Get/Put within a transaction.
  Transaction txn = ds.beginTransaction();
  assertGetEquals(ds, key, originalEntity);
  ds.put(mutatedEntity); // Write the mutated Entity.
  assertGetEquals(ds, key, originalEntity); // Within a txn, the put is not yet reflected.
  txn.commit();

  // Now that the txn is committed, the mutated entity will show up in Get.
  assertGetEquals(ds, key, mutatedEntity);
}
 
Example #25
Source File: TransactionTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleDefault() throws EntityNotFoundException, InterruptedException {
    clearData(kindName);
    Transaction tx = service.beginTransaction();
    Entity newRec = new Entity(kindName);
    newRec.setProperty("check", "4100331");
    newRec.setProperty("step", "added");
    Key key = service.put(tx, newRec);
    tx.commit();
    Entity qRec = service.get(key);
    assertEquals("4100331", qRec.getProperty("check"));

    tx = service.beginTransaction();
    qRec = service.get(key);
    qRec.setUnindexedProperty("step", "update");
    service.put(tx, newRec);
    tx.rollback();
    qRec = service.get(key);
    assertEquals("added", qRec.getProperty("step"));
}
 
Example #26
Source File: TransactionCleanupFilter.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
void handleAbandonedTxns(Collection<Transaction> txns) {
  // TODO(user): In the dev appserver, capture a stack trace whenever a
  // transaction is started so we can print it here.
  for (Transaction txn : txns) {
    try {
      logger.warning("Request completed without committing or rolling back transaction with id "
          + txn.getId() + ".  Transaction will be rolled back.");
      txn.rollback();
    } catch (Exception e) {
      // We swallow exceptions so that there is no risk of our cleanup
      // impacting the actual result of the request.
      logger.log(Level.SEVERE, "Swallowing an exception we received while trying to rollback "
          + "abandoned transaction with id " + txn.getId(), e);
    }
  }
}
 
Example #27
Source File: LocalRawGcsService.java    From appengine-gcs-client with Apache License 2.0 6 votes vote down vote up
@Override
public boolean deleteObject(GcsFilename filename, long timeoutMillis) throws IOException {
  ensureInitialized();
  Transaction tx = datastore.beginTransaction();
  Key key = makeKey(filename);
  try {
    datastore.get(tx, key);
    datastore.delete(tx, key);
    blobstoreService.delete(getBlobKeyForFilename(filename));
  } catch (EntityNotFoundException ex) {
    return false;
  } finally {
    if (tx.isActive()) {
      tx.commit();
    }
  }

  return true;
}
 
Example #28
Source File: AsyncTestBase.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
protected <T> T inTx(Action<T> action) throws Exception {
    AsyncDatastoreService ads = DatastoreServiceFactory.getAsyncDatastoreService();
    Transaction tx = ads.beginTransaction().get();
    boolean ok = false;
    try {
        T result = action.run(ads);
        ok = true;
        return result;
    } finally {
        if (ok)
            tx.commitAsync();
        else
            tx.rollbackAsync();

        sync(); // wait for tx to finish
    }
}
 
Example #29
Source File: TransactionTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testClosedTx() throws InterruptedException {
    clearData(kindName);
    Transaction tx = service.beginTransaction();
    Entity newRec = new Entity(kindName);
    newRec.setProperty("check", "4100331");
    newRec.setProperty("stamp", new Date());
    service.put(newRec);
    tx.commit();
    service.put(tx, new Entity(kindName));
}
 
Example #30
Source File: TransactionCleanupFilter.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
  try {
    chain.doFilter(request, response);
  } finally {
    Collection<Transaction> txns = datastoreService.getActiveTransactions();
    if (!txns.isEmpty()) {
      handleAbandonedTxns(txns);
    }
  }
}