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

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

Introduction

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

Prototype

public static MultipartEntityBuilder create() 

Source Link

Usage

From source file:com.android.tools.idea.diagnostics.crash.GoogleCrash.java

@NotNull
private static MultipartEntityBuilder newMultipartEntityBuilderWithKv(@NotNull Map<String, String> kv) {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    kv.forEach(builder::addTextBody);/* www. ja va 2  s.  c  o  m*/
    return builder;
}

From source file:com.ibm.streamsx.topology.internal.context.AnalyticsServiceStreamsContext.java

private BigInteger postJob(CloseableHttpClient httpClient, JSONObject credentials, File bundle,
        JSONObject submitConfig) throws ClientProtocolException, IOException {

    String url = getSubmitURL(credentials, bundle);

    HttpPost postJobWithConfig = new HttpPost(url);
    postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());

    FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM);
    StringBody configBody = new StringBody(submitConfig.serialize(), ContentType.APPLICATION_JSON);

    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bundleBody)
            .addPart("json", configBody).build();

    postJobWithConfig.setEntity(reqEntity);

    JSONObject jsonResponse = getJsonResponse(httpClient, postJobWithConfig);

    Topology.STREAMS_LOGGER.info("Streaming Analytics Service submit job response:" + jsonResponse.serialize());

    Object jobId = jsonResponse.get("jobId");
    if (jobId == null)
        return BigInteger.valueOf(-1);
    return new BigInteger(jobId.toString());
}

From source file:org.apache.nifi.api.client.impl.AbstractNiFiAPIClient.java

public <U extends Entity> Object post(Class<? extends ApplicationResource> resourceClass, Method nifiApiMethod,
        U u, Map<String, String> pathParams, InputStream payloadData) {

    StringBuilder stringBuilder = new StringBuilder(this.baseUrl);
    stringBuilder.append(resourceClass.getAnnotation(Path.class).value());
    stringBuilder.append("/");
    stringBuilder.append(nifiApiMethod.getAnnotation(Path.class).value());

    String fullRequest = replaceUriWithPathParams(stringBuilder.toString(), pathParams);

    HttpPost request = new HttpPost(fullRequest);

    StringBuffer result = new StringBuffer();
    try {//from w  w w . java 2  s . c om

        //Set the Accept and Content-Type headers appropriately.
        String produces = nifiApiMethod.getAnnotation(Produces.class).value()[0];
        String consumes = nifiApiMethod.getAnnotation(Consumes.class).value()[0];

        //Set POST request payload. Can only upload either Inputstream OR Object currently.
        if (u != null || payloadData != null) {
            if (u != null) {
                StringEntity input = new StringEntity(mapper.writeValueAsString(u));
                request.setEntity(input);
                request.setHeader("Content-type", consumes);
            } else {
                InputStreamEntity inputStreamEntity = new InputStreamEntity(payloadData);
                request.setEntity(inputStreamEntity);

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                //builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);

                // This attaches the file to the POST:
                builder.addBinaryBody("template", payloadData, ContentType.APPLICATION_OCTET_STREAM,
                        "SomethingTest.xml");

                HttpEntity multipart = builder.build();
                request.setEntity(multipart);
            }
        }

        request.addHeader("Accept", produces);

        HttpResponse response = client.execute(request);

        //Examine the return type and handle that data appropriately.
        Header rCT = response.getHeaders("Content-Type")[0];
        if (rCT.getValue().equalsIgnoreCase("application/xml")) {
            //                TemplateDTO templateDTO = TemplateDeserializer.deserialize(response.getEntity().getContent());
            //                return templateDTO;
            return null;
        } else {
            return mapper.readValue(response.getEntity().getContent(),
                    nifiApiMethod.getAnnotation(ApiOperation.class).response());
        }

    } catch (Exception ex) {
        logger.error("Unable to complete HTTP POST due to {}", ex.getMessage());
        return null;
    }
}

From source file:io.swagger.client.api.DefaultApi.java

