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

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

Introduction

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

Prototype

public Charset getCharset() 

Source Link

Usage

From source file:com.serphacker.serposcope.scraper.http.ScrapClient.java

public Charset getDetectedCharset() {
    ContentType contentType = null;
    try {//from  w w w. j  a  v  a2  s .  com
        contentType = ContentType.get(response.getEntity());
    } catch (Exception ex) {
    }

    Charset charset = null;
    if (contentType != null) {
        try {
            charset = contentType.getCharset();
        } catch (final Exception ex) {
        }

        if (charset == null) {
            if (contentType.getMimeType().contains("text/html")) {
                charset = detectCharsetFromHtmlMeta();
            }
        }

    }

    return charset;
}

From source file:sk.datalan.solr.impl.HttpSolrServer.java

protected NamedList<Object> executeMethod(HttpRequestBase method, final ResponseParser processor)
        throws SolrServerException {
    //    // XXX client already has this set, is this needed?
    //    method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
    //        followRedirects);
    method.addHeader("User-Agent", AGENT);

    InputStream respBody = null;//from   www  . ja v a  2s  . c  o  m
    boolean shouldClose = true;
    boolean success = false;
    try {
        // Execute the method.
        final HttpResponse response = httpClient.execute(method);
        int httpStatus = response.getStatusLine().getStatusCode();

        // Read the contents
        respBody = response.getEntity().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) {
                throw new RemoteSolrException(httpStatus,
                        "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:"
                                + response.getStatusLine().getReasonPhrase(),
                        null);
            }
        }
        if (processor == null) {

            // 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;
            success = true;
            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(httpStatus,
                            "Could not parse response with encoding " + encoding, e);
                }
                RemoteSolrException e = new RemoteSolrException(httpStatus, msg, null);
                throw e;
            }
        }

        //      if(true) {
        //        ByteArrayOutputStream copy = new ByteArrayOutputStream();
        //        IOUtils.copy(respBody, copy);
        //        String val = new String(copy.toByteArray());
        //        System.out.println(">RESPONSE>"+val+"<"+val.length());
        //        respBody = new ByteArrayInputStream(copy.toByteArray());
        //      }
        NamedList<Object> rsp = null;
        ContentType ct = ContentType.getOrDefault(response.getEntity());
        try {
            rsp = processor.processResponse(respBody, ct.getCharset().toString());
        } catch (Exception e) {
            throw new RemoteSolrException(httpStatus, e.getMessage(), e);
        }
        if (httpStatus != HttpStatus.SC_OK) {
            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");
                    }
                }
            } catch (Exception ex) {
            }
            if (reason == null) {
                StringBuilder msg = new StringBuilder();
                msg.append(response.getStatusLine().getReasonPhrase());
                msg.append("\n\n");
                msg.append("request: ").append(method.getURI());
                reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);
            }
            throw new RemoteSolrException(httpStatus, reason, null);
        }
        success = true;
        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 (respBody != null && shouldClose) {
            try {
                respBody.close();
            } catch (IOException e) {
                log.error("", e);
            } finally {
                if (!success) {
                    method.abort();
                }
            }
        }
    }
}

From source file:eu.eubrazilcc.lvl.core.entrez.EntrezHelper.java

public ESearchResult esearch(final String database, final String query, final int retstart, final int retmax)
        throws Exception {
    return httpClient.request(ESEARCH_BASE_URI).post()
            .bodyForm(esearchForm(database, query, retstart, retmax).build())
            .handleResponse(new ResponseHandler<ESearchResult>() {
                @Override//from  w  w w . ja  v a  2  s  . c  o  m
                public ESearchResult handleResponse(final HttpResponse response) throws IOException {
                    final StatusLine statusLine = response.getStatusLine();
                    final HttpEntity entity = response.getEntity();
                    if (statusLine.getStatusCode() >= 300) {
                        throw new HttpResponseException(statusLine.getStatusCode(),
                                statusLine.getReasonPhrase());
                    }
                    if (entity == null) {
                        throw new ClientProtocolException("Response contains no content");
                    }
                    final ContentType contentType = getOrDefault(entity);
                    final String mimeType = contentType.getMimeType();
                    if (!mimeType.equals(APPLICATION_XML.getMimeType())
                            && !mimeType.equals(TEXT_XML.getMimeType())) {
                        throw new ClientProtocolException("Unexpected content type:" + contentType);
                    }
                    Charset charset = contentType.getCharset();
                    if (charset == null) {
                        charset = HTTP.DEF_CONTENT_CHARSET;
                    }
                    return ESEARCH_XMLB.typeFromInputStream(entity.getContent());
                }
            }, false);
}

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

