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:mesquite.zephyr.RAxMLRunnerCIPRes.RAxMLRunnerCIPRes.java

public void prepareRunnerObject(Object obj) {
    if (obj instanceof MultipartEntityBuilder) {
        MultipartEntityBuilder builder = (MultipartEntityBuilder) obj;
        final File file = new File(externalProcRunner.getInputFilePath(DATAFILENUMBER));
        FileBody fb = new FileBody(file);
        builder.addPart("input.infile_", fb);
    }/*from   w w w .  j  av a 2s  .  c o  m*/
}

From source file:org.guvnor.ala.wildfly.access.WildflyClient.java

public int deploy(File file) throws WildflyClientException {

    // the digest auth backend
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(host, managementPort),
            new UsernamePasswordCredentials(user, password));

    CloseableHttpClient httpclient = custom().setDefaultCredentialsProvider(credsProvider).build();

    HttpPost post = new HttpPost("http://" + host + ":" + managementPort + "/management-upload");

    post.addHeader("X-Management-Client-Name", "HAL");

    // the file to be uploaded
    FileBody fileBody = new FileBody(file);

    // the DMR operation
    ModelNode operation = new ModelNode();
    operation.get("address").add("deployment", file.getName());
    operation.get("operation").set("add");
    operation.get("runtime-name").set(file.getName());
    operation.get("enabled").set(true);
    operation.get("content").add().get("input-stream-index").set(0); // point to the multipart index used

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {//from   ww w .  j  ava 2 s.com
        operation.writeBase64(bout);
    } catch (IOException ex) {
        getLogger(WildflyClient.class.getName()).log(SEVERE, null, ex);
    }

    // the multipart
    MultipartEntityBuilder builder = create();
    builder.setMode(BROWSER_COMPATIBLE);
    builder.addPart("uploadFormElement", fileBody);
    builder.addPart("operation",
            new ByteArrayBody(bout.toByteArray(), create("application/dmr-encoded"), "blob"));
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try {
        HttpResponse response = httpclient.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new WildflyClientException("Error Deploying App Status Code: " + statusCode);
        }
        return statusCode;
    } catch (IOException ex) {
        LOG.error("Error Deploying App : " + ex.getMessage(), ex);
        throw new WildflyClientException("Error Deploying App : " + ex.getMessage(), ex);
    }
}

From source file:ua.pp.msk.maven.MavenHttpClient.java

private int execute(File file) throws ArtifactPromotingException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    int status = -1;
    try {//from   w  w  w. j  a va 2 s. c o m
        getLog().debug("Connecting to URL: " + url);
        HttpPost post = new HttpPost(url);

        post.setHeader("User-Agent", userAgent);

        if (username != null && username.length() != 0 && password != null) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
            post.addHeader(new BasicScheme().authenticate(creds, post, null));
        }
        if (file == null) {
            if (!urlParams.isEmpty()) {
                post.setEntity(new UrlEncodedFormEntity(urlParams));
            }
        } else {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();

            if (!urlParams.isEmpty()) {
                for (NameValuePair nvp : urlParams) {
                    builder.addPart(nvp.getName(),
                            new StringBody(nvp.getValue(), ContentType.MULTIPART_FORM_DATA));
                }
            }
            FileBody fb = new FileBody(file);
            // Not used because of form submission
            // builder.addBinaryBody("file", file,
            // ContentType.DEFAULT_BINARY, file.getName());
            builder.addPart("file", fb);
            HttpEntity sendEntity = builder.build();
            post.setEntity(sendEntity);
        }

        CloseableHttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        StatusLine statusLine = response.getStatusLine();
        status = statusLine.getStatusCode();
        getLog().info(
                "Response status code: " + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        // Perhaps I need to parse html
        // String html = EntityUtils.toString(entity);

    } catch (AuthenticationException ex) {
        throw new ArtifactPromotingException(ex);
    } catch (UnsupportedEncodingException ex) {
        throw new ArtifactPromotingException(ex);
    } catch (IOException ex) {
        throw new ArtifactPromotingException(ex);
    } finally {
        try {
            client.close();
        } catch (IOException ex) {
            throw new ArtifactPromotingException("Cannot close http client", ex);
        }
    }
    return status;
}

From source file:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java

