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

The following examples show how to use org.apache.olingo.server.api.uri.queryoption.OrderByOption. 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: OrderByHandler.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static void applyOrderByOption(final OrderByOption orderByOption, final EntityCollection entitySet,
    final UriInfoResource uriInfo, final Edm edm) throws ODataApplicationException {

  if (orderByOption == null) {
    return;
  }

  try {
    applyOrderByOptionInternal(orderByOption, entitySet, uriInfo, edm);
  } catch (SystemQueryOptionsRuntimeException e) {
    if (e.getCause() instanceof ODataApplicationException) {
      // Throw the nested exception, to send the correct HTTP status code in the HTTP response
      throw (ODataApplicationException) e.getCause();
    } else {
      throw new ODataApplicationException("Exception in orderBy evaluation",
          HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ROOT);
    }
  }
}
 
Example #2
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 #3
Source File: Parser.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void parseOrderByOption(OrderByOption orderByOption, final EdmType contextType,
    final List<String> entitySetNames, final Map<String, AliasQueryOption> aliases)
    throws UriParserException, UriValidationException {
  if (orderByOption != null) {
    final String optionValue = orderByOption.getText();
    UriTokenizer orderByTokenizer = new UriTokenizer(optionValue);
    final OrderByOption option = new OrderByParser(edm, odata).parse(orderByTokenizer,
        contextType instanceof EdmStructuredType ? (EdmStructuredType) contextType : null,
        entitySetNames,
        aliases);
    checkOptionEOF(orderByTokenizer, orderByOption.getName(), optionValue);
    for (final OrderByItem item : option.getOrders()) {
      ((OrderByOptionImpl) orderByOption).addOrder(item);
    }
  }
}
 
Example #4
Source File: OrderByParser.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public OrderByOption parse(UriTokenizer tokenizer, final EdmStructuredType referencedType,
    final Collection<String> crossjoinEntitySetNames, final Map<String, AliasQueryOption> aliases)
    throws UriParserException, UriValidationException {
  OrderByOptionImpl orderByOption = new OrderByOptionImpl();
  do {
    final Expression orderByExpression = new ExpressionParser(edm, odata)
        .parse(tokenizer, referencedType, crossjoinEntitySetNames, aliases);
    OrderByItemImpl item = new OrderByItemImpl();
    item.setExpression(orderByExpression);
    if (tokenizer.next(TokenKind.AscSuffix)) {
      item.setDescending(false);
    } else if (tokenizer.next(TokenKind.DescSuffix)) {
      item.setDescending(true);
    }
    orderByOption.addOrder(item);
  } while (tokenizer.next(TokenKind.COMMA));
  return orderByOption;
}
 
Example #5
Source File: ExpandValidator.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public FilterValidator goOrder(final int index) {
  final OrderByOption orderBy = expandItem.getOrderByOption();
  return new FilterValidator()
      .setValidator(this)
      .setEdm(edm)
      .setExpression(orderBy.getOrders().get(index).getExpression());
}
 
Example #6
Source File: QueryHandler.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * This method applies order by option query to the given entity collection.
 *
 * @param orderByOption    Order by option
 * @param entitySet        Entity Set
 * @param edmBindingTarget Binding Target
 */