private ContentType receiveWithCharsetParameter(ContentType contentType, Charset charset) {
    if (contentType.getCharset() != null) {
        return contentType;
    }/*from   ww  w .j a v  a 2s .c  o m*/
    final String mimeType = contentType.getMimeType();
    if (mimeType.equals(ContentType.TEXT_PLAIN.getMimeType())
            || AbstractFutureCallback.ODATA_MIME_TYPE.matcher(mimeType).matches()) {
        return contentType.withCharset(charset);
    }
    return contentType;
}

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

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    HttpDispatcherProperties httpDispatcherProperties = (HttpDispatcherProperties) connectorProperties;
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.WRITING));

    String responseData = null;//w w w . java2s . co m
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;
    boolean validateResponse = false;

    CloseableHttpClient client = null;
    HttpRequestBase httpMethod = null;
    CloseableHttpResponse httpResponse = null;
    File tempFile = null;
    int socketTimeout = NumberUtils.toInt(httpDispatcherProperties.getSocketTimeout(), 30000);

    try {
        configuration.configureDispatcher(this, httpDispatcherProperties);

        long dispatcherId = getDispatcherId();
        client = clients.get(dispatcherId);
        if (client == null) {
            BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                    socketFactoryRegistry.build());
            httpClientConnectionManager
                    .setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
            HttpClientBuilder clientBuilder = HttpClients.custom()
                    .setConnectionManager(httpClientConnectionManager);
            HttpUtil.configureClientBuilder(clientBuilder);

            if (httpDispatcherProperties.isUseProxyServer()) {
                clientBuilder.setRoutePlanner(new DynamicProxyRoutePlanner());
            }

            client = clientBuilder.build();
            clients.put(dispatcherId, client);
        }

        URI hostURI = new URI(httpDispatcherProperties.getHost());
        String host = hostURI.getHost();
        String scheme = hostURI.getScheme();
        int port = hostURI.getPort();
        if (port == -1) {
            if (scheme.equalsIgnoreCase("https")) {
                port = 443;
            } else {
                port = 80;
            }
        }

        // Parse the content type field first, and then add the charset if needed
        ContentType contentType = ContentType.parse(httpDispatcherProperties.getContentType());
        Charset charset = null;
        if (contentType.getCharset() == null) {
            charset = Charset.forName(CharsetUtils.getEncoding(httpDispatcherProperties.getCharset()));
        } else {
            charset = contentType.getCharset();
        }

        if (httpDispatcherProperties.isMultipart()) {
            tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
        }

        HttpHost target = new HttpHost(host, port, scheme);

        httpMethod = buildHttpRequest(hostURI, httpDispatcherProperties, connectorMessage, tempFile,
                contentType, charset);

        HttpClientContext context = HttpClientContext.create();

        // authentication
        if (httpDispatcherProperties.isUseAuthentication()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            Credentials credentials = new UsernamePasswordCredentials(httpDispatcherProperties.getUsername(),
                    httpDispatcherProperties.getPassword());
            credsProvider.setCredentials(authScope, credentials);
            AuthCache authCache = new BasicAuthCache();
            RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.<AuthSchemeProvider>create();

            if (AuthSchemes.DIGEST.equalsIgnoreCase(httpDispatcherProperties.getAuthenticationType())) {
                logger.debug("using Digest authentication");
                registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    processDigestChallenge(authCache, target, credentials, httpMethod, context);
                }
            } else {
                logger.debug("using Basic authentication");
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    authCache.put(target, new BasicScheme());
                }
            }

            context.setCredentialsProvider(credsProvider);
            context.setAuthSchemeRegistry(registryBuilder.build());
            context.setAuthCache(authCache);

            logger.debug("using authentication with credentials: " + credentials);
        }

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(socketTimeout)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).build();
        context.setRequestConfig(requestConfig);

        // Set proxy information
        if (httpDispatcherProperties.isUseProxyServer()) {
            context.setAttribute(PROXY_CONTEXT_KEY, new HttpHost(httpDispatcherProperties.getProxyAddress(),
                    Integer.parseInt(httpDispatcherProperties.getProxyPort())));
        }

        // execute the method
        logger.debug(
                "executing method: type=" + httpMethod.getMethod() + ", uri=" + httpMethod.getURI().toString());
        httpResponse = client.execute(target, httpMethod, context);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        logger.debug("received status code: " + statusCode);

        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        for (Header header : httpResponse.getAllHeaders()) {
            List<String> list = headers.get(header.getName());

            if (list == null) {
                list = new ArrayList<String>();
                headers.put(header.getName(), list);
            }

            list.add(header.getValue());
        }

        connectorMessage.getConnectorMap().put("responseStatusLine", statusLine.toString());
        connectorMessage.getConnectorMap().put("responseHeaders",
                new MessageHeaders(new CaseInsensitiveMap(headers)));

        ContentType responseContentType = ContentType.get(httpResponse.getEntity());
        if (responseContentType == null) {
            responseContentType = ContentType.TEXT_PLAIN;
        }

        Charset responseCharset = charset;
        if (responseContentType.getCharset() != null) {
            responseCharset = responseContentType.getCharset();
        }

        final String responseBinaryMimeTypes = httpDispatcherProperties.getResponseBinaryMimeTypes();
        BinaryContentTypeResolver binaryContentTypeResolver = new BinaryContentTypeResolver() {
            @Override
            public boolean isBinaryContentType(ContentType contentType) {
                return HttpDispatcher.this.isBinaryContentType(responseBinaryMimeTypes, contentType);
            }
        };

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

        // The entity could be null in certain cases such as 204 responses
        if (httpResponse.getEntity() != null) {
            // Only parse multipart if XML Body is selected and Parse Multipart is enabled
            if (httpDispatcherProperties.isResponseXmlBody()
                    && httpDispatcherProperties.isResponseParseMultipart()
                    && responseContentType.getMimeType().startsWith(FileUploadBase.MULTIPART)) {
                responseBody = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(),
                        responseContentType.toString()));
            } else if (binaryContentTypeResolver.isBinaryContentType(responseContentType)) {
                responseBody = IOUtils.toByteArray(httpResponse.getEntity().getContent());
            } else {
                responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharset);
            }
        }

        /*
         * Now that we have the response body, we need to create the actual Response message
         * data. Depending on the connector settings this could be our custom serialized XML, a
         * Base64 string encoded from the raw response payload, or a string encoded from the
         * payload with the request charset.
         */
        if (httpDispatcherProperties.isResponseXmlBody()) {
            responseData = HttpMessageConverter.httpResponseToXml(statusLine.toString(), headers, responseBody,
                    responseContentType, httpDispatcherProperties.isResponseParseMultipart(),
                    httpDispatcherProperties.isResponseIncludeMetadata(), binaryContentTypeResolver);
        } else if (responseBody instanceof byte[]) {
            responseData = new String(Base64Util.encodeBase64((byte[]) responseBody), "US-ASCII");
        } else {
            responseData = (String) responseBody;
        }

        validateResponse = httpDispatcherProperties.getDestinationConnectorProperties().isValidateResponse();

        if (statusCode < HttpStatus.SC_BAD_REQUEST) {
            responseStatus = Status.SENT;
        } else {
            eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                    connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                    connectorProperties.getName(), "Received error response from HTTP server.", null));
            responseStatusMessage = ErrorMessageBuilder
                    .buildErrorResponse("Received error response from HTTP server.", null);
            responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseData,
                    null);
        }
    } catch (Exception e) {
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error connecting to HTTP server.", e));
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error connecting to HTTP server", e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error connecting to HTTP server", e);
    } finally {
        try {
            HttpClientUtils.closeQuietly(httpResponse);

            // Delete temp files if we created them
            if (tempFile != null) {
                tempFile.delete();
                tempFile = null;
            }
        } finally {
            eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.IDLE));
        }
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

