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:net.sf.jclal.util.mail.SenderEmail.java

/**
 * Send the email with the indicated parameters
 *
 * @param subject The subject//  w w  w. j  a  v  a2s .  c  o m
 * @param content The content
 * @param reportFile The reportFile to send
 */
public void sendEmail(String subject, String content, File reportFile) {

    // Get system properties
    Properties properties = new Properties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);

    if (!user.isEmpty() && !pass.isEmpty()) {

        properties.setProperty("mail.user", user);

        properties.setProperty("mail.password", pass);
    }

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.addRecipients(Message.RecipientType.TO, toRecipients.toString());

        // Set Subject: header field
        message.setSubject(subject);

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setText(content);

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        if (attachReporFile) {

            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(reportFile)));
            messageBodyPart.setFileName(reportFile.getName());
            multipart.addBodyPart(messageBodyPart);
        }

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {

        Logger.getLogger(SenderEmail.class.getName()).log(Level.SEVERE, null, e);
    }

}

From source file:org.wso2.carbon.connector.integration.test.gmail.GmailConnectorIntegrationTestForSendAttachment.java

@BeforeClass(alwaysRun = true)
public void setEnvironment() throws Exception {
    super.init();

    ConfigurationContextProvider configurationContextProvider = ConfigurationContextProvider.getInstance();
    ConfigurationContext cc = configurationContextProvider.getConfigurationContext();

    mediationLibUploadStub = new MediationLibraryUploaderStub(cc,
            esbServer.getBackEndUrl() + "MediationLibraryUploader");
    AuthenticateStub.authenticateStub("admin", "admin", mediationLibUploadStub);

    adminServiceStub = new MediationLibraryAdminServiceStub(cc,
            esbServer.getBackEndUrl() + "MediationLibraryAdminService");
    AuthenticateStub.authenticateStub("admin", "admin", adminServiceStub);

    if (System.getProperty("os.name").toLowerCase().contains("windows")) {
        repoLocation = System.getProperty("connector_repo").replace("/", "\\");
    } else {//  w  w  w  . j  a v a 2 s  .  c  o m
        repoLocation = System.getProperty("connector_repo").replace("/", "/");
    }

    log.warn("REPOLOCATION:" + repoLocation);

    proxyAdmin = new ProxyServiceAdminClient(esbServer.getBackEndUrl(), esbServer.getSessionCookie());
    ConnectorIntegrationUtil.uploadConnector(repoLocation, mediationLibUploadStub, gmailConnectorFileName);
    byte maxAttempts = 10;
    int sleepTimer = 30000;
    for (byte attemptCount = 0; attemptCount < maxAttempts; attemptCount++) {
        Thread.sleep(sleepTimer);
        String[] libraries = adminServiceStub.getAllLibraries();
        if (Arrays.asList(libraries).contains("{org.wso2.carbon.connector}" + CONNECTOR_NAME)) {
            break;
        } else {
            sleepTimer *= SLEEP_TIMER_PROGRESSION_FACTOR;
        }
    }

    adminServiceStub.updateStatus("{org.wso2.carbon.connector}" + CONNECTOR_NAME, CONNECTOR_NAME,
            "org.wso2.carbon.connector", "enabled");
    gmailConnectorProperties = ConnectorIntegrationUtil.getConnectorConfigProperties(CONNECTOR_NAME);

    // Initializing the local variables which are used in the test cases
    mailSubject = "Gmail Integration Testing (Random ID:" + UUID.randomUUID().toString() + ")";
    deleteMailSubject = "[This will be deleted] Gmail Integration Testing (Random ID:"
            + UUID.randomUUID().toString() + ")";
    attachmentMap = new HashMap<String, DataHandler>();
    for (String fileName : fileNames) {
        attachmentMap.put(fileName,
                new DataHandler(new FileDataSource(new File(ProductConstant.SYSTEM_TEST_RESOURCE_LOCATION
                        + ConnectorIntegrationUtil.ESB_CONFIG_LOCATION + File.separator + fileName))));
    }
}

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

@Test(description = "Perform bulk user import and check the bulkuserimport log file is created.")
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
public void testBulkUserImportLogFileIsPresent() throws RemoteException, UserAdminUserAdminException {

    File bulkUserFile = new File(BULK_USER_FILE + BULK_USER_IMPORT_SUCCESS_FILE);

    DataHandler handler = new DataHandler(new FileDataSource(bulkUserFile));
    userMgtClient.bulkImportUsers(USER_STORE_DOMAIN, BULK_USER_IMPORT_SUCCESS_FILE, handler, null);

    File logDir = new File(LOG_FILE_LOCATION);
    String[] logFiles = logDir.list();
    if (ArrayUtils.isNotEmpty(logFiles)) {
        for (String fileName : logFiles) {
            if (LOG_FILE_NAME.equals(fileName)) {
                isFilePresent = true;/*from www.  j  av a2 s.  c o m*/
            }
        }
    }
    assertTrue(isFilePresent);
}

