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(expected = IOException.class)
public void testExceptionOnClosePropagatesWhenThereIsNoOtherException() throws Exception {
    StringEntity responseEntity = new StringEntity(VALID_RESPONSE, ContentType.TEXT_PLAIN);
    HttpMethodFactory methodFactory = expectCreateHttpPost();
    CloseableHttpResponse httpResponse = EasyMock.createMock(CloseableHttpResponse.class);
    expectHttpResponse(httpResponse, 200, responseEntity);
    expectClose(httpResponse, new IOException("Expect this!"));
    HttpClient client = expectHttpInvocation(httpResponse);
    EasyMock.replay(httpResponse);//from   w ww  .jav  a  2  s .c o m
    minFraudImpl.setHttpClient(client);
    minFraudImpl.setMethodFactory(methodFactory);
    minFraudImpl.setEndpoint(ENDPOINT);
    minFraudImpl.calculateRisk(newRiskScoreRequest());
}

From source file:be.samey.io.ServerConn.java

private HttpEntity makeEntity(String baits, String[] names, Path[] filepaths, double poscutoff,
        double negcutoff, String[] orthNames, Path[] orthPaths) throws UnsupportedEncodingException {

    MultipartEntityBuilder mpeb = MultipartEntityBuilder.create();

    //make hidden form fields, to the server knows to use the api
    mpeb.addPart("__controller", new StringBody("api"));
    mpeb.addPart("__action", new StringBody("execute_job"));

    //make the bait part
    StringBody baitspart = new StringBody(baits, ContentType.TEXT_PLAIN);
    mpeb.addPart("baits", baitspart);

    //make the species file upload parts
    for (int i = 0; i < CyModel.MAX_SPECIES_COUNT; i++) {
        if (i < names.length && i < filepaths.length) {
            mpeb.addBinaryBody("matrix[]", filepaths[i].toFile(), ContentType.TEXT_PLAIN, names[i]);
        }/*from  w  w  w.j a v a  2 s . c  o  m*/
    }

    //make the cutoff parts
    StringBody poscpart = new StringBody(Double.toString(poscutoff));
    mpeb.addPart("positive_correlation", poscpart);
    StringBody negcpart = new StringBody(Double.toString(negcutoff));
    mpeb.addPart("negative_correlation", negcpart);

    //make the orthgroup file upload parts
    for (int i = 0; i < CyModel.MAX_ORTHGROUP_COUNT; i++) {
        if (cyModel.getOrthGroupPaths() != null && i < orthNames.length && i < orthPaths.length) {
            mpeb.addBinaryBody("orthologs[]", orthPaths[i].toFile(), ContentType.TEXT_PLAIN, orthNames[i]);
        }
    }

    return mpeb.build();
}

From source file:edu.si.services.sidora.rest.batch.BatchServiceTest.java

@Test
public void newBatchRequest_addResourceObjects_Test() throws Exception {

    String resourceListXML = FileUtils
            .readFileToString(new File("src/test/resources/test-data/batch-test-files/audio/audioFiles.xml"));

    String expectedHTTPResponseBody = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
            + "<Batch>\n" + "    <ParentPID>" + parentPid + "</ParentPID>\n" + "    <CorrelationID>"
            + correlationId + "</CorrelationID>\n" + "</Batch>\n";

    BatchRequestResponse expectedCamelResponseBody = new BatchRequestResponse();
    expectedCamelResponseBody.setParentPID(parentPid);
    expectedCamelResponseBody.setCorrelationId(correlationId);

    MockEndpoint mockEndpoint = getMockEndpoint("mock:result");
    mockEndpoint.expectedMessageCount(1);

    context.getComponent("sql", SqlComponent.class).setDataSource(db);
    context.getRouteDefinition("BatchProcessResources").autoStartup(false);

    //Configure and use adviceWith to mock for testing purpose
    context.getRouteDefinition("BatchProcessAddResourceObjects").adviceWith(context,
            new AdviceWithRouteBuilder() {
                @Override//  w  w w.j  a  va  2  s  .co m
                public void configure() throws Exception {
                    weaveById("httpGetResourceList").replace().setBody(simple(resourceListXML));

                    weaveByToString(".*bean:batchRequestControllerBean.*").replace().setHeader("correlationId",
                            simple(correlationId));

                    weaveAddLast().to("mock:result");

                }
            });

    HttpPost post = new HttpPost(BASE_URL + "/addResourceObjects/" + parentPid);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT);

    // Add filelist xml URL upload
    builder.addTextBody("resourceFileList", resourceFileList, ContentType.TEXT_PLAIN);
    // Add metadata xml file URL upload
    builder.addTextBody("ds_metadata", ds_metadata, ContentType.TEXT_PLAIN);
    // Add sidora xml URL upload
    builder.addTextBody("ds_sidora", ds_sidora, ContentType.TEXT_PLAIN);
    // Add association xml URL upload
    builder.addTextBody("association", association, ContentType.TEXT_PLAIN);
    // Add resourceOwner string
    builder.addTextBody("resourceOwner", resourceOwner, ContentType.TEXT_PLAIN);

    post.setEntity(builder.build());

    HttpResponse response = httpClient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
    String responseBody = EntityUtils.toString(response.getEntity());
    log.debug("======================== [ RESPONSE ] ========================\n" + responseBody);

    assertEquals(expectedHTTPResponseBody, responseBody);

    log.debug("===============[ DB Requests ]================\n{}",
            jdbcTemplate.queryForList("select * from sidora.camelBatchRequests"));
    log.debug("===============[ DB Resources ]===============\n{}",
            jdbcTemplate.queryForList("select * from sidora.camelBatchResources"));

    BatchRequestResponse camelResultBody = (BatchRequestResponse) mockEndpoint.getExchanges().get(0).getIn()
            .getBody();

    assertIsInstanceOf(BatchRequestResponse.class, camelResultBody);
    assertEquals(camelResultBody.getParentPID(), parentPid);
    assertEquals(camelResultBody.getCorrelationId(), correlationId);

    assertMockEndpointsSatisfied();

}

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  www .jav  a2s.c o m
public static HttpResponse callPostUrlPure(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
    HttpPost request = new HttpPost(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 'POST' 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;
}

From source file:MainFrame.HttpCommunicator.java

public boolean removeLessons(JSONObject jsObj) throws MalformedURLException, IOException {
    String response = null;/*from  w  ww . j  a v a  2  s .  c  o  m*/
    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));
        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    } else {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");

        StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apiDeskViewer.removeLesson", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    }

    if (response.equals(new String("\"success\"")))
        return true;
    else
        return false;
}

