Example usage for org.apache.http.entity.mime MultipartEntityBuilder addPart

List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder addPart

Introduction

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

Prototype

public MultipartEntityBuilder addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

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

public void changeAppIcon(String applicationHash, File appIcon) throws AppCloudIntegrationTestException {
    HttpClient httpclient = null;/*  ww w.  j a  v  a  2 s. co m*/
    org.apache.http.HttpResponse response = null;
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
        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_CHANGE_ICON, new FileBody(appIcon));
        builder.addPart(PARAM_NAME_ACTION, new StringBody(CHANGE_APP_ICON_ACTION, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_HASH_ID,
                new StringBody(applicationHash, 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("Update app icon failed " + result);
        }
    } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) {
        // In most of the cases, even though connection is timed out, actual activity is completed.
        // And this will be asserted so if it failed due to a valid case, it will be captured.
        log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1);
    } catch (IOException e) {
        log.error("Failed to invoke app icon update API.", e);
        throw new AppCloudIntegrationTestException("Failed to invoke app icon update API.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(httpclient);
    }
}

From source file:cn.vlabs.duckling.vwb.service.ddl.RestClient.java

private HttpEntity buildMultiPartForm(String dataFieldName, String filename, InputStream stream,
        String... params) {//from   w w w.  j  a  va  2s  .  c om
    MultipartEntityBuilder builder = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody(dataFieldName, stream, ContentType.DEFAULT_BINARY, filename);

    if (params != null) {
        for (int i = 0; i < params.length / 2; i++) {
            StringBody contentBody = new StringBody(params[i * 2 + 1], DEFAULT_CONTENT_TYPE);
            builder.addPart(params[i * 2], contentBody);
        }
    }

    HttpEntity reqEntity = builder.setCharset(DEFAULT_CHARSET).build();
    return reqEntity;
}

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 w  ww  . j a va 2  s .co  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.modeshape.web.jcr.rest.AbstractRestTest.java