/**
 * Channel sync availability/*from ww  w  .j  a v a  2s  . co  m*/
 * Checks if a list of client channel identifiers are currently broadcasting synchronizable content
 * @param authorization Authorization token (&#39;Bearer &lt;token&gt;&#39;)
 * @param channelIdList List of client channel IDs as a comma separated list
 * @param acceptLanguage Client locale, as &lt;language&gt;-&lt;country&gt;
 * @param contentType application/json
 * @return List<ChannelStatus>
 */
public List<ChannelStatus> getReadyChannels(String authorization, List<String> channelIdList,
        String acceptLanguage, String contentType) throws ApiException {
    Object localVarPostBody = null;

    // verify the required parameter 'authorization' is set
    if (authorization == null) {
        throw new ApiException(400,
                "Missing the required parameter 'authorization' when calling getReadyChannels");
    }

    // verify the required parameter 'channelIdList' is set
    if (channelIdList == null) {
        throw new ApiException(400,
                "Missing the required parameter 'channelIdList' when calling getReadyChannels");
    }

    // create path and map variables
    String localVarPath = "/channels/{channel_id_list}/ready".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "channel_id_list" + "\\}", apiInvoker.escapeString(channelIdList.toString()));

    // query params
    List<Pair> localVarQueryParams = new ArrayList<Pair>();
    // header params
    Map<String, String> localVarHeaderParams = new HashMap<String, String>();
    // form params
    Map<String, String> localVarFormParams = new HashMap<String, String>();

    localVarHeaderParams.put("Authorization", ApiInvoker.parameterToString(authorization));
    localVarHeaderParams.put("Accept-Language", ApiInvoker.parameterToString(acceptLanguage));
    localVarHeaderParams.put("Content-Type", ApiInvoker.parameterToString(contentType));

    String[] localVarContentTypes = { "application/json" };
    String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json";

    if (localVarContentType.startsWith("multipart/form-data")) {
        // file uploading
        MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();

        localVarPostBody = localVarBuilder.build();
    } else {
        // normal form params
    }

    try {
        String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "GET", localVarQueryParams,
                localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType);
        if (localVarResponse != null) {
            return (List<ChannelStatus>) ApiInvoker.deserialize(localVarResponse, "array", ChannelStatus.class);
        } else {
            return null;
        }
    } catch (ApiException ex) {
        throw ex;
    }
}

From source file:com.scoopit.weedfs.client.WeedFSClientImpl.java

private int write(WeedFSFile file, Location location, File fileToUpload, byte[] dataToUpload,
        InputStream inputToUpload, String fileName) throws IOException, WeedFSException {
    StringBuilder url = new StringBuilder();
    if (!location.publicUrl.contains("http")) {
        url.append("http://");
    }/*from w  w  w. j a v a  2 s  .  c  om*/
    url.append(location.publicUrl);
    url.append('/');
    url.append(file.fid);

    if (file.version > 0) {
        url.append('_');
        url.append(file.version);
    }

    HttpPost post = new HttpPost(url.toString());

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    if (fileToUpload != null) {
        if (fileName == null) {
            fileName = fileToUpload.getName();
        }
        multipartEntityBuilder.addBinaryBody("file", fileToUpload, ContentType.APPLICATION_OCTET_STREAM,
                sanitizeFileName(fileName));
    } else if (dataToUpload != null) {
        multipartEntityBuilder.addBinaryBody("file", dataToUpload, ContentType.APPLICATION_OCTET_STREAM,
                sanitizeFileName(fileName));
    } else {
        multipartEntityBuilder.addBinaryBody("file", inputToUpload, ContentType.APPLICATION_OCTET_STREAM,
                sanitizeFileName(fileName));
    }
    post.setEntity(multipartEntityBuilder.build());

    try {
        HttpResponse response = httpClient.execute(post);

        String content = getContentOrNull(response);
        ObjectMapper mapper = new ObjectMapper();
        try {
            WriteResult result = mapper.readValue(content, WriteResult.class);

            if (result.error != null) {
                throw new WeedFSException(result.error);
            }

            return result.size;
        } catch (JsonMappingException | JsonParseException e) {
            throw new WeedFSException("Unable to parse JSON from weed-fs from: " + content, e);
        }
    } finally {
        post.abort();
    }
}

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

/**
 * Execute the post request.//  www  . j  a v a2 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:com.ibm.sbt.services.client.Request.java

/**
 * Method to retrieve the request body./*from  w  ww .  ja va 2s.  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.nuxeo.ecm.core.opencmis.impl.CmisSuiteSession2.java

protected HttpEntity getCheckInHttpEntity(File file) {
    FormBodyPart cmisactionPart = FormBodyPartBuilder
            .create("cmisaction", new StringBody("checkIn", ContentType.TEXT_PLAIN)).build();
    FormBodyPart contentPart = FormBodyPartBuilder
            .create("content", new FileBody(file, ContentType.TEXT_PLAIN, "testfile.txt")).build();
    HttpEntity entity = MultipartEntityBuilder.create().addPart(cmisactionPart).addPart(contentPart).build();
    return entity;
}

From source file:com.activiti.service.activiti.AppService.java

protected void uploadNewAppDefinitionVersion(HttpServletResponse httpResponse, ServerConfig serverConfig,
        String name, byte[] bytes, String appId) throws IOException {
    URIBuilder builder = clientUtil/* ww w  . ja  v  a2 s  .c o  m*/
            .createUriBuilder(MessageFormat.format(APP_IMPORT_AND_PUBLISH_AS_NEW_VERSION_URL, appId));
    HttpPost post = new HttpPost(clientUtil.getServerUrl(serverConfig, builder));
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody("file", bytes, ContentType.APPLICATION_OCTET_STREAM, name).build();
    post.setEntity(reqEntity);
    clientUtil.execute(post, httpResponse, serverConfig);
}