Java Code Examples for org.apache.olingo.server.api.uri.UriResourceEntitySet#getEntitySet()

The following examples show how to use org.apache.olingo.server.api.uri.UriResourceEntitySet#getEntitySet() . 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: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public void deleteEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo)
    throws ODataApplicationException {

  // 1. Retrieve the entity set which belongs to the requested entity
  List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
  // Note: only in our example we can assume that the first segment is the EntitySet
  UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
  EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();

  // 2. delete the data in backend
  List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
  storage.deleteEntityData(edmEntitySet, keyPredicates);

  // 3. configure the response object
  response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example 2
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public void deleteEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo)
         throws ODataApplicationException {
	
	// 1. Retrieve the entity set which belongs to the requested entity 
	List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
	// Note: only in our example we can assume that the first segment is the EntitySet
	UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0); 
	EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();

	// 2. delete the data in backend
	List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
	storage.deleteEntityData(edmEntitySet, keyPredicates);
	
	//3. configure the response object
	response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example 3
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public void deleteEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo)
         throws ODataApplicationException {
	
	// 1. Retrieve the entity set which belongs to the requested entity 
	List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
	// Note: only in our example we can assume that the first segment is the EntitySet
	UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0); 
	EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();

	// 2. delete the data in backend
	List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
	storage.deleteEntityData(edmEntitySet, keyPredicates);
	
	//3. configure the response object
	response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example 4
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public void updateEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
    ContentType requestFormat, ContentType responseFormat)
        throws ODataApplicationException, DeserializerException, SerializerException {

  // 1. Retrieve the entity set which belongs to the requested entity
  List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
  // Note: only in our example we can assume that the first segment is the EntitySet
  UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
  EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();
  EdmEntityType edmEntityType = edmEntitySet.getEntityType();

  // 2. update the data in backend
  // 2.1. retrieve the payload from the PUT request for the entity to be updated
  InputStream requestInputStream = request.getBody();
  ODataDeserializer deserializer = this.odata.createDeserializer(requestFormat);
  DeserializerResult result = deserializer.entity(requestInputStream, edmEntityType);
  Entity requestEntity = result.getEntity();
  // 2.2 do the modification in backend
  List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
  // Note that this updateEntity()-method is invoked for both PUT or PATCH operations
  HttpMethod httpMethod = request.getMethod();
  storage.updateEntityData(edmEntitySet, keyPredicates, requestEntity, httpMethod);

  // 3. configure the response object
  response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example 5
Source File: TechnicalProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
protected EdmEntitySet getEntitySetBasedOnTypeCast(UriResourceEntitySet uriResource) {
  EdmEntitySet entitySet = null;
  EdmEntityContainer container = this.serviceMetadata.getEdm().getEntityContainer();
  if (uriResource.getTypeFilterOnEntry() != null ||
      uriResource.getTypeFilterOnCollection() != null) {
    List<EdmEntitySet> entitySets = container.getEntitySets();
    for (EdmEntitySet entitySet1 : entitySets) {
      EdmEntityType entityType = entitySet1.getEntityType();
      if ((uriResource.getTypeFilterOnEntry() != null && 
          entityType.getName().equalsIgnoreCase(uriResource.getTypeFilterOnEntry().getName())) ||
          (uriResource.getTypeFilterOnCollection() != null && 
          entityType.getName().equalsIgnoreCase(uriResource.getTypeFilterOnCollection().getName()))) {
        entitySet = entitySet1;
        break;
      }
    }
  } else {
    entitySet = uriResource.getEntitySet();
  }
  return entitySet;
}
 
Example 6
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public void updateEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
                          ContentType requestFormat, ContentType responseFormat)
						throws ODataApplicationException, DeserializerException, SerializerException {
	
	// 1. Retrieve the entity set which belongs to the requested entity 
	List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
	// Note: only in our example we can assume that the first segment is the EntitySet
	UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0); 
	EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();
	EdmEntityType edmEntityType = edmEntitySet.getEntityType();

	// 2. update the data in backend
	// 2.1. retrieve the payload from the PUT request for the entity to be updated 
	InputStream requestInputStream = request.getBody();
	ODataDeserializer deserializer = this.odata.createDeserializer(requestFormat);
	DeserializerResult result = deserializer.entity(requestInputStream, edmEntityType);
	Entity requestEntity = result.getEntity();
	// 2.2 do the modification in backend
	List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
	// Note that this updateEntity()-method is invoked for both PUT or PATCH operations
	HttpMethod httpMethod = request.getMethod();
	storage.updateEntityData(edmEntitySet, keyPredicates, requestEntity, httpMethod);
	
	//3. configure the response object
	response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example 7
