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:org.duracloud.common.web.RestHttpHelper.java

public HttpResponse multipartFilePost(String url, File file) throws Exception {
    ContentType contentType = ContentType.MULTIPART_FORM_DATA;
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody(file.getName(), file, contentType, file.getName()).build();
    return multipartPost(url, reqEntity);
}

From source file:rogerthat.topdesk.bizz.Util.java

public static void uploadFile(String apiUrl, String apiKey, String unid, byte[] content, String contentType,
        String fileName) throws IOException, ParseException {
    URL url = new URL(apiUrl + "/api/incident/upload/" + unid);
    HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST, FetchOptions.Builder.withDeadline(30));
    log.info("Uploading attachment of size " + content.length / 1000 + "KB");
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addBinaryBody("filename", content,
                    org.apache.http.entity.ContentType.create(contentType), fileName);

    addMultipartBodyToRequest(multipartEntityBuilder.build(), request);
    String authHeader = "TOKEN id=\"" + apiKey + "\"";
    request.addHeader(new HTTPHeader("Authorization", authHeader));
    URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService();
    HTTPResponse response = urlFetch.fetch(request);
    int responseCode = response.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        String responseContent = getContent(response);
        throw new TopdeskApiException("Uploading image " + fileName + " failed with response code "
                + responseCode + "\nContent:" + responseContent);
    }/*w  w  w. j a v  a2  s  .  c om*/
}

From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java

@Override
public final <RS> Will<Response<RS>> post(String resource, MultiPartRequest request, Class<RS> clazz)
        throws RestEndpointIOException {
    HttpPost post = new HttpPost(spliceUrl(resource));

    try {/*  w  w w. ja  v a  2  s . co  m*/

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (MultiPartRequest.MultiPartSerialized<?> serializedPart : request.getSerializedRQs()) {
            Serializer serializer = getSupportedSerializer(serializedPart);
            builder.addPart(serializedPart.getPartName(),
                    new StringBody(new String(serializer.serialize(serializedPart.getRequest())),
                            ContentType.parse(serializer.getMimeType())));
        }

        for (MultiPartRequest.MultiPartBinary partBinaty : request.getBinaryRQs()) {
            builder.addPart(partBinaty.getPartName(), new ByteArrayBody(partBinaty.getData().read(),
                    ContentType.parse(partBinaty.getContentType()), partBinaty.getFilename()));
        }

        /* Here is some dirty hack to avoid problem with MultipartEntity and asynchronous http client
         *  Details can be found here: http://comments.gmane.org/gmane.comp.apache.httpclient.user/2426
         *
         *  The main idea is to replace MultipartEntity with NByteArrayEntity once first
         * doesn't support #getContent method
         *  which is required for async client implementation. So, we are copying response
         *  body as byte array to NByteArrayEntity to
         *  leave it unmodified.
         *
         *  Alse we need to add boundary value to content type header. Details are here:
         *  http://en.wikipedia.org/wiki/Delimiter#Content_boundary
         *  MultipartEntity generates correct header by yourself, but we need to put it
         *  manually once we replaced entity type to NByteArrayEntity
         */
        String boundary = "-------------" + UUID.randomUUID().toString();
        builder.setBoundary(boundary);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        builder.build().writeTo(baos);

        post.setEntity(new NByteArrayEntity(baos.toByteArray(), ContentType.MULTIPART_FORM_DATA));
        post.setHeader("Content-Type", "multipart/form-data;boundary=" + boundary);

    } catch (Exception e) {
        throw new RestEndpointIOException("Unable to build post multipart request", e);
    }
    return executeInternal(post, new ClassConverterCallback<RS>(serializers, clazz));
}

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

private HttpEntity createUploadEntity(final File archive) {
    return MultipartEntityBuilder.create().setContentType(ContentType.MULTIPART_FORM_DATA)
            .setBoundary(BOUNDARY_PARAM).addTextBody("test1", BOUNDARY_PARAM)
            .addTextBody("test2", BOUNDARY_PARAM)
            .addBinaryBody("file", archive, ContentType.APPLICATION_OCTET_STREAM, DEPLOYMENT_NAME).build();
}

From source file:org.nuxeo.ecm.core.opencmis.impl.CmisSuiteSession2.java

