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.cloudera.oryx.contrib.flume.OryxEventSink.java

/**
 * Sends the given {@code batch} to Oryx in a HTTP POST request.
 * @param batch the batch of records to send to Oryx
 *///from  www. jav  a  2  s  . co m
private void processBatch(Collection<String> batch) {
    if (log.isDebugEnabled()) {
        log.debug("Sending batch of {} records to Oryx at {}", batch.size(), oryxUri);
    }

    StringBuilder sb = new StringBuilder();
    for (String record : batch) {
        sb.append(record).append('\n');
    }

    HttpPost post = new HttpPost(oryxUri);
    HttpEntity entity = new StringEntity(sb.toString(), ContentType.TEXT_PLAIN);
    post.setEntity(entity);

    try {
        HttpResponse response = client.execute(post);
        if (log.isDebugEnabled()) {
            log.debug("HTTP response from Oryx: '{}'", response.getStatusLine());
        }
        EntityUtils.consumeQuietly(response.getEntity());
    } catch (IOException e) {
        log.error("Unable to POST batch to Oryx", e);
    }
}

From source file:org.jboss.as.quickstarts.resteasyspring.test.ResteasySpringIT.java

@Test
public void testLocatingResource() throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        {// w  w  w .ja v a 2s  .  c  om
            URI uri = new URIBuilder().setScheme("http").setHost("localhost:8080")
                    .setPath("/spring-resteasy/locating/hello").setParameter("name", "JBoss Developer").build();
            HttpGet method = new HttpGet(uri);
            try (CloseableHttpResponse response = client.execute(method)) {
                Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatusLine().getStatusCode());
                Assert.assertTrue(EntityUtils.toString(response.getEntity()).contains("JBoss Developer"));
            } finally {
                method.releaseConnection();
            }
        }
        {
            HttpGet method = new HttpGet("http://localhost:8080/spring-resteasy/locating/basic");
            try (CloseableHttpResponse response = client.execute(method)) {
                Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatusLine().getStatusCode());
                Assert.assertTrue(EntityUtils.toString(response.getEntity()).contains("basic"));
            } finally {
                method.releaseConnection();
            }
        }
        {
            HttpPut method = new HttpPut("http://localhost:8080/spring-resteasy/locating/basic");
            method.setEntity(new StringEntity("basic", ContentType.TEXT_PLAIN));
            try (CloseableHttpResponse response = client.execute(method)) {
                Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatusLine().getStatusCode());
            } finally {
                method.releaseConnection();
            }
        }
        {
            URI uri = new URIBuilder().setScheme("http").setHost("localhost:8080")
                    .setPath("/spring-resteasy/locating/queryParam").setParameter("param", "hello world")
                    .build();
            HttpGet method = new HttpGet(uri);
            try (CloseableHttpResponse response = client.execute(method)) {
                Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatusLine().getStatusCode());
                Assert.assertTrue(EntityUtils.toString(response.getEntity()).contains("hello world"));
            } finally {
                method.releaseConnection();
            }
        }
        {
            HttpGet method = new HttpGet(
                    "http://localhost:8080/spring-resteasy/locating/matrixParam;param=matrix");
            try (CloseableHttpResponse response = client.execute(method)) {
                Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatusLine().getStatusCode());
                Assert.assertTrue(EntityUtils.toString(response.getEntity()).equals("matrix"));
            } finally {
                method.releaseConnection();
            }
        }
        {
            HttpGet method = new HttpGet("http://localhost:8080/spring-resteasy/locating/uriParam/1234");
            try (CloseableHttpResponse response = client.execute(method)) {
                Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatusLine().getStatusCode());
                Assert.assertTrue(EntityUtils.toString(response.getEntity()).equals("1234"));
            } finally {
                method.releaseConnection();
            }
        }
    }
}

From source file:org.nuxeo.ecm.core.opencmis.impl.CmisSuiteSession2.java

protected HttpEntity getCreateDocumentHttpEntity(File file) {
    FormBodyPart cmisactionPart = FormBodyPartBuilder
            .create("cmisaction", new StringBody("createDocument", ContentType.TEXT_PLAIN)).build();
    FormBodyPart contentPart = FormBodyPartBuilder
            .create("content", new FileBody(file, ContentType.TEXT_PLAIN, "testfile.txt")).build();
    HttpEntity entity = MultipartEntityBuilder.create().addPart(cmisactionPart)
            .addTextBody("propertyId[0]", "cmis:name").addTextBody("propertyValue[0]", "testfile01")
            .addTextBody("propertyId[1]", "cmis:objectTypeId").addTextBody("propertyValue[1]", "File")
            .addPart(contentPart).build();
    return entity;
}

From source file:com.mirth.connect.client.core.ConnectServiceUtil.java

