List of usage examples for javax.mail BodyPart getHeader
public String[] getHeader(String header_name) throws MessagingException;
From source file:immf.SendMailBridge.java
private void parseBodypart(SenderMail sendMail, BodyPart bp, String subtype, String parentSubtype) throws IOException { boolean limiterr = false; String badfile = null;// ww w. jav a 2s. c om try { String contentType = bp.getContentType().toLowerCase(); log.info("Bodypart ContentType:" + contentType); log.info("subtype:" + subtype); if (contentType.startsWith("multipart/")) { parseMultipart(sendMail, (Multipart) bp.getContent(), getSubtype(contentType), subtype); } else if (sendMail.getPlainTextContent() == null && contentType.startsWith("text/plain")) { // ???plain/text? String content = (String) bp.getContent(); log.info("set Content text [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); sendMail.setPlainTextContent(content); } else if (sendMail.getHtmlContent() == null && contentType.startsWith("text/html") && (subtype.equalsIgnoreCase("alternative") || subtype.equalsIgnoreCase("related"))) { String content = (String) bp.getContent(); log.info("set Content html [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); // html???? sendMail.setHtmlContent(content); } else if (contentType.startsWith("text/html")) { // subtype?mixed?? String content = (String) bp.getContent(); if (sendMail.getHtmlContent() == null) { // text/plain???????? text/html????????? log.info("set Content html [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); // html???? sendMail.setHtmlContent(content); } else { log.info("Discarding duplicate content [" + content + "]"); } } else { log.debug("attach"); // ???? if (subtype.equalsIgnoreCase("related")) { // SenderAttachment file = new SenderAttachment(); String fname = uniqId(); String fname2 = Util.getFileName(bp); // iPhone?gifpng?????????????ContentType(?png???gif?) if (getSubtype(contentType).equalsIgnoreCase("png")) { file.setContentType("image/gif"); fname = fname + ".gif"; fname2 = getBasename(fname2) + ".gif"; file.setData(inputstream2bytes(Util.png2gif(bp.getInputStream()))); } else { file.setContentType(contentType); fname = fname + "." + getSubtype(contentType); file.setData(inputstream2bytes(bp.getInputStream())); } file.setInline(true); boolean inline = !this.forcePlainText & sendMail.checkAttachmentCapability(file); if (!inline) { file.setInline(false); if (!sendMail.checkAttachmentCapability(file)) { limiterr = true; badfile = fname2; throw new Exception("Attachments: size limit or file count limit exceeds!"); } } if (inline) { file.setFilename(fname); file.setContentId(bp.getHeader("Content-Id")[0]); log.info("Inline Attachment " + file.loggingString() + ", Hash:" + file.getHash()); } else { file.setFilename(fname2); log.info("Attachment " + file.loggingString()); } sendMail.addAttachmentFileIdList(file); } else { // ? SenderAttachment file = new SenderAttachment(); file.setInline(false); file.setContentType(contentType); String fname = Util.getFileName(bp); if (getSubtype(contentType).equalsIgnoreCase("png")) { file.setContentType("image/gif"); file.setFilename(getBasename(fname) + ".gif"); file.setData(inputstream2bytes(Util.png2gif(bp.getInputStream()))); } else { file.setFilename(fname); file.setData(inputstream2bytes(bp.getInputStream())); } if (!sendMail.checkAttachmentCapability(file)) { limiterr = true; badfile = file.getFilename(); throw new Exception("Attachments: size limit or file count limit exceeds!"); } sendMail.addAttachmentFileIdList(file); log.info("Attachment " + file.loggingString()); } } } catch (Exception e) { log.error("parse bodypart error.", e); if (limiterr) { sendMail.addPlainTextContent("\n[(" + badfile + ")]"); if (sendMail.getHtmlContent() != null) { sendMail.addHtmlContent("[(" + badfile + ")]<br>"); } } else { throw new IOException("BodyPart error." + e.getMessage(), e); } } }
From source file:immf.SendMailBridge.java
private void parseBodypartmixed(SenderMail sendMail, BodyPart bp, String subtype, String parentSubtype) throws IOException { boolean limiterr = false; String badfile = null;// w w w . ja v a2s . co m try { String contentType = bp.getContentType().toLowerCase(); log.info("Bodypart ContentType:" + contentType); log.info("subtype:" + subtype); if (contentType.startsWith("multipart/")) { parseMultipart(sendMail, (Multipart) bp.getContent(), getSubtype(contentType), subtype); } else if (sendMail.getPlainTextContent() == null && contentType.startsWith("text/plain")) { // ???plain/text? String content = (String) bp.getContent(); log.info("set Content text [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); sendMail.setPlainTextContent(content); // HTML??????<br>????????HtmlConverter? // ??????HTML???HTML??????? if (sendMail.getHtmlWorkingContent() == null) { sendMail.setHtmlWorkingContent( "<body>" + Util.easyEscapeHtml(content).replaceAll("\\r\\n", "<br>") + "<br>"); } else { sendMail.addHtmlWorkingContent( Util.easyEscapeHtml(content).replaceAll("\\r\\n", "<br>") + "<br>"); } } else if (sendMail.getHtmlContent() == null && contentType.startsWith("text/html") && (parentSubtype.equalsIgnoreCase("alternative") || parentSubtype.equalsIgnoreCase("related"))) { // ???text/html String content = (String) bp.getContent(); log.info("set Content html [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); // 2?3?HTML?????????</body>??????? content = this.charConv.convert(content, charset); content = HtmlConvert.replaceAllCaseInsenstive(content, "</body>.*", ""); log.debug(" conv " + content); sendMail.setHtmlContent(content); } else { log.debug("attach"); // ???? String contentDisposition = bp.getDisposition(); if (contentDisposition != null && contentDisposition.equalsIgnoreCase(Part.INLINE)) { // SenderAttachment file = new SenderAttachment(); String uniqId = uniqId(); String fname = uniqId; String fname2 = Util.getFileName(bp); // iPhone?gifpng?????????????gif??(?png???gif?) if (getSubtype(contentType).equalsIgnoreCase("png")) { file.setContentType("image/gif"); fname = fname + ".gif"; fname2 = getBasename(fname2) + ".gif"; file.setData(inputstream2bytes(Util.png2gif(bp.getInputStream()))); } else { file.setContentType(contentType); fname = fname + "." + getSubtype(contentType); file.setData(inputstream2bytes(bp.getInputStream())); } file.setInline(true); boolean inline = !this.forcePlainText & sendMail.checkAttachmentCapability(file); if (!inline) { file.setInline(false); if (!sendMail.checkAttachmentCapability(file)) { limiterr = true; badfile = fname2; throw new Exception("Attachments: size limit or file count limit exceeds!"); } } if (inline) { file.setFilename(fname); if (bp.getHeader("Content-Id") == null) { file.setContentId(uniqId); } else { file.setContentId(bp.getHeader("Content-Id")[0]); } log.info("Inline Attachment(mixed) " + file.loggingString() + ", Hash:" + file.getHash()); // ??HTML? if (sendMail.getHtmlContent() != null) { sendMail.addHtmlContent("<img src=\"cid:" + file.getContentId() + "\"><br>"); } if (sendMail.getHtmlWorkingContent() == null) { sendMail.setHtmlWorkingContent( "<body><img src=\"cid:" + file.getContentId() + "\"><br>"); } else { sendMail.addHtmlWorkingContent("<img src=\"cid:" + file.getContentId() + "\"><br>"); } } else { file.setFilename(fname2); log.info("Attachment " + file.loggingString()); } sendMail.addAttachmentFileIdList(file); } else { // ? SenderAttachment file = new SenderAttachment(); file.setInline(false); file.setContentType(contentType); String fname = Util.getFileName(bp); if (fname == null && sendMail.getPlainTextContent() != null && contentType.startsWith("text/plain")) { // ??????? String content = (String) bp.getContent(); log.info("add Content text [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); // ??HTML????<br> sendMail.addPlainTextContent("\n" + content); sendMail.addHtmlWorkingContent( Util.easyEscapeHtml(content).replaceAll("\\r\\n", "<br>") + "<br>"); } else if (fname == null && sendMail.getHtmlContent() != null && contentType.startsWith("text/html") && (parentSubtype.equalsIgnoreCase("alternative") || parentSubtype.equalsIgnoreCase("related"))) { // ????text/html???? String content = (String) bp.getContent(); log.info("add Content html [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); content = HtmlConvert.replaceAllCaseInsenstive(content, ".*<body[^>]*>", ""); content = HtmlConvert.replaceAllCaseInsenstive(content, "</body>.*", ""); log.debug(" conv " + content); sendMail.addHtmlContent(content); } else { // ?????? if (getSubtype(contentType).equalsIgnoreCase("png")) { file.setContentType("image/gif"); file.setFilename(getBasename(fname) + ".gif"); file.setData(inputstream2bytes(Util.png2gif(bp.getInputStream()))); } else { file.setFilename(fname); file.setData(inputstream2bytes(bp.getInputStream())); } if (!sendMail.checkAttachmentCapability(file)) { limiterr = true; badfile = file.getFilename(); throw new Exception("Attachments: size limit or file count limit exceeds!"); } sendMail.addAttachmentFileIdList(file); log.info("Attachment " + file.loggingString()); } } } } catch (Exception e) { log.error("parse bodypart error(mixed).", e); if (limiterr) { sendMail.addPlainTextContent("\n[(" + badfile + ")]"); if (sendMail.getHtmlContent() != null) { sendMail.addHtmlContent("[(" + badfile + ")]<br>"); } if (sendMail.getHtmlWorkingContent() == null) { sendMail.setHtmlWorkingContent("<body>[(" + badfile + ")]<br>"); } else { sendMail.addHtmlWorkingContent("[(" + badfile + ")]<br>"); } } else { throw new IOException("BodyPart error(mixed)." + e.getMessage(), e); } } }
From source file:org.apache.axis2.transport.http.MultipartFormDataFormatterTest.java
public void testTransportHeadersOfFileAttachments() throws Exception { String FILE_NAME = "binaryFile.xml"; String FIELD_NAME = "fileData"; String CONTENT_TYPE_VALUE = "text/xml"; String MEDIATE_ELEMENT = "mediate"; String FILE_KEY = "fileAttachment"; String CONTENT_DISPOSITION = "Content-Disposition"; String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding"; String CONTENT_TYPE = "Content-Type"; String FORM_DATA_ELEMENT = "form-data"; String NAME_ELEMENT = "name"; String FILE_NAME_ELEMENT = "filename"; String CONTENT_TRANSFER_ENCODING_VALUE = "binary"; MultipartFormDataFormatter formatter = new MultipartFormDataFormatter(); File binaryAttachment = getTestResourceFile(FILE_NAME); MessageContext mc = new MessageContext(); DiskFileItem diskFileItem = null;/*from w ww. j a v a 2 s .com*/ InputStream input = null; try { if (binaryAttachment.exists() && !binaryAttachment.isDirectory()) { diskFileItem = (DiskFileItem) new DiskFileItemFactory().createItem(FIELD_NAME, CONTENT_TYPE_VALUE, true, binaryAttachment.getName()); input = new FileInputStream(binaryAttachment); OutputStream os = diskFileItem.getOutputStream(); int ret = input.read(); while (ret != -1) { os.write(ret); ret = input.read(); } os.flush(); } } finally { input.close(); } DataSource dataSource = new DiskFileDataSource(diskFileItem); DataHandler dataHandler = new DataHandler(dataSource); SOAPFactory soapFactory = OMAbstractFactory.getSOAP12Factory(); SOAPEnvelope soapEnvelope = soapFactory.getDefaultEnvelope(); SOAPBody body = soapEnvelope.getBody(); OMElement bodyFirstChild = soapFactory.createOMElement(new QName(MEDIATE_ELEMENT), body); OMText binaryNode = soapFactory.createOMText(dataHandler, true); soapFactory.createOMElement(FILE_KEY, null, bodyFirstChild).addChild(binaryNode); mc.setEnvelope(soapEnvelope); OMOutputFormat format = new OMOutputFormat(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); formatter.writeTo(mc, format, baos, true); MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), format.getContentType())); BodyPart bp = mp.getBodyPart(0); String contentDispositionValue = FORM_DATA_ELEMENT + "; " + NAME_ELEMENT + "=\"" + FILE_KEY + "\"; " + FILE_NAME_ELEMENT + "=\"" + binaryAttachment.getName() + "\""; String contentTypeValue = bp.getHeader(CONTENT_TYPE)[0].split(";")[0]; assertEquals(contentDispositionValue, bp.getHeader(CONTENT_DISPOSITION)[0]); assertEquals(CONTENT_TYPE_VALUE, contentTypeValue); assertEquals(CONTENT_TRANSFER_ENCODING_VALUE, bp.getHeader(CONTENT_TRANSFER_ENCODING)[0]); }
From source file:org.apache.hupa.server.utils.MessageUtils.java
/** * Extract the attachments present in a mime message * * @param logger/*from ww w . j a v a 2s.c om*/ * @param content * @return A list of body parts of the attachments * @throws MessagingException * @throws IOException */ static public List<BodyPart> extractMessageAttachments(Log logger, Object content) throws MessagingException, IOException { ArrayList<BodyPart> ret = new ArrayList<BodyPart>(); if (content instanceof Multipart) { Multipart part = (Multipart) content; for (int i = 0; i < part.getCount(); i++) { BodyPart bodyPart = part.getBodyPart(i); String fileName = bodyPart.getFileName(); String[] contentId = bodyPart.getHeader("Content-ID"); if (bodyPart.isMimeType("multipart/*")) { ret.addAll(extractMessageAttachments(logger, bodyPart.getContent())); } else { if (contentId != null || fileName != null) { ret.add(bodyPart); } } } } else { logger.error("Unknown content: " + content.getClass().getName()); } return ret; }
From source file:org.apache.hupa.server.utils.MessageUtils.java
static public List<BodyPart> extractInlineImages(Log logger, Object content) throws MessagingException, IOException { ArrayList<BodyPart> ret = new ArrayList<BodyPart>(); for (BodyPart attach : extractMessageAttachments(logger, content)) { if (attach.getHeader("Content-ID") != null && attach.getContentType().startsWith("image/")) ret.add(attach);//from ww w.j a v a 2 s . co m } return ret; }
From source file:org.geoserver.wcs.GetCoverageTest.java
@Test public void testLargerThanData() throws Exception { MockHttpServletResponse response = getAsServletResponse("wcs/BlueMarble/wcs?identifier=" + getLayerId(TASMANIA_BM) + "&request=getcoverage&service=wcs&version=1.1.1&&format=image/geotiff" + "&BoundingBox=-90,-180,90,180,urn:ogc:def:crs:EPSG:6.6:4326&GridBaseCRS=EPSG:4326"); // parse the multipart, check there are two parts Multipart multipart = getMultipart(response); assertEquals(2, multipart.getCount()); BodyPart coveragePart = multipart.getBodyPart(1); assertEquals("image/tiff", coveragePart.getContentType()); assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]); // save// ww w .ja v a 2 s . c om File tiffFile = File.createTempFile("wcs", "", new File("target")); IOUtils.copy(coveragePart.getInputStream(), new FileOutputStream(tiffFile)); // make sure we can read the coverage back GeoTiffReader reader = new GeoTiffReader(tiffFile); GridCoverage2D result = reader.read(null); coverages.add(result); // see that we got the entire coverage, but nothing more CoverageInfo ci = getCatalog().getCoverageByName(TASMANIA_BM.getLocalPart()); GridCoverage2D original = (GridCoverage2D) ci.getGridCoverage(null, null); coverages.add(original); // the grid should not be swapped since the target output is expressed in EPSG:XYWZ form GridEnvelope originalRange = original.getGridGeometry().getGridRange(); GridEnvelope actualRange = result.getGridGeometry().getGridRange(); assertEquals(originalRange.getSpan(0), actualRange.getSpan(0)); assertEquals(originalRange.getSpan(1), actualRange.getSpan(1)); // check also the geographic bounds Envelope2D originalEnv = original.getEnvelope2D(); Envelope2D actualEnv = result.getEnvelope2D(); assertEquals(originalEnv.getMinX(), actualEnv.getMinX(), 1e-6); assertEquals(originalEnv.getMinY(), actualEnv.getMinY(), 1e-6); assertEquals(originalEnv.getMaxX(), actualEnv.getMaxX(), 1e-6); assertEquals(originalEnv.getMaxY(), actualEnv.getMaxY(), 1e-6); // cleanup tiffFile.delete(); }
From source file:org.geoserver.wcs.GetCoverageTest.java
@Test public void testRasterFilterGreen() throws Exception { String queryString = "wcs?identifier=" + getLayerId(MOSAIC) + "&request=getcoverage" + "&service=wcs&version=1.1.1&&format=image/tiff" + "&BoundingBox=0,0,1,1,urn:ogc:def:crs:EPSG:6.6:4326" + "&CQL_FILTER=location like 'green%25'"; MockHttpServletResponse response = getAsServletResponse(queryString); // parse the multipart, check there are two parts Multipart multipart = getMultipart(response); assertEquals(2, multipart.getCount()); BodyPart coveragePart = multipart.getBodyPart(1); assertEquals("image/tiff", coveragePart.getContentType()); assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]); // make sure we can read the coverage back ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next(); reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream())); RenderedImage image = reader.read(0); // check the pixel int[] pixel = new int[3]; image.getData().getPixel(0, 0, pixel); assertEquals(0, pixel[0]);// w ww . java 2s. c o m assertEquals(255, pixel[1]); assertEquals(0, pixel[2]); }
From source file:org.geoserver.wcs.GetCoverageTest.java
@Test public void testRasterFilterRed() throws Exception { String queryString = "wcs?identifier=" + getLayerId(MOSAIC) + "&request=getcoverage" + "&service=wcs&version=1.1.1&&format=image/tiff" + "&BoundingBox=0,0,1,1,urn:ogc:def:crs:EPSG:6.6:4326" + "&CQL_FILTER=location like 'red%25'"; MockHttpServletResponse response = getAsServletResponse(queryString); // parse the multipart, check there are two parts Multipart multipart = getMultipart(response); assertEquals(2, multipart.getCount()); BodyPart coveragePart = multipart.getBodyPart(1); assertEquals("image/tiff", coveragePart.getContentType()); assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]); // make sure we can read the coverage back ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next(); reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream())); RenderedImage image = reader.read(0); // check the pixel int[] pixel = new int[3]; image.getData().getPixel(0, 0, pixel); assertEquals(255, pixel[0]);//w w w . j av a 2 s.c o m assertEquals(0, pixel[1]); assertEquals(0, pixel[2]); }
From source file:org.geoserver.wcs.GetCoverageTest.java
@Test public void testReadNoGridCRS() throws Exception { String request = // " <wcs:GetCoverage service=\"WCS\" version=\"1.1.1\" " + " xmlns:wcs=\"http://www.opengis.net/wcs/1.1.1\" " + " xmlns:gml=\"http://www.opengis.net/gml\"" + " xmlns:ows=\"http://www.opengis.net/ows/1.1\" >\n" + " <ows:Identifier>" + getLayerId(MockData.TASMANIA_DEM) + " </ows:Identifier>\n" + " <wcs:DomainSubset>\n" + " <ows:BoundingBox crs=\"http://www.opengis.net/gml/srs/epsg.xml#4326\">\n" + " <ows:LowerCorner>-180.0 -90.0</ows:LowerCorner>\n" + " <ows:UpperCorner>180.0 90.0</ows:UpperCorner>\n" + " </ows:BoundingBox>\n" // + " </wcs:DomainSubset>\n" + " <wcs:Output format=\"image/tiff\"/>\n" + " </wcs:GetCoverage>"; MockHttpServletResponse response = postAsServletResponse("wcs", request); // parse the multipart, check there are two parts Multipart multipart = getMultipart(response); assertEquals(2, multipart.getCount()); BodyPart coveragePart = multipart.getBodyPart(1); assertEquals("image/tiff", coveragePart.getContentType()); assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]); // make sure we can read the coverage back ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next(); reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream())); RenderedImage image = reader.read(0); }
From source file:org.geoserver.wcs.GetCoverageTest.java
/** * This tests just ended up throwing an exception as the coverage being encoded * was too large due to a bug in the scales estimation * //from w w w . ja va 2s . c o m * @throws Exception */ @Test public void testRotatedPost() throws Exception { String request = "<GetCoverage xmlns=\"http://www.opengis.net/wcs/1.1.1\" xmlns:gml=\"http://www.opengis.net/gml\"\n" + " xmlns:ows11=\"http://www.opengis.net/ows/1.1\"\n" + " xmlns:ows=\"http://www.opengis.net/ows/1.1\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \r\n" + // " xmlns:wcs=\"http://schemas.opengis.net/wcs/1.1.1\"\n" + " xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n" + " service=\"WCS\"\n" + " version=\"1.1.1\"\n" + " xsi:schemaLocation=\"http://www.opengis.net/wcs/1.1.1 http://schemas.opengis.net/wcs/1.1.1/wcsAll.xsd\">\n" + " <ows11:Identifier>RotatedCad</ows11:Identifier>\n" + " <DomainSubset>\n" + " <ows11:BoundingBox crs=\"urn:ogc:def:crs:OGC:1.3:CRS84\">\n" + " <ows11:LowerCorner>7.7634301664746515 45.14713380418506</ows11:LowerCorner>\n" + " <ows11:UpperCorner>7.764350661575157 45.14763319238466</ows11:UpperCorner>\n" + " </ows11:BoundingBox>\n" + " </DomainSubset>\n" + " <Output format=\"image/tiff\"/>\n" + "</GetCoverage>"; MockHttpServletResponse response = postAsServletResponse("wcs", request); // parse the multipart, check there are two parts Multipart multipart = getMultipart(response); assertEquals(2, multipart.getCount()); BodyPart coveragePart = multipart.getBodyPart(1); assertEquals("image/tiff", coveragePart.getContentType()); assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]); // make sure we can read the coverage back ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next(); reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream())); RenderedImage image = reader.read(0); // check the image is suitably small (without requiring an exact size) assertTrue(image.getWidth() < 1000); assertTrue(image.getHeight() < 1000); }