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

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

Introduction

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

Prototype

public String getMimeType() 

Source Link

Usage

From source file:org.duniter.core.client.service.HttpServiceImpl.java

protected Object parseResponse(HttpUriRequest request, HttpResponse response, Class<?> ResultClass)
        throws IOException {
    Object result = null;//  w  w w. j  a v  a  2 s  .  c  om

    boolean isStreamContent = ResultClass == null || ResultClass.equals(InputStream.class);
    boolean isStringContent = !isStreamContent && ResultClass != null && ResultClass.equals(String.class);

    InputStream content = response.getEntity().getContent();

    // If should return an inputstream
    if (isStreamContent) {
        result = content; // must be close by caller
    }

    // If should return String
    else if (isStringContent) {
        try {
            String stringContent = getContentAsString(content);
            // Add a debug before returning the result
            if (log.isDebugEnabled()) {
                log.debug("Parsing response:\n" + stringContent);
            }
            return stringContent;
        } finally {
            if (content != null) {
                content.close();
            }
        }
    }

    // deserialize Json
    else {

        try {
            result = readValue(content, ResultClass);
        } catch (Exception e) {
            String requestPath = request.getURI().toString();

            // Check if content-type error
            ContentType contentType = ContentType.getOrDefault(response.getEntity());
            String actualMimeType = contentType.getMimeType();
            if (!ObjectUtils.equals(ContentType.APPLICATION_JSON.getMimeType(), actualMimeType)) {
                throw new TechnicalException(I18n.t("duniter4j.client.core.invalidResponseContentType",
                        requestPath, ContentType.APPLICATION_JSON.getMimeType(), actualMimeType));
            }

            // throw a generic error
            throw new TechnicalException(I18n.t("duniter4j.client.core.invalidResponse", requestPath), e);
        } finally {
            if (content != null) {
                content.close();
            }
        }
    }

    if (result == null) {
        throw new TechnicalException(
                I18n.t("duniter4j.client.core.emptyResponse", request.getURI().toString()));
    }

    return result;
}

From source file:de.tudarmstadt.ukp.shibhttpclient.ShibHttpClient.java

/** 
 * Checks whether the HttpResponse is a SAML SOAP message
 * @param res the HttpResponse to check//ww w  . ja  v a  2s . c  om
 * @return true if the HttpResponse is a SAML SOAP message, false if not
 */
