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

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

Introduction

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

Prototype

public MultipartEntityBuilder addTextBody(final String name, final String text) 

Source Link

Usage

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  ww w .  jav  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:nzilbb.bas.BAS.java

/**
 * Invoke the general MAUS service, for forced alignment given a WAV file and a phonemic transcription.
 * @param LANGUAGE <a href="https://tools.ietf.org/html/rfc5646">RFC 5646</a> tag for identifying the language.
 * @param SIGNAL The signal, in WAV format.
 * @param BPF Phonemic transcription of the utterance to be segmented. Format is a <a href="http://www.bas.uni-muenchen.de/forschung/Bas/BasFormatseng.html">BAS Partitur Format (BPF)</a> file with a KAN tier.
 * @param MINPAUSLEN Controls the behaviour of optional inter-word silence. If set to 1, maus will detect all inter-word silence intervals that can be found (minimum length for a silence interval is then 10 msec = 1 frame). If set to values n&gt;1, the minimum length for an inter-word silence interval to be detected is set to n&times;10 msec.
 * @param STARTWORD If set to a value n&gt;0, this option causes maus to start the segmentation with the word number n (word numbering in BPF starts with 0).
 * @param ENDWORD If set to a value n&lt;999999, this option causes maus to end the segmentation with the word number n (word numbering in BPF starts with 0). 
 * @param RULESET MAUS rule set file; UTF-8 encoded; one rule per line; two different file types defined by the extension: '*.nrul' : phonological rule set without statistical information
 * @param OUTFORMAT Defines the output format:
 *  <ul>//from   ww  w .  j  ava 2 s.com
 *   <li>"TextGrid" - a praat compatible TextGrid file</li> 
 *   <li>"par" or "mau-append" - the input BPF file with a new (or replaced) tier MAU</li>
 *   <li>"csv" or "mau" - only the BPF MAU tier (CSV table)</li> 
 *   <li>"legacyEMU" - a file with extension *.EMU that contains in the first part the Emu hlb file (*.hlb) and in the second part the Emu phonetic segmentation (*.phonetic)</li>
 *   <li>emuR - an Emu compatible *_annot.json file</li>
 *  </ul>
 * @param MAUSSHIFT If set to n, this option causes the calculated MAUS segment boundaries to be shifted by n msec (default: 10) into the future.
 * @param INSPROB The option INSPROB influences the probability of deletion of segments. It is a constant factor (a constant value added to the log likelihood score) after each segment. Therefore, a higher value of INSPROB will cause the probability of segmentations with more segments go up, thus decreasing the probability of deletions (and increasing the probability of insertions, which are rarely modelled in the rule sets).
 * @param INSKANTEXTGRID Switch to create an additional tier in the TextGrid output file with a word segmentation labelled with the canonic phonemic transcript.
 * @param INSORTTEXTGRID Switch to create an additional tier ORT in the TextGrid output file with a word segmentation labelled with the orthographic transcript (taken from the input ORT tier)
 * @param USETRN  If set to true, the service searches the input BPF for a TRN tier. The synopsis for a TRN entry is: 'TRN: (start-sample) (duration-sample) (word-link-list) (label)', e.g. 'TRN: 23654 56432 0,1,2,3,4,5,6 sentence1' (the speech within the recording 'sentence1' starts with sample 23654, last for 56432 samples and covers the words 0-6). If only one TRN entry is found, the segmentation is restricted within a time range given by this TRN tier entry.
 * @param OUTSYMBOL Defines the encoding of phonetic symbols in output. 
 *  <ul>
 *   <li>"sampa" - (default), phonetic symbols are encoded in language specific SAM-PA (with some coding differences to official SAM-PA</li>
 *   <li>"ipa" - the service produces UTF-8 IPA output.</li> 
 *   <li>"manner" - the service produces IPA manner of articulation for each segment; possible values are: silence, vowel, diphthong, plosive, nasal, fricative, affricate, approximant, lateral-approximant, ejective.</li>
 *   <li>"place" - the service produces IPA place of articulation for each segment; possible values are: silence, labial, dental, alveolar, post-alveolar, palatal, velar, uvular, glottal, front, central, back.</li> </ul>
 * @param NOINITIALFINALSILENCE Switch to suppress the automatic modeling on a leading/trailing silence interval. 
 * @param WEIGHT weights the influence of the statistical pronunciation model against the acoustical scores. More precisely WEIGHT is multiplied to the pronunciation model score (log likelihood) before adding the score to the acoustical score within the search. Since the pronunciation model in most cases favors the canonical pronunciation, increasing WEIGHT will at some point cause MAUS to choose always the canonical pronunciation; lower values of WEIGHT will favor less probable paths be selected according to acoustic evidence
 * @param MODUS Operation modus of MAUS: 
 *  <ul>
 *   <li>"standard" (default) - the segmentation and labelling using the MAUS technique as described in Schiel ICPhS 1999.</li> 
 *   <li>"align" - a forced alignment is performed on the input SAM-PA string defined in the KAN tier of the BPF.</li>
 * </ul>
 * @return The response to the request.
 * @throws IOException If an IO error occurs.
 * @throws ParserConfigurationException If the XML parser for parsing the response could not be configured.
 */
