/** * This method is used to send slack notification. * * @return boolean slack response * @throws IOException */ private void notifyOnSlack(Employee employee, Visitor visitor, SlackChannel channel, String locationName) throws IOException { Map<String,ContentBody> attachment = createAttachment(imageService.getBaseDirPathAsStr(), visitor.getVisitorPic(), imageService.getDefaultImageFile()); Map<String, String> param = null; if (Objects.nonNull(employee)) { String slackMessage = createMessage(configurationService.getSlackConfiguration().getMessage(), visitor, employee, locationName); param = buildSlackRequestParam(employee.getSlackId(), slackMessage, configurationService.getSlackConfiguration().getToken()); } else { String channelMessage = messageForChannel(configurationService.getSlackConfiguration(). getChannelMessage(), visitor, channel, locationName); param = buildSlackRequestParam(channel.getChannelId(), channelMessage, configurationService.getSlackConfiguration().getToken()); } slackService.sendMessage(param, attachment); }
private HttpPost composeMultiPartFormRequest(final String uri, final Parameters parameters, final Map<String, ContentBody> files) { HttpPost request = new HttpPost(uri); MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try { Charset utf8 = Charset.forName("UTF-8"); for(Parameter param : parameters) if(param.isSingleValue()) multiPartEntity.addPart(param.getName(), new StringBody(param.getValue(), utf8)); else for(String value : param.getValues()) multiPartEntity.addPart(param.getName(), new StringBody(value, utf8)); } catch (UnsupportedEncodingException e) { throw MechanizeExceptionFactory.newException(e); } List<String> fileNames = new ArrayList<String>(files.keySet()); Collections.sort(fileNames); for(String name : fileNames) { ContentBody contentBody = files.get(name); multiPartEntity.addPart(name, contentBody); } request.setEntity(multiPartEntity); return request; }
private void uploadDatabase() throws Exception { tempDB = File.createTempFile("temp_", ".sqlite", serviceModule.getDirectoryPath()); databaseManager.mergeRecord().dumpDatabaseTo(tempDB); // check if database is empty if (databaseManager.mergeRecord().isEmpty(tempDB)) { FLog.d("database is empty"); return; } HashMap<String, ContentBody> extraParts = new HashMap<String, ContentBody>(); extraParts.put("user", new StringBody(databaseManager.getUserId())); if (!uploadFile("db", Request.DATABASE_UPLOAD_REQUEST(serviceModule), tempDB, serviceModule.getDirectoryPath(), extraParts)) { FLog.d("Failed to upload database"); return; } }
/** * Determines the total length of the multipart content (content length of * individual parts plus that of extra elements required to delimit the parts * from one another). If any of the @{link BodyPart}s contained in this object * is of a streaming entity of unknown length the total length is also unknown. * <p> * This method buffers only a small amount of data in order to determine the * total length of the entire entity. The content of individual parts is not * buffered. * </p> * * @return total length of the multipart entity if known, {@code -1} * otherwise. */ public long getTotalLength() { long contentLen = 0; for (final FormBodyPart part: getBodyParts()) { final ContentBody body = part.getBody(); final long len = body.getContentLength(); if (len >= 0) { contentLen += len; } else { return -1; } } final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { doWriteTo(out, false); final byte[] extra = out.toByteArray(); return contentLen + extra.length; } catch (final IOException ex) { // Should never happen return -1; } }
/** * @deprecated (4.4) use {@link org.apache.http.entity.mime.FormBodyPartBuilder}. */ @Deprecated protected void generateContentType(final ContentBody body) { final ContentType contentType; if (body instanceof AbstractContentBody) { contentType = ((AbstractContentBody) body).getContentType(); } else { contentType = null; } if (contentType != null) { addField(MIME.CONTENT_TYPE, contentType.toString()); } else { final StringBuilder buffer = new StringBuilder(); buffer.append(body.getMimeType()); // MimeType cannot be null if (body.getCharset() != null) { // charset may legitimately be null buffer.append("; charset="); buffer.append(body.getCharset()); } addField(MIME.CONTENT_TYPE, buffer.toString()); } }
@Test public void testMismatch() throws Exception { ContentBody cb = genContent(); startUpload(cb, 100); // session - 0 // next expected segment - 1 // epoch - 0 // no such session tryUploading(cb, journalId, 5, 2, 0, true, false); // journalId mismatch tryUploading(cb, journalId + "foo", 0, 1, 0, true, false); // out of order tryUploading(cb, journalId, 0, 2, 0, true, false); // valid segment tryUploading(cb, journalId, 0, 1, 0, false, false); // valid + close tryUploading(cb, journalId, 0, 2, 0, false, true); // try uploading after close tryUploading(cb, journalId, 0, 2, 0, true, true); }
/** * Create image with given txid. Finalize and/or delete md5 file if specified. */ private void createImage(long txid, boolean finalize, boolean removeMd5) throws IOException { // create image ContentBody cb = genContent(txid); HttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = TestJournalNodeImageUpload.createRequest( httpAddress, cb); UploadImageParam.setHeaders(postRequest, journalId, FAKE_NSINFO.toColonSeparatedString(), 0, txid, 0, 0, true); httpClient.execute(postRequest); if (finalize) { // roll the image journal.saveDigestAndRenameCheckpointImage(txid, digests.get(txid)); // remove md5 file if requested which leaves only the image file if (removeMd5) { MD5FileUtils.getDigestFileForFile( journal.getImageStorage().getImageFile(txid)).delete(); } } }
/** * Generate random contents for the image and store it together with the md5 * for later comparison. */ private ContentBody genContent(long txid) throws IOException { MessageDigest digester = MD5Hash.getDigester(); // write through digester so we can roll the written image ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); DigestOutputStream ds = new DigestOutputStream(bos, digester); // generate random bytes new Random().nextBytes(randomBytes); ds.write(randomBytes); ds.flush(); // get written hash MD5Hash hash = new MD5Hash(digester.digest()); // store contents and digest digests.put(txid, hash); content.put(txid, Arrays.copyOf(randomBytes, randomBytes.length)); return new ByteArrayBody(bos.toByteArray(), "filename"); }
@Test public void testOTAWrongToken() throws Exception { HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123); post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth)); String fileName = "test.bin"; InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName); ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("upfile", fileBody); HttpEntity entity = builder.build(); post.setEntity(entity); try (CloseableHttpResponse response = httpclient.execute(post)) { assertEquals(400, response.getStatusLine().getStatusCode()); String error = consumeText(response); assertNotNull(error); assertEquals("Invalid token.", error); } }
@Test public void testAuthorizationFailed() throws Exception { HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123); post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString("123:123".getBytes())); String fileName = "test.bin"; InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName); ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("upfile", fileBody); HttpEntity entity = builder.build(); post.setEntity(entity); try (CloseableHttpResponse response = httpclient.execute(post)) { assertEquals(403, response.getStatusLine().getStatusCode()); String error = consumeText(response); assertNotNull(error); assertEquals("Authentication failed.", error); } }
/** * Upload with <a href="http://www.sockshare.com/apidocs.php">API</a>. */ private void apiUpload() throws UnsupportedEncodingException, IOException, Exception{ uploading(); ContentBody cbFile = createMonitoredFileBody(); NUHttpPost httppost = new NUHttpPost(apiURL); MultipartEntity mpEntity = new MultipartEntity(); mpEntity.addPart("file", cbFile); mpEntity.addPart("user", new StringBody(sockShareAccount.username)); mpEntity.addPart("password", new StringBody(sockShareAccount.password)); httppost.setEntity(mpEntity); HttpResponse response = httpclient.execute(httppost); String reqResponse = EntityUtils.toString(response.getEntity()); //NULogger.getLogger().info(reqResponse); if(reqResponse.contains("File Uploaded Successfully")){ gettingLink(); downURL = StringUtils.stringBetweenTwoStrings(reqResponse, "<link>", "</link>"); } else{ //Handle the errors status = UploadStatus.GETTINGERRORS; throw new Exception(StringUtils.stringBetweenTwoStrings(reqResponse, "<message>", "</message>")); } }
private static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); //httppost.setHeader("Cookie", sidcookie+";"+mysessioncookie); file = new File("h:/UploadingdotcomUploaderPlugin.java"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("notprivate", new StringBody("false")); mpEntity.addPart("folder", new StringBody("/")); mpEntity.addPart("Filedata", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into zippyshare.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } downloadlink=parseResponse(uploadresponse, "value=\"http://", "\""); downloadlink="http://"+downloadlink; System.out.println("Download Link : "+downloadlink); httpclient.getConnectionManager().shutdown(); }
private static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); file = new File("h:/UploadingdotcomUploaderPlugin.java"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("emai", new StringBody("Free")); mpEntity.addPart("upload_range", new StringBody("1")); mpEntity.addPart("upfile_0", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into MegaShare.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); uploadresponse = response.getLastHeader("Location").getValue(); System.out.println("Upload response : "+uploadresponse); System.out.println(response.getStatusLine()); httpclient.getConnectionManager().shutdown(); }
public static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(postURL); File file = new File("d:/hai.html"); System.out.println(ukeycookie); httppost.setHeader("Cookie", ukeycookie + ";" + skeycookie + ";" + usercookie); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("", cbFile); httppost.setEntity(mpEntity); System.out.println("Now uploading your file into mediafire..........................."); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Getting upload response key value.........."); uploadresponsekey = EntityUtils.toString(resEntity); getUploadResponseKey(); System.out.println("upload resoponse key " + uploadresponsekey); } }
private static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); file = new File("h:/install.txt"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("Filedata", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into sharesend.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } System.out.println("Upload Response : " + uploadresponse); System.out.println("Download Link : http://sharesend.com/" + uploadresponse); httpclient.getConnectionManager().shutdown(); }
private static void fileUpload() throws Exception { file = new File("/home/vigneshwaran/VIGNESH/dinesh.txt"); httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("ssd", new StringBody(ssd)); mpEntity.addPart("Filedata", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into slingfile.com"); HttpResponse response = httpclient.execute(httppost); // HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); }
private static void fileUpload() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); httppost.setHeader("Cookie", sidcookie); file = new File("h:/install.txt"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("filepc", cbFile); mpEntity.addPart("server", new StringBody(server)); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into uploadbox.com"); HttpResponse response = httpclient.execute(httppost); System.out.println(response.getStatusLine()); uploadresponse = response.getLastHeader("Location").getValue(); uploadresponse = getData(uploadresponse); downloadlink = parseResponse(uploadresponse, "name=\"loadlink\" id=\"loadlink\" class=\"text\" onclick=\"this.select();\" value=\"", "\""); deletelink = parseResponse(uploadresponse, "name=\"deletelink\" id=\"deletelink\" class=\"text\" onclick=\"this.select();\" value=\"", "\""); System.out.println("Download link " + downloadlink); System.out.println("deletelink : " + deletelink); }
public static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); file = new File("/home/vigneshwaran/dinesh.txt"); HttpPost httppost = new HttpPost(postURL); httppost.setHeader("Cookie", langcookie + ";" + sessioncookie + ";" + mailcookie + ";" + namecookie + ";" + rolecookie + ";" + orderbycookie + ";" + directioncookie + ";"); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("files[]", cbFile); httppost.setEntity(mpEntity); System.out.println("Now uploading your file into wupload..........................."); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (response.getStatusLine().getStatusCode() == 302 && response.getFirstHeader("Location").getValue().contains("upload/done/")) { System.out.println("Upload successful :)"); } else { System.out.println("Upload failed :("); } }
private static void fileUpload() throws Exception { file = new File("C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\Sample Pictures\\Sunset.jpg"); httpclient = new DefaultHttpClient(); //http://upload3.divshare.com/cgi-bin/upload.cgi?sid=8ef15852c69579ebb2db1175ce065ba6 HttpPost httppost = new HttpPost(downURL + "cgi-bin/upload.cgi?sid=" + sid); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("file[0]", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into divshare.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(resEntity)); }
private static void fileUpload() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); file = new File("h:/Sakura haruno.jpg"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("Filedata", cbFile); // mpEntity.addPart("server", new StringBody(server)); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into ugotfile.com"); HttpResponse response = httpclient.execute(httppost); System.out.println(response.getStatusLine()); if (response != null) { uploadresponse = EntityUtils.toString(response.getEntity()); } System.out.println("Upload Response : " + uploadresponse); downloadlink = parseResponse(uploadresponse, "[\"", "\""); downloadlink = downloadlink.replaceAll("\\\\/", "/"); deletelink = parseResponse(uploadresponse, "\",\"", "\""); deletelink = deletelink.replaceAll("\\\\/", "/"); System.out.println("Download Link : " + downloadlink); System.out.println("Delete Link : " + deletelink); }
public static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); file = new File("C:\\Documents and Settings\\dinesh\\Desktop\\GeDotttUploaderPlugin.java"); HttpPost httppost = new HttpPost("https://docs.zoho.com/uploadsingle.do?isUploadStatus=false&folderId=0&refFileElementId=refFileElement0"); httppost.setHeader("Cookie", cookies.toString()); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("multiupload_file", cbFile); httppost.setEntity(mpEntity); System.out.println("Now uploading your file into zoho docs..........................."); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { String tmp = EntityUtils.toString(resEntity); // System.out.println(tmp); if(tmp.contains("File Uploaded Successfully")) System.out.println("File Uploaded Successfully"); } // uploadresponse = response.getLastHeader("Location").getValue(); // System.out.println("Upload response : " + uploadresponse); }
public FormBodyPart(final String name, final ContentBody body) { super(); if (name == null) { throw new IllegalArgumentException("Name may not be null"); } if (body == null) { throw new IllegalArgumentException("Body may not be null"); } this.name = name; Header header = new Header(); setHeader(header); setBody(body); generateContentDisp(body); generateContentType(body); generateTransferEncoding(body); }
protected HttpPost setupPostWithFileName(HttpPost request, String fileName){ if (fileName == null || fileName.length() == 0) return request; ContentBody fileBody = new FileBody(new File(fileName), ContentType.DEFAULT_BINARY); MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setBoundary("boundaryABC--WebKitFormBoundaryGMApUciYGfDuPa49"); multipartEntity.addPart("file", fileBody); request.setEntity(multipartEntity.build()); // MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "boundaryABC--WebKitFormBoundaryGMApUciYGfDuPa49", Charset.forName("UTF-8")); // mpEntity.addPart("userfile", fileBody); // request.setEntity(mpEntity); // FileEntity entity = new FileEntity(new File(fileName), ContentType.APPLICATION_OCTET_STREAM); // BasicHeader basicHeader = new BasicHeader(HTTP.CONTENT_TYPE,"application/json"); //request.getParams().setBooleanParameter("http.protocol.expect-continue", false); // entity.setContentType(basicHeader); // request.setEntity(mpEntity); return request; }
/** * Determines the total length of the multipart content (content length of * individual parts plus that of extra elements required to delimit the parts * from one another). If any of the @{link BodyPart}s contained in this object * is of a streaming entity of unknown length the total length is also unknown. * <p/> * This method buffers only a small amount of data in order to determine the * total length of the entire entity. The content of individual parts is not * buffered. * * @return total length of the multipart entity if known, <code>-1</code> * otherwise. */ public long getTotalLength() { long contentLen = 0; for (FormBodyPart part: this.parts) { ContentBody body = part.getBody(); long len = body.getContentLength(); if (len >= 0) { contentLen += len; } else { return -1; } } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { doWriteTo(this.mode, out, false); byte[] extra = out.toByteArray(); return contentLen + extra.length; } catch (IOException ex) { // Should never happen return -1; } }
public FormBodyPart(final String name, final ContentBody body) { super(); if (name == null) { throw new IllegalArgumentException("Name may not be null"); } if (body == null) { throw new IllegalArgumentException("Body may not be null"); } this.name = name; this.body = body; this.header = new Header(); generateContentDisp(body); generateContentType(body); generateTransferEncoding(body); }
public ContentBody toContentBody() { if (file != null) { return new FileBody(file) { @Override public String getFilename() { return fileName; } }; } else if (data != null) { return new ByteBufferBody(data) { @Override public String getFilename() { return fileName; } }; } else { // never happens throw new IllegalStateException("no upload data"); } }
public static byte[] postApiRaw(final String path, Object... arguments) throws Exception { Map<String, Object> args = argMap(path, arguments); final List<NameValuePair> params = createParamsList(); final URI uri = createURI(API_POST_SCHEME, path, params); final MultipartEntity entity = new MultipartEntity(); for (String name : args.keySet()) { final Object value = args.get(name); if(value instanceof ContentBody) entity.addPart(name, (ContentBody)value); else entity.addPart(name, new StringBody(value.toString())); } // for ... final HttpPost httppost = new HttpPost(uri); httppost.setEntity(entity); return executeRaw(httppost); }
/** * Determines the total length of the multipart content (content length of * individual parts plus that of extra elements required to delimit the parts * from one another). If any of the @{link BodyPart}s contained in this object * is of a streaming entity of unknown length the total length is also unknown. * <p> * This method buffers only a small amount of data in order to determine the * total length of the entire entity. The content of individual parts is not * buffered. * </p> * * @return total length of the multipart entity if known, {@code -1} otherwise. */ public long getTotalLength() { long contentLen = 0; for (final FormBodyPart part: getBodyParts()) { final ContentBody body = part.getBody(); final long len = body.getContentLength(); if (len >= 0) { contentLen += len; } else { return -1; } } final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { doWriteTo(out, false); final byte[] extra = out.toByteArray(); return contentLen + extra.length; } catch (final IOException ex) { // Should never happen return -1; } }
@Override protected HttpEntity buildEntity(ICommRestRequest restRequest) throws Exception{ ICommRestMultiPartRequest multiPartRequest = null; if( restRequest instanceof ICommRestMultiPartRequest){ multiPartRequest = (ICommRestMultiPartRequest) restRequest; } MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT); if(multiPartRequest != null){ for(NameValuePair nvp:multiPartRequest.getNameValuePairs()) { if(nvp.getName().equalsIgnoreCase("File")) { File file = new File(nvp.getValue()); FileBody isb = new FileBody(file,"application/*"); entity.addPart(nvp.getName(), isb); } else { try{ LogHelper.w("RestRequest-Request",nvp.getName() + ": " + nvp.getValue()); ContentBody cb = new StringBody(nvp.getValue(),"", null); entity.addPart(nvp.getName(),cb); }catch(Exception ex){ LogHelper.e("MultiElementJsonRestHandler", "failed to add name value pair to HttpEntity with " + ex.getMessage()); } } } } return entity; }
/** * @param dirPath * @param imageDbpath * @param defaultImageFile * @return * @throws IOException */ public Map<String, ContentBody> createAttachment(String dirPath, String imageDbpath, File defaultImageFile) throws IOException { Map<String, ContentBody> parameters = new HashMap<>(); if (StringUtils.isNotBlank(imageDbpath)) { parameters.put(NotificationKey.file.name(), new FileBody(new File(Util.getImageFullPath(dirPath, imageDbpath)))); } else { parameters.put(NotificationKey.file.name(), new FileBody(defaultImageFile)); } return parameters; }
/**used to send slack notification. * * @param param * @param attachment */ public void sendMessage(Map<String, String> param, Map<String, ContentBody> attachment) { try { CloseableHttpResponse res = httpConnector.postRequest(HttpConnectorHelper.buildMultiPartEntity(param, attachment), Constants.SLACK_FILE_SEND_API); logger.info(res.toString()); } catch(Exception e) { logger.error("Exception while sending slack notifaction.",e); } }
/** * @param buildMap * @param partParam * * @return HttpEntity */ public static HttpEntity buildMultiPartEntity(Map<String, String> buildMap, Map<String, ContentBody> partParam) { if (MapUtils.isEmpty(buildMap)) { return null; } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); buildMap.forEach((k, v) -> builder.addTextBody(k, v)); if (MapUtils.isNotEmpty(partParam)) { partParam.forEach((k, v) -> builder.addPart(k, v)); } return builder.build(); }