protected HttpEntity getCreateDocumentHttpEntity(File file) {
    FormBodyPart cmisactionPart = FormBodyPartBuilder
            .create("cmisaction", new StringBody("createDocument", ContentType.TEXT_PLAIN)).build();
    FormBodyPart contentPart = FormBodyPartBuilder
            .create("content", new FileBody(file, ContentType.TEXT_PLAIN, "testfile.txt")).build();
    HttpEntity entity = MultipartEntityBuilder.create().addPart(cmisactionPart)
            .addTextBody("propertyId[0]", "cmis:name").addTextBody("propertyValue[0]", "testfile01")
            .addTextBody("propertyId[1]", "cmis:objectTypeId").addTextBody("propertyValue[1]", "File")
            .addPart(contentPart).build();
    return entity;
}

From source file:com.alibaba.shared.django.DjangoClient.java

protected void uploadFileChunks(InputStream is, int maxChunkSize, final String fileId, final int sequence,
        final String fillename, List<DjangoMessage> holder) throws IOException, URISyntaxException {
    final MessageDigest digest = Digests.defaultDigest();
    byte[] buf = new byte[8000];
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int len = is.read(buf), processCount = len;
    while (len >= 0 && processCount < maxChunkSize) {
        baos.write(buf, 0, len);//from  w ww. j a va 2 s. c  o m
        digest.update(buf, 0, len);
        processCount += len;
        if (maxChunkSize <= processCount) {
            break;
        }
        len = is.read(buf);
    }
    if (processCount > 0) {
        holder.add(executeRequest(new Supplier<HttpUriRequest>() {
            public HttpUriRequest get() {
                MultipartEntityBuilder meb = MultipartEntityBuilder.create();
                meb.addTextBody(ACCESS_TOKEN_KEY, accessToken()).addTextBody("fileId", fileId)
                        .addTextBody("sequence", String.valueOf(sequence))
                        .addTextBody("md5", Digests.toHexDigest(digest.digest())).addBinaryBody(FILE_KEY,
                                baos.toByteArray(), ContentType.APPLICATION_OCTET_STREAM, fillename);
                HttpPost post = new HttpPost(chunkUrl);
                post.setEntity(meb.build());
                return post;
            }
        }));
        uploadFileChunks(is, maxChunkSize, fileId, sequence + 1, fillename, holder);
    }
}

From source file:org.duracloud.common.web.RestHttpHelper.java

public HttpResponse multipartFileStreamPost(String url, String fileName, InputStream stream) throws Exception {
    ContentType contentType = ContentType.MULTIPART_FORM_DATA;
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody(fileName, stream, contentType, fileName).build();
    return multipartPost(url, reqEntity);
}

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

protected void uploadAppDefinition(HttpServletResponse httpResponse, ServerConfig serverConfig, String name,
        byte[] bytes) throws IOException {
    HttpPost post = new HttpPost(clientUtil.getServerUrl(serverConfig, APP_IMPORT_AND_PUBLISH_URL));
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody("file", bytes, ContentType.APPLICATION_OCTET_STREAM, name).build();
    post.setEntity(reqEntity);/*from w w w. j  av  a 2s  .  c o m*/
    clientUtil.execute(post, httpResponse, serverConfig);
}

From source file:org.wso2.appcloud.integration.test.utils.clients.ApplicationClient.java