public BASResponse MAUS(String LANGUAGE, InputStream SIGNAL, InputStream BPF, String OUTFORMAT,
        String OUTSYMBOL, Integer MINPAUSLEN, Integer STARTWORD, Integer ENDWORD, InputStream RULESET,
        Integer MAUSSHIFT, Double INSPROB, Boolean INSKANTEXTGRID, Boolean INSORTTEXTGRID, Boolean USETRN,
        Boolean NOINITIALFINALSILENCE, Double WEIGHT, String MODUS)
        throws IOException, ParserConfigurationException {
    if (OUTSYMBOL == null)
        OUTSYMBOL = "sampa";
    // "40 msec seems to be the border of perceivable silence, we set this option default to 5"
    if (MINPAUSLEN == null)
        MINPAUSLEN = 5;
    HttpPost request = new HttpPost(getMAUSUrl());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create()
            .addTextBody("LANGUAGE", languageTagger.tag(LANGUAGE))
            .addBinaryBody("SIGNAL", SIGNAL, ContentType.create("audio/wav"), "BAS.wav")
            .addBinaryBody("BPF", BPF, ContentType.create("text/plain-bas"), "BAS.par")
            .addTextBody("OUTFORMAT", OUTFORMAT).addTextBody("OUTSYMBOL", OUTSYMBOL);
    if (USETRN != null)
        builder.addTextBody("USETRN", USETRN.toString());
    if (MINPAUSLEN != null)
        builder.addTextBody("MINPAUSLEN", MINPAUSLEN.toString());
    if (STARTWORD != null)
        builder.addTextBody("STARTWORD", STARTWORD.toString());
    if (ENDWORD != null)
        builder.addTextBody("ENDWORD", ENDWORD.toString());
    if (RULESET != null)
        builder.addBinaryBody("RULESET", RULESET, ContentType.create("text/plain"), "RULESET.txt");
    if (MAUSSHIFT != null)
        builder.addTextBody("MAUSSHIFT", MAUSSHIFT.toString());
    if (INSPROB != null)
        builder.addTextBody("INSPROB", INSPROB.toString());
    if (INSKANTEXTGRID != null)
        builder.addTextBody("INSKANTEXTGRID", INSKANTEXTGRID.toString());
    if (INSORTTEXTGRID != null)
        builder.addTextBody("INSORTTEXTGRID", INSORTTEXTGRID.toString());
    if (NOINITIALFINALSILENCE != null)
        builder.addTextBody("NOINITIALFINALSILENCE", NOINITIALFINALSILENCE.toString());
    if (WEIGHT != null)
        builder.addTextBody("WEIGHT", WEIGHT.toString());
    if (MODUS != null)
        builder.addTextBody("MODUS", MODUS.toString());
    HttpEntity entity = builder.build();
    request.setEntity(entity);
    HttpResponse httpResponse = httpclient.execute(request);
    HttpEntity result = httpResponse.getEntity();
    return new BASResponse(result.getContent());
}

