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

The following examples show how to use org.apache.olingo.server.api.ODataResponse#setContent() . 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: AsyncResponseSerializerTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleResponse() throws Exception {
  ODataResponse response = new ODataResponse();
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.APPLICATION_JSON.toContentTypeString());
  response.setHeader(HttpHeader.CONTENT_LENGTH, String.valueOf(200));

  response.setContent(IOUtils.toInputStream("Walter Winter" + CRLF));

  AsyncResponseSerializer serializer = new AsyncResponseSerializer();
  InputStream in = serializer.serialize(response);
  String result = IOUtils.toString(in);
  assertEquals("HTTP/1.1 200 OK" + CRLF
      + "Content-Type: application/json" + CRLF
      + "Content-Length: 200" + CRLF + CRLF
      + "Walter Winter" + CRLF, result);
}
 
Example 3
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 4
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 5
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 6
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 7
Source File: BatchResponseSerializerTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void bigResponse() throws Exception {
  List<ODataResponsePart> parts = new ArrayList<ODataResponsePart>();

  ODataResponse response = new ODataResponse();
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.TEXT_PLAIN.toContentTypeString());
  String bigData = generateData(10000);
  response.setContent(IOUtils.toInputStream(bigData));
  parts.add(new ODataResponsePart(Collections.singletonList(response), false));

  final BatchResponseSerializer serializer = new BatchResponseSerializer();
  final InputStream content = serializer.serialize(parts, BOUNDARY);

  assertNotNull(content);
  final BatchLineReader reader = new BatchLineReader(content);
  final List<String> body = reader.toList();
  reader.close();

  int line = 0;
  assertEquals(10, body.size());
  assertEquals("--" + BOUNDARY + CRLF, body.get(line++));
  assertEquals("Content-Type: application/http" + CRLF, body.get(line++));
  assertEquals("Content-Transfer-Encoding: binary" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals("HTTP/1.1 200 OK" + CRLF, body.get(line++));
  assertEquals("Content-Type: text/plain" + CRLF, body.get(line++));
  assertEquals("Content-Length: 10000" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals(bigData + CRLF, body.get(line++));
  assertEquals("--" + BOUNDARY + "--" + CRLF, body.get(line++));
}
 
Example 8
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 = null;
	
	try {
	  storage.beginTransaction();
	  createdEntity = storage.createEntityData(edmEntitySet, requestEntity, request.getRawBaseUri());
	  storage.commitTransaction();
	} catch( ODataApplicationException e ) {
	  storage.rollbackTransaction();
	  throw e;
	}
	  
	  // 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 9
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 10
Source File: BatchResponseSerializerTest.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Test
public void testODataContentWithODataResponse() throws Exception {
  List<ODataResponsePart> parts = new ArrayList<ODataResponsePart>();
  
  ODataResponse response = new ODataResponse();
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.TEXT_PLAIN.toContentTypeString());
  String bigData = generateData(10000);
  response.setContent(IOUtils.toInputStream(bigData));
  parts.add(new ODataResponsePart(response, false));
  
  ServiceMetadata serviceMetadata = mock(ServiceMetadata.class);
  final EdmEntityType edmEntityType = mock(EdmEntityType.class);
  EntityIterator entityCollection = new EntityIterator() {
    
    @Override
    public Entity next() {
      return null;
    }
    
    @Override
    public boolean hasNext() {
      return false;
    }
  };  

  SerializerStreamResult serializerResult = OData.newInstance().
      createSerializer(ContentType.APPLICATION_JSON).entityCollectionStreamed(
      serviceMetadata,
      edmEntityType,
      entityCollection,
      EntityCollectionSerializerOptions.with().contextURL
      (ContextURL.with().oDataPath("http://host/svc").build()).build());
  ODataResponse response1 = new ODataResponse();
  response1.setODataContent(serializerResult.getODataContent());
  response1.setStatusCode(HttpStatusCode.OK.getStatusCode());
  parts.add(new ODataResponsePart(response1, false));

  BatchResponseSerializer serializer = new BatchResponseSerializer();
  final InputStream content = serializer.serialize(parts, BOUNDARY);

  assertNotNull(content);

  final BatchLineReader reader = new BatchLineReader(content);
  final List<String> body = reader.toList();
  reader.close();

  int line = 0;
  assertEquals(18, body.size());
  assertEquals("--" + BOUNDARY + CRLF, body.get(line++));
  assertEquals("Content-Type: application/http" + CRLF, body.get(line++));
  assertEquals("Content-Transfer-Encoding: binary" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals("HTTP/1.1 200 OK" + CRLF, body.get(line++));
  assertEquals("Content-Type: text/plain" + CRLF, body.get(line++));
  assertEquals("Content-Length: 10000" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals(bigData + CRLF, body.get(line++));
  assertEquals("--" + BOUNDARY + CRLF, body.get(line++));
  assertEquals("Content-Type: application/http" + CRLF, body.get(line++));
  assertEquals("Content-Transfer-Encoding: binary" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals("HTTP/1.1 200 OK" + CRLF, body.get(line++));
  assertEquals("Content-Length: 47" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals("{\"@odata.context\":\"../../$metadata\",\"value\":[]}" + CRLF, body.get(line++));
  assertEquals("--" + BOUNDARY + "--" + CRLF, body.get(line++));
}
 
Example 11
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
	// the last segment is the Property
	UriResourceProperty uriProperty = (UriResourceProperty)resourceParts.get(resourceParts.size() -1); 
	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 serializerResult = serializer.primitive(serviceMetadata, edmPropertyType, property, options);
		InputStream propertyStream = serializerResult.getContent();

		//4. configure the response object
		response.setContent(propertyStream);
		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 12
Source File: TechnicalBatchProcessor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public void processBatch(final BatchFacade facade, final ODataRequest request, final ODataResponse response)
    throws ODataApplicationException, ODataLibraryException {
  // only the first batch call (process batch) must be handled in a separate way for async support
  // because a changeset has to be wrapped within a process batch call
  if(odata.createPreferences(request.getHeaders(HttpHeader.PREFER)).hasRespondAsync()) {
    TechnicalAsyncService asyncService = TechnicalAsyncService.getInstance();
    BatchProcessor processor = new TechnicalBatchProcessor(dataProvider);
    processor.init(odata, serviceMetadata);
    AsyncProcessor<BatchProcessor> asyncProcessor = asyncService.register(processor, BatchProcessor.class);
    asyncProcessor.prepareFor().processBatch(facade, request, response);
    String location = asyncProcessor.processAsync();
    TechnicalAsyncService.acceptedResponse(response, location);
    //
    return;
  }


  final boolean continueOnError =
      odata.createPreferences(request.getHeaders(HttpHeader.PREFER)).hasContinueOnError();

  final String boundary = facade.extractBoundaryFromContentType(request.getHeader(HttpHeader.CONTENT_TYPE));
  final BatchOptions options = BatchOptions.with()
      .rawBaseUri(request.getRawBaseUri())
      .rawServiceResolutionUri(request.getRawServiceResolutionUri()).build();
  final List<BatchRequestPart> parts = odata.createFixedFormatDeserializer().parseBatchRequest(request.getBody(),
      boundary, options);
  final List<ODataResponsePart> responseParts = new ArrayList<ODataResponsePart>();

  for (BatchRequestPart part : parts) {
    final ODataResponsePart responsePart = facade.handleBatchRequest(part);
    responseParts.add(responsePart); // Also add failed responses.
    final int statusCode = responsePart.getResponses().get(0).getStatusCode();

    if ((statusCode >= 400 && statusCode <= 600) && !continueOnError) {

      // Perform some additional actions.
      // ...

      break; // Stop processing, but serialize responses to all recent requests.
    }
  }

  final String responseBoundary = "batch_" + UUID.randomUUID().toString();
  final InputStream responseContent =
      odata.createFixedFormatSerializer().batchResponse(responseParts, responseBoundary);
  response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.MULTIPART_MIXED + ";boundary=" + responseBoundary);
  response.setContent(responseContent);
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  if (continueOnError) {
    response.setHeader(HttpHeader.PREFERENCE_APPLIED,
        PreferencesApplied.with().continueOnError().build().toValueString());
  }
}
 
Example 13
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 14
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
  // the last segment is the Property
  UriResourceProperty uriProperty = (UriResourceProperty) resourceParts.get(resourceParts.size() - 1);
  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 serializerResult = serializer.primitive(serviceMetadata, edmPropertyType, property, options);
    InputStream propertyStream = serializerResult.getContent();

    // 4. configure the response object
    response.setContent(propertyStream);
    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 15
Source File: TechnicalActionProcessor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public void processActionPrimitiveCollection(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;
  List<UriResource> uriResource = uriInfo.asUriInfoResource().getUriResourceParts();
  Property property = null;
  if (uriResource.size() > 1) {
    UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) uriResource.get(0);
    action = ((UriResourceAction) uriResource.get(uriResource.size() - 1)).getAction();
    parameters = readParameters(action, request.getBody(), requestFormat);
    property = dataProvider.processBoundActionPrimitiveCollection(action.getName(), parameters, 
        uriResourceEntitySet.getEntitySet(), uriResourceEntitySet.getKeyPredicates());
  } else {
    action = ((UriResourceAction) uriResource.get(0))
        .getAction();
    parameters = readParameters(action, request.getBody(), requestFormat);
    property =
        dataProvider.processActionPrimitiveCollection(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 EdmPrimitiveType type = (EdmPrimitiveType) action.getReturnType().getType();
    final ContextURL contextURL = ContextURL.with().type(type).navOrPropertyPath(action.getName())
        .asCollection().build();
    final PrimitiveSerializerOptions options = PrimitiveSerializerOptions.with().contextURL(contextURL).build();
    final SerializerResult result =
        odata.createSerializer(responseFormat).primitiveCollection(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 16
Source File: BatchResponseSerializerTest.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Test
public void batchResponseUmlautsUtf8() throws Exception {
  List<ODataResponsePart> parts = new ArrayList<ODataResponsePart>();

  ODataResponse response = new ODataResponse();
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.APPLICATION_JSON.toContentTypeString());
  response.setContent(IOUtils.toInputStream("{\"name\":\"Wälter Winter\"}" + CRLF));
  parts.add(new ODataResponsePart(Collections.singletonList(response), false));

  ODataResponse changeSetResponse = new ODataResponse();
  changeSetResponse.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
  changeSetResponse.setHeader(HttpHeader.CONTENT_ID, "1");
  parts.add(new ODataResponsePart(Collections.singletonList(changeSetResponse), true));

  BatchResponseSerializer serializer = new BatchResponseSerializer();
  final InputStream content = serializer.serialize(parts, BOUNDARY);
  assertNotNull(content);
  final BatchLineReader reader = new BatchLineReader(content);
  final List<String> body = reader.toList();
  reader.close();

  int line = 0;
  assertEquals(24, body.size());
  assertEquals("--" + BOUNDARY + CRLF, body.get(line++));
  assertEquals("Content-Type: application/http" + CRLF, body.get(line++));
  assertEquals("Content-Transfer-Encoding: binary" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals("HTTP/1.1 200 OK" + CRLF, body.get(line++));
  assertEquals("Content-Type: application/json" + CRLF, body.get(line++));
  assertEquals("Content-Length: 27" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals("{\"name\":\"Wälter Winter\"}" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals("--" + BOUNDARY + CRLF, body.get(line++));
  assertTrue(body.get(line++).startsWith("Content-Type: multipart/mixed; boundary=changeset_"));
  assertEquals(CRLF, body.get(line++));
  assertTrue(body.get(line++).startsWith("--changeset_"));
  assertEquals("Content-Type: application/http" + CRLF, body.get(line++));
  assertEquals("Content-Transfer-Encoding: binary" + CRLF, body.get(line++));
  assertEquals("Content-ID: 1" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals("HTTP/1.1 204 No Content" + CRLF, body.get(line++));
  assertEquals("Content-Length: 0" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertTrue(body.get(line++).startsWith("--changeset_"));
  assertEquals("--" + BOUNDARY + "--" + CRLF, body.get(line++));
}
 
Example 17
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 4 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 = null;
  try {
    storage.beginTransaction();
    createdEntity = storage.createEntityData(edmEntitySet, requestEntity, request.getRawBaseUri());
    storage.commitTransaction();
  } catch(ODataApplicationException e) {
    storage.rollbackTranscation();
    throw e;
  }

  // 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 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: 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 20
Source File: BatchResponseSerializerTest.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Test
public void batchResponse() throws Exception {
  final List<ODataResponsePart> parts = new ArrayList<ODataResponsePart>();
  ODataResponse response = new ODataResponse();
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.TEXT_PLAIN.toContentTypeString());
  response.setContent(IOUtils.toInputStream("Walter Winter" + CRLF));
  parts.add(new ODataResponsePart(Collections.singletonList(response), false));

  ODataResponse changeSetResponse = new ODataResponse();
  changeSetResponse.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
  changeSetResponse.setHeader(HttpHeader.CONTENT_ID, "1");
  parts.add(new ODataResponsePart(Collections.singletonList(changeSetResponse), true));

  BatchResponseSerializer serializer = new BatchResponseSerializer();
  final InputStream content = serializer.serialize(parts, BOUNDARY);
  assertNotNull(content);
  final BatchLineReader reader = new BatchLineReader(content);
  final List<String> body = reader.toList();
  reader.close();

  int line = 0;
  assertEquals(24, body.size());
  assertEquals("--" + BOUNDARY + CRLF, body.get(line++));
  assertEquals("Content-Type: application/http" + CRLF, body.get(line++));
  assertEquals("Content-Transfer-Encoding: binary" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals("HTTP/1.1 200 OK" + CRLF, body.get(line++));
  assertEquals("Content-Type: text/plain" + CRLF, body.get(line++));
  assertEquals("Content-Length: 15" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals("Walter Winter" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals("--" + BOUNDARY + CRLF, body.get(line++));
  assertTrue(body.get(line++).startsWith("Content-Type: multipart/mixed; boundary=changeset_"));
  assertEquals(CRLF, body.get(line++));
  assertTrue(body.get(line++).startsWith("--changeset_"));
  assertEquals("Content-Type: application/http" + CRLF, body.get(line++));
  assertEquals("Content-Transfer-Encoding: binary" + CRLF, body.get(line++));
  assertEquals("Content-ID: 1" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals("HTTP/1.1 204 No Content" + CRLF, body.get(line++));
  assertEquals("Content-Length: 0" + CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertEquals(CRLF, body.get(line++));
  assertTrue(body.get(line++).startsWith("--changeset_"));
  assertEquals("--" + BOUNDARY + "--" + CRLF, body.get(line++));
}