Java Code Examples for org.apache.olingo.server.api.ODataResponse#setStatusCode()

The following examples show how to use org.apache.olingo.server.api.ODataResponse#setStatusCode() . 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
@Override
public void readMediaEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
    throws ODataApplicationException, ODataLibraryException {
  
  final UriResource firstResoucePart = uriInfo.getUriResourceParts().get(0);
  if(firstResoucePart instanceof UriResourceEntitySet) {
    final EdmEntitySet edmEntitySet = Util.getEdmEntitySet(uriInfo);
    final UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) firstResoucePart;
    
    final Entity entity = storage.readEntityData(edmEntitySet, uriResourceEntitySet.getKeyPredicates());
    if(entity == null) {
      throw new ODataApplicationException("Entity not found", HttpStatusCode.NOT_FOUND.getStatusCode(), 
          Locale.ENGLISH);
    }

    final byte[] mediaContent = storage.readMedia(entity);
    final InputStream responseContent = odata.createFixedFormatSerializer().binary(mediaContent);
    
    response.setStatusCode(HttpStatusCode.OK.getStatusCode());
    response.setContent(responseContent);
    response.setHeader(HttpHeader.CONTENT_TYPE, entity.getMediaContentType());
  } else {
    throw new ODataApplicationException("Not implemented", HttpStatusCode.BAD_REQUEST.getStatusCode(), 
        Locale.ENGLISH);
  }
}
 
Example 3
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 4
Source File: ProductEntityProcessor.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
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();
    for (UriParameter kp : keyPredicates) {
        LOG.info("Deleting entity {} ( {} )", kp.getName(), kp.getText());
    }

    storage.deleteEntityData(edmEntitySet, keyPredicates);

    // 3. configure the response object
    response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example 5
Source File: TechnicalEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void updateReference(final ODataRequest request, ODataResponse response, final UriInfo uriInfo,
    final ContentType requestFormat) throws ODataApplicationException, ODataLibraryException {

  final ODataDeserializer deserializer = odata.createDeserializer(requestFormat);
  final DeserializerResult references = deserializer.entityReferences(request.getBody());

  if (references.getEntityReferences().size() != 1) {
    throw new ODataApplicationException("A post request to a collection navigation property must "
        + "contain a single entity reference", HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ROOT);
  }

  final Entity entity = readEntity(uriInfo, true);
  final UriResourceNavigation navigationProperty = getLastNavigation(uriInfo);
  ensureNavigationPropertyNotNull(navigationProperty);
  dataProvider.createReference(entity, navigationProperty.getProperty(), references.getEntityReferences().get(0),
      request.getRawBaseUri());

  response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example 6
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 7
Source File: DemoEntityCollectionProcessor.java    From cxf 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 we have retrieve the requested EntitySet from the uriInfo object 
    // (representation of the parsed service 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 
    // it has to be delivered as EntitySet object
    EntityCollection entitySet = getData(edmEntitySet);

    // 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).contextURL(contextUrl).build();
    SerializerResult serializedContent = serializer.entityCollection(serviceMetadata, 
        edmEntityType, entitySet, opts);

    // Finally: configure the response object: set the body, headers and status code
    response.setContent(serializedContent.getContent());
    response.setStatusCode(HttpStatusCode.OK.getStatusCode());
    response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example 8
Source File: CarsProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void readEntityCollection(final ODataRequest request, ODataResponse response, final UriInfo uriInfo,
    final ContentType requestedContentType) throws ODataApplicationException, SerializerException {
  // First we have to figure out which entity set to use
  final EdmEntitySet edmEntitySet = getEdmEntitySet(uriInfo.asUriInfoResource());

  // Second we fetch the data for this specific entity set from the mock database and transform it into an EntitySet
  // object which is understood by our serialization
  EntityCollection entitySet = dataProvider.readAll(edmEntitySet);

  // Next we create a serializer based on the requested format. This could also be a custom format but we do not
  // support them in this example
  ODataSerializer serializer = odata.createSerializer(requestedContentType);

  // Now the content is serialized using the serializer.
  final ExpandOption expand = uriInfo.getExpandOption();
  final SelectOption select = uriInfo.getSelectOption();
  final String id = request.getRawBaseUri() + "/" + edmEntitySet.getName();
  InputStream serializedContent = serializer.entityCollection(edm, edmEntitySet.getEntityType(), entitySet,
      EntityCollectionSerializerOptions.with()
          .id(id)
          .contextURL(isODataMetadataNone(requestedContentType) ? null :
              getContextUrl(edmEntitySet, false, expand, select, null))
          .count(uriInfo.getCountOption())
          .expand(expand).select(select)
          .build()).getContent();

  // Finally we set the response data, headers and status code
  response.setContent(serializedContent);
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, requestedContentType.toContentTypeString());
}
 
