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:it.cnr.icar.eric.server.repository.filesystem.FileSystemRepositoryManager.java

/**
* Returns the RepositoryItem with the given unique ID.
*
* @param id Unique id for repository item
* @return RepositoryItem instance// w w w.  j  a  v a2s. co  m
* @exception RegistryException
*/
@SuppressWarnings({ "unused", "deprecation" })
public RepositoryItem getRepositoryItem(String id) throws RegistryException {
    RepositoryItem repositoryItem = null;
    String origId = id;

    // Strip off the "urn:uuid:"
    id = Utility.getInstance().stripId(id);

    try {
        String path = getRepositoryItemPath(id);
        File riFile = new File(path);

        if (!riFile.exists()) {
            String errmsg = ServerResourceBundle.getInstance().getString("message.RepositoryItemDoesNotExist",
                    new Object[] { id });
            log.error(errmsg);
            throw new RegistryException(errmsg);
        }

        DataHandler contentDataHandler = new DataHandler(new FileDataSource(riFile));

        Element sigElement = null;
        path += ".sig";

        File sigFile = new File(path);

        if (!sigFile.exists()) {
            String errmsg = "Payload signature for repository item id=\"" + id + "\" does not exist!";
            //log.error(errmsg);

            throw new RegistryException(errmsg);
        } else {

            javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory
                    .newInstance();
            dbf.setNamespaceAware(true);
            javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
            org.w3c.dom.Document sigDoc = db.parse(new FileInputStream(sigFile));

            repositoryItem = new RepositoryItemImpl(id, sigDoc.getDocumentElement(), contentDataHandler);
        }

    } catch (RegistryException e) {
        throw e;
    } catch (Exception e) {
        throw new RegistryException(e);
    }

    return repositoryItem;
}

From source file:org.wso2.carbon.wsdl2code.WSDL2Code.java

/**
 * This method will generate the code based on the options array. Options
 * arrya should be as follows, new String[] {"-uri", "location of wsdl",
 * "-g" ...}. Thus, the incoming XML should be as follows,
 * <p/>//  ww  w  .  j  a v a  2  s.  c  om
 * <ns:codegenRequest xmlns:ns="http://org.wso2.wsf/tools">
 * <options>-uri</options> <options>file://foo</options> ...
 * </ns:codegenRequest>
 * <p/>
 * Once codegenerated, location of genereated code will be send as an ID,
 * thus, one could easily download artifact as a zip file or jar file.
 *
 * @param options
 * @return String
 * @throws AxisFault
 */