protected boolean isSamlSoapResponse(HttpResponse res) {
    boolean isSamlSoap = false;
    if (res.getFirstHeader(HttpHeaders.CONTENT_TYPE) != null) {
        ContentType contentType = ContentType.parse(res.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
        isSamlSoap = MIME_TYPE_PAOS.equals(contentType.getMimeType());
    }
    return isSamlSoap;
}

From source file:org.n52.oxf.sos.adapter.wrapper.SOSWrapper.java

private void processOptionalMimetypeParameter(final Map<String, ?> parameters,
        final ParameterContainer parameterContainer) throws OXFException {
    if (parameters.get(MIME_TYPE) != null && parameters.get(CHARSET) != null) {
        final String mimeType = (String) parameters.get(MIME_TYPE);
        final String charSet = (String) parameters.get(CHARSET);
        if (!mimeType.isEmpty() && !charSet.isEmpty()) {
            final Charset charset = Charset.forName(charSet);
            final ContentType contentType = ContentType.create(mimeType, charset);
            parameterContainer.addParameterShell(MIMETYPE, contentType.getMimeType());
            parameterContainer.addParameterShell(ENCODING, charSet);
        }/*from w ww.  jav  a 2  s  .  c  om*/
    }
}

From source file:org.n52.oxf.sos.adapter.wrapper.SOSWrapper.java

private void processOptionalMimetypeParameter(final MimetypeAwareRequestParameters parameters,
        final ParameterContainer parameterContainer) throws OXFException {
    if (parameters.isSetMimetype() && parameters.isValid()) {
        final String type = parameters.getSingleValue(MimetypeAwareRequestParameters.MIME_TYPE);
        final String charSet = parameters.getSingleValue(MimetypeAwareRequestParameters.CHARSET);
        final ContentType contentType = ContentType.create(type, Charset.forName(charSet));
        parameterContainer.addParameterShell(MIMETYPE, contentType.getMimeType());
        parameterContainer.addParameterShell(ENCODING, charSet);
    }//from   w  w  w.j  a  v a 2s . co  m
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

private boolean isBinaryContentType(String binaryMimeTypes, ContentType contentType) {
    String mimeType = contentType.getMimeType();

    if (connectorProperties.isResponseBinaryMimeTypesRegex()) {
        Pattern binaryMimeTypesRegex = binaryMimeTypesRegexMap.get(binaryMimeTypes);

        if (binaryMimeTypesRegex == null) {
            try {
                binaryMimeTypesRegex = Pattern.compile(binaryMimeTypes);

                if (binaryMimeTypesRegexMap.size() >= MAX_MAP_SIZE) {
                    binaryMimeTypesRegexMap.clear();
                }//from w  ww. j  a  v  a2 s  .c  om

                binaryMimeTypesRegexMap.put(binaryMimeTypes, binaryMimeTypesRegex);
            } catch (PatternSyntaxException e) {
                logger.warn("Invalid binary MIME types regular expression: " + binaryMimeTypes, e);
                return false;
            }
        }

        return binaryMimeTypesRegex.matcher(mimeType).matches();
    } else {
        String[] binaryMimeTypesArray = binaryMimeTypesArrayMap.get(binaryMimeTypes);

        if (binaryMimeTypesArray == null) {
            binaryMimeTypesArray = StringUtils.split(binaryMimeTypes.replaceAll("\\s*,\\s*", ",").trim(), ',');

            if (binaryMimeTypesArrayMap.size() >= MAX_MAP_SIZE) {
                binaryMimeTypesArrayMap.clear();
            }

            binaryMimeTypesArrayMap.put(binaryMimeTypes, binaryMimeTypesArray);
        }

        return StringUtils.startsWithAny(mimeType, binaryMimeTypesArray);
    }
}

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

public void canfindByMultipleMethods() throws Exception {
    MantaHttpHeaders headers = new MantaHttpHeaders(EXAMPLE_HEADERS);
    ContentType troff = ContentType.create("application/x-troff");
    ContentType jsonStream = ContentType.create("application/x-json-stream");

    File temp = File.createTempFile("upload", ".jpeg");
    FileUtils.forceDeleteOnExit(temp);/*from   w  ww . j a va  2s.c om*/
    Assert.assertEquals(
            ContentTypeLookup.findOrDefaultContentType(headers, "/stor/unknown", temp, troff).getMimeType(),
            "image/jpeg");
    headers.put("Content-Type", "application/x-json-stream; type=directory");
    temp = File.createTempFile("upload", ".jpeg");
    FileUtils.forceDeleteOnExit(temp);
    Assert.assertEquals(
            ContentTypeLookup.findOrDefaultContentType(headers, "/stor/unknown", temp, troff).getMimeType(),
            jsonStream.getMimeType());
}

From source file:com.joyent.manta.exception.MantaClientHttpResponseException.java

/**
 * Builds a client exception object that is annotated with all of the
 * relevant request and response debug information.
 *
 * @param request HTTP request object/*from w  ww.  j a  va  2s .c o  m*/
 * @param response HTTP response object
 * @param path The fully qualified path of the object. i.e. /user/stor/foo/bar/baz
 * @param expectedResponseCodes list of allowed response codes when the exception is response-code-related
 */
public MantaClientHttpResponseException(final HttpRequest request, final HttpResponse response,
        final String path, final int... expectedResponseCodes) {
    super(buildExceptionMessageFromHttpExchange(request, response, path, expectedResponseCodes));
    final HttpEntity entity = response.getEntity();
    final ContentType jsonContentType = ContentType.APPLICATION_JSON;

    final ContentType responseContentType;

    if (entity != null && entity.getContentType() != null) {
        responseContentType = ContentType.getLenient(entity);
    } else {
        responseContentType = null;
    }

    ErrorDetail errorDetail = null;
    ObjectMapper mapper = MantaObjectMapper.INSTANCE;

    if (entity != null && (responseContentType == null
            || responseContentType.getMimeType().equals(jsonContentType.getMimeType()))) {
        byte[] jsonBytes = new byte[0];

        try (InputStream jsonStream = entity.getContent()) {
            jsonBytes = IOUtils.toByteArray(jsonStream);
            errorDetail = mapper.readValue(jsonBytes, ErrorDetail.class);
        } catch (RuntimeException | JsonProcessingException e) {
            String json = new String(jsonBytes, StandardCharsets.UTF_8);
            String msg = String.format("Unable to deserialize json " + "error data. Actual response:\n%s",
                    json);
            LOGGER.warn(msg, e);
        } catch (IOException e) {
            LOGGER.warn("Problem getting response error content", e);
        }
    }

    setRequestId(HttpHelper.extractRequestId(response));
    setStatusLine(response.getStatusLine());

    if (errorDetail == null) {
        setServerCode(MantaErrorCode.NO_CODE_ERROR);
    } else {
        setServerCode(MantaErrorCode.valueOfCode(errorDetail.getCode()));
        setContextValue("server_message", errorDetail.getMessage());
    }

    HttpHelper.annotateContextedException(this, request, response);

    /* We don't want any problems processing headers to get in the way of
     * properly throwing an exception, so we warn if we hit any error cases
     * instead of raise the exception. */
    try {
        final Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            setHeaders(new MantaHttpHeaders(responseHeaders));
        }
    } catch (RuntimeException e) {
        LOGGER.warn("Error setting response headers on exception", e);
    }
}

From source file:org.ambraproject.wombat.service.FreemarkerMailServiceImpl.java

private BodyPart createBodyPart(ContentType contentType, Template htmlTemplate, Model context)
        throws IOException, MessagingException {
    BodyPart htmlPage = new MimeBodyPart();
    String encoding = getConfiguration().getDefaultEncoding();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(0x100);
    Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream, encoding));

    htmlTemplate.setOutputEncoding(encoding);
    htmlTemplate.setEncoding(encoding);//  w w  w.  j  a  va 2s .  c o m

    try {
        htmlTemplate.process(context, writer);
    } catch (TemplateException e) {
        throw new MailPreparationException("Can't generate " + contentType.getMimeType() + " subscription mail",
                e);
    }

    htmlPage.setDataHandler(createBodyPartDataHandler(outputStream.toByteArray(),
            contentType.toString() + "; charset=" + getConfiguration().getDefaultEncoding()));

    return htmlPage;
}

