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.currencyfair.minfraud.MinFraudImplTest.java

@Test
public void testNonCloseableHttpResponseIsSupported() throws Exception {
    StringEntity responseEntity = new StringEntity(VALID_RESPONSE, ContentType.TEXT_PLAIN);
    HttpMethodFactory methodFactory = expectCreateHttpPost();
    HttpResponse httpResponse = EasyMock.createMock(HttpResponse.class);
    expectHttpResponse(httpResponse, 200, responseEntity);
    HttpClient client = expectHttpInvocation(httpResponse);
    EasyMock.replay(httpResponse);/*from   ww w.  j av  a 2  s .  co  m*/
    minFraudImpl.setHttpClient(client);
    minFraudImpl.setMethodFactory(methodFactory);
    minFraudImpl.setEndpoint(ENDPOINT);
    RiskScoreResponse response = minFraudImpl.calculateRisk(newRiskScoreRequest());
    Assert.assertNotNull(response);
    Assert.assertEquals(new BigDecimal("23.2"), response.getRiskScore());
    Assert.assertTrue(response.getGeoIpDetails().isCountryMatch());
    Assert.assertFalse(response.getGeoIpDetails().isHighRiskCountry());
    Assert.assertEquals("IE", response.getGeoIpDetails().getIpCountryCode());
    Assert.assertEquals(Integer.valueOf(48), response.getGeoIpDetails().getDistance());
    EasyMock.verify(httpResponse);
}

From source file:org.ballerinalang.composer.service.tryit.service.HttpTryItClient.java

/**
 * {@inheritDoc}/*from w w w  . jav  a 2s.  c om*/
 */
@Override
public String execute() throws TryItException {
    try {
        HttpClient client = HttpClientBuilder.create().build();
        HttpCoreContext localContext = new HttpCoreContext();
        // Create url for the request.
        String requestUrl = this.buildUrl();
        String httpMethod = this.clientArgs.get(TryItConstants.HTTP_METHOD).getAsString();
        switch (httpMethod.toLowerCase(Locale.getDefault())) {
        case "get":
        case "delete":
        case "options":
        case "head":
        case "trace":
            HttpRequestBase httpRequest = new TryItHttpRequestBase(httpMethod.toUpperCase(Locale.getDefault()));

            // Setting the url for the request.
            httpRequest.setURI(URI.create(requestUrl));

            // Setting the request headers.
            JsonArray getHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS);
            for (JsonElement getHeader : getHeaders) {
                JsonObject header = getHeader.getAsJsonObject();
                if (StringUtils.isNotBlank(header.get("key").getAsString())
                        && StringUtils.isNotBlank(header.get("value").getAsString())) {
                    httpRequest.setHeader(header.get("key").getAsString(), header.get("value").getAsString());
                }
            }

            // Setting the content type.
            if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) {
                httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType());
            } else {
                httpRequest.setHeader(HttpHeaders.CONTENT_TYPE,
                        this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString());
            }

            // To track how long the request took.
            long start = System.currentTimeMillis();

            // Executing the request.
            HttpResponse response = client.execute(httpRequest, localContext);
            long elapsed = System.currentTimeMillis() - start;

            return jsonStringifyResponse(response, localContext.getRequest().getAllHeaders(), requestUrl,
                    elapsed);
        default:
            HttpEntityEnclosingRequestBase httpEntityRequest = new TryItHttpEntityEnclosingRequestBase(
                    httpMethod.toUpperCase(Locale.getDefault()));

            // Setting the url for the request.
            httpEntityRequest.setURI(URI.create(requestUrl));

            // Setting the request headers.
            JsonArray getEntityHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS);
            for (JsonElement getHeader : getEntityHeaders) {
                JsonObject header = getHeader.getAsJsonObject();
                if (StringUtils.isNotBlank(header.get("key").getAsString())
                        && StringUtils.isNotBlank(header.get("value").getAsString())) {
                    httpEntityRequest.setHeader(header.get("key").getAsString(),
                            header.get("value").getAsString());
                }
            }

            // Setting the body of the request.
            StringEntity postEntity = new StringEntity(
                    this.clientArgs.get(TryItConstants.REQUEST_BODY).getAsString());
            httpEntityRequest.setEntity(postEntity);

            // Setting the content type.
            if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) {
                httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType());
            } else {
                httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE,
                        this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString());
            }

            // To track how long the request took.
            long entityRequestStart = System.currentTimeMillis();

            // Executing the request.
            HttpResponse entityResponse = client.execute(httpEntityRequest, localContext);
            long entityRequestDuration = System.currentTimeMillis() - entityRequestStart;
            return jsonStringifyResponse(entityResponse, localContext.getRequest().getAllHeaders(), requestUrl,
                    entityRequestDuration);
        }
    } catch (IOException e) {
        throw new TryItException(e.getMessage());
    }
}

