Example usage for org.apache.http.entity.mime.content StringBody StringBody

List of usage examples for org.apache.http.entity.mime.content StringBody StringBody

Introduction

In this page you can find the example usage for org.apache.http.entity.mime.content StringBody StringBody.

Prototype

public StringBody(final String text, Charset charset) throws UnsupportedEncodingException 

Source Link

Usage

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.jboss.as.test.integration.management.http.HttpGenericOperationUnitTestCase.java

private ContentBody getOperationBody(final ModelNode operation, final boolean encoded) throws IOException {
    if (encoded) {
        return new DMRContentEncodedBody(operation);
    } else {//from  w ww .j  a  v a 2 s  .c  o m
        return new StringBody(operation.toJSONString(true), ContentType.APPLICATION_JSON);
    }
}

From source file:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java

/**
 * Upload a sample datatset from resources
 * /*from  ww  w  .ja  va  2s  . c  om*/
 * @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:org.xmetdb.rest.protocol.attachments.CallableAttachmentImporter.java

protected HttpEntity createPOSTEntity(DBAttachment attachment) throws Exception {
    Charset utf8 = Charset.forName("UTF-8");

    if ("text/uri-list".equals(attachment.getFormat())) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("title", attachment.getTitle()));
        formparams.add(new BasicNameValuePair("dataset_uri", attachment.getDescription()));
        formparams.add(new BasicNameValuePair("folder",
                attachment_type.substrate.equals(attachment.getType()) ? "substrate" : "product"));
        return new UrlEncodedFormEntity(formparams, "UTF-8");
    } else {/*from  w  w w  . ja v a2 s .com*/
        if (attachment.getResourceURL() == null)
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Attachment resource URL is null! ");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, utf8);
        entity.addPart("title", new StringBody(attachment.getTitle(), utf8));
        entity.addPart("seeAlso", new StringBody(attachment.getDescription(), utf8));
        entity.addPart("license", new StringBody("XMETDB", utf8));
        entity.addPart("file", new FileBody(new File(attachment.getResourceURL().toURI())));
        return entity;
    }
    //match, seeAlso, license
}

From source file:MainFrame.HttpCommunicator.java

public boolean setPassword(String password, String group) throws IOException {
    String response = null;//from   w w w . j  a v  a 2 s .  c  om
    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: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.
 * /*from   ww  w  .  ja v a 2 s. c om*/
 * @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:org.bonitasoft.engine.api.HTTPServerAPI.java

final HttpEntity buildEntity(final Map<String, Serializable> options, final List<String> classNameParameters,
        final Object[] parametersValues, final XStream xstream)
        throws UnsupportedEncodingException, IOException {
    final HttpEntity httpEntity;
    /*/*  w w  w  .j  av  a  2s  . com*/
     * if we have a business archive we use multipart to have the business archive attached as a binary content (it can be big)
     */
    if (classNameParameters.contains(BusinessArchive.class.getName())
            || classNameParameters.contains(byte[].class.getName())) {
        final List<Object> bytearrayParameters = new ArrayList<Object>();
        final MultipartEntity entity = new MultipartEntity(null, null, UTF8);
        entity.addPart(OPTIONS, new StringBody(toXML(options, xstream), UTF8));
        entity.addPart(CLASS_NAME_PARAMETERS, new StringBody(toXML(classNameParameters, xstream), UTF8));
        for (int i = 0; i < parametersValues.length; i++) {
            final Object parameterValue = parametersValues[i];
            if (parameterValue instanceof BusinessArchive || parameterValue instanceof byte[]) {
                parametersValues[i] = BYTE_ARRAY;
                bytearrayParameters.add(parameterValue);
            }
        }
        entity.addPart(PARAMETERS_VALUES, new StringBody(toXML(parametersValues, xstream), UTF8));
        int i = 0;
        for (final Object object : bytearrayParameters) {
            entity.addPart(BINARY_PARAMETER + i, new ByteArrayBody(serialize(object), BINARY_PARAMETER + i));
            i++;
        }
        httpEntity = entity;
    } else {
        final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(OPTIONS, toXML(options, xstream)));
        nvps.add(new BasicNameValuePair(CLASS_NAME_PARAMETERS, toXML(classNameParameters, xstream)));
        nvps.add(new BasicNameValuePair(PARAMETERS_VALUES, toXML(parametersValues, xstream)));
        httpEntity = new UrlEncodedFormEntity(nvps, UTF_8);
    }
    return httpEntity;
}