From source file:com.nc.common.utils.HttpUtils.java

/**
 * <pre>/*from   w  ww  .  ja  v a  2s .c  o m*/
 * 1.  : http  
 * 2.  : OpenAPI Multipart 
 * </pre>
 *
 * @method Name : execOpenAPIMultipart
 * @param String subUrl, Map<String, Object> paramMap
 * @return String
 * @throws Exception
 * 
 */
public String execOpenAPIMultipart(String subUrl, Map<String, Object> paramMap) throws Exception {
    String result = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {

        HttpPost httpPost = new HttpPost(new URI(serverOpenAPI + subUrl));
        // httpPost.addHeader("Content-Type", "application/json");

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .setCharset(Charset.forName(CommonConstants.DEFAULT_CHARSET));

        Iterator<String> iter = paramMap.keySet().iterator();
        String key = null;
        String val = null;

        while (iter.hasNext()) {
            key = iter.next();
            val = (String) paramMap.get(key);

            if (log.isDebugEnabled()) {
                log.debug(
                        "==========================================================================================");
                log.debug(" = ? : [{} - {}] =", key, val);
                log.debug(
                        "==========================================================================================");
            }

            multipartEntityBuilder.addTextBody(key, val);
        }
        httpPost.setEntity(multipartEntityBuilder.build());

        if (log.isDebugEnabled()) {
            log.debug(
                    "==========================================================================================");
            log.debug("= API   : [{}]", httpPost);
            log.debug(
                    "==========================================================================================");
        }

        CloseableHttpResponse response = httpclient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();

        if (log.isDebugEnabled()) {
            log.debug(
                    "==========================================================================================");
            log.debug("= API  ? : [{}]", statusLine);
            log.debug(
                    "==========================================================================================");
        }

        try {
            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity, CommonConstants.DEFAULT_CHARSET);
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "==========================================================================================");
                        log.debug("= API    : [{}] =", result);
                        log.debug(
                                "==========================================================================================");
                    }
                }
                EntityUtils.consume(entity);
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
    return result;
}

From source file:de.geeksfactory.opacclient.apis.Open.java

/**
 * Better version of JSoup's implementation of this function ({@link
 * org.jsoup.nodes.FormElement#formData()}).
 *
 * @param form       The form to submit/*www . jav  a 2s. co m*/
 * @param submitName The name attribute of the button which is clicked to submit the form, or
 *                   null
 * @return A MultipartEntityBuilder containing the data of the form
 */
protected MultipartEntityBuilder formData(FormElement form, String submitName) {
    MultipartEntityBuilder data = MultipartEntityBuilder.create();
    data.setLaxMode();

    // iterate the form control elements and accumulate their values
    for (Element el : form.elements()) {
        if (!el.tag().isFormSubmittable()) {
            continue; // contents are form listable, superset of submitable
        }
        String name = el.attr("name");
        if (name.length() == 0)
            continue;
        String type = el.attr("type");

        if ("select".equals(el.tagName())) {
            Elements options = el.select("option[selected]");
            boolean set = false;
            for (Element option : options) {
                data.addTextBody(name, option.val());
                set = true;
            }
            if (!set) {
                Element option = el.select("option").first();
                if (option != null) {
                    data.addTextBody(name, option.val());
                }
            }
        } else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) {
            // only add checkbox or radio if they have the checked attribute
            if (el.hasAttr("checked")) {
                data.addTextBody(name, el.val().length() > 0 ? el.val() : "on");
            }
        } else if ("submit".equalsIgnoreCase(type) || "image".equalsIgnoreCase(type)) {
            if (submitName != null && el.attr("name").contains(submitName)) {
                data.addTextBody(name, el.val());
            }
        } else {
            data.addTextBody(name, el.val());
        }
    }
    return data;
}