From source file:org.ballerinalang.composer.service.workspace.tryit.HttpTryItClient.java

/**
 * {@inheritDoc}//from  w  w  w .j  av  a  2  s.com
 */
@Override
public String execute() throws TryItException {
    try {
        HttpClient client = HttpClientBuilder.create().build();
        HttpCoreContext localContext = new HttpCoreContext();
        // Create url for the request.
        String requestUrl = this.buildUrl();
        String httpMethod = this.clientArgs.get(TryItConstants.HTTP_METHOD).getAsString();
        switch (httpMethod.toLowerCase(Locale.getDefault())) {
        case "get":
        case "delete":
        case "options":
        case "head":
        case "trace":
            HttpRequestBase httpRequest = new TryItHttpRequestBase(httpMethod.toUpperCase(Locale.getDefault()));

            // Setting the url for the request.
            httpRequest.setURI(URI.create(requestUrl));

            // Setting the request headers.
            JsonArray getHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS);
            for (JsonElement getHeader : getHeaders) {
                JsonObject header = getHeader.getAsJsonObject();
                if (StringUtils.isNotBlank(header.get("key").getAsString())
                        && StringUtils.isNotBlank(header.get("value").getAsString())) {
                    httpRequest.setHeader(header.get("key").getAsString(), header.get("value").getAsString());
                }
            }

            // Setting the content type.
            if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) {
                httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType());
            } else {
                httpRequest.setHeader(HttpHeaders.CONTENT_TYPE,
                        this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString());
            }

            // To track how long the request took.
            long start = System.currentTimeMillis();

            // Executing the request.
            HttpResponse response = client.execute(httpRequest, localContext);
            long elapsed = System.currentTimeMillis() - start;

            return jsonStringifyResponse(response, localContext.getRequest().getAllHeaders(), requestUrl,
                    elapsed);
        default:
            HttpEntityEnclosingRequestBase httpEntityRequest = new TryItHttpEntityEnclosingRequestBase(
                    httpMethod.toUpperCase(Locale.getDefault()));

            // Setting the url for the request.
            httpEntityRequest.setURI(URI.create(requestUrl));

            // Setting the request headers.
            JsonArray getEntityHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS);
            for (JsonElement getHeader : getEntityHeaders) {
                JsonObject header = getHeader.getAsJsonObject();
                if (StringUtils.isNotBlank(header.get("key").getAsString())
                        && StringUtils.isNotBlank(header.get("value").getAsString())) {
                    httpEntityRequest.setHeader(header.get("key").getAsString(),
                            header.get("value").getAsString());
                }
            }

            // Setting the body of the request.
            StringEntity postEntity = new StringEntity(
                    this.clientArgs.get(TryItConstants.REQUEST_BODY).getAsString());
            httpEntityRequest.setEntity(postEntity);

            // Setting the content type.
            if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) {
                httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType());
            } else {
                httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE,
                        this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString());
            }

            // To track how long the request took.
            long entityRequestStart = System.currentTimeMillis();

            // Executing the request.
            HttpResponse entityResponse = client.execute(httpEntityRequest, localContext);
            long entityRequestDuration = System.currentTimeMillis() - entityRequestStart;
            return jsonStringifyResponse(entityResponse, localContext.getRequest().getAllHeaders(), requestUrl,
                    entityRequestDuration);
        }
    } catch (java.io.IOException e) {
        throw new TryItException(e.getMessage());
    }
}

From source file:com.qwazr.utils.http.HttpUtils.java

/**
 * Return a string with the content of any TEXT/PLAIN entity
 *
 * @param response      The response to check
 * @param expectedCodes The expected content type
 * @return the entity content/*from w  w  w .j a  va2s .c o  m*/
 * @throws IllegalStateException if the ob
 * @throws IOException           if any I/O error occurs
 */
public static String checkTextPlainEntity(HttpResponse response, int... expectedCodes) throws IOException {
    HttpUtils.checkStatusCodes(response, expectedCodes);
    HttpEntity entity = HttpUtils.checkIsEntity(response, ContentType.TEXT_PLAIN);
    Header header = entity.getContentEncoding();
    String encoding = header == null ? null : header.getValue();
    if (encoding == null)
        return IOUtils.toString(entity.getContent());
    else
        return IOUtils.toString(entity.getContent(), encoding);
}