public String doPostMultiData(String url, String method, MobileApplicationBean mobileApplicationBean,
        String cookie) throws IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("Cookie", "JSESSIONID=" + cookie);
    MultipartEntityBuilder reqEntity;
    if (method.equals("upload")) {
        reqEntity = MultipartEntityBuilder.create();
        FileBody fileBody = new FileBody(new File(mobileApplicationBean.getApkFile()));
        reqEntity.addPart("file", fileBody);
    } else {// w w  w.j  av  a2  s . c o m
        reqEntity = MultipartEntityBuilder.create();
        reqEntity.addPart("version",
                new StringBody(mobileApplicationBean.getVersion(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("provider",
                new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("markettype",
                new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("platform",
                new StringBody(mobileApplicationBean.getPlatform(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("name",
                new StringBody(mobileApplicationBean.getName(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("description",
                new StringBody(mobileApplicationBean.getDescription(), ContentType.MULTIPART_FORM_DATA));
        FileBody bannerImageFile = new FileBody(new File(mobileApplicationBean.getBannerFilePath()));
        reqEntity.addPart("bannerFile", bannerImageFile);
        FileBody iconImageFile = new FileBody(new File(mobileApplicationBean.getIconFile()));
        reqEntity.addPart("iconFile", iconImageFile);
        FileBody screenShot1 = new FileBody(new File(mobileApplicationBean.getScreenShot1File()));
        reqEntity.addPart("screenshot1File", screenShot1);
        FileBody screenShot2 = new FileBody(new File(mobileApplicationBean.getScreenShot2File()));
        reqEntity.addPart("screenshot2File", screenShot2);
        FileBody screenShot3 = new FileBody(new File(mobileApplicationBean.getScreenShot3File()));
        reqEntity.addPart("screenshot3File", screenShot3);
        reqEntity.addPart("addNewAssetButton", new StringBody("Submit", ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("mobileapp",
                new StringBody(mobileApplicationBean.getMobileapp(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("sso_ssoProvider",
                new StringBody(mobileApplicationBean.getSso_ssoProvider(), ContentType.MULTIPART_FORM_DATA));
        reqEntity.addPart("appmeta",
                new StringBody(mobileApplicationBean.getAppmeta(), ContentType.MULTIPART_FORM_DATA));
    }
    final HttpEntity entity = reqEntity.build();
    httpPost.setEntity(entity);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = httpClient.execute(httpPost, responseHandler);
    if (!method.equals("upload")) {
        String id_part = responseBody.split(",")[2].split(":")[1];
        return id_part.substring(2, (id_part.length() - 2));
    }
    return responseBody;
}

From source file:org.jboss.as.test.integration.management.http.HttpGenericOperationUnitTestCase.java

/**
 * Execute the post request.//from   w w w.ja v a  2  s . c om
 *
 * @param operation the operation body
 * @param encoded   whether it should send the dmr encoded header
 * @param streams   the optional input streams
 * @return the response from the server
 * @throws IOException
 */
private ModelNode executePost(final ContentBody operation, final boolean encoded,
        final List<ContentBody> streams) throws IOException {
    final HttpPost post = new HttpPost(uri);
    post.setHeader("X-Management-Client-Name", "test-client");
    final MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addPart("operation",
            operation);
    for (ContentBody stream : streams) {
        entityBuilder.addPart("input-streams", stream);
    }
    post.setEntity(entityBuilder.build());
    return parseResponse(httpClient.execute(post), encoded);
}

From source file:org.brutusin.rpc.client.http.HttpEndpoint.java

private CloseableHttpResponse doExec(String serviceId, JsonNode input, HttpMethod httpMethod,
        final ProgressCallback progressCallback) throws IOException {
    RpcRequest request = new RpcRequest();
    request.setJsonrpc("2.0");
    request.setMethod(serviceId);/* w w w  .  jav a2  s  . com*/
    request.setParams(input);
    final String payload = JsonCodec.getInstance().transform(request);
    final HttpUriRequest req;
    if (httpMethod == HttpMethod.GET) {
        String urlparam = URLEncoder.encode(payload, "UTF-8");
        req = new HttpGet(this.endpoint + "?jsonrpc=" + urlparam);
    } else {
        HttpEntityEnclosingRequestBase reqBase;
        if (httpMethod == HttpMethod.POST) {
            reqBase = new HttpPost(this.endpoint);
        } else if (httpMethod == HttpMethod.PUT) {
            reqBase = new HttpPut(this.endpoint);
        } else {
            throw new AssertionError();
        }
        req = reqBase;
        HttpEntity entity;
        Map<String, InputStream> files = JsonCodec.getInstance().getStreams(input);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.STRICT);
        builder.addPart("jsonrpc", new StringBody(payload, ContentType.APPLICATION_JSON));
        if (files != null && !files.isEmpty()) {
            files = sortFiles(files);
            for (Map.Entry<String, InputStream> entrySet : files.entrySet()) {
                String key = entrySet.getKey();
                InputStream is = entrySet.getValue();
                if (is instanceof MetaDataInputStream) {
                    MetaDataInputStream mis = (MetaDataInputStream) is;
                    builder.addPart(key, new InputStreamBody(mis, mis.getName()));
                } else {
                    builder.addPart(key, new InputStreamBody(is, key));
                }
            }
        }
        entity = builder.build();
        if (progressCallback != null) {
            entity = new ProgressHttpEntityWrapper(entity, progressCallback);
        }
        reqBase.setEntity(entity);
    }
    HttpClientContext context = contexts.get();
    if (this.clientContextFactory != null && context == null) {
        context = clientContextFactory.create();
        contexts.set(context);
    }
    return this.httpClient.execute(req, context);
}

From source file:com.ibm.sbt.services.client.Request.java

/**
 * Method to retrieve the request body.//from w  w  w. j  a va2 s.c o m
 * @return The request body
 */
public Object getBody() {
    if (body != null) {
        return body;
    }
    if (!bodyParts.isEmpty()) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (BodyPart bodyPart : bodyParts) {
            builder.addPart(bodyPart.getName(), bodyPart.getData());
        }
        return builder.build();
    }
    return null;
}

From source file:org.apache.sling.scripting.sightly.it.SlingSpecificsSightlyIT.java

private void uploadFile(String fileName, String serverFileName, String url) throws IOException {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(launchpadURL + url);
    post.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    InputStreamBody inputStreamBody = new InputStreamBody(
            this.getClass().getClassLoader().getResourceAsStream(fileName), ContentType.TEXT_PLAIN, fileName);
    entityBuilder.addPart(serverFileName, inputStreamBody);
    post.setEntity(entityBuilder.build());
    httpClient.execute(post);//from ww  w.jav  a2 s.c o m
}

From source file:org.ops4j.pax.web.itest.base.HttpTestClient.java

public void testPostMultipart(String path, Map<String, Object> multipartContent, String expectedContent,
        int httpRC) throws IOException {
    HttpPost httppost = new HttpPost(path);

    httppost.addHeader("Accept-Language", "en-us;q=0.8,en;q=0.5");

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    for (Entry<String, Object> content : multipartContent.entrySet()) {
        if (content.getValue() instanceof String) {
            multipartEntityBuilder.addPart(content.getKey(),
                    new StringBody((String) content.getValue(), ContentType.TEXT_PLAIN));
        }//from   w  ww  .  j  av  a  2  s  .  co m
    }

    httppost.setEntity(multipartEntityBuilder.build());

    CloseableHttpResponse response = httpclient.execute(httppost, context);

    assertEquals("HttpResponseCode", httpRC, response.getStatusLine().getStatusCode());

    String responseBodyAsString = EntityUtils.toString(response.getEntity());
    if (expectedContent != null) {
        assertTrue("Content: " + responseBodyAsString, responseBodyAsString.contains(expectedContent));
    }
    response.close();
}

From source file:com.secdec.codedx.api.client.CodeDxClient.java

/**
 * Kicks off a CodeDx analysis run on a specified project
 *
 * @return A StartAnalysisResponse object
 * @param projectId The project ID/*  w w  w.  j a  va 2  s.c  o m*/
 * @param artifacts An array of streams to send over as analysis artifacts
 * @throws ClientProtocolException
 * @throws IOException
 * @throws CodeDxClientException
 *
 */
public StartAnalysisResponse startAnalysis(int projectId, InputStream[] artifacts)
        throws ClientProtocolException, IOException, CodeDxClientException {

    HttpPost postRequest = new HttpPost(url + "projects/" + projectId + "/analysis");
    postRequest.addHeader(KEY_HEADER, key);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    for (InputStream artifact : artifacts) {

        builder.addPart("file[]", new InputStreamBody(artifact, "file[]"));
    }

    HttpEntity entity = builder.build();

    postRequest.setEntity(entity);

    HttpResponse response = httpClient.execute(postRequest);

    int responseCode = response.getStatusLine().getStatusCode();

    if (responseCode != 202) {

        throw new CodeDxClientException(
                "Failed to start analysis.  " + IOUtils.toString(response.getEntity().getContent()),
                responseCode);
    }

    String data = IOUtils.toString(response.getEntity().getContent());

    return gson.<StartAnalysisResponse>fromJson(data, new TypeToken<StartAnalysisResponse>() {
    }.getType());
}