public static void applyOrderByOption(final OrderByOption orderByOption, final EntityCollection entitySet,
                                      final EdmBindingTarget edmBindingTarget) {
    Collections.sort(entitySet.getEntities(), new Comparator<Entity>() {
        @Override
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public int compare(final Entity e1, final Entity e2) {
            // Evaluate the first order option for both entity
            // If and only if the result of the previous order option is equals to 0
            // evaluate the next order option until all options are evaluated or they are not equals
            int result = 0;
            for (int i = 0; i < orderByOption.getOrders().size() && result == 0; i++) {
                try {
                    final OrderByItem item = orderByOption.getOrders().get(i);
                    final TypedOperand op1 = item.getExpression()
                                                 .accept(new ExpressionVisitorImpl(e1, edmBindingTarget))
                                                 .asTypedOperand();
                    final TypedOperand op2 = item.getExpression()
                                                 .accept(new ExpressionVisitorImpl(e2, edmBindingTarget))
                                                 .asTypedOperand();
                    if (op1.isNull() || op2.isNull()) {
                        if (op1.isNull() && op2.isNull()) {
                            result = 0; // null is equals to null
                        } else {
                            result = op1.isNull() ? -1 : 1;
                        }
                    } else {
                        Object o1 = op1.getValue();
                        Object o2 = op2.getValue();

                        if (o1.getClass() == o2.getClass() && o1 instanceof Comparable) {
                            result = ((Comparable) o1).compareTo(o2);
                        } else {
                            result = 0;
                        }
                    }
                    result = item.isDescending() ? result * -1 : result;
                } catch (ExpressionVisitException | ODataApplicationException e) {
                    throw new RuntimeException(e);
                }
            }
            return result;
        }
    });
}
 
Example #7
Source File: ProductsEntityCollectionProcessor.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private static void applyOrderby(UriInfo uriInfo, EntityCollection entityCollection) {
    List<Entity> entityList = entityCollection.getEntities();

    OrderByOption orderByOption = uriInfo.getOrderByOption();
    if (orderByOption == null) {
        return;
    }

    List<OrderByItem> orderItemList = orderByOption.getOrders();
    OrderByItem orderByItem = orderItemList.get(0); // in our example we support only one
    Expression expression = orderByItem.getExpression();
    if (! (expression instanceof Member)) {
        return;
    }

    UriInfoResource resourcePath = ((Member)expression).getResourcePath();
    UriResource uriResource = resourcePath.getUriResourceParts().get(0);
    if (! (uriResource instanceof UriResourcePrimitiveProperty)) {
        return;
    }

    EdmProperty edmProperty = ((UriResourcePrimitiveProperty)uriResource).getProperty();
    String sortPropertyName = edmProperty.getName();

    // do the sorting for the list of entities
    Collections.sort(entityList, new Comparator<Entity>() {

        // we delegate the sorting to the native sorter of Integer and String
        @Override
        public int compare(Entity entity1, Entity entity2) {
            int compareResult = 0;

            if (sortPropertyName.equals("ID")) {
                Integer integer1 = (Integer)entity1.getProperty(sortPropertyName).getValue();
                Integer integer2 = (Integer)entity2.getProperty(sortPropertyName).getValue();
                compareResult = integer1.compareTo(integer2);
            } else {
                String propertyValue1 = (String)entity1.getProperty(sortPropertyName).getValue();
                String propertyValue2 = (String)entity2.getProperty(sortPropertyName).getValue();
                compareResult = propertyValue1.compareTo(propertyValue2);
            }

            // if 'desc' is specified in the URI, change the order of the list
            if (orderByItem.isDescending()) {
                return -compareResult; // just convert the result to negative value to change the order
            }

            return compareResult;
        }
    });
}
 
Example #8
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 #9
Source File: ExpandItemImpl.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public OrderByOption getOrderByOption() {
  return orderByOption;
}
 
Example #10
Source File: UriInfoImpl.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public OrderByOption getOrderByOption() {
  return (OrderByOption) systemQueryOptions.get(SystemQueryOptionKind.ORDERBY);
}
 
Example #11
Source File: RequestURLHierarchyVisitor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(OrderByOption option) {
}
 
