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

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

Introduction

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

Prototype

public MultipartEntityBuilder addBinaryBody(final String name, final InputStream stream,
            final ContentType contentType, final String filename) 

Source Link

Usage

From source file:SubmitResults.java

private File populateRequest(final Main parent, String formStatus, String filePath, HttpPost req,
        final String changeIdXSLT, ContentType ct, MultipartEntityBuilder entityBuilder,
        final String newIdent) {

    File ammendedFile = null;//  w  w w  .  j  av a  2 s  .co m

    final File instanceFile = new File(filePath);

    if (formStatus != null) {
        System.out.println("Setting form status in header: " + formStatus);
        req.setHeader("form_status", formStatus); // smap add form_status header
    } else {
        System.out.println("Form Status null");
    }

    if (newIdent != null) {
        // Transform the survey ID
        try {
            System.out.println("Transformaing Instance file: " + instanceFile);
            PipedInputStream in = new PipedInputStream();
            final PipedOutputStream outStream = new PipedOutputStream(in);
            new Thread(new Runnable() {
                public void run() {
                    try {
                        InputStream xslStream = new ByteArrayInputStream(changeIdXSLT.getBytes("UTF-8"));
                        Transformer transformer = TransformerFactory.newInstance()
                                .newTransformer(new StreamSource(xslStream));
                        StreamSource source = new StreamSource(instanceFile);
                        StreamResult out = new StreamResult(outStream);
                        transformer.setParameter("surveyId", newIdent);
                        transformer.transform(source, out);
                        outStream.close();
                    } catch (TransformerConfigurationException e1) {
                        parent.appendToStatus("Error changing ident: " + e1.toString());
                    } catch (TransformerFactoryConfigurationError e1) {
                        parent.appendToStatus("Error changing ident: " + e1.toString());
                    } catch (TransformerException e) {
                        parent.appendToStatus("Error changing ident: " + e.toString());
                    } catch (IOException e) {
                        parent.appendToStatus("Error changing ident: " + e.toString());
                    }
                }
            }).start();
            System.out.println("Saving stream to file");
            ammendedFile = saveStreamTemp(in);
        } catch (Exception e) {
            parent.appendToStatus("Error changing ident: " + e.toString());
        }
    }

    /*
     * Add submission file as file body, hence save to temporary file first
     */
    if (newIdent == null) {
        ct = ContentType.create("text/xml");
        entityBuilder.addBinaryBody("xml_submission_file", instanceFile, ct, instanceFile.getPath());
    } else {
        FileBody fb = new FileBody(ammendedFile);
        entityBuilder.addPart("xml_submission_file", fb);
    }

    parent.appendToStatus("Instance file path: " + instanceFile.getPath());

    /*
     *  find all files referenced by the survey
     *  Temporarily check to see if the parent directory is "uploadedSurveys". If it is
     *   then we will need to scan the submission file to get the list of attachments to 
     *   send. 
     *  Alternatively this is a newly submitted survey stored in its own directory just as
     *  surveys are stored on the phone.  We can then just add all the surveys that are in 
     *  the same directory as the submission file.
     */
    File[] allFiles = instanceFile.getParentFile().listFiles();

    // add media files ignoring invisible files and the submission file
    List<File> files = new ArrayList<File>();
    for (File f : allFiles) {
        String fileName = f.getName();
        if (!fileName.startsWith(".") && !fileName.equals(instanceFile.getName())) { // ignore invisible files and instance xml file    
            files.add(f);
        }
    }

    for (int j = 0; j < files.size(); j++) {

        File f = files.get(j);
        String fileName = f.getName();
        ct = ContentType.create(getContentType(parent, fileName));
        FileBody fba = new FileBody(f, ct, fileName);
        entityBuilder.addPart(fileName, fba);

    }

    req.setEntity(entityBuilder.build());

    return ammendedFile;
}

From source file:com.ibm.iotf.client.api.APIClient.java