public CodegenDownloadData codegen(String[] options) throws AxisFault {

    String uuid = String.valueOf(System.currentTimeMillis() + Math.random());
    ConfigurationContext configContext = getConfigContext();
    String codegenOutputDir = configContext.getProperty(ServerConstants.WORK_DIR) + File.separator
            + "tools_codegen" + File.separator + uuid + File.separator;
    System.getProperties().remove("project.base.dir");
    System.getProperties().remove("name");
    System.setProperty("project.base.dir", codegenOutputDir);

    String projectName = "";

    ArrayList<String> optionsList = new ArrayList<String>();
    HashMap<String, String> projOptionsList = new HashMap<String, String>();
    // adding default configurations

    projOptionsList.put("-gid", "org.wso2.carbon");
    projOptionsList.put("-vn", "0.0.1-SNAPSHOT");
    projOptionsList.put("-aid", "wso2-axis2-client");
    for (int j = 0; j < options.length; j++) {
        String option = options[j];
        if (option.equalsIgnoreCase("-gid") || option.equalsIgnoreCase("-vn")
                || option.equalsIgnoreCase("-aid")) {
            projOptionsList.put(option, options[j + 1]);
            j++;
        } else {
            optionsList.add(option);
        }
    }
    optionsList.add("--noBuildXML");

    String[] args = optionsList.toArray(new String[optionsList.size()]);
    Map allOptions;
    try {
        CommandLineOptionParser commandLineOptionParser = new CommandLineOptionParser(args);
        allOptions = commandLineOptionParser.getAllOptions();
        //validation
        List list = commandLineOptionParser.getInvalidOptions(new WSDL2JavaOptionsValidator());
        if (list.size() > 0) {
            String faultOptions = "";
            for (Iterator iterator = list.iterator(); iterator.hasNext();) {
                CommandLineOption commandLineOption = (CommandLineOption) iterator.next();
                String optionValue = commandLineOption.getOptionValue();
                faultOptions += "Invalid input for [ " + commandLineOption.getOptionType()
                        + (optionValue != null ? " : " + optionValue + " ]" : " ]") + "\n";

            }

            log.error(faultOptions);
            throw new AxisFault(faultOptions);
        }
        CommandLineOption commandLineOption = (CommandLineOption) allOptions.get("uri");
        if (commandLineOption == null) {
            throw new AxisFault("WSDL URI or Path Cannot be empty");
        }
        String uriValue = commandLineOption.getOptionValue().trim();
        projectName = getProjectName(uriValue);
        if ("".equals(uriValue)) {
            throw new AxisFault("WSDL URI or Path Cannot be empty");
        } else if (!(uriValue.startsWith("https://") || uriValue.startsWith("http://"))) {
            File file = new File(uriValue);
            if (!(file.exists() && file.isFile())) {
                throw new AxisFault("The wsdl uri should be a URL or a valid path on the file system");
            }
        }
        //            new CodeGenerationEngine(commandLineOptionParser).generate();
        (new POMGenerator()).generateAxis2Client(allOptions, codegenOutputDir, projOptionsList);
    } catch (Exception e) {
        String rootMsg = "Code generation failed";
        Throwable throwable = e.getCause();
        if (throwable != null) {
            String msg = throwable.getMessage();
            if (msg != null) {
                log.error(rootMsg + " " + msg, throwable);
                throw new AxisFault(throwable.toString());
            }
        }
        log.error(rootMsg, e);
        throw AxisFault.makeFault(e);
    }
    //set the output name
    CommandLineOption option = (CommandLineOption) allOptions
            .get(CommandLineOptionConstants.WSDL2JavaConstants.SERVICE_NAME_OPTION);

    try {
        //achive destination
        uuid = String.valueOf(System.currentTimeMillis() + Math.random());
        File destDir = new File(configContext.getProperty(ServerConstants.WORK_DIR) + File.separator
                + "tools_codegen" + File.separator + uuid);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        String destFileName = projectName + "-client.zip";
        String destArchive = destDir.getAbsolutePath() + File.separator + destFileName;

        new ArchiveManipulator().archiveDir(destArchive, new File(codegenOutputDir).getPath());
        FileManipulator.deleteDir(new File(codegenOutputDir));

        DataHandler handler;
        if (destArchive != null) {
            File file = new File(destArchive);
            FileDataSource datasource = new FileDataSource(file);
            handler = new DataHandler(datasource);

            CodegenDownloadData data = new CodegenDownloadData();
            data.setFileName(file.getName());
            data.setCodegenFileData(handler);
            return data;
        } else {
            return null;
        }

    } catch (IOException e) {
        String msg = WSDL2Code.class.getName() + " IOException has occured.";
        log.error(msg, e);
        throw new AxisFault(msg, e);
    }
}

From source file:org.chenillekit.mail.services.impl.MailServiceImpl.java

/**
 * send a plain text message./*from   w w  w.j a  v a  2s .co  m*/
 *
 * @param headers    the mail headers
 * @param body      the mail body (text based)
 * @param attachments array of files to attach at this mail
 *
 * @return true if mail successfull send
 */
public boolean sendPlainTextMail(MailMessageHeaders headers, String body, File... attachments) {
    DataSource[] dataSources = null;

    if (attachments != null) {
        dataSources = new DataSource[attachments.length];
        for (int x = 0; x < attachments.length; x++)
            dataSources[x] = new FileDataSource(attachments[x]);
    }

    return sendPlainTextMail(headers, body, dataSources);
}

