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:org.eclipse.vorto.repository.RestModelRepository.java

@Override
public UploadResult upload(String name, byte[] model) {
    Objects.requireNonNull(model, "Model should not be null.");
    Objects.requireNonNull(name, "Name should not be null.");
    try {/*from ww w . ja v  a 2  s  .  c o m*/
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody(FILE_PARAMETER_NAME, model, ContentType.APPLICATION_OCTET_STREAM, name);
        HttpEntity fileToUpload = builder.build();

        UploadResultView uploadResult = httpClient.executePost("secure", fileToUpload, uploadResponseConverter);

        return uploadResultConverter.apply(uploadResult);
    } catch (Exception e) {
        throw new CheckInModelException("Error in uploading file to remote repository", e);
    }
}

From source file:com.releasequeue.server.ReleaseQueueServer.java

@Override
public HttpResponse uploadPackage(FilePath packagePath, String distribution, String component)
        throws MalformedURLException, IOException {
    String repoType = FilenameUtils.getExtension(packagePath.toString());

    String uploadPath = String.format("%s/%s/repositories/%s/packages?distribution=%s&component=%s",
            this.basePath, this.userName, repoType, distribution, component);
    URL uploadPackageUrl = new URL(this.serverUrl, uploadPath);

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = new HttpPost(uploadPackageUrl.toString());
    setAuthHeader(uploadFile);/*from  www. j  a  v a2  s.com*/

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("file", new File(packagePath.toString()), ContentType.APPLICATION_OCTET_STREAM,
            packagePath.getName());
    HttpEntity multipart = builder.build();

    uploadFile.setEntity(multipart);

    HttpResponse response = httpClient.execute(uploadFile);
    return response;
}

From source file:Vdisk.java

public void upload_file(String local_filepath, String filepath)
        throws URISyntaxException, FileNotFoundException, IOException {
    File file = new File(local_filepath);
    URI uri = new URIBuilder().setScheme("http").setHost("upload-vdisk.sina.com.cn/2/files/sandbox/")
            .setPath(filepath).setParameter("access_token", this.access_token).build();
    HttpPost httpPost = new HttpPost(uri);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, local_filepath);
    HttpEntity entity = builder.build();
    httpPost.setEntity(entity);/*from  w  ww  . jav  a 2  s  .  c o m*/
    CloseableHttpClient postClient = HttpClients.createDefault();
    try (CloseableHttpResponse response = postClient.execute(httpPost)) {
        System.out.println(response);//check result
    } finally {
        postClient.close();
    }
}

From source file:com.norconex.committer.gsa.GsaCommitter.java

@Override
protected void commitBatch(List<ICommitOperation> batch) {

    File xmlFile = null;/*from  w w w .j a v a  2  s .  c om*/
    try {
        xmlFile = File.createTempFile("batch", ".xml");
        FileOutputStream fout = new FileOutputStream(xmlFile);
        XmlOutput xmlOutput = new XmlOutput(fout);
        Map<String, Integer> stats = xmlOutput.write(batch);
        fout.close();

        HttpPost post = new HttpPost(feedUrl);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addBinaryBody("data", xmlFile, ContentType.APPLICATION_XML, xmlFile.getName());
        builder.addTextBody("datasource", "GSA_Commiter");
        builder.addTextBody("feedtype", "full");

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        CloseableHttpResponse response = httpclient.execute(post);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) {
            throw new CommitterException("Invalid response to Committer HTTP request. " + "Response code: "
                    + status.getStatusCode() + ". Response Message: " + status.getReasonPhrase());
        }
        LOG.info("Sent " + stats.get("docAdded") + " additions and " + stats.get("docRemoved")
                + " removals to GSA");

    } catch (Exception e) {
        throw new CommitterException("Cannot index document batch to GSA.", e);
    } finally {
        FileUtils.deleteQuietly(xmlFile);
    }
}

From source file:com.microsoft.cognitive.speakerrecognition.SpeakerRestClientHelper.java

