Java Code Examples for org.apache.olingo.commons.api.data.EntityCollection#getEntities()

The following examples show how to use org.apache.olingo.commons.api.data.EntityCollection#getEntities() . 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: Util.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet,
    List<UriParameter> keyParams) throws ODataApplicationException {

  List<Entity> entityList = entitySet.getEntities();

  // loop over all entities in order to find that one that matches
  // all keys in request e.g. contacts(ContactID=1, CompanyID=1)
  for (Entity entity : entityList) {
    boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
    if (foundEntity) {
      return entity;
    }
  }

  return null;
}
 
Example 2
Source File: TripPinDataModel.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private EntityCollection getEvents(int tripId, EntityCollection result) {
  Map<String, Object> map = this.tripLinks.get(tripId);
  if (map == null) {
    return null;
  }

  ArrayList<Integer> events = (ArrayList<Integer>) map.get("Events");
  EntityCollection set = getEntitySet("Event");
  int i = result.getEntities().size();
  if (events != null) {
    for (int event : events) {
      for (Entity e : set.getEntities()) {
        if (e.getProperty("PlanItemId").getValue().equals(event)) {
          result.getEntities().add(e);
          i++;
          break;
        }
      }
    }
  }
  result.setCount(i);
  return result;
}
 
Example 3
Source File: Util.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet,
    List<UriParameter> keyParams) {

  List<Entity> entityList = entitySet.getEntities();

  // loop over all entities in order to find that one that matches
  // all keys in request e.g. contacts(ContactID=1, CompanyID=1)
  for (Entity entity : entityList) {
    boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
    if (foundEntity) {
      return entity;
    }
  }

  return null;
}
 
Example 4
Source File: TripPinDataModel.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private EntityCollection getFlights(int tripId, EntityCollection result) {
  Map<String, Object> map = this.tripLinks.get(tripId);
  if (map == null) {
    return null;
  }

  ArrayList<Integer> flights = (ArrayList<Integer>) map.get("Flights");
  EntityCollection set = getEntitySet("Flight");
  int i = result.getEntities().size();
  if (flights != null) {
    for (int flight : flights) {
      for (Entity e : set.getEntities()) {
        if (e.getProperty("PlanItemId").getValue().equals(flight)) {
          result.getEntities().add(e);
          i++;
          break;
        }
      }
    }
  }
  result.setCount(i);
  return result;
}
 
Example 5
Source File: TripPinDataModel.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public EntityCollection getEntitySet(String name, int skip, int pageSize) {
  EntityCollection set = this.entitySetMap.get(name);
  if (set == null) {
    return null;
  }

  EntityCollection modifiedES = new EntityCollection();
  int i = 0;
  for (Entity e : set.getEntities()) {
    if (skip >= 0 && i >= skip && modifiedES.getEntities().size() < pageSize) {
      modifiedES.getEntities().add(e);
    }
    i++;
  }
  modifiedES.setCount(i);
  set.setCount(i);

  if (skip == -1 && pageSize == -1) {
    return set;
  }
  return modifiedES;
}
 
Example 6
Source File: Util.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet,
                                List<UriParameter> keyParams) throws ODataApplicationException {

  List<Entity> entityList = entitySet.getEntities();

  // loop over all entities in order to find that one that matches all keys in request
  // e.g. contacts(ContactID=1, CompanyID=1)
  for (Entity entity: entityList) {
    boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
    if (foundEntity) {
      return entity;
    }
  }

  return null;
}
 
Example 7
Source File: Util.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet,
                                List<UriParameter> keyParams) throws ODataApplicationException {

  List<Entity> entityList = entitySet.getEntities();

  // loop over all entities in order to find that one that matches all keys in request
  // e.g. contacts(ContactID=1, CompanyID=1)
  for (Entity entity: entityList) {
    boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
    if (foundEntity) {
      return entity;
    }
  }

  return null;
}
 
Example 8
Source File: Util.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet,
    List<UriParameter> keyParams) throws ODataApplicationException {

  List<Entity> entityList = entitySet.getEntities();

  // loop over all entities in order to find that one that matches all keys in request
  // e.g. contacts(ContactID=1, CompanyID=1)
  for (Entity entity: entityList) {
    boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
    if (foundEntity) {
      return entity;
    }
  }

  return null;
}
 
Example 9
Source File: Util.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet,
    List<UriParameter> keyParams) throws ODataApplicationException {

  List<Entity> entityList = entitySet.getEntities();

  // loop over all entities in order to find that one that matches
  // all keys in request e.g. contacts(ContactID=1, CompanyID=1)
  for (Entity entity : entityList) {
    boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
    if (foundEntity) {
      return entity;
    }
  }

  return null;
}
 
