Example usage for org.apache.http.entity ContentType parse

List of usage examples for org.apache.http.entity ContentType parse

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType parse.

Prototype

public static ContentType parse(String str) throws ParseException, UnsupportedCharsetException 

Source Link

Usage

From source file:com.github.parisoft.resty.entity.EntityWriterImpl.java

@Override
public HttpEntity getEntity() throws IOException {
    final Object rawEntity = request.entity();
    final String rawType = request.headers().containsKey(CONTENT_TYPE)
            ? request.headers().getFirst(CONTENT_TYPE)
            : null;// www.ja  v a2 s  . c om
    final HttpEntity entity;

    try {
        if (rawEntity == null || rawEntity instanceof HttpEntity) {
            entity = (HttpEntity) rawEntity;
        } else if (rawEntity instanceof String || isPrimitive(rawEntity)) {
            final ContentType contentType = (rawType == null) ? null : ContentType.parse(rawType);

            entity = new StringEntity(rawEntity.toString(), contentType);
        } else {
            final ContentType contentType = ContentType.parse(rawType);
            final MediaType mediaType = MediaTypeUtils.valueOf(contentType);
            final String entityAsString = JacksonUtils.write(rawEntity, mediaType);

            entity = new StringEntity(entityAsString, contentType);
        }
    } catch (Exception e) {
        throw new IOException("Cannot write request entity", e);
    }

    return entity;
}

From source file:io.cloudslang.content.httpclient.build.EntityBuilderTest.java

@Test
public void buildEntityWithContentType() {
    ContentType parsedContentType = ContentType.parse(CONTENT_TYPE);
    HttpEntity httpEntity = entityBuilder.setBody("testBody").setContentType(parsedContentType).buildEntity();
    assertThat(httpEntity, instanceOf(StringEntity.class));
    StringEntity stringEntity = (StringEntity) httpEntity;
    assertEquals(CONTENT_TYPE, stringEntity.getContentType().getValue());
}

From source file:org.opentravel.otm.forum2016.am.UploadAPIDocumentOperation.java

/**
 * @see org.opentravel.otm.forum2016.am.RESTClientOperation#execute()
 *//* w  w  w .j a v a  2 s .  c  om*/
@Override
public APIDocument execute() throws IOException {
    HttpPost request = new HttpPost(APIPublisherConfig.getWSO2PublisherApiBaseUrl() + "/" + apiId
            + "/documents/" + documentId + "/content");

    request.setEntity(MultipartEntityBuilder.create()
            .addBinaryBody("file", contentFile, ContentType.parse(contentType), contentFile.getName()).build());
    return execute(request);
}

From source file:net.javacrumbs.restfire.httpcomponents.HttpComponentsRequestBuilder.java

private ContentType getContentType() {
    Header contentTypeHeader = request.getFirstHeader("Content-Type");
    if (contentTypeHeader != null) {
        return ContentType.parse(contentTypeHeader.getValue());
    } else {// ww w .j a v a  2  s . co m
        return null;
    }
}

From source file:io.cloudslang.content.httpclient.build.EntityBuilderTest.java

@Test
public void buildEntityWithFile() throws Exception {
    ContentType parsedContentType = ContentType.parse(CONTENT_TYPE);
    final String fileName = "testFile.txt";
    PowerMockito.whenNew(File.class).withArguments(fileName).thenReturn(fileMock);
    PowerMockito.when(fileMock.exists()).thenReturn(true);

    HttpEntity httpEntity = entityBuilder.setFilePath(fileName).setContentType(parsedContentType).buildEntity();
    assertThat(httpEntity, instanceOf(FileEntity.class));
    FileEntity fileEntity = (FileEntity) httpEntity;
    assertEquals(CONTENT_TYPE, fileEntity.getContentType().getValue());
}

From source file:org.jboss.arquillian.warp.impl.client.execution.DefaultResponseTransformationService.java

