Java Code Examples for javax.mail.util.ByteArrayDataSource
The following are top voted examples for showing how to use
javax.mail.util.ByteArrayDataSource. These examples are extracted from open source projects.
You can vote up the examples you like and your votes will be used in our system to generate
more good examples.
Example 1
Project: Camel File: MailBinding.java View source code | 7 votes |
protected String populateContentOnBodyPart(BodyPart part, MailConfiguration configuration, Exchange exchange) throws MessagingException, IOException { String contentType = determineContentType(configuration, exchange); if (contentType != null) { LOG.trace("Using Content-Type {} for BodyPart: {}", contentType, part); // always store content in a byte array data store to avoid various content type and charset issues String data = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange.getIn().getBody()); // use empty data if the body was null for some reason (otherwise there is a NPE) data = data != null ? data : ""; DataSource ds = new ByteArrayDataSource(data, contentType); part.setDataHandler(new DataHandler(ds)); // set the content type header afterwards part.setHeader("Content-Type", contentType); } return contentType; }
Example 2
Project: simple-java-mail File: MailTestDemoApp.java View source code | 7 votes |
public static void main(final String[] args) throws Exception { final EmailPopulatingBuilder emailPopulatingBuilderNormal = EmailBuilder.startingBlank(); emailPopulatingBuilderNormal.from("lollypop", "lol[email protected]com"); // don't forget to add your own address here -> emailPopulatingBuilderNormal.to("C.Cane", YOUR_GMAIL_ADDRESS); emailPopulatingBuilderNormal.withPlainText("We should meet up!"); emailPopulatingBuilderNormal.withHTMLText("<b>We should meet up!</b><img src='cid:thumbsup'>"); emailPopulatingBuilderNormal.withSubject("hey"); // add two text files in different ways and a black thumbs up embedded image -> emailPopulatingBuilderNormal.withAttachment("dresscode.txt", new ByteArrayDataSource("Black Tie Optional", "text/plain")); emailPopulatingBuilderNormal.withAttachment("location.txt", "On the moon!".getBytes(Charset.defaultCharset()), "text/plain"); String base64String = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABeElEQVRYw2NgoAAYGxu3GxkZ7TY1NZVloDcAWq4MxH+B+D8Qv3FwcOCgtwM6oJaDMTAUXOhmuYqKCjvQ0pdoDrCnmwNMTEwakC0H4u8GBgYC9Ap6DSD+iewAoIPm0ctyLqBlp9F8/x+YE4zpYT8T0LL16JYD8U26+B7oyz4sloPwenpYno3DchCeROsUbwa05A8eB3wB4kqgIxOAuArIng7EW4H4EhC/B+JXQLwDaI4ryZaDSjeg5mt4LCcFXyIn1fdSyXJQVt1OtMWGhoai0OD8T0W8GohZifE1PxD/o7LlsPLiFNAKRrwOABWptLAcqc6QGDAHQEOAYaAc8BNotsJAOgAUAosG1AFA/AtUoY3YEFhKMAvS2AE7iC1+WaG1H6gY3gzE36hUFJ8mqzbU1dUVBBqQBzTgIDQRkWo5qCZdpaenJ0Zx1aytrc0DDB0foIG1oAYKqC0IZK8D4n1AfA6IzwPxXpCFoGoZVEUDaRGGUTAKRgEeAAA2eGJC+ETCiAAAAABJRU5ErkJggg=="; emailPopulatingBuilderNormal.withEmbeddedImage("thumbsup", parseBase64Binary(base64String), "image/png"); // let's try producing and then consuming a MimeMessage -> Email emailNormal = emailPopulatingBuilderNormal.buildEmail(); final MimeMessage mimeMessage = EmailConverter.emailToMimeMessage(emailNormal); final Email emailFromMimeMessage = EmailConverter.mimeMessageToEmail(mimeMessage); // note: the following statements will produce 6 new emails! sendMail(emailNormal); sendMail(emailFromMimeMessage); // should produce the exact same result as emailPopulatingBuilderNormal! }
Example 3
Project: jersey-smime File: SignedReader.java View source code | 7 votes |
@Override public SignedInput readFrom(Class<SignedInput> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> headers, InputStream entityStream) throws IOException, WebApplicationException { Class<?> baseType = null; Type baseGenericType = null; if (genericType instanceof ParameterizedType) { ParameterizedType param = (ParameterizedType) genericType; baseGenericType = param.getActualTypeArguments()[0]; baseType = Types.getRawType(baseGenericType); } try { ByteArrayDataSource ds = new ByteArrayDataSource(entityStream, mediaType.toString()); MimeMultipart mm = new MimeMultipart(ds); SignedInputImpl input = new SignedInputImpl(); input.setType(baseType); input.setGenericType(baseGenericType); input.setAnnotations(annotations); input.setBody(mm); input.setProviders(providers); return input; } catch (MessagingException e) { throw new RuntimeException(e); } }
Example 4
Project: carrier File: SMTPMessageFactory.java View source code | 6 votes |
/** * Creates a list of {@link MimeMessage} attachments using the given incoming e-mail. * * @param email The parsed e-mail. * @return A list containing the attachments, if any. * @throws Exception If there is an error while constructing the list of attachments. */ private List<BodyPart> createMimeMessageAttachments(Email email) throws Exception { List<BodyPart> attachments = new LinkedList<>(); for (Attachment attachment : email.getAttachments()) { BodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setFileName(attachment.getAttachmentName()); byte[] data = ByteStreams.toByteArray(attachment.getIs()); DataSource source = new ByteArrayDataSource(data, "application/octet-stream"); attachmentBodyPart.setDataHandler(new DataHandler(source)); attachments.add(attachmentBodyPart); } return attachments; }
Example 5
Project: dungeonstory-java File: MailTestApp.java View source code | 6 votes |
public static void main(final String[] args) throws Exception { clearConfigProperties(); final Email emailNormal = new Email(); emailNormal.setFromAddress("lollypop", "[email protected]"); // don't forget to add your own address here -> emailNormal.addRecipient("C.Cane", YOUR_GMAIL_ADDRESS, RecipientType.TO); emailNormal.setText("We should meet up!"); emailNormal.setTextHTML("<b>We should meet up!</b><img src='cid:thumbsup'>"); emailNormal.setSubject("hey"); // add two text files in different ways and a black thumbs up embedded image -> emailNormal.addAttachment("dresscode.txt", new ByteArrayDataSource("Black Tie Optional", "text/plain")); emailNormal.addAttachment("location.txt", "On the moon!".getBytes(Charset.defaultCharset()), "text/plain"); String base64String = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABeElEQVRYw2NgoAAYGxu3GxkZ7TY1NZVloDcAWq4MxH+B+D8Qv3FwcOCgtwM6oJaDMTAUXOhmuYqKCjvQ0pdoDrCnmwNMTEwakC0H4u8GBgYC9Ap6DSD+iewAoIPm0ctyLqBlp9F8/x+YE4zpYT8T0LL16JYD8U26+B7oyz4sloPwenpYno3DchCeROsUbwa05A8eB3wB4kqgIxOAuArIng7EW4H4EhC/B+JXQLwDaI4ryZaDSjeg5mt4LCcFXyIn1fdSyXJQVt1OtMWGhoai0OD8T0W8GohZifE1PxD/o7LlsPLiFNAKRrwOABWptLAcqc6QGDAHQEOAYaAc8BNotsJAOgAUAosG1AFA/AtUoY3YEFhKMAvS2AE7iC1+WaG1H6gY3gzE36hUFJ8mqzbU1dUVBBqQBzTgIDQRkWo5qCZdpaenJ0Zx1aytrc0DDB0foIG1oAYKqC0IZK8D4n1AfA6IzwPxXpCFoGoZVEUDaRGGUTAKRgEeAAA2eGJC+ETCiAAAAABJRU5ErkJggg=="; emailNormal.addEmbeddedImage("thumbsup", parseBase64Binary(base64String), "image/png"); // let's try producing and then consuming a MimeMessage -> final MimeMessage mimeMessage = Mailer.produceMimeMessage(emailNormal); final Email emailFromMimeMessage = new Email(mimeMessage); // note: the following statements will produce 6 new emails! sendMail(emailNormal); sendMail(emailFromMimeMessage); // should produce the exact same result as emailNormal! }
Example 6
Project: IdentityRegistry File: EmailUtil.java View source code | 6 votes |
public void sendBugReport(BugReport report) throws MailException, MessagingException { MimeMessage message = this.mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(bugReportEmail); helper.setFrom(from); helper.setSubject(report.getSubject()); helper.setText(report.getDescription()); if (report.getAttachments() != null) { for (BugReportAttachment attachment : report.getAttachments()) { // Decode base64 encoded data byte[] data = Base64.getDecoder().decode(attachment.getData()); ByteArrayDataSource dataSource = new ByteArrayDataSource(data, attachment.getMimetype()); helper.addAttachment(attachment.getName(), dataSource); } } this.mailSender.send(message); }
Example 7
Project: Camel File: CxfMtomConsumerPayloadModeTest.java View source code | 6 votes |
@Test public void testConsumer() throws Exception { if (MtomTestHelper.isAwtHeadless(logger, null)) { return; } context.createProducerTemplate().send("cxf:bean:consumerEndpoint", new Processor() { public void process(Exchange exchange) throws Exception { exchange.setPattern(ExchangePattern.InOut); assertEquals("Get a wrong Content-Type header", "application/xop+xml", exchange.getIn().getHeader("Content-Type")); List<Source> elements = new ArrayList<Source>(); elements.add(new DOMSource(StaxUtils.read(new StringReader(getRequestMessage())).getDocumentElement())); CxfPayload<SoapHeader> body = new CxfPayload<SoapHeader>(new ArrayList<SoapHeader>(), elements, null); exchange.getIn().setBody(body); exchange.getIn().addAttachment(MtomTestHelper.REQ_PHOTO_CID, new DataHandler(new ByteArrayDataSource(MtomTestHelper.REQ_PHOTO_DATA, "application/octet-stream"))); exchange.getIn().addAttachment(MtomTestHelper.REQ_IMAGE_CID, new DataHandler(new ByteArrayDataSource(MtomTestHelper.requestJpeg, "image/jpeg"))); } }); }
Example 8
Project: Camel File: CxfMtomDisabledConsumerPayloadModeTest.java View source code | 6 votes |
@SuppressWarnings("unchecked") public void process(Exchange exchange) throws Exception { CxfPayload<SoapHeader> in = exchange.getIn().getBody(CxfPayload.class); // verify request Assert.assertEquals(1, in.getBody().size()); DataHandler dr = exchange.getIn().getAttachment(MtomTestHelper.REQ_PHOTO_CID); Assert.assertEquals("application/octet-stream", dr.getContentType()); MtomTestHelper.assertEquals(MtomTestHelper.REQ_PHOTO_DATA, IOUtils.readBytesFromStream(dr.getInputStream())); dr = exchange.getIn().getAttachment(MtomTestHelper.REQ_IMAGE_CID); Assert.assertEquals("image/jpeg", dr.getContentType()); MtomTestHelper.assertEquals(MtomTestHelper.requestJpeg, IOUtils.readBytesFromStream(dr.getInputStream())); // create response List<Source> elements = new ArrayList<Source>(); elements.add(new DOMSource(StaxUtils.read(new StringReader(MtomTestHelper.MTOM_DISABLED_RESP_MESSAGE)).getDocumentElement())); CxfPayload<SoapHeader> body = new CxfPayload<SoapHeader>(new ArrayList<SoapHeader>(), elements, null); exchange.getOut().setBody(body); exchange.getOut().addAttachment(MtomTestHelper.RESP_PHOTO_CID, new DataHandler(new ByteArrayDataSource(MtomTestHelper.RESP_PHOTO_DATA, "application/octet-stream"))); exchange.getOut().addAttachment(MtomTestHelper.RESP_IMAGE_CID, new DataHandler(new ByteArrayDataSource(MtomTestHelper.responseJpeg, "image/jpeg"))); }
Example 9
Project: Camel File: MailBinding.java View source code | 6 votes |
protected String populateContentOnMimeMessage(MimeMessage part, MailConfiguration configuration, Exchange exchange) throws MessagingException, IOException { String contentType = determineContentType(configuration, exchange); LOG.trace("Using Content-Type {} for MimeMessage: {}", contentType, part); String body = exchange.getIn().getBody(String.class); if (body == null) { body = ""; } // always store content in a byte array data store to avoid various content type and charset issues DataSource ds = new ByteArrayDataSource(body, contentType); part.setDataHandler(new DataHandler(ds)); // set the content type header afterwards part.setHeader("Content-Type", contentType); return contentType; }
Example 10
Project: Camel File: MimeMultipartDataFormatTest.java View source code | 6 votes |
@Test public void roundtripWithBinaryAttachments() throws IOException { String attContentType = "application/binary"; byte[] attText = {0, 1, 2, 3, 4, 5, 6, 7}; String attFileName = "Attachment File Name"; in.setBody("Body text"); DataSource ds = new ByteArrayDataSource(attText, attContentType); in.addAttachment(attFileName, new DataHandler(ds)); Exchange result = template.send("direct:roundtrip", exchange); Message out = result.getOut(); assertEquals("Body text", out.getBody(String.class)); assertTrue(out.hasAttachments()); assertEquals(1, out.getAttachmentNames().size()); assertThat(out.getAttachmentNames(), hasItem(attFileName)); DataHandler dh = out.getAttachment(attFileName); assertNotNull(dh); assertEquals(attContentType, dh.getContentType()); InputStream is = dh.getInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); IOHelper.copyAndCloseInput(is, os); assertArrayEquals(attText, os.toByteArray()); }
Example 11
Project: Camel File: MimeMultipartDataFormatTest.java View source code | 6 votes |
@Test public void roundtripWithBinaryAttachmentsAndBinaryContent() throws IOException { String attContentType = "application/binary"; byte[] attText = {0, 1, 2, 3, 4, 5, 6, 7}; String attFileName = "Attachment File Name"; in.setBody("Body text"); DataSource ds = new ByteArrayDataSource(attText, attContentType); in.addAttachment(attFileName, new DataHandler(ds)); Exchange result = template.send("direct:roundtripbinarycontent", exchange); Message out = result.getOut(); assertEquals("Body text", out.getBody(String.class)); assertTrue(out.hasAttachments()); assertEquals(1, out.getAttachmentNames().size()); assertThat(out.getAttachmentNames(), hasItem(attFileName)); DataHandler dh = out.getAttachment(attFileName); assertNotNull(dh); assertEquals(attContentType, dh.getContentType()); InputStream is = dh.getInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); IOHelper.copyAndCloseInput(is, os); assertArrayEquals(attText, os.toByteArray()); }
Example 12
Project: openxds File: XdsTest.java View source code | 6 votes |
protected OMElement addOneDocument(OMElement request, String document, String documentId) throws IOException { OMFactory fac = OMAbstractFactory.getOMFactory(); OMNamespace ns = fac.createOMNamespace("urn:ihe:iti:xds-b:2007" , null); OMElement docElem = fac.createOMElement("Document", ns); docElem.addAttribute("id", documentId, null); // A string, turn it into an StreamSource DataSource ds = new ByteArrayDataSource(document, "text/xml"); DataHandler handler = new DataHandler(ds); OMText binaryData = fac.createOMText(handler, true); docElem.addChild(binaryData); Iterator iter = request.getChildrenWithLocalName("SubmitObjectsRequest"); OMElement submitObjectsRequest = null; for (;iter.hasNext();) { submitObjectsRequest = (OMElement)iter.next(); if (submitObjectsRequest != null) break; } submitObjectsRequest.insertSiblingAfter(docElem); return request; }
Example 13
Project: simple-java-mail File: EmailPopulatingBuilderUsingDefaultsFromPropertyFileTest.java View source code | 6 votes |
@Test public void testBuilderSimpleBuildWithStandardEmail() throws IOException { ByteArrayDataSource namedAttachment = new ByteArrayDataSource("Black Tie Optional", "text/plain"); namedAttachment.setName("dresscode.txt"); // normally not needed, but otherwise the equals will fail String base64String = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABeElEQVRYw2NgoAAYGxu3GxkZ7TY1NZVloDcAWq4MxH+B+D8Qv3FwcOCgtwM6oJaDMTAUXOhmuYqKCjvQ0pdoDrCnmwNMTEwakC0H4u8GBgYC9Ap6DSD+iewAoIPm0ctyLqBlp9F8/x+YE4zpYT8T0LL16JYD8U26+B7oyz4sloPwenpYno3DchCeROsUbwa05A8eB3wB4kqgIxOAuArIng7EW4H4EhC/B+JXQLwDaI4ryZaDSjeg5mt4LCcFXyIn1fdSyXJQVt1OtMWGhoai0OD8T0W8GohZifE1PxD/o7LlsPLiFNAKRrwOABWptLAcqc6QGDAHQEOAYaAc8BNotsJAOgAUAosG1AFA/AtUoY3YEFhKMAvS2AE7iC1+WaG1H6gY3gzE36hUFJ8mqzbU1dUVBBqQBzTgIDQRkWo5qCZdpaenJ0Zx1aytrc0DDB0foIG1oAYKqC0IZK8D4n1AfA6IzwPxXpCFoGoZVEUDaRGGUTAKRgEeAAA2eGJC+ETCiAAAAABJRU5ErkJggg=="; final Email email = EmailBuilder.startingBlank() .from("lollypop", "[email protected]") .to("C.Cane", "[email protected]") .withPlainText("We should meet up!") .withHTMLText("<b>We should meet up!</b><img src='cid:thumbsup'>") .withSubject("hey") .withAttachment("dresscode.txt", namedAttachment) .withAttachment("location.txt", "On the moon!".getBytes(Charset.defaultCharset()), "text/plain") .withEmbeddedImage("thumbsup", parseBase64Binary(base64String), "image/png") .buildEmail(); assertThat(EmailHelper.createDummyEmailBuilder(true, true, false).buildEmail()).isEqualTo(email); }
Example 14
Project: simple-java-mail File: EmailPopulatingBuilderUsingDefaultsFromPropertyFileTest.java View source code | 6 votes |
@Test public void testBuilderSimpleBuildWithStandardEmail_PlusOptionals() throws IOException { ByteArrayDataSource namedAttachment = new ByteArrayDataSource("Black Tie Optional", "text/plain"); namedAttachment.setName("dresscode.txt"); // normally not needed, but otherwise the equals will fail String base64String = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABeElEQVRYw2NgoAAYGxu3GxkZ7TY1NZVloDcAWq4MxH+B+D8Qv3FwcOCgtwM6oJaDMTAUXOhmuYqKCjvQ0pdoDrCnmwNMTEwakC0H4u8GBgYC9Ap6DSD+iewAoIPm0ctyLqBlp9F8/x+YE4zpYT8T0LL16JYD8U26+B7oyz4sloPwenpYno3DchCeROsUbwa05A8eB3wB4kqgIxOAuArIng7EW4H4EhC/B+JXQLwDaI4ryZaDSjeg5mt4LCcFXyIn1fdSyXJQVt1OtMWGhoai0OD8T0W8GohZifE1PxD/o7LlsPLiFNAKRrwOABWptLAcqc6QGDAHQEOAYaAc8BNotsJAOgAUAosG1AFA/AtUoY3YEFhKMAvS2AE7iC1+WaG1H6gY3gzE36hUFJ8mqzbU1dUVBBqQBzTgIDQRkWo5qCZdpaenJ0Zx1aytrc0DDB0foIG1oAYKqC0IZK8D4n1AfA6IzwPxXpCFoGoZVEUDaRGGUTAKRgEeAAA2eGJC+ETCiAAAAABJRU5ErkJggg=="; final Email email = EmailBuilder.startingBlank() .from("lollypop", "[email protected]") .withReplyTo("lollypop-reply", "[email protected]") .withBounceTo("lollypop-bounce", "[email protected]") .to("C.Cane", "[email protected]") .withPlainText("We should meet up!") .withHTMLText("<b>We should meet up!</b><img src='cid:thumbsup'>") .withSubject("hey") .withAttachment("dresscode.txt", namedAttachment) .withAttachment("location.txt", "On the moon!".getBytes(Charset.defaultCharset()), "text/plain") .withEmbeddedImage("thumbsup", parseBase64Binary(base64String), "image/png") .withDispositionNotificationTo("[email protected]") .withReturnReceiptTo("Complex Email", "[email protected]") .withHeader("dummyHeader", "dummyHeaderValue") .buildEmail(); assertThat(EmailHelper.createDummyEmailBuilder(true, false, true).buildEmail()).isEqualTo(email); }
Example 15
Project: openmeetings File: MailHandler.java View source code | 6 votes |
protected MimeMessage appendIcsBody(MimeMessage msg, MailMessage m) throws Exception { log.debug("setMessageBody for iCal message"); // -- Create a new message -- Multipart multipart = new MimeMultipart(); Multipart multiBody = new MimeMultipart("alternative"); BodyPart html = new MimeBodyPart(); html.setDataHandler(new DataHandler(new ByteArrayDataSource(m.getBody(), "text/html; charset=UTF-8"))); multiBody.addBodyPart(html); BodyPart iCalContent = new MimeBodyPart(); iCalContent.addHeader("content-class", "urn:content-classes:calendarmessage"); iCalContent.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(m.getIcs()), "text/calendar; charset=UTF-8; method=REQUEST"))); multiBody.addBodyPart(iCalContent); BodyPart body = new MimeBodyPart(); body.setContent(multiBody); multipart.addBodyPart(body); BodyPart iCalAttachment = new MimeBodyPart(); iCalAttachment.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(m.getIcs()), "application/ics"))); iCalAttachment.removeHeader("Content-Transfer-Encoding"); iCalAttachment.addHeader("Content-Transfer-Encoding", "base64"); iCalAttachment.removeHeader("Content-Type"); iCalAttachment.addHeader("Content-Type", "application/ics"); iCalAttachment.setFileName("invite.ics"); multipart.addBodyPart(iCalAttachment); msg.setContent(multipart); return msg; }
Example 16
Project: muleebmsadapter File: AbstractEbMSDAO.java View source code | 6 votes |
private List<DataSource> getAttachments(long messageId) throws DAOException { try { return simpleJdbcTemplate.query( "select name, content_type, content" + " from ebms_attachment" + " where ebms_message_id = ?", new ParameterizedRowMapper<DataSource>() { @Override public DataSource mapRow(ResultSet rs, int rowNum) throws SQLException { ByteArrayDataSource result = new ByteArrayDataSource(rs.getBytes("content"),rs.getString("content_type")); result.setName(rs.getString("name")); return result; } }, messageId ); } catch (DataAccessException e) { throw new DAOException(e); } }
Example 17
Project: muleebmsadapter File: EbMSMessageUtils.java View source code | 6 votes |
public static EbMSMessage ebMSMessageContentToEbMSMessage(CollaborationProtocolAgreement cpa, EbMSMessageContent content, String hostname) throws DatatypeConfigurationException { MessageHeader messageHeader = createMessageHeader(cpa,content.getContext(),hostname); AckRequested ackRequested = createAckRequested(cpa,content.getContext()); Manifest manifest = createManifest(); for (int i = 0; i < content.getAttachments().size(); i++) manifest.getReference().add(createReference(i + 1)); List<DataSource> attachments = new ArrayList<DataSource>(); for (EbMSAttachment attachment : content.getAttachments()) { ByteArrayDataSource ds = new ByteArrayDataSource(attachment.getContent(),attachment.getContentType()); ds.setName(attachment.getName()); attachments.add(ds); } return new EbMSMessage(messageHeader,ackRequested,manifest,attachments); }
Example 18
Project: Tournament File: SmtpMailService.java View source code | 6 votes |
/** * Add file attachments to multi part document * * @param multipart * @param attachments * @throws MessagingException */ private static void addFileAttachments(MimeMultipart multipart, List<MailAttachmentPO> attachments) throws MessagingException { for (MailAttachmentPO attachment : attachments) { if (null == attachment.getCid() || attachment.getCid().isEmpty()) { DataSource byteDataSource = new ByteArrayDataSource(attachment.getContent(), attachment.getMimeType()); DataHandler attachementDataHandler = new DataHandler(byteDataSource); BodyPart memoryBodyPart = new MimeBodyPart(); memoryBodyPart.setDataHandler(attachementDataHandler); memoryBodyPart.setFileName(attachment.getName()); // Add part to multi-part multipart.addBodyPart(memoryBodyPart); } } }
Example 19
Project: blynk-server File: GMailClient.java View source code | 6 votes |
private void attachCSV(Multipart multipart, QrHolder[] attachmentData) throws Exception { StringBuilder sb = new StringBuilder(); for (QrHolder qrHolder : attachmentData) { sb.append(qrHolder.token) .append(",") .append(qrHolder.deviceId) .append(",") .append(qrHolder.dashId) .append("\n"); } MimeBodyPart attachmentsPart = new MimeBodyPart(); ByteArrayDataSource source = new ByteArrayDataSource(sb.toString(), "text/csv"); attachmentsPart.setDataHandler(new DataHandler(source)); attachmentsPart.setFileName("tokens.csv"); multipart.addBodyPart(attachmentsPart); }
Example 20
Project: Lapwing File: ITSProcessorImpl.java View source code | 6 votes |
@Override public SOAPResponse check(SOAPRequest input) throws ServerException { Pipeline pipeline = new Pipeline(); byte[] annotatedFile; try { Input ltinput = new Input(); ltinput.setData(input.getData().getInputStream()); ltinput.setEncoding(input.getEncoding()); ltinput.setSrcLocale(input.getSource()); ltinput.setTgtLocale(input.getTarget()); Output output = pipeline.check(ltinput); SOAPResponse response = new SOAPResponse(); annotatedFile = IOUtils.readBytesFromStream(output.getData()); DataSource responseFile = new ByteArrayDataSource(annotatedFile, ITSProcessorImpl.OUTPUT_MIME_TYPE); DataHandler handler = new DataHandler(responseFile); response.setData(handler); response.setEncoding(output.getEncoding()); return response; } catch (Exception e) { throw new ServerException(e); } }
Example 21
Project: openhim-mediator-xds File: XDSbMimeProcessorActor.java View source code | 6 votes |
private void parseMimeMessage(String msg, String contentType) throws IOException, MessagingException, SOAPPartNotFound, UnprocessableContentFound { mimeMessage = new MimeMultipart(new ByteArrayDataSource(msg, contentType)); for (int i=0; i<mimeMessage.getCount(); i++) { BodyPart part = mimeMessage.getBodyPart(i); if (part.getContentType().contains("application/soap+xml")) { _soapPart = getValue(part); } else { _documents.add(getValue(part)); } } if (_soapPart==null) { throw new SOAPPartNotFound(); } }
Example 22
Project: xltestview-plugin File: XLTestServerImplTest.java View source code | 6 votes |
private void verifyUploadRequest(final RecordedRequest request) throws IOException, MessagingException { assertEquals(request.getRequestLine(), "POST /api/internal/import/testspecid HTTP/1.1"); assertEquals(request.getHeader("accept"), "application/json; charset=utf-8"); assertEquals(request.getHeader("authorization"), "Basic YWRtaW46YWRtaW4="); assertThat(request.getHeader("Content-Length"), is(nullValue())); assertThat(request.getHeader("Transfer-Encoding"), is("chunked")); assertThat(request.getChunkSizes().get(0), greaterThan(0)); assertThat(request.getChunkSizes().size(), greaterThan(0)); assertTrue(request.getBodySize() > 0); ByteArrayDataSource bads = new ByteArrayDataSource(request.getBody().inputStream(), "multipart/mixed"); MimeMultipart mp = new MimeMultipart(bads); assertTrue(request.getBodySize() > 0); assertEquals(mp.getCount(), 2); assertEquals(mp.getContentType(), "multipart/mixed"); // TODO could do additional checks on metadata content BodyPart bodyPart1 = mp.getBodyPart(0); assertEquals(bodyPart1.getContentType(), "application/json; charset=utf-8"); BodyPart bodyPart2 = mp.getBodyPart(1); assertEquals(bodyPart2.getContentType(), "application/zip"); }
Example 23
Project: wso2-axis2 File: SOAPMessageFormatterTest.java View source code | 6 votes |
public void testMM7() throws Exception { SOAPMessageFormatter formatter = new SOAPMessageFormatter(); MessageContext mc = new MessageContext(); SOAPFactory factory = OMAbstractFactory.getSOAP11Factory(); mc.setEnvelope(factory.getDefaultEnvelope()); mc.setDoingSwA(true); Attachments attachments = mc.getAttachmentMap(); attachments.addDataHandler("[email protected]", new DataHandler("test1", "text/plain")); attachments.addDataHandler("[email protected]", new DataHandler("test2", "text/plain")); mc.setProperty(Constants.Configuration.MM7_COMPATIBLE, true); OMOutputFormat format = new OMOutputFormat(); format.setDoingSWA(true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); formatter.writeTo(mc, format, baos, true); MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), format.getContentType())); assertEquals(2, mp.getCount()); BodyPart bp = mp.getBodyPart(0); assertEquals("<" + format.getRootContentId() + ">", bp.getHeader("Content-ID")[0]); bp = mp.getBodyPart(1); Object content = bp.getContent(); assertTrue(content instanceof MimeMultipart); MimeMultipart inner = (MimeMultipart)content; assertEquals(2, inner.getCount()); bp = inner.getBodyPart(0); assertEquals("<[email protected]>", bp.getHeader("Content-ID")[0]); assertEquals("test1", bp.getContent()); bp = inner.getBodyPart(1); assertEquals("<[email protected]>", bp.getHeader("Content-ID")[0]); assertEquals("test2", bp.getContent()); }
Example 24
Project: cleverbus File: EmailServiceCamelSmtpImpl.java View source code | 6 votes |
@Override public void sendEmail(final Email email) { Assert.notNull(email, "email can not be null"); Assert.notEmpty(email.getRecipients(), "email must have at least one recipients"); Assert.hasText(email.getSubject(), "subject in email can not be empty"); Assert.hasText(email.getBody(), "body in email can not be empty"); producerTemplate.send("smtp://" + smtp, new Processor() { @Override public void process(final Exchange exchange) throws Exception { Message in = exchange.getIn(); in.setHeader("To", StringUtils.join(email.getRecipients(), ",")); in.setHeader("From", StringUtils.isBlank(email.getFrom()) ? from : email.getFrom()); in.setHeader("Subject", email.getSubject()); in.setHeader("contentType", email.getContentType().getContentType()); in.setBody(email.getBody()); if (email.getAllAtachments() != null && !email.getAllAtachments().isEmpty()) { for (EmailAttachment attachment : email.getAllAtachments()) { in.addAttachment(attachment.getFileName(), new DataHandler(new ByteArrayDataSource( attachment.getContent(), "*/*"))); } } } }); }
Example 25
Project: elasticsearch-imap File: AttachmentMapperTest.java View source code | 6 votes |
@Test public void testAttachments() throws Exception{ Map<String, Object> settings = settings("/river-imap-attachments.json"); final Properties props = new Properties(); final String user = XContentMapValues.nodeStringValue(settings.get("user"), null); final String password = XContentMapValues.nodeStringValue(settings.get("password"), null); for (final Map.Entry<String, Object> entry : settings.entrySet()) { if (entry != null && entry.getKey().startsWith("mail.")) { props.setProperty(entry.getKey(), String.valueOf(entry.getValue())); } } registerRiver("imap_river", "river-imap-attachments.json"); final Session session = Session.getInstance(props); final Store store = session.getStore(); store.connect(user, password); checkStoreForTestConnection(store); final Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); final MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(EMAIL_TO)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS)); message.setSubject(EMAIL_SUBJECT + "::attachment test"); message.setSentDate(new Date()); BodyPart bp = new MimeBodyPart(); bp.setText("Text"); Multipart mp = new MimeMultipart(); mp.addBodyPart(bp); bp = new MimeBodyPart(); DataSource ds = new ByteArrayDataSource(this.getClass().getResourceAsStream("/httpclient-tutorial.pdf"), AttachmentMapperTest.APPLICATION_PDF); bp.setDataHandler(new DataHandler(ds)); bp.setFileName("httpclient-tutorial.pdf"); mp.addBodyPart(bp); message.setContent(mp); inbox.appendMessages(new Message[]{message}); IMAPUtils.close(inbox); IMAPUtils.close(store); //let the river index Thread.sleep(20*1000); esSetup.client().admin().indices().refresh(new RefreshRequest()).actionGet(); SearchResponse searchResponse = esSetup.client().prepareSearch("imapriverdata").setTypes("mail").execute().actionGet(); Assert.assertEquals(1, searchResponse.getHits().totalHits()); //BASE64 content httpclient-tutorial.pdf Assert.assertTrue(searchResponse.getHits().hits()[0].getSourceAsString().contains(AttachmentMapperTest.PDF_BASE64_DETECTION)); searchResponse = esSetup.client().prepareSearch("imapriverdata").addFields("*").setTypes("mail").setQuery(QueryBuilders.matchPhraseQuery("attachments.content.content", PDF_CONTENT_TO_SEARCH)).execute().actionGet(); Assert.assertEquals(1, searchResponse.getHits().totalHits()); Assert.assertEquals(1, searchResponse.getHits().hits()[0].field("attachments.content.content").getValues().size()); Assert.assertEquals("HttpClient Tutorial", searchResponse.getHits().hits()[0].field("attachments.content.title").getValue().toString()); Assert.assertEquals("application/pdf", searchResponse.getHits().hits()[0].field("attachments.content.content_type").getValue().toString()); Assert.assertTrue(searchResponse.getHits().hits()[0].field("attachments.content.content").getValue().toString().contains(PDF_CONTENT_TO_SEARCH)); }
Example 26
Project: camel-agent File: MailBinding.java View source code | 6 votes |
protected String populateContentOnMimeMessage(MimeMessage part, MailConfiguration configuration, Exchange exchange) throws MessagingException, IOException { String contentType = determineContentType(configuration, exchange); LOG.trace("Using Content-Type {} for MimeMessage: {}", contentType, part); String body = exchange.getIn().getBody(String.class); if (body == null) { body = ""; } // always store content in a byte array data store to avoid various content type and charset issues DataSource ds = new ByteArrayDataSource(body, contentType); part.setDataHandler(new DataHandler(ds)); // set the content type header afterwards part.setHeader("Content-Type", contentType); return contentType; }
Example 27
Project: camel-agent File: MailBinding.java View source code | 6 votes |
protected String populateContentOnBodyPart(BodyPart part, MailConfiguration configuration, Exchange exchange) throws MessagingException, IOException { String contentType = determineContentType(configuration, exchange); if (contentType != null) { LOG.trace("Using Content-Type {} for BodyPart: {}", contentType, part); // always store content in a byte array data store to avoid various content type and charset issues String data = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange.getIn().getBody()); // use empty data if the body was null for some reason (otherwise there is a NPE) data = data != null ? data : ""; DataSource ds = new ByteArrayDataSource(data, contentType); part.setDataHandler(new DataHandler(ds)); // set the content type header afterwards part.setHeader("Content-Type", contentType); } return contentType; }
Example 28
Project: PortlandStateJava File: Survey.java View source code | 6 votes |
private static MimeBodyPart createXmlAttachment(Student student) { byte[] xmlBytes = getXmlBytes(student); if (saveStudentXmlFile) { writeStudentXmlToFile(xmlBytes, student); } DataSource ds = new ByteArrayDataSource(xmlBytes, "text/xml"); DataHandler dh = new DataHandler(ds); MimeBodyPart filePart = new MimeBodyPart(); try { String xmlFileTitle = student.getId() + ".xml"; filePart.setDataHandler(dh); filePart.setFileName(xmlFileTitle); filePart.setDescription("XML file for " + student.getFullName()); } catch (MessagingException ex) { printErrorMessageAndExit("** Exception with file part", ex); } return filePart; }
Example 29
Project: extemporal File: EmailTestPlatform.java View source code | 6 votes |
protected boolean transmitEmail(String to, ByteBuffer msgContent, Message emailSkeleton) { try { if (emailSkeleton == null) { emailSkeleton = new MimeMessage(mSession); emailSkeleton.setFrom(new InternetAddress(mEndpoint)); emailSkeleton.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); } byte[] mc = new byte[msgContent.remaining()]; msgContent.get(mc); ByteArrayDataSource dSrc = new ByteArrayDataSource(mc, "application/octet-stream"); emailSkeleton.setDataHandler(new DataHandler(dSrc)); final Transport channel = mSession.getTransport(mSmtpAccountURN); channel.connect(); // throws if can't connect channel.sendMessage(emailSkeleton, emailSkeleton.getRecipients(Message.RecipientType.TO)); channel.close(); } catch (MessagingException e) { e.printStackTrace(); return false; } return true; }
Example 30
Project: dropwizard-jaxws File: JAXWSEnvironmentTest.java View source code | 6 votes |
@Test public void publishEndpointWithMtom() throws Exception { jaxwsEnvironment.publishEndpoint( new EndpointBuilder("local://path", service) .enableMtom()); verify(mockInvokerBuilder).create(any(), any(Invoker.class)); byte[] response = testutils.invokeBytes("local://path", LocalTransportFactory.TRANSPORT_ID, soapRequest.getBytes()); verify(mockInvoker).invoke(any(Exchange.class), any()); MimeMultipart mimeMultipart = new MimeMultipart(new ByteArrayDataSource(response, "application/xop+xml; charset=UTF-8; type=\"text/xml\"")); assertThat(mimeMultipart.getCount(), equalTo(1)); testutils.assertValid("/soap:Envelope/soap:Body/a:fooResponse", StaxUtils.read(mimeMultipart.getBodyPart(0).getInputStream())); }
Example 31
Project: dropwizard-jaxws File: AccessMtomServiceResource.java View source code | 6 votes |
@GET @Timed public String getFoo() { ObjectFactory of = new ObjectFactory(); Hello h = of.createHello(); h.setTitle("Hello"); h.setBinary(new DataHandler(new ByteArrayDataSource("test".getBytes(), "text/plain"))); HelloResponse hr = mtomServiceClient.hello(h); try { return "Hello response: " + hr.getTitle() + ", " + IOUtils.readStringFromStream(hr.getBinary().getInputStream()); } catch (IOException e) { throw new RuntimeException(e); } }
Example 32
Project: jersey-smime File: SignedTest.java View source code | 6 votes |
@Test public void testOutput2() throws Exception { SMIMESignedGenerator gen = new SMIMESignedGenerator(); SignerInfoGenerator signer = new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").build("SHA1WITHRSA", privateKey, cert); gen.addSignerInfoGenerator(signer); MimeMultipart mp = gen.generate(createMsg()); ByteArrayOutputStream os = new ByteArrayOutputStream(); mp.writeTo(os); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); String contentType = mp.getContentType(); contentType = contentType.replace("\r\n", "").replace("\t", " "); ByteArrayDataSource ds = new ByteArrayDataSource(is, contentType); MimeMultipart mm = new MimeMultipart(ds); MimeBodyPart part = (MimeBodyPart) mm.getBodyPart(0); }
Example 33
Project: logistimo-web-service File: EmailService.java View source code | 5 votes |
private void addAttachment(Multipart mp, byte[] attachmentData, String mimeType, String filename) throws MessagingException { if (mp == null) { return; } ByteArrayDataSource dataSrc = new ByteArrayDataSource(attachmentData, mimeType); MimeBodyPart attachment = new MimeBodyPart(); attachment.setFileName(filename); attachment.setDataHandler(new DataHandler(dataSrc)); ///attachment.setContent( attachmentData, mimeType ); mp.addBodyPart(attachment); }
Example 34
Project: logistimo-web-service File: EmailService.java View source code | 5 votes |
private void addAttachmentStream(Multipart mp, InputStream attachmentStream, String mimeType, String filename, BodyPart message) throws MessagingException, IOException { if (mp == null) { return; } ByteArrayDataSource dataSrc = new ByteArrayDataSource(attachmentStream, mimeType); MimeBodyPart attachment = new MimeBodyPart(); attachment.setFileName(filename); attachment.setDataHandler(new DataHandler(dataSrc)); ///attachment.setContent( attachmentData, mimeType ); mp.addBodyPart(message); mp.addBodyPart(attachment); }
Example 35
Project: chronos File: CallableQuery.java View source code | 5 votes |
@CoverageIgnore private static DataSource createAttachment(PersistentResultSet results) { try { String text = makeAttachmentText(results); DataSource source = new ByteArrayDataSource(text, TSV); return source; } catch (IOException e) { throw new RuntimeException(e); } }
Example 36
Project: openex-worker File: EmailAttacher.java View source code | 5 votes |
@SuppressWarnings({"unused", "unchecked"}) public void process(Exchange exchange) { List<EmailAttachment> filesContent = (List) exchange.getProperty(ATTACHMENTS_CONTENT, new ArrayList<>()); for (EmailAttachment attachment : filesContent) { ByteArrayDataSource bds = new ByteArrayDataSource(attachment.getData(), attachment.getContentType()); exchange.getIn().addAttachmentObject(attachment.getName(), new DefaultAttachment(bds)); } }
Example 37
Project: SoapUI-Cookbook File: InvoicePortImpl.java View source code | 5 votes |
public void getInvoice(javax.xml.ws.Holder<java.lang.String> invoiceNo, javax.xml.ws.Holder<java.lang.String> company, javax.xml.ws.Holder<java.lang.Double> amount, javax.xml.ws.Holder<javax.activation.DataHandler> file) { LOG.info("Executing operation getInvoice"); System.out.println("Invoice no: "+invoiceNo.value); try { company.value = "company"; System.out.println("Company: "+company.value); amount.value = 100d; System.out.println("Amount: "+amount); String attachmentFileName = "/temp/invoice1.pdf"; System.out.println("Attachment: "+attachmentFileName); File attachment = new File(attachmentFileName); InputStream attachmentInputStream = new FileInputStream(attachment); ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream(); copyInputStreamToOutputStream(attachmentInputStream, responseOutputStream); System.out.println("Attachment size: " + responseOutputStream.size()); attachmentInputStream.close(); file.value = new DataHandler(new ByteArrayDataSource( responseOutputStream.toByteArray(), "application/pdf")); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } }
Example 38
Project: qianworks-meican File: MimeMessageParser.java View source code | 5 votes |
/** * Parses the MimePart to create a DataSource. * * @param part the current part to be processed * @return the DataSource * @throws MessagingException creating the DataSource failed * @throws IOException creating the DataSource failed */ private static DataSource createDataSource(final MimePart part) throws MessagingException, IOException { final DataHandler dataHandler = part.getDataHandler(); final DataSource dataSource = dataHandler.getDataSource(); final String contentType = getBaseMimeType(dataSource.getContentType()); final byte[] content = MimeMessageParser.getContent(dataSource.getInputStream()); final ByteArrayDataSource result = new ByteArrayDataSource(content, contentType); final String dataSourceName = getDataSourceName(part, dataSource); result.setName(dataSourceName); return result; }
Example 39
Project: Camel File: MimeMultipartDataFormat.java View source code | 5 votes |
private void writeBodyPart(byte[] bodyContent, Part part, ContentType contentType) throws MessagingException { DataSource ds = new ByteArrayDataSource(bodyContent, contentType.toString()); part.setDataHandler(new DataHandler(ds)); part.setHeader(CONTENT_TYPE, contentType.toString()); if (contentType.match("text/*")) { part.setHeader(CONTENT_TRANSFER_ENCODING, "8bit"); } else if (binaryContent) { part.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); } else { part.setHeader(CONTENT_TRANSFER_ENCODING, "base64"); } }
Example 40
Project: metaworks_framework File: MessageCreator.java View source code | 5 votes |
public MimeMessagePreparator buildMimeMessagePreparator(final Map<String, Object> props) { MimeMessagePreparator preparator = new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { EmailTarget emailUser = (EmailTarget) props.get(EmailPropertyType.USER.getType()); EmailInfo info = (EmailInfo) props.get(EmailPropertyType.INFO.getType()); boolean isMultipart = CollectionUtils.isNotEmpty(info.getAttachments()); MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, info.getEncoding()); message.setTo(emailUser.getEmailAddress()); message.setFrom(info.getFromAddress()); message.setSubject(info.getSubject()); if (emailUser.getBCCAddresses() != null && emailUser.getBCCAddresses().length > 0) { message.setBcc(emailUser.getBCCAddresses()); } if (emailUser.getCCAddresses() != null && emailUser.getCCAddresses().length > 0) { message.setCc(emailUser.getCCAddresses()); } String messageBody = info.getMessageBody(); if (messageBody == null) { messageBody = buildMessageBody(info, props); } message.setText(messageBody, true); for (Attachment attachment : info.getAttachments()) { ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment.getData(), attachment.getMimeType()); message.addAttachment(attachment.getFilename(), dataSource); } } }; return preparator; }