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:bioLockJ.module.agent.MailAgent.java

private BodyPart getAttachment(final String filePath) throws Exception {
    try {//from  w  ww . ja va2  s .  c  o m
        final DataSource source = new FileDataSource(filePath);
        final File logFile = new File(filePath);
        final double fileSize = logFile.length() / 1000000;
        if (fileSize < emailMaxAttachmentMB) {
            final BodyPart attachPart = new MimeBodyPart();
            attachPart.setDataHandler(new DataHandler(source));
            attachPart.setFileName(filePath.substring(filePath.lastIndexOf(File.separator) + 1));
            return attachPart;
        } else {
            Log.out.warn("File [" + filePath
                    + "] too large to attach.  Max file size configured in prop file set to = "
                    + emailMaxAttachmentMB + " MB");

        }
    } catch (final Exception ex) {
        Log.out.error("Unable to attach file", ex);
    }

    return null;
}

From source file:org.wso2.carbon.identity.workflow.mgt.template.impl.BPELApprovalDeployer.java

private void deployArtifacts() throws RemoteException {

    String bpelArchiveName = processName + Constants.ZIP_EXT;
    String archiveHome = System.getProperty(Constants.TEMP_DIR_PROPERTY) + File.separator;
    DataSource bpelDataSource = new FileDataSource(archiveHome + bpelArchiveName);
    WorkflowDeployerClient workflowDeployerClient = new WorkflowDeployerClient(bpsHost, bpsUser,
            password.toCharArray());//  w  w w .  j ava 2  s .c  o m
    workflowDeployerClient.uploadBPEL(
            getBPELUploadedFileItem(new DataHandler(bpelDataSource), bpelArchiveName, Constants.ZIP_TYPE));
    String htArchiveName = htName + Constants.ZIP_EXT;
    DataSource htDataSource = new FileDataSource(archiveHome + htArchiveName);
    workflowDeployerClient.uploadHumanTask(
            getHTUploadedFileItem(new DataHandler(htDataSource), htArchiveName, Constants.ZIP_TYPE));
}

From source file:org.bimserver.client.Client.java

public void checkin(SProject project) {
    JFileChooser chooser = new JFileChooser(".");
    int showOpenDialog = chooser.showOpenDialog(this);
    if (showOpenDialog == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        FileDataSource dataSource = new FileDataSource(file);
        checkin(project, dataSource, file.length());
    }//from   w  w  w .j av  a2s.com
}

From source file:org.codice.alliance.core.email.impl.EmailSenderImpl.java

/** sendEmail method sends email after receiving input parameters */
@Override//from   w w  w.  j  av a 2 s  . c o  m
public void sendEmail(String fromEmail, String toEmail, String subject, String body,
        List<Pair<String, InputStream>> attachments) throws IOException {
    notNull(fromEmail, "fromEmail must be non-null");
    notNull(toEmail, "toEmail must be non-null");
    notNull(subject, "subject must be non-null");
    notNull(body, "body must be non-null");
    notNull(attachments, "attachments must be non-null");

    if (StringUtils.isBlank(mailHost)) {
        throw new IOException("the mail server hostname has not been configured");
    }

    List<File> tempFiles = new LinkedList<>();

    try {
        InternetAddress emailAddr = new InternetAddress(toEmail);
        emailAddr.validate();

        Properties properties = createSessionProperties();

        Session session = Session.getDefaultInstance(properties);

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(fromEmail));
        mimeMessage.addRecipient(Message.RecipientType.TO, emailAddr);
        mimeMessage.setSubject(subject);

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body);

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        Holder<Long> bytesWritten = new Holder<>(0L);

        for (Pair<String, InputStream> attachment : attachments) {

            messageBodyPart = new MimeBodyPart();
            File file = File.createTempFile("email-sender-", ".dat");
            tempFiles.add(file);

            copyDataToTempFile(file, attachment.getValue(), bytesWritten);
            messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(file)));
            messageBodyPart.setFileName(attachment.getKey());
            multipart.addBodyPart(messageBodyPart);
        }

        mimeMessage.setContent(multipart);

        send(mimeMessage);

        LOGGER.debug("Email sent to " + toEmail);

    } catch (AddressException e) {
        throw new IOException("invalid email address: email=" + toEmail, e);
    } catch (MessagingException e) {
        throw new IOException("message error occurred on send", e);
    } finally {
        tempFiles.forEach(file -> {
            if (!file.delete()) {
                LOGGER.debug("unable to delete tmp file: path={}", file);
            }
        });
    }
}

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

@Test
public void deleteNewMessageTest() throws Exception {
    vbox.addMessage(new NewVMailMessageImpl("123", "222", new Date(), new FileDataSource(testFile)));
    assertEquals(1, vbox.getNewMessagesCount());
    vbox.getNewMessages().get(0).delete();
    assertEquals(0, vbox.getNewMessagesCount());
}