/**
 * Adds a stream to an HTTP entity//from w w  w.ja v  a  2s  . c o  m
 *
 * @param someStream Input stream to be added to an HTTP entity
 * @param fieldName A description of the entity content
 * @param fileName Name of the file attached as an entity
 * @return HTTP entity
 * @throws IOException Signals a failure while reading the input stream
 */
HttpEntity addStreamToEntity(InputStream someStream, String fieldName, String fileName) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int bytesRead;
    byte[] bytes = new byte[1024];
    while ((bytesRead = someStream.read(bytes)) > 0) {
        byteArrayOutputStream.write(bytes, 0, bytesRead);
    }
    byte[] data = byteArrayOutputStream.toByteArray();

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.setStrictMode();
    builder.addBinaryBody(fieldName, data, ContentType.MULTIPART_FORM_DATA, fileName);
    return builder.build();
}

From source file:org.lokra.seaweedfs.core.VolumeWrapper.java

/**
 * Upload file.//w  w  w. j a  v  a 2 s. c om
 *
 * @param url         url
 * @param fid         fid
 * @param fileName    fileName
 * @param stream      stream
 * @param ttl         ttl
 * @param contentType contentType
 * @return The size returned is the size stored on SeaweedFS.
 * @throws IOException Http connection is fail or server response within some error message.
 */
long uploadFile(String url, String fid, String fileName, InputStream stream, String ttl,
        ContentType contentType) throws IOException {
    HttpPost request;
    if (ttl != null)
        request = new HttpPost(url + "/" + fid + "?ttl=" + ttl);
    else
        request = new HttpPost(url + "/" + fid);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(CharsetUtils.get("UTF-8"));
    builder.addBinaryBody("upload", stream, contentType, fileName);
    HttpEntity entity = builder.build();
    request.setEntity(entity);
    JsonResponse jsonResponse = connection.fetchJsonResultByRequest(request);
    convertResponseStatusToException(jsonResponse.statusCode, url, fid, false, false, false, false);
    return (Integer) objectMapper.readValue(jsonResponse.json, Map.class).get("size");
}

From source file:org.flowable.ui.modeler.service.AppDefinitionPublishService.java

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {//w  w  w  . j ava  2  s . c  o  m
    String deployApiUrl = modelerAppProperties.getDeploymentApiUrl();
    Assert.hasText(deployApiUrl, "flowable.modeler.app.deployment-api-url must be set");
    String basicAuthUser = properties.getIdmAdmin().getUser();
    String basicAuthPassword = properties.getIdmAdmin().getPassword();

    String tenantId = tenantProvider.getTenantId();
    if (!deployApiUrl.endsWith("/")) {
        deployApiUrl = deployApiUrl.concat("/");
    }
    deployApiUrl = deployApiUrl
            .concat(String.format("app-repository/deployments?deploymentKey=%s&deploymentName=%s",
                    encode(deploymentKey), encode(deploymentName)));

    if (tenantId != null) {
        StringBuilder sb = new StringBuilder(deployApiUrl);
        sb.append("&tenantId=").append(encode(tenantId));
        deployApiUrl = sb.toString();
    }

    HttpPost httpPost = new HttpPost(deployApiUrl);
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.getEncoder()
            .encode((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();
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        clientBuilder
                .setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }));

    } 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: {} for url",
                    response.getStatusLine() + httpPost.getURI().toString());
            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:com.frochr123.periodictasks.RefreshProjectorThread.java

