org.apache.olingo.server.api.uri.queryoption.FilterOption Java Examples

The following examples show how to use org.apache.olingo.server.api.uri.queryoption.FilterOption. 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: ExpandSystemQueryOptionHandler.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void applyOptionsToEntityCollection(final EntityCollection entitySet,
    final EdmBindingTarget edmBindingTarget,
    final FilterOption filterOption, final OrderByOption orderByOption, final CountOption countOption,
    final SkipOption skipOption, final TopOption topOption, final ExpandOption expandOption,
    final UriInfoResource uriInfo, final Edm edm)
    throws ODataApplicationException {

  FilterHandler.applyFilterSystemQuery(filterOption, entitySet, uriInfo, edm);
  OrderByHandler.applyOrderByOption(orderByOption, entitySet, uriInfo, edm);
  CountHandler.applyCountSystemQueryOption(countOption, entitySet);
  SkipHandler.applySkipSystemQueryHandler(skipOption, entitySet);
  TopHandler.applyTopSystemQueryOption(topOption, entitySet);

  // Apply nested expand system query options to remaining entities
  if (expandOption != null) {
    for (final Entity entity : entitySet.getEntities()) {
      applyExpandOptionToEntity(entity, edmBindingTarget, expandOption, uriInfo, edm);
    }
  }
}
 
Example #2
Source File: QueryHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * This method applies filter query option to the given entity collection.
 *
 * @param filterOption Filter option
 * @param entitySet    Entity collection
 * @param edmEntitySet Entity set
 * @throws ODataApplicationException
 */
public static void applyFilterSystemQuery(final FilterOption filterOption, final EntityCollection entitySet,
                                          final EdmBindingTarget edmEntitySet) throws ODataApplicationException {
    try {
        final Iterator<Entity> iter = entitySet.getEntities().iterator();
        while (iter.hasNext()) {
            final VisitorOperand operand =
                    filterOption.getExpression().accept(new ExpressionVisitorImpl(iter.next(), edmEntitySet));
            final TypedOperand typedOperand = operand.asTypedOperand();

            if (typedOperand.is(ODataConstants.primitiveBoolean)) {
                if (Boolean.FALSE.equals(typedOperand.getTypedValue(Boolean.class))) {
                    iter.remove();
                }
            } else {
                throw new ODataApplicationException(
                        "Invalid filter expression. Filter expressions must return a value of " +
                        "type Edm.Boolean", HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ROOT);
            }
        }

    } catch (ExpressionVisitException e) {
        throw new ODataApplicationException("Exception in filter evaluation",
                                            HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ROOT);
    }
}
 
Example #3
Source File: FilterParser.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public FilterOption parse(UriTokenizer tokenizer, final EdmType referencedType,
    final Collection<String> crossjoinEntitySetNames, final Map<String, AliasQueryOption> aliases)
    throws UriParserException, UriValidationException {
  final Expression filterExpression = new ExpressionParser(edm, odata)
      .parse(tokenizer, referencedType, crossjoinEntitySetNames, aliases);
  final EdmType type = ExpressionParser.getType(filterExpression);
  if (type == null || type.equals(odata.createPrimitiveTypeInstance(EdmPrimitiveTypeKind.Boolean))) {
    return new FilterOptionImpl().setExpression(filterExpression);
  } else {
    throw new UriParserSemanticException("Filter expressions must be boolean.",
        UriParserSemanticException.MessageKeys.TYPES_NOT_COMPATIBLE,
        "Edm.Boolean", type.getFullQualifiedName().getFullQualifiedNameAsString());
  }
}
 
