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) 

Source Link

Usage

From source file:org.openbaton.sdk.api.util.RestRequest.java

/**
 * Used to upload tar files to the NFVO for creating VNFPackages.
 *
 * @param f the tar file containing the VNFPackage
 * @return the created VNFPackage object
 * @throws SDKException/*  ww w. j  a  v a2  s . com*/
 */
public VNFPackage requestPostPackage(final File f) throws SDKException {
    CloseableHttpResponse response = null;
    HttpPost httpPost = null;

    try {
        try {
            checkToken();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new SDKException("Could not get token", e);
        }
        log.debug("Executing post on " + baseUrl);
        httpPost = new HttpPost(this.baseUrl);
        httpPost.setHeader(new BasicHeader("accept", "multipart/form-data"));
        httpPost.setHeader(new BasicHeader("project-id", projectId));
        if (token != null)
            httpPost.setHeader(new BasicHeader("authorization", bearerToken.replaceAll("\"", "")));

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addBinaryBody("file", f);
        httpPost.setEntity(multipartEntityBuilder.build());

        response = httpClient.execute(httpPost);
    } catch (ClientProtocolException e) {
        httpPost.releaseConnection();
        throw new SDKException("Could not create VNFPackage from file " + f.getName(), e);
    } catch (IOException e) {
        httpPost.releaseConnection();
        throw new SDKException("Could not create VNFPackage from file " + f.getName(), e);
    }

    // check response status
    checkStatus(response, HttpURLConnection.HTTP_OK);
    // return the response of the request
    String result = "";
    if (response.getEntity() != null)
        try {
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }

    if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) {
        JsonParser jsonParser = new JsonParser();
        JsonElement jsonElement = jsonParser.parse(result);
        result = mapper.toJson(jsonElement);
        log.debug("Uploaded the VNFPackage");
        log.trace("received: " + result);

        log.trace("Casting it into: " + VNFPackage.class);
        httpPost.releaseConnection();
        return mapper.fromJson(result, VNFPackage.class);
    }
    httpPost.releaseConnection();
    return null;
}

From source file:apiserver.core.connectors.coldfusion.ColdFusionHttpBridge.java

