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

The following examples show how to use com.google.appengine.api.datastore.Entity#getProperty() . 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: ShardedCounter.java    From appengine-modules-sample-java with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve the value of this sharded counter.
 *
 * @return Summed total of all shards' counts
 */
public long getCount() {
  final Long value = (Long) mc.get(kind);
  if (value != null) {
    return value;
  }

  long sum = 0;
  final Query query = new Query(kind);
  for (final Entity shard : ds.prepare(query).asIterable()) {
    sum += (Long) shard.getProperty(CounterShard.COUNT);
  }
  mc.put(kind, sum, Expiration.byDeltaSeconds(60),
      SetPolicy.ADD_ONLY_IF_NOT_PRESENT);

  return sum;
}
 
Example 2
Source File: SecurityChecker.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Checks ACL of the specified CloudEntity to see if the specified user can
 * write on it.
 *
 * @param e
 *          {@link com.google.appengine.api.datastore.Entity} of CloudEntity
 * @param user
 *          User object representing the caller.
 * @throws com.google.api.server.spi.response.UnauthorizedException
 *           if the user does not have permission to write on the entity
 */
protected void checkAclForWrite(Entity e, User user) throws UnauthorizedException {

  // get ACL
  String userId = getUserId(user);
  String ownerId = (String) e.getProperty(EntityDto.PROP_OWNER);

  // check ACL
  boolean isOwner = userId.equals(ownerId);
  boolean isPublic = e.getKind().startsWith(KIND_PREFIX_PUBLIC);
  boolean isWritable = isOwner || isPublic;
  if (!isWritable) {
    String id = e.getKey().getName();
    throw new UnauthorizedException("Insuffient permission for updating a CloudEntity: " + id
        + " by: " + userId);
  }
}
 
Example 3
Source File: TaskQueueTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testCountdownMillis() {
    String testMethodTag = "testCountdownMillis";
    int countdownMillis = 10000;
    TaskOptions taskoptions = TaskOptions.Builder
        .withMethod(TaskOptions.Method.POST)
        .param(TEST_RUN_ID, testRunId)
        .param(TEST_METHOD_TAG, testMethodTag)
        .countdownMillis(countdownMillis);

    long etaMillis = System.currentTimeMillis() + countdownMillis;
    QueueFactory.getQueue(E2E_TESTING_EXEC).add(taskoptions);

    Entity entity = dsUtil.waitForTaskThenFetchEntity(waitInterval, retryMax, testMethodTag);
    long executedAt = (Long) entity.getProperty(EXECUTED_AT);
    Assert.assertTrue("Expected executed_at to be >= " + etaMillis + ", but was: " + executedAt, executedAt >= etaMillis);
}
 
Example 4
Source File: MetadataPropertiesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
Collection<String> representationsOfProperty(DatastoreService ds, String kind, String property) {

    // Start with unrestricted non-keys-only property query
    Query q = new Query(Entities.PROPERTY_METADATA_KIND);

    // Limit to specified kind and property
    q.setFilter(
        new FilterPredicate(
            "__key__", Query.FilterOperator.EQUAL, Entities.createPropertyKey(kind, property)));

    // Get query result
    Entity propInfo = ds.prepare(q).asSingleEntity();

    // Return collection of property representations
    return (Collection<String>) propInfo.getProperty("property_representation");
  }
 
Example 5
Source File: SessionData.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
/**
 * Query datastore for a session for a particular user via id.
 * 
 * @param currentUser
 * @param id
 * @return
 */
public static SessionData load(String currentUser, Long id) {
  Key userKey = KeyFactory.createKey(User.KIND, currentUser);
  Key sessionKey = KeyFactory.createKey(userKey, KIND, id);

  try {
    Entity e = Datastore.getDatastore().get(sessionKey);

    return new SessionData(
        BaseEncoding.base64().decode((String) e.getProperty(CHALLENGE_PROPERTY)),
        (String) e.getProperty(ORIGIN_PROPERTY), (Date) e.getProperty(TIMESTAMP_PROPERTY));
  } catch (EntityNotFoundException e1) {
    return null;
  }
}
 
