Java Code Examples for com.google.appengine.api.datastore.DatastoreService#beginTransaction()

The following examples show how to use com.google.appengine.api.datastore.DatastoreService#beginTransaction() . 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 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
Source File: ServersStartServlet.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
private void datastoreSave(Key key) {
  DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
  Transaction tx = ds.beginTransaction();
  Entity entity = new Entity(key);
  entity.setProperty("value", Integer.valueOf(CountServlet.localCount.get()));
  ds.put(entity);
  tx.commit();
}
 
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: 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 14
Source File: TestBase.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
/**
 * Should work in all envs?
 * A bit complex / overkill ...
 *
 * @return true if in-container, false otherewise
 */
protected static boolean isInContainer() {
    try {
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        Transaction tx = ds.beginTransaction();
        try {
            return (ds.getCurrentTransaction() != null);
        } finally {
            tx.rollback();
        }
    } catch (Throwable ignored) {
        return false;
    }
}
 
Example 15
Source File: TransactionsTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void transactionalTaskEnqueuing() throws Exception {
  // [START transactional_task_enqueuing]
  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
  Queue queue = QueueFactory.getDefaultQueue();
  Transaction txn = datastore.beginTransaction();
  // ...

  queue.add(txn, TaskOptions.Builder.withUrl("/path/to/handler"));

  // ...

  txn.commit();
  // [END transactional_task_enqueuing]
}
 
Example 16
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 17
Source File: TransactionsTest.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@Test
public void entityGroups() throws Exception {
  try {
    // [START entity_groups]
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity person = new Entity("Person", "tom");
    datastore.put(person);

    // Transactions on root entities
    Transaction txn = datastore.beginTransaction();

    Entity tom = datastore.get(person.getKey());
    tom.setProperty("age", 40);
    datastore.put(txn, tom);
    txn.commit();

    // Transactions on child entities
    txn = datastore.beginTransaction();
    tom = datastore.get(person.getKey());
    Entity photo = new Entity("Photo", tom.getKey());

    // Create a Photo that is a child of the Person entity named "tom"
    photo.setProperty("photoUrl", "http://domain.com/path/to/photo.jpg");
    datastore.put(txn, photo);
    txn.commit();

    // Transactions on entities in different entity groups
    txn = datastore.beginTransaction();
    tom = datastore.get(person.getKey());
    Entity photoNotAChild = new Entity("Photo");
    photoNotAChild.setProperty("photoUrl", "http://domain.com/path/to/photo.jpg");
    datastore.put(txn, photoNotAChild);

    // Throws IllegalArgumentException because the Person entity
    // and the Photo entity belong to different entity groups.
    txn.commit();
    // [END entity_groups]
    fail("Expected IllegalArgumentException");
  } catch (IllegalArgumentException expected) {
    // We expect to get an exception that complains that we don't have a XG-transaction.
  }
}