Source File: DemoEntityCollectionProcessor.java    From olingo-odata4 with Apache License 2.0 5 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();
		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 and deliver as EntitySet
		EntityCollection entityCollection = storage.readEntitySetData(edmEntitySet);

		// 3rd: 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();

		// 4th: 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: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void readEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
    throws ODataApplicationException, SerializerException {

  // 1. retrieve the Entity Type
  List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
  // Note: only in our example we can assume that the first segment is the EntitySet
  UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
  EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();

  // 2. retrieve the data from backend
  List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
  Entity entity = storage.readEntityData(edmEntitySet, keyPredicates);

  // 3. serialize
  EdmEntityType entityType = edmEntitySet.getEntityType();

  ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).suffix(ContextURL.Suffix.ENTITY).build();
  // expand and select currently not supported
  EntitySerializerOptions options = EntitySerializerOptions.with().contextURL(contextUrl).build();

  ODataSerializer serializer = this.odata.createSerializer(responseFormat);
  SerializerResult serializerResult = serializer.entity(serviceMetadata, entityType, entity, options);
  InputStream entityStream = serializerResult.getContent();

  // 4. configure the response object
  response.setContent(entityStream);
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example 9
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void readEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
						throws ODataApplicationException, SerializerException {

	// 1. retrieve the Entity Type
	List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
	// Note: only in our example we can assume that the first segment is the EntitySet
	UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
	EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();

	// 2. retrieve the data from backend
	List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
	Entity entity = storage.readEntityData(edmEntitySet, keyPredicates);

	// 3. serialize
	EdmEntityType entityType = edmEntitySet.getEntityType();

	ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).suffix(ContextURL.Suffix.ENTITY).build();
 	// expand and select currently not supported
	EntitySerializerOptions options = EntitySerializerOptions.with().contextURL(contextUrl).build();

	ODataSerializer serializer = this.odata.createSerializer(responseFormat);
	SerializerResult serializerResult = serializer.entity(serviceMetadata, entityType, entity, options);
	InputStream entityStream = serializerResult.getContent();

	//4. configure the response object
	response.setContent(entityStream);
	response.setStatusCode(HttpStatusCode.OK.getStatusCode());
	response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example 10
Source File: Util.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public static EdmEntitySet getEdmEntitySet(UriInfoResource uriInfo) throws ODataApplicationException {

    List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
    // To get the entity set we have to interpret all URI segments
    if (!(resourcePaths.get(0) instanceof UriResourceEntitySet)) {
      // Here we should interpret the whole URI but in this example we do not support navigation so we throw an
      // exception
      throw new ODataApplicationException("Invalid resource type for first segment.", HttpStatusCode.NOT_IMPLEMENTED
          .getStatusCode(), Locale.ENGLISH);
    }

    UriResourceEntitySet uriResource = (UriResourceEntitySet) resourcePaths.get(0);

    return uriResource.getEntitySet();
  }
 
Example 11
Source File: Util.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public static EdmEntitySet getEdmEntitySet(UriInfoResource uriInfo) throws ODataApplicationException {

    List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
    // To get the entity set we have to interpret all URI segments
    if (!(resourcePaths.get(0) instanceof UriResourceEntitySet)) {
      // Here we should interpret the whole URI but in this example we do not support navigation so we throw an
      // exception
      throw new ODataApplicationException("Invalid resource type for first segment.", HttpStatusCode.NOT_IMPLEMENTED
          .getStatusCode(), Locale.ENGLISH);
    }

    UriResourceEntitySet uriResource = (UriResourceEntitySet) resourcePaths.get(0);

    return uriResource.getEntitySet();
  }
 
Example 12
Source File: Util.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public static EdmEntitySet getEdmEntitySet(UriInfoResource uriInfo) throws ODataApplicationException {

    List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
    // To get the entity set we have to interpret all URI segments
    if (!(resourcePaths.get(0) instanceof UriResourceEntitySet)) {
      // Here we should interpret the whole URI but in this example we do not support navigation so we throw an
      // exception
      throw new ODataApplicationException("Invalid resource type for first segment.", HttpStatusCode.NOT_IMPLEMENTED
          .getStatusCode(), Locale.ENGLISH);
    }

    UriResourceEntitySet uriResource = (UriResourceEntitySet) resourcePaths.get(0);

    return uriResource.getEntitySet();
  }
 