From source file:org.smartloli.kafka.eagle.api.email.MailServiceImpl.java

/** Send mail in HTML format */
private boolean sendHtmlMail(MailSenderInfo mailInfo) {
    boolean enableMailAlert = SystemConfigUtils.getBooleanProperty("kafka.eagle.mail.enable");
    if (enableMailAlert) {
        SaAuthenticatorInfo authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            authenticator = new SaAuthenticatorInfo(mailInfo.getUserName(), mailInfo.getPassword());
        }/*  w  w w.ja va 2s .  com*/
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            Message mailMessage = new MimeMessage(sendMailSession);
            Address from = new InternetAddress(mailInfo.getFromAddress());
            mailMessage.setFrom(from);
            Address[] to = new Address[mailInfo.getToAddress().split(",").length];
            int i = 0;
            for (String e : mailInfo.getToAddress().split(","))
                to[i++] = new InternetAddress(e);
            mailMessage.setRecipients(Message.RecipientType.TO, to);
            mailMessage.setSubject(mailInfo.getSubject());
            mailMessage.setSentDate(new Date());
            Multipart mainPart = new MimeMultipart();
            BodyPart html = new MimeBodyPart();
            html.setContent(mailInfo.getContent(), "text/html; charset=UTF-8");
            mainPart.addBodyPart(html);

            if (mailInfo.getImagesMap() != null && !mailInfo.getImagesMap().isEmpty()) {
                for (Entry<String, String> entry : mailInfo.getImagesMap().entrySet()) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    File file = new File(entry.getValue());
                    FileDataSource fds = new FileDataSource(file);
                    mbp.setDataHandler(new DataHandler(fds));
                    try {
                        mbp.setFileName(MimeUtility.encodeWord(entry.getKey(), "UTF-8", null));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mbp.setContentID(entry.getKey());
                    mbp.setHeader("Content-ID", "<image>");
                    mainPart.addBodyPart(mbp);
                }
            }

            List<File> list = mailInfo.getFileList();
            if (list != null && list.size() > 0) {
                for (File f : list) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(f.getAbsolutePath());
                    mbp.setDataHandler(new DataHandler(fds));
                    mbp.setFileName(f.getName());
                    mainPart.addBodyPart(mbp);
                }

                list.clear();
            }

            mailMessage.setContent(mainPart);
            // mailMessage.saveChanges();
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
    }
    return false;
}

From source file:com.collabnet.ccf.teamforge.TFAttachmentHandler.java

/**
 * This method uploads the file and gets the new file descriptor returned
 * from the TF system. It then associates the file descriptor to the
 * artifact there by adding the attachment to the artifact.
 * /*from   w w w.j a v a 2  s .  c om*/
 * @param sessionId
 *            - The current session id
 * @param artifactId
 *            - The artifact's id to which the attachment should be added.
 * @param comment
 *            - Comment for the attachment addition
 * @param fileName
 *            - Name of the file that is attached to this artifact
 * @param mimeType
 *            - MIME type of the file that is being attached.
 * @param att
 *            - the file content
 * @param linkUrl
 * 
 * @throws RemoteException
 *             - if any SOAP api call fails
 * @throws PlanningFolderRuleViolationException
 */
public ArtifactDO attachFileToArtifact(Connection connection, String artifactId, String comment,
        String fileName, String mimeType, GenericArtifact att, byte[] linkUrl)
        throws RemoteException, PlanningFolderRuleViolationException {
    ArtifactDO soapDo = null;
    String attachmentDataFileName = GenericArtifactHelper
            .getStringGAField(AttachmentMetaData.ATTACHMENT_DATA_FILE, att);
    boolean retryCall = true;
    while (retryCall) {
        retryCall = false;
        String fileDescriptor = null;
        try {
            byte[] data = null;
            if (StringUtils.isEmpty(attachmentDataFileName)) {
                if (linkUrl == null) {
                    data = att.getRawAttachmentData();
                } else {
                    data = linkUrl;
                }
                fileDescriptor = connection.getFileStorageClient().startFileUpload();
                connection.getFileStorageClient().write(fileDescriptor, data);
                connection.getFileStorageClient().endFileUpload(fileDescriptor);
            } else {
                try {
                    DataSource dataSource = new FileDataSource(new File(attachmentDataFileName));
                    DataHandler dataHandler = new DataHandler(dataSource);
                    fileDescriptor = connection.getFileStorageClient().uploadFile(dataHandler);
                } catch (IOException e) {
                    String message = "Exception while uploading the attachment " + attachmentDataFileName;
                    log.error(message, e);
                    throw new CCFRuntimeException(message, e);
                }
            }

            soapDo = connection.getTrackerClient().getArtifactData(artifactId);
            boolean fileAttached = true;
            while (fileAttached) {
                try {
                    fileAttached = false;
                    connection.getTrackerClient().setArtifactData(soapDo, comment, fileName, mimeType,
                            fileDescriptor);
                } catch (AxisFault e) {
                    javax.xml.namespace.QName faultCode = e.getFaultCode();
                    if (!faultCode.getLocalPart().equals("VersionMismatchFault")) {
                        throw e;
                    }
                    logConflictResolutor.warn("Stale attachment update, trying again ...:", e);
                    soapDo = connection.getTrackerClient().getArtifactData(artifactId);
                    fileAttached = true;
                }
            }
        } catch (AxisFault e) {
            javax.xml.namespace.QName faultCode = e.getFaultCode();
            if (!faultCode.getLocalPart().equals("InvalidSessionFault")) {
                throw e;
            }
            if (connectionManager.isEnableReloginAfterSessionTimeout()
                    && (!connectionManager.isUseStandardTimeoutHandlingCode())) {
                log.warn("While uploading an attachment, the session id became invalid, trying again", e);
                retryCall = true;
            } else {
                throw e;
            }
        }
    }
    // we have to increase the version after the update
    // TODO Find out whether this really works if last modified date differs
    // from actual last modified date
    soapDo.setVersion(soapDo.getVersion() + 1);
    return soapDo;
}