protected Response doPostMultiPart(String filePath, String elementName, String url, String contentType) {
    try {/*from w w  w  .  ja  va  2s.  c  om*/

        if (StringUtil.isBlank(contentType)) {
            contentType = MediaType.APPLICATION_OCTET_STREAM;
        }

        url = URL_ENCODER.encode(RestHelper.urlFrom(getServerContext(), url));

        HttpPost post = new HttpPost(url);
        post.setHeader("Accept", MediaType.APPLICATION_JSON);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IoUtil.write(fileStream(filePath), baos);
        entityBuilder.addPart(elementName, new ByteArrayBody(baos.toByteArray(), "test_file"));
        post.setEntity(entityBuilder.build());

        return new Response(post);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
        return null;
    }
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlFileInputTest.java

/**
 * Test HttpClient for uploading a file with non-ASCII name, if it works it means HttpClient has fixed its bug.
 *
 * Test for http://issues.apache.org/jira/browse/HTTPCLIENT-293,
 * which is related to http://sourceforge.net/p/htmlunit/bugs/535/
 *
 * @throws Exception if the test fails/*from  www. j a va  2 s .  co  m*/
 */
@Test
public void uploadFileWithNonASCIIName_HttpClient() throws Exception {
    final String filename = "\u6A94\u6848\uD30C\uC77C\u30D5\u30A1\u30A4\u30EB\u0645\u0644\u0641.txt";
    final String path = getClass().getClassLoader().getResource(filename).toExternalForm();
    final File file = new File(new URI(path));
    assertTrue(file.exists());

    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/upload2", Upload2Servlet.class);

    startWebServer("./", null, servlets);
    final HttpPost filePost = new HttpPost("http://localhost:" + PORT + "/upload2");

    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(Charset.forName("UTF-8"));
    builder.addPart("myInput", new FileBody(file, ContentType.APPLICATION_OCTET_STREAM));

    filePost.setEntity(builder.build());

    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    final HttpResponse httpResponse = clientBuilder.build().execute(filePost);

    InputStream content = null;
    try {
        content = httpResponse.getEntity().getContent();
        final String response = new String(IOUtils.toByteArray(content));
        //this is the value with ASCII encoding
        assertFalse("3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 2E 74 78 74 <br>myInput".equals(response));
    } finally {
        IOUtils.closeQuietly(content);
    }
}

From source file:net.ychron.unirestinst.request.body.MultipartBody.java

public HttpEntity getEntity() {
    if (hasFile) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if (mode != null) {
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        }/*from ww  w  .j av a  2s.c o  m*/
        for (String key : parameters.keySet()) {
            List<Object> value = parameters.get(key);
            ContentType contentType = contentTypes.get(key);
            for (Object cur : value) {
                if (cur instanceof File) {
                    File file = (File) cur;
                    builder.addPart(key, new FileBody(file, contentType, file.getName()));
                } else if (cur instanceof InputStreamBody) {
                    builder.addPart(key, (ContentBody) cur);
                } else if (cur instanceof ByteArrayBody) {
                    builder.addPart(key, (ContentBody) cur);
                } else {
                    builder.addPart(key, new StringBody(cur.toString(), contentType));
                }
            }
        }
        return builder.build();
    } else {
        try {
            return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:aajavafx.VisitorController.java

@FXML
private void handleSave(ActionEvent event) {
    if (imageFile != null) {

        String visitorId = visitorIDField.getText();
        visitorIDField.clear();/*from   ww w.ja v a 2  s . c o m*/
        String firstName = firstNameField.getText();
        firstNameField.clear();
        String lastName = lastNameField.getText();
        lastNameField.clear();
        String email = emailField.getText();
        emailField.clear();
        String phoneNumber = phoneNumberField.getText();
        phoneNumberField.clear();
        Integer companyId = getCompanyIDFromName(companyBox.getValue().toString());
        try {
            Gson gson = new Gson();
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpEntityEnclosingRequestBase HttpEntity = null; //this is the superclass for post, put, get, etc
            if (visitorIDField.isEditable()) { //then we are posting a new record
                HttpEntity = new HttpPost(VisitorsRootURL); //so make a http post object
            } else { //we are editing a record 
                HttpEntity = new HttpPut(VisitorsRootURL); //so make a http put object
            }
            Company company = getCompany(companyId);
            Visitors visitor = new Visitors(visitorId, firstName, lastName, email, phoneNumber, company);

            String jsonString = new String(gson.toJson(visitor));
            System.out.println("json string: " + jsonString);
            StringEntity postString = new StringEntity(jsonString);

            HttpEntity.setEntity(postString);
            HttpEntity.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(HttpEntity);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 204) {
                System.out.println("New visitor posted successfully");
            } else {
                System.out.println("Server error: " + response.getStatusLine());
            }
            visitorIDField.setEditable(false);
            firstNameField.setEditable(false);
            lastNameField.setEditable(false);
            emailField.setEditable(false);
            phoneNumberField.setEditable(false);
            companyBox.setEditable(false);
            visitorIDField.clear();
            firstNameField.clear();
            lastNameField.clear();
            emailField.clear();
            tableVisitors.setItems(getVisitors());
        } catch (UnsupportedEncodingException ex) {
            System.out.println(ex);
        } catch (IOException e) {
            System.out.println(e);
        } catch (JSONException je) {
            System.out.println("JSON error: " + je);
        }

        FileInputStream fis = null;
        try {

            fis = new FileInputStream(imageFile);
            HttpClient httpClient = HttpClientBuilder.create().build();
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            FileBody fileBody = new FileBody(new File(imageFile.getName())); //image should be a String
            builder.addPart("file", new InputStreamBody(fis, imageFile.getName()));
            //builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // server back-end URL
            HttpPost httppost = new HttpPost(postHTML);
            //MultipartEntity entity = new MultipartEntity();
            // set the file input stream and file name as arguments
            //entity.addPart("file", new InputStreamBody(fis, inFile.getName()));
            HttpEntity entity = builder.build();
            httppost.setEntity(entity);
            // execute the request
            HttpResponse response = httpClient.execute(httppost);

            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity responseEntity = response.getEntity();
            String responseString = EntityUtils.toString(responseEntity, "UTF-8");

            System.out.println("[" + statusCode + "] " + responseString);

        } catch (ClientProtocolException e) {
            System.err.println("Unable to make connection");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Unable to read file");
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
            }
        }

    } else {
        errorLabel.setText("Record Not Saved: Please attach a photo for this visitor");
        errorLabel.setVisible(true);
    }

}

From source file:com.liferay.sync.engine.session.Session.java

private HttpEntity _getEntity(Map<String, Object> parameters) throws Exception {

    Path deltaFilePath = (Path) parameters.get("deltaFilePath");
    Path filePath = (Path) parameters.get("filePath");
    String zipFileIds = (String) parameters.get("zipFileIds");
    Path zipFilePath = (Path) parameters.get("zipFilePath");

    MultipartEntityBuilder multipartEntityBuilder = _getMultipartEntityBuilder(parameters);

    if (deltaFilePath != null) {
        multipartEntityBuilder.addPart("deltaFile", _getFileBody(deltaFilePath,
                (String) parameters.get("mimeType"), (String) parameters.get("title")));
    } else if (filePath != null) {
        multipartEntityBuilder.addPart("file",
                _getFileBody(filePath, (String) parameters.get("mimeType"), (String) parameters.get("title")));
    } else if (zipFileIds != null) {
        return _getURLEncodedFormEntity(parameters);
    } else if (zipFilePath != null) {
        multipartEntityBuilder.addPart("zipFile",
                _getFileBody(zipFilePath, "application/zip", String.valueOf(zipFilePath.getFileName())));
    }//from   w  ww . j  a v  a2 s  .  co m

    return multipartEntityBuilder.build();
}

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

/**
 * @throws MLHttpClientException//from w  ww  .  j a  va2 s . c om
 */
public CloseableHttpResponse predictFromCSV(long modelId, String resourcePath) throws MLHttpClientException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/models/predict");
        httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("modelId", new StringBody(modelId + "", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN));

        if (resourcePath != null) {
            File file = new File(getResourceAbsolutePath(resourcePath));
            multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM,
                    "IndiansDiabetesPredict.csv");
        }
        httpPost.setEntity(multipartEntityBuilder.build());
        return httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to predict from csv " + resourcePath, e);
    }
}