org.apache.olingo.server.api.ODataRequest Java Examples

The following examples show how to use org.apache.olingo.server.api.ODataRequest. 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: TechnicalEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void readMediaEntity(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
    final ContentType responseFormat) throws ODataApplicationException, ODataLibraryException {
  getEdmEntitySet(uriInfo); // including checks
  final Entity entity = readEntity(uriInfo);
  final EdmEntitySet edmEntitySet = getEdmEntitySet(uriInfo.asUriInfoResource());
  if (isMediaStreaming(edmEntitySet)) {
EntityMediaObject mediaEntity = new EntityMediaObject();
mediaEntity.setBytes(dataProvider.readMedia(entity));
   response.setODataContent(odata.createFixedFormatSerializer()
   		.mediaEntityStreamed(mediaEntity).getODataContent());
  } else {
  	response.setContent(odata.createFixedFormatSerializer().binary(dataProvider.readMedia(entity)));
  }
  response.setContent(odata.createFixedFormatSerializer().binary(dataProvider.readMedia(entity)));
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, entity.getMediaContentType());
  if (entity.getMediaETag() != null) {
    response.setHeader(HttpHeader.ETAG, entity.getMediaETag());
  }
}
 
Example #2
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void dispatchPrimitiveCollectionProperty() throws Exception {
  final String uri = "ESMixPrimCollComp(7)/CollPropertyString";
  final PrimitiveCollectionProcessor processor = mock(PrimitiveCollectionProcessor.class);

  dispatch(HttpMethod.GET, uri, processor);
  verify(processor).readPrimitiveCollection(
      any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class), any(ContentType.class));

  dispatch(HttpMethod.PUT, uri, processor);
  verify(processor).updatePrimitiveCollection(
      any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class), any(ContentType.class),
      any(ContentType.class));

  dispatch(HttpMethod.DELETE, uri, processor);
  verify(processor).deletePrimitiveCollection(any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class));

  dispatchMethodNotAllowed(HttpMethod.POST, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.HEAD, uri, processor);
}
 
Example #3
Source File: MockedBatchHandlerTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test(expected = BatchDeserializerException.class)
public void testInvalidContentType() throws Exception {
  final String content = ""
      + "--batch_12345" + CRLF
      + "Content-Type: multipart/mixed; boundary=changeset_12345" + CRLF
      + CRLF
      + "--changeset_12345" + CRLF
      + "Content-Type: application/http" + CRLF
      + "Content-Transfer-Encoding: binary" + CRLF
      + "Content-Id: 1" + CRLF
      + CRLF
      + "PUT ESAllPrim(1) HTTP/1.1" + CRLF
      + "Content-Type: application/json;odata=verbose" + CRLF
      + CRLF
      + CRLF
      + "--changeset_12345--" + CRLF
      + CRLF
      + "--batch_12345--";

  final Map<String, List<String>> header = new HashMap<String, List<String>>();
  header.put(HttpHeader.CONTENT_TYPE, Arrays.asList(new String[] { "application/http" }));
  final ODataResponse response = new ODataResponse();
  final ODataRequest request = buildODataRequest(content, header);

  batchHandler.process(request, response, true);
}
 
Example #4
Source File: TechnicalEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void createReference(final ODataRequest request, final 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 #5
Source File: BatchRequestParserTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void absoluteUri() throws Exception {
  final List<BatchRequestPart> batchRequestParts = parse(
      createBatchWithGetRequest(SERVICE_ROOT + "/ESAllPrim?$top=1", null));

  Assert.assertEquals(1, batchRequestParts.size());
  final BatchRequestPart part = batchRequestParts.get(0);

  Assert.assertEquals(1, part.getRequests().size());
  final ODataRequest request = part.getRequests().get(0);

  Assert.assertEquals("/ESAllPrim", request.getRawODataPath());
  Assert.assertEquals("$top=1", request.getRawQueryPath());
  Assert.assertEquals(SERVICE_ROOT + "/ESAllPrim?$top=1", request.getRawRequestUri());
  Assert.assertEquals(SERVICE_ROOT, request.getRawBaseUri());
}
 
Example #6
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void updateMediaEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
    ContentType requestFormat, 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 = odata.createFixedFormatDeserializer().binary(request.getBody());
    storage.updateMedia(entity, requestFormat.toContentTypeString(), mediaContent);
    
    response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
  } else {
    throw new ODataApplicationException("Not implemented", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), 
        Locale.ENGLISH);
  }
}
 
