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:org.apache.solr.client.solrj.impl.HttpSolrClient.java

protected NamedList<Object> executeMethod(HttpRequestBase method, final ResponseParser processor)
        throws SolrServerException {
    method.addHeader("User-Agent", AGENT);

    org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder = HttpClientUtil
            .createDefaultRequestConfigBuilder();
    if (soTimeout != null) {
        requestConfigBuilder.setSocketTimeout(soTimeout);
    }//from  www . java2  s  .  co m
    if (connectionTimeout != null) {
        requestConfigBuilder.setConnectTimeout(connectionTimeout);
    }
    if (followRedirects != null) {
        requestConfigBuilder.setRedirectsEnabled(followRedirects);
    }

    method.setConfig(requestConfigBuilder.build());

    HttpEntity entity = null;
    InputStream respBody = null;
    boolean shouldClose = true;
    try {
        // Execute the method.
        HttpClientContext httpClientRequestContext = HttpClientUtil.createNewHttpClientRequestContext();
        final HttpResponse response = httpClient.execute(method, httpClientRequestContext);
        int httpStatus = response.getStatusLine().getStatusCode();

        // Read the contents
        entity = response.getEntity();
        respBody = entity.getContent();
        Header ctHeader = response.getLastHeader("content-type");
        String contentType;
        if (ctHeader != null) {
            contentType = ctHeader.getValue();
        } else {
            contentType = "";
        }

        // handle some http level checks before trying to parse the response
        switch (httpStatus) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_BAD_REQUEST:
        case HttpStatus.SC_CONFLICT: // 409
            break;
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_MOVED_TEMPORARILY:
            if (!followRedirects) {
                throw new SolrServerException(
                        "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ").");
            }
            break;
        default:
            if (processor == null || "".equals(contentType)) {
                throw new RemoteSolrException(baseUrl, httpStatus, "non ok status: " + httpStatus + ", message:"
                        + response.getStatusLine().getReasonPhrase(), null);
            }
        }
        if (processor == null || processor instanceof InputStreamResponseParser) {

            // no processor specified, return raw stream
            NamedList<Object> rsp = new NamedList<>();
            rsp.add("stream", respBody);
            // Only case where stream should not be closed
            shouldClose = false;
            return rsp;
        }

        String procCt = processor.getContentType();
        if (procCt != null) {
            String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT);
            String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT);
            if (!procMimeType.equals(mimeType)) {
                // unexpected mime type
                String msg = "Expected mime type " + procMimeType + " but got " + mimeType + ".";
                Header encodingHeader = response.getEntity().getContentEncoding();
                String encoding;
                if (encodingHeader != null) {
                    encoding = encodingHeader.getValue();
                } else {
                    encoding = "UTF-8"; // try UTF-8
                }
                try {
                    msg = msg + " " + IOUtils.toString(respBody, encoding);
                } catch (IOException e) {
                    throw new RemoteSolrException(baseUrl, httpStatus,
                            "Could not parse response with encoding " + encoding, e);
                }
                throw new RemoteSolrException(baseUrl, httpStatus, msg, null);
            }
        }

        NamedList<Object> rsp = null;
        String charset = EntityUtils.getContentCharSet(response.getEntity());
        try {
            rsp = processor.processResponse(respBody, charset);
        } catch (Exception e) {
            throw new RemoteSolrException(baseUrl, httpStatus, e.getMessage(), e);
        }
        if (httpStatus != HttpStatus.SC_OK) {
            NamedList<String> metadata = null;
            String reason = null;
            try {
                NamedList err = (NamedList) rsp.get("error");
                if (err != null) {
                    reason = (String) err.get("msg");
                    if (reason == null) {
                        reason = (String) err.get("trace");
                    }
                    metadata = (NamedList<String>) err.get("metadata");
                }
            } catch (Exception ex) {
            }
            if (reason == null) {
                StringBuilder msg = new StringBuilder();
                msg.append(response.getStatusLine().getReasonPhrase()).append("\n\n").append("request: ")
                        .append(method.getURI());
                reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);
            }
            RemoteSolrException rss = new RemoteSolrException(baseUrl, httpStatus, reason, null);
            if (metadata != null)
                rss.setMetadata(metadata);
            throw rss;
        }
        return rsp;
    } catch (ConnectException e) {
        throw new SolrServerException("Server refused connection at: " + getBaseURL(), e);
    } catch (SocketTimeoutException e) {
        throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(),
                e);
    } catch (IOException e) {
        throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e);
    } finally {
        if (shouldClose) {
            Utils.consumeFully(entity);
        }
    }
}