From source file:org.graphwalker.restful.RestTest.java

@Override
public void e_Load() {
    HttpPost request = new HttpPost("http://localhost:9191/graphwalker/load");
    FileEntity fileEntity = new FileEntity(ResourceUtils.getResourceAsFile("gw3/UC01.json"),
            ContentType.TEXT_PLAIN);
    request.setEntity(fileEntity);/*from  w  w  w  .ja va  2  s. c  om*/
    response = httpExecute(request);
}

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

@Test
public void nonBlockingFlowRef() throws Exception {
    Response response = Request
            .Post(String.format("http://localhost:%s/%s", port.getNumber(), "nonBlockingFlowRefBasic"))
            .connectTimeout(RECEIVE_TIMEOUT).bodyString(TEST_MESSAGE, ContentType.TEXT_PLAIN).execute();
    HttpResponse httpResponse = response.returnResponse();
    assertThat(httpResponse.getStatusLine().getStatusCode(), is(200));
    assertThat(IOUtils.toString(httpResponse.getEntity().getContent()), is(TEST_MESSAGE));

    SensingNullRequestResponseMessageProcessor flow1RequestResponseProcessor = muleContext.getRegistry()
            .lookupObject(FLOW1_SENSING_PROCESSOR_NAME);
    SensingNullRequestResponseMessageProcessor flow2RequestResponseProcessor = muleContext.getRegistry()
            .lookupObject(FLOW2_SENSING_PROCESSOR_NAME);
    assertThat(flow1RequestResponseProcessor.requestThread,
            not(equalTo(flow1RequestResponseProcessor.responseThread)));
    assertThat(flow2RequestResponseProcessor.requestThread,
            not(equalTo(flow2RequestResponseProcessor.responseThread)));
}

From source file:tools.devnull.boteco.client.rest.impl.DefaultRestConfiguration.java

public ContentTypeSelector with(Object object) {
    return new ContentTypeSelector() {
        @Override/*www.jav  a2s.co  m*/
        public RestConfiguration asJson() {
            return as(gsonBuilder.create().toJson(object), ContentType.APPLICATION_JSON);
        }

        @Override
        public RestConfiguration asPlainText() {
            return as(object.toString(), ContentType.TEXT_PLAIN);
        }

        @Override
        public RestConfiguration asFormUrlEncoded() {
            List<BasicNameValuePair> pairs;
            if (object instanceof Map) {
                pairs = ((Set<Map.Entry>) ((Map) object).entrySet()).stream().map(
                        entry -> new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()))
                        .collect(Collectors.toList());
            } else {
                pairs = elements().in(object).stream()
                        .map(el -> new BasicNameValuePair(el.name(), el.value().toString()))
                        .collect(Collectors.toList());
            }
            return setEntity(new UrlEncodedFormEntity(pairs, Charset.defaultCharset()));
        }

        private RestConfiguration as(String content, ContentType contentType) {
            return setEntity(new StringEntity(content, contentType));
        }

        private RestConfiguration setEntity(HttpEntity entity) {
            if (DefaultRestConfiguration.this.request instanceof HttpEntityEnclosingRequest) {
                ((HttpEntityEnclosingRequest) DefaultRestConfiguration.this.request).setEntity(entity);
            } else {
                throw new BotException("This request doesn't allow entities");
            }
            return DefaultRestConfiguration.this;
        }

    };
}