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

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

Introduction

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

Prototype

ContentType TEXT_PLAIN

To view the source code for org.apache.http.entity ContentType TEXT_PLAIN.

Click Source Link

Usage

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  ww.  j av  a  2  s  .c  o  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.liferay.sync.engine.session.Session.java

private StringBody _getStringBody(Object value) {
    return new StringBody(String.valueOf(value),
            ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), Charset.forName("UTF-8")));
}

From source file:com.naryx.tagfusion.cfm.http.cfHttpConnection.java

private void addFormData() throws cfmRunTimeException {
    Map<String, String> formData = httpData.getFormData();
    Iterator<String> keys = formData.keySet().iterator();
    String nextKey;/*ww  w . j  a va 2  s .c o  m*/

    if (message.getMethod().equalsIgnoreCase("POST")) {

        if (isMultipart || httpData.getFiles().size() > 0) {

            if (multipartEntityBuilder == null)
                multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(charset);

            while (keys.hasNext()) {
                nextKey = keys.next();
                multipartEntityBuilder.addPart(nextKey,
                        new StringBody(formData.get(nextKey), ContentType.TEXT_PLAIN));
            }

        } else {

            Header contentType = message.getFirstHeader("Content-type");
            if (contentType == null) {
                // otherwise it's been set manually so don't override it
                message.setHeader("Content-type", "application/x-www-form-urlencoded");
            }

            StringBuilder paramStr = new StringBuilder();
            while (keys.hasNext()) {
                nextKey = keys.next();
                paramStr.append(nextKey);
                paramStr.append('=');
                paramStr.append(formData.get(nextKey));
                paramStr.append('&');
            }
            if (paramStr.length() > 0) {
                paramStr.deleteCharAt(paramStr.length() - 1); // remove last &
                ((HttpPost) message).setEntity(new StringEntity(paramStr.toString(), this.charset));
            }

        }
    }
}

From source file:com.mxhero.plugin.cloudstorage.onedrive.api.Items.java

/**
 * Simple upload.//ww  w. j  a v  a2  s.  c o  m
 *
 * @param path the path
 * @param file the file
 * @param conflictBehavior the conflict behavior
 * @return the item
 * @throws IllegalArgumentException the illegal argument exception
 */
private Item simpleUpload(final String path, final File file, final ConflictBehavior conflictBehavior) {
    final Command<Item> command = this.commandFactory.create();
    command.validate(Validator.builder().file().name(file.getName()).build());
    return command.excecute(new CommandHandler<Item>() {

        @Override
        public Item response(HttpResponse response) {
            try {
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED
                        || response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    return OneDrive.JACKSON.readValue(EntityUtils.toString(response.getEntity()), Item.class);
                }
                if (response.getStatusLine().getStatusCode() > 399) {
                    throw new ApiException(response);
                }
                throw new IllegalArgumentException(
                        "error reading response body with code " + response.getStatusLine().getStatusCode());
            } catch (Exception e) {
                throw new IllegalArgumentException("error reading response", e);
            }
        }

        /* (non-Javadoc)
         * @see com.mxhero.plugin.cloudstorage.onedrive.api.command.CommandHandler#request()
         */
        @Override
        public HttpUriRequest request() {
            try {
                URIBuilder builder = new URIBuilder(command.baseUrl() + path);
                builder.addParameter("@name.conflictBehavior", conflictBehavior.name());
                HttpPut httpPut = new HttpPut(builder.build().toString());
                httpPut.setHeader("Content-Type", "text/plain");
                httpPut.setEntity(new FileEntity(file, ContentType.TEXT_PLAIN));
                return httpPut;
            } catch (Exception e) {
                throw new IllegalArgumentException("couldn't create query", e);
            }
        }
    });
}

From source file:org.wso2.appcloud.integration.test.utils.clients.ApplicationClient.java

public void changeAppIcon(String applicationHash, File appIcon) throws AppCloudIntegrationTestException {
    HttpClient httpclient = null;/*from  w  w w .  j  a va  2s . c  o m*/
    org.apache.http.HttpResponse response = null;
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();

        HttpPost httppost = new HttpPost(this.endpoint);
        httppost.setConfig(requestConfig);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart(PARAM_NAME_CHANGE_ICON, new FileBody(appIcon));
        builder.addPart(PARAM_NAME_ACTION, new StringBody(CHANGE_APP_ICON_ACTION, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_HASH_ID,
                new StringBody(applicationHash, ContentType.TEXT_PLAIN));
        httppost.setEntity(builder.build());
        httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE));
        response = httpclient.execute(httppost);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity());
            throw new AppCloudIntegrationTestException("Update app icon failed " + result);
        }
    } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) {
        // In most of the cases, even though connection is timed out, actual activity is completed.
        // And this will be asserted so if it failed due to a valid case, it will be captured.
        log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1);
    } catch (IOException e) {
        log.error("Failed to invoke app icon update API.", e);
        throw new AppCloudIntegrationTestException("Failed to invoke app icon update API.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(httpclient);
    }
}

