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

The following examples show how to use org.apache.olingo.server.api.ODataResponse. 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: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void dispatchPrimitiveProperty() throws Exception {
  final String uri = "ESAllPrim(0)/PropertyString";
  final PrimitiveProcessor processor = mock(PrimitiveProcessor.class);

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

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

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

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

  dispatchMethodNotAllowed(HttpMethod.POST, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.HEAD, uri, processor);
}
 
Example #2
Source File: ErrorHandler.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
void handleServerError(final ODataRequest request, final ODataResponse response,
    final ODataServerError serverError) {
  try {
    ODataSerializer serializer = this.odata.createSerializer(this.contentType);
    ErrorResponse errorResponse = new ErrorResponse(this.metadata, serializer, this.contentType, response);
    handler.processError(serverError, errorResponse);
  } catch (Exception e) {
    // This should never happen but to be sure we have this catch here
    // to prevent sending a stacktrace to a client.
    String responseContent = "{\"error\":{\"code\":null,\"message\":\"An unexpected exception occurred during "
        + "error processing with message: " + e.getMessage() + "\"}}"; //$NON-NLS-1$ //$NON-NLS-2$
    response.setContent(new ByteArrayInputStream(responseContent.getBytes()));
    response.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode());
    response.setHeader(HttpHeader.CONTENT_TYPE,
        ContentType.APPLICATION_JSON.toContentTypeString());
  }
}
 
Example #3
Source File: AsyncResponseSerializerTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void biggerResponse() throws Exception {
  ODataResponse response = new ODataResponse();
  response.setStatusCode(HttpStatusCode.ACCEPTED.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.APPLICATION_JSON.toContentTypeString());
  response.setHeader(HttpHeader.CONTENT_LENGTH, String.valueOf(0));

  String testData = testData(20000);
  response.setContent(IOUtils.toInputStream(testData));

  AsyncResponseSerializer serializer = new AsyncResponseSerializer();
  InputStream in = serializer.serialize(response);
  String result = IOUtils.toString(in);
  assertEquals("HTTP/1.1 202 Accepted" + CRLF
      + "Content-Type: application/json" + CRLF
      + "Content-Length: 0" + CRLF + CRLF
      + testData, result);
}
 
Example #4
Source File: MockedBatchHandlerTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test(expected = BatchDeserializerException.class)
public void testInvalidMethod() 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 = getMimeHeader();
  final ODataResponse response = new ODataResponse();
  final ODataRequest request = buildODataRequest(content, header);
  request.setMethod(HttpMethod.GET);

  batchHandler.process(request, response, true);
}
 
Example #5
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 = 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 #6
Source File: ODataNettyHandlerImpl.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
@Override
public void processNettyRequest(HttpRequest request, HttpResponse response, 
		Map<String, String> requestParameters) {
	  ODataRequest odRequest = new ODataRequest();
    Exception exception = null;
    ODataResponse odResponse;
    
    final int processMethodHandle = 
    		debugger.startRuntimeMeasurement("ODataNettyHandlerImpl", "process");
    try {
      fillODataRequest(odRequest, request, 
          requestParameters.get(SPLIT) != null? Integer.parseInt(requestParameters.get(SPLIT)) : split, 
              requestParameters.get(CONTEXT_PATH));

      odResponse = process(odRequest);
      // ALL future methods after process must not throw exceptions!
    } catch (Exception e) {
      exception = e;
      odResponse = handleException(odRequest, e);
    }
    debugger.stopRuntimeMeasurement(processMethodHandle);

    convertToHttp(response, odResponse);
  }
 
Example #7
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void validateInvalidOdataVersionAndMaxVersion3() throws Exception {
  final String uri = "ESAllPrim(0)";
  final EntityProcessor processor = mock(EntityProcessor.class);

  final Map<String, String> headers = new HashMap<String, String>();
  headers.put(HttpHeader.ODATA_VERSION, "5.0");
  headers.put(HttpHeader.ODATA_MAX_VERSION, "5.0");
  
  final ODataResponse response = dispatchToValidateHeaders
      (HttpMethod.GET, uri, null, headers, processor);
  assertEquals("4.0", response.getHeader(HttpHeader.ODATA_VERSION));
  assertEquals(400, response.getStatusCode());
  assertNotNull(response.getContent());
  String doc = IOUtils.toString(response.getContent());
  assertTrue(doc.contains("OData version '5.0' is not supported."));
}
 
