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:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java

private void addFormMultipart(HttpRequestInterface<?> request, MimeMultipart formMp, String name, String value)
        throws MessagingException {
    MimeBodyPart part = new MimeBodyPart();

    if (value.startsWith("file:")) {
        String fileName = value.substring(5);
        File file = new File(fileName);
        part.setDisposition("form-data; name=\"" + name + "\"; filename=\"" + file.getName() + "\"");
        if (file.exists()) {
            part.setDataHandler(new DataHandler(new FileDataSource(file)));
        } else {// w  w  w . j  a  va2s .c  om
            for (Attachment attachment : request.getAttachments()) {
                if (attachment.getName().equals(fileName)) {
                    part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));
                    break;
                }
            }
        }

        part.setHeader("Content-Type", ContentTypeHandler.getContentTypeFromFilename(file.getName()));
        part.setHeader("Content-Transfer-Encoding", "binary");
    } else {
        part.setDisposition("form-data; name=\"" + name + "\"");
        part.setText(value, System.getProperty("soapui.request.encoding", request.getEncoding()));
    }

    if (part != null) {
        formMp.addBodyPart(part);
    }
}

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

@Test(groups = "wso2.is", description = "Check importing bulk users")
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);//from w  w  w.  j  a v a  2s  .c o 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.connector.integration.test.apns.PushNotificationIntegrationTest.java

/**
 * Test case to verify that the connector properly handles errors when the payload is too long.
 */// w w w . ja  v  a  2 s.  c o  m
@Test(groups = {
        "org.wso2.carbon.connector.apns" }, priority = 1, description = "Integration test to cover error handling logic when the payload is too long", expectedExceptions = AxisFault.class, expectedExceptionsMessageRegExp = ".*"
                + Utils.Errors.ERROR_CODE_PAYLOAD_ERROR + ".*")
public void testSendPushNotificationWithTooLongPayload() 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 = apnsProperties.getProperty(PROPERTY_KEY_CERTIFICATE_PASSWORD);

    String deviceToken = apnsProperties.getProperty(PROPERTY_KEY_DEVICE_TOKEN);
    String alert = String.format("Message : %s", StringUtils.repeat("x", 256));
    String sound = "sound";
    int badge = 1;

    String requestTemplate = ConnectorIntegrationUtil.getRequest("with_optional_params");
    String request = String.format(requestTemplate, environment, certificateAttachmentName, password,
            deviceToken, alert, badge, sound);
    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:checkwebsite.Mainframe.java

/**
 *
 * @param email//from w  w w . j  a v a  2s  .  c om
 * @param msg
 */
protected void notify(String email, String msg) {
    // Recipient's email ID needs to be mentioned.
    String to = email;//change accordingly

    // go to link below and turn on Access for less secure apps
    //https://www.google.com/settings/security/lesssecureapps
    // Sender's email ID needs to be mentioned
    String from = "";//Enter your email id here
    final String username = "";//Enter your email id here
    final String password = "";//Enter your password here

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

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

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

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject("Report of your website : " + wurl);

        //            // Now set the actual message
        //            message.setText("Hello, " + msg + " this is sample for to check send "
        //                    + "email using JavaMailAPI ");
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Now set the actual message
        messageBodyPart.setText("Please! find your website report in attachment");

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

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

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "WebsiteReport.txt";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);

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

        // Send message
        Transport.send(message);
        lblWarning.setText("report sent...");
        System.out.println("Sent message successfully....");

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

From source file:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java