From source file:org.entermedia.email.PostMail.java

public void postMail(List<InternetAddress> recipients, List<InternetAddress> blindrecipients, String subject,
        String inHtml, String inText, String from, List inAttachments, Map inProperties)
        throws MessagingException {
    // Set the host smtp address
    Properties props = new Properties();
    // create some properties and get the default Session
    props.put("mail.smtp.host", fieldSmtpServer);
    props.put("mail.smtp.port", String.valueOf(getPort()));
    props.put("mail.smtp.auth", new Boolean(fieldSmtpSecured).toString());
    if (isSslEnabled()) {
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    }//from   w w  w.j av  a 2s  .  co m
    Session session = null;
    if (isEnableTls()) {
        props.put("mail.smtp.starttls.enable", "true");
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(getSmtpUsername(), getSmtpPassword());
            }
        });
    } else if (fieldSmtpSecured) {
        SmtpAuthenticator auth = new SmtpAuthenticator();
        session = Session.getInstance(props, auth);
    } else {
        session = Session.getInstance(props);
    }
    // session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);
    MimeMultipart mp = null;
    // msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message,
    // "text/html")));

    if (inAttachments != null && inAttachments.size() == 0) {
        inAttachments = null;
    }

    if (inText != null && inHtml != null || inAttachments != null) {
        // Create an "Alternative" Multipart message
        mp = new MimeMultipart("mixed");

        if (inText != null) {
            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setContent(inText, "text/plain");
            mp.addBodyPart(messageBodyPart);
        }
        if (inHtml != null) {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(inHtml, "text/html");
            mp.addBodyPart(messageBodyPart);
        }
        if (inAttachments != null) {
            for (Iterator iterator = inAttachments.iterator(); iterator.hasNext();) {
                String filename = (String) iterator.next();

                File file = new File(filename);

                if (file.exists() && !file.isDirectory()) {
                    // create the second message part
                    MimeBodyPart mbp = new MimeBodyPart();

                    FileDataSource fds = new FileDataSource(file);
                    mbp.setDataHandler(new DataHandler(fds));

                    mbp.setFileName(fds.getName());

                    mp.addBodyPart(mbp);
                }
            }
        }

        msg.setContent(mp);

    } else if (inHtml != null) {
        msg.setContent(inHtml, "text/html");
    } else {
        msg.setContent(inText, "text/plain");
    }
    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);
    //msg.setRecipient(RecipientType.BCC, addressFrom);
    msg.setSentDate(new Date());
    if (recipients == null || recipients.isEmpty()) {
        throw new MessagingException("No recipients specified");
    }
    InternetAddress[] addressTo = recipients.toArray(new InternetAddress[recipients.size()]);

    msg.setRecipients(Message.RecipientType.TO, addressTo);

    //add bcc
    if (blindrecipients != null && !blindrecipients.isEmpty()) {
        InternetAddress[] addressBcc = blindrecipients.toArray(new InternetAddress[blindrecipients.size()]);
        msg.setRecipients(Message.RecipientType.BCC, addressBcc);
    }

    // Optional : You can also set your custom headers in the Email if you
    // Want
    // msg.addHeader("MyHeaderName", "myHeaderValue");
    // Setting the Subject and Content Type
    msg.setSubject(subject);

    // Transport tr = session.getTransport("smtp");
    // tr.connect(serverandport[0], null, null);
    // msg.saveChanges(); // don't forget this
    // tr.sendMessage(msg, msg.getAllRecipients());
    // tr.close();
    // msg.setContent(msg, "text/plain");

    Transport.send(msg);
    log.info("sent email " + subject);
}

From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java

