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

The following examples show how to use com.google.appengine.api.datastore.Transaction#rollback() . 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: 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 2
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 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: 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 5
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 6
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 7
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 8
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 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: TransactionTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
private GroupParentKeys writeMultipleGroup(boolean allow) throws Exception {

        GroupParentKeys keys = new GroupParentKeys();

        TransactionOptions tos = TransactionOptions.Builder.withXG(allow);
        Transaction tx = service.beginTransaction(tos);
        try {
            Entity parent = new Entity(kindName);
            parent.setProperty("check", "parent");
            parent.setProperty("stamp", new Date());
            keys.firstParent = service.put(tx, parent);

            Entity other = new Entity(otherKind);
            other.setProperty("check", "other");
            other.setProperty("stamp", new Date());
            keys.secondParent = service.put(tx, other);
            tx.commit();

            sync(sleepTime);
        } catch (Exception e) {
            tx.rollback();
            throw e;
        }
        sync(sleepTime);

        return keys;
    }
 
Example 11
Source File: TaskQueueTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testTransactionalTasksMustBeNamelessIterable() {
    Transaction tx = DatastoreServiceFactory.getDatastoreService().beginTransaction();
    try {
        getDefaultQueue().add(tx, Collections.singleton(TaskOptions.Builder.withTaskName("foo")));
    } finally {
        tx.rollback();
    }
}
 
Example 12
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 13
Source File: AsyncTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testBeginTx() throws Exception {
    final AsyncDatastoreService service = DatastoreServiceFactory.getAsyncDatastoreService();

    Transaction tx = waitOnFuture(service.beginTransaction(TransactionOptions.Builder.withXG(true)));
    Key key, key2;
    try {
        key = waitOnFuture(service.put(tx, new Entity("AsyncTx")));
        key2 = waitOnFuture(service.put(tx, new Entity("AsyncTx")));
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        throw e;
    }

    if (key != null && key2 != null) {
        tx = waitOnFuture(service.beginTransaction(TransactionOptions.Builder.withXG(true)));
        try {
            try {
                try {
                    Assert.assertNotNull(waitOnFuture(service.get(tx, key)));
                    Assert.assertNotNull(waitOnFuture(service.get(tx, Collections.singleton(key2))));
                } finally {
                    service.delete(tx, key2);
                }
            } finally {
                service.delete(tx, Collections.singleton(key));
            }
        } finally {
            tx.rollback();
        }
    }
}
 
Example 14
Source File: TxPolicyTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testAutoPolicy() throws Exception {
    DatastoreServiceConfig config = DatastoreServiceConfig.Builder.withImplicitTransactionManagementPolicy(ImplicitTransactionManagementPolicy.AUTO);
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService(config);

    Key k1 = null;
    Transaction tx = ds.beginTransaction();
    try {
        // this one should be part of auto Tx
        k1 = ds.put(new Entity("PutAutoTx"));
    } finally {
        tx.rollback();
    }

    Assert.assertTrue(ds.get(Collections.singleton(k1)).isEmpty());

    k1 = ds.put(new Entity("DeleteAutoTx"));
    try {
        Assert.assertNotNull(ds.get(k1));

        tx = ds.beginTransaction();
        try {
            // this one should be part of auto Tx
            ds.delete(k1);
        } finally {
            tx.rollback();
        }

        Assert.assertNotNull(ds.get(k1));
    } finally {
        ds.delete(k1);
    }
}
 
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.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 16
Source File: TransactionsTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testXGTransaction() throws Exception {

    final int N = 25; // max XG entity groups

    List<Key> keys = new ArrayList<>();
    for (int i = 0; i < N + 1; i++) {
        keys.add(service.put(new Entity("XG")));
    }

    boolean ok = false;
    Transaction tx = service.beginTransaction(TransactionOptions.Builder.withXG(true));
    try {
        for (int i = 0; i < N; i++) {
            service.get(keys.get(i));
        }

        try {
            service.get(keys.get(N));
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // pass
        }
        ok = true;
    } finally {
        if (ok) {
            tx.commit();
        } else {
            tx.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.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 18
Source File: TransactionTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testAllowMultipleGroupFalseWithNs() throws Exception {
    NamespaceManager.set("");
    clearData(kindName);
    NamespaceManager.set("trns");
    try {
        clearData(kindName);
        TransactionOptions tos = TransactionOptions.Builder.withXG(false);
        Transaction tx = service.beginTransaction(tos);
        try {
            List<Entity> es = new ArrayList<>();
            NamespaceManager.set("");
            Entity ens1 = new Entity(kindName);
            ens1.setProperty("check", "entity-nons");
            ens1.setProperty("stamp", new Date());
            es.add(ens1);

            NamespaceManager.set("trns");
            Entity ens2 = new Entity(kindName);
            ens2.setProperty("check", "entity-trns");
            ens2.setProperty("stamp", new Date());
            es.add(ens2);
            service.put(tx, es);
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
            throw e;
        }
    } finally {
        NamespaceManager.set("");
    }
}
 
Example 19
Source File: TransactionsTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetCurrentTx() throws Exception {
    Transaction tx = service.beginTransaction();
    try {
        Assert.assertEquals(tx, service.getCurrentTransaction(null));
    } finally {
        tx.rollback();
    }

    Transaction dummy = new Transaction() {
        public void commit() {
        }

        public Future<Void> commitAsync() {
            return null;
        }

        public void rollback() {
        }

        public Future<Void> rollbackAsync() {
            return null;
        }

        public String getId() {
            return "dummy";
        }

        public String getApp() {
            return ApiProxy.getCurrentEnvironment().getAppId();
        }

        public boolean isActive() {
            return false;
        }
    };

    Assert.assertSame(dummy, service.getCurrentTransaction(dummy));
}
 
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;
}