Example #8
Source File: BatchReferenceRewriter.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private String getODataPath(final ODataRequest request, final ODataResponse response)
    throws BatchDeserializerException {
  String resourceUri = null;

  if (request.getMethod() == HttpMethod.POST) {
    // Create entity
    // The URI of the new resource will be generated by the server and published in the location header
    final String locationHeader = response.getHeader(HttpHeader.LOCATION);
    resourceUri = locationHeader == null ? null : parseODataPath(locationHeader, request.getRawBaseUri());
  } else {
    // Update, Upsert (PUT, PATCH, Delete)
    // These methods still addresses a given resource, so we use the URI given by the request
    resourceUri = request.getRawODataPath();
  }

  return resourceUri;
}
 
Example #9
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void uriParserExceptionResultsInRightResponseEdmCause() throws Exception {
  final OData odata = OData.newInstance();
  final ServiceMetadata serviceMetadata = odata.createServiceMetadata(
      new CsdlAbstractEdmProvider() {
        @Override
        public CsdlEntitySet getEntitySet(final FullQualifiedName entityContainer, final String entitySetName)
            throws ODataException {
          throw new ODataException("msg");
        }
      },
      Collections.<EdmxReference> emptyList());

  ODataRequest request = new ODataRequest();
  request.setMethod(HttpMethod.GET);
  request.setRawODataPath("EdmException");

  final ODataResponse response =
      new ODataHandlerImpl(odata, serviceMetadata, new ServerCoreDebugger(odata)).process(request);
  assertNotNull(response);
  assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode());
}
 
Example #10
Source File: DefaultRedirectProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void redirect(final ODataRequest request, final ODataResponse response) {
  response.setStatusCode(HttpStatusCode.TEMPORARY_REDIRECT.getStatusCode());

  String location;

  String rawUri = request.getRawRequestUri();
  String rawQueryPath = request.getRawQueryPath();
  if (rawQueryPath == null) {
    location = request.getRawRequestUri() + "/";
  } else {
    location = rawUri.substring(0, rawUri.indexOf(rawQueryPath) - 1) + "/?" + rawQueryPath;
  }

  response.setHeader(HttpHeader.LOCATION, location);
}
 
Example #11
Source File: BatchRequest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
ODataResponsePart processChangeSet(BatchRequestPart partRequest, ServiceHandler serviceHandler)
    throws BatchDeserializerException {
  List<ODataResponse> changeSetResponses = new ArrayList<ODataResponse>();
  // change set need to be a in a atomic operation
  for (ODataRequest changeSetPartRequest : partRequest.getRequests()) {

    this.rewriter.replaceReference(changeSetPartRequest);

    ODataResponse partResponse = executeSingleRequest(changeSetPartRequest, serviceHandler);

    this.rewriter.addMapping(changeSetPartRequest, partResponse);
    addContentID(changeSetPartRequest, partResponse);

    if (partResponse.getStatusCode() < 400) {
      changeSetResponses.add(partResponse);
    } else {
      // 11.7.4 Responding to a Batch Request
      return new ODataResponsePart(partResponse, false);
    }
  }
  return new ODataResponsePart(changeSetResponses, true);
}
 
Example #12
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 #13
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 #14
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 #15
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void dispatchEntitySetCount() throws Exception {
  final String uri = "ESAllPrim/$count";
  final CountEntityCollectionProcessor processor = mock(CountEntityCollectionProcessor.class);

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

  dispatchMethodNotAllowed(HttpMethod.POST, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.PATCH, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.PUT, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.DELETE, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.HEAD, uri, processor);
}
 
Example #16
Source File: ODataDispatcher.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void handleValueDispatching(final ODataRequest request, final ODataResponse response,
    final int lastPathSegmentIndex) throws ODataApplicationException, ODataLibraryException {
  // The URI Parser already checked if $value is allowed here so we only have to dispatch to the correct processor
  final UriResource resource = uriInfo.getUriResourceParts().get(lastPathSegmentIndex - 1);
  if (resource instanceof UriResourceProperty
      || resource instanceof UriResourceFunction
          && ((UriResourceFunction) resource).getType().getKind() == EdmTypeKind.PRIMITIVE) {
    handlePrimitiveValueDispatching(request, response, resource);
  } else {
    handleMediaValueDispatching(request, response, resource);
  }
}
 