Example 10
Source File: DataProvider.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public Entity create(final EdmEntitySet edmEntitySet) throws DataProviderException {
  final EdmEntityType edmEntityType = edmEntitySet.getEntityType();
  EntityCollection entitySet = readAll(edmEntitySet);
  final List<Entity> entities = entitySet.getEntities();
  final Map<String, Object> newKey = findFreeComposedKey(entities, edmEntityType);
  Entity newEntity = new Entity();
  newEntity.setType(edmEntityType.getFullQualifiedName().getFullQualifiedNameAsString());
  for (final String keyName : edmEntityType.getKeyPredicateNames()) {
    newEntity.addProperty(DataCreator.createPrimitive(keyName, newKey.get(keyName)));
  }

  createProperties(edmEntityType, newEntity.getProperties());
  try {
    newEntity.setId(URI.create(odata.createUriHelper().buildCanonicalURL(edmEntitySet, newEntity)));
  } catch (final SerializerException e) {
    throw new DataProviderException("Unable to set entity ID!", HttpStatusCode.INTERNAL_SERVER_ERROR, e);
  }
  entities.add(newEntity);

  return newEntity;
}
 
Example 11
Source File: DemoEntityCollectionProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method for providing some sample data
 * @param edmEntitySet for which the data is requested
 * @return data of requested entity set
 */
private EntityCollection getData(EdmEntitySet edmEntitySet){

  EntityCollection productsCollection = new EntityCollection();
  // check for which EdmEntitySet the data is requested
  if(DemoEdmProvider.ES_PRODUCTS_NAME.equals(edmEntitySet.getName())) {
    List<Entity> productList = productsCollection.getEntities();

    // add some sample product entities
    final Entity e1 = new Entity()
        .addProperty(new Property(null, "ID", ValueType.PRIMITIVE, 1))
        .addProperty(new Property(null, "Name", ValueType.PRIMITIVE, "Notebook Basic 15"))
        .addProperty(new Property(null, "Description", ValueType.PRIMITIVE,
            "Notebook Basic, 1.7GHz - 15 XGA - 1024MB DDR2 SDRAM - 40GB"));
    e1.setId(createId("Products", 1));
    productList.add(e1);

    final Entity e2 = new Entity()
        .addProperty(new Property(null, "ID", ValueType.PRIMITIVE, 2))
        .addProperty(new Property(null, "Name", ValueType.PRIMITIVE, "1UMTS PDA"))
        .addProperty(new Property(null, "Description", ValueType.PRIMITIVE,
            "Ultrafast 3G UMTS/HSDPA Pocket PC, supports GSM network"));
    e2.setId(createId("Products", 1));
    productList.add(e2);

    final Entity e3 = new Entity()
        .addProperty(new Property(null, "ID", ValueType.PRIMITIVE, 3))
        .addProperty(new Property(null, "Name", ValueType.PRIMITIVE, "Ergo Screen"))
        .addProperty(new Property(null, "Description", ValueType.PRIMITIVE,
            "19 Optimum Resolution 1024 x 768 @ 85Hz, resolution 1280 x 960"));
    e3.setId(createId("Products", 1));
    productList.add(e3);
  }

  return productsCollection;
}
 
Example 12
Source File: DataProvider.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private List<Entity> createInlineEntities(final String rawBaseUri, final EdmEntitySet targetEntitySet,
    final EntityCollection changedEntitySet) throws DataProviderException {
  List<Entity> entities = new ArrayList<Entity>();

  for (final Entity newEntity : changedEntitySet.getEntities()) {
    entities.add(createInlineEntity(rawBaseUri, targetEntitySet, newEntity));
  }

  return entities;
}
 
Example 13
Source File: DemoEntityCollectionProcessor.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method for providing some sample data
 * @param edmEntitySet for which the data is requested
 * @return data of requested entity set
 */