From source file:org.eclipse.rdf4j.http.client.RDF4JProtocolSession.java

protected void upload(InputStream contents, String baseURI, RDFFormat dataFormat, boolean overwrite,
        boolean preserveNodeIds, Action action, Resource... contexts)
        throws IOException, RDFParseException, RepositoryException, UnauthorizedException {
    // Set Content-Length to -1 as we don't know it and we also don't want to
    // cache//ww w  . jav  a2  s.co m
    HttpEntity entity = new InputStreamEntity(contents, -1, ContentType.parse(dataFormat.getDefaultMIMEType()));
    upload(entity, baseURI, overwrite, preserveNodeIds, action, contexts);
}

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

private HttpRequestMessage createRequestMessage(Request request, boolean ignorePayload)
        throws IOException, MessagingException {
    HttpRequestMessage requestMessage = new HttpRequestMessage();
    requestMessage.setMethod(request.getMethod());
    requestMessage.setHeaders(HttpMessageConverter.convertFieldEnumerationToMap(request));
    requestMessage.setParameters(extractParameters(request));

    ContentType contentType;/*from   www .j a v a  2  s  . c  o m*/
    try {
        contentType = ContentType.parse(request.getContentType());
    } catch (RuntimeException e) {
        contentType = ContentType.TEXT_PLAIN;
    }
    requestMessage.setContentType(contentType);

    requestMessage.setRemoteAddress(StringUtils.trimToEmpty(request.getRemoteAddr()));
    requestMessage.setQueryString(StringUtils.trimToEmpty(request.getQueryString()));
    requestMessage.setRequestUrl(StringUtils.trimToEmpty(getRequestURL(request)));
    requestMessage.setContextPath(StringUtils.trimToEmpty(new URL(requestMessage.getRequestUrl()).getPath()));

    if (!ignorePayload) {
        InputStream requestInputStream = request.getInputStream();
        // If a security handler already consumed the entity, get it from the request attribute instead
        try {
            byte[] entity = (byte[]) request.getAttribute(EntityProvider.ATTRIBUTE_NAME);
            if (entity != null) {
                requestInputStream = new ByteArrayInputStream(entity);
            }
        } catch (Exception e) {
        }

        // If the request is GZIP encoded, uncompress the content
        List<String> contentEncodingList = requestMessage.getCaseInsensitiveHeaders()
                .get(HTTP.CONTENT_ENCODING);
        if (CollectionUtils.isNotEmpty(contentEncodingList)) {
            for (String contentEncoding : contentEncodingList) {
                if (contentEncoding != null && (contentEncoding.equalsIgnoreCase("gzip")
                        || contentEncoding.equalsIgnoreCase("x-gzip"))) {
                    requestInputStream = new GZIPInputStream(requestInputStream);
                    break;
                }
            }
        }

        /*
         * First parse out the body of the HTTP request. Depending on the connector settings,
         * this could end up being a string encoded with the request charset, a byte array
         * representing the raw request payload, or a MimeMultipart object.
         */

        // Only parse multipart if XML Body is selected and Parse Multipart is enabled
        if (connectorProperties.isXmlBody() && connectorProperties.isParseMultipart()
                && ServletFileUpload.isMultipartContent(request)) {
            requestMessage.setContent(
                    new MimeMultipart(new ByteArrayDataSource(requestInputStream, contentType.toString())));
        } else if (isBinaryContentType(contentType)) {
            requestMessage.setContent(IOUtils.toByteArray(requestInputStream));
        } else {
            requestMessage.setContent(IOUtils.toString(requestInputStream,
                    HttpMessageConverter.getDefaultHttpCharset(request.getCharacterEncoding())));
        }
    }

    return requestMessage;
}

From source file:org.apache.openaz.xacml.pdp.test.TestBase.java

/**
 * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision.
 *
 * @param file//from  w  w w. j a v  a2  s . c  om
 * @return
 */