public ResponseEntity invokeFilePost(String cfcPath_, String method_, Map<String, Object> methodArgs_)
        throws ColdFusionException {
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

        HttpHost host = new HttpHost(cfHost, cfPort, cfProtocol);
        HttpPost method = new HttpPost(validatePath(cfPath) + cfcPath_);

        MultipartEntityBuilder me = MultipartEntityBuilder.create();
        me.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        if (methodArgs_ != null) {
            for (String s : methodArgs_.keySet()) {
                Object obj = methodArgs_.get(s);

                if (obj != null) {
                    if (obj instanceof String) {
                        me.addTextBody(s, (String) obj);
                    } else if (obj instanceof Integer) {
                        me.addTextBody(s, ((Integer) obj).toString());
                    } else if (obj instanceof File) {
                        me.addBinaryBody(s, (File) obj);
                    } else if (obj instanceof IDocument) {
                        me.addBinaryBody(s, ((IDocument) obj).getFile());
                        //me.addTextBody( "name", ((IDocument)obj).getFileName() );
                        //me.addTextBody("contentType", ((IDocument) obj).getContentType().contentType );
                    } else if (obj instanceof IDocument[]) {
                        for (int i = 0; i < ((IDocument[]) obj).length; i++) {
                            IDocument iDocument = ((IDocument[]) obj)[i];
                            me.addBinaryBody(s, iDocument.getFile());
                            //me.addTextBody("name", iDocument.getFileName() );
                            //me.addTextBody("contentType", iDocument.getContentType().contentType );
                        }// w  w w  . j a  va 2s.c o m

                    } else if (obj instanceof BufferedImage) {

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        ImageIO.write((BufferedImage) obj, "jpg", baos);

                        String _fileName = (String) methodArgs_.get(ApiServerConstants.FILE_NAME);
                        String _mimeType = ((MimeType) methodArgs_.get(ApiServerConstants.CONTENT_TYPE))
                                .getExtension();
                        ContentType _contentType = ContentType.create(_mimeType);
                        me.addBinaryBody(s, baos.toByteArray(), _contentType, _fileName);
                    } else if (obj instanceof byte[]) {
                        me.addBinaryBody(s, (byte[]) obj);
                    } else if (obj instanceof Map) {
                        ObjectMapper mapper = new ObjectMapper();
                        String _json = mapper.writeValueAsString(obj);

                        me.addTextBody(s, _json);
                    }
                }
            }
        }

        HttpEntity httpEntity = me.build();
        method.setEntity(httpEntity);

        HttpResponse response = httpClient.execute(host, method);//, responseHandler);

        // Examine the response status
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream inputStream = entity.getContent();
                //return inputStream;

                byte[] _body = IOUtils.toByteArray(inputStream);

                MultiValueMap _headers = new LinkedMultiValueMap();
                for (Header header : response.getAllHeaders()) {
                    if (header.getName().equalsIgnoreCase("content-length")) {
                        _headers.add(header.getName(), header.getValue());
                    } else if (header.getName().equalsIgnoreCase("content-type")) {
                        _headers.add(header.getName(), header.getValue());

                        // special condition to add zip to the file name.
                        if (header.getValue().indexOf("text/") > -1) {
                            //add nothing extra
                        } else if (header.getValue().indexOf("zip") > -1) {
                            if (methodArgs_.get("file") != null) {
                                String _fileName = ((Document) methodArgs_.get("file")).getFileName();
                                _headers.add("Content-Disposition",
                                        "attachment; filename=\"" + _fileName + ".zip\"");
                            }
                        } else if (methodArgs_.get("file") != null) {
                            String _fileName = ((Document) methodArgs_.get("file")).getFileName();
                            _headers.add("Content-Disposition", "attachment; filename=\"" + _fileName + "\"");
                        }

                    }
                }

                return new ResponseEntity(_body, _headers, org.springframework.http.HttpStatus.OK);
                //Map json = (Map)deSerializeJson(inputStream);
                //return json;
            }
        }

        MultiValueMap _headers = new LinkedMultiValueMap();
        _headers.add("Content-Type", "text/plain");
        return new ResponseEntity(response.getStatusLine().toString(), _headers,
                org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}

From source file:at.gv.egiz.sl.util.BKUSLConnector.java

