List of usage examples for javax.mail.internet MimeBodyPart getDataHandler
@Override public DataHandler getDataHandler() throws MessagingException
From source file:org.apache.axis.attachments.MimeUtils.java
/** * Determine the length for the individual part. * @param bp is the part to be searched. * @return the length in bytes.//from www .j a v a 2 s .c om */ protected static long getContentLength(javax.mail.internet.MimeBodyPart bp) { long headerLength = -1L; long dataSize = -1L; try { headerLength = getHeaderLength(bp); javax.activation.DataHandler dh = bp.getDataHandler(); javax.activation.DataSource ds = dh.getDataSource(); // Do files our selfs since this is costly to read in. Ask the file system. // This is 90% of the use of attachments. if (ds instanceof javax.activation.FileDataSource) { javax.activation.FileDataSource fdh = (javax.activation.FileDataSource) ds; java.io.File df = fdh.getFile(); if (!df.exists()) { throw new RuntimeException(Messages.getMessage("noFile", df.getAbsolutePath())); } dataSize = df.length(); } else { dataSize = bp.getSize(); if (-1 == dataSize) { // Data size is not known so read it the hard way... dataSize = 0; java.io.InputStream in = ds.getInputStream(); byte[] readbuf = new byte[64 * 1024]; int bytesread; do { bytesread = in.read(readbuf); if (bytesread > 0) { dataSize += bytesread; } } while (bytesread > -1); in.close(); } } } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); } return dataSize + headerLength; }
From source file:org.apache.olingo.fit.AbstractServices.java
protected Response bodyPartRequest(final MimeBodyPart body, final Map<String, String> references) throws Exception { @SuppressWarnings("unchecked") final Enumeration<Header> en = body.getAllHeaders(); Header header = en.nextElement();//from w ww . ja va 2 s . c o m final String request = header.getName() + (StringUtils.isNotBlank(header.getValue()) ? ":" + header.getValue() : ""); final Matcher matcher = REQUEST_PATTERN.matcher(request); final Matcher matcherRef = BATCH_REQUEST_REF_PATTERN.matcher(request); final MultivaluedMap<String, String> headers = new MultivaluedHashMap<String, String>(); while (en.hasMoreElements()) { header = en.nextElement(); headers.putSingle(header.getName(), header.getValue()); } final Response res; final String url; final String method; if (matcher.find()) { url = matcher.group(2); method = matcher.group(1); } else if (matcherRef.find()) { url = references.get(matcherRef.group(2)) + matcherRef.group(3); method = matcherRef.group(1); } else { url = null; method = null; } if (url == null) { res = null; } else { final WebClient client = WebClient.create(url, "odatajclient", "odatajclient", null); client.headers(headers); if ("DELETE".equals(method)) { res = client.delete(); } else { final InputStream is = body.getDataHandler().getInputStream(); String content = IOUtils.toString(is); IOUtils.closeQuietly(is); final Matcher refs = REF_PATTERN.matcher(content); while (refs.find()) { content = content.replace(refs.group(1), references.get(refs.group(1))); } if ("PATCH".equals(method) || "MERGE".equals(method)) { client.header("X-HTTP-METHOD", method); res = client.invoke("POST", IOUtils.toInputStream(content)); } else { res = client.invoke(method, IOUtils.toInputStream(content)); } } // When updating to CXF 3.0.1, uncomment the following line, see CXF-5865 //client.close(); } return res; }
From source file:org.apache.olingo.fit.Services.java
private Response bodyPartRequest(final MimeBodyPart body, final Map<String, String> references) throws Exception { @SuppressWarnings("unchecked") final Enumeration<Header> en = body.getAllHeaders(); Header header = en.nextElement();//from w ww .ja va 2 s .co m final String request = header.getName() + (StringUtils.isNotBlank(header.getValue()) ? ":" + header.getValue() : ""); final Matcher matcher = REQUEST_PATTERN.matcher(request); final Matcher matcherRef = BATCH_REQUEST_REF_PATTERN.matcher(request); final MultivaluedMap<String, String> headers = new MultivaluedHashMap<String, String>(); while (en.hasMoreElements()) { header = en.nextElement(); headers.putSingle(header.getName(), header.getValue()); } final Response res; final String url; final String method; if (matcher.find()) { url = matcher.group(2); method = matcher.group(1); } else if (matcherRef.find()) { url = references.get(matcherRef.group(2)) + matcherRef.group(3); method = matcherRef.group(1); } else { url = null; method = null; } if (url == null) { res = null; } else { final WebClient client = WebClient.create(url, "odatajclient", "odatajclient", null); client.headers(headers); if ("DELETE".equals(method)) { res = client.delete(); } else { final InputStream is = body.getDataHandler().getInputStream(); String content = IOUtils.toString(is); IOUtils.closeQuietly(is); final Matcher refs = REF_PATTERN.matcher(content); while (refs.find()) { content = content.replace(refs.group(1), references.get(refs.group(1))); } if ("PATCH".equals(method) || "MERGE".equals(method)) { client.header("X-HTTP-METHOD", method); res = client.invoke("POST", IOUtils.toInputStream(content)); } else { res = client.invoke(method, IOUtils.toInputStream(content)); } } // When updating to CXF 3.0.1, uncomment the following line, see CXF-5865 // client.close(); } return res; }
From source file:org.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Message.java
public Attach getAttach(Part part, String baseStorePath) throws MessagingException, IOException { MimeBodyPart mimePart = (MimeBodyPart) part; Attach attach = new Attach(); if (StringUtils.isEmpty(mimePart.getFileName())) { attach.setFileName("UNKNOWN"); } else {/* ww w . jav a 2s . c o m*/ String fileName = mimePart.getFileName(); String encoded = System.getProperty("mail.mime.encodefilename"); if (Boolean.parseBoolean(encoded)) { fileName = MimeUtility.decodeText(fileName); } attach.setFileName(fileName); } ContentType type = new ContentType(mimePart.getContentType()); attach.setMimeType(type.getBaseType()); InputStream inputStream = mimePart.getDataHandler().getInputStream(); attach.buildMd5Checksum(inputStream); attach.buildPath(mimePart, baseStorePath); return attach; }
From source file:org.nuclos.server.ruleengine.RuleInterface.java
/** * * @param pop3Host//from ww w.ja v a2 s .c o m * @param pop3Port * @param pop3User * @param pop3Password * @param remove * @return * @throws NuclosFatalRuleException */ public List<NuclosMail> getMails(String pop3Host, String pop3Port, final String pop3User, final String pop3Password, boolean remove) throws NuclosFatalRuleException { try { Properties properties = new Properties(); properties.setProperty("mail.pop3.host", pop3Host); properties.setProperty("mail.pop3.port", pop3Port); properties.setProperty("mail.pop3.auth", "true"); properties.setProperty("mail.pop3.socketFactory.class", "javax.net.DefaultSocketFactory"); Session session = Session.getInstance(properties, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(pop3User, pop3Password); } }); session.setDebug(true); Store store = session.getStore("pop3"); store.connect(); Folder folder = store.getFolder("INBOX"); if (remove) { folder.open(Folder.READ_WRITE); } else { folder.open(Folder.READ_ONLY); } List<NuclosMail> result = new ArrayList<NuclosMail>(); Message message[] = folder.getMessages(); for (int i = 0; i < message.length; i++) { Message m = message[i]; NuclosMail mail = new NuclosMail(); logger.debug("Received mail: From: " + Arrays.toString(m.getFrom()) + "; To: " + Arrays.toString(m.getAllRecipients()) + "; ContentType: " + m.getContentType() + "; Subject: " + m.getSubject() + "; Sent: " + m.getSentDate()); Address[] senders = m.getFrom(); if (senders.length == 1 && senders[0] instanceof InternetAddress) { mail.setFrom(((InternetAddress) senders[0]).getAddress()); } else { mail.setFrom(Arrays.toString(m.getFrom())); } mail.setTo(Arrays.toString(m.getRecipients(RecipientType.TO))); mail.setSubject(m.getSubject()); if (m.isMimeType("text/plain")) { mail.setMessage((String) m.getContent()); } else { Multipart mp = (Multipart) m.getContent(); for (int j = 0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); MimeBodyPart mimePart = (MimeBodyPart) part; logger.debug( "Disposition: " + disposition + "; Part ContentType: " + mimePart.getContentType()); if (disposition == null && (mimePart.isMimeType("text/plain") || mimePart.isMimeType("text/html"))) { mail.setMessage((String) mimePart.getDataHandler().getContent()); } } getAttachments(mp, mail); } result.add(mail); if (remove) { m.setFlag(Flags.Flag.DELETED, true); } } if (remove) { folder.close(true); } else { folder.close(false); } store.close(); return result; } catch (Exception e) { throw new NuclosFatalRuleException(e); } }
From source file:org.xmlactions.email.EMailParser.java
private void handlePart(Part part) throws MessagingException, IOException, DocumentException { log.debug("\n\n\nhandlePart ==>>"); log.debug("part.toString():" + part.toString()); log.debug(//from w ww .j a v a2 s. c o m "part.getContent():" + (part.getFileName() == null ? part.getContent().toString() : "Attachment")); log.debug("part.getContentType():" + part.getContentType()); log.debug("part.getFilename():" + part.getFileName()); log.debug("part.isAttachment:" + part.getFileName()); log.debug("part.isMessage:" + (part.getContent() instanceof Message)); Object obj = part.getContent(); if (obj instanceof Multipart) { Multipart mmp = (Multipart) obj; for (int i = 0; i < mmp.getCount(); i++) { Part bodyPart = mmp.getBodyPart(i); if (bodyPart instanceof Message) { setFirstMessageProcessed(true);// need to mark this when we // get a forwarded message // so we don't look for case // numbers in forwarded // emails. } handlePart(bodyPart); } } else if (obj instanceof Part) { if (obj instanceof Message) { setFirstMessageProcessed(true);// need to mark this when we get // a forwarded message so we // don't look for case numbers // in forwarded emails. } handlePart((Part) obj); } else { if (part instanceof MimeBodyPart) { MimeBodyPart p = (MimeBodyPart) part; Enumeration enumeration = p.getAllHeaders(); while (enumeration.hasMoreElements()) { Object e = enumeration.nextElement(); if (e == null) e = null; } Object content = p.getContent(); enumeration = p.getAllHeaderLines(); while (enumeration.hasMoreElements()) { Object e = enumeration.nextElement(); if (e == null) e = null; } DataHandler dh = p.getDataHandler(); if (dh == null) dh = null; } addPart(part); log.debug("=== Add Part ==="); log.debug((String) (part.getFileName() != null ? "isAttachment" : part.getContent())); // log.info("not recognised class:" + obj.getClass().getName() + // "\n" + obj); } log.debug("<<== handlePart"); }
From source file:org.xwiki.mail.internal.AttachmentMimeBodyPartFactoryTest.java
@Test public void createAttachmentBodyPart() throws Exception { Environment environment = this.mocker.getInstance(Environment.class); when(environment.getTemporaryDirectory()).thenReturn(new File(TEMPORARY_DIRECTORY)); Attachment attachment = mock(Attachment.class); when(attachment.getContent()).thenReturn("Lorem Ipsum".getBytes()); when(attachment.getFilename()).thenReturn("image.png"); when(attachment.getMimeType()).thenReturn("image/png"); MimeBodyPart part = this.mocker.getComponentUnderTest().create(attachment, Collections.<String, Object>emptyMap()); assertEquals("<image.png>", part.getContentID()); // JavaMail adds some extra params to the content-type header // (e.g. image/png; name=attachment8219195155963823979.tmp) , we just verify the content type that we passed. assertTrue(part.getContentType().startsWith("image/png")); // We verify the format of the generated temporary file containing our attachment data assertTrue(part.getFileName().matches("attachment.*\\.tmp")); assertEquals("Lorem Ipsum", IOUtils.toString(part.getDataHandler().getInputStream())); }
From source file:org.xwiki.mail.internal.AttachmentMimeBodyPartFactoryTest.java
@Test public void createAttachmentBodyPartWithHeader() throws Exception { Environment environment = this.mocker.getInstance(Environment.class); when(environment.getTemporaryDirectory()).thenReturn(new File(TEMPORARY_DIRECTORY)); Attachment attachment = mock(Attachment.class); when(attachment.getContent()).thenReturn("Lorem Ipsum".getBytes()); when(attachment.getFilename()).thenReturn("image.png"); when(attachment.getMimeType()).thenReturn("image/png"); Map<String, Object> parameters = Collections.singletonMap("headers", (Object) Collections.singletonMap("Content-Transfer-Encoding", "quoted-printable")); MimeBodyPart part = this.mocker.getComponentUnderTest().create(attachment, parameters); assertEquals("<image.png>", part.getContentID()); // JavaMail adds some extra params to the content-type header // (e.g. image/png; name=attachment8219195155963823979.tmp) , we just verify the content type that we passed. assertTrue(part.getContentType().startsWith("image/png")); // We verify the format of the generated temporary file containing our attachment data assertTrue(part.getFileName().matches("attachment.*\\.tmp")); assertArrayEquals(new String[] { "quoted-printable" }, part.getHeader("Content-Transfer-Encoding")); assertEquals("Lorem Ipsum", IOUtils.toString(part.getDataHandler().getInputStream())); }
From source file:org.xwiki.mail.internal.factory.attachment.AttachmentMimeBodyPartFactoryTest.java
@Test public void createAttachmentBodyPart() throws Exception { Environment environment = this.mocker.getInstance(Environment.class); when(environment.getTemporaryDirectory()).thenReturn(new File(TEMPORARY_DIRECTORY)); Attachment attachment = mock(Attachment.class); when(attachment.getContent()).thenReturn("Lorem Ipsum".getBytes()); when(attachment.getFilename()).thenReturn("image.png"); when(attachment.getMimeType()).thenReturn("image/png"); MimeBodyPart part = this.mocker.getComponentUnderTest().create(attachment, Collections.<String, Object>emptyMap()); assertEquals("<image.png>", part.getContentID()); // JavaMail adds some extra params to the content-type header // (e.g. image/png; name=image.png) , we just verify the content type that we passed. assertTrue(part.getContentType().startsWith("image/png")); // We verify that the Content-Disposition has the correct file namr assertTrue(part.getFileName().matches("image\\.png")); assertEquals("Lorem Ipsum", IOUtils.toString(part.getDataHandler().getInputStream())); }
From source file:org.xwiki.mail.internal.factory.attachment.AttachmentMimeBodyPartFactoryTest.java
@Test public void createAttachmentBodyPartWithHeader() throws Exception { Environment environment = this.mocker.getInstance(Environment.class); when(environment.getTemporaryDirectory()).thenReturn(new File(TEMPORARY_DIRECTORY)); Attachment attachment = mock(Attachment.class); when(attachment.getContent()).thenReturn("Lorem Ipsum".getBytes()); when(attachment.getFilename()).thenReturn("image.png"); when(attachment.getMimeType()).thenReturn("image/png"); Map<String, Object> parameters = Collections.singletonMap("headers", (Object) Collections.singletonMap("Content-Transfer-Encoding", "quoted-printable")); MimeBodyPart part = this.mocker.getComponentUnderTest().create(attachment, parameters); assertEquals("<image.png>", part.getContentID()); // JavaMail adds some extra params to the content-type header // (e.g. image/png; name=image.png) , we just verify the content type that we passed. assertTrue(part.getContentType().startsWith("image/png")); // We verify that the Content-Disposition has the correct file namr assertTrue(part.getFileName().matches("image\\.png")); assertArrayEquals(new String[] { "quoted-printable" }, part.getHeader("Content-Transfer-Encoding")); assertEquals("Lorem Ipsum", IOUtils.toString(part.getDataHandler().getInputStream())); }