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.wso2.carbon.wsdl2code.WSDL2Code.java

private CodegenDownloadData getJaxRSCodegenDownloadData(ConfigurationContext configContext,
        String codegenOutputDir, ArrayList<String> optionsList, HashMap<String, String> projOptionsList)
        throws AxisFault {
    String uuid;/* ww w. j  av  a  2  s  .com*/

    String[] args = optionsList.toArray(new String[optionsList.size()]);

    try {
        POMGenerator.generateJaxRSClient(optionsList, 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);
    }

    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 = uuid.substring(2) + ".zip";
        String destFileName = getJAXWSRSProjectname(optionsList) + "-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:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Helper method to create a MimeBodyPart from a binary file.
 *
 * @param file     The file.//from   w  w w.  java 2  s .  c o  m
 * @param contentType The Mime content type of the file.
 * @param fileName The name of the file - as it will appear for the mail recipient.
 * @return The resulting MimeBodyPart.
 * @throws SystemException if the MimeBodyPart can't be created.
 */
public static MimeBodyPart createMimeBodyPartFromBinaryFile(final File file, final String contentType,
        String fileName) throws SystemException {
    try {
        MimeBodyPart attachmentPart1 = new MimeBodyPart();
        FileDataSource fileDataSource1 = new FileDataSource(file) {
            @Override
            public String getContentType() {
                return contentType;
            }
        };
        attachmentPart1.setDataHandler(new DataHandler(fileDataSource1));
        attachmentPart1.setFileName(fileName);
        return attachmentPart1;
    } catch (MessagingException e) {
        throw new SystemException("Feil ved generering av MimeBodyPart fra binrfil", e);
    }
}

From source file:com.gtwm.jasperexecute.RunJasperReports.java

public void emailReport(String emailHost, String emailUser, String emailPass, Set<String> emailRecipients,
        String emailSender, String emailSubject, List<String> attachmentFileNames) throws MessagingException {
    Properties props = new Properties();
    //props.setProperty("mail.debug", "true");
    props.setProperty("mail.smtp.host", emailHost);
    if (emailUser != null) {
        props.setProperty("mail.smtp.auth", "true");
    }//  www  . j  ava2s  .  co  m
    Authenticator emailAuthenticator = new EmailAuthenticator(emailUser, emailPass);
    Session mailSession = Session.getDefaultInstance(props, emailAuthenticator);
    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");
    // transport.connect(emailHost, emailUser, emailPass);
    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:org.wso2.carbon.connector.integration.test.apns.PushNotificationIntegrationTest.java

/**
 * Test case to verify that the connector properly handles errors when
 * certificate password is wrong./*from   w  ww. ja  va  2 s . c om*/
 * 
 * @throws Exception
 */
@Test(groups = {
        "org.wso2.carbon.connector.apns" }, priority = 1, description = "Integration test to cover error handling logic when the certificate password is wrong", expectedExceptions = AxisFault.class, expectedExceptionsMessageRegExp = ".*"
                + Utils.Errors.ERROR_CODE_INVALID_CERTIFICATE_INFO + ".*")
public void testSendPushNotificationWithWrongPassword() throws Exception {

    // Add proxy service
    String proxyServiceName = "apns_push";

    URL proxyUrl = new URL(
            "file:" + File.separator + File.separator + ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION
                    + ConnectorIntegrationUtil.ESB_CONFIG_LOCATION + File.separator + "proxies" + File.separator
                    + CONNECTOR_NAME + File.separator + proxyServiceName + ".xml");

    proxyAdmin.addProxyService(new DataHandler(proxyUrl));

    // Construct and send the request.

    String environment = PushNotificationRequest.SANDBOX_DESTINATION;
    String certificateAttachmentName = "certificate";
    String password = "wrong_password";

    String deviceToken = apnsProperties.getProperty(PROPERTY_KEY_DEVICE_TOKEN);

    String requestTemplate = ConnectorIntegrationUtil.getRequest("with_mandatory_params");
    String request = String.format(requestTemplate, environment, certificateAttachmentName, password,
            deviceToken);
    OMElement requestEnvelope = AXIOMUtil.stringToOM(request);

    String certificateFileName = apnsProperties.getProperty(PROPERTY_KEY_APNS_CERTIFICATE_FILENAME);
    Map<String, DataHandler> attachmentMap = new HashMap<String, DataHandler>();
    attachmentMap
            .put(certificateAttachmentName,
                    new DataHandler(new FileDataSource(new File(ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION
                            + ConnectorIntegrationUtil.ESB_CONFIG_LOCATION + File.separator + "auth"
                            + File.separator + certificateFileName))));

    OperationClient mepClient = ConnectorIntegrationUtil.buildMEPClientWithAttachment(
            new EndpointReference(getProxyServiceURL(proxyServiceName)), requestEnvelope, attachmentMap);
    try {
        mepClient.execute(true);
    } finally {
        proxyAdmin.deleteProxy(proxyServiceName);
    }
}

From source file:org.wso2.carbon.identity.tests.user.mgt.UserMgtServiceAbstractTestCase.java

@SetEnvironment(executionEnvironments = { ExecutionEnvironment.integration_all })
@Test(groups = "wso2.is", description = "Check importing bulk users", dependsOnMethods = "testGetRolePermissions")
public void testBulkImportUsers() throws Exception {

    File bulkUserFile = new File(
            getISResourceLocation() + File.separator + "userMgt" + File.separator + "bulkUserImport.csv");

    DataHandler handler = new DataHandler(new FileDataSource(bulkUserFile));
    userMgtClient.bulkImportUsers("bulkUserImport.csv", handler, "PassWord1@");

    String[] userList = userMgtClient.listUsers("*", 100);

    Assert.assertNotNull(userList);/*www  .  j av  a  2s .co m*/
    Assert.assertEquals(userMgtClient.listUsers("bulkUser1", 10), new String[] { "bulkUser1" });
    Assert.assertEquals(userMgtClient.listUsers("bulkUser2", 10), new String[] { "bulkUser2" });
    Assert.assertEquals(userMgtClient.listUsers("bulkUser3", 10), new String[] { "bulkUser3" });

    userMgtClient.deleteUser("bulkUser1");
    userMgtClient.deleteUser("bulkUser2");
    userMgtClient.deleteUser("bulkUser3");
}

From source file:com.ikon.util.MailUtils.java

/**
 * Create a mail./*ww w .j a  v a2  s.c o  m*/
 * 
 * @param fromAddress Origin address.
 * @param toAddress Destination addresses.
 * @param subject The mail subject.
 * @param text The mail body.
 * @throws MessagingException If there is any error.
 */
private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text,
        Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException,
        PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath });
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (fromAddress != null) {
        InternetAddress from = new InternetAddress(fromAddress);
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[toAddress.size()];
    int idx = 0;

    for (Iterator<String> it = toAddress.iterator(); it.hasNext();) {
        to[idx++] = new InternetAddress(it.next());
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    Multipart content = new MimeMultipart();

    // HTML Part
    MimeBodyPart htmlPart = new MimeBodyPart();
    StringBuilder htmlContent = new StringBuilder();
    htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
    htmlContent.append("<html>\n<head>\n");
    htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
    htmlContent.append("</head>\n<body>\n");
    htmlContent.append(text);
    htmlContent.append("\n</body>\n</html>");
    htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8");
    htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8");
    htmlPart.setDisposition(Part.INLINE);
    content.addBodyPart(htmlPart);
    idx = 0;

    if (docsPath != null) {
        for (String docPath : docsPath) {
            InputStream is = null;
            FileOutputStream fos = null;
            String docName = PathUtils.getName(docPath);

            try {
                final Document doc = OKMDocument.getInstance().getProperties(null, docPath);
                is = OKMDocument.getInstance().getContent(null, docPath, false);
                final File tmpAttch = tmpAttachments.get(idx++);
                fos = new FileOutputStream(tmpAttch);
                IOUtils.copy(is, fos);
                fos.flush();

                // Document attachment part
                MimeBodyPart docPart = new MimeBodyPart();
                DataSource source = new FileDataSource(tmpAttch.getPath()) {
                    public String getContentType() {
                        return doc.getMimeType();
                    }
                };

                docPart.setDataHandler(new DataHandler(source));
                docPart.setFileName(MimeUtility.encodeText(docName));
                docPart.setDisposition(Part.ATTACHMENT);
                content.addBodyPart(docPart);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(fos);
            }
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(subject, "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

From source file:immf.MyHtmlEmail.java

/**
 * Embeds a file in the HTML.//  www .j  ava 2s  .co m
 *
 * <p>This method embeds a file located by an URL into
 * the mail body. It allows, for instance, to add inline images
 * to the email.  Inline files may be referenced with a
 * <code>cid:xxxxxx</code> URL, where xxxxxx is the Content-ID
 * returned by the embed function. Files are bound to their names, which is
 * the value returned by {@link java.io.File#getName()}. If the same file
 * is embedded multiple times, the same CID is guaranteed to be returned.
 *
 * <p>While functionally the same as passing <code>FileDataSource</code> to
 * {@link #embed(DataSource, String, String)}, this method attempts
 * to validate the file before embedding it in the message and will throw
 * <code>EmailException</code> if the validation fails. In this case, the
 * <code>HtmlEmail</code> object will not be changed.
 *
 * @param file The <code>File</code> to embed
 * @param cid the Content-ID to use for the embedded <code>File</code>
 * @return A String with the Content-ID of the file.
 * @throws EmailException when the supplied <code>File</code> cannot be used
 *  or if the file has already been embedded;
 *  also see {@link javax.mail.internet.MimeBodyPart} for definitions
 * @since 1.1
 */
public String embed(File file, String cid) throws EmailException {
    if (StringUtils.isEmpty(file.getName())) {
        throw new EmailException("file name cannot be null or empty");
    }

    // verify that the File can provide a canonical path
    String filePath = null;
    try {
        filePath = file.getCanonicalPath();
    } catch (IOException ioe) {
        throw new EmailException("couldn't get canonical path for " + file.getName(), ioe);
    }

    // check if a FileDataSource for this name has already been attached;
    // if so, return the cached CID value.
    if (inlineEmbeds.containsKey(file.getName())) {
        InlineImage ii = (InlineImage) inlineEmbeds.get(file.getName());
        FileDataSource fileDataSource = (FileDataSource) ii.getDataSource();
        // make sure the supplied file has the same canonical path
        // as the one already associated with this name.
        String existingFilePath = null;
        try {
            existingFilePath = fileDataSource.getFile().getCanonicalPath();
        } catch (IOException ioe) {
            throw new EmailException("couldn't get canonical path for file "
                    + fileDataSource.getFile().getName() + "which has already been embedded", ioe);
        }
        if (filePath.equals(existingFilePath)) {
            return ii.getCid();
        } else {
            throw new EmailException("embedded name '" + file.getName() + "' is already bound to file "
                    + existingFilePath + "; existing names cannot be rebound");
        }
    }

    // verify that the file is valid
    if (!file.exists()) {
        throw new EmailException("file " + filePath + " doesn't exist");
    }
    if (!file.isFile()) {
        throw new EmailException("file " + filePath + " isn't a normal file");
    }
    if (!file.canRead()) {
        throw new EmailException("file " + filePath + " isn't readable");
    }

    return embed(new FileDataSource(file), file.getName());
}

From source file:com.openkm.util.MailUtils.java

/**
 * Create a mail.//  www  . j a v  a 2  s  .  c om
 * 
 * @param fromAddress Origin address.
 * @param toAddress Destination addresses.
 * @param subject The mail subject.
 * @param text The mail body.
 * @throws MessagingException If there is any error.
 */
private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text,
        Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException,
        PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath });
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (fromAddress != null && Config.SEND_MAIL_FROM_USER) {
        InternetAddress from = new InternetAddress(fromAddress);
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[toAddress.size()];
    int idx = 0;

    for (Iterator<String> it = toAddress.iterator(); it.hasNext();) {
        to[idx++] = new InternetAddress(it.next());
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    Multipart content = new MimeMultipart();

    // HTML Part
    MimeBodyPart htmlPart = new MimeBodyPart();
    StringBuilder htmlContent = new StringBuilder();
    htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
    htmlContent.append("<html>\n<head>\n");
    htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
    htmlContent.append("</head>\n<body>\n");
    htmlContent.append(text);
    htmlContent.append("\n</body>\n</html>");
    htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8");
    htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8");
    htmlPart.setDisposition(Part.INLINE);
    content.addBodyPart(htmlPart);
    idx = 0;

    if (docsPath != null) {
        for (String docPath : docsPath) {
            InputStream is = null;
            FileOutputStream fos = null;
            String docName = PathUtils.getName(docPath);

            try {
                final Document doc = OKMDocument.getInstance().getProperties(null, docPath);
                is = OKMDocument.getInstance().getContent(null, docPath, false);
                final File tmpAttch = tmpAttachments.get(idx++);
                fos = new FileOutputStream(tmpAttch);
                IOUtils.copy(is, fos);
                fos.flush();

                // Document attachment part
                MimeBodyPart docPart = new MimeBodyPart();
                DataSource source = new FileDataSource(tmpAttch.getPath()) {
                    public String getContentType() {
                        return doc.getMimeType();
                    }
                };

                docPart.setDataHandler(new DataHandler(source));
                docPart.setFileName(MimeUtility.encodeText(docName));
                docPart.setDisposition(Part.ATTACHMENT);
                content.addBodyPart(docPart);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(fos);
            }
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(subject, "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

From source file:org.wso2.identity.integration.test.user.mgt.UserMgtServiceAbstractTestCase.java

@SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL })
//    @Test(groups = "wso2.is", description = "Check importing bulk users", dependsOnMethods = "testGetRolePermissions")
public void testBulkImportUsers() throws Exception {

    //ToDo:get userStoreDomain properly
    String userStoreDomain = "PRIMARY";
    File bulkUserFile = new File(
            getISResourceLocation() + File.separator + "userMgt" + File.separator + "bulkUserImport.csv");

    DataHandler handler = new DataHandler(new FileDataSource(bulkUserFile));
    userMgtClient.bulkImportUsers(userStoreDomain, "bulkUserImport.csv", handler, "PassWord1@");

    String[] userList = userMgtClient.listUsers("*", 100);

    Assert.assertNotNull(userList);/*w  w  w. j  a  va  2s. co  m*/
    Assert.assertEquals(userMgtClient.listUsers("bulkUser1", 10), new String[] { "bulkUser1" });
    Assert.assertEquals(userMgtClient.listUsers("bulkUser2", 10), new String[] { "bulkUser2" });
    Assert.assertEquals(userMgtClient.listUsers("bulkUser3", 10), new String[] { "bulkUser3" });

    userMgtClient.deleteUser("bulkUser1");
    userMgtClient.deleteUser("bulkUser2");
    userMgtClient.deleteUser("bulkUser3");
}

From source file:org.wso2.carbon.mediation.library.service.MediationLibraryAdminService.java

/**
 * Used to download a carbon application archive.
 * /* w w w  .jav a 2 s .  c om*/
 * @param fileName
 *            the name of the application archive (.car) to be downloaded
 * @return datahandler corresponding to the .car file to be downloaded
 * @throws Exception
 *             for invalid scenarios
 */
public DataHandler downloadLibraryArchive(String fileName) throws Exception {
    // CarbonApplication instance to delete
    Library currentMediationLib = null;
    // Iterate all applications for this tenant and find the application to
    // delete
    SynapseConfiguration synConfigForTenant = getSynapseConfiguration();
    Collection<Library> appList = synConfigForTenant.getSynapseLibraries().values();
    for (Library mediationLib : appList) {
        if (fileName.equals(mediationLib.getQName().getLocalPart().toString())) {
            currentMediationLib = mediationLib;
        }
    }

    FileDataSource datasource = new FileDataSource(new File(currentMediationLib.getFileName()));
    DataHandler handler = new DataHandler(datasource);

    return handler;
}