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:utils.APIImporter.java

private static void addAPIImage(String folderPath, String accessToken, String uuid) {
    File apiFolder = new File(folderPath);
    File[] fileArray = apiFolder.listFiles();
    if (fileArray != null) {
        for (File file : fileArray) {
            String fileName = file.getName();
            String imageName = fileName.substring(0, fileName.indexOf("."));
            if (imageName.equalsIgnoreCase(ImportExportConstants.IMG_NAME)) {
                File imageFile = new File(folderPath + ImportExportConstants.ZIP_FILE_SEPARATOR + fileName);
                MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
                multipartEntityBuilder.addBinaryBody(ImportExportConstants.MULTIPART_FILE, imageFile);
                HttpEntity entity = multipartEntityBuilder.build();
                String url = config.getPublisherUrl() + "apis/" + uuid + "/thumbnail";
                CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
                HttpPost request = new HttpPost(url);
                request.setHeader(HttpHeaders.AUTHORIZATION,
                        ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken);
                request.setEntity(entity);
                try {
                    client.execute(request);
                } catch (IOException e) {
                    errorMsg = "Error occurred while publishing the API thumbnail";
                    log.error(errorMsg, e);
                }/* w w  w  . ja  v a  2 s  . c  o  m*/
                break;
            }
        }
    }
}

From source file:utils.APIImporter.java

/**
 * update the content of a document of the API been sent
 * @param folderPath folder path to the imported API
 * @param uuid uuid of the API/*from   w  ww . ja  va  2  s.c  o m*/
 * @param response payload for the publishing document
 * @param accessToken access token
 */
private static void addDocumentContent(String folderPath, String uuid, String response, String accessToken) {
    String documentId = ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_ID);
    String sourceType = ImportExportUtils.readJsonValues(response, ImportExportConstants.SOURCE_TYPE);
    String documentName = ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME);
    String directoryName;
    //setting directory name depending on the document source type
    if (sourceType.equals(ImportExportConstants.INLINE_DOC_TYPE)) {
        directoryName = ImportExportConstants.INLINE_DOCUMENT_DIRECTORY;
    } else {
        directoryName = ImportExportConstants.FILE_DOCUMENT_DIRECTORY;
    }
    //getting document content
    String documentContentPath = folderPath + ImportExportConstants.DIRECTORY_SEPARATOR
            + ImportExportConstants.DOCUMENT_DIRECTORY + ImportExportConstants.DIRECTORY_SEPARATOR
            + directoryName + ImportExportConstants.DIRECTORY_SEPARATOR + documentName;
    File content = new File(documentContentPath);
    HttpEntity entity = null;
    if (sourceType.equals(ImportExportConstants.FILE_DOC_TYPE)) {
        //adding file type content
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addBinaryBody(ImportExportConstants.MULTIPART_FILE, content);
        entity = multipartEntityBuilder.build();
    } else {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(content));
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();
            }
            String inlineContent = sb.toString();
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addTextBody(ImportExportConstants.MULTIPART_Inline, inlineContent,
                    ContentType.APPLICATION_OCTET_STREAM);
            entity = multipartEntityBuilder.build();
        } catch (IOException e) {
            errorMsg = "error occurred while retrieving content of document "
                    + ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME);
            log.error(errorMsg, e);
        } finally {
            IOUtils.closeQuietly(br);
        }
    }
    String url = config.getPublisherUrl() + "apis/" + uuid + "/documents/" + documentId + "/content";
    CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
    HttpPost request = new HttpPost(url);
    request.setHeader(HttpHeaders.AUTHORIZATION,
            ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken);
    request.setEntity(entity);
    try {
        client.execute(request);
    } catch (IOException e) {
        errorMsg = "error occurred while uploading the content of document "
                + ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME);
        log.error(errorMsg, e);
    }
}

From source file:co.aurasphere.botmill.fb.internal.util.network.FbBotMillNetworkController.java

/**
 * POSTs a message as a JSON string to Facebook.
 *
 * @param recipient//from w ww . j ava 2 s .  c  om
 *            the recipient
 * @param type
 *            the type
 * @param file
 *            the file
 */
public static void postFormDataMessage(String recipient, AttachmentType type, File file) {
    String pageToken = FbBotMillContext.getInstance().getPageToken();
    // If the page token is invalid, returns.
    if (!validatePageToken(pageToken)) {
        return;
    }

    // TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO)
    HttpPost post = new HttpPost(FbBotMillNetworkConstants.FACEBOOK_BASE_URL
            + FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken);

    FileBody filedata = new FileBody(file);
    StringBody recipientPart = new StringBody("{\"id\":\"" + recipient + "\"}",
            ContentType.MULTIPART_FORM_DATA);
    StringBody messagePart = new StringBody(
            "{\"attachment\":{\"type\":\"" + type.name().toLowerCase() + "\", \"payload\":{}}}",
            ContentType.MULTIPART_FORM_DATA);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.STRICT);
    builder.addPart("recipient", recipientPart);
    builder.addPart("message", messagePart);
    // builder.addPart("filedata", filedata);
    builder.addBinaryBody("filedata", file);
    builder.setContentType(ContentType.MULTIPART_FORM_DATA);

    // builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");
    HttpEntity entity = builder.build();
    post.setEntity(entity);

    // Logs the raw JSON for debug purposes.
    BufferedReader br;
    // post.addHeader("Content-Type", "multipart/form-data");
    try {
        // br = new BufferedReader(new InputStreamReader(
        // ())));

        Header[] allHeaders = post.getAllHeaders();
        for (Header h : allHeaders) {

            logger.debug("Header {} ->  {}", h.getName(), h.getValue());
        }
        // String output = br.readLine();

    } catch (Exception e) {
        e.printStackTrace();
    }

    // postInternal(post);
}