From source file:be.ugent.psb.coexpnetviz.io.JobServer.java

private HttpEntity makeRequestEntity(JobDescription job) throws UnsupportedEncodingException {

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

    // Action to request of server
    entityBuilder.addTextBody("__controller", "api");
    entityBuilder.addTextBody("__action", "execute_job");

    // Baits /*from  w  w w  .  j  a va2  s.c om*/
    if (job.getBaitGroupSource() == BaitGroupSource.FILE) {
        entityBuilder.addBinaryBody("baits_file", job.getBaitGroupPath().toFile(), ContentType.TEXT_PLAIN,
                job.getBaitGroupPath().getFileName().toString());
    } else if (job.getBaitGroupSource() == BaitGroupSource.TEXT) {
        entityBuilder.addTextBody("baits", job.getBaitGroupText());
    } else {
        assert false;
    }

    // Expression matrices
    for (Path path : job.getExpressionMatrixPaths()) {
        entityBuilder.addBinaryBody("matrix[]", path.toFile(), ContentType.TEXT_PLAIN, path.toString());
    }

    // Correlation method
    String correlationMethod = null;
    if (job.getCorrelationMethod() == CorrelationMethod.MUTUAL_INFORMATION) {
        correlationMethod = "mutual_information";
    } else if (job.getCorrelationMethod() == CorrelationMethod.PEARSON) {
        correlationMethod = "pearson_r";
    } else {
        assert false;
    }
    entityBuilder.addTextBody("correlation_method", correlationMethod);

    // Cutoffs
    entityBuilder.addTextBody("lower_percentile_rank", Double.toString(job.getLowerPercentile()));
    entityBuilder.addTextBody("upper_percentile_rank", Double.toString(job.getUpperPercentile()));

    // Gene families source
    String orthologsSource = null;
    if (job.getGeneFamiliesSource() == GeneFamiliesSource.PLAZA) {
        orthologsSource = "plaza";
    } else if (job.getGeneFamiliesSource() == GeneFamiliesSource.CUSTOM) {
        orthologsSource = "custom";
        entityBuilder.addBinaryBody("gene_families", job.getGeneFamiliesPath().toFile(), ContentType.TEXT_PLAIN,
                job.getGeneFamiliesPath().getFileName().toString());
    } else if (job.getGeneFamiliesSource() == GeneFamiliesSource.NONE) {
        orthologsSource = "none";
    } else {
        assert false;
    }
    entityBuilder.addTextBody("gene_families_source", orthologsSource);

    return entityBuilder.build();
}

From source file:cpcc.com.services.CommunicationServiceTest.java

@BeforeMethod
public void setUp() throws Exception {
    content = null;/*  w ww . j  av  a 2 s .c  o m*/
    throwHttpException = false;

    handler = mock(HttpRequestHandler.class);

    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            request = (BasicHttpEntityEnclosingRequest) args[0];
            HttpResponse response = (HttpResponse) args[1];
            // HttpContext context = (HttpContext) args[2];

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(request.getEntity().getContent(), baos);
            content = baos.toByteArray();

            if (throwHttpException) {
                throw new HttpException("HttpException thrown on purpose!");
            }

            final int statusCode = response.getStatusLine().getStatusCode();
            final String reasonPhrase = response.getStatusLine().getReasonPhrase();
            final ProtocolVersion protocolVersion = response.getProtocolVersion();

            response.setStatusLine(new MyStatusLine(protocolVersion, statusCode, reasonPhrase));
            HttpEntity entity = EntityBuilder.create().setContentType(ContentType.TEXT_PLAIN)
                    .setText(REASON_PHRASE).build();

            response.setEntity(entity);
            return null;
        }
    }).when(handler).handle(any(HttpRequest.class), any(HttpResponse.class), any(HttpContext.class));

    server = new LocalTestServer(null, null);
    server.register("/*", handler);
    server.start();
    InetSocketAddress addr = server.getServiceAddress();
    String serverUrl = "http://" + addr.getHostString() + ":" + addr.getPort();

    realVehicle = mock(RealVehicle.class);
    when(realVehicle.getUrl()).thenReturn(serverUrl + "/rv001");

    com = new CommunicationServiceImpl();
}

From source file:com.adobe.ibm.watson.traits.impl.WatsonServiceClient.java

