List of usage examples for javax.mail.internet ContentType match
public boolean match(String s)
From source file:org.simplejavamail.internal.util.MimeMessageParser.java
/** * Checks whether the MimePart contains an object of the given mime type. * * @param part the current MimePart/* w ww . j a v a 2 s .c o m*/ * @param mimeType the mime type to check * @return {@code true} if the MimePart matches the given mime type, {@code false} otherwise * @throws MessagingException parsing the MimeMessage failed */ private static boolean isMimeType(final MimePart part, final String mimeType) throws MessagingException { // Do not use part.isMimeType(String) as it is broken for MimeBodyPart // and does not really check the actual content type. try { final ContentType ct = new ContentType(part.getDataHandler().getContentType()); return ct.match(mimeType); } catch (final ParseException ex) { return part.getContentType().equalsIgnoreCase(mimeType); } }
From source file:org.esxx.Response.java
public static void writeObject(Object object, ContentType ct, OutputStream out) throws IOException { if (object == null) { return;// ww w.j a v a 2 s .c o m } // Unwrap wrapped objects object = JS.toJavaObject(object); // Convert complex types to primitive types if (object instanceof Node) { ESXX esxx = ESXX.getInstance(); if (ct.match("message/rfc822")) { try { String xml = esxx.serializeNode((Node) object); org.esxx.xmtp.XMTPParser xmtpp = new org.esxx.xmtp.XMTPParser(); javax.mail.Message msg = xmtpp.convertMessage(new StringReader(xml)); object = new ByteArrayOutputStream(); msg.writeTo(new FilterOutputStream((OutputStream) object) { @Override public void write(int b) throws IOException { if (b == '\r') { return; } else if (b == '\n') { out.write('\r'); out.write('\n'); } else { out.write(b); } } }); } catch (javax.xml.stream.XMLStreamException ex) { throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex); } catch (javax.mail.MessagingException ex) { throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex); } } else { object = esxx.serializeNode((Node) object); } } else if (object instanceof Scriptable) { if (ct.match("application/x-www-form-urlencoded")) { String cs = Parsers.getParameter(ct, "charset", "UTF-8"); object = StringUtil.encodeFormVariables(cs, (Scriptable) object); } else if (ct.match("text/csv")) { object = jsToCSV(ct, (Scriptable) object); } else { object = jsToJSON(object).toString(); } } else if (object instanceof byte[]) { object = new ByteArrayInputStream((byte[]) object); } else if (object instanceof File) { object = new FileInputStream((File) object); } // Serialize primitive types if (object instanceof ByteArrayOutputStream) { ByteArrayOutputStream bos = (ByteArrayOutputStream) object; bos.writeTo(out); } else if (object instanceof ByteBuffer) { // Write result as-is to output stream WritableByteChannel wbc = Channels.newChannel(out); ByteBuffer bb = (ByteBuffer) object; bb.rewind(); while (bb.hasRemaining()) { wbc.write(bb); } wbc.close(); } else if (object instanceof InputStream) { IO.copyStream((InputStream) object, out); } else if (object instanceof Reader) { // Write stream as-is, using the specified charset (if present) String cs = Parsers.getParameter(ct, "charset", "UTF-8"); Writer ow = new OutputStreamWriter(out, cs); IO.copyReader((Reader) object, ow); } else if (object instanceof String) { // Write string as-is, using the specified charset (if present) String cs = Parsers.getParameter(ct, "charset", "UTF-8"); Writer ow = new OutputStreamWriter(out, cs); ow.write((String) object); ow.flush(); } else if (object instanceof RenderedImage) { Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(ct.getBaseType()); if (!i.hasNext()) { throw new ESXXException("No ImageWriter available for " + ct.getBaseType()); } ImageWriter writer = i.next(); writer.setOutput(ImageIO.createImageOutputStream(out)); writer.write((RenderedImage) object); } else { throw new UnsupportedOperationException("Unsupported object class type: " + object.getClass()); } }
From source file:com.eviware.soapui.impl.wsdl.monitor.ContentTypes.java
private boolean contentTypeMatches(ContentType contentType, ContentType respondedContentType) { // ContentType doesn't take wildcards into account for the primary type, but we want to do that return contentType.match(respondedContentType) || ((contentType.getPrimaryType().charAt(0) == '*' || respondedContentType.getPrimaryType().charAt(0) == '*') && (contentType.getSubType().charAt(0) == '*' || respondedContentType.getSubType().charAt(0) == '*' || contentType.getSubType().equalsIgnoreCase(respondedContentType.getSubType()))); }
From source file:org.aksw.resparql.IMyHandler.java
public static Map<String, ContentType> getPreferredFormats(Headers requestHeaders) throws ParseException { // Content negotiation List<String> accepts = requestHeaders.get("Accept"); if (accepts == null) accepts = Collections.emptyList(); logger.info("Accept header: " + accepts); Map<String, ContentType> result = new HashMap<String, ContentType>(); int acceptCounter = 0; for (String accept : accepts) { String[] items = accept.split(","); for (String item : items) { ++acceptCounter;// ww w . j av a 2 s. c o m ContentType ct = null; try { ct = new ContentType(item); } catch (Exception e) { logger.warn("Error parsing content type", e); continue; } // FIXME Would be nice if this was configurable if (ct.match("text/plain") || ct.match("text/html") || ct.match("*/*")) { if (!result.containsKey("N-TRIPLE")) { //result.put("N-TRIPLE", ct); // We serve N-Triples by default result.put("N-TRIPLE", new ContentType("text/plain")); } //responseContentType = "text/plain; charset=UTF-8"; } for (Map.Entry<ContentType, String> entry : contentTypeToJenaFormat.entrySet()) { if (!ct.match(entry.getKey())) continue; String tmp = entry.getValue(); if (tmp != null) { // If a format was specified in the query string, we also need // a compatible content type // E.g. if format=N3, but accept=rdf+xml we can't use that accept type if (!result.containsKey(tmp)) { result.put(tmp, ct); } } } } } return result; }
From source file:org.esxx.Parsers.java
public Object parse(ContentType ct, InputStream is, final URI is_uri, Collection<URI> external_uris, PrintWriter err, Context cx, Scriptable scope) throws Exception { // Read-only accesses; no syncronization required Parser parser = parserMap.get(ct.getBaseType()); if (parser == null) { if (ct.getBaseType().endsWith("+xml")) { parser = parserMap.get("application/xml"); } else if (ct.match("image/*")) { parser = parserMap.get("image/*"); } else if (ct.match("text/*")) { parser = parserMap.get("text/plain"); } else {// w w w .j a va2s. c o m parser = parserMap.get("application/octet-stream"); } } Object result = null; try { result = parser.parse(ct, is, is_uri, external_uris, err, cx, scope); } finally { if (result != is) { is.close(); } } return result; }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//from w w w .j av a2 s . c o m * * @param message DOCUMENT ME! * * @return DOCUMENT ME! */ public static boolean haveAttachment(Message message) { ContentType xct = MessageUtilities.getContentType(message); if (xct.match("application/pkcs7-signature") || // new implementations xct.match("application/x-pkcs7-signature") || // old implementations xct.match("multipart/signed")) { // internet standard // signed by some means return false; } else if (xct.match("application/pkcs7-mime") || // new implementations xct.match("application/x-pkcs7-mime") || // old implementations xct.match("multipart/encrypted")) { // internet standard // encrypted or enveloped by some means return false; } else if (xct.match("multipart/mixed")) { // attachments of some type return true; } else { return false; } }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//from w w w . java2s. c om * * @param dmailParts DOCUMENT ME! * @param contentType DOCUMENT ME! * @param buffer DOCUMENT ME! * * @return DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ protected static StringBuffer scanDmailParts(Vector dmailParts, StringBuffer buffer, boolean chooseHtml, String breakLine) throws MessagingException { if ((buffer.length() == 0) && (dmailParts != null)) { int size = dmailParts.size(); int j = 0; for (int i = 0; i < size; i++) { //message/rfc822 MailPart dmailPart = (MailPart) dmailParts.get(j); //ContentType xctype = MessageUtilities.getContentType(dmailPart.getContentType()); ContentType xctype = MessageUtilities.getContentType(dmailPart.getPart()); if (xctype.match("text/plain") && !chooseHtml) { String xjcharset = xctype.getParameter("charset"); if (xjcharset == null) { // not present, assume ASCII character encoding try { Header xheader; Enumeration xe = dmailPart.getPart().getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); String aux = xheader.getName().toLowerCase().trim(); if (aux.indexOf("subject") > -1) { int pos1 = aux.indexOf("=?"); int pos2 = aux.indexOf("?q?"); if ((pos1 > -1) && (pos2 > -1)) { xjcharset = aux.substring(pos1, pos2); } break; } } } catch (Exception ex) { } if (xjcharset == null) { xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms } } //String str = JavaScriptFilter.apply(buff.toString()); xjcharset = MimeUtility.javaCharset(xjcharset); MessageUtilities.decodeTextPlain(buffer, dmailPart.getPart(), breakLine, xjcharset); dmailParts.removeElementAt(j); break; } else if (xctype.match("text/html") && chooseHtml) { String xjcharset = xctype.getParameter("charset"); if (xjcharset == null) { // not present, assume ASCII character encoding try { Header xheader; Enumeration xe = dmailPart.getPart().getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); String aux = xheader.getName().toLowerCase().trim(); if (aux.indexOf("subject") > -1) { int pos1 = aux.indexOf("=?"); int pos2 = aux.indexOf("?q?"); if ((pos1 > -1) && (pos2 > -1)) { xjcharset = aux.substring(pos1, pos2); } break; } } } catch (Exception ex) { } if (xjcharset == null) { xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms } } xjcharset = MimeUtility.javaCharset(xjcharset); MessageUtilities.decodeTextHtml(buffer, dmailPart.getPart(), xjcharset); dmailParts.removeElementAt(j); break; } else { j++; } } } return buffer; }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//from ww w . ja v a 2 s . com * * @param part DOCUMENT ME! * * @return DOCUMENT ME! */ private static int getPartSize(Part part) { int size = 0; try { boolean attachIt = true; ContentType xctype = MessageUtilities.getContentType(part); ContentDisposition xcdisposition = MessageUtilities.getContentDisposition(part); if (xctype.match("multipart/*")) { attachIt = false; Multipart xmulti = (Multipart) MessageUtilities.getPartContent(part); int xparts = xmulti.getCount(); for (int xindex = 0; xindex < xparts; xindex++) { MessageUtilities.getPartSize(xmulti.getBodyPart(xindex)); } } else if (xctype.match("text/plain")) { if (xcdisposition.match("inline")) { attachIt = false; size += sizeInline(part); } } else if (xctype.match("text/html")) { if (xcdisposition.match("inline")) { attachIt = false; size += sizeInline(part); } } if (attachIt) { size += IOUtils.toByteArray(part.getInputStream()).length; } } catch (MessagingException e) { } catch (IOException e) { } catch (Exception e) { } return size; }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * Given a message that we are replying to, or forwarding, * * @param part The part to decode./* ww w. ja va 2 s . c om*/ * @param buffer The new message body text buffer. * @param dmailParts Vector for new message's attachments. * * @return The buffer being filled in with the body. * * @throws MessagingException DOCUMENT ME! * @throws IOException */ protected static StringBuffer subDecodeContent(Part part, StringBuffer buffer, Vector dmailParts, boolean chooseHtml, String breakLine) throws MessagingException, IOException { boolean attachIt = true; // decode based on content type and disposition ContentType xctype = MessageUtilities.getContentType(part); ContentDisposition xcdisposition = MessageUtilities.getContentDisposition(part); if (xctype.match("multipart/*")) { attachIt = false; Multipart xmulti = (Multipart) MessageUtilities.getPartContent(part); int xparts = 0; try { xparts = xmulti.getCount(); } catch (MessagingException e) { attachIt = true; xparts = 0; } for (int xindex = 0; xindex < xparts; xindex++) { MessageUtilities.subDecodeContent(xmulti.getBodyPart(xindex), buffer, dmailParts, chooseHtml, breakLine); } } else if (xctype.match("message/rfc822")) { MimeMessage newMessage = new MimeMessage((Session) null, part.getInputStream()); decodeContent(newMessage, buffer, dmailParts, chooseHtml, breakLine); } else if (xctype.match("text/plain") && !chooseHtml) { if (xcdisposition.match("inline")) { attachIt = false; String xjcharset = xctype.getParameter("charset"); if (xjcharset == null) { // not present, assume ASCII character encoding try { Header xheader; Enumeration xe = part.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); String aux = xheader.getName().toLowerCase().trim(); if (aux.indexOf("subject") > -1) { int pos1 = aux.indexOf("=?"); int pos2 = aux.indexOf("?q?"); if ((pos1 > -1) && (pos2 > -1)) { xjcharset = aux.substring(pos1, pos2); } break; } } } catch (Exception ex) { System.out.print(ex.getMessage()); } if (xjcharset == null) { xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms } } MessageUtilities.decodeTextPlain(buffer, part, breakLine, xjcharset); } } else if (xctype.match("text/html") && chooseHtml) { if (xcdisposition.match("inline")) { attachIt = false; String xjcharset = xctype.getParameter("charset"); if (xjcharset == null) { // not present, assume ASCII character encoding try { Header xheader; Enumeration xe = part.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); String aux = xheader.getName().toLowerCase().trim(); if (aux.indexOf("subject") > -1) { int pos1 = aux.indexOf("=?"); int pos2 = aux.indexOf("?q?"); if ((pos1 > -1) && (pos2 > -1)) { xjcharset = aux.substring(pos1, pos2); } break; } } } catch (Exception ex) { } if (xjcharset == null) { xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms } } MessageUtilities.decodeTextHtml(buffer, part, xjcharset); } } if (attachIt) { // UNDONE should simple single line entries be // created for other types and attachments? // // UNDONE should attachements only be created for "attachments" or all // unknown content types? if (dmailParts != null) { MailPart aux = new MailPart(); aux.setPart(part); aux.setId(dmailParts.size()); aux.setName(MessageUtilities.encodeStringToXml(MessageUtilities.getPartName(part))); aux.setContentType(xctype.getBaseType()); aux.setSize(part.getSize()); dmailParts.addElement(aux); } } return buffer; }
From source file:com.zimbra.cs.mailbox.calendar.Invite.java
/** * Returns the meeting notes. Meeting notes is the text/plain part in an * invite. It typically includes CUA-generated meeting summary as well as * text entered by the user.//from ww w . ja va2s .co m * * @return null if notes is not found * @throws ServiceException */ public static String getDescription(Part mmInv, String mimeType) throws ServiceException { if (mmInv == null) return null; try { // If top-level is text/calendar, parse the iCalendar object and return // the DESCRIPTION of the first VEVENT/VTODO encountered. String mmCtStr = mmInv.getContentType(); if (mmCtStr != null) { ContentType mmCt = new ContentType(mmCtStr); if (mmCt.match(MimeConstants.CT_TEXT_CALENDAR)) { boolean wantHtml = MimeConstants.CT_TEXT_HTML.equalsIgnoreCase(mimeType); Object mmInvContent = mmInv.getContent(); InputStream is = null; try { String charset = MimeConstants.P_CHARSET_UTF8; if (mmInvContent instanceof InputStream) { charset = mmCt.getParameter(MimeConstants.P_CHARSET); if (charset == null) charset = MimeConstants.P_CHARSET_UTF8; is = (InputStream) mmInvContent; } else if (mmInvContent instanceof String) { String str = (String) mmInvContent; charset = MimeConstants.P_CHARSET_UTF8; is = new ByteArrayInputStream(str.getBytes(charset)); } if (is != null) { ZVCalendar iCal = ZCalendarBuilder.build(is, charset); for (Iterator<ZComponent> compIter = iCal.getComponentIterator(); compIter.hasNext();) { ZComponent component = compIter.next(); ICalTok compTypeTok = component.getTok(); if (compTypeTok == ICalTok.VEVENT || compTypeTok == ICalTok.VTODO) { if (!wantHtml) return component.getPropVal(ICalTok.DESCRIPTION, null); else return component.getDescriptionHtml(); } } } } finally { ByteUtil.closeStream(is); } } } Object mmInvContent = mmInv.getContent(); if (!(mmInvContent instanceof MimeMultipart)) { if (mmInvContent instanceof InputStream) { ByteUtil.closeStream((InputStream) mmInvContent); } return null; } MimeMultipart mm = (MimeMultipart) mmInvContent; // If top-level is multipart, get description from text/* part. int numParts = mm.getCount(); String charset = null; for (int i = 0; i < numParts; i++) { BodyPart part = mm.getBodyPart(i); String ctStr = part.getContentType(); try { ContentType ct = new ContentType(ctStr); if (ct.match(mimeType)) { charset = ct.getParameter(MimeConstants.P_CHARSET); if (charset == null) charset = MimeConstants.P_CHARSET_DEFAULT; byte[] descBytes = ByteUtil.getContent(part.getInputStream(), part.getSize()); return new String(descBytes, charset); } // If part is a multipart, recurse. if (ct.getBaseType().matches(MimeConstants.CT_MULTIPART_WILD)) { String str = getDescription(part, mimeType); if (str != null) { return str; } } } catch (javax.mail.internet.ParseException e) { ZimbraLog.calendar.warn("Invalid Content-Type found: \"" + ctStr + "\"; skipping part", e); } } } catch (IOException e) { throw ServiceException.FAILURE("Unable to get calendar item notes MIME part", e); } catch (MessagingException e) { throw ServiceException.FAILURE("Unable to get calendar item notes MIME part", e); } return null; }