private File getWsdl(CloseableHttpClient client, HttpContext context, DispatchContainer dispatchContainer,
        Map<String, File> visitedUrls, String wsdlUrl) throws Exception {
    if (visitedUrls.containsKey(wsdlUrl)) {
        return visitedUrls.get(wsdlUrl);
    }//from www  . j a  v a 2  s .  c om

    String wsdl = null;
    StatusLine responseStatusLine = null;
    CloseableHttpResponse response = client.execute(new HttpGet(wsdlUrl), context);

    try {
        responseStatusLine = response.getStatusLine();

        if (responseStatusLine.getStatusCode() == HttpStatus.SC_OK) {
            ContentType responseContentType = ContentType.get(response.getEntity());
            if (responseContentType == null) {
                responseContentType = ContentType.TEXT_XML;
            }

            Charset responseCharset = responseContentType.getCharset();
            if (responseContentType.getCharset() == null) {
                responseCharset = ContentType.TEXT_XML.getCharset();
            }

            wsdl = IOUtils.toString(response.getEntity().getContent(), responseCharset);
        }
    } finally {
        HttpClientUtils.closeQuietly(response);
    }

    if (StringUtils.isNotBlank(wsdl)) {
        File tempFile = File.createTempFile("WebServiceSender", ".wsdl");
        tempFile.deleteOnExit();
        visitedUrls.put(wsdlUrl, tempFile);

        try {
            DonkeyElement element = new DonkeyElement(wsdl);
            for (DonkeyElement child : element.getChildElements()) {
                if (child.getLocalName().equals("import") && child.hasAttribute("location")) {
                    String location = new URI(wsdlUrl).resolve(child.getAttribute("location")).toString();
                    child.setAttribute("location",
                            getWsdl(client, context, dispatchContainer, visitedUrls, location).toURI().toURL()
                                    .toString());
                }
            }

            wsdl = element.toXml();
        } catch (Exception e) {
            logger.warn("Unable to cache imports for WSDL at URL: " + wsdlUrl, e);
        }

        FileUtils.writeStringToFile(tempFile, wsdl);
        dispatchContainer.getTempFiles().add(tempFile);

        return tempFile;
    } else {
        throw new Exception(
                "Unable to load WSDL at URL \"" + wsdlUrl + "\": " + String.valueOf(responseStatusLine));
    }
}

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());
    }/*ww w .  j av  a  2s  .co m*/

    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);
}

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