private EntityCollection getData(EdmEntitySet edmEntitySet) {

    EntityCollection productsCollection = new EntityCollection();
    // check for which EdmEntitySet the data is requested
    if (DemoEdmProvider.ES_PRODUCTS_NAME.equals(edmEntitySet.getName())) {
        List<Entity> productList = productsCollection.getEntities();

        // add some sample product entities
        final Entity e1 = new Entity()
                .addProperty(new Property(null, "ID", ValueType.PRIMITIVE, 1))
                .addProperty(new Property(null, "Name", ValueType.PRIMITIVE, "Notebook Basic 15"))
                .addProperty(new Property(null, "Description", ValueType.PRIMITIVE,
                        "Notebook Basic, 1.7GHz - 15 XGA - 1024MB DDR2 SDRAM - 40GB"));
        e1.setId(createId("Products", 1));
        productList.add(e1);

        final Entity e2 = new Entity()
                .addProperty(new Property(null, "ID", ValueType.PRIMITIVE, 2))
                .addProperty(new Property(null, "Name", ValueType.PRIMITIVE, "1UMTS PDA"))
                .addProperty(new Property(null, "Description", ValueType.PRIMITIVE,
                        "Ultrafast 3G UMTS/HSDPA Pocket PC, supports GSM network"));
        e2.setId(createId("Products", 1));
        productList.add(e2);

        final Entity e3 = new Entity()
                .addProperty(new Property(null, "ID", ValueType.PRIMITIVE, 3))
                .addProperty(new Property(null, "Name", ValueType.PRIMITIVE, "Ergo Screen"))
                .addProperty(new Property(null, "Description", ValueType.PRIMITIVE,
                        "19 Optimum Resolution 1024 x 768 @ 85Hz, resolution 1280 x 960"));
        e3.setId(createId("Products", 1));
        productList.add(e3);
    }

    return productsCollection;
}
 
Example 14
Source File: Util.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet, List<UriParameter> keyParams) throws ODataApplicationException {
	
	List<Entity> entityList = entitySet.getEntities();
	
	// loop over all entities in order to find that one that matches all keys in request e.g. contacts(ContactID=1, CompanyID=1) 
	for(Entity entity : entityList){
		boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
		if(foundEntity) {
			return entity;
		}
	}
	
	return null;
}
 
Example 15
Source File: DataProvider.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
public Entity readDataFromEntity(final EdmEntityType edmEntityType,
    final List<UriParameter> keys) throws DataProviderException {
  EntityCollection coll = data.get(edmEntityType.getName());
  List<Entity> entities = coll.getEntities();
  try {
    for (final Entity entity : entities) {
      boolean found = true;
      for (final UriParameter key : keys) {
        EdmKeyPropertyRef refType = edmEntityType.getKeyPropertyRef(key.getName());
        Object value =  findPropertyRefValue(entity, refType);
        
        final EdmProperty property = refType.getProperty();
        final EdmPrimitiveType type = (EdmPrimitiveType) property.getType();
        
        if (key.getExpression() != null && !(key.getExpression() instanceof Literal)) {
          throw new DataProviderException("Expression in key value is not supported yet!",
              HttpStatusCode.NOT_IMPLEMENTED);
        }
        final String text = key.getAlias() == null ? key.getText() : ((Literal) key.getExpression()).getText();
        Object keyValue = null;
        if (Calendar.class.isAssignableFrom(value.getClass())) {
          keyValue = type.valueOfString(type.fromUriLiteral(text),
              property.isNullable(), property.getMaxLength(), property.getPrecision(), property.getScale(),
              property.isUnicode(), Calendar.class);
        } else {
          keyValue = type.valueOfString(type.fromUriLiteral(text),
              property.isNullable(), property.getMaxLength(), property.getPrecision(), property.getScale(),
              property.isUnicode(), value.getClass());
        }
        if (!value.equals(keyValue)) {
          found = false;
          break;
        }
      }
      if (found) {
        return entity;
      }
    }
    return null;
  } catch (final EdmPrimitiveTypeException e) {
    throw new DataProviderException("Wrong key!", HttpStatusCode.BAD_REQUEST, e);
  }
}
 
