Search in sources :

Example 31 with FileDataSource

use of javax.activation.FileDataSource in project gitblit by gitblit.

the class MailService method createMessage.

/**
	 * Create a message.
	 *
	 * @param mailing
	 * @return a message
	 */
public Message createMessage(Mailing mailing) {
    if (mailing.subject == null) {
        mailing.subject = "";
    }
    if (mailing.content == null) {
        mailing.content = "";
    }
    Message message = new MailMessageImpl(session, mailing.id);
    try {
        String fromAddress = settings.getString(Keys.mail.fromAddress, null);
        if (StringUtils.isEmpty(fromAddress)) {
            fromAddress = "gitblit@gitblit.com";
        }
        InternetAddress from = new InternetAddress(fromAddress, mailing.from == null ? "Gitblit" : mailing.from);
        message.setFrom(from);
        Pattern validEmail = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
        // validate & add TO recipients
        List<InternetAddress> to = new ArrayList<InternetAddress>();
        for (String address : mailing.toAddresses) {
            if (StringUtils.isEmpty(address)) {
                continue;
            }
            if (validEmail.matcher(address).find()) {
                try {
                    to.add(new InternetAddress(address));
                } catch (Throwable t) {
                }
            }
        }
        // validate & add CC recipients
        List<InternetAddress> cc = new ArrayList<InternetAddress>();
        for (String address : mailing.ccAddresses) {
            if (StringUtils.isEmpty(address)) {
                continue;
            }
            if (validEmail.matcher(address).find()) {
                try {
                    cc.add(new InternetAddress(address));
                } catch (Throwable t) {
                }
            }
        }
        if (settings.getBoolean(Keys.web.showEmailAddresses, true)) {
            // full disclosure of recipients
            if (to.size() > 0) {
                message.setRecipients(Message.RecipientType.TO, to.toArray(new InternetAddress[to.size()]));
            }
            if (cc.size() > 0) {
                message.setRecipients(Message.RecipientType.CC, cc.toArray(new InternetAddress[cc.size()]));
            }
        } else {
            // everyone is bcc'd
            List<InternetAddress> bcc = new ArrayList<InternetAddress>();
            bcc.addAll(to);
            bcc.addAll(cc);
            message.setRecipients(Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()]));
        }
        message.setSentDate(new Date());
        // UTF-8 encode
        message.setSubject(MimeUtility.encodeText(mailing.subject, "utf-8", "B"));
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setText(mailing.content, "utf-8");
        if (Mailing.Type.html == mailing.type) {
            messagePart.setHeader("Content-Type", "text/html; charset=\"utf-8\"");
        } else {
            messagePart.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
        }
        MimeMultipart multiPart = new MimeMultipart();
        multiPart.addBodyPart(messagePart);
        // handle attachments
        if (mailing.hasAttachments()) {
            for (File file : mailing.attachments) {
                if (file.exists()) {
                    MimeBodyPart filePart = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(file);
                    filePart.setDataHandler(new DataHandler(fds));
                    filePart.setFileName(fds.getName());
                    multiPart.addBodyPart(filePart);
                }
            }
        }
        message.setContent(multiPart);
    } catch (Exception e) {
        logger.error("Failed to properly create message", e);
    }
    return message;
}
Also used : Pattern(java.util.regex.Pattern) InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) ArrayList(java.util.ArrayList) DataHandler(javax.activation.DataHandler) Date(java.util.Date) MessagingException(javax.mail.MessagingException) SendFailedException(javax.mail.SendFailedException) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File)

Example 32 with FileDataSource

use of javax.activation.FileDataSource in project powermock by powermock.

the class PrivateInstanceMockingTest method usingMultipleArgumentsOnPrivateMethodWorks.

