com.google.appengine.api.datastore.Query.CompositeFilterOperator Java Examples

The following examples show how to use com.google.appengine.api.datastore.Query.CompositeFilterOperator. 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: QueriesTest.java    From java-docs-samples with Apache License 2.0 9 votes vote down vote up
@Test
public void queryInterface_orFilter_printsMatchedEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Person", "a");
  a.setProperty("height", 100);
  Entity b = new Entity("Person", "b");
  b.setProperty("height", 150);
  Entity c = new Entity("Person", "c");
  c.setProperty("height", 200);
  datastore.put(ImmutableList.<Entity>of(a, b, c));

  StringWriter buf = new StringWriter();
  PrintWriter out = new PrintWriter(buf);
  long minHeight = 125;
  long maxHeight = 175;

  // Act
  // [START gae_java8_datastore_interface_3]
  Filter tooShortFilter = new FilterPredicate("height", FilterOperator.LESS_THAN, minHeight);

  Filter tooTallFilter = new FilterPredicate("height", FilterOperator.GREATER_THAN, maxHeight);

  Filter heightOutOfRangeFilter = CompositeFilterOperator.or(tooShortFilter, tooTallFilter);

  Query q = new Query("Person").setFilter(heightOutOfRangeFilter);
  // [END gae_java8_datastore_interface_3]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertWithMessage("query results").that(results).containsExactly(a, c);
}
 
Example #2
Source File: SchemaTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertyMetadata() {
    NamespaceManager.set(namespaceDat[2]);
    // sort by kind/property, kindDat[1] < kindDat[0] < kindDat[2]
    Query q = new Query("__property__").addSort(Entity.KEY_RESERVED_PROPERTY).setKeysOnly();
    // filter out properties for kind "testing"
    Key key1 = Entities.createPropertyKey(kindDat[0], "urlData");
    Key key2 = Entities.createPropertyKey(kindDat[2], "urlData");
    q.setFilter(CompositeFilterOperator.and(
        new FilterPredicate(Entity.KEY_RESERVED_PROPERTY, FilterOperator.GREATER_THAN, key1),
        new FilterPredicate(Entity.KEY_RESERVED_PROPERTY, FilterOperator.LESS_THAN_OR_EQUAL, key2)));
    List<Entity> el = service.prepare(q).asList(fo);
    // un-indexed property, textData, will not be returned in __property__ queries.
    assertEquals(13, el.size());
    for (int i = 0; i < el.size(); i++) {
        assertEquals(namespaceDat[2], el.get(i).getKey().getNamespace());
        assertEquals(kindDat[2], el.get(i).getKey().getParent().getName());
        if (i == 0) {
            assertEquals("adressData", el.get(0).getKey().getName());
        } else if (i == el.size() - 1) {
            assertEquals("urlData", el.get(el.size() - 1).getKey().getName());
        }
    }
}
 
Example #3
Source File: IndexesServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {
  // [START exploding_index_example_1]
  Query q =
      new Query("Widget")
          .setFilter(
              CompositeFilterOperator.and(
                  new FilterPredicate("x", FilterOperator.EQUAL, 1),
                  new FilterPredicate("y", FilterOperator.EQUAL, 2)))
          .addSort("date", Query.SortDirection.ASCENDING);
  // [END exploding_index_example_1]
  List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());

  PrintWriter out = resp.getWriter();
  out.printf("Got %d widgets.\n", results.size());
}
 
Example #4
Source File: MetadataPropertiesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
void printPropertyRange(DatastoreService ds, PrintWriter writer) {

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

    // Limit range
    q.setFilter(
        CompositeFilterOperator.and(
            new FilterPredicate(
                Entity.KEY_RESERVED_PROPERTY,
                Query.FilterOperator.GREATER_THAN_OR_EQUAL,
                Entities.createPropertyKey("Employee", "salary")),
            new FilterPredicate(
                Entity.KEY_RESERVED_PROPERTY,
                Query.FilterOperator.LESS_THAN_OR_EQUAL,
                Entities.createPropertyKey("Manager", "salary"))));
    q.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING);

    // Print query results
    for (Entity e : ds.prepare(q).asIterable()) {
      writer.println(e.getKey().getParent().getName() + ": " + e.getKey().getName());
    }
  }
 