From source file:org.apache.hadoop.gateway.dispatch.CappedBufferHttpEntityTest.java

@Test
public void testIsStreaming() throws Exception {
    String input = "0123456789";
    BasicHttpEntity basic;//from  w  w  w  . j  av  a 2  s  . c  om
    InputStreamEntity streaming;
    CappedBufferHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    replay = new CappedBufferHttpEntity(basic, 5);
    assertThat(replay.isStreaming(), is(true));

    basic = new BasicHttpEntity();
    basic.setContent(null);
    replay = new CappedBufferHttpEntity(basic, 5);
    assertThat(replay.isStreaming(), is(false));

    streaming = new InputStreamEntity(new ByteArrayInputStream(input.getBytes(UTF8)), 10,
            ContentType.TEXT_PLAIN);
    replay = new CappedBufferHttpEntity(streaming, 5);
    assertThat(replay.isStreaming(), is(true));
}

From source file:org.apache.hadoop.gateway.dispatch.PartiallyRepeatableHttpEntityTest.java

@Test
public void testIsStreaming() throws Exception {
    String input = "0123456789";
    BasicHttpEntity basic;//from w w  w .ja va2s  .  c  o  m
    InputStreamEntity streaming;
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.isStreaming(), is(true));

    basic = new BasicHttpEntity();
    basic.setContent(null);
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.isStreaming(), is(false));

    streaming = new InputStreamEntity(new ByteArrayInputStream(input.getBytes(UTF8)), 10,
            ContentType.TEXT_PLAIN);
    replay = new PartiallyRepeatableHttpEntity(streaming, 5);
    assertThat(replay.isStreaming(), is(true));
}

From source file:com.clxcommunications.xms.ApiConnectionIT.java

@Test
public void canHandle404WhenFetchingBatchSync() throws Exception {
    String spid = TestUtils.freshServicePlanId();
    BatchId batchId = TestUtils.freshBatchId();

    String path = "/v1/" + spid + "/batches/" + batchId;

    wm.stubFor(get(urlEqualTo(path)).willReturn(aResponse().withStatus(404)
            .withHeader("Content-Type", ContentType.TEXT_PLAIN.toString()).withBody("BAD")));

    ApiConnection conn = ApiConnection.builder().servicePlanId(spid).token("toktok")
            .endpoint("http://localhost:" + wm.port()).start();

    try {//ww w.  j av a 2 s. co m
        conn.fetchBatch(batchId);
        fail("Expected exception, got none");
    } catch (NotFoundException e) {
        assertThat(e.getPath(), is(path));
    } finally {
        conn.close();
    }
}

From source file:de.tu_dortmund.ub.data.dswarm.Task.java

/**
 * upload a file and update an existing resource with it
 *
 * @param resourceUUID//from  ww w  .j  ava 2  s .c  o  m
 * @param filename
 * @param name
 * @param description
 * @return responseJson
 * @throws Exception
 */
private String uploadFileAndUpdateResource(String resourceUUID, String filename, String name,
        String description) throws Exception {

    if (null == resourceUUID)
        throw new Exception("ID of the resource to update was null.");

    String responseJson = null;

    String file = config.getProperty("resource.watchfolder") + File.separatorChar + filename;

    // ggf. Preprocessing: insert CDATA in XML and write new XML file to tmp folder
    if (Boolean.parseBoolean(config.getProperty("resource.preprocessing"))) {

        Document document = new SAXBuilder().build(new File(file));

        file = config.getProperty("preprocessing.folder") + File.separatorChar + UUID.randomUUID() + ".xml";

        XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
        BufferedWriter bufferedWriter = null;
        try {

            bufferedWriter = new BufferedWriter(new FileWriter(file));

            out.output(new SAXBuilder().build(new StringReader(
                    XmlTransformer.xmlOutputter(document, config.getProperty("preprocessing.xslt"), null))),
                    bufferedWriter);
        } finally {
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
        }
    }

    // upload
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {
        HttpPut httpPut = new HttpPut(config.getProperty("engine.dswarm.api") + "resources/" + resourceUUID);

        FileBody fileBody = new FileBody(new File(file));
        StringBody stringBodyForName = new StringBody(name, ContentType.TEXT_PLAIN);
        StringBody stringBodyForDescription = new StringBody(description, ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", fileBody)
                .addPart("name", stringBodyForName).addPart("description", stringBodyForDescription).build();

        httpPut.setEntity(reqEntity);

        logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpPut.getRequestLine());

        CloseableHttpResponse httpResponse = httpclient.execute(httpPut);

        try {
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();

            switch (statusCode) {

            case 200: {

                logger.info("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
                StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, "UTF-8");
                responseJson = writer.toString();

                logger.info("[" + config.getProperty("service.name") + "] responseJson : " + responseJson);

                break;
            }
            default: {

                logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            }

            EntityUtils.consume(httpEntity);
        } finally {
            httpResponse.close();
        }
    } finally {
        httpclient.close();
    }

    return responseJson;
}