protected Response callRESTfulPDP(InputStream is) {
    Response response = null;
    HttpURLConnection connection = null;
    try {

        //
        // Open up the connection
        //
        connection = (HttpURLConnection) this.restURL.openConnection();
        connection.setRequestProperty("Content-Type", "application/json");
        //
        // Setup our method and headers
        //
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        //
        // Adding this in. It seems the HttpUrlConnection class does NOT
        // properly forward our headers for POST re-direction. It does so
        // for a GET re-direction.
        //
        // So we need to handle this ourselves.
        //
        connection.setInstanceFollowRedirects(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        //
        // Send the request
        //
        try (OutputStream os = connection.getOutputStream()) {
            IOUtils.copy(is, os);
        }
        //
        // Do the connect
        //
        connection.connect();
        if (connection.getResponseCode() == 200) {
            //
            // Read the response
            //
            ContentType contentType = null;
            try {
                contentType = ContentType.parse(connection.getContentType());

                if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
                    response = JSONResponse.load(connection.getInputStream());
                } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType())
                        || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
                    response = DOMResponse.load(connection.getInputStream());
                } else {
                    logger.error("unknown content-type: " + contentType);
                }

            } catch (Exception e) {
                String message = "Parsing Content-Type: " + connection.getContentType() + ", error="
                        + e.getMessage();
                logger.error(message, e);
            }

        } else {
            logger.error(connection.getResponseCode() + " " + connection.getResponseMessage());
        }
    } catch (Exception e) {
        logger.error(e);
    }

    return response;
}

From source file:org.openrdf.http.client.SparqlSession.java

/**
 * Parse the response in a background thread. HTTP connections are dealt with
 * in the {@link BackgroundGraphResult} or (in the error-case) in this
 * method./*from   ww w .  j  av  a2s  . c  om*/
 */
protected BackgroundGraphResult getRDFBackground(HttpUriRequest method, boolean requireContext)
        throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException,
        UnauthorizedException, QueryInterruptedException {

    boolean submitted = false;

    // Specify which formats we support using Accept headers
    Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys();
    if (rdfFormats.isEmpty()) {
        throw new RepositoryException("No tuple RDF parsers have been registered");
    }

    // send the tuple query
    HttpResponse response = sendGraphQueryViaHttp(method, requireContext, rdfFormats);
    try {

        // if we get here, HTTP code is 200
        String mimeType = getResponseMIMEType(response);
        try {
            RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats);
            RDFParser parser = Rio.createParser(format, getValueFactory());
            parser.setParserConfig(getParserConfig());
            parser.setParseErrorListener(new ParseErrorLogger());

            Charset charset = null;

            // SES-1793 : Do not attempt to check for a charset if the format is
            // defined not to have a charset
            // This prevents errors caused by people erroneously attaching a
            // charset to a binary formatted document
            HttpEntity entity = response.getEntity();
            if (format.hasCharset() && entity != null && entity.getContentType() != null) {
                // TODO copied from SPARQLGraphQuery repository, is this
                // required?
                try {
                    charset = ContentType.parse(entity.getContentType().getValue()).getCharset();
                } catch (IllegalCharsetNameException e) {
                    // work around for Joseki-3.2
                    // Content-Type: application/rdf+xml;
                    // charset=application/rdf+xml
                }
                if (charset == null) {
                    charset = UTF8;
                }
            }

            if (entity == null) {
                throw new RepositoryException("Server response was empty.");
            }

            String baseURI = method.getURI().toASCIIString();
            BackgroundGraphResult gRes = new BackgroundGraphResult(parser, entity.getContent(), charset,
                    baseURI);
            execute(gRes);
            submitted = true;
            return gRes;
        } catch (UnsupportedQueryResultFormatException e) {
            throw new RepositoryException("Server responded with an unsupported file format: " + mimeType);
        }
    } finally {
        if (!submitted) {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }

}

From source file:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java

/**
 * Parse the response in a background thread. HTTP connections are dealt with in the
 * {@link BackgroundGraphResult} or (in the error-case) in this method.
 *///from w w  w.  ja v  a 2s  . c  o  m