Example 9
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();
  // 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
  // it has to be delivered as EntitySet object
  EntityCollection entitySet = 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 serializedContent = serializer.entityCollection(serviceMetadata, edmEntityType, entitySet, opts);

  // Finally: configure the response object: set the body, headers and status code
  response.setContent(serializedContent.getContent());
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example 10
Source File: DemoBatchProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void processBatch(final BatchFacade facade, final ODataRequest request, final ODataResponse response)
    throws ODataApplicationException, ODataLibraryException {
  
  // 1. Extract the boundary
  final String boundary = facade.extractBoundaryFromContentType(request.getHeader(HttpHeader.CONTENT_TYPE));
  
  // 2. Prepare the batch options
  final BatchOptions options = BatchOptions.with().rawBaseUri(request.getRawBaseUri())
                                                  .rawServiceResolutionUri(request.getRawServiceResolutionUri())
                                                  .build();
  
  // 3. Deserialize the batch request
  final List<BatchRequestPart> requestParts = odata.createFixedFormatDeserializer()
                                                   .parseBatchRequest(request.getBody(), boundary, options);
  
  // 4. Execute the batch request parts
  final List<ODataResponsePart> responseParts = new ArrayList<ODataResponsePart>();
  for (final BatchRequestPart part : requestParts) {
    responseParts.add(facade.handleBatchRequest(part));
  }

  // 5. Create a new boundary for the response
  final String responseBoundary = "batch_" + UUID.randomUUID().toString();

  // 6. Serialize the response content
  final InputStream responseContent = odata.createFixedFormatSerializer().batchResponse(responseParts, responseBoundary);

  // 7. Setup response
  response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.MULTIPART_MIXED + ";boundary=" + responseBoundary);
  response.setContent(responseContent);
  response.setStatusCode(HttpStatusCode.ACCEPTED.getStatusCode());
}
 