From source file:org.openhealthtools.openxds.repository.Utility.java

/**
 * Create a RepositoryItem containing provided content.
 *
 * @param id the id of the created ExtrinsicObject created for the RepositoryItem
 * @param content contents of the created RepositoryItem
 *
 * @return a <code>RepositoryItem</code> value
 * @throws IOException encountered during IO operations
 *///w w w . j  ava 2 s.c o  m
public XdsRepositoryItem createRepositoryItem(String id, String content) throws IOException {
    File file = createTempFile(content, true);

    DataHandler dh = new DataHandler(new FileDataSource(file));
    XdsRepositoryItem ri = new XdsRepositoryItemImpl(id, dh);
    return ri;
}

From source file:org.bimserver.tests.TestSimultaniousDownloadWithCaching.java

private void start() {
    BimServerConfig config = new BimServerConfig();
    Path homeDir = Paths.get("home");
    try {/*from  www .j  a  v a  2  s .  com*/
        if (Files.isDirectory(homeDir)) {
            PathUtils.removeDirectoryWithContent(homeDir);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    config.setClassPath(System.getProperty("java.class.path"));
    config.setHomeDir(homeDir);
    config.setPort(8080);
    config.setStartEmbeddedWebServer(true);
    config.setResourceFetcher(new LocalDevelopmentResourceFetcher(Paths.get("../")));
    final BimServer bimServer = new BimServer(config);
    try {
        LocalDevPluginLoader.loadPlugins(bimServer.getPluginManager(), null);
        bimServer.start();
        if (bimServer.getServerInfo().getServerState() == ServerState.NOT_SETUP) {
            bimServer.getService(AdminInterface.class).setup("http://localhost", "Administrator",
                    "admin@bimserver.org", "admin", null, null, null);
        }
    } catch (PluginException e2) {
        e2.printStackTrace();
    } catch (ServerException e) {
        e.printStackTrace();
    } catch (DatabaseInitException e) {
        e.printStackTrace();
    } catch (BimserverDatabaseException e) {
        e.printStackTrace();
    } catch (DatabaseRestartRequiredException e) {
        e.printStackTrace();
    } catch (UserException e) {
        e.printStackTrace();
    }

    try {
        final ServiceMap serviceMap = bimServer.getServiceFactory().get(AccessMethod.INTERNAL);
        ServiceInterface serviceInterface = serviceMap.get(ServiceInterface.class);
        SettingsInterface settingsInterface = serviceMap.get(SettingsInterface.class);
        final AuthInterface authInterface = serviceMap.get(AuthInterface.class);
        serviceInterface = bimServer.getServiceFactory()
                .get(authInterface.login("admin@bimserver.org", "admin"), AccessMethod.INTERNAL)
                .get(ServiceInterface.class);
        settingsInterface.setCacheOutputFiles(true);
        settingsInterface.setGenerateGeometryOnCheckin(false);
        final SProject project = serviceMap.getServiceInterface().addProject("test", "ifc2x3tc1");
        SDeserializerPluginConfiguration deserializerByName = serviceMap.getServiceInterface()
                .getDeserializerByName("IfcStepDeserializer");
        Path file = Paths.get("../TestData/data/AC11-Institute-Var-2-IFC.ifc");
        serviceInterface.checkin(project.getOid(), "test", deserializerByName.getOid(), file.toFile().length(),
                file.getFileName().toString(), new DataHandler(new FileDataSource(file.toFile())), false, true);
        final SProject projectUpdate = serviceMap.getServiceInterface().getProjectByPoid(project.getOid());
        ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 20, 1, TimeUnit.HOURS,
                new ArrayBlockingQueue<Runnable>(1000));
        for (int i = 0; i < 20; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        ServiceMap serviceMap2 = bimServer.getServiceFactory().get(
                                authInterface.login("admin@bimserver.org", "admin"), AccessMethod.INTERNAL);
                        SSerializerPluginConfiguration serializerPluginConfiguration = serviceMap
                                .getServiceInterface().getSerializerByName("Ifc2x3");
                        Long download = serviceMap2.getServiceInterface().download(
                                Collections.singleton(projectUpdate.getLastRevisionId()),
                                DefaultQueries.allAsString(), serializerPluginConfiguration.getOid(), true);
                        SDownloadResult downloadData = serviceMap2.getServiceInterface()
                                .getDownloadData(download);
                        if (downloadData.getFile()
                                .getDataSource() instanceof CacheStoringEmfSerializerDataSource) {
                            CacheStoringEmfSerializerDataSource c = (CacheStoringEmfSerializerDataSource) downloadData
                                    .getFile().getDataSource();
                            try {
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                c.writeToOutputStream(baos, null);
                                System.out.println(baos.size());
                            } catch (SerializerException e) {
                                e.printStackTrace();
                            }
                        } else {
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            IOUtils.copy(downloadData.getFile().getInputStream(), baos);
                            System.out.println(baos.size());
                        }
                        serviceMap2.getServiceInterface().cleanupLongAction(download);
                    } catch (ServerException e) {
                        e.printStackTrace();
                    } catch (UserException e) {
                        e.printStackTrace();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (PublicInterfaceNotFoundException e1) {
                        e1.printStackTrace();
                    }
                }
            });
        }
        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.HOURS);
        bimServer.stop();
    } catch (ServerException e1) {
        e1.printStackTrace();
    } catch (UserException e1) {
        e1.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (PublicInterfaceNotFoundException e2) {
        e2.printStackTrace();
    }
}

