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

The following examples show how to use org.apache.olingo.server.api.uri.queryoption.OrderByItem. 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: 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 #2
Source File: DebugTabUri.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void appendOrderByItemsJson(final JsonGenerator gen, final List<OrderByItem> orders) throws IOException {
  gen.writeStartArray();
  for (final OrderByItem item : orders) {
    gen.writeStartObject();
    gen.writeStringField("nodeType", "order");
    gen.writeStringField("sortorder", item.isDescending() ? "desc" : "asc");
    gen.writeFieldName("expression");
    appendExpressionJson(gen, item.getExpression());
    gen.writeEndObject();
  }
  gen.writeEndArray();
}
 
Example #3
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 #4
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 #5
Source File: OrderByOptionImpl.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public List<OrderByItem> getOrders() {
  return Collections.unmodifiableList(orders);
}
 
Example #6
Source File: OrderByOptionImpl.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
public OrderByOptionImpl addOrder(final OrderByItem order) {
  orders.add(order);
  return this;
}
 
Example #7
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 #8
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;
  }