Example #4
Source File: DemoEntityCollectionProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private List<Entity> applyFilterQueryOption(List<Entity> entityList, FilterOption filterOption)
    throws ODataApplicationException {

  if (filterOption != null) {
    try {
      Iterator<Entity> entityIterator = entityList.iterator();

      // Evaluate the expression for each entity
      // If the expression is evaluated to "true", keep the entity otherwise remove it from the entityList
      while (entityIterator.hasNext()) {
        // To evaluate the the expression, create an instance of the Filter Expression Visitor and pass
        // the current entity to the constructor
        Entity currentEntity = entityIterator.next();
        Expression filterExpression = filterOption.getExpression();
        FilterExpressionVisitor expressionVisitor = new FilterExpressionVisitor(currentEntity);

        // Start evaluating the expression
        Object visitorResult = filterExpression.accept(expressionVisitor);

        // The result of the filter expression must be of type Edm.Boolean
        if (visitorResult instanceof Boolean) {
          if (!Boolean.TRUE.equals(visitorResult)) {
            // The expression evaluated to false (or null), so we have to remove the currentEntity from entityList
            entityIterator.remove();
          }
        } else {
          throw new ODataApplicationException("A filter expression must evaulate to type Edm.Boolean",
              HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ENGLISH);
        }
      }

    } catch (ExpressionVisitException e) {
      throw new ODataApplicationException("Exception in filter evaluation",
          HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ENGLISH);
    }
  }
  
  return entityList;
}
 
Example #5
Source File: Parser.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void parseFilterOption(FilterOption filterOption, final EdmType contextType,
    final List<String> entitySetNames, final Map<String, AliasQueryOption> aliases)
    throws UriParserException, UriValidationException {
  if (filterOption != null) {
    final String optionValue = filterOption.getText();
    UriTokenizer filterTokenizer = new UriTokenizer(optionValue);
    // The referring type could be a primitive type or a structured type.
    ((FilterOptionImpl) filterOption).setExpression(
        new FilterParser(edm, odata).parse(filterTokenizer, contextType, entitySetNames, aliases)
            .getExpression());
    checkOptionEOF(filterTokenizer, filterOption.getName(), optionValue);
  }
}
 
Example #6
Source File: FilterHandler.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public static void applyFilterSystemQuery(final FilterOption filterOption, final EntityCollection entitySet,
    final UriInfoResource uriInfo, final Edm edm) throws ODataApplicationException {

  if (filterOption == null) {
    return;
  }

  try {
    final Iterator<Entity> iter = entitySet.getEntities().iterator();

    while (iter.hasNext()) {
      final VisitorOperand operand = filterOption.getExpression()
          .accept(new ExpressionVisitorImpl(iter.next(), uriInfo, edm));
      final TypedOperand typedOperand = operand.asTypedOperand();

      if (typedOperand.is(primBoolean)) {
        if (Boolean.FALSE.equals(typedOperand.getTypedValue(Boolean.class))) {
          iter.remove();
        }
      } else {
        throw new ODataApplicationException(
            "Invalid filter expression. Filter expressions must return a value of type Edm.Boolean",
            HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ROOT);
      }
    }

  } catch (ExpressionVisitException e) {
    throw new ODataApplicationException("Exception in filter evaluation",
        HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ROOT);
  }
}
 