Example #5
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void queryRestrictions_compositeFilter_isInvalid() throws Exception {
  long minBirthYear = 1940;
  long maxHeight = 200;
  // [START gae_java8_datastore_inequality_filters_one_property_invalid]
  Filter birthYearMinFilter =
      new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);

  Filter heightMaxFilter =
      new FilterPredicate("height", FilterOperator.LESS_THAN_OR_EQUAL, maxHeight);

  Filter invalidFilter = CompositeFilterOperator.and(birthYearMinFilter, heightMaxFilter);

  Query q = new Query("Person").setFilter(invalidFilter);
  // [END gae_java8_datastore_inequality_filters_one_property_invalid]

  // Note: The local devserver behavior is different than the production
  // version of Cloud Datastore, so there aren't any assertions we can make
  // in this test.  The query appears to work with the local test runner,
  // but will fail in production.
}
 
Example #6
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void queryRestrictions_surprisingMultipleValuesAllMustMatch_returnsNoEntities()
    throws Exception {
  Entity a = new Entity("Widget", "a");
  List<Long> xs = Arrays.asList(1L, 2L);
  a.setProperty("x", xs);
  datastore.put(a);

  // [START gae_java8_datastore_surprising_behavior_1]
  Query q =
      new Query("Widget")
          .setFilter(
              CompositeFilterOperator.and(
                  new FilterPredicate("x", FilterOperator.GREATER_THAN, 1),
                  new FilterPredicate("x", FilterOperator.LESS_THAN, 2)));
  // [END gae_java8_datastore_surprising_behavior_1]

  // Entity "a" will not match because no individual value matches all filters.
  // See the documentation for more details:
  // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions
  // #properties_with_multiple_values_can_behave_in_surprising_ways
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertWithMessage("query results").that(results).isEmpty();
}
 
Example #7
Source File: PhotoManagerNoSql.java    From solutions-photo-sharing-demo-java with Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<Photo> getSharedPhotos(String userId) {
  Query query = new Query(getKind());
  Query.Filter ownerFilter =
      new Query.FilterPredicate(PhotoNoSql.FIELD_NAME_OWNER_ID, FilterOperator.NOT_EQUAL, userId);
  List<Query.Filter> filterList =
      Arrays.asList(ownerFilter,
          new Query.FilterPredicate(PhotoNoSql.FIELD_NAME_SHARED, FilterOperator.EQUAL, true),
          new Query.FilterPredicate(PhotoNoSql.FIELD_NAME_ACTIVE, FilterOperator.EQUAL, true)
          );
  Filter filter = new Query.CompositeFilter(CompositeFilterOperator.AND, filterList);
  query.setFilter(filter);
  FetchOptions options = FetchOptions.Builder.withDefaults();
  return queryEntities(query, options);
}
 
Example #8
Source File: CommentManagerNoSql.java    From solutions-photo-sharing-demo-java with Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<Comment> getComments(Photo photo) {
  Query query = new Query(getKind());
  Query.Filter photoIdFilter =
      new Query.FilterPredicate(CommentNoSql.FIELD_NAME_PHOTO_ID,
          FilterOperator.EQUAL, photo.getId());
  List<Filter> filters = Arrays.asList(photoIdFilter, new Query.FilterPredicate(
      CommentNoSql.FIELD_NAME_PHOTO_OWNER_ID, FilterOperator.EQUAL, photo.getOwnerId()));
  Filter filter = new Query.CompositeFilter(CompositeFilterOperator.AND, filters);
  query.setFilter(filter);
  query.addSort(CommentNoSql.FIELD_NAME_TIMESTAMP, SortDirection.DESCENDING);
  FetchOptions options = FetchOptions.Builder.withDefaults();
  return queryEntities(query, options);
}
 
Example #9
Source File: DatastoreUtil.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
public Entity getMarker(String marker) {
    DatastoreService service = DatastoreServiceFactory.getDatastoreService();
    FilterPredicate testRunFilter = new FilterPredicate(TEST_RUN_ID, FilterOperator.EQUAL, testRunId);
    FilterPredicate markerFilter = new FilterPredicate(MARKER, FilterOperator.EQUAL, marker);
    CompositeFilter filter = CompositeFilterOperator.and(testRunFilter, markerFilter);
    Query query = new Query(entityName).setFilter(filter);
    return service.prepare(query).asSingleEntity();
}
 
Example #10
Source File: FilterDto.java    From solutions-mobile-backend-starter-java with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the tree of {@link FilterDto}s to a tree of {@link FilterDto}s.
 */
