List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder create
public static MultipartEntityBuilder create()
From source file:nzilbb.bas.BAS.java
/** * Invokes the G2P service for converting orthography into phonemic transcription. * @param lng <a href="https://tools.ietf.org/html/rfc5646">RFC 5646</a> tag for identifying the language. * @param i The text to transform.// w w w. j a v a2 s. c o m * @param iform The format of <var>i</var> - * <ul> * <li>"txt" indicates connected text input, which will be tokenized before the conversion.</li> * <li>"list" indicates a sequence of unconnected words, that does not need to be tokenized. Furthermore, "list" requires a different part-of-speech tagging strategy than "txt" for the extraction of the "extended" feature set (see Parameter <var>featset</var>).</li> * <li>"tg" indicates TextGrid input. Long and short format is supported. For TextGrid input additionally the name of the item containing the words to be transcribed is to be specified by the parameter "tgname". In combination with "bpf" output format "tg" input additionally requires the specification of the sample rate by the parameter "tgrate".</li> * <li>"tcf" indicates, that the input format is TCF containing at least a tokenization dominated by the element "tokens".</li> * <li>Input format "bpf" indicates BAS partitur file input containing an ORT tier to be transcribed.</li> * </ul> * @param tgitem Only needed, if <var>iform</var> is "tg". Name of the TextGrid item, that contains the words to be transcribed. In case of TextGrid output, this item is the reference for the added items. * @param tgrate Only needed, if <var>iform</var> is "tg" and oform is "bpf(s)". Sample rate to convert time values from TextGrid to sample values in BAS partiture file. * @param outsym Ouput phoneme symbol inventory: * <ul> * <li>"sampa" - language-specific SAMPA variant is the default.</li> * <li>"x-sampa" - language independent X-SAMPA and IPA can be chosen.</li> * <li>"maus-sampa" - maps the output to a language-specific phoneme subset that WEBMAUS can process.</li> * <li>"ipa" - Unicode-encoded IPA.</li> * <li>"arpabet" - supported for eng-US only</li> * </ul> * @param featset - Feature set used for grapheme-phoneme conversion. * <ul> * <li>"standard" comprises a letter window centered on the grapheme to be converted.</li> * <li>"extended" set additionally includes part of speech and morphological analyses.</li> * </ul> * @param oform Output format: * <ul> * <li>"bpf" indicates the BAS Partitur Format (BPF) file with a KAN tier.</li> * <li>"bpfs" differs from "bpf" only in that respect, that the phonemes are separated by blanks. In case of TextGrid input, both "bpf" and "bpfs" require the additional parameters "tgrate" and "tgitem". The content of the TextGrid tier "tgitem" is stored as a word chunk segmentation in the partiture tier TRN.</li> * <li>"txt" indicates a replacement of the input words by their transcriptions; single line output without punctuation, where phonemes are separated by blanks and words by tabulators.</li> * <li>"tab" returns the grapheme phoneme conversion result in form of a table with two columns. The first column comprises the words, the second column their blank-separated transcriptions.</li> * <li>"exttab" results in a 5-column table. The columns contain from left to right: words, transcriptions, part of speech, morpheme segmentations, and morpheme class segmentations.</li> * <li>"lex" transforms the table to a lexicon, i.e. words are unique and sorted.</li> * <li>"extlex" provides the same information as "exttab" in a unique and sorted manner. For all lex and tab outputs columns are separated by ';'.</li> * <li>"exttcf" which is currently available for German and English only additionally adds part of speech (STTS tagset), morphs, and morph classes.</li> * <li>With "tg" and "exttg" TextGrid output is produced.</li> * </ul> * @param syl whether or not word stress is to be added to the output transcription. * @param stress whether or not the output transcription is to be syllabified. * @param nrm Detects and expands 22 non-standard word types. * @param com whether <*> strings should be treated as annotation markers. If true, then strings of this type are considered as annotation markers that are not processed but passed on to the output. * @param align "yes", "no", or "sym" decision whether or not the transcription is to be letter-aligned. Syllable boundaries and word stress are not part of the output of this 'sym' alignment. * @return The result of this call. * @throws IOException If an IO error occurs. * @throws ParserConfigurationException If the XML parser for parsing the response could not be configured. */ public BASResponse G2P(String lng, InputStream i, String iform, String tgitem, int tgrate, String outsym, String featset, String oform, boolean syl, boolean stress, boolean nrm, boolean com, String align) throws IOException, ParserConfigurationException { HttpPost request = new HttpPost(getG2PUrl()); HttpEntity entity = MultipartEntityBuilder.create().addTextBody("lng", languageTagger.tag(lng)) .addBinaryBody("i", i, ContentType.create("text/plain"), "BAS." + iform).addTextBody("iform", iform) .addTextBody("tgitem", tgitem).addTextBody("tgrate", "" + tgrate).addTextBody("outsym", outsym) .addTextBody("featset", featset).addTextBody("oform", oform).addTextBody("syl", syl ? "yes" : "no") .addTextBody("stress", stress ? "yes" : "no").addTextBody("nrm", nrm ? "yes" : "no") .addTextBody("com", nrm ? "yes" : "no").addTextBody("align", align).build(); request.setEntity(entity); HttpResponse httpResponse = httpclient.execute(request); HttpEntity result = httpResponse.getEntity(); return new BASResponse(result.getContent()); }
From source file:io.swagger.client.api.CameraApi.java
/** * Stop liveview/* ww w .j a v a 2 s. co m*/ * * @return void */ public void liveviewStopPost() throws TimeoutException, ExecutionException, InterruptedException, ApiException { Object postBody = null; // create path and map variables String path = "/liveview/stop".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>(); 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:io.swagger.client.api.CameraApi.java
/** * Stop liveview/*from w ww. ja va2 s.c om*/ * */ public void liveviewStopPost(final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) { Object postBody = null; // create path and map variables String path = "/liveview/stop".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>(); 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 { apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames, new Response.Listener<String>() { @Override public void onResponse(String localVarResponse) { responseListener.onResponse(localVarResponse); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { errorListener.onErrorResponse(error); } }); } catch (ApiException ex) { errorListener.onErrorResponse(new VolleyError(ex)); } }
From source file:org.openbaton.marketplace.core.VNFPackageManagement.java
public void dispatch(VNFPackageMetadata vnfPackageMetadata) throws FailedToUploadException { RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(60000) .build();// ww w . j a v a 2s. com CloseableHttpResponse response = null; HttpPost httpPost = null; String url = "https://" + fitEagleIp + ":" + fitEaglePort + "/OpenBaton/upload/v2"; try { log.debug("Executing post on " + url); httpPost = new HttpPost(url); // httpPost.setHeader(new BasicHeader("Accept", "multipart/form-data")); // httpPost.setHeader(new BasicHeader("Content-type", "multipart/form-data")); httpPost.setHeader(new BasicHeader("username", userManagement.getCurrentUser())); httpPost.setHeader(new BasicHeader("filename", vnfPackageMetadata.getVnfPackageFileName())); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addBinaryBody("file", vnfPackageMetadata.getVnfPackageFile()); httpPost.setEntity(multipartEntityBuilder.build()); CloseableHttpClient client = getHttpClientForSsl(config); response = client.execute(httpPost); } catch (ClientProtocolException e) { httpPost.releaseConnection(); e.printStackTrace(); log.error("NotAble to upload VNFPackage"); throw new FailedToUploadException( "Not Able to upload VNFPackage to Fiteagle because: " + e.getMessage()); } catch (IOException e) { httpPost.releaseConnection(); e.printStackTrace(); httpPost.releaseConnection(); log.error("NotAble to upload VNFPackage"); throw new FailedToUploadException( "Not Able to upload VNFPackage to Fiteagle because: " + e.getMessage()); } // check response status String result = ""; if (response != null && response.getEntity() != null) { try { result = EntityUtils.toString(response.getEntity()); } catch (IOException e) { e.printStackTrace(); httpPost.releaseConnection(); throw new FailedToUploadException( "Not Able to upload VNFPackage to Fiteagle because: " + e.getMessage()); } } if (response != null && response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { log.debug("Uploaded the VNFPackage"); log.debug("received: " + result); if (vnfPackageMetadata.getRequirements() == null) { vnfPackageMetadata.setRequirements(new HashMap<String, String>()); } vnfPackageMetadata.getRequirements().put("fiteagle-id", result); } else throw new FailedToUploadException( "Not Able to upload VNFPackage to Fiteagle because: Fiteagle answered " + response.getStatusLine().getStatusCode()); httpPost.releaseConnection(); }
From source file:io.swagger.client.api.CameraApi.java
/** * Set camera settings/*from w w w . ja va 2 s . co m*/ * Allow to set camera settings * @param body order placed for purchasing the pet * @return void */ public void settingsPost(CameraSettings body) throws TimeoutException, ExecutionException, InterruptedException, ApiException { Object postBody = body; // create path and map variables String path = "/settings".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>(); 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.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) */// w w w .java2 s . c o m @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:org.wso2.msf4j.HttpServerTest.java
@Test public void testFormParamWithMultipart() throws IOException, URISyntaxException { HttpURLConnection connection = request("/test/v1/formParam", HttpMethod.POST); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("name", new StringBody("wso2", ContentType.TEXT_PLAIN)); builder.addPart("age", new StringBody("10", ContentType.TEXT_PLAIN)); HttpEntity build = builder.build();/*from w w w. ja v a 2 s .c o m*/ connection.setRequestProperty("Content-Type", build.getContentType().getValue()); try (OutputStream out = connection.getOutputStream()) { build.writeTo(out); } InputStream inputStream = connection.getInputStream(); String response = StreamUtil.asString(inputStream); IOUtils.closeQuietly(inputStream); connection.disconnect(); assertEquals(response, "wso2:10"); }
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/*from w w w . ja v a 2 s .c o 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:io.swagger.client.api.CameraApi.java
/** * Set camera settings//from ww w .j a v a2 s.c om * Allow to set camera settings * @param body order placed for purchasing the pet */ public void settingsPost(CameraSettings body, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) { Object postBody = body; // create path and map variables String path = "/settings".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>(); 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 { apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames, new Response.Listener<String>() { @Override public void onResponse(String localVarResponse) { responseListener.onResponse(localVarResponse); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { errorListener.onErrorResponse(error); } }); } catch (ApiException ex) { errorListener.onErrorResponse(new VolleyError(ex)); } }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testFormDataParamWithSimpleRequest() throws IOException, URISyntaxException { // Send x-form-url-encoded request HttpURLConnection connection = request("/test/v1/formDataParam", HttpMethod.POST); String rawData = "name=wso2&age=10"; ByteBuffer encodedData = Charset.defaultCharset().encode(rawData); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED); connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length)); try (OutputStream os = connection.getOutputStream()) { os.write(Arrays.copyOf(encodedData.array(), encodedData.limit())); }/*ww w . j a v a 2s .com*/ InputStream inputStream = connection.getInputStream(); String response = StreamUtil.asString(inputStream); IOUtils.closeQuietly(inputStream); connection.disconnect(); assertEquals(response, "wso2:10"); // Send multipart/form-data request connection = request("/test/v1/formDataParam", HttpMethod.POST); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("name", new StringBody("wso2", ContentType.TEXT_PLAIN)); builder.addPart("age", new StringBody("10", ContentType.TEXT_PLAIN)); HttpEntity build = builder.build(); connection.setRequestProperty("Content-Type", build.getContentType().getValue()); try (OutputStream out = connection.getOutputStream()) { build.writeTo(out); } inputStream = connection.getInputStream(); response = StreamUtil.asString(inputStream); IOUtils.closeQuietly(inputStream); connection.disconnect(); assertEquals(response, "wso2:10"); }