public static int getNotificationCount(String serverId, String mirthVersion,
        Map<String, String> extensionVersions, Set<Integer> archivedNotifications, String[] protocols,
        String[] cipherSuites) {//from   ww w. j ava2  s . c o  m
    CloseableHttpClient client = null;
    HttpPost post = new HttpPost();
    CloseableHttpResponse response = null;

    int notificationCount = 0;

    try {
        ObjectMapper mapper = new ObjectMapper();
        String extensionVersionsJson = mapper.writeValueAsString(extensionVersions);
        NameValuePair[] params = { new BasicNameValuePair("op", NOTIFICATION_COUNT_GET),
                new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion),
                new BasicNameValuePair("extensionVersions", extensionVersionsJson) };
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT)
                .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();

        post.setURI(URI.create(URL_CONNECT_SERVER + URL_NOTIFICATION_SERVLET));
        post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8")));

        HttpClientContext postContext = HttpClientContext.create();
        postContext.setRequestConfig(requestConfig);
        client = getClient(protocols, cipherSuites);
        response = client.execute(post, postContext);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if ((statusCode == HttpStatus.SC_OK)) {
            HttpEntity responseEntity = response.getEntity();
            Charset responseCharset = null;
            try {
                responseCharset = ContentType.getOrDefault(responseEntity).getCharset();
            } catch (Exception e) {
                responseCharset = ContentType.TEXT_PLAIN.getCharset();
            }

            List<Integer> notificationIds = mapper.readValue(
                    IOUtils.toString(responseEntity.getContent(), responseCharset).trim(),
                    new TypeReference<List<Integer>>() {
                    });
            for (int id : notificationIds) {
                if (!archivedNotifications.contains(id)) {
                    notificationCount++;
                }
            }
        }
    } catch (Exception e) {
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(client);
    }
    return notificationCount;
}

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

