org.apache.olingo.commons.api.http.HttpHeader Java Examples

The following examples show how to use org.apache.olingo.commons.api.http.HttpHeader. 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 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 #3
Source File: BasicBoundFunctionITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void boundFunctionReturningDerievedType() throws Exception {
  URL url = new URL(SERVICE_URI + "ESBase(111)/olingo.odata.test1.ETTwoBase/"
      + "olingo.odata.test1.BFESBaseRTESTwoBase()");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  final String expected =  "\"PropertyInt16\":111,"
      +  "\"PropertyString\":\"TEST A\","
      +  "\"AdditionalPropertyString_5\":\"TEST A 0815\","
      +  "\"AdditionalPropertyString_6\":\"TEST B 0815\"";
  String content = IOUtils.toString(connection.getInputStream());
  assertTrue(content.contains(expected));
  connection.disconnect();
}
 
Example #4
Source File: InOperatorITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void querySimple() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim?$filter=PropertyString%20in%20("
      + "%27Second%20Resource%20-%20negative%20values%27,%27xyz%27)");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=minimal");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertEquals(ContentType.JSON, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE)));

  final String content = IOUtils.toString(connection.getInputStream());
  assertTrue(content.contains("\"value\":[{\"PropertyInt16\":-32768,"
      + "\"PropertyString\":\"Second Resource - negative values\","
      + "\"PropertyBoolean\":false,\"PropertyByte\":0,\"PropertySByte\":-128,"
      + "\"PropertyInt32\":-2147483648,\"PropertyInt64\":-9223372036854775808,"
      + "\"PropertySingle\":-1.79E8,\"PropertyDouble\":-179000.0,\"PropertyDecimal\":-34,"
      + "\"PropertyBinary\":\"ASNFZ4mrze8=\",\"PropertyDate\":\"2015-11-05\","
      + "\"PropertyDateTimeOffset\":\"2005-12-03T07:17:08Z\",\"PropertyDuration\":\"PT9S\","
      + "\"PropertyGuid\":\"76543201-23ab-cdef-0123-456789dddfff\","
      + "\"PropertyTimeOfDay\":\"23:49:14\"}]"));
}
 
Example #5
Source File: AsyncBatchRequestWrapperImpl.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void retrieveMonitorDetails(final ODataBatchResponse res) {
  Collection<String> headers = res.getHeader(HttpHeader.LOCATION);
  if (headers == null || headers.isEmpty()) {
    throw new AsyncRequestException("Invalid async request response. Monitor URL not found");
  } else {
    this.location = createLocation(headers.iterator().next());
  }

  headers = res.getHeader(HttpHeader.RETRY_AFTER);
  if (headers != null && !headers.isEmpty()) {
    this.retryAfter = parseReplyAfter(headers.iterator().next());
  }

  headers = res.getHeader(HttpHeader.PREFERENCE_APPLIED);
  if (headers != null && !headers.isEmpty()) {
    for (String header : headers) {
      if (header.equalsIgnoreCase(new ODataPreferences().respondAsync())) {
        preferenceApplied = true;
      }
    }
  }

  IOUtils.closeQuietly(res.getRawResponse());
}
 
Example #6
Source File: BatchRequestParserTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void contentTypeCaseInsensitive() throws Exception {
  final String batch = "--" + BOUNDARY + CRLF
      + HttpHeader.CONTENT_TYPE + ": " + MULTIPART_MIXED + "; boundary=" + CHANGESET_BOUNDARY + CRLF
      + CRLF
      + "--" + CHANGESET_BOUNDARY + CRLF
      + MIME_HEADERS
      + HttpHeader.CONTENT_ID + ": 1" + CRLF
      + HttpHeader.CONTENT_LENGTH + ": 200" + CRLF
      + CRLF
      + HttpMethod.PATCH + " ESAllPrim(32767)" + HTTP_VERSION + CRLF
      + HttpHeader.CONTENT_TYPE + ": " + APPLICATION_JSON + CRLF
      + CRLF
      + "{\"PropertyString\":\"new\"}" + CRLF
      + "--" + CHANGESET_BOUNDARY + "--" + CRLF
      + CRLF
      + "--" + BOUNDARY + "--";

  parse(batch);
}
 
