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:io.swagger.client.api.CameraApi.java

/**
* Activate autofocus on specified area (coordinates)
* 
 * @param x /* w ww.j  av  a2 s.  c o  m*/
 * @param y 
 * @return void
*/
public void autofocusPost(Integer x, Integer y)
        throws TimeoutException, ExecutionException, InterruptedException, ApiException {
    Object postBody = null;

    // verify the required parameter 'x' is set
    if (x == null) {
        VolleyError error = new VolleyError("Missing the required parameter 'x' when calling autofocusPost",
                new ApiException(400, "Missing the required parameter 'x' when calling autofocusPost"));
    }

    // verify the required parameter 'y' is set
    if (y == null) {
        VolleyError error = new VolleyError("Missing the required parameter 'y' when calling autofocusPost",
                new ApiException(400, "Missing the required parameter 'y' when calling autofocusPost"));
    }

    // create path and map variables
    String path = "/autofocus".replaceAll("\\{format\\}", "json");

    // query params
    List<Pair> queryParams = new ArrayList<Pair>();
    // header params
    Map<String, String> headerParams = new HashMap<String, String>();
    // form params
    Map<String, String> formParams = new HashMap<String, String>();

    queryParams.addAll(ApiInvoker.parameterToPairs("", "x", x));
    queryParams.addAll(ApiInvoker.parameterToPairs("", "y", y));

    String[] contentTypes = {

    };
    String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

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

        HttpEntity httpEntity = localVarBuilder.build();
        postBody = httpEntity;
    } else {
        // normal form params
    }

    String[] authNames = new String[] {};

    try {
        String localVarResponse = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody,
                headerParams, formParams, contentType, authNames);
        if (localVarResponse != null) {
            return;
        } else {
            return;
        }
    } catch (ApiException ex) {
        throw ex;
    } catch (InterruptedException ex) {
        throw ex;
    } catch (ExecutionException ex) {
        if (ex.getCause() instanceof VolleyError) {
            VolleyError volleyError = (VolleyError) ex.getCause();
            if (volleyError.networkResponse != null) {
                throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage());
            }
        }
        throw ex;
    } catch (TimeoutException ex) {
        throw ex;
    }
}

From source file:org.apache.syncope.installer.utilities.HttpUtils.java

public String postWithDigestAuth(final String url, final String file) {
    String responseBodyAsString = "";
    try (CloseableHttpResponse response = httpClient.execute(targetHost,
            httpPost(url, MultipartEntityBuilder.create().addPart("bin", new FileBody(new File(file))).build()),
            setAuth(targetHost, new DigestScheme()))) {
        responseBodyAsString = IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8"));
        handler.logOutput("Http status: " + response.getStatusLine().getStatusCode(), true);
        InstallLog.getInstance().info("Http status: " + response.getStatusLine().getStatusCode());
    } catch (IOException e) {
        final String messageError = "Error calling " + url + ": " + e.getMessage();
        handler.emitError(messageError, messageError);
        InstallLog.getInstance().error(messageError);
    }/*from   w w  w .  java2 s  .c o m*/

    return responseBodyAsString;
}

From source file:org.olat.test.rest.RepositoryRestClient.java

public CourseVO deployCourse(File archive, String resourcename, String displayname)
        throws URISyntaxException, IOException {

    RestConnection conn = new RestConnection(deploymentUrl);
    assertTrue(conn.login(username, password));

    URI request = UriBuilder.fromUri(deploymentUrl.toURI()).path("restapi").path("repo/courses").build();
    HttpPost method = conn.createPost(request, MediaType.APPLICATION_JSON);
    String softKey = UUID.randomUUID().toString();
    HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("file", archive, ContentType.APPLICATION_OCTET_STREAM, archive.getName())
            .addTextBody("filename", archive.getName()).addTextBody("resourcename", resourcename)
            .addTextBody("displayname", displayname).addTextBody("access", "3").addTextBody("softkey", softKey)
            .build();//from  w w  w. ja  v  a2  s. com
    method.setEntity(entity);

    HttpResponse response = conn.execute(method);
    assertTrue(
            response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201);

    CourseVO vo = conn.parse(response, CourseVO.class);
    assertNotNull(vo);
    assertNotNull(vo.getRepoEntryKey());
    assertNotNull(vo.getKey());
    return vo;
}

From source file:com.ibm.streamsx.topology.internal.streaminganalytics.RestUtils.java

/**
 * Submit an application bundle to execute as a job.
 *//*w w  w .  j a  va2 s.co m*/
public static JsonObject postJob(CloseableHttpClient httpClient, JsonObject service, File bundle,
        JsonObject jobConfigOverlay) throws ClientProtocolException, IOException {

    final String serviceName = jstring(service, "name");
    final JsonObject credentials = service.getAsJsonObject("credentials");

    String url = getJobSubmitURL(credentials, bundle);

    HttpPost postJobWithConfig = new HttpPost(url);
    postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());
    postJobWithConfig.addHeader(AUTH.WWW_AUTH_RESP, getAPIKey(credentials));
    FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM);
    StringBody configBody = new StringBody(jobConfigOverlay.toString(), ContentType.APPLICATION_JSON);

    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("sab", bundleBody)
            .addPart(DeployKeys.JOB_CONFIG_OVERLAYS, configBody).build();

    postJobWithConfig.setEntity(reqEntity);

    JsonObject jsonResponse = getGsonResponse(httpClient, postJobWithConfig);

    RemoteContext.REMOTE_LOGGER.info("Streaming Analytics service (" + serviceName + "): submit job response:"
            + jsonResponse.toString());

    return jsonResponse;
}

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