Example #7
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 #8
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void dispatchReferenceCollection() throws Exception {
  final String uri = "ESAllPrim(0)/NavPropertyETTwoPrimMany/$ref";
  final String singletonUri = "SINav/NavPropertyETTwoKeyNavMany/$ref";
  final ReferenceCollectionProcessor processor = mock(ReferenceCollectionProcessor.class);

  dispatch(HttpMethod.GET, uri, processor);
  verify(processor).readReferenceCollection(any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class),
      any(ContentType.class));

  dispatchMethodNotAllowed(HttpMethod.PATCH, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.PUT, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.HEAD, uri, processor); 
  
  //singleton ref
  dispatch(HttpMethod.GET, singletonUri, processor);
  verify(processor, times(2)).readReferenceCollection(any(ODataRequest.class), 
      any(ODataResponse.class), any(UriInfo.class),
      any(ContentType.class));

  dispatchMethodNotAllowed(HttpMethod.PATCH, singletonUri, processor);
  dispatchMethodNotAllowed(HttpMethod.PUT, singletonUri, processor);
  dispatchMethodNotAllowed(HttpMethod.HEAD, singletonUri, processor);
}
 
Example #9
Source File: OData4HttpHandler.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
ODataRequest createODataRequest(final HttpServletRequest httpRequest, final int split)
    throws ODataLibraryException {
  try {
    ODataRequest odRequest = new ODataRequest();

    odRequest.setBody(httpRequest.getInputStream());
    copyHeaders(odRequest, httpRequest);
    odRequest.setMethod(extractMethod(httpRequest));
    fillUriInformation(odRequest, httpRequest, split);

    return odRequest;
  } catch (final IOException e) {
    throw new SerializerException(
        "An I/O exception occurred.", e, SerializerException.MessageKeys.IO_EXCEPTION); //$NON-NLS-1$
  }
}
 
Example #10
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void dispatchComplexProperty() throws Exception {
  final String uri = "ESMixPrimCollComp(7)/PropertyComp";
  final ComplexProcessor processor = mock(ComplexProcessor.class);

  dispatch(HttpMethod.GET, uri, processor);
  verify(processor).readComplex(
      any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class), any(ContentType.class));

  dispatch(HttpMethod.PATCH, uri, processor);
  verify(processor).updateComplex(
      any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class), any(ContentType.class),
      any(ContentType.class));

  dispatch(HttpMethod.PUT, uri, processor);
  verify(processor, times(2)).updateComplex(
      any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class), any(ContentType.class),
      any(ContentType.class));

  dispatch(HttpMethod.DELETE, uri, processor);
  verify(processor).deleteComplex(any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class));

  dispatchMethodNotAllowed(HttpMethod.POST, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.HEAD, uri, processor);
}
 
Example #11
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * This method is invoked when a single entity has to be read.
 * In our example, this can be either a "normal" read operation, or a navigation:
 * 
 * Example for "normal" read operation:
 * http://localhost:8080/DemoService/DemoService.svc/Products(1)
 * 
 * Example for navigation
 * http://localhost:8080/DemoService/DemoService.svc/Products(1)/Category
 */
public void readEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
    throws ODataApplicationException, SerializerException {
  
  // The sample service supports only functions imports and entity sets.
  // We do not care about bound functions and composable functions.
  
  UriResource uriResource = uriInfo.getUriResourceParts().get(0); 
  
  if(uriResource instanceof UriResourceEntitySet) {
    readEntityInternal(request, response, uriInfo, responseFormat);
  } else if(uriResource instanceof UriResourceFunction) {
    readFunctionImportInternal(request, response, uriInfo, responseFormat);
  } else {
    throw new ODataApplicationException("Only EntitySet is supported",
        HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ENGLISH);
  }
  
}
 
Example #12
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void dispatchSingletonMedia() throws Exception {
  final String uri = "SIMedia/$value";
  final MediaEntityProcessor processor = mock(MediaEntityProcessor.class);
  
  dispatch(HttpMethod.GET, uri, processor);
  verify(processor).readMediaEntity(
      any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class), any(ContentType.class));

  dispatch(HttpMethod.PUT, uri, processor);
  verify(processor).updateMediaEntity(
      any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class), any(ContentType.class),
      any(ContentType.class));

  dispatchMethodNotAllowed(HttpMethod.PATCH, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.POST, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.DELETE, uri, processor);
}
 
