List of usage examples for javax.mail.internet ContentType ContentType
public ContentType(String s) throws ParseException
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/*from ww w. j a va 2 s. com*/ * @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:msgshow.java
public static void dumpPart(Part p) throws Exception { if (p instanceof Message) dumpEnvelope((Message) p);// w ww .j av a 2 s . c o m /** Dump input stream .. InputStream is = p.getInputStream(); // If "is" is not already buffered, wrap a BufferedInputStream // around it. if (!(is instanceof BufferedInputStream)) is = new BufferedInputStream(is); int c; while ((c = is.read()) != -1) System.out.write(c); **/ String ct = p.getContentType(); try { pr("CONTENT-TYPE: " + (new ContentType(ct)).toString()); } catch (ParseException pex) { pr("BAD CONTENT-TYPE: " + ct); } String filename = p.getFileName(); if (filename != null) pr("FILENAME: " + filename); /* * Using isMimeType to determine the content type avoids * fetching the actual content data until we need it. */ if (p.isMimeType("text/plain")) { pr("This is plain text"); pr("---------------------------"); if (!showStructure && !saveAttachments) System.out.println((String) p.getContent()); } else if (p.isMimeType("multipart/*")) { pr("This is a Multipart"); pr("---------------------------"); Multipart mp = (Multipart) p.getContent(); level++; int count = mp.getCount(); for (int i = 0; i < count; i++) dumpPart(mp.getBodyPart(i)); level--; } else if (p.isMimeType("message/rfc822")) { pr("This is a Nested Message"); pr("---------------------------"); level++; dumpPart((Part) p.getContent()); level--; } else { if (!showStructure && !saveAttachments) { /* * If we actually want to see the data, and it's not a * MIME type we know, fetch it and check its Java type. */ Object o = p.getContent(); if (o instanceof String) { pr("This is a string"); pr("---------------------------"); System.out.println((String) o); } else if (o instanceof InputStream) { pr("This is just an input stream"); pr("---------------------------"); InputStream is = (InputStream) o; int c; while ((c = is.read()) != -1) System.out.write(c); } else { pr("This is an unknown type"); pr("---------------------------"); pr(o.toString()); } } else { // just a separator pr("---------------------------"); } } /* * If we're saving attachments, write out anything that * looks like an attachment into an appropriately named * file. Don't overwrite existing files to prevent * mistakes. */ if (saveAttachments && level != 0 && p instanceof MimeBodyPart && !p.isMimeType("multipart/*")) { String disp = p.getDisposition(); // many mailers don't include a Content-Disposition if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) { if (filename == null) filename = "Attachment" + attnum++; pr("Saving attachment to file " + filename); try { File f = new File(filename); if (f.exists()) // XXX - could try a series of names throw new IOException("file exists"); ((MimeBodyPart) p).saveFile(f); } catch (IOException ex) { pr("Failed to save attachment: " + ex); } pr("---------------------------"); } } }
From source file:org.alfresco.repo.imap.AttachmentsExtractor.java
/** * Create an attachment given a mime part * /*from w ww. j av a2 s.com*/ * @param messageFile the file containing the message * @param attachmentsFolderRef where to put the attachment * @param part the mime part * @throws MessagingException * @throws IOException */ private void createAttachment(NodeRef messageFile, NodeRef attachmentsFolderRef, Part part) throws MessagingException, IOException { String fileName = part.getFileName(); if (fileName == null || fileName.isEmpty()) { fileName = "unnamed"; } try { fileName = MimeUtility.decodeText(fileName); } catch (UnsupportedEncodingException e) { if (logger.isWarnEnabled()) { logger.warn("Cannot decode file name '" + fileName + "'", e); } } ContentType contentType = new ContentType(part.getContentType()); if (contentType.getBaseType().equalsIgnoreCase("application/ms-tnef")) { // The content is TNEF HMEFMessage hmef = new HMEFMessage(part.getInputStream()); // hmef.getBody(); List<org.apache.poi.hmef.Attachment> attachments = hmef.getAttachments(); for (org.apache.poi.hmef.Attachment attachment : attachments) { String subName = attachment.getLongFilename(); NodeRef attachmentNode = fileFolderService.searchSimple(attachmentsFolderRef, subName); if (attachmentNode == null) { /* * If the node with the given name does not already exist Create the content node to contain the attachment */ FileInfo createdFile = fileFolderService.create(attachmentsFolderRef, subName, ContentModel.TYPE_CONTENT); attachmentNode = createdFile.getNodeRef(); serviceRegistry.getNodeService().createAssociation(messageFile, attachmentNode, ImapModel.ASSOC_IMAP_ATTACHMENT); byte[] bytes = attachment.getContents(); ContentWriter writer = fileFolderService.getWriter(attachmentNode); // TODO ENCODING - attachment.getAttribute(TNEFProperty.); String extension = attachment.getExtension(); String mimetype = mimetypeService.getMimetype(extension); if (mimetype != null) { writer.setMimetype(mimetype); } OutputStream os = writer.getContentOutputStream(); ByteArrayInputStream is = new ByteArrayInputStream(bytes); FileCopyUtils.copy(is, os); } } } else { // not TNEF NodeRef attachmentFile = fileFolderService.searchSimple(attachmentsFolderRef, fileName); // The one possible behaviour /* * if (result.size() > 0) { for (FileInfo fi : result) { fileFolderService.delete(fi.getNodeRef()); } } */ // And another one behaviour which will overwrite the content of the existing file. It is performance preferable. if (attachmentFile == null) { FileInfo createdFile = fileFolderService.create(attachmentsFolderRef, fileName, ContentModel.TYPE_CONTENT); nodeService.createAssociation(messageFile, createdFile.getNodeRef(), ImapModel.ASSOC_IMAP_ATTACHMENT); attachmentFile = createdFile.getNodeRef(); } else { String newFileName = imapService.generateUniqueFilename(attachmentsFolderRef, fileName); FileInfo createdFile = fileFolderService.create(attachmentsFolderRef, newFileName, ContentModel.TYPE_CONTENT); nodeService.createAssociation(messageFile, createdFile.getNodeRef(), ImapModel.ASSOC_IMAP_ATTACHMENT); attachmentFile = createdFile.getNodeRef(); } nodeService.setProperty(attachmentFile, ContentModel.PROP_DESCRIPTION, nodeService.getProperty(messageFile, ContentModel.PROP_NAME)); ContentWriter writer = fileFolderService.getWriter(attachmentFile); writer.setMimetype(contentType.getBaseType()); OutputStream os = writer.getContentOutputStream(); FileCopyUtils.copy(part.getInputStream(), os); } }
From source file:org.silverpeas.components.mailinglist.service.job.MailProcessor.java
protected static String extractContentType(String contentType) { try {//from www . j av a2 s . c o m ContentType type = new ContentType(contentType); return type.getBaseType(); } catch (ParseException e) { SilverTrace.error("mailinglist", "MailProcessor.extractContentType()", "mailinglist.notification.error", e); } return contentType; }
From source file:org.alfresco.module.org_alfresco_module_rm.action.impl.SplitEmailAction.java
/** * Create attachment from Mime Message Part * @param messageNodeRef - the node ref of the mime message * @param parentNodeRef - the node ref of the parent folder * @param part/*from w ww.j av a 2 s .c o m*/ * @throws MessagingException * @throws IOException */ private void createAttachment(NodeRef messageNodeRef, NodeRef parentNodeRef, Part part) throws MessagingException, IOException { String fileName = part.getFileName(); try { fileName = MimeUtility.decodeText(fileName); } catch (UnsupportedEncodingException e) { if (logger.isWarnEnabled()) { logger.warn("Cannot decode file name '" + fileName + "'", e); } } Map<QName, Serializable> messageProperties = getNodeService().getProperties(messageNodeRef); String messageTitle = (String) messageProperties.get(ContentModel.PROP_NAME); if (messageTitle == null) { messageTitle = fileName; } else { messageTitle = messageTitle + " - " + fileName; } ContentType contentType = new ContentType(part.getContentType()); Map<QName, Serializable> docProps = new HashMap<QName, Serializable>(1); docProps.put(ContentModel.PROP_NAME, messageTitle + " - " + fileName); docProps.put(ContentModel.PROP_TITLE, fileName); /** * Create an attachment node in the same folder as the message */ ChildAssociationRef attachmentRef = getNodeService().createNode(parentNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, fileName), ContentModel.TYPE_CONTENT, docProps); /** * Write the content into the new attachment node */ ContentWriter writer = getContentService().getWriter(attachmentRef.getChildRef(), ContentModel.PROP_CONTENT, true); writer.setMimetype(contentType.getBaseType()); OutputStream os = writer.getContentOutputStream(); FileCopyUtils.copy(part.getInputStream(), os); /** * Create a link from the message to the attachment */ createRMReference(messageNodeRef, attachmentRef.getChildRef()); }
From source file:org.apache.solr.handler.dataimport.FsMailEntityProcessor.java
public boolean addPartToDocument(Part part, Map<String, Object> row, boolean outerMost) throws Exception { if (outerMost && part instanceof Message) { if (!addEnvelopToDocument(part, row)) { return false; }// w w w .j av a2 s. c o m // store hash row.put(HASH, DigestUtils.md5Hex((String) row.get(FROM_CLEAN) + "" + (String) row.get(SUBJECT))); } String ct = part.getContentType(); ContentType ctype = new ContentType(ct); if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); int count = mp.getCount(); if (part.isMimeType("multipart/alternative")) { count = 1; } for (int i = 0; i < count; i++) { addPartToDocument(mp.getBodyPart(i), row, false); } } else if (part.isMimeType("message/rfc822")) { addPartToDocument((Part) part.getContent(), row, false); } else { String disp = part.getDisposition(); @SuppressWarnings("resource") // Tika will close stream InputStream is = part.getInputStream(); String fileName = part.getFileName(); Metadata md = new Metadata(); md.set(HttpHeaders.CONTENT_TYPE, ctype.getBaseType().toLowerCase(Locale.ROOT)); md.set(TikaMetadataKeys.RESOURCE_NAME_KEY, fileName); String content = this.tika.parseToString(is, md); if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) { if (row.get(ATTACHMENT) == null) { row.put(ATTACHMENT, new ArrayList<String>()); } List<String> contents = (List<String>) row.get(ATTACHMENT); contents.add(content); row.put(ATTACHMENT, contents); if (row.get(ATTACHMENT_NAMES) == null) { row.put(ATTACHMENT_NAMES, new ArrayList<String>()); } List<String> names = (List<String>) row.get(ATTACHMENT_NAMES); names.add(fileName); row.put(ATTACHMENT_NAMES, names); } else { if (row.get(CONTENT) == null) { row.put(CONTENT, new ArrayList<String>()); } List<String> contents = (List<String>) row.get(CONTENT); contents.add(content); row.put(CONTENT, contents); } } return true; }
From source file:com.silverpeas.mailinglist.service.job.MailProcessor.java
protected static String extractContentType(String contentType) { try {//from w w w. j a v a 2 s. com ContentType type = new ContentType(contentType); return type.getBaseType(); } catch (ParseException e) { SilverTrace.error("mailingList", "MailProcessor.extractContentType()", "mailinglist.notification.error", e); } return contentType; }
From source file:com.zotoh.crypto.CryptoUte.java
/** * @param cType/*w ww . j av a 2s . c o m*/ * @return */ public static String getCharset(String cType) { String rc = null; if (!isEmpty(cType)) try { String charset = (new ContentType(cType)).getParameter("charset"); rc = MimeUtility.javaCharset(charset); } catch (Exception e) { tlog().warn("", e); } return rc; }
From source file:MainClass.java
public static void dumpPart(Part p) throws Exception { if (p instanceof Message) dumpEnvelope((Message) p);//from w ww .j a va2 s.co m /** * Dump input stream .. * * InputStream is = p.getInputStream(); // If "is" is not already buffered, * wrap a BufferedInputStream // around it. if (!(is instanceof * BufferedInputStream)) is = new BufferedInputStream(is); int c; while ((c = * is.read()) != -1) System.out.write(c); * */ String ct = p.getContentType(); try { pr("CONTENT-TYPE: " + (new ContentType(ct)).toString()); } catch (ParseException pex) { pr("BAD CONTENT-TYPE: " + ct); } String filename = p.getFileName(); if (filename != null) pr("FILENAME: " + filename); /* * Using isMimeType to determine the content type avoids fetching the actual * content data until we need it. */ if (p.isMimeType("text/plain")) { pr("This is plain text"); pr("---------------------------"); if (!showStructure && !saveAttachments) System.out.println((String) p.getContent()); } else if (p.isMimeType("multipart/*")) { pr("This is a Multipart"); pr("---------------------------"); Multipart mp = (Multipart) p.getContent(); level++; int count = mp.getCount(); for (int i = 0; i < count; i++) dumpPart(mp.getBodyPart(i)); level--; } else if (p.isMimeType("message/rfc822")) { pr("This is a Nested Message"); pr("---------------------------"); level++; dumpPart((Part) p.getContent()); level--; } else { if (!showStructure && !saveAttachments) { /* * If we actually want to see the data, and it's not a MIME type we * know, fetch it and check its Java type. */ Object o = p.getContent(); if (o instanceof String) { pr("This is a string"); pr("---------------------------"); System.out.println((String) o); } else if (o instanceof InputStream) { pr("This is just an input stream"); pr("---------------------------"); InputStream is = (InputStream) o; int c; while ((c = is.read()) != -1) System.out.write(c); } else { pr("This is an unknown type"); pr("---------------------------"); pr(o.toString()); } } else { // just a separator pr("---------------------------"); } } /* * If we're saving attachments, write out anything that looks like an * attachment into an appropriately named file. Don't overwrite existing * files to prevent mistakes. */ if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) { String disp = p.getDisposition(); // many mailers don't include a Content-Disposition if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) { if (filename == null) filename = "Attachment" + attnum++; pr("Saving attachment to file " + filename); try { File f = new File(filename); if (f.exists()) // XXX - could try a series of names throw new IOException("file exists"); ((MimeBodyPart) p).saveFile(f); } catch (IOException ex) { pr("Failed to save attachment: " + ex); } pr("---------------------------"); } } }
From source file:com.ctriposs.r2.message.rest.QueryTunnelUtil.java
/** * Helper function to create multi-part MIME * * @param entity the body of a request * @param entityContentType content type of the body * @param query a query part of a request * * @return a ByteString that represents a multi-part encoded entity that contains both *//*ww w . j a v a 2s . com*/ private static MimeMultipart createMultiPartEntity(ByteString entity, String entityContentType, String query) throws MessagingException { MimeMultipart multi = new MimeMultipart(MIXED); // Create current entity with the associated type MimeBodyPart dataPart = new MimeBodyPart(); ContentType contentType = new ContentType(entityContentType); dataPart.setContent(entity.copyBytes(), contentType.getBaseType()); dataPart.setHeader(HEADER_CONTENT_TYPE, entityContentType); // Encode query params as form-urlencoded MimeBodyPart argPart = new MimeBodyPart(); argPart.setContent(query, FORM_URL_ENCODED); argPart.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED); multi.addBodyPart(argPart); multi.addBodyPart(dataPart); return multi; }