From source file:com.oakhole.voa.utils.HttpClientUtils.java

/**
 * post/*from  w  w  w . j a v  a2  s.  c o m*/
 *
 * @param uri
 * @param map
 * @return
 */
public static String post(String uri, Map<String, Object> map) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(uri);
    HttpEntity httpEntity = null;
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    for (String key : map.keySet()) {
        Object value = map.get(key);
        if (value != null && value instanceof String) {
            String param = (String) value;
            multipartEntityBuilder.addTextBody(key, param, ContentType.create("text/plain", CHARSET));
        }
        if (value != null && value instanceof File) {
            multipartEntityBuilder.addBinaryBody(key, (File) value);
        }
    }
    try {
        httpPost.setEntity(multipartEntityBuilder.build());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            httpEntity = httpResponse.getEntity();
        }
    } catch (IOException e) {
        logger.error(":{}", e.getMessage());
    }
    try {
        return EntityUtils.toString(httpEntity, CHARSET);
    } catch (IOException e) {
        logger.error(":{}", e.getMessage());
    }
    return "";
}

From source file:co.aurasphere.botmill.fb.internal.util.network.NetworkUtils.java

/**
 * POSTs a message as a JSON string to Facebook.
 *
 * @param recipient//from   www  .j  a  v a  2  s .  c  om
 *            the recipient
 * @param type
 *            the type
 * @param file
 *            the file
 */
public static void postFormDataMessage(String recipient, AttachmentType type, File file) {
    String pageToken = FbBotMillContext.getInstance().getPageToken();
    // If the page token is invalid, returns.
    if (!validatePageToken(pageToken)) {
        return;
    }

    // TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO)
    HttpPost post = new HttpPost(FbBotMillNetworkConstants.FACEBOOK_BASE_URL
            + FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken);

    FileBody filedata = new FileBody(file);
    StringBody recipientPart = new StringBody("{\"id\":\"" + recipient + "\"}",
            ContentType.MULTIPART_FORM_DATA);
    StringBody messagePart = new StringBody(
            "{\"attachment\":{\"type\":\"" + type.name().toLowerCase() + "\", \"payload\":{}}}",
            ContentType.MULTIPART_FORM_DATA);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.STRICT);
    builder.addPart("recipient", recipientPart);
    builder.addPart("message", messagePart);
    // builder.addPart("filedata", filedata);
    builder.addBinaryBody("filedata", file);
    builder.setContentType(ContentType.MULTIPART_FORM_DATA);

    // builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");
    HttpEntity entity = builder.build();
    post.setEntity(entity);

    // Logs the raw JSON for debug purposes.
    BufferedReader br;
    // post.addHeader("Content-Type", "multipart/form-data");
    try {
        // br = new BufferedReader(new InputStreamReader(
        // ())));

        Header[] allHeaders = post.getAllHeaders();
        for (Header h : allHeaders) {

            logger.debug("Header {} ->  {}", h.getName(), h.getValue());
        }
        // String output = br.readLine();

    } catch (Exception e) {
        e.printStackTrace();
    }

    send(post);
}

From source file:org.brunocvcunha.jiphy.requests.JiphyUploadRequest.java

/**
 * Creates required multipart entity with the image binary
 * //  ww  w  . j  a v  a  2s  .co m
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException
 * @throws IOException
 */
protected HttpEntity createMultipartEntity() throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("file", file);

    HttpEntity entity = builder.build();
    return entity;
}

From source file:org.metaeffekt.dcc.agent.UnitBasedEndpointUriBuilder.java