Example #7
Source File: ApplyParser.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private ApplyItem parseTrafo(EdmStructuredType referencedType) throws UriParserException, UriValidationException {
  if (tokenizer.next(TokenKind.AggregateTrafo)) {
    return parseAggregateTrafo(referencedType);

  } else if (tokenizer.next(TokenKind.IDENTITY)) {
    return new IdentityImpl();

  } else if (tokenizer.next(TokenKind.ComputeTrafo)) {
    return parseComputeTrafo(referencedType);

  } else if (tokenizer.next(TokenKind.ConcatMethod)) {
    return parseConcatTrafo(referencedType);

  } else if (tokenizer.next(TokenKind.ExpandTrafo)) {
    return new ExpandImpl().setExpandOption(parseExpandTrafo(referencedType));

  } else if (tokenizer.next(TokenKind.FilterTrafo)) {
    final FilterOption filterOption = new FilterParser(edm, odata)
        .parse(tokenizer, referencedType, crossjoinEntitySetNames, aliases);
    ParserHelper.requireNext(tokenizer, TokenKind.CLOSE);
    return new FilterImpl().setFilterOption(filterOption);

  } else if (tokenizer.next(TokenKind.GroupByTrafo)) {
    return parseGroupByTrafo(referencedType);

  } else if (tokenizer.next(TokenKind.SearchTrafo)) {
    final SearchOption searchOption = new SearchParser().parse(tokenizer);
    ParserHelper.requireNext(tokenizer, TokenKind.CLOSE);
    return new SearchImpl().setSearchOption(searchOption);

  } else if (tokenizer.next(TokenKind.QualifiedName)) {
    return parseCustomFunction(new FullQualifiedName(tokenizer.getText()), referencedType);

  } else {
    final TokenKind kind = ParserHelper.next(tokenizer,
        TokenKind.BottomCountTrafo, TokenKind.BottomPercentTrafo, TokenKind.BottomSumTrafo,
        TokenKind.TopCountTrafo, TokenKind.TopPercentTrafo, TokenKind.TopSumTrafo);
    if (kind == null) {
      throw new UriParserSyntaxException("Invalid apply expression syntax.",
          UriParserSyntaxException.MessageKeys.SYNTAX);
    } else {
      return parseBottomTop(kind, referencedType);
    }
  }
}
 
Example #8
Source File: ProductsEntityCollectionProcessor.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private static EntityCollection applyQueryOptions(UriInfo uriInfo, List<Entity> entityList, EntityCollection returnEntityCollection) throws ODataApplicationException {
    // handle $skip
    SkipOption skipOption = uriInfo.getSkipOption();
    if (skipOption != null) {
        int skipNumber = skipOption.getValue();
        if (skipNumber >= 0) {
            if (skipNumber <= entityList.size()) {
                entityList = entityList.subList(skipNumber, entityList.size());
            } else {
                // The client skipped all entities
                entityList.clear();
            }
        } else {
            throw new ODataApplicationException("Invalid value for $skip", HttpStatusCode.BAD_REQUEST.getStatusCode(),
                                                Locale.ROOT);
        }
    }

    // handle $top
    TopOption topOption = uriInfo.getTopOption();
    if (topOption != null) {
        int topNumber = topOption.getValue();
        if (topNumber >= 0) {
            if (topNumber <= entityList.size()) {
                entityList = entityList.subList(0, topNumber);
            } // else the client has requested more entities than available => return what we have
        } else {
            throw new ODataApplicationException("Invalid value for $top", HttpStatusCode.BAD_REQUEST.getStatusCode(),
                                                Locale.ROOT);
        }
    }

    // handle $filter
    FilterOption filterOption = uriInfo.getFilterOption();
    if(filterOption != null) {
        // Apply $filter system query option
        try {
              Iterator<Entity> entityIterator = entityList.iterator();

              // Evaluate the expression for each entity
              // If the expression is evaluated to "true", keep the entity otherwise remove it from the entityList
              while (entityIterator.hasNext()) {
                  // To evaluate the the expression, create an instance of the Filter Expression Visitor and pass
                  // the current entity to the constructor
                  Entity currentEntity = entityIterator.next();
                  Expression filterExpression = filterOption.getExpression();
                  FilterExpressionVisitor expressionVisitor = new FilterExpressionVisitor(currentEntity);

                  // Start evaluating the expression
                  Object visitorResult = filterExpression.accept(expressionVisitor);

                  // The result of the filter expression must be of type Edm.Boolean
                  if(visitorResult instanceof Boolean) {
                      if(!Boolean.TRUE.equals(visitorResult)) {
                        // The expression evaluated to false (or null), so we have to remove the currentEntity from entityList
                        entityIterator.remove();
                      }
                  } else {
                      throw new ODataApplicationException("A filter expression must evaulate to type Edm.Boolean",
                          HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ENGLISH);
                  }
              }

            } catch (ExpressionVisitException e) {
              throw new ODataApplicationException("Exception in filter evaluation",
                  HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ENGLISH, e);
            }
    }

    // after applying the system query options, create the EntityCollection based on the reduced list
    for (Entity entity : entityList) {
        returnEntityCollection.getEntities().add(entity);
    }

    // apply $orderby
    applyOrderby(uriInfo, returnEntityCollection);

    return returnEntityCollection;
}
 