Example 6
Source File: EmbeddedEntityTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    EmbeddedEntity embedded = new EmbeddedEntity();
    embedded.setProperty("string", "foo");

    Entity entity = createTestEntity();
    entity.setProperty("embedded", embedded);
    Key key = service.put(entity);

    Entity storedEntity = service.get(key);
    EmbeddedEntity storedEmbedded = (EmbeddedEntity) storedEntity.getProperty("embedded");

    assertEquals(embedded, storedEmbedded);
}
 
Example 7
Source File: StatsServlet.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  // [START stat_example]
  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
  Entity globalStat = datastore.prepare(new Query("__Stat_Total__")).asSingleEntity();
  Long totalBytes = (Long) globalStat.getProperty("bytes");
  Long totalEntities = (Long) globalStat.getProperty("count");
  // [END stat_example]

  resp.setContentType("text/plain");
  resp.setCharacterEncoding("UTF-8");
  PrintWriter w = resp.getWriter();
  w.printf("%d bytes\n%d entities\n", totalBytes, totalEntities);
}
 
Example 8
Source File: LocalRawGcsService.java    From appengine-gcs-client with Apache License 2.0 5 votes vote down vote up
private GcsFileMetadata createGcsFileMetadataFromBlobstore(Entity entity, GcsFilename filename) {
  return new GcsFileMetadata(
      filename,
      GcsFileOptions.getDefaultInstance(),
      "",
      (Long) entity.getProperty("size"),
      (Date) entity.getProperty("creation"));
}
 
Example 9
Source File: JobInstanceRecord.java    From appengine-pipelines with Apache License 2.0 5 votes vote down vote up
public JobInstanceRecord(Entity entity) {
  super(entity);
  jobKey = (Key) entity.getProperty(JOB_KEY_PROPERTY);
  jobClassName = (String) entity.getProperty(JOB_CLASS_NAME_PROPERTY);
  if (entity.hasProperty(JOB_DISPLAY_NAME_PROPERTY)) {
    jobDisplayName = (String) entity.getProperty(JOB_DISPLAY_NAME_PROPERTY);
  } else {
    jobDisplayName = jobClassName;
  }
  if (entity.hasProperty(INSTANCE_BYTES_PROPERTY)) {
    value = entity.getProperty(INSTANCE_BYTES_PROPERTY);
  } else {
    value = entity.getProperty(INSTANCE_VALUE_PROPERTY);
  }
}
 
Example 10
Source File: ShardedCounter.java    From appengine-modules-sample-java with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the value of this sharded counter.
 * 
 * @return Summed total of all shards' counts
 */
public long getCount() {
  long sum = 0;

  final Query query = new Query("SimpleCounterShard");
  for (final Entity e : ds.prepare(query).asIterable()) {
    sum += (Long) e.getProperty("count");
  }

  return sum;
}
 
Example 11
Source File: DatastoreHelperTestBase.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
protected Object[] getResult(Query query, String pName) {
    int count = service.prepare(query).countEntities(FetchOptions.Builder.withDefaults());
    Object result[] = new Object[count];
    int pt = 0;
    for (Entity readRec : service.prepare(query).asIterable()) {
        result[pt++] = readRec.getProperty(pName);
    }
    return result;
}
 
Example 12
Source File: GeoPtDataTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testGets() throws Exception {
    Query query = new Query(kindName, rootKey);
    GeoPt filter = new GeoPt(Float.valueOf(60).floatValue(), Float.valueOf(145).floatValue());
    query.setFilter(new FilterPredicate(propertyName, Query.FilterOperator.EQUAL, filter));
    Entity entity = service.prepare(query).asSingleEntity();
    GeoPt geopt = (GeoPt) entity.getProperty(propertyName);
    assertTrue(geopt.equals(filter));
    assertEquals(Float.valueOf(geopt.getLatitude()).toString(), Float.valueOf(60).toString());
    assertEquals(Float.valueOf(geopt.getLongitude()).toString(), Float.valueOf(145).toString());
}
 
