List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder build
public HttpEntity build()
From source file:com.collaide.fileuploader.requests.repository.FilesRequest.java
/** * send a file on the server/* w w w . j a va2 s. c om*/ * * @param file the file to send * @param id the id of the folder (on the server) to send the file. If the * id is equal to zero, the file is send to the root repository */ public void create(File file, int id) { HttpPost httppost = getHttpPostForCreate(); FileBody bin = new FileBody(file); MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create().addPart("repo_file[file]", bin) .addTextBody("authenticity_token", CurrentUser.getUser().getCsrf()); if (id != 0) { reqEntity.addTextBody("repo_file[id]", String.valueOf(id)); } httppost.setEntity(reqEntity.build()); httppost.setHeader("X-CSRF-Token", CurrentUser.getUser().getCsrf()); SendFileThread sendFile = new SendFileThread(httppost, getHttpClient()); sendFile.start(); getSendFileList().add(sendFile); if (getSendFileList().size() >= getMaxConnection()) { terminate(); } }
From source file:org.lokra.seaweedfs.core.VolumeWrapper.java
/** * Upload file.//from w w w.java 2 s . c om * * @param url url * @param fid fid * @param fileName fileName * @param stream stream * @param ttl ttl * @param contentType contentType * @return The size returned is the size stored on SeaweedFS. * @throws IOException Http connection is fail or server response within some error message. */ long uploadFile(String url, String fid, String fileName, InputStream stream, String ttl, ContentType contentType) throws IOException { HttpPost request; if (ttl != null) request = new HttpPost(url + "/" + fid + "?ttl=" + ttl); else request = new HttpPost(url + "/" + fid); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(CharsetUtils.get("UTF-8")); builder.addBinaryBody("upload", stream, contentType, fileName); HttpEntity entity = builder.build(); request.setEntity(entity); JsonResponse jsonResponse = connection.fetchJsonResultByRequest(request); convertResponseStatusToException(jsonResponse.statusCode, url, fid, false, false, false, false); return (Integer) objectMapper.readValue(jsonResponse.json, Map.class).get("size"); }
From source file:org.retrostore.data.BlobstoreWrapperImpl.java
@Override public void addScreenshot(String appId, byte[] data, Responder.ContentType contentType, String cookie) { Preconditions.checkArgument(!Strings.isNullOrEmpty(appId), "'appId' missing"); Preconditions.checkArgument(data != null && data.length > 0, "'data' is empty"); Preconditions.checkNotNull(contentType, "'contentType' missing"); Preconditions.checkArgument(!Strings.isNullOrEmpty(cookie), "'cookie' missing"); LOG.info(String.format("About to add a screenshot blob of size %d with type %s.", data.length, contentType.str));// w ww .j ava2 s .c o m final String PATH_UPLOAD = "/screenshotUpload"; String forwardTo = PATH_UPLOAD + "?appId=" + appId; LOG.info("Forward to: " + forwardTo); String uploadUrl = createUploadUrl(forwardTo); LOG.info("UploadUrl: " + uploadUrl); // It is important that we set the cookie so that we're authenticated. We do not allow // anonymous requests to upload screenshots. HttpPost post = new HttpPost(uploadUrl); post.setHeader("Cookie", cookie); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Note we need to use the deprecated constructor so we can use our content type. builder.addPart("file", new ByteArrayBody(data, contentType.str, "screenshot")); HttpEntity entity = builder.build(); post.setEntity(entity); HttpClient client = HttpClientBuilder.create().build(); try { LOG.info("POST constructed. About to make request!"); HttpResponse response = client.execute(post); LOG.info("Request succeeded!"); ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); LOG.info(new String(out.toByteArray(), "UTF-8")); } catch (IOException e) { LOG.log(Level.SEVERE, "Cannot make POST request.", e); } }
From source file:io.wcm.maven.plugins.contentpackage.DownloadMojo.java
/** * Download content package from CRX instance *///from ww w .j a va2s . c o m private File downloadFile(File file, String ouputFilePath) throws MojoExecutionException { try (CloseableHttpClient httpClient = getHttpClient()) { getLog().info("Download " + file.getName() + " from " + getCrxPackageManagerUrl()); // 1st: try upload to get path of package - or otherwise make sure package def exists (no install!) HttpPost post = new HttpPost(getCrxPackageManagerUrl() + "/.json?cmd=upload"); MultipartEntityBuilder entity = MultipartEntityBuilder.create().addBinaryBody("package", file) .addTextBody("force", "true"); post.setEntity(entity.build()); JSONObject jsonResponse = executePackageManagerMethodJson(httpClient, post); boolean success = jsonResponse.optBoolean("success", false); String msg = jsonResponse.optString("msg", null); String path = jsonResponse.optString("path", null); // package already exists - get path from error message and continue if (!success && StringUtils.startsWith(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX) && StringUtils.isEmpty(path)) { path = StringUtils.substringAfter(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX); success = true; } if (!success) { throw new MojoExecutionException("Package path detection failed: " + msg); } getLog().info("Package path is: " + path + " - now rebuilding package..."); // 2nd: build package HttpPost buildMethod = new HttpPost(getCrxPackageManagerUrl() + "/console.html" + path + "?cmd=build"); executePackageManagerMethodHtml(httpClient, buildMethod, 0); // 3rd: download package String crxUrl = StringUtils.removeEnd(getCrxPackageManagerUrl(), "/crx/packmgr/service"); HttpGet downloadMethod = new HttpGet(crxUrl + path); // execute download CloseableHttpResponse response = httpClient.execute(downloadMethod); try { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // get response stream InputStream responseStream = response.getEntity().getContent(); // delete existing file File outputFileObject = new File(ouputFilePath); if (outputFileObject.exists()) { outputFileObject.delete(); } // write response file FileOutputStream fos = new FileOutputStream(outputFileObject); IOUtil.copy(responseStream, fos); fos.flush(); responseStream.close(); fos.close(); getLog().info("Package downloaded to " + outputFileObject.getAbsolutePath()); return outputFileObject; } else { throw new MojoExecutionException( "Package download failed:\n" + EntityUtils.toString(response.getEntity())); } } finally { if (response != null) { EntityUtils.consumeQuietly(response.getEntity()); try { response.close(); } catch (IOException ex) { // ignore } } } } catch (FileNotFoundException ex) { throw new MojoExecutionException("File not found: " + file.getAbsolutePath(), ex); } catch (IOException ex) { throw new MojoExecutionException("Download operation failed.", ex); } }
From source file:io.wcm.maven.plugins.contentpackage.InstallMojo.java
/** * Deploy file via package manager/*from www. j av a 2 s. c o m*/ */ private void installFile(File file) throws MojoExecutionException { try (CloseableHttpClient httpClient = getHttpClient()) { // if bundles are still stopping/starting, wait for completion waitForBundlesActivation(httpClient); if (this.install) { getLog().info("Upload and install " + file.getName() + " to " + getCrxPackageManagerUrl()); } else { getLog().info("Upload " + file.getName() + " to " + getCrxPackageManagerUrl()); } // prepare post method HttpPost post = new HttpPost(getCrxPackageManagerUrl() + "/.json?cmd=upload"); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addBinaryBody("package", file); if (this.force) { entityBuilder.addTextBody("force", "true"); } post.setEntity(entityBuilder.build()); // execute post JSONObject jsonResponse = executePackageManagerMethodJson(httpClient, post); boolean success = jsonResponse.optBoolean("success", false); String msg = jsonResponse.optString("msg", null); String path = jsonResponse.optString("path", null); if (success) { if (this.install) { getLog().info("Package uploaded, now installing..."); try { post = new HttpPost(getCrxPackageManagerUrl() + "/console.html" + new URIBuilder().setPath(path).build().getRawPath() + "?cmd=install" + (this.recursive ? "&recursive=true" : "")); } catch (URISyntaxException ex) { throw new MojoExecutionException("Invalid path: " + path, ex); } // execute post executePackageManagerMethodHtml(httpClient, post, 0); } else { getLog().info("Package uploaded successfully (without installing)."); } } else if (StringUtils.startsWith(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX) && !this.force) { getLog().info("Package skipped because it was already uploaded."); } else { throw new MojoExecutionException("Package upload failed: " + msg); } } catch (IOException ex) { throw new MojoExecutionException("Install operation failed.", ex); } }
From source file:com.king.ess.gsa.GSAFeedForm.java
/** * It sends XML with feeds to GSA using proper form: * //from w ww . j a v a 2s . c om * @param xmlDocument GSADocumentFormatter containing XML Document information * * @return Was posted Ok? */ public boolean sendForm(GSADocumentFormatter xmlDocument) { boolean bSent = false; HttpClient client = HttpClientBuilder.create().build(); try { HttpPost postPageRequest; postPageRequest = new HttpPost(this.gsaServer); InputStream is = xmlDocument.writeToInputStream(); // Add Form parameters MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(FEEDTYPE_PARAM, xmlDocument.getFeedType(), ContentType.TEXT_PLAIN); builder.addTextBody(DATASOURCE_PARAM, xmlDocument.getDatasource(), ContentType.TEXT_PLAIN); builder.addBinaryBody(XMLFILE_PARAM, is); HttpEntity multipartEntity = builder.build(); postPageRequest.setEntity(multipartEntity); HttpResponse postPageResponse = client.execute(postPageRequest); int status = postPageResponse.getStatusLine().getStatusCode(); if (!(bSent = (status == 200))) log.error("GitHub API (" + this.gsaServer + ") returned " + status); else log.info("XML For datasource '" + xmlDocument.getDatasource() + "' and FeedType '" + xmlDocument.getFeedType() + "' was posted successfully to GSA!!"); } catch (Exception e) { log.error("Exception " + e.getMessage() + " in HTTP request " + this.gsaServer); } return bSent; }
From source file:it.polimi.diceH2020.plugin.net.NetworkManager.java
/** * Sends to the backend the models to be simulated * // ww w. j av a 2 s.c o m * @param files * The model files * @param scenario * The scenario parameter * @throws UnsupportedEncodingException */ public void sendModel(List<File> files, String scenario) throws UnsupportedEncodingException { HttpClient httpclient = HttpClients.createDefault(); HttpResponse response; HttpPost post = new HttpPost(uploadRest); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("scenario", new StringBody(scenario, ContentType.DEFAULT_TEXT)); for (File file : files) { builder.addPart("file[]", new FileBody(file)); } post.setEntity(builder.build()); try { response = httpclient.execute(post); String json = EntityUtils.toString(response.getEntity()); HttpPost repost = new HttpPost(this.getLink(json)); response = httpclient.execute(repost); String js = EntityUtils.toString(response.getEntity()); parseJson(js); System.out.println("Code : " + response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { System.err.println("Error: POST not succesfull"); } else { } System.out.println(Configuration.getCurrent().getID()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.kurento.test.recorder.RecorderIT.java
private void testRecord(String handler, int statusCode) throws IOException { // To follow redirect: .setRedirectStrategy(new LaxRedirectStrategy()) HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost("http://localhost:" + getServerPort() + "/kmf-content-api-test/" + handler); MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); File file = new File("small"); URL small = new URL(VideoURLs.map.get("small-webm")); FileUtils.copyURLToFile(small, file); FileBody fb = new FileBody(file); multipartEntity.addPart("file", fb); HttpEntity httpEntity = multipartEntity.build(); post.setEntity(httpEntity);//from w w w .j a v a 2s.c om EntityUtils.consume(httpEntity); HttpResponse response = client.execute(post); final int responseStatusCode = response.getStatusLine().getStatusCode(); log.info("Response Status Code: {}", responseStatusCode); log.info("Deleting tmp file: {}", file.delete()); Assert.assertEquals("HTTP response status code must be " + statusCode, statusCode, responseStatusCode); }
From source file:org.flowable.ui.modeler.service.AppDefinitionPublishService.java
protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey, String deploymentName) {//from w ww .j a va 2 s. c om String deployApiUrl = modelerAppProperties.getDeploymentApiUrl(); Assert.hasText(deployApiUrl, "flowable.modeler.app.deployment-api-url must be set"); String basicAuthUser = properties.getIdmAdmin().getUser(); String basicAuthPassword = properties.getIdmAdmin().getPassword(); String tenantId = tenantProvider.getTenantId(); if (!deployApiUrl.endsWith("/")) { deployApiUrl = deployApiUrl.concat("/"); } deployApiUrl = deployApiUrl .concat(String.format("app-repository/deployments?deploymentKey=%s&deploymentName=%s", encode(deploymentKey), encode(deploymentName))); if (tenantId != null) { StringBuilder sb = new StringBuilder(deployApiUrl); sb.append("&tenantId=").append(encode(tenantId)); deployApiUrl = sb.toString(); } HttpPost httpPost = new HttpPost(deployApiUrl); httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.getEncoder() .encode((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8"))))); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName); HttpEntity entity = entityBuilder.build(); httpPost.setEntity(entity); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); clientBuilder .setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } })); } catch (Exception e) { LOGGER.error("Could not configure SSL for http client", e); throw new InternalServerErrorException("Could not configure SSL for http client", e); } CloseableHttpClient client = clientBuilder.build(); try { HttpResponse response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { return; } else { LOGGER.error("Invalid deploy result code: {} for url", response.getStatusLine() + httpPost.getURI().toString()); throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine()); } } catch (IOException ioe) { LOGGER.error("Error calling deploy endpoint", ioe); throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage()); } finally { if (client != null) { try { client.close(); } catch (IOException e) { LOGGER.warn("Exception while closing http client", e); } } } }