Example 11
Source File: TechnicalEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteEntity(final ODataRequest request, ODataResponse response, final UriInfo uriInfo)
    throws ODataLibraryException, ODataApplicationException {
  final EdmEntitySet edmEntitySet = getEdmEntitySet(uriInfo);
  final Entity entity = readEntity(uriInfo);

  odata.createETagHelper().checkChangePreconditions(entity.getETag(),
      request.getHeaders(HttpHeader.IF_MATCH),
      request.getHeaders(HttpHeader.IF_NONE_MATCH));
  dataProvider.delete(edmEntitySet, entity);
  response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example 12
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void createEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
												 ContentType requestFormat, ContentType responseFormat)
			throws ODataApplicationException, DeserializerException, SerializerException {
	
	// 1. Retrieve the entity type from the URI 
	EdmEntitySet edmEntitySet = Util.getEdmEntitySet(uriInfo);
	EdmEntityType edmEntityType = edmEntitySet.getEntityType();

	// 2. create the data in backend 
	// 2.1. retrieve the payload from the POST request for the entity to create and deserialize it
	InputStream requestInputStream = request.getBody();
	ODataDeserializer deserializer = odata.createDeserializer(requestFormat);
	DeserializerResult result = deserializer.entity(requestInputStream, edmEntityType);
	Entity requestEntity = result.getEntity();
	// 2.2 do the creation in backend, which returns the newly created entity
	Entity createdEntity = storage.createEntityData(edmEntitySet, requestEntity);
	
	// 3. serialize the response (we have to return the created entity)
	ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).build(); 
	EntitySerializerOptions options = EntitySerializerOptions.with().contextURL(contextUrl).build(); // expand and select currently not supported 
	
	ODataSerializer serializer = odata.createSerializer(responseFormat);
	SerializerResult serializedResponse = serializer.entity(serviceMetadata, edmEntityType, createdEntity, options);
	
	//4. configure the response object
	response.setContent(serializedResponse.getContent());
	response.setStatusCode(HttpStatusCode.CREATED.getStatusCode());
	response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example 13
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void createEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
												 ContentType requestFormat, ContentType responseFormat)
			throws ODataApplicationException, DeserializerException, SerializerException {
	
	// 1. Retrieve the entity type from the URI 
	EdmEntitySet edmEntitySet = Util.getEdmEntitySet(uriInfo);
	EdmEntityType edmEntityType = edmEntitySet.getEntityType();

	// 2. create the data in backend 
	// 2.1. retrieve the payload from the POST request for the entity to create and deserialize it
	InputStream requestInputStream = request.getBody();
	ODataDeserializer deserializer = this.odata.createDeserializer(requestFormat);
	DeserializerResult result = deserializer.entity(requestInputStream, edmEntityType);
	Entity requestEntity = result.getEntity();
	// 2.2 do the creation in backend, which returns the newly created entity
	Entity createdEntity = storage.createEntityData(edmEntitySet, requestEntity);
	
	// 3. serialize the response (we have to return the created entity)
	ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).build(); 
	EntitySerializerOptions options = EntitySerializerOptions.with().contextURL(contextUrl).build(); // expand and select currently not supported 
	
	ODataSerializer serializer = this.odata.createSerializer(responseFormat);
	SerializerResult serializedResponse = serializer.entity(serviceMetadata, edmEntityType, createdEntity, options);
	
	//4. configure the response object
	final String location = request.getRawBaseUri() + '/'
       + odata.createUriHelper().buildCanonicalURL(edmEntitySet, createdEntity);
	
	response.setHeader(HttpHeader.LOCATION, location);
	response.setContent(serializedResponse.getContent());
	response.setStatusCode(HttpStatusCode.CREATED.getStatusCode());
	response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example 14
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();
  // 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
  // it has to be delivered as EntitySet object
  EntityCollection entitySet = 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 serializedContent = serializer.entityCollection(serviceMetadata, edmEntityType, entitySet, opts);

  // Finally: configure the response object: set the body, headers and status code
  response.setContent(serializedContent.getContent());
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example 15
Source File: MockedBatchHandlerTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void processBatch(final BatchFacade fascade, final ODataRequest request, final ODataResponse response)
    throws ODataApplicationException, BatchSerializerException, ODataLibraryException {
  final String boundary = getBoundary(request.getHeader(HttpHeader.CONTENT_TYPE));
  final BatchOptions options = BatchOptions.with().isStrict(true).rawBaseUri(BASE_URI).build();
  final List<BatchRequestPart> parts =
      odata.createFixedFormatDeserializer().parseBatchRequest(request.getBody(), boundary, options);
  final List<ODataResponsePart> responseParts = new ArrayList<ODataResponsePart>();

  for (BatchRequestPart part : parts) {
    for (final ODataRequest oDataRequest : part.getRequests()) {
      // Mock the processor for a given requests
      when(oDataHandler.process(oDataRequest)).then(new Answer<ODataResponse>() {
        @Override
        public ODataResponse answer(final InvocationOnMock invocation) throws Throwable {
          Object[] arguments = invocation.getArguments();

          return buildResponse((ODataRequest) arguments[0]);
        }
      });
    }

    responseParts.add(fascade.handleBatchRequest(part));
  }

  final String responeBoundary = "batch_" + UUID.randomUUID().toString();
  final InputStream responseStream =
      odata.createFixedFormatSerializer().batchResponse(responseParts, responeBoundary);

  response.setStatusCode(HttpStatusCode.ACCEPTED.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.MULTIPART_MIXED + ";boundary=" + responeBoundary);
  response.setContent(responseStream);
}
 
Example 16
Source File: TripPinHandler.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public void apply(DataRequest dataRequest, ODataResponse response)
    throws ODataLibraryException, ODataApplicationException {
  response.setStatusCode(501);
}
 
Example 17
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 18
Source File: DemoPrimitiveProcessor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
public void readPrimitive(ODataRequest request, ODataResponse response, 
							UriInfo uriInfo, ContentType responseFormat) 
							throws ODataApplicationException, SerializerException {

	// 1. Retrieve info from URI
	// 1.1. retrieve the info about the requested entity set 
	List<UriResource> resourceParts = uriInfo.getUriResourceParts();
	// Note: only in our example we can rely that the first segment is the EntitySet
	UriResourceEntitySet uriEntityset = (UriResourceEntitySet) resourceParts.get(0); 
	EdmEntitySet edmEntitySet = uriEntityset.getEntitySet();
	// the key for the entity
	List<UriParameter> keyPredicates = uriEntityset.getKeyPredicates();
	
	// 1.2. retrieve the requested (Edm) property 
	UriResourceProperty uriProperty = (UriResourceProperty)resourceParts.get(resourceParts.size() -1); // the last segment is the Property
	EdmProperty edmProperty = uriProperty.getProperty();
	String edmPropertyName = edmProperty.getName();
	// in our example, we know we have only primitive types in our model
	EdmPrimitiveType edmPropertyType = (EdmPrimitiveType) edmProperty.getType(); 
	
	
	// 2. retrieve data from backend
	// 2.1. retrieve the entity data, for which the property has to be read
	Entity entity = storage.readEntityData(edmEntitySet, keyPredicates);
	if (entity == null) { // Bad request
		throw new ODataApplicationException("Entity not found",
						HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
	} 
	
	// 2.2. retrieve the property data from the entity
	Property property = entity.getProperty(edmPropertyName);
	if (property == null) {
		throw new ODataApplicationException("Property not found",
             HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
	}		
	
	// 3. serialize
	Object value = property.getValue();
	if (value != null) {
		// 3.1. configure the serializer
		ODataSerializer serializer = odata.createSerializer(responseFormat);
		
		ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).navOrPropertyPath(edmPropertyName).build();
		PrimitiveSerializerOptions options = PrimitiveSerializerOptions.with().contextURL(contextUrl).build();
		// 3.2. serialize
		SerializerResult result = serializer.primitive(serviceMetadata, edmPropertyType, property, options);
		
		//4. configure the response object
		response.setContent(result.getContent());
		response.setStatusCode(HttpStatusCode.OK.getStatusCode());
		response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());		
	}else{
		// in case there's no value for the property, we can skip the serialization
		response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
	}
}
 