/**
 * Fetches the IBM Watson Personal Insights report using the user's Twitter Timeline.
 * @param language//from w ww  .  j a va 2s  . c om
 * @param tweets
 * @param resource
 * @return
 * @throws Exception
 */
public String getWatsonScore(String language, String tweets, Resource resource) throws Exception {

    HttpsURLConnection connection = null;

    // Check if the username and password have been injected to the service.
    // If not, extract them from the cloud service configuration attached to the page.
    if (this.username == null || this.password == null) {
        getWatsonCloudSettings(resource);
    }

    // Build the request to IBM Watson.
    log.info("The Base Url is: " + this.baseUrl);
    String encodedCreds = getBasicAuthenticationEncoding();
    URL url = new URL(this.baseUrl + "/v2/profile");

    connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Content-Language", language);
    connection.setRequestProperty("Accept-Language", "en-us");
    connection.setRequestProperty("Content-Type", ContentType.TEXT_PLAIN.toString());
    connection.setRequestProperty("Authorization", "Basic " + encodedCreds);
    connection.setUseCaches(false);
    connection.getOutputStream().write(tweets.getBytes());
    connection.getOutputStream().flush();
    connection.connect();

    log.info("Parsing response from Watson");
    StringBuilder str = new StringBuilder();

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line = "";
    while ((line = br.readLine()) != null) {
        str.append(line + System.getProperty("line.separator"));
    }

    if (connection.getResponseCode() != 200) {
        // The call failed, throw an exception.
        log.error(connection.getResponseCode() + " : " + connection.getResponseMessage());
        connection.disconnect();
        throw new Exception("IBM Watson Server responded with an error: " + connection.getResponseMessage());
    } else {
        connection.disconnect();
        return str.toString();
    }
}

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

@Test
public void testHelloSpringResource() throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        {/*from  www .j  ava2 s.c  o  m*/
            URI uri = new URIBuilder().setScheme("http").setHost(url.getHost()).setPort(url.getPort())
                    .setPath(url.getPath() + "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(url.toString() + "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(url.toString() + "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(url.getHost()).setPort(url.getPort())
                    .setPath(url.getPath() + "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(url.toString() + "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/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:com.jaeksoft.searchlib.scheduler.task.TaskUploadMonitor.java

@Override
public void execute(Client client, TaskProperties properties, Variables variables, TaskLog taskLog)
        throws SearchLibException {
    String url = properties.getValue(propUrl);
    URI uri;//from  ww w  . j  a  va 2 s  . c  o  m
    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new SearchLibException(e);
    }
    String login = properties.getValue(propLogin);
    String password = properties.getValue(propPassword);
    String instanceId = properties.getValue(propInstanceId);

    CredentialItem credentialItem = null;
    if (!StringUtils.isEmpty(login) && !StringUtils.isEmpty(password))
        credentialItem = new CredentialItem(CredentialType.BASIC_DIGEST, null, login, password, null, null);
    HttpDownloader downloader = client.getWebCrawlMaster().getNewHttpDownloader(true);
    try {
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addPart("instanceId",
                new StringBody(instanceId, ContentType.TEXT_PLAIN));

        new Monitor().writeToPost(entityBuilder);
        DownloadItem downloadItem = downloader.post(uri, credentialItem, null, null, entityBuilder.build());
        if (downloadItem.getStatusCode() != 200)
            throw new SearchLibException(
                    "Wrong code status:" + downloadItem.getStatusCode() + " " + downloadItem.getReasonPhrase());
        taskLog.setInfo("Monitoring data uploaded");
    } catch (ClientProtocolException e) {
        throw new SearchLibException(e);
    } catch (IOException e) {
        throw new SearchLibException(e);
    } catch (IllegalStateException e) {
        throw new SearchLibException(e);
    } catch (URISyntaxException e) {
        throw new SearchLibException(e);
    } finally {
        downloader.release();
    }

}

From source file:com.github.tomakehurst.wiremock.RequestQueryAcceptanceTest.java

@Test
public void requestBodyEncodingRemainsUtf8() {
    byte[] body = new byte[] { -38, -100 }; // UTF-8 bytes for 
    testClient.post("/encoding", new ByteArrayEntity(body, ContentType.TEXT_PLAIN));

    List<LoggedRequest> requests = findAll(postRequestedFor(urlEqualTo("/encoding")));
    LoggedRequest request = requests.get(0);
    assertThat(request.getBodyAsString(), is(""));
}