public DjangoMessage uploadFile(final byte[] bytes, final String filename)
        throws IOException, URISyntaxException {
    return executeRequest(new Supplier<HttpUriRequest>() {
        public HttpUriRequest get() {
            HttpPost post = new HttpPost(uploadFileUrl);
            MultipartEntityBuilder meb = MultipartEntityBuilder.create();
            meb.addTextBody(ACCESS_TOKEN_KEY, accessToken()).addTextBody("md5", Digests.md5(bytes))
                    .addBinaryBody(FILE_KEY, bytes, ContentType.APPLICATION_XML, filename);
            post.setEntity(meb.build());
            return post;
        }// w  ww  . j a v  a  2 s  .c om
    });
}

From source file:io.wcm.maven.plugins.contentpackage.DownloadMojo.java

/**
 * Download content package from CRX instance
 *///from  w  ww.ja va2s.c  o m
private File downloadFile(File file, String ouputFilePath) throws MojoExecutionException {
    try (CloseableHttpClient httpClient = getHttpClient()) {
        getLog().info("Download " + file.getName() + " from " + getCrxPackageManagerUrl());

        // 1st: try upload to get path of package - or otherwise make sure package def exists (no install!)
        HttpPost post = new HttpPost(getCrxPackageManagerUrl() + "/.json?cmd=upload");
        MultipartEntityBuilder entity = MultipartEntityBuilder.create().addBinaryBody("package", file)
                .addTextBody("force", "true");
        post.setEntity(entity.build());
        JSONObject jsonResponse = executePackageManagerMethodJson(httpClient, post);
        boolean success = jsonResponse.optBoolean("success", false);
        String msg = jsonResponse.optString("msg", null);
        String path = jsonResponse.optString("path", null);

        // package already exists - get path from error message and continue
        if (!success && StringUtils.startsWith(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX)
                && StringUtils.isEmpty(path)) {
            path = StringUtils.substringAfter(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX);
            success = true;
        }
        if (!success) {
            throw new MojoExecutionException("Package path detection failed: " + msg);
        }

        getLog().info("Package path is: " + path + " - now rebuilding package...");

        // 2nd: build package
        HttpPost buildMethod = new HttpPost(getCrxPackageManagerUrl() + "/console.html" + path + "?cmd=build");
        executePackageManagerMethodHtml(httpClient, buildMethod, 0);

        // 3rd: download package
        String crxUrl = StringUtils.removeEnd(getCrxPackageManagerUrl(), "/crx/packmgr/service");
        HttpGet downloadMethod = new HttpGet(crxUrl + path);

        // execute download
        CloseableHttpResponse response = httpClient.execute(downloadMethod);
        try {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                // get response stream
                InputStream responseStream = response.getEntity().getContent();

                // delete existing file
                File outputFileObject = new File(ouputFilePath);
                if (outputFileObject.exists()) {
                    outputFileObject.delete();
                }

                // write response file
                FileOutputStream fos = new FileOutputStream(outputFileObject);
                IOUtil.copy(responseStream, fos);
                fos.flush();
                responseStream.close();
                fos.close();

                getLog().info("Package downloaded to " + outputFileObject.getAbsolutePath());

                return outputFileObject;
            } else {
                throw new MojoExecutionException(
                        "Package download failed:\n" + EntityUtils.toString(response.getEntity()));
            }
        } finally {
            if (response != null) {
                EntityUtils.consumeQuietly(response.getEntity());
                try {
                    response.close();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }
    } catch (FileNotFoundException ex) {
        throw new MojoExecutionException("File not found: " + file.getAbsolutePath(), ex);
    } catch (IOException ex) {
        throw new MojoExecutionException("Download operation failed.", ex);
    }
}

From source file:org.openscore.content.httpclient.build.EntityBuilder.java

public HttpEntity buildEntity() {
    AbstractHttpEntity httpEntity = null;
    if (!StringUtils.isEmpty(formParams)) {
        List<? extends NameValuePair> list;
        list = getNameValuePairs(formParams, !Boolean.parseBoolean(this.formParamsAreURLEncoded),
                HttpClientInputs.FORM_PARAMS, HttpClientInputs.FORM_PARAMS_ARE_URLENCODED);
        httpEntity = new UrlEncodedFormEntity(list, contentType.getCharset());
    } else if (!StringUtils.isEmpty(body)) {
        httpEntity = new StringEntity(body, contentType);
    } else if (!StringUtils.isEmpty(filePath)) {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IllegalArgumentException(
                    "file set by input '" + HttpClientInputs.SOURCE_FILE + "' does not exist:" + filePath);
        }//from ww  w.  j  a v  a 2 s.c  om
        httpEntity = new FileEntity(file, contentType);
    }
    if (httpEntity != null) {
        if (!StringUtils.isEmpty(chunkedRequestEntity)) {
            httpEntity.setChunked(Boolean.parseBoolean(chunkedRequestEntity));
        }
        return httpEntity;
    }

    if (!StringUtils.isEmpty(multipartBodies) || !StringUtils.isEmpty(multipartFiles)) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if (!StringUtils.isEmpty(multipartBodies)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartBodies, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_BODIES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType bodiesCT = ContentType.parse(multipartBodiesContentType);
            for (NameValuePair nameValuePair : list) {
                multipartEntityBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), bodiesCT);
            }
        }

        if (!StringUtils.isEmpty(multipartFiles)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartFiles, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_FILES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType filesCT = ContentType.parse(multipartFilesContentType);
            for (NameValuePair nameValuePair : list) {
                File file = new File(nameValuePair.getValue());
                multipartEntityBuilder.addBinaryBody(nameValuePair.getName(), file, filesCT, file.getName());
            }
        }
        return multipartEntityBuilder.build();
    }

    return null;
}

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

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

    File xmlFile = null;/*from ww w  .  ja v  a2s .c o  m*/
    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);
    }
}