Example 19
Source File: TechnicalPrimitiveComplexProcessor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private void readProperty(final ODataRequest request, ODataResponse response, final UriInfo uriInfo,
    final ContentType contentType, final RepresentationType representationType)
        throws ODataApplicationException, ODataLibraryException {
  final UriInfoResource resource = uriInfo.asUriInfoResource();
  validateOptions(resource);
  validatePath(resource);
  final EdmEntitySet edmEntitySet = getEdmEntitySet(resource);

  final List<UriResource> resourceParts = resource.getUriResourceParts();
  final int trailing =
      representationType == RepresentationType.COUNT || representationType == RepresentationType.VALUE ? 1 : 0;
  final List<String> path = getPropertyPath(resourceParts, trailing);

  final Entity entity = readEntity(uriInfo);

  if (entity != null && entity.getETag() != null) {
    if (odata.createETagHelper().checkReadPreconditions(entity.getETag(),
        request.getHeaders(HttpHeader.IF_MATCH),
        request.getHeaders(HttpHeader.IF_NONE_MATCH))) {
      response.setStatusCode(HttpStatusCode.NOT_MODIFIED.getStatusCode());
      response.setHeader(HttpHeader.ETAG, entity.getETag());
      return;
    }
  }

  final Property property = entity == null ?
      getPropertyData(
          dataProvider.readFunctionPrimitiveComplex(((UriResourceFunction) resourceParts.get(0)).getFunction(),
          ((UriResourceFunction) resourceParts.get(0)).getParameters(), resource), path) :
      getData(entity, path, resourceParts, resource);

  // TODO: implement filter on collection properties (on a shallow copy of the values)
  // FilterHandler.applyFilterSystemQuery(uriInfo.getFilterOption(), property, uriInfo, serviceMetadata.getEdm());

  if (property == null && representationType != RepresentationType.COUNT) {
    if (representationType == RepresentationType.VALUE) {
      response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
    } else {
      throw new ODataApplicationException("Nothing found.", HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ROOT);
    }
  } else {
    if (property.getValue() == null && representationType != RepresentationType.COUNT) {
      response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
    } else {
      response.setStatusCode(HttpStatusCode.OK.getStatusCode());
      if (representationType == RepresentationType.COUNT) {
        response.setContent(odata.createFixedFormatSerializer().count(
            property.asCollection().size()));
      } else {
        final EdmProperty edmProperty = path.isEmpty() ? null :
            ((UriResourceProperty) resourceParts.get(resourceParts.size() - trailing - 1)).getProperty();
        EdmType type = null;
        if (resourceParts.get(resourceParts.size() - trailing - 1) 
           instanceof UriResourceComplexProperty &&
            ((UriResourceComplexProperty)resourceParts.get(resourceParts.size() - trailing - 1)).
            getComplexTypeFilter() != null) {
          type = ((UriResourceComplexProperty)resourceParts.get(resourceParts.size() - trailing - 1)).
              getComplexTypeFilter();
        }else if(resourceParts.get(resourceParts.size() - trailing - 1) 
           instanceof UriResourceFunction &&
            ((UriResourceFunction)resourceParts.get(resourceParts.size() - trailing - 1)).
            getFunction() != null){ 
          type = ((UriResourceFunction)resourceParts.get(resourceParts.size() - trailing - 1)).
              getType();
        }else {
          type = edmProperty == null ?
              ((UriResourceFunction) resourceParts.get(0)).getType() :
              edmProperty.getType();
        }
        final EdmReturnType returnType = resourceParts.get(0) instanceof UriResourceFunction ?
            ((UriResourceFunction) resourceParts.get(0)).getFunction().getReturnType() : 
              resourceParts.get(1) instanceof UriResourceFunction ? 
                  ((UriResourceFunction) resourceParts.get(1)).getFunction().getReturnType():null ;

        if (representationType == RepresentationType.VALUE) {
          response.setContent(serializePrimitiveValue(property, edmProperty, (EdmPrimitiveType) type, returnType));
        }else if(representationType == RepresentationType.PRIMITIVE && type.getFullQualifiedName()
            .getFullQualifiedNameAsString().equals(EDMSTREAM)){
          response.setContent(odata.createFixedFormatSerializer().binary(dataProvider.readStreamProperty(property)));
          response.setStatusCode(HttpStatusCode.OK.getStatusCode());
          response.setHeader(HttpHeader.CONTENT_TYPE, ((Link)property.getValue()).getType());
          if (entity.getMediaETag() != null) {
            response.setHeader(HttpHeader.ETAG, entity.getMediaETag());
          }
        }else {
          final ExpandOption expand = uriInfo.getExpandOption();
          final SelectOption select = uriInfo.getSelectOption();
          final SerializerResult result = serializeProperty(entity, edmEntitySet, path, property, edmProperty,
              type, returnType, representationType, contentType, expand, select);
          response.setContent(result.getContent());
        }
      }
      response.setHeader(HttpHeader.CONTENT_TYPE, contentType.toContentTypeString());
    }
    if (entity != null && entity.getETag() != null) {
      response.setHeader(HttpHeader.ETAG, entity.getETag());
    }
  }
}
 