/**
 * Create a draft schema definition/*  w w  w. ja v a 2s  .c  o  m*/
 * 
 * @param schemaFile File containing the schema file
 *      
 * @param schemaName String containing the schema name
 *      
 * @param schemaDescription String containing the description of schema
 * 
 * @param schemaType String containing the schema type (like for e.g. json-schema)
 * 
 * @return If successful, JsonObject response from Watson IoT Platform.
 * 
 * @throws IoTFCReSTException Failure in creating a draft schema definition
 */
public JsonObject addDraftSchemaDefinition(File schemaFile, String schemaName, String schemaDescription,
        String schemaType) throws IoTFCReSTException {
    final String METHOD = "addDraftSchemaDefinition";
    HttpResponse response = null;
    JsonElement jsonResponse = null;
    int code = 0;
    String method = "post";
    try {
        StringBuilder sb = new StringBuilder("https://");
        sb.append(orgId).append('.').append(this.domain).append(BASIC_API_V0002_URL).append("/draft/schemas/");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        builder.addBinaryBody("schemaFile", new FileInputStream(schemaFile),
                org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM, schemaFile.getName());

        builder.addTextBody("description", schemaDescription);
        builder.addTextBody("name", schemaName);

        URIBuilder uri = new URIBuilder(sb.toString());

        HttpPost post = new HttpPost(uri.build());

        byte[] encoding = Base64.encodeBase64(new String(authKey + ":" + authToken).getBytes());
        String encodedString = new String(encoding);

        post.setHeader("Authorization", "Basic " + encodedString);

        HttpClient client = HttpClientBuilder.create().useSystemProperties().setSslcontext(sslContext).build();
        HttpEntity multipart = builder.build();
        post.setEntity(multipart);

        response = client.execute(post);
        code = response.getStatusLine().getStatusCode();
        String result = this.readContent(response, METHOD);
        jsonResponse = new JsonParser().parse(result);
        if (code == 201 || code == 400 || code == 401 || code == 403 || code == 404 || code == 500) {
            if (code == 201) {
                //Success
                return jsonResponse.getAsJsonObject();
            } else {
                String reason = null;
                switch (code) {
                case 400:
                    reason = IoTFCReSTException.HTTP_ADD_SCHEMA_DEFINITION_ERR_400;
                    break;
                case 401:
                    reason = IoTFCReSTException.HTTP_ADD_SCHEMA_DEFINITION_ERR_401;
                    break;
                case 403:
                    reason = IoTFCReSTException.HTTP_ADD_SCHEMA_DEFINITION_ERR_403;
                    break;
                case 500:
                    reason = IoTFCReSTException.HTTP_ADD_SCHEMA_DEFINITION_ERR_500;
                    break;
                }
                throw new IoTFCReSTException(method, sb.toString(), null, code, reason, jsonResponse);
            }
        } else {
            throw new IoTFCReSTException(code, "Unexpected error", jsonResponse);
        }
    } catch (IoTFCReSTException e) {
        throw e;
    } catch (Exception e) {
        // This includes JsonSyntaxException
        IoTFCReSTException ex = new IoTFCReSTException(
                "Failure in creating a draft schema definition " + "::" + e.getMessage());
        ex.initCause(e);
        throw ex;
    }
}

From source file:org.flowable.app.service.editor.AppDefinitionPublishService.java

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {//w  ww .  j  a va  2 s  .c  o m
    String deployApiUrl = environment.getRequiredProperty("deployment.api.url");
    String basicAuthUser = environment.getRequiredProperty("idm.admin.user");
    String basicAuthPassword = environment.getRequiredProperty("idm.admin.password");

    if (deployApiUrl.endsWith("/") == false) {
        deployApiUrl = deployApiUrl.concat("/");
    }
    deployApiUrl = deployApiUrl
            .concat(String.format("repository/deployments?deploymentKey=%s&deploymentName=%s",
                    encode(deploymentKey), encode(deploymentName)));

    HttpPost httpPost = new HttpPost(deployApiUrl);
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(
            Base64.encodeBase64((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8")))));

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName);

    HttpEntity entity = entityBuilder.build();
    httpPost.setEntity(entity);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    SSLConnectionSocketFactory sslsf = null;
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        clientBuilder.setSSLSocketFactory(sslsf);
    } catch (Exception e) {
        logger.error("Could not configure SSL for http client", e);
        throw new InternalServerErrorException("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return;
        } else {
            logger.error("Invalid deploy result code: {}", response.getStatusLine());
            throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine());
        }
    } catch (IOException ioe) {
        logger.error("Error calling deploy endpoint", ioe);
        throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage());
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                logger.warn("Exception while closing http client", e);
            }
        }
    }
}