public Filter getDatastoreFilter() {

  switch (this.operator) {
  case EQ:
    return new Query.FilterPredicate(getPropName(), Query.FilterOperator.EQUAL, getOperand());
  case LT:
    return new Query.FilterPredicate(getPropName(), Query.FilterOperator.LESS_THAN, getOperand());
  case LE:
    return new Query.FilterPredicate(getPropName(), Query.FilterOperator.LESS_THAN_OR_EQUAL,
        getOperand());
  case GT:
    return new Query.FilterPredicate(getPropName(), Query.FilterOperator.GREATER_THAN,
        getOperand());
  case GE:
    return new Query.FilterPredicate(getPropName(), Query.FilterOperator.GREATER_THAN_OR_EQUAL,
        getOperand());
  case NE:
    return new Query.FilterPredicate(getPropName(), Query.FilterOperator.NOT_EQUAL, getOperand());
  case IN:
    LinkedList<Object> l = new LinkedList<Object>(values);
    l.removeFirst();
    return new Query.FilterPredicate(getPropName(), Query.FilterOperator.IN, l);
  case AND:
    return new Query.CompositeFilter(CompositeFilterOperator.AND, getSubfilters(subfilters));
  case OR:
    return new Query.CompositeFilter(CompositeFilterOperator.OR, getSubfilters(subfilters));
  }
  return null;
}
 
Example #11
Source File: FilterDto.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the tree of {@link FilterDto}s to a tree of {@link FilterDto}s.
 */
public Filter getDatastoreFilter() {

  switch (this.operator) {
  case EQ:
    return new Query.FilterPredicate(getPropName(), Query.FilterOperator.EQUAL, getOperand());
  case LT:
    return new Query.FilterPredicate(getPropName(), Query.FilterOperator.LESS_THAN, getOperand());
  case LE:
    return new Query.FilterPredicate(getPropName(), Query.FilterOperator.LESS_THAN_OR_EQUAL,
        getOperand());
  case GT:
    return new Query.FilterPredicate(getPropName(), Query.FilterOperator.GREATER_THAN,
        getOperand());
  case GE:
    return new Query.FilterPredicate(getPropName(), Query.FilterOperator.GREATER_THAN_OR_EQUAL,
        getOperand());
  case NE:
    return new Query.FilterPredicate(getPropName(), Query.FilterOperator.NOT_EQUAL, getOperand());
  case IN:
    LinkedList<Object> l = new LinkedList<Object>(values);
    l.removeFirst();
    return new Query.FilterPredicate(getPropName(), Query.FilterOperator.IN, l);
  case AND:
    return new Query.CompositeFilter(CompositeFilterOperator.AND, getSubfilters(subfilters));
  case OR:
    return new Query.CompositeFilter(CompositeFilterOperator.OR, getSubfilters(subfilters));
  }
  return null;
}
 
Example #12
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void queryRestrictions_surprisingMultipleValuesTwoNotEquals_returnsMatchedEntities()
    throws Exception {
  Entity a = new Entity("Widget", "a");
  a.setProperty("x", ImmutableList.<Long>of(1L, 2L));
  Entity b = new Entity("Widget", "b");
  b.setProperty("x", ImmutableList.<Long>of(1L, 2L, 3L));
  datastore.put(ImmutableList.<Entity>of(a, b));

  // [START gae_java8_datastore_surprising_behavior_4]
  Query q =
      new Query("Widget")
          .setFilter(
              CompositeFilterOperator.and(
                  new FilterPredicate("x", FilterOperator.NOT_EQUAL, 1),
                  new FilterPredicate("x", FilterOperator.NOT_EQUAL, 2)));
  // [END gae_java8_datastore_surprising_behavior_4]

  // The two NOT_EQUAL filters in the query become like the combination of queries:
  // x < 1 OR (x > 1 AND x < 2) OR x > 2
  //
  // Only "b" has some value which matches the "x > 2" portion of this query.
  //
  // See the documentation for more details:
  // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions
  // #properties_with_multiple_values_can_behave_in_surprising_ways
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertWithMessage("query results").that(results).containsExactly(b);
}
 
