Java Code Examples for org.apache.olingo.commons.api.format.ContentType#parse()

The following examples show how to use org.apache.olingo.commons.api.format.ContentType#parse() . 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: ClientEntitySetIteratorTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetEntitySetIteratorWithInnerNavArray() throws IOException, URISyntaxException {
    String str = "{\"@odata.context\":\"$metadata#Cubes(Name)\","
        + "\"value\":[{\"@odata.etag\":\"W/\\\"c24af675e00a3f95ef63f223fb9c2cc8d6455459\\\"\","
        + "\"Name\":\"}Capabilities\","
        + "\"NavProp\":[{\"PropertyInt1\":1},{\"PropertyInt2\":2}]},"
        + "{\"@odata.etag\":\"W/\\\"c24af675e00a3f95ef63f223fb9c2cc8d6455459\\\"\",\"Name\":\"ABC()}\","
        + "\"NavProp\":[{\"PropertyInt1\":3}]}]}";
    
    InputStream stream = new ByteArrayInputStream(str.getBytes());
    ODataClient oDataClient = ODataClientFactory.getClient();
    ClientEntitySetIterator<ClientEntitySet, ClientEntity> entitySetIterator = 
        new ClientEntitySetIterator<ClientEntitySet, ClientEntity>(
        oDataClient, stream, ContentType.parse(ContentType.JSON.toString()));

    ArrayList<ClientEntity> entities = new ArrayList<ClientEntity>();
    while (entitySetIterator.hasNext()) {
        ClientEntity next = entitySetIterator.next();
        entities.add(next);
    }

    Assert.assertEquals(2, entities.size());
    Assert.assertNotNull(entities.get(0).getProperty("NavProp"));
    Assert.assertTrue(entities.get(0).getProperty("NavProp").hasCollectionValue());
    Assert.assertEquals("}Capabilities", entities.get(0).getProperty("Name").getPrimitiveValue().toString());
}
 
Example 2
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void validAcceptCharsetHeader() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf-8;q=0.1");
  connection.setRequestProperty(HttpHeader.ACCEPT, ContentType.APPLICATION_JSON.toContentTypeString());
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertNotNull(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  ContentType contentType = ContentType.parse(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  assertEquals("application", contentType.getType());
  assertEquals("json", contentType.getSubtype());
  assertEquals(3, contentType.getParameters().size());
  assertEquals("0.1", contentType.getParameter("q"));
  assertEquals("minimal", contentType.getParameter("odata.metadata"));
  assertEquals("utf-8", contentType.getParameter("charset"));

  final String content = IOUtils.toString(connection.getInputStream());
  assertNotNull(content);
}
 
Example 3
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void unsupportedAcceptHeaderWithSupportedAcceptCharsetHeader() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf8;q=0.1");
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;charset=iso8859-1");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertNotNull(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  ContentType contentType = ContentType.parse(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  assertEquals("application", contentType.getType());
  assertEquals("json", contentType.getSubtype());
  assertEquals(3, contentType.getParameters().size());
  assertEquals("0.1", contentType.getParameter("q"));
  assertEquals("minimal", contentType.getParameter("odata.metadata"));
  assertEquals("utf8", contentType.getParameter("charset"));

  final String content = IOUtils.toString(connection.getInputStream());
  assertNotNull(content);
}
 