Example 13
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void readEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
						throws ODataApplicationException, SerializerException {

	// 1. retrieve the Entity Type
	List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
	// Note: only in our example we can assume that the first segment is the EntitySet
	UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
	EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();

	// 2. retrieve the data from backend
	List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
	Entity entity = storage.readEntityData(edmEntitySet, keyPredicates);

	// 3. serialize
	EdmEntityType entityType = edmEntitySet.getEntityType();

	ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).suffix(ContextURL.Suffix.ENTITY).build();
 	// expand and select currently not supported
	EntitySerializerOptions options = EntitySerializerOptions.with().contextURL(contextUrl).build();

	ODataSerializer serializer = this.odata.createSerializer(responseFormat);
	SerializerResult serializerResult = serializer.entity(serviceMetadata, entityType, entity, options);
	InputStream entityStream = serializerResult.getContent();

	//4. configure the response object
	response.setContent(entityStream);
	response.setStatusCode(HttpStatusCode.OK.getStatusCode());
	response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example 14
Source File: TechnicalActionProcessor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public void processActionComplex(final ODataRequest request, ODataResponse response, final UriInfo uriInfo,
    final ContentType requestFormat, final ContentType responseFormat)
    throws ODataApplicationException, ODataLibraryException {
  EdmAction action = null;
  Map<String, Parameter> parameters = null;
  Property property = null;
  final List<UriResource> resourcePaths = uriInfo.asUriInfoResource().getUriResourceParts();
  if (resourcePaths.size() > 1) {
    if (resourcePaths.get(0) instanceof UriResourceEntitySet) {
      UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
      EdmEntitySet entitySet = uriResourceEntitySet.getEntitySet();
      action = ((UriResourceAction) resourcePaths.get(resourcePaths.size() - 1))
          .getAction();
      parameters = readParameters(action, request.getBody(), requestFormat);
      property =
          dataProvider.processBoundActionComplex(action.getName(), parameters, entitySet, 
              uriResourceEntitySet.getKeyPredicates());
    }
  } else {
    action = ((UriResourceAction) resourcePaths.get(0))
        .getAction();
    parameters = readParameters(action, request.getBody(), requestFormat);
    property = dataProvider.processActionComplex(action.getName(), parameters);
  }
  
  EdmComplexType type = (EdmComplexType) action.getReturnType().getType();
  if (property == null || property.isNull()) {
    if (action.getReturnType().isNullable()) {
      response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
    } else {
      // Not nullable return type so we have to give back an Internal Server Error
      throw new ODataApplicationException("The action could not be executed.",
          HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ROOT);
    }
  } else {
    final Return returnPreference = odata.createPreferences(request.getHeaders(HttpHeader.PREFER)).getReturn();
    if (returnPreference == null || returnPreference == Return.REPRESENTATION) {
      final ContextURL contextURL = ContextURL.with().type(type).build();
      final ComplexSerializerOptions options = ComplexSerializerOptions.with().contextURL(contextURL).build();
      final SerializerResult result =
          odata.createSerializer(responseFormat).complex(serviceMetadata, type, property, options);
      response.setContent(result.getContent());
      response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
      response.setStatusCode(HttpStatusCode.OK.getStatusCode());
    } else {
      response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
    }
    if (returnPreference != null) {
      response.setHeader(HttpHeader.PREFERENCE_APPLIED,
          PreferencesApplied.with().returnRepresentation(returnPreference).build().toValueString());
    }
  }
}
 
Example 15
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 16
Source File: TechnicalActionProcessor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public void processActionComplexCollection(final ODataRequest request, ODataResponse response,
    final UriInfo uriInfo, final ContentType requestFormat, final ContentType responseFormat)
    throws ODataApplicationException, ODataLibraryException {
  EdmAction action = null;
  Map<String, Parameter> parameters = null;
  Property property = null;
  final List<UriResource> resourcePaths = uriInfo.asUriInfoResource().getUriResourceParts();
  if (resourcePaths.size() > 1) {
    if (resourcePaths.get(0) instanceof UriResourceEntitySet) {
      UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
      EdmEntitySet entitySet = uriResourceEntitySet.getEntitySet();
      action = ((UriResourceAction) resourcePaths.get(resourcePaths.size() - 1))
          .getAction();
      parameters = readParameters(action, request.getBody(), requestFormat);
      property =
          dataProvider.processBoundActionComplexCollection(action.getName(), parameters, entitySet, 
              uriResourceEntitySet.getKeyPredicates());
    }
  } else {
    action = ((UriResourceAction) resourcePaths.get(0))
        .getAction();
    parameters = readParameters(action, request.getBody(), requestFormat);
    property =
        dataProvider.processActionComplexCollection(action.getName(), parameters);
  }
  
  if (property == null || property.isNull()) {
    // Collection Propertys must never be null
    throw new ODataApplicationException("The action could not be executed.",
        HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ROOT);
  } else if (property.asCollection().contains(null) && !action.getReturnType().isNullable()) {
    // Not nullable return type but array contains a null value
    throw new ODataApplicationException("The action could not be executed.",
        HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ROOT);
  }
  final Return returnPreference = odata.createPreferences(request.getHeaders(HttpHeader.PREFER)).getReturn();
  if (returnPreference == null || returnPreference == Return.REPRESENTATION) {
    final EdmComplexType type = (EdmComplexType) action.getReturnType().getType();
    final ContextURL contextURL = ContextURL.with().type(type).asCollection().build();
    final ComplexSerializerOptions options = ComplexSerializerOptions.with().contextURL(contextURL).build();
    final SerializerResult result =
        odata.createSerializer(responseFormat).complexCollection(serviceMetadata, type, property, options);
    response.setContent(result.getContent());
    response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
    response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  } else {
    response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
  }
  if (returnPreference != null) {
    response.setHeader(HttpHeader.PREFERENCE_APPLIED,
        PreferencesApplied.with().returnRepresentation(returnPreference).build().toValueString());
  }
}
 