@Override
public HttpResponse transformResponse(HttpRequest request, HttpResponse response) {

    if (response instanceof FullHttpResponse) {

        FullHttpResponse fullResponse = (FullHttpResponse) response;

        String contentTypeHeader = fullResponse.headers().get("Content-Type");

        if (contentTypeHeader != null && contentTypeHeader.startsWith("text/")) {

            ContentType contentType = ContentType.parse(contentTypeHeader);
            Charset charset = contentType.getCharset();

            ByteBuf content = fullResponse.content();

            byte[] data = new byte[content.readableBytes()];
            content.readBytes(data);/*from   ww  w  .j a  va 2  s.  com*/

            String responseToTransform = createStringFromData(data, charset);
            RealURLToProxyURLMapping mapping = realToProxyURLMappingInst.get();

            for (Map.Entry<URL, URL> entry : mapping.asMap().entrySet()) {
                String realUrl = entry.getKey().toExternalForm();
                String proxyUrl = entry.getValue().toExternalForm();

                int urlStart = responseToTransform.indexOf(realUrl);

                if (urlStart > 0) {
                    responseToTransform = responseToTransform.replace(realUrl, proxyUrl);
                }
            }

            byte[] bytes = createDataFromString(responseToTransform, charset);
            ByteBuf transformedContent = Unpooled.buffer(bytes.length);
            transformedContent.writeBytes(bytes);

            DefaultFullHttpResponse transformedResponse = new DefaultFullHttpResponse(
                    fullResponse.getProtocolVersion(), fullResponse.getStatus(), transformedContent);
            transformedResponse.headers().set(fullResponse.headers());
            HttpHeaders.setContentLength(transformedResponse, bytes.length);

            return transformedResponse;
        }
    }

    return response;
}

From source file:com.blacklocus.jres.handler.JresJsonResponseHandler.java

<RESPONSE extends JresReply> Pair<JsonNode, RESPONSE> read(HttpResponse http, Class<RESPONSE> responseClass) {
    if (http.getEntity() == null) {
        return null;

    } else {//from   ww w  .j a v a2s. com
        ContentType contentType = ContentType.parse(http.getEntity().getContentType().getValue());
        if (ContentType.APPLICATION_JSON.getMimeType().equals(contentType.getMimeType())) {
            try {

                JsonNode node = ObjectMappers.fromJson(http.getEntity().getContent(), JsonNode.class);
                if (LOG.isDebugEnabled()) {
                    LOG.debug(ObjectMappers.toJson(node));
                }
                return Pair.of(node,
                        responseClass == null ? null : ObjectMappers.fromJson(node, responseClass));

            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } else {
            throw new RuntimeException("Unable to read content with " + contentType
                    + ". This ResponseHandler can only decode " + ContentType.APPLICATION_JSON);
        }
    }
}

From source file:com.joyent.manta.http.ContentTypeLookup.java

/**
 * Finds the content type set in {@link MantaHttpHeaders} and returns that if it
 * is not null. Otherwise, it will return the specified default content type.
 *
 * @param headers headers to parse for content type
 * @param filename path to the destination file
 * @param file file that is being probed for content type
 * @param defaultContentType content type to default to
 * @return content type object//from ww w  . ja v a 2 s .c  o  m
 * @throws IOException thrown when we can't access the file being analyzed
 */
public static ContentType findOrDefaultContentType(final MantaHttpHeaders headers, final String filename,
        final File file, final ContentType defaultContentType) throws IOException {
    final String headerContentType;

    if (headers != null) {
        headerContentType = headers.getContentType();
    } else {
        headerContentType = null;
    }

    String type = ObjectUtils.firstNonNull(
            // Use explicitly set headers if available
            headerContentType,
            // Detect based on destination and then source
            // filename.  URLConnection uses a property list
            // bundled with the JVM and is expected to be
            // consistent on all platforms.  As implied by the
            // method name, the contents of the file are not
            // considered.
            URLConnection.guessContentTypeFromName(filename),
            URLConnection.guessContentTypeFromName(file.getName()),
            // Probe using the JVM default detection method.  The
            // detection methods vary across platforms and may
            // rely on /etc/mime.types or include native libraries
            // such as libgio or libreal.  The contents of the
            // file may be inspected.  This check is ordered last
            // both for cross-platform consistency.  See
            // https://github.com/joyent/java-manta/issues/276 for
            // further context.
            Files.probeContentType(file.toPath()));

    if (type == null) {
        return defaultContentType;
    }

    return ContentType.parse(type);
}

From source file:io.cloudslang.content.httpclient.build.EntityBuilderTest.java

@Test
public void buildEmptyEntity() {
    ContentType parsedContentType = ContentType.parse(CONTENT_TYPE);
    HttpEntity httpEntity = entityBuilder.setContentType(parsedContentType).buildEntity();
    assertNull(httpEntity);/*  w  w w.  jav  a 2 s  .c  o  m*/
}

From source file:nl.nn.adapterframework.http.HttpResponseHandler.java

public ContentType getContentType() {
    Header contentTypeHeader = this.getFirstHeader(HttpHeaders.CONTENT_TYPE);
    ContentType contentType;/*w w  w. j  a  v a 2s .  c om*/
    if (contentTypeHeader != null) {
        contentType = ContentType.parse(contentTypeHeader.getValue());
    } else {
        contentType = ContentType.getOrDefault(httpEntity);
    }
    return contentType;
}