From source file:org.kohsuke.stapler.RequestImplTest.java

private byte[] generateMultipartData() throws IOException {
    MultipartEntityBuilder reqEntityBuilder = MultipartEntityBuilder.create();

    reqEntityBuilder.setBoundary("mpboundary");
    reqEntityBuilder.addBinaryBody("pomFile", new File("./pom.xml"), ContentType.TEXT_XML, "pom.xml");
    reqEntityBuilder.addTextBody("text1", "text1_val");
    reqEntityBuilder.addTextBody("text2", "text2_val");

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {/*from w  ww.  jav a2 s. co  m*/
        reqEntityBuilder.build().writeTo(outputStream);
        outputStream.flush();
        return outputStream.toByteArray();
    } finally {
        outputStream.close();
    }
}

From source file:org.rapidoid.http.HttpClient.java

public Future<byte[]> request(String verb, String uri, Map<String, String> headers, Map<String, String> data,
        Map<String, String> files, byte[] body, String contentType, Callback<byte[]> callback,
        boolean fullResponse) {

    headers = U.safe(headers);//from  w w w.j a va 2s  .  co m
    data = U.safe(data);
    files = U.safe(files);

    HttpRequestBase req;
    boolean canHaveBody = false;

    if ("GET".equalsIgnoreCase(verb)) {
        req = new HttpGet(uri);
    } else if ("DELETE".equalsIgnoreCase(verb)) {
        req = new HttpDelete(uri);
    } else if ("OPTIONS".equalsIgnoreCase(verb)) {
        req = new HttpOptions(uri);
    } else if ("HEAD".equalsIgnoreCase(verb)) {
        req = new HttpHead(uri);
    } else if ("TRACE".equalsIgnoreCase(verb)) {
        req = new HttpTrace(uri);
    } else if ("POST".equalsIgnoreCase(verb)) {
        req = new HttpPost(uri);
        canHaveBody = true;
    } else if ("PUT".equalsIgnoreCase(verb)) {
        req = new HttpPut(uri);
        canHaveBody = true;
    } else if ("PATCH".equalsIgnoreCase(verb)) {
        req = new HttpPatch(uri);
        canHaveBody = true;
    } else {
        throw U.illegalArg("Illegal HTTP verb: " + verb);
    }

    for (Entry<String, String> e : headers.entrySet()) {
        req.addHeader(e.getKey(), e.getValue());
    }

    if (canHaveBody) {
        HttpEntityEnclosingRequestBase entityEnclosingReq = (HttpEntityEnclosingRequestBase) req;

        if (body != null) {

            NByteArrayEntity entity = new NByteArrayEntity(body);

            if (contentType != null) {
                entity.setContentType(contentType);
            }

            entityEnclosingReq.setEntity(entity);
        } else {

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();

            for (Entry<String, String> entry : files.entrySet()) {
                String filename = entry.getValue();
                File file = IO.file(filename);
                builder = builder.addBinaryBody(entry.getKey(), file, ContentType.DEFAULT_BINARY, filename);
            }

            for (Entry<String, String> entry : data.entrySet()) {
                builder = builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.DEFAULT_TEXT);
            }

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            try {
                builder.build().writeTo(stream);
            } catch (IOException e) {
                throw U.rte(e);
            }

            byte[] bytes = stream.toByteArray();
            NByteArrayEntity entity = new NByteArrayEntity(bytes, ContentType.MULTIPART_FORM_DATA);

            entityEnclosingReq.setEntity(entity);
        }
    }

    Log.debug("Starting HTTP request", "request", req.getRequestLine());

    return execute(client, req, callback, fullResponse);
}