Example 4
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void validFormatWithAcceptCharsetHeader() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim?$format=json");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf-8;q=0.1");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertNotNull(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  ContentType contentType = ContentType.parse(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  assertEquals("application", contentType.getType());
  assertEquals("json", contentType.getSubtype());
  assertEquals(3, contentType.getParameters().size());
  assertEquals("0.1", contentType.getParameter("q"));
  assertEquals("minimal", contentType.getParameter("odata.metadata"));
  assertEquals("utf-8", contentType.getParameter("charset"));

  final String content = IOUtils.toString(connection.getInputStream());
  assertNotNull(content);
}
 
Example 5
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleValuesInAcceptCharsetHeader1() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf-8;q=0.1,iso-8859-1,unicode-1-1");
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertNotNull(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  ContentType contentType = ContentType.parse(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  assertEquals("application", contentType.getType());
  assertEquals("json", contentType.getSubtype());
  assertEquals(3, contentType.getParameters().size());
  assertEquals("minimal", contentType.getParameter("odata.metadata"));
  assertEquals("utf-8", contentType.getParameter("charset"));
  assertEquals("0.1", contentType.getParameter("q"));

  final String content = IOUtils.toString(connection.getInputStream());
  assertNotNull(content);
}
 
Example 6
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleValuesInAcceptCharsetHeader2() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim"); 

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf-8;q=0.1,utf-8;q=0.8,utf8");
  connection.setRequestProperty(HttpHeader.ACCEPT, ContentType.APPLICATION_JSON.toContentTypeString());
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertNotNull(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  ContentType contentType = ContentType.parse(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  assertEquals("application", contentType.getType());
  assertEquals("json", contentType.getSubtype());
  assertEquals(2, contentType.getParameters().size());
  assertEquals("utf8", contentType.getParameter("charset"));
  assertEquals("minimal", contentType.getParameter("odata.metadata"));
  
  final String content = IOUtils.toString(connection.getInputStream());
  assertNotNull(content);
}
 
Example 7
Source File: ClientEntitySetIteratorTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void testEntitySetIteratorNextLink() throws IOException, URISyntaxException {
    String str = "{\"@odata.context\":\"$metadata#Cubes(Name)\","
        + "\"@odata.metadataEtag\": \"W/\\\"582997db-15b9-4a23-a8b0-c91bf45b4194\\\"\","
        + "\"@odata.nextLink\":\"http://localhost:8082/odata-server-tecsvc/odata.svc/"
        + "ESServerSidePaging?%24skiptoken=1%2A10\","
        + "\"value\":[{\"PropertyInt16\": 0,\"PropertyString\": \"\"}]}";
    
    InputStream stream = new ByteArrayInputStream(str.getBytes());
    ODataClient oDataClient = ODataClientFactory.getClient();
    ClientEntitySetIterator<ClientEntitySet, ClientEntity> entitySetIterator = 
        new ClientEntitySetIterator<ClientEntitySet, ClientEntity>(
        oDataClient, stream, ContentType.parse(ContentType.JSON.toString()));
    
    ArrayList<ClientEntity> entities = new ArrayList<ClientEntity>();
    while (entitySetIterator.hasNext()) {
        ClientEntity next = entitySetIterator.next();
        entities.add(next);
    }

    Assert.assertEquals(1, entities.size());
    Assert.assertNotNull(entitySetIterator.getNext());
    Assert.assertEquals("http://localhost:8082/odata-server-tecsvc/"
        + "odata.svc/ESServerSidePaging?%24skiptoken=1%2A10", entitySetIterator.getNext().toString());
}
 
Example 8
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void formatWithAcceptCharset() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim?$format=application/json;charset=utf-8");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "abc");
  connection.connect();

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

  assertNotNull(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  ContentType contentType = ContentType.parse(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  assertEquals("application", contentType.getType());
  assertEquals("json", contentType.getSubtype());
  assertEquals(2, contentType.getParameters().size());
  assertEquals("minimal", contentType.getParameter("odata.metadata"));
  assertEquals("utf-8", contentType.getParameter("charset"));

  final String content = IOUtils.toString(connection.getInputStream());
  assertNotNull(content);
}
 
Example 9
Source File: BatchLineReader.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void updateCurrentCharset(final String currentLine) {
  if (currentLine != null) {
    if (currentLine.startsWith(HttpHeader.CONTENT_TYPE)) {
      final ContentType contentType = ContentType.parse(
          currentLine.substring(HttpHeader.CONTENT_TYPE.length() + 1, currentLine.length() - 2).trim());
      if (contentType != null) {
        final String charsetString = contentType.getParameter(ContentType.PARAMETER_CHARSET);
        currentCharset = charsetString == null ?
            contentType.isCompatible(ContentType.APPLICATION_JSON) || contentType.getSubtype().contains("xml") ?
                Charset.forName("UTF-8") :
                DEFAULT_CHARSET :
            Charset.forName(charsetString);

        final String boundary = contentType.getParameter(BOUNDARY);
        if (boundary != null) {
          currentBoundary = DOUBLE_DASH + boundary;
        }
      }
    } else if (CRLF.equals(currentLine)) {
      readState.foundLinebreak();
    } else if (isBoundary(currentLine)) {
      readState.foundBoundary();
    }
  }
}
 
Example 10
Source File: ClientEntitySetIteratorTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetEntitySetIteratorWithInnerNav() throws IOException, URISyntaxException {
    String str = "{\"@odata.context\":\"$metadata#Cubes(Name)\","
        + "\"value\":[{\"@odata.etag\":\"W/\\\"c24af675e00a3f95ef63f223fb9c2cc8d6455459\\\"\","
        + "\"Name\":\"}Capabilities\","
        + "\"NavProp\":{\"PropertyInt\":1}}]}";
    
    InputStream stream = new ByteArrayInputStream(str.getBytes());
    ODataClient oDataClient = ODataClientFactory.getClient();
    ClientEntitySetIterator<ClientEntitySet, ClientEntity> entitySetIterator = 
        new ClientEntitySetIterator<ClientEntitySet, ClientEntity>(
        oDataClient, stream, ContentType.parse(ContentType.JSON.toString()));

    ArrayList<ClientEntity> entities = new ArrayList<ClientEntity>();
    while (entitySetIterator.hasNext()) {
        ClientEntity next = entitySetIterator.next();
        entities.add(next);
    }

    Assert.assertEquals(1, entities.size());
    Assert.assertNotNull(entities.get(0).getProperty("NavProp"));
    Assert.assertEquals("}Capabilities", entities.get(0).getProperty("Name").getPrimitiveValue().toString());
}
 
Example 11
Source File: ODataValueRequestImpl.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public ClientPrimitiveValue getBody() {
  if (value == null) {
    final ContentType contentType = ContentType.parse(getContentType());

    try {
      value = odataClient.getObjectFactory().newPrimitiveValueBuilder().
              setType(contentType.isCompatible(ContentType.TEXT_PLAIN)
                      ? EdmPrimitiveTypeKind.String : EdmPrimitiveTypeKind.Stream).
              setValue(IOUtils.toString(getRawResponse())).build();
    } catch (Exception e) {
      throw new HttpClientException(e);
    } finally {
      this.close();
    }
  }
  return value;
}
 
Example 12
Source File: ODataValueUpdateRequestImpl.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public ClientPrimitiveValue getBody() {
  if (resValue == null) {
    final ContentType contentType = ContentType.parse(getAccept());
    
    try {
      resValue = odataClient.getObjectFactory().newPrimitiveValueBuilder().
              setType(contentType.isCompatible(ContentType.TEXT_PLAIN)
                      ? EdmPrimitiveTypeKind.String : EdmPrimitiveTypeKind.Stream).
              setValue(getRawResponse()).
              build();
    } catch (Exception e) {
      throw new HttpClientException(e);
    } finally {
      this.close();
    }
  }
  return resValue;
}
 
Example 13
Source File: BatchRequestTransformator.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private Charset getCharset(final BatchQueryOperation operation) {
  final ContentType contentType = ContentType.parse(operation.getHeaders().getHeader(HttpHeader.CONTENT_TYPE));
  if (contentType != null) {
    final String charsetValue = contentType.getParameter(ContentType.PARAMETER_CHARSET);
    if (charsetValue == null) {
      if (contentType.isCompatible(ContentType.APPLICATION_JSON) || contentType.getSubtype().contains("xml")) {
        return Charset.forName("UTF-8");
      }
    } else {
      return Charset.forName(charsetValue);
    }
  }
  return Charset.forName("ISO-8859-1");
}
 
Example 14
Source File: ClientEntitySetIteratorTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test(expected=IllegalStateException.class)
public void testEntitySetIteratorGetNextMethod() throws IOException, URISyntaxException {
    String str = "{\"@odata.context\":\"$metadata#Cubes(Name)\","
        + "\"@odata.metadataEtag\": \"W/\\\"582997db-15b9-4a23-a8b0-c91bf45b4194\\\"\","
        + "\"value\":[{\"PropertyInt16\": 0,\"PropertyString\": \"\"}]}";
    
    InputStream stream = new ByteArrayInputStream(str.getBytes());
    ODataClient oDataClient = ODataClientFactory.getClient();
    ClientEntitySetIterator<ClientEntitySet, ClientEntity> entitySetIterator = 
        new ClientEntitySetIterator<ClientEntitySet, ClientEntity>(
        oDataClient, stream, ContentType.parse(ContentType.JSON.toString()));

    entitySetIterator.getNext();
}
 
Example 15
Source File: ODataEntitySetIteratorRequestImpl.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public ClientEntitySetIterator<ES, E> getBody() {
  if (entitySetIterator == null) {
    entitySetIterator = new ClientEntitySetIterator<>(
            odataClient, getRawResponse(), ContentType.parse(getContentType()));
  }
  return entitySetIterator;
}
 
Example 16
Source File: ClientEntitySetIteratorTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test(expected=UnsupportedOperationException.class)
public void testEntitySetIteratorRemoveMethod() throws IOException, URISyntaxException {
    String str = "{\"@odata.context\":\"$metadata#Cubes(Name)\","
        + "\"@odata.metadataEtag\": \"W/\\\"582997db-15b9-4a23-a8b0-c91bf45b4194\\\"\","
        + "\"value\":[{\"PropertyInt16\": 0,\"PropertyString\": \"\"}]}";
    
    InputStream stream = new ByteArrayInputStream(str.getBytes());
    ODataClient oDataClient = ODataClientFactory.getClient();
    ClientEntitySetIterator<ClientEntitySet, ClientEntity> entitySetIterator = 
        new ClientEntitySetIterator<ClientEntitySet, ClientEntity>(
        oDataClient, stream, ContentType.parse(ContentType.JSON.toString()));

    entitySetIterator.remove();
}
 
Example 17
Source File: ODataDispatcher.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void handleMediaValueDispatching(final ODataRequest request, final ODataResponse response,
    final UriResource resource) throws ContentNegotiatorException, 
   ODataApplicationException, ODataLibraryException,
    ODataHandlerException, PreconditionException {
  final HttpMethod method = request.getMethod();
  validatePreferHeader(request);
  if (method == HttpMethod.GET) {
    // This can be a GET on an EntitySet, Navigation or Function
    final ContentType requestedContentType = ContentNegotiator.
        doContentNegotiation(uriInfo.getFormatOption(),
        request, handler.getCustomContentTypeSupport(), RepresentationType.MEDIA);
    handler.selectProcessor(MediaEntityProcessor.class)
        .readMediaEntity(request, response, uriInfo, requestedContentType);
    // PUT and DELETE can only be called on EntitySets or Navigation properties which are media resources
  } else if (method == HttpMethod.PUT && (isEntityOrNavigationMedia(resource) 
      || isSingletonMedia(resource))) {
    validatePreconditions(request, true);
    final ContentType requestFormat = ContentType.parse(request.getHeader(HttpHeader.CONTENT_TYPE));
    final ContentType responseFormat = ContentNegotiator.doContentNegotiation(uriInfo.getFormatOption(),
        request, handler.getCustomContentTypeSupport(), RepresentationType.ENTITY);
    handler.selectProcessor(MediaEntityProcessor.class)
        .updateMediaEntity(request, response, uriInfo, requestFormat, responseFormat);
  } else if (method == HttpMethod.DELETE && isEntityOrNavigationMedia(resource)) {
    validatePreconditions(request, true);
    handler.selectProcessor(MediaEntityProcessor.class)
        .deleteMediaEntity(request, response, uriInfo);
  } else {
    throwMethodNotAllowed(method);
  }
}
 
Example 18
Source File: ODataUpdateTests.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static void updateProperty(String serviceURI, String resourcePath, String keyPredicate, String property, String value) throws Exception {
    URI httpURI = URI.create(serviceURI + FORWARD_SLASH +
                             resourcePath + OPEN_BRACKET +
                             QUOTE_MARK + keyPredicate + QUOTE_MARK +
                             CLOSE_BRACKET);

    ObjectNode node = OBJECT_MAPPER.createObjectNode();
    node.put(property, value);

    String data = OBJECT_MAPPER.writeValueAsString(node);
    HttpPatch request = new HttpPatch(httpURI);

    StringEntity httpEntity = new StringEntity(data, org.apache.http.entity.ContentType.APPLICATION_JSON);
    httpEntity.setChunked(false);
    request.setEntity(httpEntity);

    Header contentTypeHeader = request.getEntity().getContentType();
    ContentType contentType = ContentType.parse(contentTypeHeader.getValue());

    request.addHeader(HttpHeaders.ACCEPT, "application/json;odata.metadata=full,application/xml,*/*");
    request.addHeader(HttpHeaders.ACCEPT_CHARSET, Constants.UTF8.toLowerCase());
    request.addHeader(HttpHeaders.CONTENT_TYPE, contentType.toString());
    request.addHeader(HttpHeader.ODATA_VERSION, ODataServiceVersion.V40.toString());
    request.addHeader(HttpHeader.ODATA_MAX_VERSION, ODataServiceVersion.V40.toString());

    try (CloseableHttpClient client = HttpClients.createMinimal();
        CloseableHttpResponse response = client.execute(request)) {
        StatusLine statusLine = response.getStatusLine();
        assertEquals(HttpStatus.SC_NO_CONTENT, statusLine.getStatusCode());
    }
}
 
Example 19
Source File: ODataDispatcher.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private void handlePrimitiveDispatching(final ODataRequest request, final ODataResponse response,
    final boolean isCollection) throws ODataApplicationException, ODataLibraryException {
  final HttpMethod method = request.getMethod();
  final RepresentationType representationType = isCollection ? RepresentationType.COLLECTION_PRIMITIVE
      : RepresentationType.PRIMITIVE;
  if (method == HttpMethod.GET) {
    validatePreferHeader(request);
    final ContentType requestedContentType = ContentNegotiator.doContentNegotiation(uriInfo.getFormatOption(),
        request, handler.getCustomContentTypeSupport(), representationType);
    if (isCollection) {
      handler.selectProcessor(PrimitiveCollectionProcessor.class)
          .readPrimitiveCollection(request, response, uriInfo, requestedContentType);
    } else {
      handler.selectProcessor(PrimitiveProcessor.class)
          .readPrimitive(request, response, uriInfo, requestedContentType);
    }
  } else if (method == HttpMethod.PUT || method == HttpMethod.PATCH) {
    validatePreconditions(request, false);
    ContentType requestFormat = null;
    List<UriResource> uriResources = uriInfo.getUriResourceParts();
    UriResource uriResource = uriResources.get(uriResources.size() - 1);
    if (uriResource instanceof UriResourcePrimitiveProperty &&
  		  ((UriResourcePrimitiveProperty)uriResource).getType()
  		  .getFullQualifiedName().getFullQualifiedNameAsString().equalsIgnoreCase(EDMSTREAM)) {
  	 requestFormat = ContentType.parse(request.getHeader(HttpHeader.CONTENT_TYPE));
    } else {
  	  requestFormat = getSupportedContentType(request.getHeader(HttpHeader.CONTENT_TYPE),
  	          representationType, true);
    }
    final ContentType responseFormat = ContentNegotiator.doContentNegotiation(uriInfo.getFormatOption(),
        request, handler.getCustomContentTypeSupport(), representationType);
    if (isCollection) {
      handler.selectProcessor(PrimitiveCollectionProcessor.class)
          .updatePrimitiveCollection(request, response, uriInfo, requestFormat, responseFormat);
    } else {
      handler.selectProcessor(PrimitiveProcessor.class)
          .updatePrimitive(request, response, uriInfo, requestFormat, responseFormat);
    }
  } else if (method == HttpMethod.DELETE) {
    validatePreferHeader(request);
    validatePreconditions(request, false);
    if (isCollection) {
      handler.selectProcessor(PrimitiveCollectionProcessor.class)
          .deletePrimitiveCollection(request, response, uriInfo);
    } else {
      handler.selectProcessor(PrimitiveProcessor.class)
          .deletePrimitive(request, response, uriInfo);
    }
  } else {
    throwMethodNotAllowed(method);
  }
}
 
Example 20
Source File: StaticContentController.java    From teiid-spring-boot with Apache License 2.0 4 votes vote down vote up
static void writeError(ServletRequest request, String code, String message,
        HttpServletResponse httpResponse, int statusCode) throws IOException {
    httpResponse.setStatus(statusCode);
    String format = request.getParameter("$format"); //$NON-NLS-1$
    if (format == null) {
        //TODO: could also look at the accepts header
        ContentType contentType = ContentType.parse(request.getContentType());
        if (contentType == null || contentType.isCompatible(ContentType.APPLICATION_JSON)) {
            format = "json"; //$NON-NLS-1$
        } else {
            format = "xml"; //$NON-NLS-1$
        }
    }
    PrintWriter writer = httpResponse.getWriter();
    if (code == null) {
        code = "";
    }
    if (message == null) {
        message = "";
    }
    if (format.equalsIgnoreCase("json")) { //$NON-NLS-1$
        httpResponse.setHeader(HttpHeader.CONTENT_TYPE, ContentType.APPLICATION_JSON.toContentTypeString());
        writer.write("{ \"error\": { \"code\": \""); //$NON-NLS-1$
        JSONParser.escape(code, writer);
        writer.write("\", \"message\": \""); //$NON-NLS-1$
        JSONParser.escape(message, writer);
        writer.write("\" } }"); //$NON-NLS-1$
    } else {
        try {
            httpResponse.setHeader(HttpHeader.CONTENT_TYPE, ContentType.APPLICATION_XML.toContentTypeString());
            XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer);
            xmlStreamWriter.writeStartElement("m", "error", "http://docs.oasis-open.org/odata/ns/metadata"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            xmlStreamWriter.writeNamespace("m", "http://docs.oasis-open.org/odata/ns/metadata"); //$NON-NLS-1$ //$NON-NLS-2$
            xmlStreamWriter.writeStartElement("m", "code", "http://docs.oasis-open.org/odata/ns/metadata"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            xmlStreamWriter.writeCharacters(code);
            xmlStreamWriter.writeEndElement();
            xmlStreamWriter.writeStartElement("m", "message", "http://docs.oasis-open.org/odata/ns/metadata"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            xmlStreamWriter.writeCharacters(message);
            xmlStreamWriter.writeEndElement();
            xmlStreamWriter.writeEndElement();
            xmlStreamWriter.flush();
        } catch (XMLStreamException x) {
            throw new IOException(x);
        }
    }
    writer.close();
}