Example #13
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void queryRestrictions_surprisingMultipleValuesEquals_returnsMatchedEntities()
    throws Exception {
  Entity a = new Entity("Widget", "a");
  a.setProperty("x", ImmutableList.<Long>of(1L, 2L));
  Entity b = new Entity("Widget", "b");
  b.setProperty("x", ImmutableList.<Long>of(1L, 3L));
  Entity c = new Entity("Widget", "c");
  c.setProperty("x", ImmutableList.<Long>of(-6L, 2L));
  Entity d = new Entity("Widget", "d");
  d.setProperty("x", ImmutableList.<Long>of(-6L, 4L));
  Entity e = new Entity("Widget", "e");
  e.setProperty("x", ImmutableList.<Long>of(1L, 2L, 3L));
  datastore.put(ImmutableList.<Entity>of(a, b, c, d, e));

  // [START gae_java8_datastore_surprising_behavior_2]
  Query q =
      new Query("Widget")
          .setFilter(
              CompositeFilterOperator.and(
                  new FilterPredicate("x", FilterOperator.EQUAL, 1),
                  new FilterPredicate("x", FilterOperator.EQUAL, 2)));
  // [END gae_java8_datastore_surprising_behavior_2]

  // Only "a" and "e" have both 1 and 2 in the "x" array-valued property.
  // See the documentation for more details:
  // https://cloud.google.com/appengine/docs/java/datastore/query-restrictions
  // #properties_with_multiple_values_can_behave_in_surprising_ways
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertWithMessage("query results").that(results).containsExactly(a, e);
}
 
Example #14
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void queryRestrictions_compositeFilter_returnsMatchedEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Person", "a");
  a.setProperty("birthYear", 1930);
  Entity b = new Entity("Person", "b");
  b.setProperty("birthYear", 1960);
  Entity c = new Entity("Person", "c");
  c.setProperty("birthYear", 1990);
  datastore.put(ImmutableList.<Entity>of(a, b, c));

  // Act
  long minBirthYear = 1940;
  long maxBirthYear = 1980;
  // [START gae_java8_datastore_inequality_filters_one_property_valid_1]
  Filter birthYearMinFilter =
      new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);

  Filter birthYearMaxFilter =
      new FilterPredicate("birthYear", FilterOperator.LESS_THAN_OR_EQUAL, maxBirthYear);

  Filter birthYearRangeFilter =
      CompositeFilterOperator.and(birthYearMinFilter, birthYearMaxFilter);

  Query q = new Query("Person").setFilter(birthYearRangeFilter);
  // [END gae_java8_datastore_inequality_filters_one_property_valid_1]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertWithMessage("query results").that(results).containsExactly(b);
}
 
Example #15
Source File: MetadataNamespacesTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
List<String> getNamespaces(DatastoreService ds, String start, String end) {

    // Start with unrestricted namespace query
    Query q = new Query(Entities.NAMESPACE_METADATA_KIND);
    List<Filter> subFilters = new ArrayList();
    // Limit to specified range, if any
    if (start != null) {
      subFilters.add(
          new FilterPredicate(
              Entity.KEY_RESERVED_PROPERTY,
              FilterOperator.GREATER_THAN_OR_EQUAL,
              Entities.createNamespaceKey(start)));
    }
    if (end != null) {
      subFilters.add(
          new FilterPredicate(
              Entity.KEY_RESERVED_PROPERTY,
              FilterOperator.LESS_THAN_OR_EQUAL,
              Entities.createNamespaceKey(end)));
    }

    q.setFilter(CompositeFilterOperator.and(subFilters));

    // Initialize result list
    List<String> results = new ArrayList<String>();

    // Build list of query results
    for (Entity e : ds.prepare(q).asIterable()) {
      results.add(Entities.getNamespaceFromNamespaceKey(e.getKey()));
    }

    // Return result list
    return results;
  }
 
Example #16
Source File: MetadataKindsTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
void printLowercaseKinds(DatastoreService ds, PrintWriter writer) {

    // Start with unrestricted kind query
    Query q = new Query(Entities.KIND_METADATA_KIND);

    List<Filter> subFils = new ArrayList();

    // Limit to lowercase initial letters
    subFils.add(
        new FilterPredicate(
            Entity.KEY_RESERVED_PROPERTY,
            FilterOperator.GREATER_THAN_OR_EQUAL,
            Entities.createKindKey("a")));

    String endChar = Character.toString((char) ('z' + 1)); // Character after 'z'

    subFils.add(
        new FilterPredicate(
            Entity.KEY_RESERVED_PROPERTY,
            FilterOperator.LESS_THAN,
            Entities.createKindKey(endChar)));

    q.setFilter(CompositeFilterOperator.and(subFils));

    // Print heading
    writer.println("Lowercase kinds:");

    // Print query results
    for (Entity e : ds.prepare(q).asIterable()) {
      writer.println("  " + e.getKey().getName());
    }
  }
 