private void sendResponse(Request baseRequest, HttpServletResponse servletResponse,
        DispatchResult dispatchResult) throws Exception {
    ContentType contentType = ContentType
            .parse(replaceValues(connectorProperties.getResponseContentType(), dispatchResult));
    if (!connectorProperties.isResponseDataTypeBinary() && contentType.getCharset() == null) {
        /*//from  w  ww  . j  a v a2s  .c  om
         * If text mode is used and a specific charset isn't already defined, use the one from
         * the connector properties. We can't use ContentType.withCharset here because it
         * doesn't preserve other parameters, like boundary definitions
         */
        contentType = ContentType.parse(contentType.toString() + "; charset="
                + CharsetUtils.getEncoding(connectorProperties.getCharset()));
    }
    servletResponse.setContentType(contentType.toString());

    // set the response headers
    for (Entry<String, List<String>> entry : connectorProperties.getResponseHeaders().entrySet()) {
        for (String headerValue : entry.getValue()) {
            servletResponse.addHeader(entry.getKey(), replaceValues(headerValue, dispatchResult));
        }
    }

    // set the status code
    int statusCode = NumberUtils
            .toInt(replaceValues(connectorProperties.getResponseStatusCode(), dispatchResult), -1);

    /*
     * set the response body and status code (if we choose a response from the drop-down)
     */
    if (dispatchResult != null && dispatchResult.getSelectedResponse() != null) {
        dispatchResult.setAttemptedResponse(true);

        Response selectedResponse = dispatchResult.getSelectedResponse();
        Status newMessageStatus = selectedResponse.getStatus();

        /*
         * If the status code is custom, use the entered/replaced string If is is not a
         * variable, use the status of the destination's response (success = 200, failure = 500)
         * Otherwise, return 200
         */
        if (statusCode != -1) {
            servletResponse.setStatus(statusCode);
        } else if (newMessageStatus != null && newMessageStatus.equals(Status.ERROR)) {
            servletResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        } else {
            servletResponse.setStatus(HttpStatus.SC_OK);
        }

        String message = selectedResponse.getMessage();

        if (message != null) {
            OutputStream responseOutputStream = servletResponse.getOutputStream();
            byte[] responseBytes;
            if (connectorProperties.isResponseDataTypeBinary()) {
                responseBytes = Base64Util.decodeBase64(message.getBytes("US-ASCII"));
            } else {
                responseBytes = message.getBytes(CharsetUtils.getEncoding(connectorProperties.getCharset()));
            }

            // If the client accepts GZIP compression, compress the content
            boolean gzipResponse = false;
            for (Enumeration<String> en = baseRequest.getHeaders("Accept-Encoding"); en.hasMoreElements();) {
                String acceptEncoding = en.nextElement();

                if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
                    gzipResponse = true;
                    break;
                }
            }

            if (gzipResponse) {
                servletResponse.setHeader(HTTP.CONTENT_ENCODING, "gzip");
                GZIPOutputStream gzipOutputStream = new GZIPOutputStream(responseOutputStream);
                gzipOutputStream.write(responseBytes);
                gzipOutputStream.finish();
            } else {
                responseOutputStream.write(responseBytes);
            }

            // TODO include full HTTP payload in sentResponse
        }
    } else {
        /*
         * If the status code is custom, use the entered/replaced string Otherwise, return 200
         */
        if (statusCode != -1) {
            servletResponse.setStatus(statusCode);
        } else {
            servletResponse.setStatus(HttpStatus.SC_OK);
        }
    }
}

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