From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java

/**
 * @see org.opentravel.schemacompiler.repository.Repository#publish(java.io.InputStream,
 *      java.lang.String, java.lang.String, java.lang.String, java.lang.String,
 *      java.lang.String, org.opentravel.schemacompiler.model.TLLibraryStatus)
 *//*from   w  ww.j ava 2 s  .c  om*/
@Override
public RepositoryItem publish(InputStream unmanagedContent, String filename, String libraryName,
        String namespace, String versionIdentifier, String versionScheme, TLLibraryStatus initialStatus)
        throws RepositoryException {
    try {
        // Build a repository item to represent the content that we are attempting to publish
        String targetNS = RepositoryNamespaceUtils.normalizeUri(namespace);
        RepositoryItemImpl item = new RepositoryItemImpl();
        String baseNamespace = targetNS;

        if (versionScheme != null) {
            VersionScheme vScheme = VersionSchemeFactory.getInstance().getVersionScheme(versionScheme);
            baseNamespace = vScheme.getBaseNamespace(targetNS);
        }

        item.setRepository(this);
        item.setNamespace(targetNS);
        item.setBaseNamespace(baseNamespace);
        item.setFilename(filename);
        item.setVersion(versionIdentifier);
        item.setStatus(initialStatus);
        item.setState(RepositoryItemState.MANAGED_UNLOCKED);

        // Invoke the remote web service call to perform the publication
        HttpPost postRequest = newPostRequest(PUBLISH_ENDPOINT);
        MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();

        if (versionScheme != null) {
            mpEntity.addTextBody("versionScheme", versionScheme);
        }
        mpEntity.addBinaryBody("fileContent", toByteArray(unmanagedContent), ContentType.DEFAULT_BINARY,
                filename);
        mpEntity.addTextBody("namespace", targetNS);
        mpEntity.addTextBody("libraryName", libraryName);
        mpEntity.addTextBody("version", versionIdentifier);
        mpEntity.addTextBody("status", initialStatus.toRepositoryStatus().toString());
        postRequest.setEntity(mpEntity.build());

        log.info("Sending publish request to HTTP endpoint: " + endpointUrl);
        HttpResponse response = executeWithAuthentication(postRequest);

        if (response.getStatusLine().getStatusCode() != HTTP_RESPONSE_STATUS_OK) {
            throw new RepositoryException(getResponseErrorMessage(response));
        }
        log.info("Publish response received - Status OK");
        return item;

    } catch (VersionSchemeException e) {
        throw new RepositoryException(e.getMessage(), e);

    } catch (IOException e) {
        throw new RepositoryException("The remote repository is unavailable.", e);

    } finally {
        try {
            if (unmanagedContent != null)
                unmanagedContent.close();
        } catch (Throwable t) {
        }
    }
}

From source file:nl.uva.mediamosa.impl.MediaMosaImpl.java

/**
 * @param postRequest//w  ww  .  j  av  a2 s.  c om
 * @param postParams
 * @return
 * @throws java.io.IOException
 */
public Response doPostRequest(String uploadHost, String postRequest, String postParams, InputStream stream,
        String mimeType, String filename) throws IOException {
    HttpPost httpPost = new HttpPost(uploadHost + postRequest);

    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
    mpBuilder.addBinaryBody("file", stream, ContentType.create(mimeType), filename);

    List<NameValuePair> nvps = URLEncodedUtils.parse(postParams, Charset.forName("UTF-8"));
    for (NameValuePair nameValuePair : nvps) {
        mpBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue());
    }
    httpPost.setEntity(mpBuilder.build());

    return UnmarshallUtil.unmarshall(getXmlTransformedResponse(httpPost));
}

From source file:service.OrderService.java