Example 16
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 17
Source File: JsonEntitySetSerializer.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
protected void doContainerSerialize(final ResWrap<EntityCollection> container, final JsonGenerator jgen)
    throws IOException, EdmPrimitiveTypeException {

  final EntityCollection entitySet = container.getPayload();

  jgen.writeStartObject();

  if (serverMode && !isODataMetadataNone) {
    if (container.getContextURL() != null) {
      jgen.writeStringField(Constants.JSON_CONTEXT, container.getContextURL().toASCIIString());
    }

    if (container.getMetadataETag() != null) {
      jgen.writeStringField(Constants.JSON_METADATA_ETAG, container.getMetadataETag());
    }
  }

  if (entitySet.getId() != null && isODataMetadataFull) {
    jgen.writeStringField(Constants.JSON_ID, entitySet.getId().toASCIIString());
  }
  final Integer count = entitySet.getCount() == null ? entitySet.getEntities().size() : entitySet.getCount();
  if (isIEEE754Compatible) {
    jgen.writeStringField(Constants.JSON_COUNT, Integer.toString(count));
  } else {
    jgen.writeNumberField(Constants.JSON_COUNT, count);
  }
  if (serverMode) {
    if (entitySet.getNext() != null) {
      jgen.writeStringField(Constants.JSON_NEXT_LINK,
          entitySet.getNext().toASCIIString());
    }
    if (entitySet.getDeltaLink() != null && !isODataMetadataNone) {
      jgen.writeStringField(Constants.JSON_DELTA_LINK,
          entitySet.getDeltaLink().toASCIIString());
    }
  }

  for (Annotation annotation : entitySet.getAnnotations()) {
    valuable(jgen, annotation, "@" + annotation.getTerm());
  }

  jgen.writeArrayFieldStart(Constants.VALUE);
  final JsonEntitySerializer entitySerializer = new JsonEntitySerializer(serverMode, contentType);
  for (Entity entity : entitySet.getEntities()) {
    entitySerializer.doSerialize(entity, jgen);
  }
  jgen.writeEndArray();

  jgen.writeEndObject();
}
 
Example 18
Source File: DataProvider.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
public Entity read(final EdmEntityType edmEntityType, final EntityCollection entitySet,
    final List<UriParameter> keys) throws DataProviderException {
  try {
    for (final Entity entity : entitySet.getEntities()) {
      boolean found = true;
      for (final UriParameter key : keys) {
        EdmKeyPropertyRef refType = edmEntityType.getKeyPropertyRef(key.getName());
        Object value =  findPropertyRefValue(entity, refType);
        
        final EdmProperty property = refType.getProperty();
        final EdmPrimitiveType type = (EdmPrimitiveType) property.getType();
        
        if (key.getExpression() != null && !(key.getExpression() instanceof Literal)) {
          throw new DataProviderException("Expression in key value is not supported yet!",
              HttpStatusCode.NOT_IMPLEMENTED);
        }
        Object keyValue = null;
        final String text = key.getAlias() == null ? key.getText() : ((Literal) key.getExpression()).getText();
        if (Calendar.class.isAssignableFrom(value.getClass())) {
          keyValue = type.valueOfString(type.fromUriLiteral(text),
              property.isNullable(), property.getMaxLength(), property.getPrecision(), property.getScale(),
              property.isUnicode(), Calendar.class);
        } else {
          keyValue = type.valueOfString(type.fromUriLiteral(text),
              property.isNullable(), property.getMaxLength(), property.getPrecision(), property.getScale(),
              property.isUnicode(), value.getClass());
        }
        if (!value.equals(keyValue)) {
          found = false;
          break;
        }
      }
      if (found) {
        return entity;
      }
    }
    return null;
  } catch (final EdmPrimitiveTypeException e) {
    throw new DataProviderException("Wrong key!", HttpStatusCode.BAD_REQUEST, e);
  }
}
 
Example 19
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 20
Source File: ProductsEntityCollectionProcessor.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Override
public void readEntityCollection(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
    throws ODataApplicationException, ODataLibraryException {
    // 1st we have retrieve the requested EntitySet from the uriInfo object (representation of the parsed service URI)
    List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
    UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet)resourcePaths.get(0); // in our example, the first segment is the EntitySet
    EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();

    // 2nd: fetch the data from backend for this requested EntitySetName
    // it has to be delivered as EntitySet object
    EntityCollection entityCollection = storage.readEntitySetData(edmEntitySet);

    // 3rd: apply System Query Options
    // modify the result set according to the query options, specified by the end user
    List<Entity> entityList = entityCollection.getEntities();
    EntityCollection returnEntityCollection = new EntityCollection();

    // handle $count: always return the original number of entities, without considering $top and $skip
    CountOption countOption = uriInfo.getCountOption();
    if (countOption != null) {
        boolean isCount = countOption.getValue();
        if (isCount) {
            returnEntityCollection.setCount(entityList.size());
        }
    }

    applyQueryOptions(uriInfo, entityList, returnEntityCollection);

    // 3rd: create a serializer based on the requested format (json)
    ODataSerializer serializer = odata.createSerializer(responseFormat);

    // 4th: Now 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)
            .count(countOption)
            .contextURL(contextUrl)
            .build();

    SerializerResult serializerResult = serializer.entityCollection(serviceMetadata,
                                                                    edmEntityType,
                                                                    returnEntityCollection,
                                                                    opts);
    InputStream serializedContent = serializerResult.getContent();

    // Finally: 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());
}