@Test
public void usingMultipleArgumentsOnPrivateMethodWorks() throws Exception {
    File file = mock(File.class);
    FileDataSource fileDataSource = mock(FileDataSource.class);
    StringReader expected = new StringReader("Some string");
    PrivateMethodDemo tested = mock(PrivateMethodDemo.class);
    doReturn(expected).when(tested, method(PrivateMethodDemo.class, "createReader", File.class, FileDataSource.class)).withArguments(file, fileDataSource);
    StringReader actual = Whitebox.invokeMethod(tested, "createReader", file, fileDataSource);
    assertSame(expected, actual);
}
Also used : PrivateMethodDemo(samples.privatemocking.PrivateMethodDemo) FileDataSource(javax.activation.FileDataSource) StringReader(java.io.StringReader) File(java.io.File) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 33 with FileDataSource

use of javax.activation.FileDataSource in project ats-framework by Axway.

the class MimePackage method addAttachmentDir.

/**
     * Appends all files in a specified folder as attachments
     *
     * @param folder the folder containing all files to be attached
     * @throws PackageException
     */
@PublicAtsApi
public void addAttachmentDir(String folder) throws PackageException {
    // fetch list of files in specified directory
    File dir = new File(folder);
    File[] list = dir.listFiles();
    if (null == list) {
        throw new PackageException("Could not read from directory '" + folder + "'.");
    } else {
        // process all files, skipping directories
        for (int i = 0; i < list.length; i++) {
            if ((null != list[i]) && (!list[i].isDirectory())) {
                // add attachment to multipart content
                MimeBodyPart attPart = new MimeBodyPart();
                FileDataSource ds = new FileDataSource(list[i].getPath());
                try {
                    attPart.setDataHandler(new DataHandler(ds));
                    attPart.setDisposition(MimeBodyPart.ATTACHMENT);
                    attPart.setFileName(ds.getName());
                } catch (MessagingException me) {
                    throw new PackageException(me);
                }
                addPart(attPart, PART_POSITION_LAST);
            }
        }
    }
}
Also used : MessagingException(javax.mail.MessagingException) FileDataSource(javax.activation.FileDataSource) NoSuchMimePackageException(com.axway.ats.action.objects.model.NoSuchMimePackageException) PackageException(com.axway.ats.action.objects.model.PackageException) DataHandler(javax.activation.DataHandler) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File) PublicAtsApi(com.axway.ats.common.PublicAtsApi)

Example 34 with FileDataSource

use of javax.activation.FileDataSource in project spring-framework by spring-projects.

the class Jaxb2UnmarshallerTests method marshalAttachments.

@Test
public void marshalAttachments() throws Exception {
    unmarshaller = new Jaxb2Marshaller();
    unmarshaller.setClassesToBeBound(BinaryObject.class);
    unmarshaller.setMtomEnabled(true);
    unmarshaller.afterPropertiesSet();
    MimeContainer mimeContainer = mock(MimeContainer.class);
    Resource logo = new ClassPathResource("spring-ws.png", getClass());
    DataHandler dataHandler = new DataHandler(new FileDataSource(logo.getFile()));
    given(mimeContainer.isXopPackage()).willReturn(true);
    given(mimeContainer.getAttachment("<6b76528d-7a9c-4def-8e13-095ab89e9bb7@http://springframework.org/spring-ws>")).willReturn(dataHandler);
    given(mimeContainer.getAttachment("<99bd1592-0521-41a2-9688-a8bfb40192fb@http://springframework.org/spring-ws>")).willReturn(dataHandler);
    given(mimeContainer.getAttachment("696cfb9a-4d2d-402f-bb5c-59fa69e7f0b3@spring-ws.png")).willReturn(dataHandler);
    String content = "<binaryObject xmlns='http://springframework.org/spring-ws'>" + "<bytes>" + "<xop:Include href='cid:6b76528d-7a9c-4def-8e13-095ab89e9bb7@http://springframework.org/spring-ws' xmlns:xop='http://www.w3.org/2004/08/xop/include'/>" + "</bytes>" + "<dataHandler>" + "<xop:Include href='cid:99bd1592-0521-41a2-9688-a8bfb40192fb@http://springframework.org/spring-ws' xmlns:xop='http://www.w3.org/2004/08/xop/include'/>" + "</dataHandler>" + "<swaDataHandler>696cfb9a-4d2d-402f-bb5c-59fa69e7f0b3@spring-ws.png</swaDataHandler>" + "</binaryObject>";
    StringReader reader = new StringReader(content);
    Object result = unmarshaller.unmarshal(new StreamSource(reader), mimeContainer);
    assertTrue("Result is not a BinaryObject", result instanceof BinaryObject);
    BinaryObject object = (BinaryObject) result;
    assertNotNull("bytes property not set", object.getBytes());
    assertTrue("bytes property not set", object.getBytes().length > 0);
    assertNotNull("datahandler property not set", object.getSwaDataHandler());
}
Also used : StreamSource(javax.xml.transform.stream.StreamSource) ClassPathResource(org.springframework.core.io.ClassPathResource) Resource(org.springframework.core.io.Resource) FileDataSource(javax.activation.FileDataSource) StringReader(java.io.StringReader) DataHandler(javax.activation.DataHandler) ClassPathResource(org.springframework.core.io.ClassPathResource) MimeContainer(org.springframework.oxm.mime.MimeContainer) Test(org.junit.Test)

