List of usage examples for javax.mail.internet MimeMultipart getBodyPart
public synchronized BodyPart getBodyPart(String CID) throws MessagingException
From source file:nl.nn.adapterframework.http.HttpSender.java
public static String handleMultipartResponse(String contentType, InputStream inputStream, ParameterResolutionContext prc, HttpMethod httpMethod) throws IOException, SenderException { String result = null;/*from w w w . ja v a2 s . co m*/ try { InputStreamDataSource dataSource = new InputStreamDataSource(contentType, inputStream); MimeMultipart mimeMultipart = new MimeMultipart(dataSource); for (int i = 0; i < mimeMultipart.getCount(); i++) { BodyPart bodyPart = mimeMultipart.getBodyPart(i); boolean lastPart = mimeMultipart.getCount() == i + 1; if (i == 0) { String charset = org.apache.http.entity.ContentType.parse(bodyPart.getContentType()) .getCharset().name(); InputStream bodyPartInputStream = bodyPart.getInputStream(); result = Misc.streamToString(bodyPartInputStream, charset); if (lastPart) { bodyPartInputStream.close(); } } else { // When the last stream is read the // httpMethod.releaseConnection() can be called, hence pass // httpMethod to ReleaseConnectionAfterReadInputStream. prc.getSession().put("multipart" + i, new ReleaseConnectionAfterReadInputStream( lastPart ? httpMethod : null, bodyPart.getInputStream())); } } } catch (MessagingException e) { throw new SenderException("Could not read mime multipart response", e); } return result; }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
public void testMessageModifiedBetweenReads() throws Exception { // Get test message UID final Long uid = getMessageUid(folder, 1); // Get unmodified message BODY body = getMessageBody(folder, uid); // Parse the multipart MIME message MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()), new BufferedInputStream(body.getByteArrayInputStream())); // Reading first part - should be successful MimeMultipart content = (MimeMultipart) message.getContent(); assertNotNull(content.getBodyPart(0).getContent()); // Reading second part - should be successful assertNotNull(content.getBodyPart(1).getContent()); // Modify message. The size of letter describing the node may change // These changes should be committed because it should be visible from client NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE); UserTransaction txn = transactionService.getUserTransaction(); txn.begin();/*from w w w .j a v a 2 s .c om*/ ContentWriter writer = fileFolderService.getWriter(contentNode); StringBuffer sb = new StringBuffer(); for (int i = 0; i < 2000; i++) { sb.append("test string"); } writer.putContent(sb.toString()); txn.commit(); // Read updated message part BODY bodyNew = getMessageBody(folder, uid); // The body should be updated assertFalse(Arrays.equals(bodyNew.getByteArray().getBytes(), body.getByteArray().getBytes())); // Parse the multipart MIME message message = new MimeMessage(Session.getDefaultInstance(new Properties()), new BufferedInputStream(bodyNew.getByteArrayInputStream())); // Reading first part - should be successful content = (MimeMultipart) message.getContent(); assertNotNull(content.getBodyPart(0).getContent()); // Reading second part - should be successful assertNotNull(content.getBodyPart(1).getContent()); }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
public void dontTestMessageCache() throws Exception { // Create messages NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE); UserTransaction txn = transactionService.getUserTransaction(); txn.begin();/* www . ja v a 2 s . c o m*/ // Create messages more than cache capacity for (int i = 0; i < 51; i++) { FileInfo fi = fileFolderService.create(nodeService.getParentAssocs(contentNode).get(0).getParentRef(), "test" + i, ContentModel.TYPE_CONTENT); ContentWriter writer = fileFolderService.getWriter(fi.getNodeRef()); writer.putContent("test"); } txn.commit(); // Reload folder folder.close(false); folder = (IMAPFolder) store.getFolder(TEST_FOLDER); folder.open(Folder.READ_ONLY); // Read all messages for (int i = 1; i < 51; i++) { // Get test message UID final Long uid = getMessageUid(folder, i); // Get Message size final int count = getMessageSize(folder, uid); // Get first part BODY body = getMessageBodyPart(folder, uid, 0, count - 100); // Read second message part BODY bodyRest = getMessageBodyPart(folder, uid, count - 100, 100); // Creating and parsing message from 2 parts MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()), new SequenceInputStream(new BufferedInputStream(body.getByteArrayInputStream()), new BufferedInputStream(bodyRest.getByteArrayInputStream()))); // Reading first part - should be successful MimeMultipart content = (MimeMultipart) message.getContent(); assertNotNull(content.getBodyPart(0).getContent()); assertNotNull(content.getBodyPart(1).getContent()); } }
From source file:voldemort.restclient.R2Store.java
private List<Versioned<byte[]>> parseGetResponse(ByteString entity) { List<Versioned<byte[]>> results = new ArrayList<Versioned<byte[]>>(); try {/*from ww w.j a va 2s . c om*/ // Build the multipart object byte[] bytes = new byte[entity.length()]; entity.copyBytes(bytes, 0); ByteArrayDataSource ds = new ByteArrayDataSource(bytes, "multipart/mixed"); MimeMultipart mp = new MimeMultipart(ds); for (int i = 0; i < mp.getCount(); i++) { MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(i); String serializedVC = part.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0]; int contentLength = Integer.parseInt(part.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]); if (logger.isDebugEnabled()) { logger.debug("Received VC : " + serializedVC); } VectorClockWrapper vcWrapper = mapper.readValue(serializedVC, VectorClockWrapper.class); InputStream input = part.getInputStream(); byte[] bodyPartBytes = new byte[contentLength]; input.read(bodyPartBytes); VectorClock clock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp()); results.add(new Versioned<byte[]>(bodyPartBytes, clock)); } } catch (MessagingException e) { throw new VoldemortException("Messaging exception while trying to parse GET response " + e.getMessage(), e); } catch (JsonParseException e) { throw new VoldemortException( "JSON parsing exception while trying to parse GET response " + e.getMessage(), e); } catch (JsonMappingException e) { throw new VoldemortException( "JSON mapping exception while trying to parse GET response " + e.getMessage(), e); } catch (IOException e) { throw new VoldemortException("IO exception while trying to parse GET response " + e.getMessage(), e); } return results; }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
public void testUnmodifiedMessage() throws Exception { // Get test message UID final Long uid = getMessageUid(folder, 1); // Get Message size final int count = getMessageSize(folder, uid); // Make multiple message reading for (int i = 0; i < 100; i++) { // Get random offset int n = (int) ((int) 100 * Math.random()); // Get first part BODY body = getMessageBodyPart(folder, uid, 0, count - n); // Read second message part BODY bodyRest = getMessageBodyPart(folder, uid, count - n, n); // Creating and parsing message from 2 parts MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()), new SequenceInputStream(new BufferedInputStream(body.getByteArrayInputStream()), new BufferedInputStream(bodyRest.getByteArrayInputStream()))); MimeMultipart content = (MimeMultipart) message.getContent(); // Reading first part - should be successful assertNotNull(content.getBodyPart(0).getContent()); // Reading second part - should be successful assertNotNull(content.getBodyPart(1).getContent()); }// w ww .j av a 2s . com }
From source file:net.fenyo.mail4hotspot.service.MailManager.java
private String getMultipartContentString(final MimeMultipart multipart, final boolean mixed) throws IOException, MessagingException { // content-type: multipart/mixed ou multipart/alternative final StringBuffer selected_content = new StringBuffer(); for (int i = 0; i < multipart.getCount(); i++) { final BodyPart body_part = multipart.getBodyPart(i); final Object content = body_part.getContent(); final String content_string; if (String.class.isInstance(content)) if (body_part.isMimeType("text/html")) content_string = GenericTools.html2Text((String) content); else if (body_part.isMimeType("text/plain")) content_string = (String) content; else { log.warn("body part content-type not handled: " + body_part.getContentType() + " -> downgrading to String"); content_string = (String) content; }//from w ww. j a va 2 s. c o m else if (MimeMultipart.class.isInstance(content)) { boolean part_mixed = false; if (body_part.isMimeType("multipart/mixed")) part_mixed = true; else if (body_part.isMimeType("multipart/alternative")) part_mixed = false; else { log.warn("body part content-type not handled: " + body_part.getContentType() + " -> downgrading to multipart/mixed"); part_mixed = true; } content_string = getMultipartContentString((MimeMultipart) content, part_mixed); } else { log.warn("invalid body part content type and class: " + content.getClass().toString() + " - " + body_part.getContentType()); content_string = ""; } if (mixed == false) { // on slectionne la premire part non vide - ce n'est pas forcment la meilleure alternative, mais comment diffrentiel un text/plain d'une pice jointe d'un text/plain du corps du message, accompagnant un text/html du mme corps ??? if (selected_content.length() == 0) selected_content.append(content_string); } else { if (selected_content.length() > 0 && content_string.length() > 0) selected_content.append("\r\n---\r\n"); selected_content.append(content_string); } } return selected_content.toString(); }
From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java
private void appendMultiPart(SampleResult child, StringBuilder cdata, MimeMultipart mmp) throws MessagingException, IOException { String preamble = mmp.getPreamble(); if (preamble != null) { cdata.append(preamble);//from w w w. ja v a 2 s . co m } child.setResponseData(cdata.toString(), child.getDataEncodingNoDefault()); int count = mmp.getCount(); for (int j = 0; j < count; j++) { BodyPart bodyPart = mmp.getBodyPart(j); final Object bodyPartContent = bodyPart.getContent(); final String contentType = bodyPart.getContentType(); SampleResult sr = new SampleResult(); sr.setSampleLabel("Part: " + j); sr.setContentType(contentType); sr.setDataEncoding(RFC_822_DEFAULT_ENCODING); sr.setEncodingAndType(contentType); sr.sampleStart(); if (bodyPartContent instanceof InputStream) { sr.setResponseData(IOUtils.toByteArray((InputStream) bodyPartContent)); } else if (bodyPartContent instanceof MimeMultipart) { appendMultiPart(sr, cdata, (MimeMultipart) bodyPartContent); } else { sr.setResponseData(bodyPartContent.toString(), sr.getDataEncodingNoDefault()); } sr.setResponseOK(); if (sr.getEndTime() == 0) {// not been set by any child samples sr.sampleEnd(); } child.addSubResult(sr); } }
From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.MimeMessageResponse.java
public MimeMessageResponse(WsdlRequest wsdlRequest, final TimeablePostMethod postMethod, String requestContent) {//from ww w.j av a 2 s . co m this.wsdlRequest = wsdlRequest; this.requestContent = requestContent; this.timeTaken = postMethod.getTimeTaken(); responseContentLength = postMethod.getResponseContentLength(); try { initHeaders(postMethod); MimeMultipart mp = new MimeMultipart(new PostResponseDataSource(postMethod)); message = new MimeMessage(HttpClientRequestTransport.JAVAMAIL_SESSION); message.setContent(mp); Header h = postMethod.getResponseHeader("Content-Type"); HeaderElement[] elements = h.getElements(); String rootPartId = null; for (HeaderElement element : elements) { if (element.getName().toUpperCase().startsWith("MULTIPART/")) { NameValuePair parameter = element.getParameterByName("start"); if (parameter != null) rootPartId = parameter.getValue(); } } for (int c = 0; c < mp.getCount(); c++) { BodyPart bodyPart = mp.getBodyPart(c); if (bodyPart.getContentType().toUpperCase().startsWith("MULTIPART/")) { MimeMultipart mp2 = new MimeMultipart(new BodyPartDataSource(bodyPart)); for (int i = 0; i < mp2.getCount(); i++) { result.add(new BodyPartAttachment(mp2.getBodyPart(i))); } } else { BodyPartAttachment attachment = new BodyPartAttachment(bodyPart); String[] contentIdHeaders = bodyPart.getHeader("Content-ID"); if (contentIdHeaders != null && contentIdHeaders.length > 0 && contentIdHeaders[0].equals(rootPartId)) { rootPart = attachment; } else result.add(attachment); } } // if no explicit root part has been set, use the first one in the result if (rootPart == null) rootPart = result.remove(0); if (wsdlRequest.getSettings().getBoolean(HttpSettings.INCLUDE_RESPONSE_IN_TIME_TAKEN)) this.timeTaken = postMethod.getTimeTakenUntilNow(); } catch (Exception e) { e.printStackTrace(); } }
From source file:voldemort.restclient.R2Store.java
private Map<ByteArray, List<Versioned<byte[]>>> parseGetAllResults(ByteString entity) { Map<ByteArray, List<Versioned<byte[]>>> results = new HashMap<ByteArray, List<Versioned<byte[]>>>(); try {/*from w w w .ja v a2s . com*/ // Build the multipart object byte[] bytes = new byte[entity.length()]; entity.copyBytes(bytes, 0); // Get the outer multipart object ByteArrayDataSource ds = new ByteArrayDataSource(bytes, "multipart/mixed"); MimeMultipart mp = new MimeMultipart(ds); for (int i = 0; i < mp.getCount(); i++) { // Get an individual part. This contains all the versioned // values for a particular key referenced by content-location MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(i); // Get the key String contentLocation = part.getHeader("Content-Location")[0]; String base64Key = contentLocation.split("/")[2]; ByteArray key = new ByteArray(RestUtils.decodeVoldemortKey(base64Key)); if (logger.isDebugEnabled()) { logger.debug("Content-Location : " + contentLocation); logger.debug("Base 64 key : " + base64Key); } // Create an array list for holding all the (versioned values) List<Versioned<byte[]>> valueResultList = new ArrayList<Versioned<byte[]>>(); // Get the nested Multi-part object. This contains one part for // each unique versioned value. ByteArrayDataSource nestedDS = new ByteArrayDataSource((String) part.getContent(), "multipart/mixed"); MimeMultipart valueParts = new MimeMultipart(nestedDS); for (int valueId = 0; valueId < valueParts.getCount(); valueId++) { MimeBodyPart valuePart = (MimeBodyPart) valueParts.getBodyPart(valueId); String serializedVC = valuePart.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0]; int contentLength = Integer.parseInt(valuePart.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]); if (logger.isDebugEnabled()) { logger.debug("Received serialized Vector Clock : " + serializedVC); } VectorClockWrapper vcWrapper = mapper.readValue(serializedVC, VectorClockWrapper.class); // get the value bytes InputStream input = valuePart.getInputStream(); byte[] bodyPartBytes = new byte[contentLength]; input.read(bodyPartBytes); VectorClock clock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp()); valueResultList.add(new Versioned<byte[]>(bodyPartBytes, clock)); } results.put(key, valueResultList); } } catch (MessagingException e) { throw new VoldemortException("Messaging exception while trying to parse GET response " + e.getMessage(), e); } catch (JsonParseException e) { throw new VoldemortException( "JSON parsing exception while trying to parse GET response " + e.getMessage(), e); } catch (JsonMappingException e) { throw new VoldemortException( "JSON mapping exception while trying to parse GET response " + e.getMessage(), e); } catch (IOException e) { throw new VoldemortException("IO exception while trying to parse GET response " + e.getMessage(), e); } return results; }
From source file:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java
@Test public void testMultipartWithIllegalContentTransferEncoding() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); mailetConfig.setInitParameter("algorithm", "AES128"); SMIMEEncrypt mailet = new SMIMEEncrypt(); mailet.init(mailetConfig);/*ww w. jav a 2 s . c o m*/ Mail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/quoted-printable-multipart.eml")); assertTrue(message.isMimeType("multipart/mixed")); MimeMultipart mp = (MimeMultipart) message.getContent(); assertEquals(2, mp.getCount()); BodyPart part = mp.getBodyPart(0); assertTrue(part.isMimeType("text/plain")); assertEquals("==", (String) part.getContent()); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("test@example.com")); mail.setRecipients(recipients); DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail); mailAttributes.setCertificates(certificates); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); KeyStoreKeyProvider keyStore = new KeyStoreKeyProvider( loadKeyStore(new File("test/resources/testdata/keys/testCertificates.p12"), "test"), "test"); SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), keyStore, "BC"); assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType()); assertEquals(SMIMEEncryptionAlgorithm.AES128_CBC.getOID().toString(), inspector.getEnvelopedInspector().getEncryptionAlgorithmOID()); assertEquals(20, inspector.getEnvelopedInspector().getRecipients().size()); MimeMessage decrypted = inspector.getContentAsMimeMessage(); decrypted.saveChanges(); assertNotNull(decrypted); MailUtils.writeMessage(decrypted, new File(tempDir, "testMultipartWithIllegalContentTransferEncoding.eml")); assertTrue(decrypted.isMimeType("multipart/mixed")); mp = (MimeMultipart) decrypted.getContent(); assertEquals(2, mp.getCount()); part = mp.getBodyPart(0); assertTrue(part.isMimeType("text/plain")); /* * The body should not be changed to =3D=3D because the body should not be quoted-printable encoded * again */ assertEquals("==", (String) part.getContent()); }