Example #13
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void dispatchMedia() throws Exception {
  final String uri = "ESMedia(1)/$value";
  final MediaEntityProcessor processor = mock(MediaEntityProcessor.class);

  dispatch(HttpMethod.GET, uri, processor);
  verify(processor).readMediaEntity(
      any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class), any(ContentType.class));

  dispatch(HttpMethod.POST, "ESMedia", processor);
  verify(processor).createMediaEntity(any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class),
      any(ContentType.class), any(ContentType.class));

  dispatch(HttpMethod.PUT, uri, processor);
  verify(processor).updateMediaEntity(any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class),
      any(ContentType.class), any(ContentType.class));

  dispatch(HttpMethod.DELETE, uri, processor);
  verify(processor).deleteMediaEntity(any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class));

  dispatchMethodNotAllowed(HttpMethod.POST, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.PATCH, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.HEAD, uri, processor);
}
 
Example #14
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void createMediaEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
    ContentType requestFormat, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException {
  
  final EdmEntitySet edmEntitySet = Util.getEdmEntitySet(uriInfo);
  final byte[] mediaContent = odata.createFixedFormatDeserializer().binary(request.getBody());
  
  final Entity entity = storage.createMediaEntity(edmEntitySet.getEntityType(), 
                                                  requestFormat.toContentTypeString(), 
                                                  mediaContent);
  
  final ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).suffix(Suffix.ENTITY).build();
  final EntitySerializerOptions opts = EntitySerializerOptions.with().contextURL(contextUrl).build();
  final SerializerResult serializerResult = odata.createSerializer(responseFormat).entity(serviceMetadata,
      edmEntitySet.getEntityType(), entity, opts);
  
  final String location = request.getRawBaseUri() + '/'
      + odata.createUriHelper().buildCanonicalURL(edmEntitySet, entity);
  response.setContent(serializerResult.getContent());
  response.setStatusCode(HttpStatusCode.CREATED.getStatusCode());
  response.setHeader(HttpHeader.LOCATION, location);
  response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example #15
Source File: DefaultProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void readMetadata(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
    final ContentType requestedContentType) throws ODataApplicationException, ODataLibraryException {
  boolean isNotModified = false;
  ServiceMetadataETagSupport eTagSupport = serviceMetadata.getServiceMetadataETagSupport();
  if (eTagSupport != null && eTagSupport.getMetadataETag() != null) {
    // Set application etag at response
    response.setHeader(HttpHeader.ETAG, eTagSupport.getMetadataETag());
    // Check if metadata document has been modified
    ETagHelper eTagHelper = odata.createETagHelper();
    isNotModified = eTagHelper.checkReadPreconditions(eTagSupport.getMetadataETag(), request
        .getHeaders(HttpHeader.IF_MATCH), request.getHeaders(HttpHeader.IF_NONE_MATCH));
  }

  // Send the correct response
  if (isNotModified) {
    response.setStatusCode(HttpStatusCode.NOT_MODIFIED.getStatusCode());
  } else {
    // HTTP HEAD requires no payload but a 200 OK response
    if (HttpMethod.HEAD == request.getMethod()) {
      response.setStatusCode(HttpStatusCode.OK.getStatusCode());
    } else {
      ODataSerializer serializer = odata.createSerializer(requestedContentType);
      response.setContent(serializer.metadataDocument(serviceMetadata).getContent());
      response.setStatusCode(HttpStatusCode.OK.getStatusCode());
      response.setHeader(HttpHeader.CONTENT_TYPE, requestedContentType.toContentTypeString());
    }
  }
}
 
Example #16
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 #17
Source File: TechnicalEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void readEntity(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
    final ContentType requestedContentType) throws ODataApplicationException, ODataLibraryException {
  validateOptions(uriInfo.asUriInfoResource());

  readEntity(request, response, uriInfo, requestedContentType, false);
}
 
Example #18
Source File: CarsProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void updatePrimitive(final ODataRequest request, final ODataResponse response,
                            final UriInfo uriInfo, final ContentType requestFormat,
                            final ContentType responseFormat)
        throws ODataApplicationException, DeserializerException, SerializerException {
  throw new ODataApplicationException("Primitive property update is not supported yet.",
          HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ENGLISH);
}
 
Example #19
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
	response.setContent(serializedResponse.getContent());
	response.setStatusCode(HttpStatusCode.CREATED.getStatusCode());
	response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example #20
Source File: TechnicalEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void readEntityCollection(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
    final ContentType requestedContentType) throws ODataApplicationException, ODataLibraryException {
  validateOptions(uriInfo.asUriInfoResource());

  readEntityCollection(request, response, uriInfo, requestedContentType, false);
}
 
