List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder build
public HttpEntity build()
From source file:gda.util.ElogEntry.java
/** * Post eLog Entry/*from w w w . ja v a2 s . c om*/ */ public void post() throws ELogEntryException { String entryType = "41";// entry type is always a log (41) String titleForPost = visit == null ? title : "Visit: " + visit + " - " + title; String content = buildContent(); MultipartEntityBuilder request = MultipartEntityBuilder.create().addTextBody("txtTITLE", titleForPost) .addTextBody("txtCONTENT", content).addTextBody("txtLOGBOOKID", logID) .addTextBody("txtGROUPID", groupID).addTextBody("txtENTRYTYPEID", entryType) .addTextBody("txtUSERID", userID); HttpEntity entity = request.build(); HttpPost httpPost = new HttpPost(targetPostURL); httpPost.setEntity(entity); CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; try { httpClient = HttpClients.createDefault(); response = httpClient.execute(httpPost); String responseString = EntityUtils.toString(response.getEntity()); System.out.println(responseString); if (!responseString.contains("New Log Entry ID")) { throw new ELogEntryException("Upload failed, status=" + response.getStatusLine().getStatusCode() + " response=" + responseString + " targetURL = " + targetPostURL + " titleForPost = " + titleForPost + " logID = " + logID + " groupID = " + groupID + " entryType = " + entryType + " userID = " + userID); } } catch (ELogEntryException e) { throw e; } catch (Exception e) { throw new ELogEntryException("Error in ELogger. Database:" + targetPostURL, e); } finally { try { if (httpClient != null) httpClient.close(); if (response != null) response.close(); } catch (IOException e) { elogger.error("Could not close connections", e); } } }
From source file:com.alibaba.shared.django.DjangoClient.java
protected void uploadFileChunks(InputStream is, int maxChunkSize, final String fileId, final int sequence, final String fillename, List<DjangoMessage> holder) throws IOException, URISyntaxException { final MessageDigest digest = Digests.defaultDigest(); byte[] buf = new byte[8000]; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = is.read(buf), processCount = len; while (len >= 0 && processCount < maxChunkSize) { baos.write(buf, 0, len);/*from w ww. j a va 2s . c o m*/ digest.update(buf, 0, len); processCount += len; if (maxChunkSize <= processCount) { break; } len = is.read(buf); } if (processCount > 0) { holder.add(executeRequest(new Supplier<HttpUriRequest>() { public HttpUriRequest get() { MultipartEntityBuilder meb = MultipartEntityBuilder.create(); meb.addTextBody(ACCESS_TOKEN_KEY, accessToken()).addTextBody("fileId", fileId) .addTextBody("sequence", String.valueOf(sequence)) .addTextBody("md5", Digests.toHexDigest(digest.digest())).addBinaryBody(FILE_KEY, baos.toByteArray(), ContentType.APPLICATION_OCTET_STREAM, fillename); HttpPost post = new HttpPost(chunkUrl); post.setEntity(meb.build()); return post; } })); uploadFileChunks(is, maxChunkSize, fileId, sequence + 1, fillename, holder); } }
From source file:com.gargoylesoftware.htmlunit.HttpWebConnectionTest.java
/** * Test that the right file part is built for a file that doesn't exist. * @throws Exception if the test fails//from www.j av a 2 s .c o m */ @Test public void buildFilePart() throws Exception { final String encoding = "ISO8859-1"; final KeyDataPair pair = new KeyDataPair("myFile", new File("this/doesnt_exist.txt"), "text/plain", encoding); final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setLaxMode(); try (final HttpWebConnection webConnection = new HttpWebConnection(getWebClient())) { webConnection.buildFilePart(pair, builder); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); builder.build().writeTo(baos); final String part = baos.toString(encoding); final String expected = "--(.*)\r\n" + "Content-Disposition: form-data; name=\"myFile\"; filename=\"doesnt_exist.txt\"\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "\r\n" + "--\\1--\r\n"; assertTrue(part, part.matches(expected)); }
From source file:com.neighbor.ex.tong.network.UploadFileAndMessage.java
@Override protected Void doInBackground(Void... voids) { try {//from w ww .jav a 2 s . co m MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addTextBody("message", URLEncoder.encode(message, "UTF-8"), ContentType.create("Multipart/related", "UTF-8")); builder.addPart("image", new FileBody(new File(path))); InputStream inputStream = null; HttpClient httpClient = AndroidHttpClient.newInstance("Android"); String carNo = prefs.getString(CONST.ACCOUNT_LICENSE, ""); String encodeCarNo = ""; if (false == carNo.equals("")) { encodeCarNo = URLEncoder.encode(carNo, "UTF-8"); } HttpPost httpPost = new HttpPost(UPLAOD_URL + encodeCarNo); httpPost.setEntity(builder.build()); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); inputStream = httpEntity.getContent(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuilder stringBuilder = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line + "\n"); } inputStream.close(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.patch.QMetryRestWebservice.java
/** * attach log using run id/*from w ww.j a v a2 s. co m*/ * * @param token * - token generate using username and password * @param projectID * @param releaseID * @param cycleID * @param testCaseRunId * @param filePath * - absolute path of file to be attached * @return */ public int attachTestLogsUsingRunId(String token, String projectID, String releaseID, String cycleID, long testCaseRunId, File filePath) { try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss"); final String CurrentDate = format.format(new Date()); Path path = Paths.get(filePath.toURI()); byte[] outFileArray = Files.readAllBytes(path); if (outFileArray != null) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(baseURL + "/rest/attachments/testLog"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(filePath); builder.addTextBody("desc", "Attached on " + CurrentDate, ContentType.TEXT_PLAIN); builder.addTextBody("type", "TCR", ContentType.TEXT_PLAIN); builder.addTextBody("entityId", String.valueOf(testCaseRunId), ContentType.TEXT_PLAIN); builder.addPart("file", bin); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); httppost.addHeader("usertoken", token); httppost.addHeader("scope", projectID + ":" + releaseID + ":" + cycleID); CloseableHttpResponse response = httpclient.execute(httppost); String str = null; try { str = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } finally { } JsonElement gson = new Gson().fromJson(str, JsonElement.class); JsonElement data = gson.getAsJsonObject().get("data"); int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString()); return id; } finally { httpclient.close(); } } else { System.out.println(filePath + " file does not exists"); } } catch (Exception ex) { System.out.println("Error in attaching file - " + filePath); System.out.println(ex.getMessage()); } return 0; }
From source file:de.siegmar.securetransfer.controller.MvcTest.java
@Test public void messageWithFileWithPassword() throws Exception { final String messageToSend = "my secret message"; final String password = "top secret password"; final String fileContent = "test file content"; final String boundary = "------TestBoundary" + UUID.randomUUID(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setBoundary(boundary) .addTextBody("expirationDays", "1").addTextBody("message", messageToSend) .addTextBody("password", password).addBinaryBody("files", fileContent.getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_OCTET_STREAM, "test.txt"); // Create new message and expect redirect with flash message after store final MvcResult createMessageResult = mockMvc .perform(post("/send").content(ByteStreams.toByteArray(builder.build().getContent())) .contentType(MediaType.MULTIPART_FORM_DATA_VALUE + "; boundary=" + boundary)) .andExpect(status().isFound()).andExpect(redirectedUrlPattern("/send/**")) .andExpect(flash().attribute("message", messageToSend)).andReturn(); // receive data after redirect final String messageStatusUrl = createMessageResult.getResponse().getRedirectedUrl(); final String linkSecret = messageStatusUrl.replaceFirst(".*linkSecret=", ""); HashCode.fromString(linkSecret);/* w w w .ja va2s .c om*/ final MvcResult messageStatusResult = mockMvc.perform(get(messageStatusUrl)).andExpect(status().isOk()) .andExpect(content().contentType("text/html;charset=UTF-8")) .andExpect(view().name("send/message_status")).andReturn(); final SenderMessage senderMessage = (SenderMessage) messageStatusResult.getModelAndView().getModel() .get("senderMessage"); assertNotNull(senderMessage); assertNotNull(senderMessage.getId()); assertNotNull(senderMessage.getReceiverId()); assertNotNull(senderMessage.getExpiration()); assertNull(senderMessage.getReceived()); assertTrue(senderMessage.isPasswordEncrypted()); final String receiveUrl = (String) messageStatusResult.getModelAndView().getModel().get("receiveUrl"); assertNotNull(receiveUrl); // call receiver URL final MvcResult confirmPage = mockMvc.perform(get(receiveUrl)).andExpect(status().isOk()) .andExpect(content().contentType("text/html;charset=UTF-8")) .andExpect(view().name("receive/message_ask_password")).andReturn(); final Document confirmPageDoc = Jsoup.parse(confirmPage.getResponse().getContentAsString()); final String passwordUrl = confirmPageDoc.getElementsByTag("form").attr("action"); // Receive message final MvcResult messageResult = mockMvc .perform(post(passwordUrl).param("linkSecret", linkSecret).param("password", password)) .andExpect(status().isOk()).andExpect(content().contentType("text/html;charset=UTF-8")) .andExpect(view().name("receive/message")).andReturn(); final DecryptedMessage decryptedMessage = (DecryptedMessage) messageResult.getModelAndView().getModel() .get("decryptedMessage"); assertEquals(messageToSend, decryptedMessage.getMessage()); assertEquals(1, decryptedMessage.getFiles().size()); final DecryptedFile file = decryptedMessage.getFiles().get(0); final String fileId = file.getId(); final String fileKey = file.getKeyHex(); // Download file final MvcResult downloadResult = mockMvc .perform(get("/receive/file/{id}/{key}", fileId, fileKey).sessionAttr("iv_file_" + fileId, file.getKeyIv().getIv())) .andExpect(request().asyncStarted()) //.andExpect(request().asyncResult("Deferred result")) .andExpect(status().isOk()).andExpect(content().contentType("application/octet-stream")) .andReturn(); downloadResult.getAsyncResult(); assertEquals(fileContent, downloadResult.getResponse().getContentAsString()); // Check message is burned mockMvc.perform(get(receiveUrl)).andExpect(status().isNotFound()) .andExpect(content().contentType("text/html;charset=UTF-8")) .andExpect(view().name("message_not_found")); // Check file is burned mockMvc.perform(get("/receive/file/{id}/{key}", fileId, fileKey).sessionAttr("iv_file_" + fileId, file.getKeyIv().getIv())).andExpect(status().isNotFound()) .andExpect(content().contentType("text/html;charset=UTF-8")) .andExpect(view().name("message_not_found")); // Check sender status page final MvcResult messageStatusResult2 = mockMvc.perform(get(messageStatusUrl)).andExpect(status().isOk()) .andExpect(content().contentType("text/html;charset=UTF-8")) .andExpect(view().name("send/message_status")).andReturn(); final SenderMessage senderMessage2 = (SenderMessage) messageStatusResult2.getModelAndView().getModel() .get("senderMessage"); assertNotNull(senderMessage2); assertNotNull(senderMessage2.getId()); assertNotNull(senderMessage2.getReceiverId()); assertNotNull(senderMessage2.getExpiration()); assertNotNull(senderMessage2.getReceived()); assertTrue(senderMessage.isPasswordEncrypted()); }
From source file:org.wso2.appcloud.integration.test.utils.clients.ApplicationClient.java
public void changeAppIcon(String applicationHash, File appIcon) throws AppCloudIntegrationTestException { HttpClient httpclient = null;//from www . j a v a 2s . c o m org.apache.http.HttpResponse response = null; try { httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build(); int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).build(); HttpPost httppost = new HttpPost(this.endpoint); httppost.setConfig(requestConfig); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(PARAM_NAME_CHANGE_ICON, new FileBody(appIcon)); builder.addPart(PARAM_NAME_ACTION, new StringBody(CHANGE_APP_ICON_ACTION, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APPLICATION_HASH_ID, new StringBody(applicationHash, ContentType.TEXT_PLAIN)); httppost.setEntity(builder.build()); httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE)); response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity()); throw new AppCloudIntegrationTestException("Update app icon failed " + result); } } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) { // In most of the cases, even though connection is timed out, actual activity is completed. // And this will be asserted so if it failed due to a valid case, it will be captured. log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1); } catch (IOException e) { log.error("Failed to invoke app icon update API.", e); throw new AppCloudIntegrationTestException("Failed to invoke app icon update API.", e); } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(httpclient); } }