Example #7
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 #8
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleValuesInAcceptHeaderWithIncorrectParam() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json,"
      + "application/json;q=0.1,application/json;q=<1");
  connection.connect();

  assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode());

  final String content = IOUtils.toString(connection.getErrorStream());
  assertTrue(content.contains("The content-type range 'application/json;q=<1' is not "
      + "supported as value of the Accept header."));
}
 
Example #9
Source File: HeaderTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleValues() {
  Header header = new Header(1);
  header.addHeader(HttpHeader.CONTENT_TYPE, ContentType.MULTIPART_MIXED.toContentTypeString(), 1);
  header.addHeader(HttpHeader.CONTENT_TYPE, ContentType.APPLICATION_ATOM_SVC.toContentTypeString(), 2);
  header.addHeader(HttpHeader.CONTENT_TYPE, ContentType.APPLICATION_ATOM_XML.toContentTypeString(), 3);

  final String fullHeaderString =
      ContentType.MULTIPART_MIXED + ", " + ContentType.APPLICATION_ATOM_SVC + ", "
          + ContentType.APPLICATION_ATOM_XML;

  assertEquals(fullHeaderString, header.getHeader(HttpHeader.CONTENT_TYPE));
  assertEquals(3, header.getHeaders(HttpHeader.CONTENT_TYPE).size());
  assertEquals(ContentType.MULTIPART_MIXED.toContentTypeString(),
      header.getHeaders(HttpHeader.CONTENT_TYPE).get(0));
  assertEquals(ContentType.APPLICATION_ATOM_SVC.toContentTypeString(),
      header.getHeaders(HttpHeader.CONTENT_TYPE).get(1));
  assertEquals(ContentType.APPLICATION_ATOM_XML.toContentTypeString(),
      header.getHeaders(HttpHeader.CONTENT_TYPE).get(2));
}
 
Example #10
Source File: BasicHttpITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBaseTypeDerivedTypeCasting1() throws Exception {
  URL url = new URL(SERVICE_URI + "ESTwoPrim(111)/olingo.odata.test1.ETBase");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=full");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  final String content = IOUtils.toString(connection.getInputStream());

  assertTrue(content.contains("\"PropertyInt16\":111"));
  assertTrue(content.contains("\"PropertyString\":\"TEST A\""));
  assertTrue(content.contains("\"AdditionalPropertyString_5\":\"TEST A 0815\""));
  assertTrue(content.contains("\"@odata.type\":\"#olingo.odata.test1.ETBase\""));
}
 
Example #11
Source File: DebugTabBody.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public DebugTabBody(final ODataResponse response) {
  this.response = response;
  if (response != null) {
    final String contentTypeString = response.getHeader(HttpHeader.CONTENT_TYPE);
    if (contentTypeString != null) {
      if (contentTypeString.startsWith("application/json")) {
        responseContent = ResponseContent.JSON;
      } else if (contentTypeString.startsWith("image/")) {
        responseContent = ResponseContent.IMAGE;
      } else if (contentTypeString.contains("xml")) {
        responseContent = ResponseContent.XML;
      } else {
        responseContent = ResponseContent.TEXT;
      }
    } else {
      responseContent = ResponseContent.TEXT;
    }
  } else {
    responseContent = ResponseContent.TEXT;
  }
}
 
Example #12
Source File: BatchPartHandler.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public ODataResponse handle(final ODataRequest request, final boolean isChangeSet)
    throws BatchDeserializerException {
  ODataResponse response;

  if (isChangeSet) {
    rewriter.replaceReference(request);

    response = oDataHandler.process(request);

    rewriter.addMapping(request, response);
  } else {
    response = oDataHandler.process(request);
  }

  // Add content id to response
  final String contentId = request.getHeader(HttpHeader.CONTENT_ID);
  if (contentId != null) {
    response.setHeader(HttpHeader.CONTENT_ID, contentId);
  }

  return response;
}
 