Example 13
Source File: PipelineModelObject.java    From appengine-pipelines with Apache License 2.0 4 votes vote down vote up
private static Key extractGeneratorJobKey(Entity entity) {
  return (Key) entity.getProperty(GENERATOR_JOB_PROPERTY);
}
 
Example 14
Source File: PipelineModelObject.java    From appengine-pipelines with Apache License 2.0 4 votes vote down vote up
private static Key extractRootJobKey(Entity entity) {
  return (Key) entity.getProperty(ROOT_JOB_KEY_PROPERTY);
}
 
Example 15
Source File: TestMetadataServlet.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
Collection<String> representationsOf(DatastoreService ds, String kind, String property) {
  Query q = new Query(Query.PROPERTY_METADATA_KIND);
  q.setAncestor(makePropertyKey(kind, property));
  Entity propInfo = ds.prepare(q).asSingleEntity();
  return (Collection<String>) propInfo.getProperty("property_representation");
}
 
Example 16
Source File: MyIndex.java    From google-geoEngine with Apache License 2.0 4 votes vote down vote up
public static int buildIndex(String group) throws IOException{
    //Get all fences of group from DataStore.
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Key fenceKey = KeyFactory.createKey("Geofence", group);

    Query query = new Query("Fence", fenceKey).addSort("id", Query.SortDirection.DESCENDING);
    List<Entity> fencesFromStore = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());

    if (!fencesFromStore.isEmpty()) {
    	//Create STRTree-Index.
        STRtree index = new STRtree();
        //Loop through the fences from DataStore.
        for (Entity fenceFromStore : fencesFromStore) {
            long id = (long) fenceFromStore.getProperty("id");
            Gson gson = new Gson();
            Text vText = (Text) fenceFromStore.getProperty("vertices");
            String vString = vText.getValue();
            double[][] vertices = gson.fromJson(vString, double[][].class);

            //Store coordinates in an array.
            Coordinate[] coordinates = new Coordinate[vertices.length];
            int i = 0;
            for(double[] point : vertices){
                Coordinate coordinate = new Coordinate(point[0],point[1]);
                coordinates[i++] = coordinate;
            }
            //Create polygon from the coordinates.
            GeometryFactory fact = new GeometryFactory();
            LinearRing linear = new GeometryFactory().createLinearRing(coordinates);
            MyPolygon polygon = new MyPolygon(linear, null, fact, id);
            //Add polygon to index.
            index.insert(polygon.getEnvelopeInternal(), polygon);
        }
        //Build the index.
        index.build();
        //Write the index to Memcache.
        MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
        //Last param is expiration date. Set to null to keep it in Memcache forever.
        syncCache.put(group, index, null); 
    }
    return fencesFromStore.size();
}
 
Example 17
Source File: AppEngineDataStoreFactory.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
/** Deserializes the specified object from a Blob using an {@link ObjectInputStream}. */
private V deserialize(Entity entity) throws IOException {
  Blob blob = (Blob) entity.getProperty(FIELD_VALUE);
  return IOUtils.deserialize(blob.getBytes());
}
 
Example 18
Source File: CrudOperations.java    From solutions-mobile-backend-starter-java with Apache License 2.0 4 votes vote down vote up
private void convertDatePropertyToEpochTime(Entity e, String propName) {
  Date d = (Date) e.getProperty(propName);
  e.setProperty(propName, Double.parseDouble(String.valueOf(d.getTime())));
}
 
Example 19
Source File: Greeting.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
static Greeting create(Entity entity) {
  User user = (User) entity.getProperty("user");
  Instant date = new Instant((Date) entity.getProperty("date"));
  String content = (String) entity.getProperty("content");
  return new AutoValue_Greeting(user, date, content);
}
 
Example 20
Source File: BackendConfigManager.java    From solutions-mobile-backend-starter-java with Apache License 2.0 2 votes vote down vote up
/**
 * Gets the last subscription deletion time.
 * @return The last subscription deletion time.  If it's null, then no subscription delete all
 *         has been issued yet.
 */
public Date getLastSubscriptionDeleteAllTime() {
  Entity config = getConfiguration();
  return (Date) config.getProperty(LAST_SUBSCRIPTION_DELETE_TIMESTAMP);
}