protected BackgroundGraphResult getRDFBackground(HttpUriRequest method, boolean requireContext)
        throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException,
        UnauthorizedException, QueryInterruptedException {

    boolean submitted = false;

    // Specify which formats we support using Accept headers
    Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys();
    if (rdfFormats.isEmpty()) {
        throw new RepositoryException("No tuple RDF parsers have been registered");
    }

    BackgroundGraphResult gRes = null;
    // send the tuple query
    HttpResponse response = sendGraphQueryViaHttp(method, requireContext, rdfFormats);
    try {

        // if we get here, HTTP code is 200
        String mimeType = getResponseMIMEType(response);
        RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats).orElseThrow(
                () -> new RepositoryException("Server responded with an unsupported file format: " + mimeType));
        RDFParser parser = Rio.createParser(format, getValueFactory());
        parser.setParserConfig(getParserConfig());
        parser.setParseErrorListener(new ParseErrorLogger());

        Charset charset = null;

        // SES-1793 : Do not attempt to check for a charset if the format is
        // defined not to have a charset
        // This prevents errors caused by people erroneously attaching a
        // charset to a binary formatted document
        HttpEntity entity = response.getEntity();
        if (format.hasCharset() && entity != null && entity.getContentType() != null) {
            // TODO copied from SPARQLGraphQuery repository, is this
            // required?
            try {
                charset = ContentType.parse(entity.getContentType().getValue()).getCharset();
            } catch (IllegalCharsetNameException e) {
                // work around for Joseki-3.2
                // Content-Type: application/rdf+xml;
                // charset=application/rdf+xml
            }
            if (charset == null) {
                charset = UTF8;
            }
        }

        if (entity == null) {
            throw new RepositoryException("Server response was empty.");
        }

        String baseURI = method.getURI().toASCIIString();
        gRes = new BackgroundGraphResult(parser, entity.getContent(), charset, baseURI);
        execute(gRes);
        submitted = true;
        return gRes;
    } finally {
        if (!submitted) {
            try {
                if (gRes != null) {
                    gRes.close();
                }
            } finally {
                EntityUtils.consumeQuietly(response.getEntity());
            }
        }
    }

}

From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java

private Olingo2BatchResponse parseResponse(Edm edm, Map<String, String> contentIdLocationMap,
        Olingo2BatchRequest request, BatchSingleResponse response)
        throws EntityProviderException, ODataApplicationException {

    // validate HTTP status
    final int statusCode = Integer.parseInt(response.getStatusCode());
    final String statusInfo = response.getStatusInfo();

    final BasicHttpResponse httpResponse = new BasicHttpResponse(
            new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode, statusInfo));
    final Map<String, String> headers = response.getHeaders();
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpResponse.setHeader(entry.getKey(), entry.getValue());
    }/*w  ww  .j a  v  a 2s.c  om*/

    ByteArrayInputStream content = null;
    try {
        if (response.getBody() != null) {
            final ContentType partContentType = receiveWithCharsetParameter(
                    ContentType.parse(headers.get(HttpHeaders.CONTENT_TYPE)), Consts.UTF_8);
            final String charset = partContentType.getCharset().toString();

            final String body = response.getBody();
            content = body != null ? new ByteArrayInputStream(body.getBytes(charset)) : null;

            httpResponse.setEntity(new StringEntity(body, charset));
        }

        AbstractFutureCallback.checkStatus(httpResponse);
    } catch (ODataApplicationException e) {
        return new Olingo2BatchResponse(statusCode, statusInfo, response.getContentId(), response.getHeaders(),
                e);
    } catch (UnsupportedEncodingException e) {
        return new Olingo2BatchResponse(statusCode, statusInfo, response.getContentId(), response.getHeaders(),
                e);
    }

    // resolve resource path and query params and parse batch part uri
    final String resourcePath = request.getResourcePath();
    final String resolvedResourcePath;
    if (resourcePath.startsWith("$") && !(METADATA.equals(resourcePath) || BATCH.equals(resourcePath))) {
        resolvedResourcePath = findLocation(resourcePath, contentIdLocationMap);
    } else {
        final String resourceLocation = response.getHeader(HttpHeaders.LOCATION);
        resolvedResourcePath = resourceLocation != null ? resourceLocation.substring(serviceUri.length())
                : resourcePath;
    }
    final Map<String, String> resolvedQueryParams = request instanceof Olingo2BatchQueryRequest
            ? ((Olingo2BatchQueryRequest) request).getQueryParams()
            : null;
    final UriInfoWithType uriInfo = parseUri(edm, resolvedResourcePath, resolvedQueryParams);

    // resolve response content
    final Object resolvedContent = content != null ? readContent(uriInfo, content) : null;

    return new Olingo2BatchResponse(statusCode, statusInfo, response.getContentId(), response.getHeaders(),
            resolvedContent);
}