public HttpUriRequest buildHttpUriRequest(Commands command, Id<DeploymentId> deploymentId, Id<UnitId> unitId,
        Id<PackageId> packageId, Map<String, byte[]> executionProperties) {
    Validate.isTrue(executionProperties != null && !executionProperties.isEmpty());

    StringBuilder sb = new StringBuilder("/");
    sb.append(PATH_ROOT).append("/");
    sb.append(deploymentId).append("/");
    sb.append("packages").append("/").append(packageId).append("/");
    sb.append("units").append("/").append(unitId).append("/");
    sb.append(command);/*from  w  w  w.jav a2s . co m*/
    String path = sb.toString();

    URIBuilder uriBuilder = createUriBuilder();
    uriBuilder.setPath(path);
    URI uri;
    try {
        uri = uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    HttpPut put = new HttpPut(uri);

    final MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
    for (Map.Entry<String, byte[]> entry : executionProperties.entrySet()) {
        multipartBuilder.addBinaryBody(entry.getKey(), entry.getValue());
    }

    put.setEntity(multipartBuilder.build());
    if (requestConfig != null) {
        put.setConfig(requestConfig);
    }
    return put;
}

From source file:com.github.fabienbarbero.flickr.api.CommandArguments.java

public HttpEntity getBody(Map<String, String> additionalParameters) {
    MultipartEntityBuilder entity = MultipartEntityBuilder.create();

    for (Parameter param : params) {
        if (!param.internal) {
            if (param.value instanceof File) {
                entity.addBinaryBody(param.key, (File) param.value);
            } else if (param.value instanceof String) {
                entity.addTextBody(param.key, (String) param.value, CT_TEXT);
            }//  ww  w .j a  va 2 s  . c  om
        }
    }
    for (Map.Entry<String, String> entry : additionalParameters.entrySet()) {
        entity.addTextBody(entry.getKey(), entry.getValue(), CT_TEXT);
    }

    return entity.build();
}

From source file:cc.sferalabs.libs.telegram.bot.api.TelegramBot.java

/**
 * Sends a request to the server.//www  . j  av  a 2s  .  c o m
 * 
 * @param <T>
 *            the class to cast the returned value to
 * @param request
 *            the request to be sent
 * @param timeout
 *            the read timeout value (in milliseconds) to be used for server
 *            response. A timeout of zero is interpreted as an infinite
 *            timeout
 * @return the JSON object representing the value of the field "result" of
 *         the response JSON object cast to the specified type parameter
 * @throws ResponseError
 *             if the server returned an error response, i.e. the value of
 *             the field "ok" of the response JSON object is {@code false}
 * @throws ParseException
 *             if an error occurs while parsing the server response
 * @throws IOException
 *             if an I/O exception occurs
 */
@SuppressWarnings("unchecked")
public <T> T sendRequest(Request request, int timeout) throws IOException, ParseException, ResponseError {
    HttpURLConnection connection = null;
    try {
        URL url = buildUrl(request);
        log.debug("Performing request: {}", url);
        connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(timeout);

        if (request instanceof SendFileRequest) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            Path filePath = ((SendFileRequest) request).getFilePath();
            builder.addBinaryBody(((SendFileRequest) request).getFileParamName(), filePath.toFile());
            HttpEntity multipart = builder.build();

            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", multipart.getContentType().getValue());
            connection.setRequestProperty("Content-Length", "" + multipart.getContentLength());

            try (OutputStream out = connection.getOutputStream()) {
                multipart.writeTo(out);
            }
        } else {
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Length", "0");
        }

        boolean httpOk = connection.getResponseCode() == HttpURLConnection.HTTP_OK;
        try (InputStream in = httpOk ? connection.getInputStream() : connection.getErrorStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
            JSONObject resp = (JSONObject) parser.parse(br);
            log.debug("Response: {}", resp);

            boolean ok = (boolean) resp.get("ok");
            if (!ok) {
                String description = (String) resp.get("description");
                if (description == null) {
                    description = "ok=false";
                }
                throw new ResponseError(description);
            }
            return (T) resp.get("result");
        }
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.king.ess.gsa.GSAFeedForm.java

/**
 * It sends XML with feeds to GSA using proper form:
 * //from w  ww .  j av  a  2  s . com
 * @param xmlDocument  GSADocumentFormatter containing XML Document information
 * 
 * @return Was posted Ok?
 */
public boolean sendForm(GSADocumentFormatter xmlDocument) {
    boolean bSent = false;

    HttpClient client = HttpClientBuilder.create().build();

    try {
        HttpPost postPageRequest;
        postPageRequest = new HttpPost(this.gsaServer);
        InputStream is = xmlDocument.writeToInputStream();

        // Add Form parameters
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        builder.addTextBody(FEEDTYPE_PARAM, xmlDocument.getFeedType(), ContentType.TEXT_PLAIN);
        builder.addTextBody(DATASOURCE_PARAM, xmlDocument.getDatasource(), ContentType.TEXT_PLAIN);
        builder.addBinaryBody(XMLFILE_PARAM, is);
        HttpEntity multipartEntity = builder.build();

        postPageRequest.setEntity(multipartEntity);

        HttpResponse postPageResponse = client.execute(postPageRequest);
        int status = postPageResponse.getStatusLine().getStatusCode();

        if (!(bSent = (status == 200)))
            log.error("GitHub API (" + this.gsaServer + ") returned " + status);
        else
            log.info("XML For datasource '" + xmlDocument.getDatasource() + "' and FeedType '"
                    + xmlDocument.getFeedType() + "' was posted successfully to GSA!!");

    } catch (Exception e) {
        log.error("Exception " + e.getMessage() + " in HTTP request " + this.gsaServer);
    }
    return bSent;
}