Example usage for org.apache.http.entity.mime.content FileBody FileBody

List of usage examples for org.apache.http.entity.mime.content FileBody FileBody

Introduction

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

Prototype

public FileBody(final File file) 

Source Link

Usage

From source file:eu.prestoprime.p4gui.connection.WorkflowConnection.java

public static String executeWorkflow(P4Service service, P4Workflow workflow, Map<String, String> dParamsString,
        Map<String, File> dParamsFile) throws WorkflowRequestException {

    if (dParamsString == null)
        dParamsString = new HashMap<>();
    if (dParamsFile == null)
        dParamsFile = new HashMap<>();

    dParamsString.put("wfID", workflow.toString());

    try {/*  ww w  .j a v  a  2  s  .co m*/
        MultipartEntity part = new MultipartEntity();

        for (String key : dParamsString.keySet()) {
            String value = dParamsString.get(key);
            part.addPart(key, new StringBody(value));
        }

        for (String key : dParamsFile.keySet()) {
            File value = dParamsFile.get(key);
            part.addPart(key, new FileBody(value));
        }

        String path = service.getURL() + "/wf/execute/" + workflow;

        logger.debug("Calling " + path);

        P4HttpClient client = new P4HttpClient(service.getUserID());
        HttpRequestBase request = new HttpPost(path);
        request.setHeader("content-data", "multipart/form-data");
        ((HttpPost) request).setEntity(part);
        HttpResponse response = client.executeRequest(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String line;
                if ((line = reader.readLine()) != null) {
                    logger.debug("Requested new job: " + line);
                    return line;
                }
            }
        } else {
            logger.debug(response.getStatusLine().toString());
            throw new WorkflowRequestException("Unable to request execution of workflow " + workflow + "...");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    throw new WorkflowRequestException(
            "Something wrong in WorkflowConnection requesting a workflow: no wfID returned...");
}

From source file:org.wisdom.test.http.MultipartBody.java

/**
 * Computes the request payload.//w  ww  .  java 2s .c om
 *
 * @return the payload containing the declared fields and files.
 */
public HttpEntity getEntity() {
    if (hasFile) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (Entry<String, Object> part : parameters.entrySet()) {
            if (part.getValue() instanceof File) {
                hasFile = true;
                builder.addPart(part.getKey(), new FileBody((File) part.getValue()));
            } else {
                builder.addPart(part.getKey(),
                        new StringBody(part.getValue().toString(), ContentType.APPLICATION_FORM_URLENCODED));
            }
        }
        return builder.build();
    } else {
        try {
            return new UrlEncodedFormEntity(getList(parameters), UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.alta189.deskbin.services.image.ImgurService.java

@Override
public String upload(File image) throws ImageServiceException {
    try {//  w  w  w  . j av a 2s .c o  m
        HttpPost post = new HttpPost(UPLOAD_URL);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("key", new StringBody(apikey, Charset.forName("UTF-8")));
        entity.addPart("type", new StringBody("file", Charset.forName("UTF-8")));
        FileBody fileBody = new FileBody(image);
        entity.addPart("image", fileBody);
        post.setEntity(entity);

        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new ImageServiceException(
                    "Error accessing imgur. Status code: " + response.getStatusLine().getStatusCode());
        }
        String json = EntityUtils.toString(response.getEntity());
        JSONObject jsonObject = new JSONObject(json).getJSONObject("upload").getJSONObject("links");
        return jsonObject.getString("imgur_page");
    } catch (Exception e) {
        throw new ImageServiceException(e);
    }
}

From source file:com.dss886.nForumSDK.service.AttachmentService.java

/**
 * /*w w w  .  jav a2s.  c o m*/
* ??idid????
* @param boardName ????
* @param file 
* @return /?
* @throws JSONException
* @throws NForumException
* @throws IOException
*/
public Attachment addAttachment(String boardName, File file, ParamOption params)
        throws JSONException, NForumException, IOException {
    String url = host + "attachment/" + boardName + "/add";
    if (params.getParams().containsKey("id")) {
        url = url + "/" + params.getParams().get("id") + returnFormat + appkey;
    } else {
        url = url + returnFormat + appkey;
    }
    FileBody fileBody = new FileBody(file);
    MultipartEntity mEntity = new MultipartEntity();
    mEntity.addPart("file", fileBody);
    PostMethod postMethod = new PostMethod(httpClient, auth, url, mEntity);
    return Attachment.parse(postMethod.postJSON());
}

From source file:gov.nist.appvet.tool.sigverifier.util.ReportUtil.java

/** This method should be used for sending files back to AppVet. */
public static boolean sendInNewHttpRequest(String appId, String reportFilePath, ToolStatus reportStatus) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
    HttpConnectionParams.setSoTimeout(httpParameters, 1200000);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    httpClient = SSLWrapper.wrapClient(httpClient);

    try {/*from w  w  w .  j av  a2  s. c  o m*/
        /*
         * To send reports back to AppVet, the following parameters must be
         * sent: - command: SUBMIT_REPORT - username: AppVet username -
         * password: AppVet password - appid: The app ID - toolid: The ID of
         * this tool - toolrisk: The risk assessment (LOW, MODERATE, HIGH,
         * ERROR) - report: The report file.
         */
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("command", new StringBody("SUBMIT_REPORT", Charset.forName("UTF-8")));
        entity.addPart("username", new StringBody(Properties.appvetUsername, Charset.forName("UTF-8")));
        entity.addPart("password", new StringBody(Properties.appvetPassword, Charset.forName("UTF-8")));
        entity.addPart("appid", new StringBody(appId, Charset.forName("UTF-8")));
        entity.addPart("toolid", new StringBody(Properties.toolId, Charset.forName("UTF-8")));
        entity.addPart("toolrisk", new StringBody(reportStatus.name(), Charset.forName("UTF-8")));
        File report = new File(reportFilePath);
        FileBody fileBody = new FileBody(report);
        entity.addPart("file", fileBody);
        HttpPost httpPost = new HttpPost(Properties.appvetUrl);
        httpPost.setEntity(entity);
        // Send the report to AppVet
        log.debug("Sending report file to AppVet");
        final HttpResponse response = httpClient.execute(httpPost);
        log.debug("Received from AppVet: " + response.getStatusLine());
        HttpEntity httpEntity = response.getEntity();
        InputStream is = httpEntity.getContent();
        String result = IOUtils.toString(is, "UTF-8");
        log.info(result);
        // Clean up
        httpPost = null;
        return true;
    } catch (Exception e) {
        log.error(e.toString());
        return false;
    }
}

From source file:net.cazzar.gradle.curseforge.CurseUpload.java

@TaskAction
public void uploadToCurseForge() {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(
            String.format("http://minecraft.curseforge.com/mc-mods/%s/upload-file.json", stub));

    //        System.out.println("VERSION: " + gameVersion);

    post.addHeader("X-API-Key", api_key);
    HttpEntity entity = MultipartEntityBuilder.create().addTextBody("name", artifact_name)
            .addTextBody("game_versions", gameVersion).addTextBody("file_type", String.valueOf(releaseType))
            .addTextBody("change_log", changeLog).addTextBody("change_log_markup_type", changeLogMarkup)
            .addTextBody("known_caveats", caveats).addTextBody("caveats_markup_type", cevatsMarkup)
            .addPart("file", new FileBody(artifact)).build();

    post.setEntity(entity);//  w ww .j  ava 2  s.c  o m
    try {
        HttpResponse response = client.execute(post);
        HttpEntity ent = response.getEntity();

        if (response.getStatusLine().getStatusCode() == 301) {
            post = new HttpPost(response.getLastHeader("Location").getValue());
            post.addHeader("X-API-Key", api_key);
            post.setEntity(entity);

            EntityUtils.consume(ent);

            response = client.execute(post);
            ent = response.getEntity();
        }

        if (response.getStatusLine().getStatusCode() != 201) {
            Gson gson = new Gson();
            @SuppressWarnings("unchecked")
            Map<String, List<String>> data = gson.fromJson(EntityUtils.toString(ent), Map.class);
            StringBuilder sb = new StringBuilder();
            Iterator<Map.Entry<String, List<String>>> iter = data.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String, List<String>> entry = iter.next();
                sb.append(entry.getKey()).append(": ").append('\n');//.append(entry.getValue());

                Iterator<String> iter2 = entry.getValue().iterator();
                while (iter2.hasNext()) {
                    sb.append('\t').append(StringEscapeUtils.unescapeHtml(iter2.next()));

                    if (iter2.hasNext())
                        sb.append('\n');
                }

                if (iter.hasNext())
                    sb.append("\n\n");
            }
            throw new RuntimeException(sb.toString());
        }

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

From source file:org.ow2.proactive_grid_cloud_portal.rm.server.serialization.CatalogRequestBuilder.java

protected HttpPost buildCatalogRequest(String fullUri) {
    String boundary = "---------------" + UUID.randomUUID().toString();
    HttpPost post = new HttpPost(fullUri);
    post.addHeader("Accept", "application/json");
    post.addHeader("Content-Type",
            org.apache.http.entity.ContentType.MULTIPART_FORM_DATA.getMimeType() + ";boundary=" + boundary);
    post.addHeader("sessionId", this.catalogObjectAction.getSessionId());

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setBoundary(boundary);//ww  w  .ja  va  2s. c  o m
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("file", new FileBody(this.catalogObjectAction.getNodeSourceJsonFile()));
    builder.addTextBody(COMMIT_MESSAGE_PARAM, this.catalogObjectAction.getCommitMessage());
    if (!this.catalogObjectAction.isRevised()) {
        builder.addTextBody(NAME_PARAM, this.catalogObjectAction.getNodeSourceName());
        builder.addTextBody(KIND_PARAM, this.catalogObjectAction.getKind());
        builder.addTextBody(OBJECT_CONTENT_TYPE_PARAM, this.catalogObjectAction.getObjectContentType());
    }
    post.setEntity(builder.build());
    return post;
}

From source file:niclients.main.pubni.java

/**
 * Creates NI publish HTTP POST signal./*from   w ww.  j a  v a  2 s.c  o m*/
 * 
 * @return       boolean true/false in success/failure
 * @throws       UnsupportedEncodingException
 */
static boolean createpub() throws UnsupportedEncodingException {

    post = new HttpPost(fqdn + "/.well-known/netinfproto/publish");

    ContentBody url = new StringBody(niname);
    ContentBody msgid = new StringBody(Integer.toString(randomGenerator.nextInt(100000000)));
    ContentBody fullPut = new StringBody("yes");
    ContentBody ext = new StringBody("no extension");
    ContentBody bin = new FileBody(new File(filename));
    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("octets", bin);
    reqEntity.addPart("URI", url);
    reqEntity.addPart("msgid", msgid);
    reqEntity.addPart("fullPut", fullPut);
    reqEntity.addPart("ext", ext);

    post.setEntity(reqEntity);
    return true;
}

From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java

@Test
public void testMultiPartRequestWithNoMultipartConfig() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {/*from ww  w  .j  a v a  2s. co  m*/
        String uri = DefaultServer.getDefaultServerURL() + "/servletContext/0";
        HttpPost post = new HttpPost(uri);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file",
                new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("PARAMS:\n", response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.ibm.watson.developer_cloud.visual_insights.v1.VisualInsights.java

/**
 * Upload a set of images as a zip file for visual insight extraction.
 *
 * @param imagesFile the images File/*from w w w  . j  a  v  a2  s  .  c om*/
 * @return the Summary of the collection's visual attributes
 */
public Summary getSummary(final File imagesFile) {
    if (imagesFile == null || !imagesFile.exists())
        throw new IllegalArgumentException("imagesFile can not be null or empty");

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart(FILE, new FileBody(imagesFile));
    Request request = Request.Post(SUMMARY_PATH).withEntity(reqEntity);

    return executeRequest(request, Summary.class);

}