public void updateProjectorImage() {
    if (!updateInProgress && !shutdownThreadRunning) {
        updateInProgress = true;//from   ww w  .  ja v  a2  s .  com

        new Thread() {
            @Override
            public void run() {
                try {
                    if (VisicutModel.getInstance() != null
                            && VisicutModel.getInstance().getSelectedLaserDevice() != null
                            && VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL() != null
                            && !VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL()
                                    .isEmpty()) {
                        BufferedImage img = PreviewImageExport.generateImage(getProjectorWidth(),
                                getProjectorHeight(), !isShutdownInProgress());

                        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                        PreviewImageExport.writePngToOutputStream(outputStream, img);
                        byte[] imagePostDataByte = outputStream.toByteArray();

                        // Create HTTP client and cusomized config for timeouts
                        CloseableHttpClient httpClient = HttpClients.createDefault();
                        RequestConfig requestConfig = RequestConfig.custom()
                                .setSocketTimeout(DEFAULT_PROJECTOR_TIMEOUT)
                                .setConnectTimeout(DEFAULT_PROJECTOR_TIMEOUT)
                                .setConnectionRequestTimeout(DEFAULT_PROJECTOR_TIMEOUT).build();

                        // Create HTTP Post request
                        HttpPost httpPost = new HttpPost(
                                VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL());
                        httpPost.setConfig(requestConfig);

                        // Insert file upload
                        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
                        multipartEntityBuilder.addBinaryBody("data", imagePostDataByte,
                                ContentType.APPLICATION_OCTET_STREAM, "data");
                        HttpEntity httpEntity = multipartEntityBuilder.build();
                        httpPost.setEntity(httpEntity);

                        // Set authentication information
                        String encodedCredentials = Helper.getEncodedCredentials(
                                VisicutModel.getInstance().getSelectedLaserDevice().getURLUser(),
                                VisicutModel.getInstance().getSelectedLaserDevice().getURLPassword());
                        if (!encodedCredentials.isEmpty()) {
                            httpPost.addHeader("Authorization", "Basic " + encodedCredentials);
                        }

                        // Send request
                        CloseableHttpResponse res = httpClient.execute(httpPost);

                        // React to possible server side errors
                        if (res.getStatusLine() == null
                                || res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                            throw new Exception("Server sent wrong HTTP status code: "
                                    + new Integer(res.getStatusLine().getStatusCode()).toString());
                        }

                        // Close everything correctly
                        res.close();
                        httpClient.close();
                    }
                }
                // This is caused internally in apache commons library for wrong authentication
                // Would need to add additional apache commons library file to get a correct exception back for that
                catch (NoClassDefFoundError error) {
                    // Set flag for exception handling, sleep and message
                    lastExceptionMessage = "Projector thread exception: Authentication error!";
                } catch (Exception e) {
                    // Set flag for exception handling, sleep and message
                    lastExceptionMessage = "Projector thread exception (2): " + e.getMessage();
                }

                updateInProgress = false;

                // Need to check if shutdown is set here first, otherwise these asynchronous calls
                // would always overwrite a call to shutdown in progress = true
                if (shutdownInProgress) {
                    shutdownInProgress = false;
                }
            }
        }.start();
    }
}

From source file:org.mule.module.http.functional.listener.HttpListenerAttachmentsTestCase.java

private HttpEntity getMultipartEntity(boolean withFile) {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody(TEXT_BODY_FIELD_NAME, TEXT_BODY_FIELD_VALUE, ContentType.TEXT_PLAIN);
    if (withFile) {
        builder.addBinaryBody(FILE_BODY_FIELD_NAME, FILE_BODY_FIELD_VALUE.getBytes(),
                ContentType.APPLICATION_OCTET_STREAM, FIELD_BDOY_FILE_NAME);
    }//from w ww  .j av  a  2s.c  o m
    return builder.build();
}

From source file:com.ritesh.idea.plugin.util.HttpRequestBuilder.java

private HttpRequestBase getHttpRequest() throws URISyntaxException, UnsupportedEncodingException {
    if (!route.isEmpty()) {
        String path = urlBuilder.getPath() + route;
        path = path.replace("//", "/");
        urlBuilder.setPath(path);/*from  www. j a  va2s  .  c o  m*/
    }
    request.setURI(urlBuilder.build());
    if (request instanceof HttpPost) {
        if (fileParam != null) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            for (NameValuePair formParam : formParams) {
                builder.addTextBody(formParam.getName(), formParam.getValue());
            }
            HttpEntity entity = builder
                    .addBinaryBody(fileParam, fileBytes, ContentType.MULTIPART_FORM_DATA, fileName).build();
            ((HttpPost) request).setEntity(entity);
        } else if (!formParams.isEmpty()) {
            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(formParams));
        }
    } else if (request instanceof HttpPut) {
        if (!formParams.isEmpty()) {
            ((HttpPut) request).setEntity(new UrlEncodedFormEntity(formParams));
        }
    }
    return request;

}