From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java

/**
 * @param runner/*  www  . j a v a2 s.  c  o  m*/
 * @param resultDir
 * @throws MessagingException
 * @throws IOException
 */
public void send(MultiHTMLSuiteRunner runner, File resultDir) throws MessagingException, IOException {

    MimeMessage mimeMessage = new MimeMessage(session);

    mimeMessage.setHeader("Content-Transfer-Encoding", "7bit");

    // To
    mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(config.getTo()));

    // From
    mimeMessage.setFrom(new InternetAddress(config.getFrom()));

    HashMap<String, Object> context = new HashMap<String, Object>();
    context.put("result", runner.getResult() ? "passed" : "failed");
    context.put("passedCount", new Integer(runner.getPassedCount()));
    context.put("failedCount", new Integer(runner.getFailedCount()));
    context.put("totalCount", new Integer(runner.getHtmlSuiteList().size()));
    context.put("startTime", new Date(runner.getStartTime()));
    context.put("endTime", new Date(runner.getEndTime()));
    context.put("htmlSuites", runner.getHtmlSuiteList());

    // subject
    mimeMessage.setSubject(TemplateUtils.merge(config.getSubject(), context), config.getCharset());

    // multipart message
    MimeMultipart content = new MimeMultipart();

    MimeBodyPart body = new MimeBodyPart();
    body.setText(TemplateUtils.merge(config.getBody(), context), config.getCharset());
    content.addBodyPart(body);

    File resultArchive = createResultArchive(resultDir);

    MimeBodyPart attachmentFile = new MimeBodyPart();
    attachmentFile.setDataHandler(new DataHandler(new FileDataSource(resultArchive)));
    attachmentFile.setFileName(RESULT_ARCHIVE_FILE);
    content.addBodyPart(attachmentFile);

    mimeMessage.setContent(content);

    // send mail
    _send(mimeMessage);
}

From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java

protected void send(String subject, String content, String contentType) throws Exception {
    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", getHost());
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);/*w w w  . j  a va2s. c om*/
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr"));
    message.setSubject(subject);

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "utf-8");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);

    List<String> fileNames = getAtchFileIds();

    for (Iterator<String> it = fileNames.iterator(); it.hasNext();) {
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(it.next());
        mbp2.setDataHandler(new DataHandler(fds));

        mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : 

        mp.addBodyPart(mbp2);
    }

    // add the Multipart to the message
    message.setContent(mp);

    for (Iterator<String> it = getReceivers().iterator(); it.hasNext();)
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next()));

    transport.connect(getHost(), getPort(), getUsername(), getPassword());
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
}

From source file:org.wso2.carbon.identity.workflow.impl.BPELDeployer.java

private void deployArtifacts() throws RemoteException {

    String bpelArchiveName = processName + BPELDeployer.Constants.ZIP_EXT;
    String archiveHome = System.getProperty(BPELDeployer.Constants.TEMP_DIR_PROPERTY) + File.separator;
    DataSource bpelDataSource = new FileDataSource(archiveHome + bpelArchiveName);
    WorkflowDeployerClient workflowDeployerClient = new WorkflowDeployerClient(bpsProfile.getManagerHostURL(),
            bpsProfile.getUsername(), bpsProfile.getPassword().toCharArray());
    workflowDeployerClient.uploadBPEL(getBPELUploadedFileItem(new DataHandler(bpelDataSource), bpelArchiveName,
            BPELDeployer.Constants.ZIP_TYPE));
    String htArchiveName = htName + BPELDeployer.Constants.ZIP_EXT;
    DataSource htDataSource = new FileDataSource(archiveHome + htArchiveName);
    workflowDeployerClient.uploadHumanTask(getHTUploadedFileItem(new DataHandler(htDataSource), htArchiveName,
            BPELDeployer.Constants.ZIP_TYPE));
}