public void createNewApplication(String applicationName, String runtime, String appTypeName,
        String applicationRevision, String applicationDescription, String uploadedFileName,
        String runtimeProperties, String tags, File uploadArtifact, boolean isNewVersion,
        String applicationContext, String conSpec, boolean setDefaultVersion, String appCreationMethod,
        String gitRepoUrl, String gitRepoBranch, String projectRoot) throws AppCloudIntegrationTestException {

    HttpClient httpclient = null;//from ww  w. jav  a2s .  c o m
    org.apache.http.HttpResponse response = null;
    int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        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_ACTION, new StringBody(CREATE_APPLICATION_ACTION, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APP_CREATION_METHOD,
                new StringBody(appCreationMethod, ContentType.TEXT_PLAIN));
        if (GITHUB.equals(appCreationMethod)) {
            builder.addPart(PARAM_NAME_GIT_REPO_URL, new StringBody(gitRepoUrl, ContentType.TEXT_PLAIN));
            builder.addPart(PARAM_NAME_GIT_REPO_BRANCH, new StringBody(gitRepoBranch, ContentType.TEXT_PLAIN));
            builder.addPart(PARAM_NAME_PROJECT_ROOT, new StringBody(projectRoot, ContentType.TEXT_PLAIN));
        } else if (DEFAULT.equals(appCreationMethod)) {
            builder.addPart(PARAM_NAME_FILE_UPLOAD, new FileBody(uploadArtifact));
            builder.addPart(PARAM_NAME_UPLOADED_FILE_NAME,
                    new StringBody(uploadedFileName, ContentType.TEXT_PLAIN));
            builder.addPart(PARAM_NAME_IS_FILE_ATTACHED,
                    new StringBody(Boolean.TRUE.toString(), ContentType.TEXT_PLAIN));//Setting true to send the file in request
        }
        builder.addPart(PARAM_NAME_CONTAINER_SPEC, new StringBody(conSpec, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_NAME, new StringBody(applicationName, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_DESCRIPTION,
                new StringBody(applicationDescription, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_RUNTIME, new StringBody(runtime, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APP_TYPE_NAME, new StringBody(appTypeName, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APP_CONTEXT, new StringBody(applicationContext, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_REVISION,
                new StringBody(applicationRevision, ContentType.TEXT_PLAIN));

        builder.addPart(PARAM_NAME_PROPERTIES, new StringBody(runtimeProperties, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_TAGS, new StringBody(tags, ContentType.TEXT_PLAIN));

        builder.addPart(PARAM_NAME_IS_NEW_VERSION,
                new StringBody(Boolean.toString(isNewVersion), ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_SET_DEFAULT_VERSION,
                new StringBody(Boolean.toString(setDefaultVersion), 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("CreateNewApplication failed " + result);
        }

    } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) {
        // In most of the cases, even though connection is timed out, actual activity is completed.
        // If application is not created, in next test case, it will be identified.
        log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1);
    } catch (IOException e) {
        log.error("Failed to invoke application creation API.", e);
        throw new AppCloudIntegrationTestException("Failed to invoke application creation API.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(httpclient);
    }
}

From source file:org.mule.test.construct.FlowRefTestCase.java

@Test
public void nonBlockingFlowRefToQueuedAsyncFlow() throws Exception {
    Response response = Request
            .Post(String.format("http://localhost:%s/%s", port.getNumber(),
                    "nonBlockingFlowRefToQueuedAsyncFlow"))
            .connectTimeout(RECEIVE_TIMEOUT).bodyString(TEST_MESSAGE, ContentType.TEXT_PLAIN).execute();
    HttpResponse httpResponse = response.returnResponse();
    assertThat(httpResponse.getStatusLine().getStatusCode(), is(500));
    assertThat(IOUtils.toString(httpResponse.getEntity().getContent()),
            is("Unable to process a synchronous event asynchronously."));
}

From source file:org.nuxeo.ecm.core.opencmis.impl.CmisSuiteSession2.java

protected HttpEntity getCheckInHttpEntity(File file) {
    FormBodyPart cmisactionPart = FormBodyPartBuilder
            .create("cmisaction", new StringBody("checkIn", ContentType.TEXT_PLAIN)).build();
    FormBodyPart contentPart = FormBodyPartBuilder
            .create("content", new FileBody(file, ContentType.TEXT_PLAIN, "testfile.txt")).build();
    HttpEntity entity = MultipartEntityBuilder.create().addPart(cmisactionPart).addPart(contentPart).build();
    return entity;
}

From source file:org.nuxeo.ecm.core.opencmis.impl.CmisSuiteSession2.java

protected HttpEntity getSetContentStreamHttpEntity(File file, String changeToken) {
    FormBodyPart cmisactionPart = FormBodyPartBuilder
            .create("cmisaction", new StringBody("setContent", ContentType.TEXT_PLAIN)).build();
    FormBodyPart contentPart = FormBodyPartBuilder
            .create("content", new FileBody(file, ContentType.TEXT_PLAIN, "testfile.txt")).build();
    HttpEntity entity = MultipartEntityBuilder.create().addPart(cmisactionPart)
            .addTextBody("changeToken", changeToken).addPart(contentPart).build();
    return entity;
}

From source file:org.mule.test.construct.FlowRefTestCase.java

@Test
public void nonBlockingFlowRefToAsyncFlow() throws Exception {
    Response response = Request
            .Post(String.format("http://localhost:%s/%s", port.getNumber(), "nonBlockingFlowRefToAsyncFlow"))
            .connectTimeout(RECEIVE_TIMEOUT).bodyString(TEST_MESSAGE, ContentType.TEXT_PLAIN).execute();
    HttpResponse httpResponse = response.returnResponse();
    assertThat(httpResponse.getStatusLine().getStatusCode(), is(500));
    assertThat(IOUtils.toString(httpResponse.getEntity().getContent()),
            is("Unable to process a synchronous event asynchronously."));
}

From source file:de.yaio.commons.http.HttpUtils.java

/** 
 * execute POST-Request for url with params
 * @param baseUrl                the url to call
 * @param username               username for auth
 * @param password               password for auth
 * @param params                 params for the request
 * @param textFileParams         text-files to upload
 * @param binFileParams          bin-files to upload
 * @return                       HttpResponse
 * @throws IOException           possible Exception if Request-state <200 > 299 
 *///from   w ww  . j  av a 2  s .co  m
public static HttpResponse callPatchUrlPure(final String baseUrl, final String username, final String password,
        final Map<String, String> params, final Map<String, String> textFileParams,
        final Map<String, String> binFileParams) throws IOException {
    // create request
    HttpPatch request = new HttpPatch(baseUrl);

    // map params
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    if (MapUtils.isNotEmpty(params)) {
        for (String key : params.keySet()) {
            builder.addTextBody(key, params.get(key), ContentType.TEXT_PLAIN);
        }
    }

    // map files
    if (MapUtils.isNotEmpty(textFileParams)) {
        for (String key : textFileParams.keySet()) {
            File file = new File(textFileParams.get(key));
            builder.addBinaryBody(key, file, ContentType.DEFAULT_TEXT, textFileParams.get(key));
        }
    }
    // map files
    if (MapUtils.isNotEmpty(binFileParams)) {
        for (String key : binFileParams.keySet()) {
            File file = new File(binFileParams.get(key));
            builder.addBinaryBody(key, file, ContentType.DEFAULT_BINARY, binFileParams.get(key));
        }
    }

    // set request
    HttpEntity multipart = builder.build();
    request.setEntity(multipart);

    // add request header
    request.addHeader("User-Agent", "YAIOCaller");

    // call url
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Sending 'PATCH' request to URL : " + baseUrl);
    }
    HttpResponse response = executeRequest(request, username, password);

    // get response
    int retCode = response.getStatusLine().getStatusCode();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Response Code : " + retCode);
    }
    return response;
}