List of usage examples for javax.mail.internet MimeUtility decode
public static InputStream decode(InputStream is, String encoding) throws MessagingException
From source file:org.apache.jetspeed.util.Base64.java
public static byte[] decodeAsByteArray(String b64string) throws Exception { InputStream in = MimeUtility.decode(new ByteArrayInputStream(b64string.getBytes()), "base64"); ByteArrayOutputStream out = new ByteArrayOutputStream(); while (true) { int b = in.read(); if (b == -1) break; else/*from ww w.j a va2s . co m*/ out.write(b); } return out.toByteArray(); }
From source file:com.adaptris.core.services.Base64DecodeService.java
/** * @see com.adaptris.core.Service#doService(com.adaptris.core.AdaptrisMessage) *//*from w w w .j a v a2s. c o m*/ public void doService(AdaptrisMessage msg) throws ServiceException { OutputStream out = null; InputStream in = null; try { out = msg.getOutputStream(); in = MimeUtility.decode(msg.getInputStream(), MimeConstants.ENCODING_BASE64); IOUtils.copy(in, out); } catch (Exception e) { throw new ServiceException(e); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
From source file:net.sf.vntconverter.VntConverter.java
/** * Dekodiert einen UTF-8-QUOTED-PRINTABLE-String in einen Java-Unicode-String. *///from w w w . jav a 2 s . co m public String decode(String in) { try { InputStream input = MimeUtility.decode(new ReaderInputStream(new StringReader(in), "UTF-8"), "quoted-printable"); StringWriter sw = new StringWriter(); OutputStream output = new WriterOutputStream(sw, "UTF-8"); copyAndClose(input, output); return sw.toString(); } catch (Exception e) { throw new RuntimeException("Exception caught in VntConverter.encode(in):", e); } }
From source file:dtw.webmail.util.FormdataMultipart.java
/** * Processes a body part of the form-data. * Extracts parameters and set values, and * leaves over the attachments./*from w ww . j ava2 s .co m*/ * * @param mbp the <tt>MimeBodyPart</tt> to be processed. * * @throws IOException if i/o operations fail. * @throws MessagingException if parsing or part handling with * Mail API classes fails. */ private void processBodyPart(MimeBodyPart mbp) throws MessagingException, IOException { //String contenttype=new String(mbp.getContentType()); //JwmaKernel.getReference().debugLog().write("Processing "+contenttype); //check if a content-type is given String[] cts = mbp.getHeader("Content-Type"); if (cts == null || cts.length == 0) { //this is a parameter, get it out and //remove the part. String controlname = extractName((mbp.getHeader("Content-Disposition"))[0]); //JwmaKernel.getReference().debugLog().write("Processing control:"+controlname); //retrieve value observing encoding InputStream in = mbp.getInputStream(); String[] encoding = mbp.getHeader("Content-Transfer-Encoding"); if (encoding != null && encoding.length > 0) { in = MimeUtility.decode(in, encoding[0]); } String value = extractValue(in); if (value != null || !value.trim().equals("")) { addParameter(controlname, value); } //flag removal m_Removed = true; removeBodyPart(mbp); } else { String filename = extractFileName((mbp.getHeader("Content-Disposition"))[0]); //normally without file the control should be not successful. //but neither netscape nor mircosoft iexploder care much. //the only feature is an empty filename. if (filename.equals("")) { //kick it out too m_Removed = true; removeBodyPart(mbp); } else { //JwmaKernel.getReference().debugLog().write("Incoming filename="+filename); //IExploder sends files with complete path. //jwma doesnt want this. int lastindex = filename.lastIndexOf("\\"); if (lastindex != -1) { filename = filename.substring(lastindex + 1, filename.length()); } //JwmaKernel.getReference().debugLog().write("Outgoing filename="+filename); //Observe a possible encoding InputStream in = mbp.getInputStream(); String[] encoding = mbp.getHeader("Content-Transfer-Encoding"); if (encoding != null && encoding.length > 0) { in = MimeUtility.decode(in, encoding[0]); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputStream out = (OutputStream) bout; int i = 0; while ((i = in.read()) != -1) { //maybe more efficient in buffers, but well out.write(i); } out.flush(); out.close(); //create the datasource MimeBodyPartDataSource mbpds = new MimeBodyPartDataSource( // contenttype,filename,bout.toByteArray() cts[0], filename, bout.toByteArray()); //Re-set the Content-Disposition header, in case //the file name was changed mbp.removeHeader("Content-Disposition"); mbp.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); //set a base64 transferencoding und the data handler mbp.addHeader("Content-Transfer-Encoding", "base64"); mbp.setDataHandler(new DataHandler(mbpds)); } } }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Decodes data by its content transfer encoding and returns it*/ private byte[] decodeContentTransferEncoding(byte[] encodedData, String contentTransferEncoding) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(encodedData); InputStream b64is = MimeUtility.decode(bais, contentTransferEncoding); byte[] tmp = new byte[encodedData.length]; int n = b64is.read(tmp); byte[] res = new byte[n]; System.arraycopy(tmp, 0, res, 0, n); return res;//from w w w . j a v a 2s . c om }
From source file:com.aliyun.odps.local.common.utils.LocalRunUtils.java
public static byte[] fromReadableString(String str) throws Exception { byte[] b = str.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(b); InputStream printableis = MimeUtility.decode(bais, "quoted-printable"); byte[] tmp = new byte[b.length]; int n = printableis.read(tmp); byte[] res = new byte[n]; System.arraycopy(tmp, 0, res, 0, n); return res;//ww w. java 2s.com }
From source file:org.apache.axis.attachments.MultiPartRelatedInputStream.java
/** * Create a new Multipart stream.//from w w w.java2 s . com * @param contentType the string that holds the contentType * @param stream the true input stream from where the source * * @throws org.apache.axis.AxisFault if the stream could not be created */ public MultiPartRelatedInputStream(String contentType, java.io.InputStream stream) throws org.apache.axis.AxisFault { super(null); // don't cache this stream. if (!(stream instanceof BufferedInputStream)) { stream = new BufferedInputStream(stream); } try { // First find the start and boundary parameters. There are real weird rules regard what // can be in real headers what needs to be escaped etc let mail parse it. javax.mail.internet.ContentType ct = new javax.mail.internet.ContentType(contentType); String rootPartContentId = ct.getParameter("start"); // Get the root part content. if (rootPartContentId != null) { rootPartContentId = rootPartContentId.trim(); if (rootPartContentId.startsWith("<")) { rootPartContentId = rootPartContentId.substring(1); } if (rootPartContentId.endsWith(">")) { rootPartContentId = rootPartContentId.substring(0, rootPartContentId.length() - 1); } } if (ct.getParameter("boundary") != null) { String boundaryStr = "--" + ct.getParameter("boundary"); // The boundary with -- add as always the case. // if start is null then the first attachment is the rootpart // First read the start boundary -- this is done with brute force since the servlet may swallow the crlf between headers. // after this we use the more efficient boundarydelimeted stream. There should never be any data here anyway. byte[][] boundaryMarker = new byte[2][boundaryStr.length() + 2]; IOUtils.readFully(stream, boundaryMarker[0]); boundary = (boundaryStr + "\r\n").getBytes("US-ASCII"); int current = 0; // This just goes brute force one byte at a time to find the first boundary. // in most cases this just a crlf. for (boolean found = false; !found; ++current) { if (!(found = java.util.Arrays.equals(boundaryMarker[current & 0x1], boundary))) { System.arraycopy(boundaryMarker[current & 0x1], 1, boundaryMarker[(current + 1) & 0x1], 0, boundaryMarker[0].length - 1); if (stream.read(boundaryMarker[(current + 1) & 0x1], boundaryMarker[0].length - 1, 1) < 1) { throw new org.apache.axis.AxisFault( Messages.getMessage("mimeErrorNoBoundary", new String(boundary))); } } } // after the first boundary each boundary will have a cr lf at the beginning since after the data in any part there // is a cr lf added to put the boundary at the begining of a line. boundaryStr = "\r\n" + boundaryStr; boundary = boundaryStr.getBytes("US-ASCII"); } else { // Since boundary is not specified, we try to find one. for (boolean found = false; !found;) { boundary = readLine(stream); if (boundary == null) throw new org.apache.axis.AxisFault(Messages.getMessage("mimeErrorNoBoundary", "--")); found = boundary.length > 4 && boundary[2] == '-' && boundary[3] == '-'; } } // create the boundary delmited stream. boundaryDelimitedStream = new org.apache.axis.attachments.BoundaryDelimitedStream(stream, boundary, 1024); // Now read through all potential streams until we have found the root part. String contentTransferEncoding = null; do { contentId = null; contentLocation = null; contentTransferEncoding = null; // Read this attachments headers from the stream. javax.mail.internet.InternetHeaders headers = new javax.mail.internet.InternetHeaders( boundaryDelimitedStream); // Use java mail utility to read through the headers. contentId = headers.getHeader(HTTPConstants.HEADER_CONTENT_ID, null); // Clean up the headers and remove any < > if (contentId != null) { contentId = contentId.trim(); if (contentId.startsWith("<")) { contentId = contentId.substring(1); } if (contentId.endsWith(">")) { contentId = contentId.substring(0, contentId.length() - 1); } contentId = contentId.trim(); // if (!contentId.startsWith("cid:")) { // contentId = // "cid:" // + contentId; // make sure its identified as cid // } } contentLocation = headers.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION, null); if (contentLocation != null) { contentLocation = contentLocation.trim(); if (contentLocation.startsWith("<")) { contentLocation = contentLocation.substring(1); } if (contentLocation.endsWith(">")) { contentLocation = contentLocation.substring(0, contentLocation.length() - 1); } contentLocation = contentLocation.trim(); } contentType = headers.getHeader(HTTPConstants.HEADER_CONTENT_TYPE, null); if (contentType != null) { contentType = contentType.trim(); } contentTransferEncoding = headers.getHeader(HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, null); if (contentTransferEncoding != null) { contentTransferEncoding = contentTransferEncoding.trim(); } java.io.InputStream decodedStream = boundaryDelimitedStream; if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) { decodedStream = MimeUtility.decode(decodedStream, contentTransferEncoding); } if ((rootPartContentId != null) && !rootPartContentId.equals(contentId)) { // This is a part that has come in prior to the root part. Need to buffer it up. javax.activation.DataHandler dh = new javax.activation.DataHandler( new org.apache.axis.attachments.ManagedMemoryDataSource(decodedStream, MAX_CACHED, contentType, true)); AttachmentPart ap = new AttachmentPart(dh); if (contentId != null) { ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, contentId); } if (contentLocation != null) { ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION, contentLocation); } for (java.util.Enumeration en = headers.getNonMatchingHeaders( new String[] { HTTPConstants.HEADER_CONTENT_ID, HTTPConstants.HEADER_CONTENT_LOCATION, HTTPConstants.HEADER_CONTENT_TYPE }); en.hasMoreElements();) { javax.mail.Header header = (javax.mail.Header) en.nextElement(); String name = header.getName(); String value = header.getValue(); if ((name != null) && (value != null)) { name = name.trim(); if (name.length() != 0) { ap.addMimeHeader(name, value); } } } addPart(contentId, contentLocation, ap); boundaryDelimitedStream = boundaryDelimitedStream.getNextStream(); // Gets the next stream. } } while ((null != boundaryDelimitedStream) && (rootPartContentId != null) && !rootPartContentId.equals(contentId)); if (boundaryDelimitedStream == null) { throw new org.apache.axis.AxisFault(Messages.getMessage("noRoot", rootPartContentId)); } soapStreamBDS = boundaryDelimitedStream; if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) { soapStream = MimeUtility.decode(boundaryDelimitedStream, contentTransferEncoding); } else { soapStream = boundaryDelimitedStream; // This should be the SOAP part } // Read from the input stream all attachments prior to the root part. } catch (javax.mail.internet.ParseException e) { throw new org.apache.axis.AxisFault(Messages.getMessage("mimeErrorParsing", e.getMessage())); } catch (java.io.IOException e) { throw new org.apache.axis.AxisFault(Messages.getMessage("readError", e.getMessage())); } catch (javax.mail.MessagingException e) { throw new org.apache.axis.AxisFault(Messages.getMessage("readError", e.getMessage())); } }
From source file:org.apache.axis.attachments.MultiPartRelatedInputStream.java
/** * This will read streams in till the one that is needed is found. * * @param id id is the stream being sought. * * @return the part for the id//from w w w.ja v a 2s . com * * @throws org.apache.axis.AxisFault */ protected Part readTillFound(final String[] id) throws org.apache.axis.AxisFault { if (boundaryDelimitedStream == null) { return null; // The whole stream has been consumed already } Part ret = null; try { if (soapStreamBDS == boundaryDelimitedStream) { // Still on the SOAP stream. if (!eos) { // The SOAP packet has not been fully read yet. Need to store it away. java.io.ByteArrayOutputStream soapdata = new java.io.ByteArrayOutputStream(1024 * 8); byte[] buf = new byte[1024 * 16]; int byteread = 0; do { byteread = soapStream.read(buf); if (byteread > 0) { soapdata.write(buf, 0, byteread); } } while (byteread > -1); soapdata.close(); soapStream = new java.io.ByteArrayInputStream(soapdata.toByteArray()); } boundaryDelimitedStream = boundaryDelimitedStream.getNextStream(); } // Now start searching for the data. if (null != boundaryDelimitedStream) { do { String contentType = null; String contentId = null; String contentTransferEncoding = null; String contentLocation = null; // Read this attachments headers from the stream. javax.mail.internet.InternetHeaders headers = new javax.mail.internet.InternetHeaders( boundaryDelimitedStream); contentId = headers.getHeader("Content-Id", null); if (contentId != null) { contentId = contentId.trim(); if (contentId.startsWith("<")) { contentId = contentId.substring(1); } if (contentId.endsWith(">")) { contentId = contentId.substring(0, contentId.length() - 1); } // if (!contentId.startsWith("cid:")) { // contentId = "cid:" + contentId; // } contentId = contentId.trim(); } contentType = headers.getHeader(HTTPConstants.HEADER_CONTENT_TYPE, null); if (contentType != null) { contentType = contentType.trim(); } contentLocation = headers.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION, null); if (contentLocation != null) { contentLocation = contentLocation.trim(); } contentTransferEncoding = headers.getHeader(HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, null); if (contentTransferEncoding != null) { contentTransferEncoding = contentTransferEncoding.trim(); } java.io.InputStream decodedStream = boundaryDelimitedStream; if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) { decodedStream = MimeUtility.decode(decodedStream, contentTransferEncoding); } ManagedMemoryDataSource source = new ManagedMemoryDataSource(decodedStream, ManagedMemoryDataSource.MAX_MEMORY_DISK_CACHED, contentType, true); DataHandler dh = new DataHandler(source); AttachmentPart ap = new AttachmentPart(dh); if (contentId != null) { ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, contentId); } if (contentLocation != null) { ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION, contentLocation); } for (java.util.Enumeration en = headers.getNonMatchingHeaders( new String[] { HTTPConstants.HEADER_CONTENT_ID, HTTPConstants.HEADER_CONTENT_LOCATION, HTTPConstants.HEADER_CONTENT_TYPE }); en.hasMoreElements();) { javax.mail.Header header = (javax.mail.Header) en.nextElement(); String name = header.getName(); String value = header.getValue(); if ((name != null) && (value != null)) { name = name.trim(); if (name.length() != 0) { ap.addMimeHeader(name, value); } } } addPart(contentId, contentLocation, ap); for (int i = id.length - 1; (ret == null) && (i > -1); --i) { if ((contentId != null) && id[i].equals(contentId)) { // This is the part being sought ret = ap; } else if ((contentLocation != null) && id[i].equals(contentLocation)) { ret = ap; } } boundaryDelimitedStream = boundaryDelimitedStream.getNextStream(); } while ((null == ret) && (null != boundaryDelimitedStream)); } } catch (Exception e) { throw org.apache.axis.AxisFault.makeFault(e); } return ret; }
From source file:org.nuxeo.ecm.platform.mail.listener.action.ExtractMessageInformationAction.java
/** * Interprets the body accordingly to the charset used. It relies on the content type being * ****;charset={charset};******/* w ww.ja va 2 s. c o m*/ * * @return the decoded String */ protected static String decodeMailBody(Part part) throws MessagingException, IOException { String encoding = null; // try to get encoding from header rather than from Stream ! // unfortunately, this does not seem to be reliable ... /* * String[] cteHeader = part.getHeader("Content-Transfer-Encoding"); if (cteHeader!=null && cteHeader.length>0) * { encoding = cteHeader[0].toLowerCase(); } */ // fall back to default sniffing // that will actually read the stream from server if (encoding == null) { encoding = MimeUtility.getEncoding(part.getDataHandler()); } InputStream is = null; try { is = MimeUtility.decode(part.getInputStream(), encoding); } catch (IOException ex) { log.error("Unable to read content", ex); return ""; } String contType = part.getContentType(); final String charsetIdentifier = "charset="; final String ISO88591 = "iso-8859-1"; final String WINDOWS1252 = "windows-1252"; int offset = contType.indexOf(charsetIdentifier); String charset = ""; if (offset >= 0) { charset = contType.substring(offset + charsetIdentifier.length()); offset = charset.indexOf(";"); if (offset > 0) { charset = charset.substring(0, offset); } } // Charset could be like "utf-8" or utf-8 if (!"".equals(charset)) { charset = charset.replaceAll("\"", ""); } log.debug("Content type: " + contType + "; charset: " + charset); if (charset.equalsIgnoreCase(ISO88591)) { // see // http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#character1 // for more details see http://en.wikipedia.org/wiki/ISO_8859-1 // section "ISO-8859-1 and Windows-1252 confusion" charset = WINDOWS1252; log.debug("Using replacing charset: " + charset); } String ret; byte[] streamContent = FileUtils.readBytes(is); if ("".equals(charset)) { ret = new String(streamContent); } else { try { ret = new String(streamContent, charset); } catch (UnsupportedEncodingException e) { // try without encoding ret = new String(streamContent); } } return ret; }