Example #12
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);
	List<Entity> entityList = entityCollection.getEntities();
	
	// 3rd apply $orderby
	OrderByOption orderByOption = uriInfo.getOrderByOption();
	if (orderByOption != null) {
		List<OrderByItem> orderItemList = orderByOption.getOrders();
		final OrderByItem orderByItem = orderItemList.get(0); // in our example we support only one
		Expression expression = orderByItem.getExpression();
		if(expression instanceof Member){
			UriInfoResource resourcePath = ((Member)expression).getResourcePath();
			UriResource uriResource = resourcePath.getUriResourceParts().get(0);
			if (uriResource instanceof UriResourcePrimitiveProperty) {
				EdmProperty edmProperty = ((UriResourcePrimitiveProperty)uriResource).getProperty();
				final String sortPropertyName = edmProperty.getName();

				// do the sorting for the list of entities  
				Collections.sort(entityList, new Comparator<Entity>() {

					// we delegate the sorting to the native sorter of Integer and String
					public int compare(Entity entity1, Entity entity2) {
						int compareResult = 0;

						if(sortPropertyName.equals("ID")){
							Integer integer1 = (Integer) entity1.getProperty(sortPropertyName).getValue();
							Integer integer2 = (Integer) entity2.getProperty(sortPropertyName).getValue();
							
							compareResult = integer1.compareTo(integer2);
						}else{
							String propertyValue1 = (String) entity1.getProperty(sortPropertyName).getValue();
							String propertyValue2 = (String) entity2.getProperty(sortPropertyName).getValue();
							
							compareResult = propertyValue1.compareTo(propertyValue2);
						}

						// if 'desc' is specified in the URI, change the order of the list 
						if(orderByItem.isDescending()){
							return - compareResult; // just convert the result to negative value to change the order
						}
						
						return compareResult;
					}
				});
			}
		}
	}
	
	
	// 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().id(id).contextURL(contextUrl).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 #13
Source File: DemoEntityCollectionProcessor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private List<Entity> applyOrderQueryOption(List<Entity> entityList, OrderByOption orderByOption) {

    if (orderByOption != null) {
      List<OrderByItem> orderItemList = orderByOption.getOrders();
      final OrderByItem orderByItem = orderItemList.get(0); // in our example we support only one
      Expression expression = orderByItem.getExpression();
      if (expression instanceof Member) {
        UriInfoResource resourcePath = ((Member) expression).getResourcePath();
        UriResource uriResource = resourcePath.getUriResourceParts().get(0);
        if (uriResource instanceof UriResourcePrimitiveProperty) {
          EdmProperty edmProperty = ((UriResourcePrimitiveProperty) uriResource).getProperty();
          final String sortPropertyName = edmProperty.getName();

          // do the sorting for the list of entities  
          Collections.sort(entityList, new Comparator<Entity>() {

            // we delegate the sorting to the native sorter of Integer and String
            public int compare(Entity entity1, Entity entity2) {
              int compareResult = 0;

              if (sortPropertyName.equals("ID")) {
                Integer integer1 = (Integer) entity1.getProperty(sortPropertyName).getValue();
                Integer integer2 = (Integer) entity2.getProperty(sortPropertyName).getValue();

                compareResult = integer1.compareTo(integer2);
              } else {
                String propertyValue1 = (String) entity1.getProperty(sortPropertyName).getValue();
                String propertyValue2 = (String) entity2.getProperty(sortPropertyName).getValue();

                compareResult = propertyValue1.compareTo(propertyValue2);
              }

              // if 'desc' is specified in the URI, change the order of the list 
              if (orderByItem.isDescending()) {
                return -compareResult; // just convert the result to negative value to change the order
              }

              return compareResult;
            }
          });
        }
      }
    }
    
    return entityList;
  }
 
Example #14
Source File: UriInfoResource.java    From olingo-odata4 with Apache License 2.0 2 votes vote down vote up
/**
 * @return Object containing information of the $orderby option
 */
OrderByOption getOrderByOption();
 
Example #15
Source File: UriInfoCrossjoin.java    From olingo-odata4 with Apache License 2.0 2 votes vote down vote up
/**
 * @return Object containing information of the $orderby option
 */
OrderByOption getOrderByOption();
 
Example #16
Source File: RequestURLVisitor.java    From olingo-odata4 with Apache License 2.0 votes vote down vote up
void visit(OrderByOption option);