List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder create
public static MultipartEntityBuilder create()
From source file:org.brutusin.rpc.client.http.HttpEndpoint.java
private CloseableHttpResponse doExec(String serviceId, JsonNode input, HttpMethod httpMethod, final ProgressCallback progressCallback) throws IOException { RpcRequest request = new RpcRequest(); request.setJsonrpc("2.0"); request.setMethod(serviceId);/* ww w . j av a 2s . co m*/ request.setParams(input); final String payload = JsonCodec.getInstance().transform(request); final HttpUriRequest req; if (httpMethod == HttpMethod.GET) { String urlparam = URLEncoder.encode(payload, "UTF-8"); req = new HttpGet(this.endpoint + "?jsonrpc=" + urlparam); } else { HttpEntityEnclosingRequestBase reqBase; if (httpMethod == HttpMethod.POST) { reqBase = new HttpPost(this.endpoint); } else if (httpMethod == HttpMethod.PUT) { reqBase = new HttpPut(this.endpoint); } else { throw new AssertionError(); } req = reqBase; HttpEntity entity; Map<String, InputStream> files = JsonCodec.getInstance().getStreams(input); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.STRICT); builder.addPart("jsonrpc", new StringBody(payload, ContentType.APPLICATION_JSON)); if (files != null && !files.isEmpty()) { files = sortFiles(files); for (Map.Entry<String, InputStream> entrySet : files.entrySet()) { String key = entrySet.getKey(); InputStream is = entrySet.getValue(); if (is instanceof MetaDataInputStream) { MetaDataInputStream mis = (MetaDataInputStream) is; builder.addPart(key, new InputStreamBody(mis, mis.getName())); } else { builder.addPart(key, new InputStreamBody(is, key)); } } } entity = builder.build(); if (progressCallback != null) { entity = new ProgressHttpEntityWrapper(entity, progressCallback); } reqBase.setEntity(entity); } HttpClientContext context = contexts.get(); if (this.clientContextFactory != null && context == null) { context = clientContextFactory.create(); contexts.set(context); } return this.httpClient.execute(req, context); }
From source file:org.apache.sling.testing.clients.osgi.OsgiConsoleClient.java
/** * Install a bundle using the Felix webconsole HTTP interface, with a specific start level * @param f/*from w w w . j a va 2s. c o m*/ * @param startBundle * @param startLevel * @return the sling response * @throws ClientException */ public SlingHttpResponse installBundle(File f, boolean startBundle, int startLevel) throws ClientException { // Setup request for Felix Webconsole bundle install MultipartEntityBuilder builder = MultipartEntityBuilder.create().addTextBody("action", "install") .addBinaryBody("bundlefile", f); if (startBundle) { builder.addTextBody("bundlestart", "true"); } if (startLevel > 0) { builder.addTextBody("bundlestartlevel", String.valueOf(startLevel)); LOG.info("Installing bundle {} at start level {}", f.getName(), startLevel); } else { LOG.info("Installing bundle {} at default start level", f.getName()); } return this.doPost(URL_BUNDLES, builder.build(), 302); }
From source file:com.shenit.commons.utils.HttpUtils.java
/** * Create a multipart form/*from w ww.j a v a 2 s .c o m*/ * * @param request * Request object * @param keyVals * Key and value pairs, the even(begins with 0) position params * are key and the odds are values * @return */ public static HttpUriRequest multipartForm(HttpPost request, Object... keyVals) { if (request == null || ValidationUtils.isEmpty(keyVals)) return request; MultipartEntityBuilder builder = MultipartEntityBuilder.create(); boolean hasVal = false; String key; for (int i = 0; i < keyVals.length; i += 2) { key = ShenStrings.str(keyVals[i]); hasVal = i + 1 < keyVals.length; if (!hasVal || keyVals[i + 1] == null) { builder.addTextBody(key, StringUtils.EMPTY, CONTENT_TYPE_PLAIN_TEXT); break; } if (keyVals[i + 1].getClass().isAssignableFrom(File.class)) { builder.addPart(key, new FileBody((File) keyVals[i + 1])); } else { builder.addTextBody(key, keyVals[i + 1].toString(), CONTENT_TYPE_PLAIN_TEXT); } } request.setEntity(builder.build()); return request; }
From source file:org.openbaton.sdk.api.util.RestRequest.java
/** * Used to upload tar files to the NFVO for creating VNFPackages. * * @param f the tar file containing the VNFPackage * @return the created VNFPackage object * @throws SDKException//from ww w .j av a2 s .com */ public VNFPackage requestPostPackage(final File f) throws SDKException { CloseableHttpResponse response = null; HttpPost httpPost = null; try { try { checkToken(); } catch (IOException e) { log.error(e.getMessage(), e); throw new SDKException("Could not get token", e); } log.debug("Executing post on " + baseUrl); httpPost = new HttpPost(this.baseUrl); httpPost.setHeader(new BasicHeader("accept", "multipart/form-data")); httpPost.setHeader(new BasicHeader("project-id", projectId)); if (token != null) httpPost.setHeader(new BasicHeader("authorization", bearerToken.replaceAll("\"", ""))); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addBinaryBody("file", f); httpPost.setEntity(multipartEntityBuilder.build()); response = httpClient.execute(httpPost); } catch (ClientProtocolException e) { httpPost.releaseConnection(); throw new SDKException("Could not create VNFPackage from file " + f.getName(), e); } catch (IOException e) { httpPost.releaseConnection(); throw new SDKException("Could not create VNFPackage from file " + f.getName(), e); } // check response status checkStatus(response, HttpURLConnection.HTTP_OK); // return the response of the request String result = ""; if (response.getEntity() != null) try { result = EntityUtils.toString(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(result); result = mapper.toJson(jsonElement); log.debug("Uploaded the VNFPackage"); log.trace("received: " + result); log.trace("Casting it into: " + VNFPackage.class); httpPost.releaseConnection(); return mapper.fromJson(result, VNFPackage.class); } httpPost.releaseConnection(); return null; }
From source file:org.apache.sling.scripting.sightly.it.SlingSpecificsSightlyIT.java
private void uploadFile(String fileName, String serverFileName, String url) throws IOException { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(launchpadURL + url); post.setHeader("Authorization", "Basic YWRtaW46YWRtaW4="); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); InputStreamBody inputStreamBody = new InputStreamBody( this.getClass().getClassLoader().getResourceAsStream(fileName), ContentType.TEXT_PLAIN, fileName); entityBuilder.addPart(serverFileName, inputStreamBody); post.setEntity(entityBuilder.build()); httpClient.execute(post);// w ww .ja v a2s . c om }
From source file:org.geogig.geoserver.rest.GeoGigWebAPIIntegrationTest.java
@Test public void testGeoPackageImport() throws Exception { URL url = getClass().getResource("places.gpkg"); // create transaction final String beginTransactionUrl = BASE_URL + "/beginTransaction"; Document dom = getAsDOM(beginTransactionUrl); assertXpathEvaluatesTo("true", "/response/success", dom); String transactionId = XMLUnit.newXpathEngine().evaluate("/response/Transaction/ID", dom); // import geopackage final String importUrl = BASE_URL + "/import?format=gpkg&message=Import%20GeoPackage&transactionId=" + transactionId;//from w w w .j av a 2 s . co m final String endTransactionUrl = BASE_URL + "/endTransaction?transactionId=" + transactionId; // construct a multipart request with the fileUpload MultipartEntityBuilder builder = MultipartEntityBuilder.create(); File f = new File(url.getFile()); builder.addBinaryBody("fileUpload", new FileInputStream(f), ContentType.APPLICATION_OCTET_STREAM, f.getName()); HttpEntity multipart = builder.build(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); multipart.writeTo(outputStream); MockHttpServletResponse response = postAsServletResponse(importUrl, outputStream.toByteArray(), multipart.getContentType().getValue()); assertEquals(200, response.getStatus()); dom = dom(new ByteArrayInputStream(response.getContentAsString().getBytes()), true); String taskId = XMLUnit.newXpathEngine().evaluate("/task/id", dom); final String taskUrl = "/geogig/tasks/" + taskId + ".xml"; while ("RUNNING".equals(XMLUnit.newXpathEngine().evaluate("/task/status", dom))) { Thread.sleep(100); dom = getAsDOM(taskUrl); } assertXpathEvaluatesTo("FINISHED", "/task/status", dom); String commitId = XMLUnit.newXpathEngine().evaluate("//commit/id", dom); // close transaction dom = getAsDOM(endTransactionUrl); assertXpathEvaluatesTo("true", "/response/success", dom); // verify the repo contains the import Repository repository = geogigData.getGeogig().getRepository(); RevCommit head = repository.getCommit(repository.getHead().get().getObjectId()); assertEquals(commitId, head.getId().toString()); assertEquals("Import GeoPackage", head.getMessage()); }
From source file:org.wisdom.framework.vertx.FileUploadTest.java
@Test public void testThatFileUpdateFailedWhenTheFileExceedTheConfiguredSize() throws InterruptedException, IOException { // Prepare the configuration ApplicationConfiguration configuration = mock(ApplicationConfiguration.class); when(configuration.getIntegerWithDefault(eq("vertx.http.port"), anyInt())).thenReturn(0); when(configuration.getIntegerWithDefault(eq("vertx.https.port"), anyInt())).thenReturn(-1); when(configuration.getIntegerWithDefault("vertx.acceptBacklog", -1)).thenReturn(-1); when(configuration.getIntegerWithDefault("vertx.receiveBufferSize", -1)).thenReturn(-1); when(configuration.getIntegerWithDefault("vertx.sendBufferSize", -1)).thenReturn(-1); when(configuration.getLongWithDefault("http.upload.disk.threshold", DiskFileUpload.MINSIZE)) .thenReturn(DiskFileUpload.MINSIZE); when(configuration.getLongWithDefault("http.upload.max", -1l)).thenReturn(10l); // 10 bytes max when(configuration.getStringArray("wisdom.websocket.subprotocols")).thenReturn(new String[0]); when(configuration.getStringArray("vertx.websocket-subprotocols")).thenReturn(new String[0]); // Prepare the router with a controller Controller controller = new DefaultController() { @SuppressWarnings("unused") public Result index() { return ok(); }/*from w ww . j a va2 s .c o m*/ }; Router router = mock(Router.class); Route route = new RouteBuilder().route(HttpMethod.POST).on("/").to(controller, "index"); when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route); ContentEngine contentEngine = getMockContentEngine(); // Configure the server. server = new WisdomVertxServer(); server.accessor = new ServiceAccessor(null, configuration, router, contentEngine, executor, null, Collections.<ExceptionMapper>emptyList()); server.configuration = configuration; server.vertx = vertx; server.start(); VertxHttpServerTest.waitForStart(server); int port = server.httpPort(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost post = new HttpPost("http://localhost:" + port + "/?id=" + 1); ByteArrayBody body = new ByteArrayBody("this is too much...".getBytes(), "my-file.dat"); StringBody description = new StringBody("my description", ContentType.TEXT_PLAIN); HttpEntity entity = MultipartEntityBuilder.create().addPart("upload", body).addPart("comment", description) .build(); post.setEntity(entity); CloseableHttpResponse response = httpclient.execute(post); // We should receive a Payload too large response (413) assertThat(response.getStatusLine().getStatusCode()).isEqualTo(413); }
From source file:net.ymate.framework.commons.HttpClientHelper.java
public IHttpResponse upload(String url, String fieldName, ContentBody uploadFile, Header[] headers, final String defaultResponseCharset) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {//from w ww. ja v a 2s. co m RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url) .setEntity(MultipartEntityBuilder.create().addPart(fieldName, uploadFile).build()); if (headers != null && headers.length > 0) { for (Header _header : headers) { _reqBuilder.addHeader(_header); } } return _httpClient.execute(_reqBuilder.build(), new ResponseHandler<IHttpResponse>() { public IHttpResponse handleResponse(HttpResponse response) throws IOException { if (StringUtils.isNotBlank(defaultResponseCharset)) { return new IHttpResponse.NEW(response, defaultResponseCharset); } return new IHttpResponse.NEW(response); } }); } finally { _httpClient.close(); } }
From source file:org.rundeck.api.ApiCall.java
private <T> T requestWithEntity(ApiPathBuilder apiPath, Handler<HttpResponse, T> handler, HttpEntityEnclosingRequestBase httpPost) { if (null != apiPath.getAccept()) { httpPost.setHeader("Accept", apiPath.getAccept()); }//from w ww . ja v a 2 s . c om // POST a multi-part request, with all attachments if (apiPath.getAttachments().size() > 0 || apiPath.getFileAttachments().size() > 0) { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); ArrayList<File> tempfiles = new ArrayList<>(); //attach streams for (Entry<String, InputStream> attachment : apiPath.getAttachments().entrySet()) { if (client.isUseIntermediateStreamFile()) { //transfer to file File f = copyToTempfile(attachment.getValue()); multipartEntityBuilder.addBinaryBody(attachment.getKey(), f); tempfiles.add(f); } else { multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue()); } } if (tempfiles.size() > 0) { handler = TempFileCleanupHandler.chain(handler, tempfiles); } //attach files for (Entry<String, File> attachment : apiPath.getFileAttachments().entrySet()) { multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue()); } httpPost.setEntity(multipartEntityBuilder.build()); } else if (apiPath.getForm().size() > 0) { try { httpPost.setEntity(new UrlEncodedFormEntity(apiPath.getForm(), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RundeckApiException("Unsupported encoding: " + e.getMessage(), e); } } else if (apiPath.getContentStream() != null && apiPath.getContentType() != null) { if (client.isUseIntermediateStreamFile()) { ArrayList<File> tempfiles = new ArrayList<>(); File f = copyToTempfile(apiPath.getContentStream()); tempfiles.add(f); httpPost.setEntity(new FileEntity(f, ContentType.create(apiPath.getContentType()))); handler = TempFileCleanupHandler.chain(handler, tempfiles); } else { InputStreamEntity entity = new InputStreamEntity(apiPath.getContentStream(), ContentType.create(apiPath.getContentType())); httpPost.setEntity(entity); } } else if (apiPath.getContents() != null && apiPath.getContentType() != null) { ByteArrayEntity bae = new ByteArrayEntity(apiPath.getContents(), ContentType.create(apiPath.getContentType())); httpPost.setEntity(bae); } else if (apiPath.getContentFile() != null && apiPath.getContentType() != null) { httpPost.setEntity( new FileEntity(apiPath.getContentFile(), ContentType.create(apiPath.getContentType()))); } else if (apiPath.getXmlDocument() != null) { httpPost.setHeader("Content-Type", "application/xml"); httpPost.setEntity(new EntityTemplate(new DocumentContentProducer(apiPath.getXmlDocument()))); } else if (apiPath.isEmptyContent()) { //empty content } else { throw new IllegalArgumentException("No Form or Multipart entity for POST content-body"); } return execute(httpPost, handler); }