Example #13
Source File: BatchTransformatorCommon.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static int getContentLength(final Header headers) throws BatchDeserializerException {
  final HeaderField contentLengthField = headers.getHeaderField(HttpHeader.CONTENT_LENGTH);

  if (contentLengthField != null && contentLengthField.getValues().size() == 1) {
    try {
      final int contentLength = Integer.parseInt(contentLengthField.getValues().get(0));

      if (contentLength < 0) {
        throw new BatchDeserializerException("Invalid content length", MessageKeys.INVALID_CONTENT_LENGTH,
            Integer.toString(contentLengthField.getLineNumber()));
      }

      return contentLength;
    } catch (NumberFormatException e) {
      throw new BatchDeserializerException("Invalid content length", e, MessageKeys.INVALID_CONTENT_LENGTH,
          Integer.toString(contentLengthField.getLineNumber()));
    }
  }

  return -1;
}
 
Example #14
Source File: EntityReferencesITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void updateReferenceAbsoluteURI() throws Exception {
  final URI uri = getClient().newURIBuilder(SERVICE_URI).appendEntitySetSegment(ES_KEY_NAV)
                                                   .appendKeySegment(1)
                                                   .appendNavigationSegment(NAV_PROPERTY_ET_KEY_NAV_ONE)
                                                   .appendRefSegment()
                                                   .build();
  
  final URI reference = getClient().newURIBuilder(SERVICE_URI).appendEntitySetSegment(ES_KEY_NAV)
                                                         .appendKeySegment(3)
                                                         .build();
  
  final ODataReferenceAddingResponse response = getClient().getCUDRequestFactory()
                                             .getReferenceSingleChangeRequest(new URI(SERVICE_URI), uri, reference)
                                             .execute();
  assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode());
  final String cookie = response.getHeader(HttpHeader.SET_COOKIE).iterator().next();

  final URI getURI = getClient().newURIBuilder(SERVICE_URI).appendEntitySetSegment(ES_KEY_NAV)
                                                      .appendKeySegment(1)
                                                      .expand(NAV_PROPERTY_ET_KEY_NAV_ONE)
                                                      .build();
  final ODataEntityRequest<ClientEntity> requestGet = getEdmEnabledClient().getRetrieveRequestFactory()
      .getEntityRequest(getURI);
  requestGet.addCustomHeader(HttpHeader.COOKIE, cookie);
  final ODataRetrieveResponse<ClientEntity> responseGet = requestGet.execute();
  assertEquals(HttpStatusCode.OK.getStatusCode(), responseGet.getStatusCode());
  
  assertShortOrInt(3, responseGet.getBody().getNavigationLink(NAV_PROPERTY_ET_KEY_NAV_ONE)
                                       .asInlineEntity()
                                       .getEntity()
                                       .getProperty(PROPERTY_INT16)
                                       .getPrimitiveValue()
                                       .asPrimitive().toValue());
}
 
Example #15
Source File: InOperatorITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void queryInOperatorWithFunction() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim?$filter=PropertyString%20in%20olingo.odata.test1.UFCRTCollString()");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=minimal");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertEquals(ContentType.JSON, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE)));

  final String content = IOUtils.toString(connection.getInputStream());
  assertTrue(content.contains("\"value\":[{\"PropertyInt16\":10,"
      + "\"PropertyString\":\"[email protected]\","
      + "\"PropertyBoolean\":false,\"PropertyByte\":0,\"PropertySByte\":0,"
      + "\"PropertyInt32\":0,\"PropertyInt64\":0,\"PropertySingle\":0.0,"
      + "\"PropertyDouble\":0.0,\"PropertyDecimal\":0,\"PropertyBinary\":\"\","
      + "\"PropertyDate\":\"1970-01-01\","
      + "\"PropertyDateTimeOffset\":\"2005-12-03T00:00:00Z\","
      + "\"PropertyDuration\":\"PT0S\","
      + "\"PropertyGuid\":\"76543201-23ab-cdef-0123-456789cccddd\","
      + "\"PropertyTimeOfDay\":\"00:01:01\"}]"));
}
 