public String send() {
    List attachmentList = null;/*from  w ww  .  ja  v a2 s.  c  o m*/
    AttachmentData a = null;
    try {
        Properties props = new Properties();

        // Server
        if (smtpServer == null || smtpServer.equals("")) {
            log.info("samigo.email.smtpServer is not set");
            smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
            if (smtpServer == null || smtpServer.equals("")) {
                log.info("smtp@org.sakaiproject.email.api.EmailService is not set");
                log.error(
                        "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService");
                return "error";
            }
        }
        props.setProperty("mail.smtp.host", smtpServer);

        // Port
        if (smtpPort == null || smtpPort.equals("")) {
            log.warn("samigo.email.smtpPort is not set. The default port 25 will be used.");
        } else {
            props.setProperty("mail.smtp.port", smtpPort);
        }

        Session session;
        session = Session.getInstance(props);
        session.setDebug(true);
        MimeMessage msg = new MimeMessage(session);

        InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName);
        msg.setFrom(fromIA);
        InternetAddress[] toIA = { new InternetAddress(toEmailAddress, toName) };
        msg.setRecipients(Message.RecipientType.TO, toIA);

        if ("yes".equals(ccMe)) {
            InternetAddress[] ccIA = { new InternetAddress(fromEmailAddress, fromName) };
            msg.setRecipients(Message.RecipientType.CC, ccIA);
        }
        msg.setSubject(subject);

        EmailBean emailBean = (EmailBean) ContextUtil.lookupBean("email");
        attachmentList = emailBean.getAttachmentList();
        StringBuilder content = new StringBuilder(message);
        ArrayList fileList = new ArrayList();
        ArrayList fileNameList = new ArrayList();
        if (attachmentList != null) {
            if (prefixedPath == null || prefixedPath.equals("")) {
                log.error("samigo.email.prefixedPath is not set");
                return "error";
            }
            Iterator iter = attachmentList.iterator();
            while (iter.hasNext()) {
                a = (AttachmentData) iter.next();
                if (a.getIsLink().booleanValue()) {
                    log.debug("send(): url");
                    content.append("<br/>\n\r");
                    content.append("<br/>"); // give a new line
                    content.append(a.getFilename());
                } else {
                    log.debug("send(): file");
                    File attachedFile = getAttachedFile(a.getResourceId());
                    fileList.add(attachedFile);
                    fileNameList.add(a.getFilename());
                }
            }
        }

        Multipart multipart = new MimeMultipart();
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content.toString(), "text/html");
        multipart.addBodyPart(messageBodyPart);
        msg.setContent(multipart);

        for (int i = 0; i < fileList.size(); i++) {
            messageBodyPart = new MimeBodyPart();
            FileDataSource source = new FileDataSource((File) fileList.get(i));
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName((String) fileNameList.get(i));
            multipart.addBodyPart(messageBodyPart);
        }
        msg.setContent(multipart);

        Transport.send(msg);
    } catch (UnsupportedEncodingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (MessagingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (ServerOverloadException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (PermissionException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IdUnusedException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (TypeException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IOException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } finally {
        if (attachmentList != null) {
            if (prefixedPath != null && !prefixedPath.equals("")) {
                StringBuilder sbPrefixedPath;
                Iterator iter = attachmentList.iterator();
                while (iter.hasNext()) {
                    sbPrefixedPath = new StringBuilder(prefixedPath);
                    sbPrefixedPath.append("/email_tmp/");
                    a = (AttachmentData) iter.next();
                    if (!a.getIsLink().booleanValue()) {
                        deleteAttachedFile(sbPrefixedPath.append(a.getResourceId()).toString());
                    }
                }
            }
        }
    }
    return "send";
}

From source file:app.logica.gestores.GestorEmail.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to//from  w w w.  jav a2s .  com
 *            Email address of the receiver.
 * @param from
 *            Email address of the sender, the mailbox account.
 * @param subject
 *            Subject of the email.
 * @param bodyText
 *            Body text of the email.
 * @param file
 *            Path to the file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
private MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        File file) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(from));
    email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");

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

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(file);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(file.getName());

    multipart.addBodyPart(mimeBodyPart);
    email.setContent(multipart);

    return email;
}