Example 35 with FileDataSource

use of javax.activation.FileDataSource in project camel by apache.

the class MimeMessageConsumeTest method populateMimeMessageBody.

/**
     * Lets encode a multipart mime message
     */
protected void populateMimeMessageBody(MimeMessage message) throws MessagingException {
    MimeBodyPart plainPart = new MimeBodyPart();
    plainPart.setText(body);
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setText("<html><body>" + body + "</body></html>");
    Multipart alt = new MimeMultipart("alternative");
    alt.addBodyPart(plainPart);
    alt.addBodyPart(htmlPart);
    Multipart mixed = new MimeMultipart("mixed");
    MimeBodyPart wrap = new MimeBodyPart();
    wrap.setContent(alt);
    mixed.addBodyPart(wrap);
    mixed.addBodyPart(plainPart);
    mixed.addBodyPart(htmlPart);
    DataSource ds;
    try {
        File f = new File(getClass().getResource("/log4j2.properties").toURI());
        ds = new FileDataSource(f);
    } catch (URISyntaxException ex) {
        ds = new URLDataSource(getClass().getResource("/log4j2.properties"));
    }
    DataHandler dh = new DataHandler(ds);
    BodyPart attachmentBodyPart;
    // Create another body part
    attachmentBodyPart = new MimeBodyPart();
    // Set the data handler to the attachment
    attachmentBodyPart.setDataHandler(dh);
    // Set the filename
    attachmentBodyPart.setFileName(dh.getName());
    // Set Disposition
    attachmentBodyPart.setDisposition(Part.ATTACHMENT);
    mixed.addBodyPart(plainPart);
    mixed.addBodyPart(htmlPart);
    // Add attachmentBodyPart to multipart
    mixed.addBodyPart(attachmentBodyPart);
    message.setContent(mixed);
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) URLDataSource(javax.activation.URLDataSource) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) URISyntaxException(java.net.URISyntaxException) DataHandler(javax.activation.DataHandler) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File) FileDataSource(javax.activation.FileDataSource) URLDataSource(javax.activation.URLDataSource) DataSource(javax.activation.DataSource)

Aggregations

FileDataSource (javax.activation.FileDataSource)55 DataHandler (javax.activation.DataHandler)46 File (java.io.File)22 DataSource (javax.activation.DataSource)18 Exchange (org.apache.camel.Exchange)18 MimeBodyPart (javax.mail.internet.MimeBodyPart)17 Test (org.junit.Test)16 Message (org.apache.camel.Message)15 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)12 MimeMultipart (javax.mail.internet.MimeMultipart)11 BodyPart (javax.mail.BodyPart)9 MimeMessage (javax.mail.internet.MimeMessage)8 Producer (org.apache.camel.Producer)7 URL (java.net.URL)6 MessagingException (javax.mail.MessagingException)6 Multipart (javax.mail.Multipart)6 InternetAddress (javax.mail.internet.InternetAddress)6 Endpoint (org.apache.camel.Endpoint)6 Processor (org.apache.camel.Processor)6 QName (javax.xml.namespace.QName)5