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: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  a v  a  2s  .  co  m
 *   <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.oneops.client.api.resource.Design.java

/**
 * Adds specific platform from Yaml/Json file input
 * /* ww  w. java  2s. c  om*/
 * @param platformName
 * @return
 * @throws OneOpsClientAPIException
 */
public JsonPath loadFile(String filecontent) throws OneOpsClientAPIException {

    if (filecontent == null || filecontent.length() == 0) {
        String msg = String.format("Missing input file content");
        throw new OneOpsClientAPIException(msg);
    }

    RequestSpecification request = createRequest();
    request.header("Content-Type", "multipart/text");
    MultipartEntityBuilder meb = MultipartEntityBuilder.create();
    meb.addTextBody("data", filecontent);
    JSONObject jo = new JSONObject();
    jo.put("data", filecontent);

    Response response = request.parameter("data", filecontent).put(DESIGN_URI + "load");
    if (response != null) {
        if (response.getStatusCode() == 200 || response.getStatusCode() == 302) {
            return response.getBody().jsonPath();
        } else {
            String msg = String.format("Failed to load yaml content due to %s", response.getStatusLine());
            throw new OneOpsClientAPIException(msg);
        }
    }
    String msg = String.format("Failed to load yaml content due to null response");
    throw new OneOpsClientAPIException(msg);
}

From source file:nzilbb.bas.BAS.java

/**
 * Invoke the Pho2Syl service to syllabify a phonemic transcription.
 * @param lng <a href="https://tools.ietf.org/html/rfc5646">RFC 5646</a> tag for identifying the language.
 * @param i 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 tier Name of tier in the annotation file, whose content is to be syllabified.
 * @param wsync Whether each word boundary is considered as syllable boundary.
 * @param oform Output format://from  w  ww.  j a  va  2  s. c o m
 *  <ul>
 *   <li>"bpf" - BAS Partiture format</li> 
 *   <li>"tg" - TextGrid format</li>
 *  </ul>
 * @param rate Only needed if <var>oform</var> = "tg" (TextGrid); Sample rate to convert sample values from BAS partiture file to seconds in TextGrid. 
 * @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 Pho2Syl(String lng, InputStream i, String tier, Boolean wsync, String oform, Integer rate)
        throws IOException, ParserConfigurationException {
    HttpPost request = new HttpPost(getPho2SylUrl());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create().addTextBody("lng", languageTagger.tag(lng))
            .addBinaryBody("i", i, ContentType.create("text/plain-bas"), "BAS.par").addTextBody("tier", tier)
            .addTextBody("oform", oform);
    if (wsync != null)
        builder.addTextBody("wsync", wsync ? "yes" : "no");
    if (rate != null)
        builder.addTextBody("rate", rate.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.adobe.aem.demo.communities.Loader.java

private static String doThumbnail(String hostname, String port, String adminPassword, String csvfile,
        String filename) {//ww w  .  j a v  a 2s .  c o m

    String pathToFile = "/content/dam/communities/resource-thumbnails/" + filename;
    File attachment = new File(csvfile.substring(0, csvfile.indexOf(".csv")) + File.separator + filename);

    ContentType ct = ContentType.MULTIPART_FORM_DATA;
    if (filename.indexOf(".mp4") > 0) {
        ct = ContentType.create("video/mp4", MIME.UTF8_CHARSET);
    } else if (filename.indexOf(".jpg") > 0 || filename.indexOf(".jpeg") > 0) {
        ct = ContentType.create("image/jpeg", MIME.UTF8_CHARSET);
    } else if (filename.indexOf(".png") > 0) {
        ct = ContentType.create("image/png", MIME.UTF8_CHARSET);
    }

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(MIME.UTF8_CHARSET);
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addBinaryBody("file", attachment, ct, attachment.getName());
    builder.addTextBody("fileName", filename, ContentType.create("text/plain", MIME.UTF8_CHARSET));

    logger.debug(
            "Adding file for thumbnails with name: " + attachment.getName() + " and type: " + ct.getMimeType());

    Loader.doPost(hostname, port, pathToFile, "admin", adminPassword, builder.build(), null);

    logger.debug("Path to thumbnail: " + pathToFile);

    return pathToFile + "/file";

}

From source file:com.lexmark.saperion.services.PutFileToSaperionECM.java

private static HttpEntity buildMultipart(String base64FileString, String fileName) throws IOException {
    String indexString = "indexName";
    StringBuilder jsonString = new StringBuilder();
    jsonString.append(setECMRequest(indexString, fileName));
    StringBody jsonBody = new StringBody(jsonString.toString(), ContentType.TEXT_PLAIN);

    FormBodyPart jsonBodyPart = new FormBodyPart("body", jsonBody);
    jsonBodyPart.addField("Content-Type", "application/json; charset=UTF-8");
    jsonBodyPart.addField("Content-ID", "body");

    StringBuilder fileBuilder = new StringBuilder();
    fileBuilder.append(base64FileString);
    StringBody fileBody = new StringBody(fileBuilder.toString(), ContentType.TEXT_PLAIN);

    FormBodyPart fileBodyPart = new FormBodyPart("filePart", fileBody);
    fileBodyPart.addField("Content-Type", "image/png");
    fileBodyPart.addField("Content-ID", "<imagefile>");

    MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
    multipartBuilder.setMode(HttpMultipartMode.STRICT);
    multipartBuilder.setBoundary("2676ff6efebdb664f8f7ccb34f864e25");
    multipartBuilder.addPart(jsonBodyPart);
    multipartBuilder.addPart(fileBodyPart);

    /*ByteArrayOutputStream out = new ByteArrayOutputStream();
    multipartBuilder.build().writeTo(out);
    out.close();/*from   ww w  . j  a  v a  2s .c o m*/
    String s = out.toString("UTF-8");
    System.err.println("output IS "+s);*/

    HttpEntity entity = multipartBuilder.build();
    return entity;

}

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.  j av a2s.c  o  m*/
                    "? ?    ? ? "
                            + 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:nzilbb.bas.BAS.java