private String sendRequestForUnloadInShop(Order order, ServiceResult result) throws Exception {
    List<String> missing = new ArrayList();
    List<String> directionNames = new ArrayList();
    for (Direction dir : order.getDirections()) {
        String dirName = (dir.getNameForShop() != null ? dir.getNameForShop() : "");
        if (dirName.isEmpty()) {
            missing.add(//from   w  ww .ja  v a  2  s. com
                    "? ?    ? ? "
                            + dir.getName());
        }
        directionNames.add(dirName);
    }
    String orderName = "";
    if (order.getOrderType() != null && order.getOrderType().getNameForShop() != null) {
        orderName = order.getOrderType().getNameForShop();
    }
    if (orderName.isEmpty()) {
        missing.add(
                "? ?    ?  ");
    }
    String subject = (order.getSubject() != null ? order.getSubject() : "");
    if (subject.isEmpty()) {
        missing.add(" ");
    }
    String price = (order.getCost() != null ? order.getCost().toString() : "0");
    String numberOfPages = (order.getNumberOfPages() != null ? order.getNumberOfPages() : "");
    if (numberOfPages.isEmpty()) {
        missing.add("? ?");
    }
    String fileName = "order" + order.getOrderId() + ".zip";

    if (missing.isEmpty()) {
        String url = "http://zaochnik5.ru/up/uploadfile.php";
        HttpPost post = new HttpPost(url);
        MultipartEntityBuilder multipart = MultipartEntityBuilder.create();
        multipart.addTextBody("type_work", orderName);
        multipart.addTextBody("name_work", subject);
        multipart.addTextBody("price", price);
        multipart.addTextBody("table_of_contents", "-");
        for (String dirName : directionNames) {
            multipart.addTextBody("napravlenie", dirName);
        }
        multipart.addTextBody("kol-vo_str", numberOfPages);
        multipart.addTextBody("fail", fileName);
        multipart.addTextBody("order_number", order.getOrderId().toString());
        multipart.addTextBody("kol-vo_order", "1");
        multipart.addTextBody("published", "0");
        multipart.addTextBody("srvkey", "8D9ucTqL4Ga2ZkLCmctR");
        byte[] zipBytes = getZipAllReadyFiles(order);
        multipart.addPart("upload", new ByteArrayBody(zipBytes, fileName));
        HttpEntity ent = multipart.build();
        post.setEntity(ent);
        HttpClient client = HttpClients.createDefault();
        HttpResponse response = client.execute(post);
        return IOUtils.toString(response.getEntity().getContent());
    } else {
        String missingStr = "";
        for (String str : missing) {
            missingStr += str + ", ";
        }
        result.addError(
                "?  ,  ?  :"
                        + missingStr);
        return "";
    }
}

From source file:com.ibm.iotf.client.api.APIClient.java

/**
 * Create a draft schema definition//from  ww  w  .j av a  2s. c  o m
 * 
 * @param schemaFile File containing the schema file
 *      
 * @param schemaName String containing the schema name
 *      
 * @param schemaDescription String containing the description of schema
 * 
 * @param schemaType String containing the schema type (like for e.g. json-schema)
 * 
 * @return If successful, JsonObject response from Watson IoT Platform.
 * 
 * @throws IoTFCReSTException Failure in creating a draft schema definition
 */