Example #16
Source File: BatchRequestParserTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void nonNumericContentLength() throws Exception {
  final String batch = "--" + BOUNDARY + CRLF
      + HttpHeader.CONTENT_TYPE + ": " + MULTIPART_MIXED + "; boundary=" + CHANGESET_BOUNDARY + CRLF
      + CRLF
      + "--" + CHANGESET_BOUNDARY + CRLF
      + MIME_HEADERS
      + HttpHeader.CONTENT_ID + ": 1" + CRLF
      + CRLF
      + HttpMethod.PATCH + " ESAllPrim(32767)" + HTTP_VERSION + CRLF
      + HttpHeader.CONTENT_TYPE + ": " + APPLICATION_JSON + CRLF
      + HttpHeader.CONTENT_LENGTH + ": 10abc" + CRLF
      + CRLF
      + "{\"PropertyString\":\"new\"}" + CRLF
      + "--" + CHANGESET_BOUNDARY + "--" + CRLF
      + CRLF
      + "--" + BOUNDARY + "--";

  parseInvalidBatchBody(batch, BatchDeserializerException.MessageKeys.INVALID_CONTENT_LENGTH);
}
 
Example #17
Source File: ServiceRequest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public Map<String, String> getPreferences(){
  HashMap<String, String> map = new HashMap<>();
  List<String> headers = request.getHeaders(HttpHeader.PREFER);
  if (headers != null) {
    for (String header:headers) {
      int idx = header.indexOf('=');
      if (idx != -1) {
        String key = header.substring(0, idx);
        String value = header.substring(idx+1);
        if (value.startsWith("\"")) {
          value = value.substring(1);
        }
        if (value.endsWith("\"")) {
          value = value.substring(0, value.length()-1);
        }
        map.put(key, value);
      } else {
        map.put(header, "true");
      }
    }
  }
  return map;
}
 
Example #18
Source File: ODataVersionConformanceITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void validODataVersionAndMaxVersionHeader1() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim?$format=json");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ODATA_VERSION, "4.0");
  connection.setRequestProperty(HttpHeader.ODATA_MAX_VERSION, "4.01");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertEquals("4.0", connection.getHeaderField(HttpHeader.ODATA_VERSION));
  assertEquals("application/json; odata.metadata=minimal", 
      connection.getHeaderField(HttpHeader.CONTENT_TYPE));

  final String content = IOUtils.toString(connection.getInputStream());
  assertNotNull(content);
}
 
Example #19
Source File: BasicHttpITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFilterWithInvalidFormEncoding() throws Exception {
  URL url = new URL(SERVICE_URI + 
      "ESAllPrim?$filter=PropertyInt16+eq+1&odata-accept-forms-encoding=qwer");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=full");
  connection.connect();

  assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode());
}
 
Example #20
Source File: BasicBoundFunctionITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void boundFunctionCETReturningPT() throws Exception {
  URL url = new URL(SERVICE_URI + "ESTwoKeyNav/olingo.odata.test1.BFNESTwoKeyNavRTString()");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  String content = IOUtils.toString(connection.getInputStream());
  assertNotNull(content);
  connection.disconnect();
}
 
Example #21
Source File: DeepInsertITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private String getCookie() {
  final EdmEnabledODataClient client = getEdmEnabledClient();
  final ODataRetrieveResponse<ClientEntitySet> response = client.getRetrieveRequestFactory()
      .getEntitySetRequest(client.newURIBuilder(SERVICE_URI).appendEntitySetSegment(ES_KEY_NAV).build())
      .execute();

  return response.getHeader(HttpHeader.SET_COOKIE).iterator().next();
}
 
Example #22
Source File: HeaderTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void caseInsensitive() {
  Header header = new Header(1);
  header.addHeader(HttpHeader.CONTENT_TYPE, ContentType.MULTIPART_MIXED.toContentTypeString(), 1);

  assertEquals(ContentType.MULTIPART_MIXED.toContentTypeString(), header.getHeader("cOnTenT-TyPE"));
  assertEquals(1, header.getHeaders("cOnTenT-TyPE").size());
  assertEquals(ContentType.MULTIPART_MIXED.toContentTypeString(), header.getHeaders("cOnTenT-TyPE").get(0));
}
 