Example 17
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());
}
 
Example 18
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 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 {
  
  EdmEntitySet responseEdmEntitySet = null; // we'll need this to build the ContextURL
  EntityCollection responseEntityCollection = null; // we'll need this to set the response body

  // 1st retrieve the requested EntitySet from the uriInfo (representation of the parsed URI)
  List<UriResource> resourceParts = uriInfo.getUriResourceParts();
  int segmentCount = resourceParts.size();

  UriResource uriResource = resourceParts.get(0); // in our example, the first segment is the EntitySet
  if (!(uriResource instanceof UriResourceEntitySet)) {
    throw new ODataApplicationException("Only EntitySet is supported",
        HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ROOT);
  }

  UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) uriResource;
  EdmEntitySet startEdmEntitySet = uriResourceEntitySet.getEntitySet();

  if (segmentCount == 1) { // this is the case for: DemoService/DemoService.svc/Categories
    responseEdmEntitySet = startEdmEntitySet; // the response body is built from the first (and only) entitySet

    // 2nd: fetch the data from backend for this requested EntitySetName and deliver as EntitySet
    responseEntityCollection = storage.readEntitySetData(startEdmEntitySet);
  } else if (segmentCount == 2) { // in case of navigation: DemoService.svc/Categories(3)/Products

    UriResource lastSegment = resourceParts.get(1); // in our example we don't support more complex URIs
    if (lastSegment instanceof UriResourceNavigation) {
      UriResourceNavigation uriResourceNavigation = (UriResourceNavigation) lastSegment;
      EdmNavigationProperty edmNavigationProperty = uriResourceNavigation.getProperty();
      EdmEntityType targetEntityType = edmNavigationProperty.getType();
      // from Categories(1) to Products
      responseEdmEntitySet = Util.getNavigationTargetEntitySet(startEdmEntitySet, edmNavigationProperty);

      // 2nd: fetch the data from backend
      // first fetch the entity where the first segment of the URI points to
      List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
      // e.g. for Categories(3)/Products we have to find the single entity: Category with ID 3
      Entity sourceEntity = storage.readEntityData(startEdmEntitySet, keyPredicates);
      // error handling for e.g. DemoService.svc/Categories(99)/Products
      if (sourceEntity == null) {
        throw new ODataApplicationException("Entity not found.",
            HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ROOT);
      }
      // then fetch the entity collection where the entity navigates to
      // note: we don't need to check uriResourceNavigation.isCollection(),
      // because we are the EntityCollectionProcessor
      responseEntityCollection = storage.getRelatedEntityCollection(sourceEntity, targetEntityType);
    }
  } else { // this would be the case for e.g. Products(1)/Category/Products
    throw new ODataApplicationException("Not supported",
        HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ROOT);
  }

  // 3rd: create and configure a serializer
  ContextURL contextUrl = ContextURL.with().entitySet(responseEdmEntitySet).build();
  final String id = request.getRawBaseUri() + "/" + responseEdmEntitySet.getName();
  EntityCollectionSerializerOptions opts = EntityCollectionSerializerOptions.with()
      .contextURL(contextUrl).id(id).build();
  EdmEntityType edmEntityType = responseEdmEntitySet.getEntityType();

  ODataSerializer serializer = odata.createSerializer(responseFormat);
  SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, edmEntityType,
      responseEntityCollection, opts);

  // 4th: configure the response object: set the body, headers and status code
  response.setContent(serializerResult.getContent());
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example 20
Source File: CategoryEntityProvider.java    From spring-boot-Olingo-oData with Apache License 2.0 3 votes vote down vote up
@Override
public EntitySet getEntitySet(UriInfo uriInfo) {
	List<UriResource> resourcePaths = uriInfo.getUriResourceParts();

	UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths
			.get(0); // in our example, the first segment is the EntitySet

	EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();

	EntitySet entitySet = getData(edmEntitySet);

	return entitySet;
}