Java源码示例:com.google.appengine.api.datastore.TransactionOptions

示例1
@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]
}
 
示例2
@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"));
}
 
示例3
@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));
    }
}
 
示例4
@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));
    }
}
 
示例5
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();
        }
    }
}
 
示例6
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();
        }
    }
}
 
示例7
@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();
}
 
示例8
@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;
}
 
示例9
/**
 * 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();
    }
  }
}
 
示例10
/**
 * 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();
    }
  }
}
 
示例11
@Test
public void testTransactionOptions() {
    TransactionOptions tos = TransactionOptions.Builder.withXG(true);
    assertEquals(true, tos.isXG());
    tos.clearXG();
    assertEquals(false, tos.isXG());
}
 
示例12
@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("");
    }
}
 
示例13
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;
    }
 
示例14
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;
    }
 
示例15
@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();
        }
    }
}
 
示例16
@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();
        }
    }
}
 
示例17
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);
    }
}
 
示例18
@Override
public Future<Transaction> beginTransaction(TransactionOptions transaction) {
  return delegate.beginTransaction(transaction);
}