public void createNewApplication(String applicationName, String runtime, String appTypeName,
        String applicationRevision, String applicationDescription, String uploadedFileName,
        String runtimeProperties, String tags, File uploadArtifact, boolean isNewVersion,
        String applicationContext, String conSpec, boolean setDefaultVersion, String appCreationMethod,
        String gitRepoUrl, String gitRepoBranch, String projectRoot) throws AppCloudIntegrationTestException {

    HttpClient httpclient = null;//from   w w w.ja  v a  2s.  c om
    org.apache.http.HttpResponse response = null;
    int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();
        HttpPost httppost = new HttpPost(this.endpoint);
        httppost.setConfig(requestConfig);

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

        builder.addPart(PARAM_NAME_ACTION, new StringBody(CREATE_APPLICATION_ACTION, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APP_CREATION_METHOD,
                new StringBody(appCreationMethod, ContentType.TEXT_PLAIN));
        if (GITHUB.equals(appCreationMethod)) {
            builder.addPart(PARAM_NAME_GIT_REPO_URL, new StringBody(gitRepoUrl, ContentType.TEXT_PLAIN));
            builder.addPart(PARAM_NAME_GIT_REPO_BRANCH, new StringBody(gitRepoBranch, ContentType.TEXT_PLAIN));
            builder.addPart(PARAM_NAME_PROJECT_ROOT, new StringBody(projectRoot, ContentType.TEXT_PLAIN));
        } else if (DEFAULT.equals(appCreationMethod)) {
            builder.addPart(PARAM_NAME_FILE_UPLOAD, new FileBody(uploadArtifact));
            builder.addPart(PARAM_NAME_UPLOADED_FILE_NAME,
                    new StringBody(uploadedFileName, ContentType.TEXT_PLAIN));
            builder.addPart(PARAM_NAME_IS_FILE_ATTACHED,
                    new StringBody(Boolean.TRUE.toString(), ContentType.TEXT_PLAIN));//Setting true to send the file in request
        }
        builder.addPart(PARAM_NAME_CONTAINER_SPEC, new StringBody(conSpec, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_NAME, new StringBody(applicationName, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_DESCRIPTION,
                new StringBody(applicationDescription, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_RUNTIME, new StringBody(runtime, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APP_TYPE_NAME, new StringBody(appTypeName, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APP_CONTEXT, new StringBody(applicationContext, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_REVISION,
                new StringBody(applicationRevision, ContentType.TEXT_PLAIN));

        builder.addPart(PARAM_NAME_PROPERTIES, new StringBody(runtimeProperties, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_TAGS, new StringBody(tags, ContentType.TEXT_PLAIN));

        builder.addPart(PARAM_NAME_IS_NEW_VERSION,
                new StringBody(Boolean.toString(isNewVersion), ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_SET_DEFAULT_VERSION,
                new StringBody(Boolean.toString(setDefaultVersion), ContentType.TEXT_PLAIN));

        httppost.setEntity(builder.build());
        httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE));
        response = httpclient.execute(httppost);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity());
            throw new AppCloudIntegrationTestException("CreateNewApplication failed " + result);
        }

    } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) {
        // In most of the cases, even though connection is timed out, actual activity is completed.
        // If application is not created, in next test case, it will be identified.
        log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1);
    } catch (IOException e) {
        log.error("Failed to invoke application creation API.", e);
        throw new AppCloudIntegrationTestException("Failed to invoke application creation API.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(httpclient);
    }
}

From source file:org.codelibs.fess.crawler.extractor.impl.ApiExtractor.java

@Override
public ExtractData getText(InputStream in, Map<String, String> params) {
    if (logger.isDebugEnabled()) {
        logger.debug("Accessing " + url);
    }//w  ww . j a  v  a2s  . c o m

    // start
    AccessTimeoutTarget accessTimeoutTarget = null;
    TimeoutTask accessTimeoutTask = null;
    if (accessTimeout != null) {
        accessTimeoutTarget = new AccessTimeoutTarget(Thread.currentThread());
        accessTimeoutTask = TimeoutManager.getInstance().addTimeoutTarget(accessTimeoutTarget,
                accessTimeout.intValue(), false);
    }

    ExtractData data = new ExtractData();
    HttpPost httpPost = new HttpPost(url);
    HttpEntity postEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .setCharset(Charset.forName("UTF-8")).addBinaryBody("filedata", in).build();
    httpPost.setEntity(postEntity);

    try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
        if (response.getStatusLine().getStatusCode() != Constants.OK_STATUS_CODE) {
            logger.error(
                    "Failed to access " + url + ", code: " + response.getStatusLine().getStatusCode() + ".");
            return null;
        }

        data.setContent(EntityUtils.toString(response.getEntity(), Charsets.UTF_8));
        Header[] headers = response.getAllHeaders();
        for (final Header header : headers) {
            data.putValue(header.getName(), header.getValue());
        }
    } catch (IOException e) {
        throw new ExtractException(e);
    } finally {
        if (accessTimeout != null) {
            accessTimeoutTarget.stop();
            if (!accessTimeoutTask.isCanceled()) {
                accessTimeoutTask.cancel();
            }
        }
    }
    return data;
}