Example #21
Source File: ProductEntityProcessor.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
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);
    LOG.info("Reading entity {}", entity.getSelfLink());

    // 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 #22
Source File: CarsProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void readPrimitiveValue(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType format)
        throws ODataApplicationException, SerializerException {
  // First we have to figure out which entity set the requested entity is in
  final EdmEntitySet edmEntitySet = getEdmEntitySet(uriInfo.asUriInfoResource());
  // Next we fetch the requested entity from the database
  final Entity entity;
  try {
    entity = readEntityInternal(uriInfo.asUriInfoResource(), edmEntitySet);
  } catch (DataProviderException e) {
    throw new ODataApplicationException(e.getMessage(), 500, Locale.ENGLISH);
  }
  if (entity == null) {
    // If no entity was found for the given key we throw an exception.
    throw new ODataApplicationException("No entity found for this key", HttpStatusCode.NOT_FOUND
            .getStatusCode(), Locale.ENGLISH);
  } else {
    // Next we get the property value from the entity and pass the value to serialization
    UriResourceProperty uriProperty = (UriResourceProperty) uriInfo
            .getUriResourceParts().get(uriInfo.getUriResourceParts().size() - 1);
    EdmProperty edmProperty = uriProperty.getProperty();
    Property property = entity.getProperty(edmProperty.getName());
    if (property == null) {
      throw new ODataApplicationException("No property found", HttpStatusCode.NOT_FOUND
              .getStatusCode(), Locale.ENGLISH);
    } else {
      if (property.getValue() == null) {
        response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
      } else {
        String value = String.valueOf(property.getValue());
        ByteArrayInputStream serializerContent = new ByteArrayInputStream(
                value.getBytes(Charset.forName("UTF-8")));
        response.setContent(serializerContent);
        response.setStatusCode(HttpStatusCode.OK.getStatusCode());
        response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.TEXT_PLAIN.toContentTypeString());
      }
    }
  }
}
 
Example #23
Source File: ODataDispatcher.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void handleMediaValueDispatching(final ODataRequest request, final ODataResponse response,
    final UriResource resource) throws ContentNegotiatorException, 
   ODataApplicationException, ODataLibraryException,
    ODataHandlerException, PreconditionException {
  final HttpMethod method = request.getMethod();
  validatePreferHeader(request);
  if (method == HttpMethod.GET) {
    // This can be a GET on an EntitySet, Navigation or Function
    final ContentType requestedContentType = ContentNegotiator.
        doContentNegotiation(uriInfo.getFormatOption(),
        request, handler.getCustomContentTypeSupport(), RepresentationType.MEDIA);
    handler.selectProcessor(MediaEntityProcessor.class)
        .readMediaEntity(request, response, uriInfo, requestedContentType);
    // PUT and DELETE can only be called on EntitySets or Navigation properties which are media resources
  } else if (method == HttpMethod.PUT && (isEntityOrNavigationMedia(resource) 
      || isSingletonMedia(resource))) {
    validatePreconditions(request, true);
    final ContentType requestFormat = ContentType.parse(request.getHeader(HttpHeader.CONTENT_TYPE));
    final ContentType responseFormat = ContentNegotiator.doContentNegotiation(uriInfo.getFormatOption(),
        request, handler.getCustomContentTypeSupport(), RepresentationType.ENTITY);
    handler.selectProcessor(MediaEntityProcessor.class)
        .updateMediaEntity(request, response, uriInfo, requestFormat, responseFormat);
  } else if (method == HttpMethod.DELETE && isEntityOrNavigationMedia(resource)) {
    validatePreconditions(request, true);
    handler.selectProcessor(MediaEntityProcessor.class)
        .deleteMediaEntity(request, response, uriInfo);
  } else {
    throwMethodNotAllowed(method);
  }
}
 
Example #24
Source File: DataRequest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private static void setServiceRoot(ContextURL.Builder builder, ODataRequest request) {
  String serviceRoot = request.getRawBaseUri();
  if (serviceRoot != null) {
    try {
      if (!serviceRoot.endsWith("/")) {
        serviceRoot = serviceRoot + "/";
      }
      builder.serviceRoot(URI.create(serviceRoot));
    } catch (IllegalArgumentException e) {
      // ignore
    }
  }
}
 