From source file:org.data2semantics.yasgui.selenium.FailNotification.java

private void sendMail(String subject, String content, String fileName) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(baseTest.props.getMailUserName(),
                    baseTest.props.getMailPassWord());
        }/*w ww.j  a v a  2  s. c  o  m*/
    });

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(baseTest.props.getMailUserName()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(baseTest.props.getMailSendTo()));
        message.setSubject(subject);
        message.setContent(content, "text/html; charset=utf-8");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        // message body
        messageBodyPart.setContent(content, "text/html; charset=utf-8");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        // attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("screenshot.png");
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);

        Transport.send(message);

        System.out.println("Email send");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.infoglue.common.util.mail.MailService.java

/**
 * @param attachments //from  www.ja  v a2  s.co m
 *
 */
private Message createMessage(String from, String to, String bcc, String subject, String content,
        String contentType, String encoding, List attachments) throws SystemException {
    try {
        final Message message = new MimeMessage(this.session);
        String contentTypeWithEncoding = contentType + ";charset=" + encoding;

        // message.setContent(content, contentType);
        message.setFrom(createInternetAddress(from));
        //message.setRecipient(Message.RecipientType.TO,
        //      createInternetAddress(to));
        message.setRecipients(Message.RecipientType.TO, createInternetAddresses(to));
        if (bcc != null)
            message.setRecipients(Message.RecipientType.BCC, createInternetAddresses(bcc));
        // message.setSubject(subject);

        ((MimeMessage) message).setSubject(subject, encoding);
        MimeMultipart mp = new MimeMultipart();
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setDataHandler(new DataHandler(new StringDataSource(content, contentTypeWithEncoding, encoding)));
        mp.addBodyPart(mbp1);
        if (attachments != null) {
            for (Iterator it = attachments.iterator(); it.hasNext();) {
                File attachmentFile = (File) it.next();
                if (attachmentFile.exists()) {
                    MimeBodyPart attachment = new MimeBodyPart();
                    attachment.setFileName(attachmentFile.getName());
                    attachment.setDataHandler(new DataHandler(new FileDataSource(attachmentFile)));
                    mp.addBodyPart(attachment);
                }
            }
        }
        message.setContent(mp);
        // message.setText(content);
        // message.setDataHandler(new DataHandler(new
        // StringDataSource(content, contentTypeWithEncoding, encoding)));
        // message.setText(content);
        // message.setDataHandler(new DataHandler(new
        // StringDataSource(content, "text/html")));

        return message;
    } catch (MessagingException e) {
        throw new SystemException("Unable to create the message.", e);
    }
}

From source file:de.extra.client.plugins.outputplugin.mtomws.WsCxfIT.java

/**
 * Fhrt zu dem RequestTransport InputFile
 * /*w w w .j  a  va2 s.  c  o  m*/
 * @param requestTransport
 * @param inputFile
 * @return
 */
private RequestTransport fillInputFile(final RequestTransport requestTransport, final File inputFile) {
    final Base64CharSequenceType base64CharSequence = requestTransport.getTransportBody().getData()
            .getBase64CharSequence();
    final DataSource source = new FileDataSource(inputFile);
    base64CharSequence.setValue(new DataHandler(source));

    return requestTransport;

}

From source file:org.wso2.bam.integration.tests.toolbox.CustomToolBoxTestCase.java

private Object[] getToolBox() throws Exception {
    BAMToolboxDepolyerServiceStub.BasicToolBox[] toolBoxes = toolboxStub.getBasicToolBoxes();
    if (null == toolBoxes || toolBoxes.length == 0) {
        throw new Exception("No default toolboxes available..");
    }//  w  ww .  ja  va  2  s.  co m
    String toolBoxLocation = toolBoxes[0].getLocation();

    File toolBox = new File(toolBoxLocation);
    FileDataSource dataSource = new FileDataSource(toolBox);
    Object[] result = new Object[2];

    result[0] = new DataHandler(dataSource);
    result[1] = toolBoxes[0].getTBoxFileName();
    return result;
}

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

/**
 * send a HTML message./*from  w  ww.  j  a va2s.  c om*/
 *
 * @param headers    the mail headers
 * @param htmlBody   the mail body (HTML based)
 * @param attachments array of files to attach at this mail
 *
 * @return true if mail successfull send
 */
public boolean sendHtmlMail(MailMessageHeaders headers, String htmlBody, 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 sendHtmlMail(headers, htmlBody, dataSources);
}