From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java

private HttpPost createPostRequest(URI uri, String postBody, String contentTypes, ServerInfo serverInfo) {
    HttpPost httpPost = new HttpPost(uri);
    ContentType contentType = ContentType.create(contentTypes);
    if (contentType == null)
        throw new RuntimeException("Couldn't create content types for " + contentTypes);

    if (ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType.getMimeType())) {
        String tokenToUse = null;
        if (serverInfo.encryptedToken != null) {
            try {
                tokenToUse = Crypto.doDecrypt(serverInfo.encryptedToken);
            } catch (GeneralSecurityException e) {
                throw new RuntimeException(e);
            }//  w  ww . ja v  a2s  . c  o  m
        }
        List<NameValuePair> params = parseQueryStringAndAddToken(postBody, tokenToUse);
        postBody = URLEncodedUtils.format(params, "UTF-8");
    }

    StringEntity entity = new StringEntity(postBody, contentType);
    httpPost.setEntity(entity);

    return httpPost;
}

From source file:net.sf.jaceko.mock.it.helper.request.HttpRequestSender.java

private MockResponse executeRequest(HttpRequestBase httpRequest, boolean binary) throws IOException {
    HttpResponse response = httpclient.execute(httpRequest);
    HttpEntity entity = response.getEntity();
    ContentType contentType = ContentType.getOrDefault(entity);

    String body = null;//from  www  .  j  a va2 s. c om
    byte[] binaryBody = null;

    if (entity != null) {
        if (binary) {
            binaryBody = EntityUtils.toByteArray(entity);
        } else {
            body = EntityUtils.toString(entity);
        }
        entity.getContent().close();
    }
    Map<String, String> headers = new HashMap<String, String>();
    Header[] allHeaders = response.getAllHeaders();
    for (Header header : allHeaders) {
        headers.put(header.getName(), header.getValue());
    }
    int responseCode = response.getStatusLine().getStatusCode();
    return MockResponse.body(body).binaryBody(binaryBody).code(responseCode)
            .contentType(MediaType.valueOf(contentType.getMimeType())).headers(headers).build();
}