Example #25
Source File: TechnicalActionProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void processActionVoid(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
    final ContentType requestFormat) throws ODataApplicationException, ODataLibraryException {
  final UriResourceAction resource =
      ((UriResourceAction) uriInfo.getUriResourceParts().get(uriInfo.getUriResourceParts().size() - 1));
  final EdmAction action = resource.getAction();
  readParameters(action, request.getBody(), requestFormat);
  response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example #26
Source File: ServiceDispatcher.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void executeIdOption(String query, ODataRequest odRequest,
    ODataResponse odResponse) throws ODataLibraryException,
    ODataApplicationException {
  StringBuilder sb = new StringBuilder();
  StringTokenizer st = new StringTokenizer(query, "&");
  boolean first = true;
  while(st.hasMoreTokens()) {
    String token = st.nextToken();
    if (token.startsWith("$id=")) {
      URI id = URI.create(Decoder.decode(token.substring(4)));
      sb.append(id.getPath());
    } else {
      if (first) {
        sb.append("?");
      } else {
        sb.append("&");
      }
      sb.append(token);
    }
  }    
  DataRequest dataRequest = new DataRequest(this.odata, this.metadata);
  this.request = dataRequest;
  
  this.request.setODataRequest(odRequest);
  this.request = this.request.parseLink(URI.create(sb.toString()));

  this.request.setODataRequest(odRequest);
  this.request.setCustomContentTypeSupport(this.customContentSupport);
  this.request.execute(this.handler, odResponse);    
}
 
Example #27
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 #28
Source File: ContentNegotiatorTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void testContentNegotiation(final String[] useCase, final RepresentationType representationType)
     throws Exception {

   FormatOption formatOption = null;
   if (useCase[1] != null) {
     formatOption = mock(FormatOption.class);
     when(formatOption.getFormat()).thenReturn(useCase[1]);
   }

   ODataRequest request = new ODataRequest();
   if (useCase[2] != null) {
     request.addHeader(HttpHeader.ACCEPT, Arrays.asList(useCase[2]));
   }

if (useCase.length > 4) {
     if (useCase[4] != null) {
       request.addHeader(HttpHeader.ACCEPT_CHARSET, Arrays.asList(useCase[4]));
     }
   }

   final CustomContentTypeSupport customContentTypeSupport = useCase[3] == null ? null :
     createCustomContentTypeSupport(useCase[3]);
   final ContentType requestedContentType = ContentNegotiator.doContentNegotiation(
         formatOption, request, customContentTypeSupport, representationType);
   assertNotNull(requestedContentType);
   if (useCase[0] != null) {
     assertEquals(ContentType.create(useCase[0]), requestedContentType);
   }
 }
 
Example #29
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void dispatchMediaDeleteIndirect() throws Exception {
  final MediaEntityProcessor processor = mock(MediaEntityProcessor.class);
  dispatch(HttpMethod.DELETE, "ESMedia(1)", processor);

  verify(processor).deleteEntity(any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class));
  dispatchMethodNotAllowed(HttpMethod.HEAD, "ESMedia(1)", processor);
}
 
Example #30
Source File: BatchRequestParserTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void nonStrictParser() throws Exception {
  final String batch = "--" + BOUNDARY + CRLF
      + HttpHeader.CONTENT_TYPE + ": " + MULTIPART_MIXED + ";boundary=" + CHANGESET_BOUNDARY + CRLF
      + "--" + CHANGESET_BOUNDARY + CRLF
      + MIME_HEADERS
      + HttpHeader.CONTENT_ID + ": myRequest" + CRLF
      + HttpMethod.PATCH + " ESAllPrim(32767)" + HTTP_VERSION + CRLF
      + ACCEPT_HEADER
      + HttpHeader.CONTENT_TYPE + ": " + APPLICATION_JSON + CRLF
      + "{\"PropertyString\":\"new\"}" + CRLF
      + "--" + CHANGESET_BOUNDARY + "--" + CRLF
      + "--" + BOUNDARY + "--";

  final List<BatchRequestPart> requests = parse(batch, false);

  Assert.assertNotNull(requests);
  Assert.assertEquals(1, requests.size());

  final BatchRequestPart part = requests.get(0);
  Assert.assertTrue(part.isChangeSet());
  Assert.assertNotNull(part.getRequests());
  Assert.assertEquals(1, part.getRequests().size());

  final ODataRequest changeRequest = part.getRequests().get(0);
  Assert.assertEquals("{\"PropertyString\":\"new\"}", IOUtils.toString(changeRequest.getBody()));
  Assert.assertEquals(APPLICATION_JSON, changeRequest.getHeader(HttpHeader.CONTENT_TYPE));
  Assert.assertEquals(HttpMethod.PATCH, changeRequest.getMethod());
}