Example #9
Source File: DemoEntityCollectionProcessor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
public void readEntityCollection(ODataRequest request, ODataResponse response, UriInfo uriInfo, 
    ContentType responseFormat) throws ODataApplicationException, SerializerException {

	// 1st: retrieve the requested EntitySet from the uriInfo (representation of the parsed URI)
	List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
	// in our example, the first segment is the EntitySet
	UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0); 
	EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();

	// 2nd: fetch the data from backend for this requested EntitySetName and deliver as EntitySet
	EntityCollection entityCollection = storage.readEntitySetData(edmEntitySet);
	
	// 3rd: Check if filter system query option is provided and apply the expression if necessary
	FilterOption filterOption = uriInfo.getFilterOption();
	if(filterOption != null) {
		// Apply $filter system query option
		try {
		      List<Entity> entityList = entityCollection.getEntities();
		      Iterator<Entity> entityIterator = entityList.iterator();
		      
		      // Evaluate the expression for each entity
		      // If the expression is evaluated to "true", keep the entity otherwise remove it from the entityList
		      while (entityIterator.hasNext()) {
		    	  // To evaluate the the expression, create an instance of the Filter Expression Visitor and pass
		    	  // the current entity to the constructor
		    	  Entity currentEntity = entityIterator.next();
		    	  Expression filterExpression = filterOption.getExpression();
		    	  FilterExpressionVisitor expressionVisitor = new FilterExpressionVisitor(currentEntity);
		    	  
		    	  // Start evaluating the expression
		    	  Object visitorResult = filterExpression.accept(expressionVisitor);
		    	  
		    	  // The result of the filter expression must be of type Edm.Boolean
		    	  if(visitorResult instanceof Boolean) {
		    		  if(!Boolean.TRUE.equals(visitorResult)) {
		    		    // The expression evaluated to false (or null), so we have to remove the currentEntity from entityList
		    		    entityIterator.remove();
		    		  }
		    	  } else {
		    		  throw new ODataApplicationException("A filter expression must evaulate to type Edm.Boolean", 
		    		      HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ENGLISH);
		    	  }
		      }

		    } catch (ExpressionVisitException e) {
		      throw new ODataApplicationException("Exception in filter evaluation",
		          HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ENGLISH);
		    }
	}
	
	// 4th: create a serializer based on the requested format (json)
	ODataSerializer serializer = odata.createSerializer(responseFormat);

	// and serialize the content: transform from the EntitySet object to InputStream
	EdmEntityType edmEntityType = edmEntitySet.getEntityType();
	ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).build();

	final String id = request.getRawBaseUri() + "/" + edmEntitySet.getName();
	EntityCollectionSerializerOptions opts = EntityCollectionSerializerOptions.with()
			.contextURL(contextUrl).id(id).build();
	SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, edmEntityType, entityCollection,
			opts);

	InputStream serializedContent = serializerResult.getContent();

	// 5th: configure the response object: set the body, headers and status code
	response.setContent(serializedContent);
	response.setStatusCode(HttpStatusCode.OK.getStatusCode());
	response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example #10
Source File: RequestURLHierarchyVisitor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(FilterOption info) {
}
 
Example #11
Source File: UriInfoImpl.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public FilterOption getFilterOption() {
  return (FilterOption) systemQueryOptions.get(SystemQueryOptionKind.FILTER);
}
 