private static void processContent(DonkeyElement contentElement, Object content, ContentType contentType,
        boolean parseMultipart, BinaryContentTypeResolver resolver)
        throws DonkeyElementException, MessagingException, IOException {
    if (resolver == null) {
        resolver = defaultResolver;/*  ww  w  .  j  av a2s  . c o  m*/
    }

    if (parseMultipart && content instanceof MimeMultipart) {
        contentElement.setAttribute("multipart", "yes");
        MimeMultipart multipart = (MimeMultipart) content;

        String boundary = contentType.getParameter("boundary");
        if (StringUtils.isNotBlank(boundary)) {
            contentElement.setAttribute("boundary", boundary);
        }

        if (StringUtils.isNotEmpty(multipart.getPreamble())) {
            contentElement.addChildElement("Preamble", multipart.getPreamble());
        }

        for (int partIndex = 0; partIndex < multipart.getCount(); partIndex++) {
            BodyPart part = multipart.getBodyPart(partIndex);
            DonkeyElement partElement = contentElement.addChildElement("Part");
            DonkeyElement headersElement = partElement.addChildElement("Headers");
            ContentType partContentType = contentType;

            for (Enumeration<javax.mail.Header> en = part.getAllHeaders(); en.hasMoreElements();) {
                javax.mail.Header header = en.nextElement();
                headersElement.addChildElement(header.getName(), header.getValue());

                if (header.getName().equalsIgnoreCase("Content-Type")) {
                    try {
                        partContentType = ContentType.parse(header.getValue());
                    } catch (RuntimeException e) {
                    }
                }
            }

            processContent(partElement.addChildElement("Content"), part.getContent(), partContentType, true,
                    resolver);
        }
    } else {
        contentElement.setAttribute("multipart", "no");
        String charset = getDefaultHttpCharset(
                contentType.getCharset() != null ? contentType.getCharset().name() : null);

        // Call the resolver to determine if the content should be Base64 encoded
        if (resolver.isBinaryContentType(contentType)) {
            contentElement.setAttribute("encoding", "Base64");
            byte[] contentByteArray = null;

            if (content instanceof StreamSource) {
                StreamSource streamSource = (StreamSource) content;
                if (streamSource.getInputStream() != null) {
                    contentByteArray = IOUtils.toByteArray(streamSource.getInputStream());
                } else if (streamSource.getReader() != null) {
                    contentByteArray = IOUtils.toString(streamSource.getReader()).getBytes(charset);
                }
            } else if (content instanceof InputStream) {
                contentByteArray = IOUtils.toByteArray((InputStream) content);
            } else if (content instanceof byte[]) {
                contentByteArray = (byte[]) content;
            }

            if (contentByteArray == null) {
                contentByteArray = (content != null ? content.toString() : "").getBytes(charset);
            }

            contentElement.setTextContent(new String(Base64Util.encodeBase64(contentByteArray), "US-ASCII"));
        } else {
            String contentText = null;

            if (content instanceof StreamSource) {
                StreamSource streamSource = (StreamSource) content;
                if (streamSource.getInputStream() != null) {
                    contentText = IOUtils.toString(streamSource.getInputStream(), charset);
                } else if (streamSource.getReader() != null) {
                    contentText = IOUtils.toString(streamSource.getReader());
                }
            } else if (content instanceof InputStream) {
                contentText = IOUtils.toString((InputStream) content, charset);
            } else if (content instanceof byte[]) {
                contentText = new String((byte[]) content, charset);
            }

            if (contentText == null) {
                contentText = content != null ? content.toString() : "";
            }

            contentElement.setTextContent(contentText);
        }
    }
}