private String performHttpRequestToBKU(String xmlRequest, RequestPackage pack, SignParameter parameter)
        throws ClientProtocolException, IOException, IllegalStateException {
    CloseableHttpClient client = null;/* www  . ja  v  a2 s.c om*/
    try {
        client = buildHttpClient();
        HttpPost post = new HttpPost(this.bkuUrl);

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setCharset(Charset.forName("UTF-8"));
        entityBuilder.addTextBody(XMLREQUEST, xmlRequest,
                ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8")));

        if (parameter != null) {
            String transactionId = parameter.getTransactionId();
            if (transactionId != null) {
                entityBuilder.addTextBody("TransactionId_", transactionId);
            }
        }

        if (pack != null && pack.getSignatureData() != null) {
            entityBuilder.addBinaryBody("fileupload",
                    PDFUtils.blackOutSignature(pack.getSignatureData(), pack.getByteRange()));
        }
        post.setEntity(entityBuilder.build());

        HttpResponse response = client.execute(post);
        logger.debug("Response Code : " + response.getStatusLine().getStatusCode());

        if (parameter instanceof BKUHeaderHolder) {
            BKUHeaderHolder holder = (BKUHeaderHolder) parameter;
            Header[] headers = response.getAllHeaders();

            if (headers != null) {
                for (int i = 0; i < headers.length; i++) {
                    BKUHeader hdr = new BKUHeader(headers[i].getName(), headers[i].getValue());
                    logger.debug("Response Header : {}", hdr.toString());
                    if (hdr.toString().contains("Server")) {
                        BaseSLConnector.responseHeader = hdr.toString();
                    }

                    holder.getProcessInfo().add(hdr);

                }

            }

            BKUHeader hdr = new BKUHeader(ErrorConstants.STATUS_INFO_SIGDEVICE, SIGNATURE_DEVICE);
            logger.debug("Response Header : {}", hdr.toString());

            holder.getProcessInfo().add(hdr);

        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();
        response = null;
        rd = null;

        logger.trace(result.toString());
        return result.toString();
    } catch (PDFIOException e) {
        throw new PdfAsWrappedIOException(e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:org.phenotips.integration.medsavant.internal.JsonMedSavantServer.java

@Override
public boolean uploadVCF(Patient patient) {
    HttpPost method = null;// w w w  .  ja  v a  2 s  .com
    try {
        MultipartEntityBuilder data = MultipartEntityBuilder.create();
        PatientData<String> identifiers = patient.getData("identifiers");
        String url = getMethodURL("UploadManager", "upload");
        String eid = identifiers.get("external_id");
        XWikiContext context = Utils.getContext();
        XWikiDocument doc = context.getWiki().getDocument(patient.getDocument(), context);
        method = new HttpPost(url);

        boolean hasData = false;
        for (XWikiAttachment attachment : doc.getAttachmentList()) {
            if (StringUtils.endsWithIgnoreCase(attachment.getFilename(), ".vcf")
                    && isCorrectVCF(attachment, eid, context)) {
                data.addBinaryBody(patient.getId() + ".vcf", attachment.getContentInputStream(context));
                hasData = true;
            }
        }
        if (hasData) {
            method.setEntity(data.build());
            this.client.execute(method).close();
            return true;
        }
    } catch (Exception ex) {
        this.logger.warn("Failed to upload VCF for patient [{}]: {}", patient.getDocument(), ex.getMessage(),
                ex);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return false;
}

From source file:at.gv.egiz.sl.util.BKUSLConnector.java

private String performHttpBulkRequestToBKU(String xmlRequest, BulkRequestPackage pack, SignParameter parameter)
        throws ClientProtocolException, IOException, IllegalStateException {
    CloseableHttpClient client = null;//  ww w.  j  av a  2 s.c o m
    try {
        client = buildHttpClient();
        HttpPost post = new HttpPost(this.bkuUrl);

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setCharset(Charset.forName("UTF-8"));
        entityBuilder.addTextBody(XMLREQUEST, xmlRequest,
                ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8")));

        if (parameter != null) {
            String transactionId = parameter.getTransactionId();
            if (transactionId != null) {
                entityBuilder.addTextBody("TransactionId_", transactionId);
            }
        }

        for (SignRequestPackage signRequestPackage : pack.getSignRequestPackages()) {

            if (pack != null && signRequestPackage != null
                    && signRequestPackage.getCmsRequest().getSignatureData() != null) {
                entityBuilder.addBinaryBody("fileupload",
                        PDFUtils.blackOutSignature(signRequestPackage.getCmsRequest().getSignatureData(),
                                signRequestPackage.getCmsRequest().getByteRange()));
            }

        }

        post.setEntity(entityBuilder.build());

        HttpResponse response = client.execute(post);
        logger.debug("Response Code : " + response.getStatusLine().getStatusCode());

        if (parameter instanceof BKUHeaderHolder) {
            BKUHeaderHolder holder = (BKUHeaderHolder) parameter;
            Header[] headers = response.getAllHeaders();

            if (headers != null) {
                for (int i = 0; i < headers.length; i++) {
                    BKUHeader hdr = new BKUHeader(headers[i].getName(), headers[i].getValue());
                    logger.debug("Response Header : {}", hdr.toString());
                    holder.getProcessInfo().add(hdr);
                }
            }

            BKUHeader hdr = new BKUHeader(ErrorConstants.STATUS_INFO_SIGDEVICE, SIGNATURE_DEVICE);
            logger.debug("Response Header : {}", hdr.toString());
            holder.getProcessInfo().add(hdr);
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();
        response = null;
        rd = null;

        logger.trace(result.toString());
        return result.toString();
    } catch (PDFIOException e) {
        throw new PdfAsWrappedIOException(e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java

/**
 * Execute an auth query using POST//w  w w.j a  va  2s .  c  om
 * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld
 * @throws Exception
 */

public JSONObject executeAuthUploadOwl(byte[] owl) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(this.userName, this.password));

    String[] serverNoProtocol = this.server.split("://");
    //System.err.println("the new server name is: " + serverNoProtocol[1]);

    HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http");

    DigestScheme digestAuth = new DigestScheme();
    AuthCache authCache = new BasicAuthCache();
    digestAuth.overrideParamter("realm", "SPARQL");
    // Suppose we already know the expected nonce value
    digestAuth.overrideParamter("nonce", "whatever");
    authCache.put(targetHost, digestAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // add new stuff
    HttpPost httppost = new HttpPost(getUploadURL());
    String resultsFormat = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    httppost.addHeader("Accept", resultsFormat);
    httppost.addHeader("X-Sparql-default-graph", this.dataset);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.addTextBody("graph-uri", this.dataset);
    builder.addBinaryBody("res-file", owl);
    HttpEntity entity = builder.build();
    httppost.setEntity(entity);

    /*  THIS IS THE MULTIPART FORMAT WE NEED TO SEND.
            
    Content-Type: multipart/form-data; boundary=---------------------------32932166721282
    Content-Length: 234
            
    -----------------------------32932166721282
    Content-Disposition: form-data; name="graph-uri"
            
    http://www.kdl.ge.com/changeme
    -----------------------------32932166721282
    Content-Disposition: form-data; name="res-file"; filename="employee.owl"
    Content-Type: application/octet-stream
            
    <rdf:RDF
        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
        xmlns:owl="http://www.w3.org/2002/07/owl#"
        xmlns="http://kdl.ge.com/pd/employee#"
        xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
      .
      .
      .
    </rdf:RDF>
            
    -----------------------------32932166721282--
            
     */

    executeTestQuery();

    HttpResponse response_http = httpclient.execute(targetHost, httppost, localcontext);
    HttpEntity resp_entity = response_http.getEntity();
    // get response with HTML tags removed
    String responseTxt = EntityUtils.toString(resp_entity, "UTF-8").replaceAll("\\<.*?>", " ");

    SimpleResultSet ret = new SimpleResultSet();

    if (responseTxt.trim().isEmpty()) {
        // success or bad login :-(
        ret.setSuccess(true);
    } else {
        ret.setSuccess(false);
        ret.addRationaleMessage(responseTxt);
    }
    resp_entity.getContent().close();
    return ret.toJson();
}

From source file:com.serphacker.serposcope.scraper.http.ScrapClient.java

public int post(String url, Map<String, Object> data, PostType dataType, String charset, String referrer) {
    clearPreviousRequest();/*from   ww  w. j  av  a2s  . c  o m*/

    HttpPost request = new HttpPost(url);
    HttpEntity entity = null;

    if (charset == null) {
        charset = "utf-8";
    }

    Charset detectedCharset = null;
    try {
        detectedCharset = Charset.forName(charset);
    } catch (Exception ex) {
        LOG.warn("invalid charset name {}, switching to utf-8");
        detectedCharset = Charset.forName("utf-8");
    }

    data = handleUnsupportedEncoding(data, detectedCharset);

    switch (dataType) {
    case URL_ENCODED:
        List<NameValuePair> formparams = new ArrayList<>();
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            if (entry.getValue() instanceof String) {
                formparams.add(new BasicNameValuePair(entry.getKey(), (String) entry.getValue()));
            } else {
                LOG.warn("trying to url encode non string data");
                formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }

        try {
            entity = new UrlEncodedFormEntity(formparams, detectedCharset);
        } catch (Exception ex) {
            statusCode = -1;
            exception = ex;
            return statusCode;
        }
        break;

    case MULTIPART:
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(detectedCharset)
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        ContentType formDataCT = ContentType.create("form-data", detectedCharset);
        //                formDataCT = ContentType.DEFAULT_TEXT;

        for (Map.Entry<String, Object> entry : data.entrySet()) {
            String key = entry.getKey();

            if (entry.getValue() instanceof String) {
                builder = builder.addTextBody(key, (String) entry.getValue(), formDataCT);
            } else if (entry.getValue() instanceof byte[]) {
                builder = builder.addBinaryBody(key, (byte[]) entry.getValue());
            } else if (entry.getValue() instanceof ContentBody) {
                builder = builder.addPart(key, (ContentBody) entry.getValue());
            } else {
                exception = new UnsupportedOperationException(
                        "unssuported body type " + entry.getValue().getClass());
                return statusCode = -1;
            }
        }

        entity = builder.build();
        break;

    default:
        exception = new UnsupportedOperationException("unspported PostType " + dataType);
        return statusCode = -1;
    }

    request.setEntity(entity);
    if (referrer != null) {
        request.addHeader("Referer", referrer);
    }
    return request(request);
}

From source file:org.rundeck.api.ApiCall.java

private <T> T requestWithEntity(ApiPathBuilder apiPath, Handler<HttpResponse, T> handler,
        HttpEntityEnclosingRequestBase httpPost) {
    if (null != apiPath.getAccept()) {
        httpPost.setHeader("Accept", apiPath.getAccept());
    }/*from   w ww .java2s.  co  m*/
    // POST a multi-part request, with all attachments
    if (apiPath.getAttachments().size() > 0 || apiPath.getFileAttachments().size() > 0) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        ArrayList<File> tempfiles = new ArrayList<>();

        //attach streams
        for (Entry<String, InputStream> attachment : apiPath.getAttachments().entrySet()) {
            if (client.isUseIntermediateStreamFile()) {
                //transfer to file
                File f = copyToTempfile(attachment.getValue());
                multipartEntityBuilder.addBinaryBody(attachment.getKey(), f);
                tempfiles.add(f);
            } else {
                multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue());
            }
        }
        if (tempfiles.size() > 0) {
            handler = TempFileCleanupHandler.chain(handler, tempfiles);
        }

        //attach files
        for (Entry<String, File> attachment : apiPath.getFileAttachments().entrySet()) {
            multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue());
        }

        httpPost.setEntity(multipartEntityBuilder.build());
    } else if (apiPath.getForm().size() > 0) {
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(apiPath.getForm(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RundeckApiException("Unsupported encoding: " + e.getMessage(), e);
        }
    } else if (apiPath.getContentStream() != null && apiPath.getContentType() != null) {
        if (client.isUseIntermediateStreamFile()) {
            ArrayList<File> tempfiles = new ArrayList<>();
            File f = copyToTempfile(apiPath.getContentStream());
            tempfiles.add(f);
            httpPost.setEntity(new FileEntity(f, ContentType.create(apiPath.getContentType())));

            handler = TempFileCleanupHandler.chain(handler, tempfiles);
        } else {
            InputStreamEntity entity = new InputStreamEntity(apiPath.getContentStream(),
                    ContentType.create(apiPath.getContentType()));
            httpPost.setEntity(entity);
        }
    } else if (apiPath.getContents() != null && apiPath.getContentType() != null) {
        ByteArrayEntity bae = new ByteArrayEntity(apiPath.getContents(),
                ContentType.create(apiPath.getContentType()));

        httpPost.setEntity(bae);
    } else if (apiPath.getContentFile() != null && apiPath.getContentType() != null) {
        httpPost.setEntity(
                new FileEntity(apiPath.getContentFile(), ContentType.create(apiPath.getContentType())));
    } else if (apiPath.getXmlDocument() != null) {
        httpPost.setHeader("Content-Type", "application/xml");
        httpPost.setEntity(new EntityTemplate(new DocumentContentProducer(apiPath.getXmlDocument())));
    } else if (apiPath.isEmptyContent()) {
        //empty content
    } else {
        throw new IllegalArgumentException("No Form or Multipart entity for POST content-body");
    }

    return execute(httpPost, handler);
}

From source file:org.wso2.store.client.ArtifactPublisher.java

/**
 * Upload assets to ES/*from  w w  w.  j  a  v a  2s . com*/
 * POST asset details to asset upload REST API
 * If attribute is a physical file seek a file in a resources directory and upload as multipart attachment.
 * @param assetArr Array of assets
 * @param dir resource files directory
 */
private void uploadAssets(Asset[] assetArr, File dir) {

    HashMap<String, String> attrMap;
    MultipartEntityBuilder multiPartBuilder;
    List<String> fileAttributes;

    File imageFile;
    String responseJson;
    StringBuilder publisherUrlBuilder;

    String uploadUrl = hostUrl + ArtifactUploadClientConstants.PUBLISHER_URL + "/";
    HttpPost httpPost;
    CloseableHttpClient httpClient = clientBuilder.build();
    CloseableHttpResponse response = null;

    for (Asset asset : assetArr) {
        publisherUrlBuilder = new StringBuilder();
        if (asset.getId() != null) {
            publisherUrlBuilder.append(uploadUrl).append(asset.getId()).append("?type=")
                    .append(asset.getType());
        } else {
            publisherUrlBuilder.append(uploadUrl).append("?type=").append(asset.getType());
        }
        multiPartBuilder = MultipartEntityBuilder.create();
        multiPartBuilder.addTextBody("sessionId", sessionId);
        multiPartBuilder.addTextBody("asset", gson.toJson(asset));

        attrMap = asset.getAttributes();
        httpPost = new HttpPost(publisherUrlBuilder.toString());

        //get file type attributes list for asset type
        fileAttributes = rxtFileAttributesMap.get(asset.getType());
        for (String attrKey : attrMap.keySet()) {
            //check attribute one by one whether is it a file type
            if (fileAttributes != null && fileAttributes.contains(attrKey)) {
                imageFile = new File(dir + File.separator + ArtifactUploadClientConstants.RESOURCE_DIR_NAME
                        + File.separator + attrMap.get(attrKey));
                multiPartBuilder.addBinaryBody(attrKey, imageFile);
            }
        }
        httpPost.setEntity(multiPartBuilder.build());
        try {
            response = httpClient.execute(httpPost, httpContext);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
                log.info("Asset " + asset.getName() + " uploaded successfully");
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) {
                log.info("Asset " + asset.getName() + " updated successfully");
            } else {
                responseJson = EntityUtils.toString(response.getEntity());
                log.info("Asset " + asset.getName() + " not uploaded successfully " + responseJson);
            }
        } catch (IOException ex) {
            log.error("Asset Id:" + asset.getId() + " Name;" + asset.getName());
            log.error("Error in asset Upload", ex);
            log.debug("Asset upload fail:" + asset);
        } finally {
            IOUtils.closeQuietly(response);
        }
    }
    IOUtils.closeQuietly(response);
    IOUtils.closeQuietly(httpClient);
}

From source file:org.kaaproject.kaa.client.transport.DesktopHttpClient.java

@Override
public byte[] executeHttpRequest(String uri, LinkedHashMap<String, byte[]> entity, boolean verifyResponse)
        throws Exception { //NOSONAR
    byte[] responseDataRaw = null;
    method = new HttpPost(url + uri);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (String key : entity.keySet()) {
        builder.addBinaryBody(key, entity.get(key));
    }/*  ww  w  . ja  v a 2  s  .  c o m*/
    HttpEntity requestEntity = builder.build();
    method.setEntity(requestEntity);
    if (!Thread.currentThread().isInterrupted()) {
        LOG.debug("Executing request {}", method.getRequestLine());
        CloseableHttpResponse response = httpClient.execute(method);
        try {
            LOG.debug("Received {}", response.getStatusLine());
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                responseDataRaw = getResponseBody(response, verifyResponse);
            } else {
                throw new TransportException(status);
            }
        } finally {
            response.close();
            method = null;
        }
    } else {
        method = null;
        throw new InterruptedException();
    }

    return responseDataRaw;
}