Example 20
Source File: DemoActionProcessor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public void processActionEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
    ContentType requestFormat, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException {

  EdmAction action = null;
  Map<String, Parameter> parameters = new HashMap<String, Parameter>(); 
  DemoEntityActionResult entityResult = null;
  if (requestFormat == null) {
    throw new ODataApplicationException("The content type has not been set in the request.",
        HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ROOT);
  }
  
  final ODataDeserializer deserializer = odata.createDeserializer(requestFormat);
  final List<UriResource> resourcePaths = uriInfo.asUriInfoResource().getUriResourceParts();
  UriResourceEntitySet boundEntity = (UriResourceEntitySet) resourcePaths.get(0);
  if (resourcePaths.size() > 1) {
    if (resourcePaths.get(1) instanceof UriResourceNavigation) {
      action = ((UriResourceAction) resourcePaths.get(2))
          .getAction();
      throw new ODataApplicationException("Action " + action.getName() + " is not yet implemented.",
            HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ENGLISH);
    } else if (resourcePaths.get(0) instanceof UriResourceEntitySet) {
      action = ((UriResourceAction) resourcePaths.get(1))
          .getAction();
      parameters = deserializer.actionParameters(request.getBody(), action)
          .getActionParameters();
      entityResult =
          storage.processBoundActionEntity(action, parameters, boundEntity.getKeyPredicates());
    }
  }
  final EdmEntitySet edmEntitySet = boundEntity.getEntitySet();
  final EdmEntityType type = (EdmEntityType) action.getReturnType().getType();

  if (entityResult == null || entityResult.getEntity() == null) {
    if (action.getReturnType().isNullable()) {
      response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
    } else {
      // Not nullable return type so we have to give back a 500
      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) {
      response.setContent(odata.createSerializer(responseFormat).entity(
          serviceMetadata,
          type,
          entityResult.getEntity(),
          EntitySerializerOptions.with()
              .contextURL(isODataMetadataNone(responseFormat) ? null : 
                getContextUrl(action.getReturnedEntitySet(edmEntitySet), type, true))
              .build())
          .getContent());
      response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
      response.setStatusCode((entityResult.isCreated() ? HttpStatusCode.CREATED : HttpStatusCode.OK)
          .getStatusCode());
    } else {
      response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
    }
    if (returnPreference != null) {
      response.setHeader(HttpHeader.PREFERENCE_APPLIED,
          PreferencesApplied.with().returnRepresentation(returnPreference).build().toValueString());
    }
    if (entityResult.isCreated()) {
      final String location = request.getRawBaseUri() + '/'
          + odata.createUriHelper().buildCanonicalURL(edmEntitySet, entityResult.getEntity());
      response.setHeader(HttpHeader.LOCATION, location);
      if (returnPreference == Return.MINIMAL) {
        response.setHeader(HttpHeader.ODATA_ENTITY_ID, location);
      }
    }
    if (entityResult.getEntity().getETag() != null) {
      response.setHeader(HttpHeader.ETAG, entityResult.getEntity().getETag());
    }
  }    
}