public JsonObject addDraftSchemaDefinition(File schemaFile, String schemaName, String schemaDescription,
        String schemaType) throws IoTFCReSTException {
    final String METHOD = "addDraftSchemaDefinition";
    HttpResponse response = null;
    JsonElement jsonResponse = null;
    int code = 0;
    String method = "post";
    try {
        StringBuilder sb = new StringBuilder("https://");
        sb.append(orgId).append('.').append(this.domain).append(BASIC_API_V0002_URL).append("/draft/schemas/");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        builder.addBinaryBody("schemaFile", new FileInputStream(schemaFile),
                org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM, schemaFile.getName());

        builder.addTextBody("description", schemaDescription);
        builder.addTextBody("name", schemaName);

        URIBuilder uri = new URIBuilder(sb.toString());

        HttpPost post = new HttpPost(uri.build());

        byte[] encoding = Base64.encodeBase64(new String(authKey + ":" + authToken).getBytes());
        String encodedString = new String(encoding);

        post.setHeader("Authorization", "Basic " + encodedString);

        HttpClient client = HttpClientBuilder.create().useSystemProperties().setSslcontext(sslContext).build();
        HttpEntity multipart = builder.build();
        post.setEntity(multipart);

        response = client.execute(post);
        code = response.getStatusLine().getStatusCode();
        String result = this.readContent(response, METHOD);
        jsonResponse = new JsonParser().parse(result);
        if (code == 201 || code == 400 || code == 401 || code == 403 || code == 404 || code == 500) {
            if (code == 201) {
                //Success
                return jsonResponse.getAsJsonObject();
            } else {
                String reason = null;
                switch (code) {
                case 400:
                    reason = IoTFCReSTException.HTTP_ADD_SCHEMA_DEFINITION_ERR_400;
                    break;
                case 401:
                    reason = IoTFCReSTException.HTTP_ADD_SCHEMA_DEFINITION_ERR_401;
                    break;
                case 403:
                    reason = IoTFCReSTException.HTTP_ADD_SCHEMA_DEFINITION_ERR_403;
                    break;
                case 500:
                    reason = IoTFCReSTException.HTTP_ADD_SCHEMA_DEFINITION_ERR_500;
                    break;
                }
                throw new IoTFCReSTException(method, sb.toString(), null, code, reason, jsonResponse);
            }
        } else {
            throw new IoTFCReSTException(code, "Unexpected error", jsonResponse);
        }
    } catch (IoTFCReSTException e) {
        throw e;
    } catch (Exception e) {
        // This includes JsonSyntaxException
        IoTFCReSTException ex = new IoTFCReSTException(
                "Failure in creating a draft schema definition " + "::" + e.getMessage());
        ex.initCause(e);
        throw ex;
    }
}

From source file:org.kochka.android.weightlogger.tools.GarminConnect.java

public boolean uploadFitFile(File fitFile) {
    if (httpclient == null)
        return false;
    try {/*  ww  w.  jav  a2 s  .c om*/
        HttpPost post = new HttpPost("http://connect.garmin.com/proxy/upload-service-1.1/json/upload/.fit");

        /*
        SimpleMultipartEntity mpEntity = new SimpleMultipartEntity();
        mpEntity.addPart("data", fitFile);
        mpEntity.addPart("responseContentType", "text/html");
        post.setEntity(mpEntity);
        */

        MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
        multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntity.addBinaryBody("data", fitFile);
        multipartEntity.addTextBody("responseContentType", "text/html");
        post.setEntity(multipartEntity.build());

        HttpEntity entity = httpclient.execute(post).getEntity();
        JSONObject js_upload = new JSONObject(EntityUtils.toString(entity));
        entity.consumeContent();
        if (js_upload.getJSONObject("detailedImportResult").getJSONArray("failures").length() != 0)
            throw new Exception("upload error");

        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.kohsuke.stapler.RequestImplTest.java

private byte[] generateMultipartData() throws IOException {
    MultipartEntityBuilder reqEntityBuilder = MultipartEntityBuilder.create();

    reqEntityBuilder.setBoundary("mpboundary");
    reqEntityBuilder.addBinaryBody("pomFile", new File("./pom.xml"), ContentType.TEXT_XML, "pom.xml");
    reqEntityBuilder.addTextBody("text1", "text1_val");
    reqEntityBuilder.addTextBody("text2", "text2_val");

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {// ww  w .  j ava2  s.  com
        reqEntityBuilder.build().writeTo(outputStream);
        outputStream.flush();
        return outputStream.toByteArray();
    } finally {
        outputStream.close();
    }
}