Example #17
Source File: IndexesServlet.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {
  Query q =
      new Query("Widget")
          .setFilter(
              CompositeFilterOperator.and(
                  new FilterPredicate("x", FilterOperator.EQUAL, 1),
                  new FilterPredicate("y", FilterOperator.EQUAL, "red")))
          .addSort("date", Query.SortDirection.ASCENDING);
  List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());

  PrintWriter out = resp.getWriter();
  out.printf("Got %d widgets.\n", results.size());
}
 
Example #18
Source File: QueriesTest.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@Test
public void queryRestrictions_compositeEqualFilter_returnsMatchedEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Person", "a");
  a.setProperty("birthYear", 1930);
  a.setProperty("city", "Somewhere");
  a.setProperty("lastName", "Someone");
  Entity b = new Entity("Person", "b");
  b.setProperty("birthYear", 1960);
  b.setProperty("city", "Somewhere");
  b.setProperty("lastName", "Someone");
  Entity c = new Entity("Person", "c");
  c.setProperty("birthYear", 1990);
  c.setProperty("city", "Somewhere");
  c.setProperty("lastName", "Someone");
  Entity d = new Entity("Person", "d");
  d.setProperty("birthYear", 1960);
  d.setProperty("city", "Nowhere");
  d.setProperty("lastName", "Someone");
  Entity e = new Entity("Person", "e");
  e.setProperty("birthYear", 1960);
  e.setProperty("city", "Somewhere");
  e.setProperty("lastName", "Noone");
  datastore.put(ImmutableList.<Entity>of(a, b, c, d, e));
  long minBirthYear = 1940;
  long maxBirthYear = 1980;
  String targetCity = "Somewhere";
  String targetLastName = "Someone";

  // [START gae_java8_datastore_inequality_filters_one_property_valid_2]
  Filter lastNameFilter = new FilterPredicate("lastName", FilterOperator.EQUAL, targetLastName);

  Filter cityFilter = new FilterPredicate("city", FilterOperator.EQUAL, targetCity);

  Filter birthYearMinFilter =
      new FilterPredicate("birthYear", FilterOperator.GREATER_THAN_OR_EQUAL, minBirthYear);

  Filter birthYearMaxFilter =
      new FilterPredicate("birthYear", FilterOperator.LESS_THAN_OR_EQUAL, maxBirthYear);

  Filter validFilter =
      CompositeFilterOperator.and(
          lastNameFilter, cityFilter, birthYearMinFilter, birthYearMaxFilter);

  Query q = new Query("Person").setFilter(validFilter);
  // [END gae_java8_datastore_inequality_filters_one_property_valid_2]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertWithMessage("query results").that(results).containsExactly(b);
}
 
Example #19
Source File: IndexesServlet.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {
  PrintWriter out = resp.getWriter();
  // These queries should all work with the same index.
  // [START queries_and_indexes_example_1]
  Query q1 =
      new Query("Person")
          .setFilter(
              CompositeFilterOperator.and(
                  new FilterPredicate("lastName", FilterOperator.EQUAL, "Smith"),
                  new FilterPredicate("height", FilterOperator.EQUAL, 72)))
          .addSort("height", Query.SortDirection.DESCENDING);
  // [END queries_and_indexes_example_1]
  List<Entity> r1 = datastore.prepare(q1).asList(FetchOptions.Builder.withDefaults());
  out.printf("Got %d results from query 1.\n", r1.size());

  // [START queries_and_indexes_example_2]
  Query q2 =
      new Query("Person")
          .setFilter(
              CompositeFilterOperator.and(
                  new FilterPredicate("lastName", FilterOperator.EQUAL, "Jones"),
                  new FilterPredicate("height", FilterOperator.EQUAL, 63)))
          .addSort("height", Query.SortDirection.DESCENDING);
  // [END queries_and_indexes_example_2]
  List<Entity> r2 = datastore.prepare(q2).asList(FetchOptions.Builder.withDefaults());
  out.printf("Got %d results from query 2.\n", r2.size());

  // [START queries_and_indexes_example_3]
  Query q3 =
      new Query("Person")
          .setFilter(
              CompositeFilterOperator.and(
                  new FilterPredicate("lastName", FilterOperator.EQUAL, "Friedkin"),
                  new FilterPredicate("firstName", FilterOperator.EQUAL, "Damian")))
          .addSort("height", Query.SortDirection.ASCENDING);
  // [END queries_and_indexes_example_3]
  List<Entity> r3 = datastore.prepare(q3).asList(FetchOptions.Builder.withDefaults());
  out.printf("Got %d results from query 3.\n", r3.size());

  // [START queries_and_indexes_example_4]
  Query q4 =
      new Query("Person")
          .setFilter(new FilterPredicate("lastName", FilterOperator.EQUAL, "Blair"))
          .addSort("firstName", Query.SortDirection.ASCENDING)
          .addSort("height", Query.SortDirection.ASCENDING);
  // [END queries_and_indexes_example_4]
  List<Entity> r4 = datastore.prepare(q4).asList(FetchOptions.Builder.withDefaults());
  out.printf("Got %d results from query 4.\n", r4.size());
}
 
