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

The following examples show how to use com.google.appengine.api.datastore.TransactionOptions. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
Source File: TransactionTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactionRollback() throws Exception {
    clearData(kindName);
    clearData(otherKind);
    GroupParentKeys keys = writeMultipleGroup(true);
    List<Entity> es = readMultipleGroup(keys);

    TransactionOptions tos = TransactionOptions.Builder.withXG(true);
    Transaction tx = service.beginTransaction(tos);
    es.get(0).setProperty("check", "parent-update");
    es.get(1).setProperty("check", "other-update");
    service.put(tx, es);
    tx.rollback();
    es = readMultipleGroup(keys);
    assertEquals("parent", es.get(0).getProperty("check"));
    assertEquals("other", es.get(1).getProperty("check"));
}
 
Example #7
Source File: ConcurrentTxServlet.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String entityGroup = req.getParameter("eg");
    String counter = req.getParameter("c");
    String parent = req.getParameter("p");
    boolean xg = Boolean.parseBoolean(req.getParameter("xg"));

    Key parentKey = "2".equals(parent) ? ROOT_2.getKey() : ROOT_1.getKey();

    Entity entity = new Entity(entityGroup, parentKey);
    entity.setProperty("foo", RANDOM.nextInt());

    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    final Transaction tx = ds.beginTransaction(TransactionOptions.Builder.withXG(xg));
    try {
        log.warning("Before put ... " + counter);
        putEntity(ds, entity);
        log.warning("After put ... " + counter);
        tx.commit();
        resp.getWriter().write("OK" + counter);
    } catch (Exception e) {
        log.warning("Error ... " + e);
        tx.rollback();
        resp.getWriter().write("ERROR" + counter + ":" + e.getClass().getName());
        error(counter);
    } finally {
        cleanup(counter);
    }
}
 
Example #8
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 #9
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 #10
Source File: TransactionTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
private GroupParentKeys writeMultipleInList(boolean allow) throws Exception {

        GroupParentKeys keys = new GroupParentKeys();

        List<Entity> es = new ArrayList<>();
        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());
            es.add(parent);
            keys.firstParent = parent.getKey();

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

            sync(sleepTime);
        } catch (Exception e) {
            tx.rollback();
            throw e;
        }
        sync(sleepTime);
        return keys;
    }
 
Example #11
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 #12
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 #13
Source File: TransactionTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactionOptions() {
    TransactionOptions tos = TransactionOptions.Builder.withXG(true);
    assertEquals(true, tos.isXG());
    tos.clearXG();
    assertEquals(false, tos.isXG());
}
 
Example #14
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 #15
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 #16
Source File: AppengineTransationDriver.java    From yawp with MIT License 5 votes vote down vote up
@Override
public TransactionDriver beginX() {
    logger.finer("begin X");
    if (!environment.isProduction()) {
        return this;
    }

    TransactionOptions options = TransactionOptions.Builder.withXG(true);
    tx = datastore().beginTransaction(options);
    logger.finer("done");
    return this;
}
 
Example #17
Source File: RemoteApiSharedTests.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void run(
    DatastoreService ds, Supplier<Key> keySupplier, Supplier<Entity> entitySupplier) {
  Transaction txn = ds.beginTransaction(TransactionOptions.Builder.withXG(true));
  if (ds.put(new Entity("xgfoo")).getId() == 0) {
    throw new RuntimeException("first entity should have received an id");
  }
  if (ds.put(new Entity("xgfoo")).getId() == 0) {
    throw new RuntimeException("second entity should have received an id");
  }
  txn.commit();
}
 
Example #18
Source File: RequestCapturingAsyncDatastoreService.java    From nomulus with Apache License 2.0 4 votes vote down vote up
@Override
public Future<Transaction> beginTransaction(TransactionOptions transaction) {
  return delegate.beginTransaction(transaction);
}