/**
 * Invoke the MaryTTS German Text-to-speech service.
 * @param INPUT_TYPE One of://from w  ww .ja va2  s . c  o  m
 *  <ul>
 *   <li>"TEXT"</li>
 *   <li>"SIMPLEPHONEMES"</li>
 *   <li>"SABLE"</li>
 *   <li>"SSML"</li>
 *   <li>"APML"</li>
 *   <li>"PHONEMES"</li>
 *   <li>"INTONATION"</li>
 *   <li>"ACOUSTPARAMS"</li>
 *   <li>"RAWMARYXML"</li>
 *   <li>"TOKENS"</li>
 *   <li>"WORDS"</li>
 *   <li>"ALLOPHONES"</li>
 *   <li>"REALISED_ACOUSTPARAMS"</li>
 *   <li>"REALISED_DURATIONS"</li>
 *   <li>"PRAAT_TEXTGRID"</li>
 *   <li>"PARTSOFSPEECH"</li>
 *  </ul>
 * @param INPUT_TEXT The text input.
 * @param OUTPUT_TYPE One of:
 *  <ul>
 *   <li>"PHONEMES"</li>
 *   <li>"INTONATION"</li>
 *   <li>"ACOUSTPARAMS"</li>
 *   <li>"RAWMARYXML"</li>
 *   <li>"TOKENS"</li>
 *   <li>"WORDS"</li>
 *   <li>"ALLOPHONES"</li>
 *   <li>"REALISED_ACOUSTPARAMS"</li>
 *   <li>"REALISED_DURATIONS"</li>
 *   <li>"PRAAT_TEXTGRID"</li>
 *   <li>"PARTSOFSPEECH"</li>
 *   <li>"AUDIO"</li>
 *   <li>"HALFPHONE_TARGETFEATURES"</li>
 *  </ul>
 * @param AUDIO If <var>OUTPUT_TYPE</var> = "AUDIO", this can be one of:
 *  <ul>
 *   <li>"WAVE_FILE"</li>
 *   <li>"AU_FILE"</li>
 *   <li>"AIFF_FILE"</li>
 *  </ul>
 * @param VOICE One of:
 *  <ul>
 *   <li>"bits4unitselautolabel"</li>
 *   <li>"bits3unitselautolabel"</li>
 *   <li>"bits3"</li>
 *   <li>"bits2unitselautolabel"</li>
 *   <li>"bits1unitselautolabel"</li>
 *   <li>"bits4unitselautolabelhmm"</li>
 *   <li>"bits3unitselautolabelhmm"</li>
 *   <li>"bits3-hsmm"</li>
 *   <li>"bits2unitselautolabelhmm"</li>
 *   <li>"bits1unitselautolabelhmm"</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 TTS(String INPUT_TYPE, InputStream INPUT_TEXT, String OUTPUT_TYPE, String AUDIO,
        String VOICE) throws IOException, ParserConfigurationException {
    if (VOICE == null)
        VOICE = "bits1unitselautolabel";
    HttpPost request = new HttpPost(getTTSUrl());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create().addTextBody("INPUT_TYPE", INPUT_TYPE)
            .addBinaryBody("INPUT_TEXT", INPUT_TEXT, ContentType.create("text/plain"), "BAS.txt")
            .addTextBody("OUTPUT_TYPE", OUTPUT_TYPE).addTextBody("AUDIO", AUDIO).addTextBody("VOICE", VOICE);
    HttpEntity entity = builder.build();
    request.setEntity(entity);
    HttpResponse httpResponse = httpclient.execute(request);
    HttpEntity result = httpResponse.getEntity();
    return new BASResponse(result.getContent());
}

From source file:wsserver.EKF1TimerSessionBean.java

private void testPost() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//  ww w. j  a  va 2 s .  c om
        HttpPost httppost = new HttpPost(
                "http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample");

        FileBody bin = new FileBody(new File(""));
        StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment)
                .build();

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        try {
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                try {
                    EntityUtils.consume(resEntity);
                } catch (Exception ee) {

                }
            } finally {
                try {
                    response.close();
                } catch (Exception ee) {

                }
            }
        } catch (Exception ee) {

        }

    } finally {
        try {
            httpclient.close();
        } catch (Exception ee) {

        }
    }
}