Example #20
Source File: DatastoreUtil.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
private CompositeFilter getTestMethodFilter(String testMethodTag) {
    FilterPredicate testRunFilter = new FilterPredicate(TEST_RUN_ID, FilterOperator.EQUAL, testRunId);
    FilterPredicate method = new FilterPredicate(TEST_METHOD_TAG, FilterOperator.EQUAL, testMethodTag);
    return CompositeFilterOperator.and(testRunFilter, method);
}
 
Example #21
Source File: DownloadServlet.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet( final HttpServletRequest request, final HttpServletResponse response ) throws ServletException, IOException {
	String fileName = request.getPathInfo();
	if ( fileName != null && !fileName.isEmpty() )
		fileName = fileName.substring( 1 ); // Cut off leading slash
	
	final DownloadDescriptor downloadDescriptor = fileName == null ? null : ROUTING_MAP.get( fileName );
	
	if ( downloadDescriptor == null ) {
		LOGGER.warning( "The requested file could not be found on the server!" );
		response.sendError( HttpServletResponse.SC_NOT_FOUND, "The requested file could not be found on the server!" );
		return;
	}
	
	response.sendRedirect( downloadDescriptor.destinationdUrl );
	
	PersistenceManager pm = null;
	try {
		final String ip = request.getRemoteAddr();
		
		boolean unique = false;
		
		if ( isFileNameLoggable( fileName ) ) {
			pm = PMF.get().getPersistenceManager();
			
			// Check if IP is unique
			// Using low-level implementation due to JDO keys-only query does not count toward the "Datastore Small Ops" but instead toward "Datastore Read Ops"
			final com.google.appengine.api.datastore.Query q = new com.google.appengine.api.datastore.Query( D.class.getSimpleName() );
			q.setFilter( CompositeFilterOperator.and(
				new FilterPredicate( "f", FilterOperator.EQUAL, fileName ),
				new FilterPredicate( "i", FilterOperator.EQUAL, ip       ) )
			);
			unique = ServerUtils.isQueryResultEmpty( q );
			
			// Log download
			final D d = new D();
			d.setF( fileName );
			d.setI( ip );
			d.setU( ServerUtils.checkUserAgent( request.getHeader( "User-Agent" ) ) );
			d.setC( ServerUtils.getLocationString( request ) );
			
			pm.makePersistent( d );
		}
		
		// Update download stats
		TaskServlet.register_updateDownloadStat( fileName, request.getHeader( "User-Agent" ), unique, downloadDescriptor.counterPersistingCycle );
		
	} catch ( final Exception e ) {
		// Don't let exceptions get away, still send back the redirect
		LOGGER.log( Level.SEVERE, "Exception logging the download, still proceeding...", e );
		e.printStackTrace();
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example #22
Source File: ServerUtils.java    From sc2gears with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the key of the single entity result of a query
 * constructed from the specified entity class and 2 equality filters with the specified property names and values,
 * connected with logical AND.
 * 
 * @param q query whose single entity result's key to be returned
 * @param entityClass entity class to construct the query
 * @param propName1   first property name to construct an equality filter for
 * @param propValue1  first value of the specified property to filter for
 * @param propName2   second property name to construct an equality filter for
 * @param propValue2  second value of the specified property to filter for
 * 
 * @return the key of the single entity result of the constructed query; or <code>null</code> if the query result is empty
 */
public static Key getSingleKeyQueryResult( final Class< ? > entityClass, final String propName1, final Object propValue1, final String propName2, final Object propValue2 ) {
	final com.google.appengine.api.datastore.Query q = new com.google.appengine.api.datastore.Query( entityClass.getSimpleName() );
	q.setFilter( CompositeFilterOperator.and(
			new com.google.appengine.api.datastore.Query.FilterPredicate( propName1, FilterOperator.EQUAL, propValue1 ),
			new com.google.appengine.api.datastore.Query.FilterPredicate( propName2, FilterOperator.EQUAL, propValue2 )
	) );
	
	return getSingleKeyQueryResult( q );
}