Example #17
Source File: DebugTabBodyTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void text() throws Exception {
  ODataResponse response = new ODataResponse();
  response.setContent(IOUtils.toInputStream("testText\n12"));
  assertEquals("\"testText\\n12\"", createJson(new DebugTabBody(response)));

  response.setContent(IOUtils.toInputStream("testText\n34"));
  assertEquals("<pre class=\"code\">\ntestText\n34\n</pre>\n", createHtml(new DebugTabBody(response)));
}
 
Example #18
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 #19
Source File: BatchReferenceRewriter.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void addMapping(final ODataRequest request, final ODataResponse response)
    throws BatchDeserializerException {
  final String resourceUri = getODataPath(request, response);
  final String contentId = request.getHeader(HttpHeader.CONTENT_ID);

  contentIdMapping.put(contentId, resourceUri);
}
 
Example #20
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void uriParserExceptionWithFormatQueryAtom() throws Exception {
  final ODataResponse response = dispatch(HttpMethod.GET, "ESAllPrims", "$format=atom", "", "", null);
  assertEquals(HttpStatusCode.NOT_FOUND.getStatusCode(), response.getStatusCode());
  assertEquals("application/json;odata.metadata=minimal",
      response.getHeader(HttpHeader.CONTENT_TYPE));
}
 
Example #21
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 #22
Source File: DefaultProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void readServiceDocument(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.getServiceDocumentETag() != null) {
    // Set application etag at response
    response.setHeader(HttpHeader.ETAG, eTagSupport.getServiceDocumentETag());
    // Check if service document has been modified
    ETagHelper eTagHelper = odata.createETagHelper();
    isNotModified = eTagHelper.checkReadPreconditions(eTagSupport.getServiceDocumentETag(), 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.serviceDocument(serviceMetadata, null).getContent());
      response.setStatusCode(HttpStatusCode.OK.getStatusCode());
      response.setHeader(HttpHeader.CONTENT_TYPE, requestedContentType.toContentTypeString());
    }
  }
}
 
Example #23
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 #24
Source File: ActionRequest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(ServiceHandler handler, ODataResponse response)
    throws ODataLibraryException, ODataApplicationException {

  // check for valid HTTP Verb
  assertHttpMethod(response);
  
  // Actions MAY return data but MUST NOT be further composed with additional
  // path segments.
  // On success, the response is 201 Created for actions that create entities,
  // 200 OK for actions
  // that return results or 204 No Content for action without a return type.
  // The client can request
  // whether any results from the action be returned using the Prefer header.

  if (!hasReturnType()) {
    handler.invoke(this, getETag(), new NoContentResponse(getServiceMetaData(), response));
  } else {
    if (isReturnTypePrimitive() || isReturnTypeComplex()) {
      handler.invoke(this, getETag(), PropertyResponse.getInstance(this, response,
          getReturnType().getType(), getContextURL(this.odata), isCollection()));
    } else {
      // EdmTypeKind.ENTITY
      if (isCollection()) {
        handler.invoke(this, getETag(),
            EntitySetResponse.getInstance(this, getContextURL(odata), false, response));
      } else {
        handler.invoke(this, getETag(),
            EntityResponse.getInstance(this, getContextURL(odata), false, response));
      }
    }
  }
}
 
Example #25
Source File: EntityResponse.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public static EntityResponse getInstance(ServiceRequest request, ContextURL contextURL,
    boolean references, ODataResponse response)
    throws ContentNegotiatorException, SerializerException {
  EntitySerializerOptions options = request.getSerializerOptions(EntitySerializerOptions.class,
      contextURL, references);
  return new EntityResponse(request.getServiceMetaData(), response, request.getSerializer(),
      options, request.getResponseContentType(), request.getPreferences(), null,
      request.getODataRequest().getRawBaseUri());
}
 
Example #26
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 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 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 #27
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 #28
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 #29
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 #30
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 result = serializer.entity(serviceMetadata, entityType, entity, options);
	
	//4. configure the response object
	response.setContent(result.getContent());
	response.setStatusCode(HttpStatusCode.OK.getStatusCode());
	response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}