Example usage for javax.activation FileDataSource FileDataSource

List of usage examples for javax.activation FileDataSource FileDataSource

Introduction

In this page you can find the example usage for javax.activation FileDataSource FileDataSource.

Prototype

public FileDataSource(String name) 

Source Link

Document

Creates a FileDataSource from the specified path name.

Usage

From source file:org.onesec.raven.ivr.vmail.impl.VMailBoxNodeTest.java

@Test
public void getSavedMessagesTest() throws Exception {
    Date messDate = new Date();
    vbox.addMessage(new NewVMailMessageImpl("123", "333", messDate, new FileDataSource(testFile)));
    Thread.sleep(10);/*  ww w . ja va  2s . c o m*/
    vbox.addMessage(new NewVMailMessageImpl("123", "222", new Date(), new FileDataSource(testFile)));
    Thread.sleep(10);
    vbox.addMessage(new NewVMailMessageImpl("123", "111", new Date(), new FileDataSource(testFile)));
    assertEquals(0, vbox.getSavedMessagesCount());
    for (SavableStoredVMailMessage mess : vbox.getNewMessages())
        mess.save();
    assertEquals(3, vbox.getSavedMessagesCount());
    List<StoredVMailMessage> messages = vbox.getSavedMessages();
    StoredVMailMessage mess = messages.get(0);
    assertEquals(messDate, mess.getMessageDate());
    assertEquals("333", mess.getSenderPhoneNumber());
    assertTrue(IOUtils.contentEquals(new FileInputStream(testFile), mess.getAudioSource().getInputStream()));
    assertEquals("222", messages.get(1).getSenderPhoneNumber());
    assertEquals("111", messages.get(2).getSenderPhoneNumber());
}

From source file:dk.dma.msinm.common.mail.AttachmentMailPart.java

/**
 * Returns a data-handler for this part/*from w w  w  . j av a  2 s.c o m*/
 * @return a data-handler for this part
 */
public DataHandler getDataHandler(Cache<URL, CachedUrlData> cache) throws MessagingException {
    if (file != null) {
        return new DataHandler(new FileDataSource(file));
    } else if (url != null) {
        return new DataHandler(new CachedUrlDataSource(url, cache));
    } else {
        return new DataHandler(new ByteArrayDataSource(content, contentType));
    }
}

From source file:org.wso2.carbon.esb.scenario.test.common.testng.listeners.TestPrepExecutionListener.java

/**
 * Function to upload carbon application
 *
 * @param carFileName//  w w  w .j av a2 s  .c om
 * @return
 * @throws RemoteException
 */
private void deployCarbonApplication(String carFileName)
        throws RemoteException, ApplicationAdminExceptionException {

    if (standaloneMode) {
        if (applicationAdminClient == null) {
            applicationAdminClient = new ApplicationAdminClient(backendURL, sessionCookie);
        }

        if (!checkCAppDeployed(applicationAdminClient, carFileName)) {

            log.info("Deploying carbon application : " + carFileName);
            // If standalone mode, deploy the CApp to the server
            String cappFilePath = carbonApplicationsDir + File.separator + carFileName
                    + ScenarioConstants.CAPP_EXTENSION;

            if (carbonAppUploaderClient == null) {
                carbonAppUploaderClient = new CarbonAppUploaderClient(backendURL, sessionCookie);
            }

            DataHandler dh = new DataHandler(new FileDataSource(new File(cappFilePath)));
            // Upload carbon application
            carbonAppUploaderClient.uploadCarbonAppArtifact(carFileName + ScenarioConstants.CAPP_EXTENSION, dh);

            //TODO - This thread sleep is added temporarily to wait until the ESB Instances sync in the cluster in clustered test environment
            if (!Boolean.valueOf(infraProperties.getProperty(ScenarioConstants.STANDALONE_DEPLOYMENT))) {
                log.info("Waiting for artifacts synchronized across cluster nodes");
                try {
                    Thread.sleep(300000);
                } catch (InterruptedException e) {
                    // log and ignore
                    log.error("Error occurred while waiting for artifacts synchronized across cluster nodes",
                            e);
                }
            }

            // Wait for Capp to sync
            log.info("Waiting for Carbon Application deployment ..");
            Awaitility.await().pollInterval(500, TimeUnit.MILLISECONDS)
                    .atMost(ScenarioConstants.ARTIFACT_DEPLOYMENT_WAIT_TIME_MS, TimeUnit.MILLISECONDS)
                    .until(isCAppDeployed(applicationAdminClient, carFileName));

        } else {
            log.info("Carbon application : " + carFileName + " already deployed");
        }
    }
}

From source file:org.openhab.binding.mail.internal.MailBuilder.java

/**
 * Build the Mail/* www .j  a v  a 2 s  . c  o  m*/
 *
 * @return instance of Email
 * @throws EmailException if something goes wrong
 */
