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:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java

/**
 * attach log using run id/*from ww w  . ja va 2  s . c o m*/
 * 
 * @param token
 *            - token generate using username and password
 * @param scope
 *            : project:release:cycle
 * @param testCaseRunId
 * @param filePath
 *            - absolute path of file to be attached
 * @param serviceUrl
 * @param scope
 * @return
 */
public int attachTestLogsUsingRunID(String serviceUrl, long testCaseRunId, File filePath, String scope) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments/testLog");

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

                FileBody bin = new FileBody(filePath);
                builder.addTextBody("desc", "Attached on " + CurrentDate,
                        org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addTextBody("type", "TCR", org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addTextBody("entityId", String.valueOf(testCaseRunId),
                        org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", scope);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:project.cs.lisa.netinf.node.resolution.NameResolutionService.java

/**
 * Creates an HTTP POST representation of a NetInf PUBLISH message.
 * @param io/*from   ww  w  .  j a  va2s .  co  m*/
 *     The information object to publish
 * @return
 *     A HttpPost representing the NetInf PUBLISH message
 * @throws UnsupportedEncodingException
 *     In case the encoding is not supported
 */
private HttpPost createPublish(InformationObject io) throws UnsupportedEncodingException {

    Log.d(TAG, "createPublish()");

    // Extracting values from IO's identifier
    String hashAlg = getHashAlg(io.getIdentifier());
    String hash = getHash(io.getIdentifier());
    String contentType = getContentType(io.getIdentifier());
    String meta = getMetadata(io.getIdentifier());
    String bluetoothMac = getBluetoothMac(io);
    String filePath = getFilePath(io);

    HttpPost post = new HttpPost(mHost + ":" + mPort + "/netinfproto/publish");

    MultipartEntity entity = new MultipartEntity();

    StringBody uri = new StringBody("ni:///" + hashAlg + ";" + hash + "?ct=" + contentType);
    entity.addPart("URI", uri);

    StringBody msgid = new StringBody(Integer.toString(mRandomGenerator.nextInt(MSG_ID_MAX)));
    entity.addPart("msgid", msgid);

    if (bluetoothMac != null) {
        StringBody l = new StringBody(bluetoothMac);
        entity.addPart("loc1", l);
    }

    if (meta != null) {
        StringBody ext = new StringBody(meta.toString());
        entity.addPart("ext", ext);
    }

    if (filePath != null) {
        StringBody fullPut = new StringBody("true");
        entity.addPart("fullPut", fullPut);
        FileBody octets = new FileBody(new File(filePath));
        entity.addPart("octets", octets);
    }

    StringBody rform = new StringBody("json");
    entity.addPart("rform", rform);

    try {
        entity.writeTo(System.out);
    } catch (IOException e) {
        Log.e(TAG, "Failed to write MultipartEntity to System.out");
    }

    post.setEntity(entity);
    return post;
}

From source file:com.ibm.devops.dra.PublishTest.java

/**
 * * Send POST request to DLMS back end with the result file
 * @param bluemixToken - the Bluemix token
 * @param contents - the result file//from w w w .ja v  a2s. c om
 * @param jobUrl -  the build url of the build job in Jenkins
 * @param timestamp
 * @return - response/error message from DLMS
 */
public String sendFormToDLMS(String bluemixToken, FilePath contents, String lifecycleStage, String jobUrl,
        String timestamp) throws IOException {

    // create http client and post method
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost postMethod = new HttpPost(this.dlmsUrl);

    postMethod = addProxyInformation(postMethod);
    // build up multi-part forms
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    if (contents != null) {

        File file = new File(root, contents.getName());
        FileBody fileBody = new FileBody(file);
        builder.addPart("contents", fileBody);

        builder.addTextBody("test_artifact", file.getName());
        if (this.isDeploy) {
            builder.addTextBody("environment_name", environmentName);
        }
        //Todo check the value of lifecycleStage
        builder.addTextBody("lifecycle_stage", lifecycleStage);
        builder.addTextBody("url", jobUrl);
        builder.addTextBody("timestamp", timestamp);

        String fileExt = FilenameUtils.getExtension(contents.getName());
        String contentType;
        switch (fileExt) {
        case "json":
            contentType = CONTENT_TYPE_JSON;
            break;
        case "xml":
            contentType = CONTENT_TYPE_XML;
            break;
        default:
            return "Error: " + contents.getName() + " is an invalid result file type";
        }

        builder.addTextBody("contents_type", contentType);
        HttpEntity entity = builder.build();
        postMethod.setEntity(entity);
        postMethod.setHeader("Authorization", bluemixToken);
    } else {
        return "Error: File is null";
    }

    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(postMethod);
        // parse the response json body to display detailed info
        String resStr = EntityUtils.toString(response.getEntity());
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(resStr);

        if (!element.isJsonObject()) {
            // 401 Forbidden
            return "Error: Upload is Forbidden, please check your org name. Error message: "
                    + element.toString();
        } else {
            JsonObject resJson = element.getAsJsonObject();
            if (resJson != null && resJson.has("status")) {
                return String.valueOf(response.getStatusLine()) + "\n" + resJson.get("status");
            } else {
                // other cases
                return String.valueOf(response.getStatusLine());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

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

public void changeAppIcon(String applicationHash, File appIcon) throws AppCloudIntegrationTestException {
    HttpClient httpclient = null;//from  w  w w .  ja v a 2  s. c  o m
    org.apache.http.HttpResponse response = null;
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
        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_CHANGE_ICON, new FileBody(appIcon));
        builder.addPart(PARAM_NAME_ACTION, new StringBody(CHANGE_APP_ICON_ACTION, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_HASH_ID,
                new StringBody(applicationHash, 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("Update app icon failed " + result);
        }
    } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) {
        // In most of the cases, even though connection is timed out, actual activity is completed.
        // And this will be asserted so if it failed due to a valid case, it will be captured.
        log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1);
    } catch (IOException e) {
        log.error("Failed to invoke app icon update API.", e);
        throw new AppCloudIntegrationTestException("Failed to invoke app icon update API.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(httpclient);
    }
}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Simple http post request. It needs an object to be sent. If an element of the object contains the key file then it will try to upload the resource indicated in the value as Uri ", example = "")
@APIParam(params = { "url", "params", "function(responseString)" })
public void httpPost(String url, Object object, final HttpPostCB callbackfn) {
    final HttpClient httpClient = new DefaultHttpClient();
    final HttpContext localContext = new BasicHttpContext();
    final HttpPost httpPost = new HttpPost(url);

    Gson g = new Gson();
    JsonArray q = g.toJsonTree(object).getAsJsonArray();

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    for (int i = 0; i < q.size(); i++) {
        Set<Entry<String, JsonElement>> set = q.get(i).getAsJsonObject().entrySet();

        // go through elements
        String name = "";
        String content = "";
        String type = "";
        for (Object element : set) {
            Entry<String, JsonElement> entry = (Entry<String, JsonElement>) element;
            if (entry.getKey().equals("name")) {
                name = entry.getValue().getAsString();
            } else if (entry.getKey().equals("content")) {
                content = entry.getValue().getAsString();
            } else if (entry.getKey().equals("type")) {
                type = entry.getValue().getAsString();
            }//from  ww  w. j  a  v  a  2s  . co  m
        }

        // create the multipart
        if (type.contains("file")) {
            File f = new File(
                    ProjectManager.getInstance().getCurrentProject().getStoragePath() + "/" + content);
            ContentBody cbFile = new FileBody(f);
            entity.addPart(name, cbFile);
        } else if (type.contains("text")) { // Normal string data
            try {
                entity.addPart(name, new StringBody(content));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    // send
    httpPost.setEntity(entity);
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                HttpResponse response = httpClient.execute(httpPost, localContext);
                callbackfn.event(response.getStatusLine().toString());
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

From source file:de.tu_dortmund.ub.data.dswarm.Task.java

/**
 * upload a file and update an existing resource with it
 *
 * @param resourceUUID//  ww w.j  a  v a2 s  .c  om
 * @param filename
 * @param name
 * @param description
 * @return responseJson
 * @throws Exception
 */
private String uploadFileAndUpdateResource(String resourceUUID, String filename, String name,
        String description) throws Exception {

    if (null == resourceUUID)
        throw new Exception("ID of the resource to update was null.");

    String responseJson = null;

    String file = config.getProperty("resource.watchfolder") + File.separatorChar + filename;

    // ggf. Preprocessing: insert CDATA in XML and write new XML file to tmp folder
    if (Boolean.parseBoolean(config.getProperty("resource.preprocessing"))) {

        Document document = new SAXBuilder().build(new File(file));

        file = config.getProperty("preprocessing.folder") + File.separatorChar + UUID.randomUUID() + ".xml";

        XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
        BufferedWriter bufferedWriter = null;
        try {

            bufferedWriter = new BufferedWriter(new FileWriter(file));

            out.output(new SAXBuilder().build(new StringReader(
                    XmlTransformer.xmlOutputter(document, config.getProperty("preprocessing.xslt"), null))),
                    bufferedWriter);
        } finally {
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
        }
    }

    // upload
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {
        HttpPut httpPut = new HttpPut(config.getProperty("engine.dswarm.api") + "resources/" + resourceUUID);

        FileBody fileBody = new FileBody(new File(file));
        StringBody stringBodyForName = new StringBody(name, ContentType.TEXT_PLAIN);
        StringBody stringBodyForDescription = new StringBody(description, ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", fileBody)
                .addPart("name", stringBodyForName).addPart("description", stringBodyForDescription).build();

        httpPut.setEntity(reqEntity);

        logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpPut.getRequestLine());

        CloseableHttpResponse httpResponse = httpclient.execute(httpPut);

        try {
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();

            switch (statusCode) {

            case 200: {

                logger.info("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
                StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, "UTF-8");
                responseJson = writer.toString();

                logger.info("[" + config.getProperty("service.name") + "] responseJson : " + responseJson);

                break;
            }
            default: {

                logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            }

            EntityUtils.consume(httpEntity);
        } finally {
            httpResponse.close();
        }
    } finally {
        httpclient.close();
    }

    return responseJson;
}