From source file:org.wso2.carbon.springservices.ui.SpringServiceMaker.java

public void createAndUploadSpringBean(String serviceHierarchy, String springContextId,
        ServiceUploaderClient client, String springBeanId, String[] beanClasses) throws Exception {
    String filePathFromArchiveId = getFilePathFromArchiveId(springBeanId);
    String filePathForSpringContext = getFilePathFromArchiveId(springContextId);

    Map fileResMap = (Map) configContext.getProperty(FILE_RESOURCE_MAP);
    fileResMap.remove(springContextId);/*  w w  w.  j a v a 2s.co m*/

    if (filePathFromArchiveId == null) {
        String msg = bundle.getString("spring.non.existent.file");
        log.warn(msg);
        throw new AxisFault(msg);
    }

    int endIndex = filePathFromArchiveId.lastIndexOf(File.separator);
    String filePath = filePathFromArchiveId.substring(0, endIndex);
    String archiveFileName = filePathFromArchiveId.substring(endIndex);
    archiveFileName = archiveFileName.substring(1, archiveFileName.lastIndexOf("."));

    ArchiveManipulator archiveManipulator = new ArchiveManipulator();

    // ----------------- Unzip the file ------------------------------------
    String unzippeDir = filePath + File.separator + "springTemp";
    File unzipped = new File(unzippeDir);
    if (!unzipped.mkdirs()) {
        log.error("Error while creating directories..");
    }

    try {
        archiveManipulator.extract(filePathFromArchiveId, unzippeDir);
    } catch (IOException e) {
        String msg = bundle.getString("spring.cannot.extract.archive");
        handleException(msg, e);
    }

    // TODO copy the spring xml
    String springContextRelLocation = "spring/context.xml";
    FileInputStream in = null;
    FileOutputStream out = null;

    try {
        File springContextRelDir = new File(unzippeDir + File.separator + "spring");
        if (!springContextRelDir.mkdirs()) {
            log.error("Error while creating directories..");
        }
        File absFile = new File(springContextRelDir, "context.xml");
        if (!absFile.exists() && !absFile.createNewFile()) {
            log.error("Error while creating file..");
        }
        File file = new File(filePathForSpringContext);
        in = new FileInputStream(file);
        out = new FileOutputStream(absFile);
        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

    } catch (FileNotFoundException e) {
        throw AxisFault.makeFault(e);
    } catch (IOException e) {
        throw AxisFault.makeFault(e);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.flush();
                out.close();
            }
        } catch (IOException e) {
            throw AxisFault.makeFault(e);
        }
    }

    // ---- Generate the services.xml and place it in META-INF -----
    File file = new File(unzippeDir + File.separator + "META-INF" + File.separator + "services.xml");
    if (!file.mkdirs()) {
        log.error("Error while creating directories..");
    }

    try {
        File absoluteFile = file.getAbsoluteFile();

        if (absoluteFile.exists() && !absoluteFile.delete()) {
            log.error("Error while deleting file..");
        }

        if (!absoluteFile.createNewFile()) {
            log.error("Error while creating file..");
        }

        OutputStream os = new FileOutputStream(file);
        OMElement servicesXML = createServicesXMLFromSpringBeans(beanClasses, springContextRelLocation);
        servicesXML.build();
        servicesXML.serialize(os);
    } catch (Exception e) {
        String msg = bundle.getString("spring.cannot.write.services.xml");
        handleException(msg, e);
    }

    // ----------------- Create the AAR ------------------------------------
    // These are the files to include in the ZIP file
    String outAARFilename = filePath + File.separator + archiveFileName + ".aar";

    try {
        archiveManipulator.archiveDir(outAARFilename, unzipped.getPath());
    } catch (IOException e) {
        String msg = bundle.getString("springcannot.create.new.aar.archive");
        handleException(msg, e);
    }

    File fileToUpload = new File(outAARFilename);

    FileDataSource fileDataSource = new FileDataSource(fileToUpload);
    DataHandler dataHandler = new DataHandler(fileDataSource);

    try {
        client.uploadService(archiveFileName + ".aar", serviceHierarchy, dataHandler);
    } catch (Exception e) {
        String msg = bundle.getString("spring.unable.to.upload");
        handleException(msg, e);
    }

}

