Java源码示例:org.apache.olingo.server.api.uri.queryoption.FilterOption

示例1
/**
 * 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);
    }
}
 
示例2
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);
    }
  }
}
 
示例3
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);
  }
}
 
示例4
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());
  }
}
 
示例5
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);
  }
}
 
示例6
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;
}
 
示例7
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;
}
 
示例8
public static String Serialize(final FilterOption filter)
    throws ExpressionVisitException, ODataApplicationException {

  Expression expression = filter.getExpression();
  return expression.accept(new FilterTreeToText());
}
 
示例9
public FilterValidator setFilter(final FilterOption filter) {
  this.filter = filter;
  assertNotNull("FilterValidator: no filter found", filter.getExpression());
  setExpression(filter.getExpression());
  return this;
}
 
示例10
public FilterValidator goFilter() {
  final FilterOption filter = uriInfo.getFilterOption();
  assertNotNull("no filter found", filter);
  return new FilterValidator().setValidator(this).setFilter(filter);
}
 
示例11
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());
  }
}
 
示例12
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);
    }
  }
}
 
示例13
@Override
public FilterOption getFilterOption() {
  return filterOption;
}
 
示例14
public FilterImpl setFilterOption(final FilterOption filterOption) {
  this.filterOption = filterOption;
  return this;
}
 
示例15
@Override
public FilterOption getFilterOption() {
  return filterOption;
}
 
示例16
@Override
public FilterOption getFilterOption() {
  return (FilterOption) systemQueryOptions.get(SystemQueryOptionKind.FILTER);
}
 
示例17
@Override
public void visit(FilterOption info) {
}
 
示例18
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());
}
 
示例19
/**
 * Gets the filter option.
 * @return a {@link FilterOption} (but never <code>null</code>)
 */
FilterOption getFilterOption();
 
示例20
/**
 * @return Object containing information of the $filter option
 */
FilterOption getFilterOption();
 
示例21
/**
 * @return Object containing information of the $filter option
 */
FilterOption getFilterOption();
 
示例22
void visit(FilterOption info);