From source file:org.wso2.bps.integration.common.clients.bpmn.ActivitiRestClient.java

/**
 * This Method is used to deploy BPMN packages to the BPMN Server
 *
 * @param fileName The name of the Package to be deployed
 * @param filePath The location of the BPMN package to be deployed
 * @throws java.io.IOException/*from  w w w.j a v  a 2s.co  m*/
 * @throws org.json.JSONException
 * @returns String array with status, deploymentID and Name
 */
public String[] deployBPMNPackage(String filePath, String fileName) throws Exception {
    String url = serviceURL + "repository/deployments";

    HttpHost target = new HttpHost(hostname, port, "http");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));

    HttpPost httpPost = new HttpPost(url);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("file", new File(filePath), ContentType.MULTIPART_FORM_DATA, fileName);
    HttpEntity multipart = builder.build();
    httpPost.setEntity(multipart);
    HttpResponse response = httpClient.execute(httpPost);
    String status = response.getStatusLine().toString();
    String responseData = EntityUtils.toString(response.getEntity());
    JSONObject jsonResponseObject = new JSONObject(responseData);
    if (status.contains(Integer.toString(HttpStatus.SC_CREATED))
            || status.contains(Integer.toString(HttpStatus.SC_OK))) {
        String deploymentID = jsonResponseObject.getString("id");
        String name = jsonResponseObject.getString("name");
        return new String[] { status, deploymentID, name };
    } else if (status.contains(Integer.toString(HttpStatus.SC_INTERNAL_SERVER_ERROR))) {

        String errorMessage = jsonResponseObject.getString("errorMessage");
        throw new RestClientException(errorMessage);
        //            return new String[]{status, errorMessage};
    } else {
        throw new RestClientException("Failed to deploy package " + fileName);
    }
}

From source file:org.wso2.carbon.apimgt.hybrid.gateway.usage.publisher.tasks.APIUsageFileUploadTask.java

/**
 * Uploads the API Usage file to Upload Service
 *
 * @param compressedFilePath File Path to the compressed file
 * @param fileName  Name of the uploading file
 * @return  Returns boolean true if uploading is successful
 *///from w w w.  ja va 2  s . c om
private boolean uploadCompressedFile(Path compressedFilePath, String fileName) {
    String response;

    try {
        String uploadServiceUrl = configManager
                .getProperty(MicroGatewayAPIUsageConstants.USAGE_UPLOAD_SERVICE_URL);
        uploadServiceUrl = (uploadServiceUrl != null && !uploadServiceUrl.isEmpty()) ? uploadServiceUrl
                : MicroGatewayAPIUsageConstants.DEFAULT_UPLOAD_SERVICE_URL;
        URL uploadServiceUrlValue = MicroGatewayCommonUtil.getURLFromStringUrlValue(uploadServiceUrl);
        HttpClient httpClient = APIUtil.getHttpClient(uploadServiceUrlValue.getPort(),
                uploadServiceUrlValue.getProtocol());
        HttpPost httppost = new HttpPost(uploadServiceUrl);

        InputStream zipStream = new FileInputStream(compressedFilePath.toString());
        MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
        mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        mBuilder.addBinaryBody("file", zipStream, ContentType.create("application/zip"), fileName);
        HttpEntity entity = mBuilder.build();
        httppost.setHeader(MicroGatewayAPIUsageConstants.FILE_NAME_HEADER, fileName);

        APIManagerConfiguration config = ServiceReferenceHolder.getInstance()
                .getAPIManagerConfigurationService().getAPIManagerConfiguration();
        String username = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME);
        char[] password = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_PASSWORD).toCharArray();

        String authHeaderValue = TokenUtil.getBasicAuthHeaderValue(username, password);
        MicroGatewayCommonUtil.cleanPasswordCharArray(password);
        httppost.setHeader(MicroGatewayAPIUsageConstants.AUTHORIZATION_HEADER, authHeaderValue);
        httppost.setHeader(MicroGatewayAPIUsageConstants.ACCEPT_HEADER,
                MicroGatewayAPIUsageConstants.ACCEPT_HEADER_APPLICATION_JSON);
        httppost.setEntity(entity);

        response = HttpRequestUtil.executeHTTPMethodWithRetry(httpClient, httppost,
                MicroGatewayAPIUsageConstants.MAX_RETRY_COUNT);
        log.info("API Usage file : " + compressedFilePath.getFileName() + " uploaded successfully. "
                + "Server Response : " + response);
        return true;
    } catch (OnPremiseGatewayException e) {
        log.error("Error occurred while uploading API Usage file.", e);
    } catch (FileNotFoundException e) {
        log.error("Error occurred while reading API Usage file from the path.", e);
    }
    return false;
}

