Java Code Examples for com.google.appengine.api.datastore.Entity#setProperty()

The following examples show how to use com.google.appengine.api.datastore.Entity#setProperty() . 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: UnindexedPropertiesTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Ignore("CAPEDWARF-66")
@Test
public void testFilterWithUnindexedPropertyType() throws Exception {
    Entity entity = new Entity(UNINDEXED_ENTITY);
    entity.setProperty("prop", "bbb");
    service.put(entity);
    sync(3000);

    assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", EQUAL, new Text("bbb")))));
    assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", LESS_THAN, new Text("ccc")))));
    assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", LESS_THAN_OR_EQUAL, new Text("ccc")))));

    // it's strange that GREATER_THAN actually DOES return a result, whereas LESS_THAN doesn't
    assertEquals(entity, getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", GREATER_THAN, new Text("aaa")))));
    assertEquals(entity, getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", GREATER_THAN_OR_EQUAL, new Text("aaa")))));

    service.delete(entity.getKey());
}
 
Example 2
Source File: DatetimeDataTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Before
public void createData() throws InterruptedException, ParseException {
    Date[] testDatas = {dfDateTime.parse("2001,1,1,23,59,59"), dfDateTime.parse("2005,5,5,13,19,19"), dfDateTime.parse("2008,8,8,3,9,9")};

    Query q = new Query(kindName, rootKey);
    if (service.prepare(q).countEntities(FetchOptions.Builder.withDefaults()) == 0) {
        List<Entity> elist = new ArrayList<Entity>();
        for (Date data : testDatas) {
            Entity newRec = new Entity(kindName, rootKey);
            newRec.setProperty(propertyName, data);
            elist.add(newRec);
        }
        service.put(elist);
        sync(waitTime);
    }
}
 
Example 3
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 4
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 5
Source File: DatastoreTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Override
protected void doTestUpdate() throws Exception {
    Key key = getKey();
    Entity e = ds.get(key);
    Assert.assertNotNull(e);
    e.setProperty("x", "z");
    ds.put(e);
}
 
Example 6
Source File: DatastoreDao.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
@Override
public Long createBook(Book book) {
  Entity incBookEntity = new Entity(BOOK_KIND);  // Key will be assigned once written
  incBookEntity.setProperty(Book.AUTHOR, book.getAuthor());
  incBookEntity.setProperty(Book.DESCRIPTION, book.getDescription());
  incBookEntity.setProperty(Book.PUBLISHED_DATE, book.getPublishedDate());
  incBookEntity.setProperty(Book.TITLE, book.getTitle());
  incBookEntity.setProperty(Book.IMAGE_URL, book.getImageUrl());
  incBookEntity.setProperty(Book.CREATED_BY, book.getCreatedBy());
  incBookEntity.setProperty(Book.CREATED_BY_ID, book.getCreatedById());

  Key bookKey = datastore.put(incBookEntity); // Save the Entity
  return bookKey.getId();                     // The ID of the Key
}
 
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: DatastoreDao.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
@Override
public Long createBook(Book book) {
  Entity incBookEntity = new Entity(BOOK_KIND);  // Key will be assigned once written
  incBookEntity.setProperty(Book.AUTHOR, book.getAuthor());
  incBookEntity.setProperty(Book.DESCRIPTION, book.getDescription());
  incBookEntity.setProperty(Book.PUBLISHED_DATE, book.getPublishedDate());
  incBookEntity.setProperty(Book.TITLE, book.getTitle());

  Key bookKey = datastore.put(incBookEntity); // Save the Entity
  return bookKey.getId();                     // The ID of the Key
}
 
Example 9
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void sortOrderExample_returnsSortedEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Person", "a");
  a.setProperty("lastName", "Alpha");
  a.setProperty("height", 100);
  Entity b = new Entity("Person", "b");
  b.setProperty("lastName", "Bravo");
  b.setProperty("height", 200);
  Entity c = new Entity("Person", "c");
  c.setProperty("lastName", "Charlie");
  c.setProperty("height", 300);
  datastore.put(ImmutableList.<Entity>of(a, b, c));

  // Act
  // [START gae_java8_datastore_sort_order]
  // Order alphabetically by last name:
  Query q1 = new Query("Person").addSort("lastName", SortDirection.ASCENDING);

  // Order by height, tallest to shortest:
  Query q2 = new Query("Person").addSort("height", SortDirection.DESCENDING);
  // [END gae_java8_datastore_sort_order]

  // Assert
  List<Entity> lastNameResults =
      datastore.prepare(q1.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertWithMessage("last name query results")
      .that(lastNameResults)
      .containsExactly(a, b, c)
      .inOrder();
  List<Entity> heightResults =
      datastore.prepare(q2.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertWithMessage("height query results")
      .that(heightResults)
      .containsExactly(c, b, a)
      .inOrder();
}
 
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: QueriesTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void singleRetrievalExample_singleEntity_returnsEntity() throws Exception {
  Entity a = new Entity("Person", "a");
  a.setProperty("lastName", "Johnson");
  Entity b = new Entity("Person", "b");
  b.setProperty("lastName", "Smith");
  datastore.put(ImmutableList.<Entity>of(a, b));

  Entity result = retrievePersonWithLastName("Johnson");

  assertWithMessage("result")
      .that(result)
      .isEqualTo(a); // Note: Entity.equals() only checks the Key.
}
 
Example 12
Source File: EntitiesTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void batchOperations_putsEntities() {
  // [START batch_operations]
  Entity employee1 = new Entity("Employee");
  Entity employee2 = new Entity("Employee");
  Entity employee3 = new Entity("Employee");
  // [START_EXCLUDE]
  employee1.setProperty("firstName", "Bill");
  employee2.setProperty("firstName", "Jane");
  employee3.setProperty("firstName", "Alex");
  // [END_EXCLUDE]

  List<Entity> employees = Arrays.asList(employee1, employee2, employee3);
  datastore.put(employees);
  // [END batch_operations]

  Map<Key, Entity> got =
      datastore.get(Arrays.asList(employee1.getKey(), employee2.getKey(), employee3.getKey()));
  assertWithMessage("employee1.firstName")
      .that((String) got.get(employee1.getKey()).getProperty("firstName"))
      .isEqualTo("Bill");
  assertWithMessage("employee2.firstName")
      .that((String) got.get(employee2.getKey()).getProperty("firstName"))
      .isEqualTo("Jane");
  assertWithMessage("employee3.firstName")
      .that((String) got.get(employee3.getKey()).getProperty("firstName"))
      .isEqualTo("Alex");
}
 
Example 13
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) {
  Key key = keySupplier.get();
  Entity entity = new Entity(key);
  entity.setProperty("prop1", 75L);
  ds.put(entity);

  assertGetEquals(ds, key, entity);
  ds.delete(key);
  assertEntityNotFoundException(ds, key);
}
 
Example 14
Source File: EntityWrapper.java    From nomulus with Apache License 2.0 5 votes vote down vote up
public static EntityWrapper from(int id, Property... properties) {
  Entity entity = new Entity(TEST_ENTITY_KIND, id);
  for (Property prop : properties) {
    entity.setProperty(prop.name(), prop.value());
  }
  return new EntityWrapper(entity);
}
 
Example 15
Source File: DatastoreHelperTestBase.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
protected Entity createTestEntity(String kind, long id) {
    Key key = KeyFactory.createKey(kind, id);
    Entity entity = new Entity(key);
    entity.setProperty("text", "Some text.");
    return entity;
}
 
Example 16
Source File: Worker.java    From io2014-codelabs with Apache License 2.0 4 votes vote down vote up
private void recordTaskProcessed(TaskHandle task) {
  cache.put(task.getName(), 1, Expiration.byDeltaSeconds(60 * 60 * 2));
  Entity entity = new Entity(PROCESSED_NOTIFICATION_TASKS_ENTITY_KIND, task.getName());
  entity.setProperty("processedAt", new Date());
  dataStore.put(entity);
}
 
Example 17
Source File: ProjectionTest.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
private void putTestData(String a, long b) {
  Entity entity = new Entity("TestKind");
  entity.setProperty("A", a);
  entity.setProperty("B", b);
  datastore.put(entity);
}
 
Example 18
Source File: DatastoreHelperTestBase.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
protected Entity createTestEntity(String kind, Key key) {
    Entity entity = new Entity(kind, key);
    entity.setProperty("text", "Some text.");
    return entity;
}
 
Example 19
Source File: BlobMetadata.java    From io2014-codelabs with Apache License 2.0 3 votes vote down vote up
/**
 * Constructs a BlobMetadata for a new blob.
 *
 * @param gcsCanonicalizedResourcePath canonicalized resource path for this blob, e.g.,
 *        "/bucket/path/objectName".
 * @param accessMode access mode for this blob.
 * @param ownerId owner of this blob.
 */
public BlobMetadata(
    String gcsCanonicalizedResourcePath, BlobAccessMode accessMode, String ownerId) {
  entity = new Entity(ENTITY_KIND, gcsCanonicalizedResourcePath);
  entity.setProperty(ENTITY_OWNER_PROPERTY, ownerId);
  entity.setUnindexedProperty(ENTITY_ACCESS_MODE_PROPERTY, (long) accessMode.ordinal());
}
 
Example 20
Source File: BlobMetadata.java    From solutions-mobile-backend-starter-java with Apache License 2.0 3 votes vote down vote up
/**
 * Constructs a BlobMetadata for a new blob.
 *
 * @param gcsCanonicalizedResourcePath canonicalized resource path for this blob, e.g.,
 *        "/bucket/path/objectName".
 * @param accessMode access mode for this blob.
 * @param ownerId owner of this blob.
 */
public BlobMetadata(
    String gcsCanonicalizedResourcePath, BlobAccessMode accessMode, String ownerId) {
  entity = new Entity(ENTITY_KIND, gcsCanonicalizedResourcePath);
  entity.setProperty(ENTITY_OWNER_PROPERTY, ownerId);
  entity.setUnindexedProperty(ENTITY_ACCESS_MODE_PROPERTY, (long) accessMode.ordinal());
}