public Email build() throws EmailException {
    Email mail;

    if (attachmentURLs.isEmpty() && attachmentFiles.isEmpty() && html.isEmpty()) {
        // text mail without attachments
        mail = new SimpleEmail();
        if (!text.isEmpty()) {
            mail.setMsg(text);
        }
    } else if (html.isEmpty()) {
        // text mail with attachments
        MultiPartEmail multipartMail = new MultiPartEmail();
        if (!text.isEmpty()) {
            multipartMail.setMsg(text);
        }
        for (File file : attachmentFiles) {
            multipartMail.attach(file);
        }
        for (URL url : attachmentURLs) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setURL(url);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            multipartMail.attach(attachment);
        }
        mail = multipartMail;
    } else {
        // html email
        HtmlEmail htmlMail = new HtmlEmail();
        if (!text.isEmpty()) {
            // alternate text supplied
            htmlMail.setTextMsg(text);
            htmlMail.setHtmlMsg(html);
        } else {
            htmlMail.setMsg(html);
        }
        for (File file : attachmentFiles) {
            htmlMail.attach(new FileDataSource(file), "", "");
        }
        for (URL url : attachmentURLs) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setURL(url);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            htmlMail.attach(attachment);
        }
        mail = htmlMail;
    }

    mail.setTo(recipients);
    mail.setSubject(subject);

    if (!sender.isEmpty()) {
        mail.setFrom(sender);
    }

    return mail;
}

From source file:net.ymate.module.mailsender.impl.DefaultMailSendProvider.java

@Override
public IMailSendBuilder create(final MailSendServerCfgMeta serverCfgMeta) {
    return new AbstractMailSendBuilder() {
        @Override/*  w w w.j a v  a 2  s  .c  o  m*/
        public void send(final String content) throws Exception {
            __sendExecPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        MimeMessage _message = new MimeMessage(serverCfgMeta.createIfNeed());
                        //
                        for (String _to : getTo()) {
                            _message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to));
                        }
                        for (String _cc : getCc()) {
                            _message.addRecipient(Message.RecipientType.CC, new InternetAddress(_cc));
                        }
                        for (String _bcc : getBcc()) {
                            _message.addRecipient(Message.RecipientType.BCC, new InternetAddress(_bcc));
                        }
                        //
                        if (getLevel() != null) {
                            switch (getLevel()) {
                            case LEVEL_HIGH:
                                _message.setHeader("X-MSMail-Priority", "High");
                                _message.setHeader("X-Priority", "1");
                                break;
                            case LEVEL_NORMAL:
                                _message.setHeader("X-MSMail-Priority", "Normal");
                                _message.setHeader("X-Priority", "3");
                                break;
                            case LEVEL_LOW:
                                _message.setHeader("X-MSMail-Priority", "Low");
                                _message.setHeader("X-Priority", "5");
                                break;
                            default:
                            }
                        }
                        //
                        String _charset = StringUtils.defaultIfEmpty(getCharset(), "UTF-8");
                        _message.setFrom(new InternetAddress(serverCfgMeta.getFromAddr(),
                                serverCfgMeta.getDisplayName(), _charset));
                        _message.setSubject(getSubject(), _charset);
                        // 
                        Multipart _container = new MimeMultipart();
                        // 
                        MimeBodyPart _textBodyPart = new MimeBodyPart();
                        if (getMimeType() == null) {
                            mimeType(IMailSender.MimeType.TEXT_PLAIN);
                        }
                        _textBodyPart.setContent(content, getMimeType().getMimeType() + ";charset=" + _charset);
                        _container.addBodyPart(_textBodyPart);
                        // ??<img src="cid:<CID_NAME>">
                        for (PairObject<String, File> _file : getAttachments()) {
                            if (_file.getValue() != null) {
                                MimeBodyPart _fileBodyPart = new MimeBodyPart();
                                FileDataSource _fileDS = new FileDataSource(_file.getValue());
                                _fileBodyPart.setDataHandler(new DataHandler(_fileDS));
                                if (_file.getKey() != null) {
                                    _fileBodyPart.setHeader("Content-ID", _file.getKey());
                                }
                                _fileBodyPart.setFileName(_fileDS.getName());
                                _container.addBodyPart(_fileBodyPart);
                            }
                        }
                        // ??
                        _message.setContent(_container);
                        Transport.send(_message);
                    } catch (Exception e) {
                        throw new RuntimeException(RuntimeUtils.unwrapThrow(e));
                    }
                }
            });
        }
    };
}

From source file:com.medsavant.mailer.Mail.java

public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) {
    try {/*  w w w.  j  av  a  2 s  .c o  m*/

        if (src == null || pw == null || host == null || port == -1) {
            return false;
        }

        if (to.isEmpty()) {
            return false;
        }

        LOG.info("Sending email to " + to + " with subject " + subject);

        // create some properties and get the default Session
        Properties props = new Properties();
        props.put("mail.smtp.user", src);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.starttls.enable", starttls);
        props.put("mail.smtp.auth", auth);
        props.put("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        props.put("mail.smtp.socketFactory.fallback", fallback);
        Session session = Session.getInstance(props, null);
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(src, srcName));
        InternetAddress[] address = InternetAddress.parse(to);
        msg.setRecipients(Message.RecipientType.BCC, address);
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();

        mbp1.setContent(text, "text/html");

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);

        if (attachment != null) {
            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();
            // attach the file to the message
            FileDataSource fds = new FileDataSource(attachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());
            mp.addBodyPart(mbp2);
        }

        // add the Multipart to the message
        msg.setContent(mp);
        // set the Date: header
        msg.setSentDate(new Date());
        // send the message
        Transport transport = session.getTransport("smtp");
        transport.connect(host, src, pw);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

        LOG.info("Mail sent");

        return true;

    } catch (Exception ex) {
        ex.printStackTrace();
        LOG.error(ex);
        return false;
    }

}

