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

The following examples show how to use com.google.appengine.api.datastore.Transaction#commit() . 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: 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 2
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 3
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 4
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 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: 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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
Source File: TransactionsTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicTxDelete() throws Exception {
    Entity entity = createTestEntity();
    service.put(entity);
    Transaction tx = service.beginTransaction();
    try {
        service.delete(tx, entity.getKey());
        assertStoreContains(entity);
        tx.commit();
        assertStoreDoesNotContain(entity);
    } catch (Exception e) {
        tx.rollback();
        throw e;
    }
}
 
Example 16
Source File: TransactionsTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void usesForTransactions_readSnapshot() throws Exception {
  String boardName = "my-message-board";
  Entity b = new Entity("MessageBoard", boardName);
  b.setProperty("count", 13);
  datastore.put(b);

  // [START uses_for_transactions_3]
  DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

  // Display information about a message board and its first 10 messages.
  Key boardKey = KeyFactory.createKey("MessageBoard", boardName);

  Transaction txn = datastore.beginTransaction();

  Entity messageBoard = datastore.get(boardKey);
  long count = (Long) messageBoard.getProperty("count");

  Query q = new Query("Message", boardKey);

  // This is an ancestor query.
  PreparedQuery pq = datastore.prepare(txn, q);
  List<Entity> messages = pq.asList(FetchOptions.Builder.withLimit(10));

  txn.commit();
  // [END uses_for_transactions_3]

  assertWithMessage("board.count").that(count).isEqualTo(13L);
}
 
Example 17
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 18
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 19
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 20
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.
  }
}