Example #12
Source File: ExpandItemImpl.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public FilterOption getFilterOption() {
  return filterOption;
}
 
Example #13
Source File: FilterImpl.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
public FilterImpl setFilterOption(final FilterOption filterOption) {
  this.filterOption = filterOption;
  return this;
}
 
Example #14
Source File: FilterImpl.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public FilterOption getFilterOption() {
  return filterOption;
}
 
Example #15
Source File: FilterValidator.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
public FilterValidator setFilter(final FilterOption filter) {
  this.filter = filter;
  assertNotNull("FilterValidator: no filter found", filter.getExpression());
  setExpression(filter.getExpression());
  return this;
}
 
Example #16
Source File: FilterTreeToText.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
public static String Serialize(final FilterOption filter)
    throws ExpressionVisitException, ODataApplicationException {

  Expression expression = filter.getExpression();
  return expression.accept(new FilterTreeToText());
}
 
Example #17
Source File: DebugTabUri.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private void appendCommonJsonObjects(JsonGenerator gen,
    final CountOption countOption, final SkipOption skipOption, final TopOption topOption,
    final FilterOption filterOption, final OrderByOption orderByOption,
    final SelectOption selectOption, final ExpandOption expandOption, final SearchOption searchOption,
    final ApplyOption applyOption)
    throws IOException {
  if (countOption != null) {
    gen.writeBooleanField("isCount", countOption.getValue());
  }

  if (skipOption != null) {
    gen.writeNumberField("skip", skipOption.getValue());
  }

  if (topOption != null) {
    gen.writeNumberField("top", topOption.getValue());
  }

  if (filterOption != null) {
    gen.writeFieldName("filter");
    appendExpressionJson(gen, filterOption.getExpression());
  }

  if (orderByOption != null && !orderByOption.getOrders().isEmpty()) {
    gen.writeFieldName("orderby");
    gen.writeStartObject();
    gen.writeStringField("nodeType", "orderCollection");
    gen.writeFieldName("orders");
    appendOrderByItemsJson(gen, orderByOption.getOrders());
    gen.writeEndObject();
  }

  if (selectOption != null && !selectOption.getSelectItems().isEmpty()) {
    gen.writeFieldName("select");
    appendSelectedPropertiesJson(gen, selectOption.getSelectItems());
  }

  if (expandOption != null && !expandOption.getExpandItems().isEmpty()) {
    gen.writeFieldName("expand");
    appendExpandedPropertiesJson(gen, expandOption.getExpandItems());
  }

  if (searchOption != null) {
    gen.writeFieldName("search");
    appendSearchJson(gen, searchOption.getSearchExpression());
  }

  if (applyOption != null) {
    gen.writeFieldName("apply");
    appendApplyItemsJson(gen, applyOption.getApplyItems());
  }
}
 
Example #18
Source File: TestUriValidator.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
public FilterValidator goFilter() {
  final FilterOption filter = uriInfo.getFilterOption();
  assertNotNull("no filter found", filter);
  return new FilterValidator().setValidator(this).setFilter(filter);
}
 
Example #19
Source File: UriInfoCrossjoin.java    From olingo-odata4 with Apache License 2.0 2 votes vote down vote up
/**
 * @return Object containing information of the $filter option
 */
FilterOption getFilterOption();
 
Example #20
Source File: UriInfoResource.java    From olingo-odata4 with Apache License 2.0 2 votes vote down vote up
/**
 * @return Object containing information of the $filter option
 */
FilterOption getFilterOption();
 
Example #21
Source File: Filter.java    From olingo-odata4 with Apache License 2.0 2 votes vote down vote up
/**
 * Gets the filter option.
 * @return a {@link FilterOption} (but never <code>null</code>)
 */
FilterOption getFilterOption();
 
Example #22
Source File: RequestURLVisitor.java    From olingo-odata4 with Apache License 2.0 votes vote down vote up
void visit(FilterOption info);