From source file:org.chenillekit.mail.services.TestMailService.java

@Test
public void send_html_datasourceattachment_mail() throws IOException, URISyntaxException {
    MailMessageHeaders headers = new MailMessageHeaders();

    headers.setFrom("sender@example.com");
    headers.addTo("receiver@example.com");

    FileDataSource file1 = new FileDataSource(new File(new ClasspathResource("dummy.txt").toURL().toURI()));
    FileDataSource file2 = new FileDataSource(new File(new ClasspathResource("log4j.xml").toURL().toURI()));
    FileDataSource file3 = new FileDataSource(
            new File(new ClasspathResource("smtp.properties").toURL().toURI()));

    MailService mailService = registry.getService(MailService.class);
    boolean sended = mailService.sendHtmlMail(headers,
            "<html><head><title>HTML title message</title></head><body><p>I'm the Body</body></html>", file1,
            file2, file3);//from  www  . j  a  v  a2 s. co m

    assertTrue(sended, "sended");
}

From source file:de.extra.client.core.model.inputdata.impl.SingleFileInputData.java

@Override
public DataSource getInputDataAsDataSource() {
    return new FileDataSource(this.inputDataFile);
}

From source file:org.apache.pdfbox.preflight.parser.PreflightParser.java

/**
 * Constructor./*from   www. jav  a2s  .  co m*/
 *
 * @param file
 * @throws IOException if there is a reading error.
 */
public PreflightParser(File file) throws IOException {
    // TODO move file handling outside of the parser
    super(new RandomAccessBufferedFileInputStream(file));
    this.setLenient(false);
    this.dataSource = new FileDataSource(file);
}

From source file:it.cnr.icar.eric.server.cms.CanonicalXMLFilteringService.java

@SuppressWarnings("unchecked")
public ServiceOutput invoke(ServerRequestContext context, ServiceInput si, ServiceType service,
        InvocationController invocationController, UserType user) throws RegistryException {
    if (log.isTraceEnabled()) {
        log.trace("CanonicalXMLFilteringService.invoke()");
    }/*w w w. ja va 2 s  .c om*/
    ServiceOutput so = new ServiceOutput();
    so.setOutput(context);
    RepositoryItem repositoryItem = si.getRepositoryItem();

    String roId = si.getRegistryObject().getId();

    ServerRequestContext outputContext = context; //new RequestContext(null);

    try {

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("subjectId", context.getUser().getId());

        //First filter the RegistryObject metadata
        StreamSource input = getAsStreamSource(si.getRegistryObject());
        StreamSource xslt = rm.getAsStreamSource(invocationController.getEoId());

        //Specify empty value to indicate that only metadata should be transformed
        //in this first XSLT invocation.
        params.put("repositoryItem", "");
        File output = runXSLT(input, xslt, getURIResolver(context), params);

        JAXBElement<RegistryObjectType> ebRegistryObject = (JAXBElement<RegistryObjectType>) bu.getJAXBContext()
                .createUnmarshaller().unmarshal(output);

        // take ComplexType from Element
        RegistryObjectType ebRegistryObjectType = ebRegistryObject.getValue();

        //Replace input RegistryObject with output RegistryObject.
        outputContext.getQueryResults().remove(si.getRegistryObject());
        outputContext.getQueryResults().add(ebRegistryObjectType);

        //Now filter the RepositoryItem content if any
        if (repositoryItem != null) {
            input = new StreamSource(repositoryItem.getDataHandler().getInputStream());
            xslt = rm.getAsStreamSource(invocationController.getEoId());

            params.put("repositoryItem", roId);
            output = runXSLT(input, xslt, getURIResolver(context), params);

            RepositoryItem outputRI = new RepositoryItemImpl(roId, new DataHandler(new FileDataSource(output)));

            //Replace input RepositoryItem with output RepositoryItem.
            outputContext.getRepositoryItemsMap().put(roId, outputRI);
        }

        // TODO: User should refer to "Service object for the
        // Content Management Service that generated the
        // Cataloged Content."
        outputContext.setUser(user);

    } catch (Exception e) {
        if (outputContext != context) {
            outputContext.rollback();
        }
        throw new RegistryException(e);
    }

    so.setOutput(outputContext);

    // Setting this error list is redundant, but Content Validation Services
    // currently output a Boolean and a RegistryErrorList, so using
    // same mechanism to report errors from Content Filtering Services.
    so.setErrorList(outputContext.getErrorList());

    if (outputContext != context) {
        outputContext.commit();
    }

    return so;
}