From source file:org.wso2.ei.businessprocess.integration.common.clients.bpmn.ActivitiRestClient.java

/**
 * This Method is used to deploy BPMN packages to the BPMN Server
 *
 * @param fileName The name of the Package to be deployed
 * @param filePath The location of the BPMN package to be deployed
 * @throws java.io.IOException/*from w w w . ja  v  a 2 s  .  c  om*/
 * @throws org.json.JSONException
 * @returns String array with status, deploymentID and Name
 */
public String[] deployBPMNPackage(String filePath, String fileName)
        throws RestClientException, IOException, JSONException {
    String url = serviceURL + "repository/deployments";
    DefaultHttpClient httpClient = getHttpClient();
    HttpPost httpPost = new HttpPost(url);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("file", new File(filePath), ContentType.MULTIPART_FORM_DATA, fileName);
    HttpEntity multipart = builder.build();
    httpPost.setEntity(multipart);
    HttpResponse response = httpClient.execute(httpPost);
    String status = response.getStatusLine().toString();
    String responseData = EntityUtils.toString(response.getEntity());
    JSONObject jsonResponseObject = new JSONObject(responseData);
    if (status.contains(Integer.toString(HttpStatus.SC_CREATED))
            || status.contains(Integer.toString(HttpStatus.SC_OK))) {
        String deploymentID = jsonResponseObject.getString(ID);
        String name = jsonResponseObject.getString(NAME);
        return new String[] { status, deploymentID, name };
    } else if (status.contains(Integer.toString(HttpStatus.SC_INTERNAL_SERVER_ERROR))) {
        String errorMessage = jsonResponseObject.getString("errorMessage");
        throw new RestClientException(errorMessage);
    } else {
        throw new RestClientException("Failed to deploy package " + fileName);
    }
}

From source file:xin.nic.sdk.registrar.util.HttpUtil.java

public static String doPost(String requestUrl, Map<String, String> paramsMap, Map<String, InputStream> files)
        throws Exception {

    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(500)
            .setSocketTimeout(20000).setConnectTimeout(20000).build();

    // ?// w  ww  .  j av  a  2s. co m
    MultipartEntityBuilder mbuilder = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(Charset.forName(charset));

    if (paramsMap != null) {
        Set<Entry<String, String>> paramsSet = paramsMap.entrySet();
        for (Entry<String, String> entry : paramsSet) {
            mbuilder.addTextBody(entry.getKey(), entry.getValue(), ContentType.create("text/plain", charset));
        }
    }

    if (files != null) {
        Set<Entry<String, InputStream>> filesSet = files.entrySet();
        for (Entry<String, InputStream> entry : filesSet) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            InputStream is = entry.getValue();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.close();
            is.close();
            mbuilder.addBinaryBody("attachment", os.toByteArray(), ContentType.APPLICATION_OCTET_STREAM,
                    entry.getKey());
        }
    }

    HttpPost httpPost = new HttpPost(requestUrl);
    httpPost.setConfig(requestConfig);

    HttpEntity httpEntity = mbuilder.build();

    httpPost.setEntity(httpEntity);

    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }

    };

    return httpClient.execute(httpPost, responseHandler);
}