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:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java

/**
 * Upload a sample datatset from resources
 * /* w  w w.  ja  va 2  s.c o  m*/
 * @param datasetName   Name for the dataset
 * @param version       Version for the dataset
 * @param resourcePath  Relative path the CSV file in resources
 * @return              Response from the backend
 * @throws              MLHttpClientException 
 */
public CloseableHttpResponse uploadDatasetFromCSV(String datasetName, String version, String resourcePath)
        throws MLHttpClientException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/datasets/");
        httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("description",
                new StringBody("Sample dataset for Testing", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("sourceType", new StringBody("file", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("destination", new StringBody("file", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("containsHeader", new StringBody("true", ContentType.TEXT_PLAIN));

        if (datasetName != null) {
            multipartEntityBuilder.addPart("datasetName", new StringBody(datasetName, ContentType.TEXT_PLAIN));
        }
        if (version != null) {
            multipartEntityBuilder.addPart("version", new StringBody(version, ContentType.TEXT_PLAIN));
        }
        if (resourcePath != null) {
            File file = new File(getResourceAbsolutePath(resourcePath));
            multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM,
                    "IndiansDiabetes.csv");
        }
        httpPost.setEntity(multipartEntityBuilder.build());
        return httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to upload dataset from csv " + resourcePath, e);
    }
}

From source file:com.code42.demo.RestInvoker.java

/**
 * Execuites CODE42 api/File to upload a single file into the root directory of the specified planUid
 * If the file is succesfully uploaded the response code of 204 is returned.
 * //www  .j  a  v a  2s . c  o m
 * @param planUid 
 * @param sessionId
 * @param file
 * @return HTTP Response code as int
 * @throws Exception
 */

public int postFileAPI(String planUid, String sessionId, File file) throws Exception {

    int respCode;
    HttpClientBuilder hcs;
    CloseableHttpClient httpClient;
    hcs = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);
    if (ssl) {
        hcs.setSSLSocketFactory(sslsf);
    }
    httpClient = hcs.build();
    StringBody planId = new StringBody(planUid, ContentType.TEXT_PLAIN);
    StringBody sId = new StringBody(sessionId, ContentType.TEXT_PLAIN);

    try {
        HttpPost httpPost = new HttpPost(ePoint + "/api/File");
        FileBody fb = new FileBody(file);
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", fb).addPart("planUid", planId)
                .addPart("sessionId", sId).build();
        httpPost.setEntity(reqEntity);
        CloseableHttpResponse resp = httpClient.execute(httpPost);
        try {
            m_log.info("executing " + httpPost.getRequestLine());
            m_log.info(resp.getStatusLine());
            respCode = resp.getStatusLine().getStatusCode();
        } finally {
            resp.close();
        }

    } finally {
        httpClient.close();
    }

    return respCode;
}

From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java

private static HttpEntity getAsEntity(final HttpParameter[] params) throws UnsupportedEncodingException {
    if (params == null)
        return null;
    if (!HttpParameter.containsFile(params))
        return new HttpParameterFormEntity(params);
    final MultipartEntityBuilder me = MultipartEntityBuilder.create();
    for (final HttpParameter param : params) {
        if (param.isFile()) {
            final ContentType contentType = ContentType.create(param.getContentType());
            final ContentBody body;
            if (param.getFile() != null) {
                body = new FileBody(param.getFile(), ContentType.create(param.getContentType()));
            } else {
                body = new InputStreamBody(param.getFileBody(), contentType, param.getFileName());
            }/*from w  ww .  j  a  v a  2s.  c  om*/
            me.addPart(param.getName(), body);
        } else {
            final ContentType contentType = ContentType.TEXT_PLAIN.withCharset(Consts.UTF_8);
            final ContentBody body = new StringBody(param.getValue(), contentType);
            me.addPart(param.getName(), body);
        }
    }
    return me.build();
}

From source file:MainFrame.HttpCommunicator.java

public boolean setPassword(String password, String group) throws IOException {
    String response = null;/*from   w  ww .jav a 2s  . c  o  m*/
    String hashPassword = md5Custom(password);
    JSONObject jsObj = new JSONObject();
    jsObj.put("group", group);
    jsObj.put("newHash", hashPassword);

    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.updateGroupAccess", 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.mule.test.construct.FlowRefTestCase.java

@Test
public void nonBlockingFlowRefToSyncFlow() throws Exception {
    Response response = Request
            .Post(String.format("http://localhost:%s/%s", port.getNumber(), "nonBlockingFlowRefToSyncFlow"))
            .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(TO_SYNC_FLOW1_SENSING_PROCESSOR_NAME);
    SensingNullRequestResponseMessageProcessor flow2RequestResponseProcessor = muleContext.getRegistry()
            .lookupObject(TO_SYNC_FLOW2_SENSING_PROCESSOR_NAME);
    assertThat(flow1RequestResponseProcessor.requestThread,
            equalTo(flow1RequestResponseProcessor.responseThread));
    assertThat(flow2RequestResponseProcessor.requestThread,
            equalTo(flow2RequestResponseProcessor.responseThread));
}

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

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

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

    final String resourceWatchFolder = config.getProperty(TPUStatics.RESOURCE_WATCHFOLDER_IDENTIFIER);
    final String completeFileName = resourceWatchFolder + File.separatorChar + filename;

    try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {

        final HttpPut httpPut = new HttpPut(
                engineDswarmAPI + DswarmBackendStatics.RESOURCES_ENDPOINT + APIStatics.SLASH + resourceUUID);

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

        final HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart(DswarmBackendStatics.NAME_IDENTIFIER, stringBodyForName)
                .addPart(DswarmBackendStatics.DESCRIPTION_IDENTIFIER, stringBodyForDescription)
                .addPart(FILE_IDENTIFIER, fileBody).build();

        httpPut.setEntity(reqEntity);

        LOG.info(String.format("[%s] request : %s", serviceName, httpPut.getRequestLine()));

        try (final CloseableHttpResponse httpResponse = httpclient.execute(httpPut)) {

            final int statusCode = httpResponse.getStatusLine().getStatusCode();

            final String message = String.format("[%s] %d : %s", serviceName, statusCode,
                    httpResponse.getStatusLine().getReasonPhrase());

            final String response = TPUUtil.getResponseMessage(httpResponse);

            switch (statusCode) {

            case 200: {

                LOG.info(message);

                LOG.debug(String.format("[%s] responseJson : %s", serviceName, response));

                return response;
            }
            default: {

                LOG.error(message);

                throw new Exception("something went wrong at data model export: " + message + " " + response);
            }
            }
        }
    }
}

From source file:tech.sirwellington.alchemy.http.HttpVerbImplTest.java

@Test
public void testExecuteWhenEntityIsText() {
    String text = one(alphabeticString());
    entity = new StringEntity(text, ContentType.TEXT_PLAIN);
    when(apacheResponse.getEntity()).thenReturn(entity);

    HttpResponse result = instance.execute(apacheClient, request);
    assertThat(result, notNullValue());//from  ww w. ja  v a2  s  .  c  om
    assertThat(result.bodyAsString(), is(text));
    JsonElement asJSON = result.body();
    assertThat(asJSON.isJsonPrimitive(), is(true));
    assertThat(asJSON.getAsJsonPrimitive().isString(), is(true));
}

From source file:com.github.restdriver.clientdriver.integration.ClientDriverSuccessTest.java

@Test
public void testJettyWorkingWithPostBody() throws Exception {

    String baseUrl = driver.getBaseUrl();
    driver.addExpectation(/*from w ww  .ja v a 2 s. c  o m*/
            onRequestTo("/blah2").withMethod(Method.PUT).withBody("Jack your body!", "text/plain"),
            giveResponse("___", "text/plain").withStatus(501));

    HttpClient client = new DefaultHttpClient();
    HttpPut putter = new HttpPut(baseUrl + "/blah2");
    putter.setEntity(new StringEntity("Jack your body!", ContentType.TEXT_PLAIN));
    HttpResponse response = client.execute(putter);

    assertThat(response.getStatusLine().getStatusCode(), is(501));
    assertThat(IOUtils.toString(response.getEntity().getContent()), equalTo("___"));

}

From source file:com.intuit.karate.http.apache.ApacheHttpClient.java

@Override
protected HttpEntity getEntity(List<MultiPartItem> items, String mediaType) {
    boolean hasNullName = false;
    for (MultiPartItem item : items) {
        if (item.getName() == null) {
            hasNullName = true;//from   w w w  .  ja  v a2  s.com
            break;
        }
    }
    if (hasNullName) { // multipart/related
        String boundary = createBoundary();
        String text = getAsStringEntity(items, boundary);
        ContentType ct = ContentType.create(mediaType)
                .withParameters(new BasicNameValuePair("boundary", boundary));
        return new StringEntity(text, ct);
    } else {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                .setContentType(ContentType.create(mediaType));
        for (MultiPartItem item : items) {
            if (item.getValue() == null || item.getValue().isNull()) {
                logger.warn("ignoring null multipart value for key: {}", item.getName());
                continue;
            }
            String name = item.getName();
            ScriptValue sv = item.getValue();
            if (name == null) {
                // builder.addPart(bodyPart);
            } else {
                FormBodyPartBuilder formBuilder = FormBodyPartBuilder.create().setName(name);
                ContentBody contentBody;
                switch (sv.getType()) {
                case INPUT_STREAM:
                    InputStream is = (InputStream) sv.getValue();
                    contentBody = new InputStreamBody(is, ContentType.APPLICATION_OCTET_STREAM, name);
                    break;
                case XML:
                    contentBody = new StringBody(sv.getAsString(), ContentType.APPLICATION_XML);
                    break;
                case JSON:
                    contentBody = new StringBody(sv.getAsString(), ContentType.APPLICATION_JSON);
                    break;
                default:
                    contentBody = new StringBody(sv.getAsString(), ContentType.TEXT_PLAIN);
                }
                formBuilder = formBuilder.setBody(contentBody);
                builder = builder.addPart(formBuilder.build());
            }
        }
        return builder.build();
    }
}