Example #23
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 #24
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 #25
Source File: DemoBatchProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void processBatch(final BatchFacade facade, final ODataRequest request, final ODataResponse response)
    throws ODataApplicationException, ODataLibraryException {
  
  // 1. Extract the boundary
  final String boundary = facade.extractBoundaryFromContentType(request.getHeader(HttpHeader.CONTENT_TYPE));
  
  // 2. Prepare the batch options
  final BatchOptions options = BatchOptions.with().rawBaseUri(request.getRawBaseUri())
                                                  .rawServiceResolutionUri(request.getRawServiceResolutionUri())
                                                  .build();
  
  // 3. Deserialize the batch request
  final List<BatchRequestPart> requestParts = odata.createFixedFormatDeserializer()
                                                   .parseBatchRequest(request.getBody(), boundary, options);
  
  // 4. Execute the batch request parts
  final List<ODataResponsePart> responseParts = new ArrayList<ODataResponsePart>();
  for (final BatchRequestPart part : requestParts) {
    responseParts.add(facade.handleBatchRequest(part));
  }

  // 5. Serialize the response content
  final InputStream responseContent = odata.createFixedFormatSerializer().batchResponse(responseParts, boundary);
  
  // 6. Create a new boundary for the response
  final String responseBoundary = "batch_" + UUID.randomUUID().toString();

  // 7. Setup response
  response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.MULTIPART_MIXED + ";boundary=" + responseBoundary);
  response.setContent(responseContent);
  response.setStatusCode(HttpStatusCode.ACCEPTED.getStatusCode());
}
 
Example #26
Source File: BatchClientITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void getBatchRequest() {
  ODataBatchRequest request = getClient().getBatchRequestFactory().getBatchRequest(SERVICE_URI);
  setCookieHeader(request);
  BatchManager payload = request.payloadManager();

  // create new request
  payload.addRequest(createGetRequest("ESAllPrim", 32767, false));

  // Fetch result
  final ODataBatchResponse response = payload.getResponse();
  saveCookieHeader(response);

  assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode());
  assertEquals("OK", response.getStatusMessage());

  final Iterator<ODataBatchResponseItem> iter = response.getBody();
  assertTrue(iter.hasNext());

  ODataBatchResponseItem item = iter.next();
  assertFalse(item.isChangeset());

  ODataResponse oDataResponse = item.next();
  assertNotNull(oDataResponse);
  assertEquals(HttpStatusCode.OK.getStatusCode(), oDataResponse.getStatusCode());
  assertEquals(1, oDataResponse.getHeader(HttpHeader.ODATA_VERSION).size());
  assertEquals("4.0", oDataResponse.getHeader(HttpHeader.ODATA_VERSION).iterator().next());
  assertEquals(1, oDataResponse.getHeader(HttpHeader.CONTENT_LENGTH).size());
  assertEquals(isJson() ? "605" : "2223", oDataResponse.getHeader(HttpHeader.CONTENT_LENGTH).iterator().next());
  assertContentType(oDataResponse.getContentType());
}
 
Example #27
Source File: EntityReferencesITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void deleteReferenceOnSingleNavigationProperty() {
  final ODataClient client = getClient();
  final URI uri = client.newURIBuilder(SERVICE_URI)
                        .appendEntitySetSegment(ES_KEY_NAV)
                        .appendKeySegment(1)
                        .appendNavigationSegment(NAV_PROPERTY_ET_KEY_NAV_ONE)
                        .appendRefSegment()
                        .build();
  
  final ODataDeleteResponse deleteResponse = client.getCUDRequestFactory().getDeleteRequest(uri).execute();
  final String cookie = deleteResponse.getHeader(HttpHeader.SET_COOKIE).iterator().next();
  
  final URI uriGet = client.newURIBuilder(SERVICE_URI)
                           .appendEntitySetSegment(ES_KEY_NAV)
                           .appendKeySegment(1)
                           .expand(NAV_PROPERTY_ET_KEY_NAV_ONE)
                           .build();
  final ODataEntityRequest<ClientEntity> requestGet = client.getRetrieveRequestFactory().getEntityRequest(uriGet);
  requestGet.addCustomHeader(HttpHeader.COOKIE, cookie);
  final ODataRetrieveResponse<ClientEntity> responseGet = requestGet.execute();
  
  
  if (isJson()) {
    assertEquals(0, responseGet.getBody().getNavigationLinks().size());
  } else {
    // in xml the links will be always present; but the content will not be if no $expand unlike 
    // json;metadata=minimal; json=full is same as application/xml
    assertEquals(6, responseGet.getBody().getNavigationLinks().size());
  }
}
 