From source file:eu.openanalytics.rsb.component.SoapMtomJobHandler.java

private ResultType buildResult(final JobType job, final MultiFilesResult multiFilesResult)
        throws FileNotFoundException, IOException {
    Validate.notNull(multiFilesResult, NULL_RESULT_RECEIVED);

    final boolean isOneZipJob = job.getPayload().size() == 1
            && Constants.ZIP_CONTENT_TYPES.contains(job.getPayload().get(0).getContentType());

    final File[] resultFiles = isOneZipJob
            ? new File[] { MultiFilesResult.zipResultFilesIfNotError(multiFilesResult) }
            : multiFilesResult.getPayload();

    final ResultType result = createResult(multiFilesResult);

    for (final File resultFile : resultFiles) {
        final PayloadType payload = soapOF.createPayloadType();
        payload.setContentType(Util.getContentType(resultFile));
        payload.setName(resultFile.getName());
        payload.setData(new DataHandler(new FileDataSource(resultFile)));
        result.getPayload().add(payload);
    }/*  w w  w.j a va2  s  . c  o  m*/
    return result;
}

From source file:eagle.common.email.EagleMailClient.java

public boolean send(String from, String to, String cc, String title, String templatePath,
        VelocityContext context, Map<String, File> attachments) {
    if (attachments == null || attachments.isEmpty()) {
        return send(from, to, cc, title, templatePath, context);
    }//from ww  w .j a  v a  2s  . com
    Template t = null;

    List<MimeBodyPart> mimeBodyParts = new ArrayList<MimeBodyPart>();
    Map<String, String> cid = new HashMap<String, String>();

    for (Map.Entry<String, File> entry : attachments.entrySet()) {
        final String attachment = entry.getKey();
        final File attachmentFile = entry.getValue();
        final MimeBodyPart mimeBodyPart = new MimeBodyPart();
        if (attachmentFile != null && attachmentFile.exists()) {
            DataSource source = new FileDataSource(attachmentFile);
            try {
                mimeBodyPart.setDataHandler(new DataHandler(source));
                mimeBodyPart.setFileName(attachment);
                mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
                mimeBodyPart.setContentID(attachment);
                cid.put(attachment, mimeBodyPart.getContentID());
                mimeBodyParts.add(mimeBodyPart);
            } catch (MessagingException e) {
                LOG.error("Generate mail failed, got exception while attaching files: " + e.getMessage(), e);
            }
        } else {
            LOG.error("Attachment: " + attachment + " is null or not exists");
        }
    }
    //TODO remove cid, because not used at all
    if (LOG.isDebugEnabled())
        LOG.debug("Cid maps: " + cid);
    context.put("cid", cid);

    try {
        t = velocityEngine.getTemplate(BASE_PATH + templatePath);
    } catch (ResourceNotFoundException ex) {
        //         LOGGER.error("Template not found:"+BASE_PATH + templatePath, ex);
    }

    if (t == null) {
        try {
            t = velocityEngine.getTemplate(templatePath);
        } catch (ResourceNotFoundException e) {
            try {
                t = velocityEngine.getTemplate("/" + templatePath);
            } catch (Exception ex) {
                LOG.error("Template not found:" + "/" + templatePath, ex);
            }
        }
    }

    final StringWriter writer = new StringWriter();
    t.merge(context, writer);
    if (LOG.isDebugEnabled())
        LOG.debug(writer.toString());
    return this._send(from, to, cc, title, writer.toString(), mimeBodyParts);
}

From source file:org.igov.io.mail.Mail.java

public Mail _Attach(File oFile) {
    _Attach(new FileDataSource(oFile), oFile.getName(), "");
    return this;
}