public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) {
    // Retrieve SMTP server information
    String host = getSmtpHost();/*from w  ww .  j  a  v  a  2  s  .c  om*/
    boolean isSmtpAuthentication = isSmtpAuthentication();
    int smtpPort = getSmtpPort();
    String smtpUser = getSmtpUser();
    String smtpPwd = getSmtpPwd();
    boolean isSmtpDebug = isSmtpDebug();

    List<String> emailErrors = new ArrayList<String>();

    if (emails.size() > 0) {

        // Corps et sujet du message
        String subject = getString("infoLetter.emailSubject") + ilp.getName();
        // Email du publieur
        String from = getUserDetail().geteMail();
        // create some properties and get the default Session
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication));

        Session session = Session.getInstance(props, null);
        session.setDebug(isSmtpDebug); // print on the console all SMTP messages.

        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "subject = " + subject);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "from = " + from);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "host= " + host);

        try {
            // create a message
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            msg.setSubject(subject, CharEncoding.UTF_8);
            ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId());
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg,
                            I18NHelper.defaultLanguage);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            for (SimpleDocument content : contents) {
                AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(),
                        content.getLanguage());
            }
            mbp1.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(
                            replaceFileServerWithLocal(
                                    IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server),
                            MimeTypes.HTML_MIME_TYPE)));
            IOUtils.closeQuietly(buffer);
            // Fichiers joints
            WAPrimaryKey publiPK = ilp.getPK();
            publiPK.setComponentName(getComponentId());
            publiPK.setSpace(getSpaceId());

            // create the Multipart and its parts to it
            String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related");
            Multipart mp = new MimeMultipart(mimeMultipart);
            mp.addBodyPart(mbp1);

            // Images jointes
            List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null);
            for (SimpleDocument attachment : fichiers) {
                // create the second message part
                MimeBodyPart mbp2 = new MimeBodyPart();

                // attach the file to the message
                FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                mbp2.setDataHandler(new DataHandler(fds));
                // For Displaying images in the mail
                mbp2.setFileName(attachment.getFilename());
                mbp2.setHeader("Content-ID", attachment.getFilename());
                SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                        "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                // create the Multipart and its parts to it
                mp.addBodyPart(mbp2);
            }

            // Fichiers joints
            fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null);

            if (!fichiers.isEmpty()) {
                for (SimpleDocument attachment : fichiers) {
                    // create the second message part
                    MimeBodyPart mbp2 = new MimeBodyPart();

                    // attach the file to the message
                    FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                    mbp2.setDataHandler(new DataHandler(fds));
                    mbp2.setFileName(attachment.getFilename());
                    // For Displaying images in the mail
                    mbp2.setHeader("Content-ID", attachment.getFilename());
                    SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                    // create the Multipart and its parts to it
                    mp.addBodyPart(mbp2);
                }
            }

            // add the Multipart to the message
            msg.setContent(mp);
            // set the Date: header
            msg.setSentDate(new Date());
            // create a Transport connection (TCP)
            Transport transport = session.getTransport("smtp");

            InternetAddress[] address = new InternetAddress[1];
            for (String email : emails) {
                try {
                    address[0] = new InternetAddress(email);
                    msg.setRecipients(Message.RecipientType.TO, address);
                    // add Transport Listener to the transport connection.
                    if (isSmtpAuthentication) {
                        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                "root.MSG_GEN_PARAM_VALUE",
                                "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser);
                        transport.connect(host, smtpPort, smtpUser, smtpPwd);
                        msg.saveChanges();
                    } else {
                        transport.connect();
                    }
                    transport.sendMessage(msg, address);
                } catch (Exception ex) {
                    SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "Email = " + email,
                            new InfoLetterException(
                                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                                    SilverpeasRuntimeException.ERROR, ex.getMessage(), ex));
                    emailErrors.add(email);
                } finally {
                    if (transport != null) {
                        try {
                            transport.close();
                        } catch (Exception e) {
                            SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                    "root.EX_IGNORED", "ClosingTransport", e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new InfoLetterException(
                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                    SilverpeasRuntimeException.ERROR, e.getMessage(), e);
        }
    }
    return emailErrors.toArray(new String[emailErrors.size()]);
}

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

/**
 * Create a mail from a Mail object/*from  www.j ava  2 s  .  c  o m*/
 */
public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException,
        AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({})", mail);
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

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

    InternetAddress[] to = new InternetAddress[mail.getTo().length];
    int i = 0;

    for (String strTo : mail.getTo()) {
        to[i++] = new InternetAddress(strTo);
    }

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

    if (Mail.MIME_TEXT.equals(mail.getMimeType())) {
        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    } else if (Mail.MIME_HTML.equals(mail.getMimeType())) {
        // 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(mail.getContent());
        htmlContent.append("\n</body>\n</html>");
        htmlPart.setContent(htmlContent.toString(), "text/html");
        htmlPart.setHeader("Content-Type", "text/html");
        htmlPart.setDisposition(Part.INLINE);
        content.addBodyPart(htmlPart);
    } else {
        log.warn("Email does not specify content MIME type");

        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    }

    for (Document doc : mail.getAttachments()) {
        InputStream is = null;
        FileOutputStream fos = null;
        String docName = PathUtils.getName(doc.getPath());

        try {
            is = OKMDocument.getInstance().getContent(token, doc.getPath(), false);
            File tmp = File.createTempFile("okm", ".tmp");
            fos = new FileOutputStream(tmp);
            IOUtils.copy(is, fos);
            fos.flush();

            // Document attachment part
            MimeBodyPart docPart = new MimeBodyPart();
            DataSource source = new FileDataSource(tmp.getPath());
            docPart.setDataHandler(new DataHandler(source));
            docPart.setFileName(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(mail.getSubject(), "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.UserManagementServiceAbstractTest.java

@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
//    @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);//from w  w w  .j  ava  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.xwiki.commons.internal.DefaultMailSender.java

private MimeBodyPart createAttachmentPart(Attachment attachment) {
    try {/*ww w. j  av  a 2s . c  om*/
        String name = attachment.getFilename();
        byte[] stream = attachment.getContent();
        File temp = File.createTempFile("tmpfile", ".tmp");
        FileOutputStream fos = new FileOutputStream(temp);
        fos.write(stream);
        fos.close();
        DataSource source = new FileDataSource(temp);
        MimeBodyPart part = new MimeBodyPart();
        String mimeType = MimeTypesUtil.getMimeTypeFromFilename(name);

        part.setDataHandler(new DataHandler(source));
        part.setHeader("Content-Type", mimeType);
        part.setFileName(name);
        part.setContentID("<" + name + ">");
        part.setDisposition("inline");

        temp.deleteOnExit();
        return part;
    } catch (Exception e) {
        return new MimeBodyPart();
    }
}

From source file:com.aipo.social.opensocial.spi.AipoStorageService.java

@Override
public String getContentType(String filePath, SecurityToken paramSecurityToken)
        throws ProtocolException, FileNotFoundException {
    String contenType = null;/*from  w  w w  .  j  a va  2s. co  m*/
    File file = new File(filePath);
    DataHandler hData = new DataHandler(new FileDataSource(file));

    if (hData != null) {
        contenType = hData.getContentType();
    }
    return contenType;
}