Example #28
Source File: BatchResponseSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void appendResponseHeader(final ODataResponse response, final int contentLength,
    final BodyBuilder builder) {
  final Map<String, List<String>> header = response.getAllHeaders();

  for (final Map.Entry<String, List<String>> entry : header.entrySet()) {
    // Requests never have a content id header.
    if (!entry.getKey().equalsIgnoreCase(HttpHeader.CONTENT_ID)) {
      appendHeader(entry.getKey(), entry.getValue().get(0), builder);
    }
  }

  appendHeader(HttpHeader.CONTENT_LENGTH, Integer.toString(contentLength), builder);
}
 
Example #29
Source File: MediaITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void create() throws Exception {
  ODataMediaEntityCreateRequest<ClientEntity> request =
      getClient().getCUDRequestFactory().getMediaEntityCreateRequest(
          getClient().newURIBuilder(TecSvcConst.BASE_URI).appendEntitySetSegment("ESMedia").build(),
          IOUtils.toInputStream("just a test"));
  request.setContentType(ContentType.TEXT_PLAIN.toContentTypeString());
  assertNotNull(request);

  final ODataMediaEntityCreateResponse<ClientEntity> response = request.payloadManager().getResponse();
  assertEquals(HttpStatusCode.CREATED.getStatusCode(), response.getStatusCode());
  assertEquals(request.getURI() + "(5)", response.getHeader(HttpHeader.LOCATION).iterator().next());
  final ClientEntity entity = response.getBody();
  assertNotNull(entity);
  final ClientProperty property = entity.getProperty("PropertyInt16");
  assertNotNull(property);
  assertNotNull(property.getPrimitiveValue());
  assertShortOrInt(5, property.getPrimitiveValue().toValue());

  // Check that the media stream has been created.
  // This check has to be in the same session in order to access the same data provider.
  ODataMediaRequest mediaRequest = getClient().getRetrieveRequestFactory().getMediaRequest(
      getClient().newURIBuilder(TecSvcConst.BASE_URI).appendEntitySetSegment("ESMedia")
          .appendKeySegment(5).appendValueSegment().build());
  mediaRequest.addCustomHeader(HttpHeader.COOKIE, response.getHeader(HttpHeader.SET_COOKIE).iterator().next());
  ODataRetrieveResponse<InputStream> mediaResponse = mediaRequest.execute();
  assertEquals(HttpStatusCode.OK.getStatusCode(), mediaResponse.getStatusCode());
  assertEquals(ContentType.TEXT_PLAIN.toContentTypeString(), mediaResponse.getContentType());
  assertEquals("just a test", IOUtils.toString(mediaResponse.getBody()));
}
 
Example #30
Source File: BatchRequestParserTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void contentLengthGreatherThanBodyLength() throws Exception {
  final String batch = "--" + BOUNDARY + CRLF
      + HttpHeader.CONTENT_TYPE + ": " + MULTIPART_MIXED + "; boundary=" + CHANGESET_BOUNDARY + CRLF
      + CRLF
      + "--" + CHANGESET_BOUNDARY + CRLF
      + MIME_HEADERS
      + HttpHeader.CONTENT_ID + ": 1" + CRLF
      + CRLF
      + HttpMethod.PATCH + " ESAllPrim(32767)" + HTTP_VERSION + CRLF
      + HttpHeader.CONTENT_TYPE + ": " + APPLICATION_JSON + CRLF
      + HttpHeader.CONTENT_LENGTH + ": 100000" + CRLF
      + CRLF
      + "{\"PropertyString\":\"new\"}" + CRLF
      + "--" + CHANGESET_BOUNDARY + "--" + CRLF
      + CRLF
      + "--" + BOUNDARY + "--";
  final List<BatchRequestPart> batchRequestParts = parse(batch);

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

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

  final ODataRequest request = part.getRequests().get(0);
  Assert.assertEquals("{\"PropertyString\":\"new\"}", IOUtils.toString(request.getBody()));
}