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.apache.padaf.preflight.Benchmark.java

/**
 * @param args/*from w w  w .j av a  2 s.  c  o m*/
 */
public static void main(String[] args) throws Exception {
    if (args.length < 3) {
        System.err.println("Usage : Benchmark loop resultFile <file1 ... filen|dir>");
        System.exit(255);
    }

    Integer loop = Integer.parseInt(args[0]);
    FileWriter resFile = new FileWriter(new File(args[1]));

    List<File> lfd = new ArrayList<File>();
    for (int i = 2; i < args.length; ++i) {
        File fi = new File(args[i]);
        if (fi.isDirectory()) {
            Collection<File> cf = FileUtils.listFiles(fi, null, true); // Get All files contained by the dir
            lfd.addAll(cf);
        } else {
            lfd.add(fi);
        }
    }

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.Z");

    PdfAValidator validator = new PdfAValidatorFactory()
            .createValidatorInstance(PdfAValidatorFactory.PDF_A_1_b);
    long startGTime = System.currentTimeMillis();

    int size = lfd.size();
    for (int i = 0; i < loop; i++) {
        File file = lfd.get(i % size);
        long startLTime = System.currentTimeMillis();
        ValidationResult result = validator.validate(new FileDataSource(file));
        if (!result.isValid()) {
            resFile.write(file.getAbsolutePath() + " isn't PDF/A\n");
            for (ValidationError error : result.getErrorsList()) {
                resFile.write(error.getErrorCode() + " : " + error.getDetails() + "\n");
            }
        }
        result.closePdf();
        long endLTime = System.currentTimeMillis();
        resFile.write(file.getName() + " (ms) : " + (endLTime - startLTime) + "\n");
        resFile.flush();
    }

    long endGTime = System.currentTimeMillis();

    resFile.write("Start : " + sdf.format(new Date(startGTime)) + "\n");
    resFile.write("End : " + sdf.format(new Date(endGTime)) + "\n");
    resFile.write("Duration (ms) : " + (endGTime - startGTime) + "\n");
    resFile.write("Average (ms) : " + (int) ((endGTime - startGTime) / loop) + "\n");

    System.out.println("Start : " + sdf.format(new Date(startGTime)));
    System.out.println("End : " + sdf.format(new Date(endGTime)));
    System.out.println("Duration (ms) : " + (endGTime - startGTime));
    System.out.println("Average (ms) : " + (int) ((endGTime - startGTime) / loop));
    resFile.flush();
    IOUtils.closeQuietly(resFile);
}

From source file:sendfile.java

public static void main(String[] args) {
    if (args.length != 5) {
        System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false");
        System.exit(1);//from  w  w  w.j  a  v  a  2s .c  o  m
    }

    String to = args[0];
    String from = args[1];
    String host = args[2];
    String filename = args[3];
    boolean debug = Boolean.valueOf(args[4]).booleanValue();
    String msgText1 = "Sending a file.\n";
    String subject = "Sending a file";

    // create some properties and get the default Session
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(subject);

        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(msgText1);

        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(filename);
        mbp2.setDataHandler(new DataHandler(fds));
        mbp2.setFileName(fds.getName());

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);

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

        // set the Date: header
        msg.setSentDate(new Date());

        // send the message
        Transport.send(msg);

    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
}

From source file:org.apache.pdfbox.preflight.Validator_A1b.java

public static void main(String[] args) throws IOException, TransformerException, ParserConfigurationException {
    if (args.length == 0) {
        usage();/*from   ww w. j av a2  s . c o  m*/
        System.exit(1);
    }

    // is output xml ?
    int posFile = 0;
    boolean outputXml = "xml".equals(args[posFile]);
    posFile += outputXml ? 1 : 0;
    // list
    boolean isGroup = "group".equals(args[posFile]);
    posFile += isGroup ? 1 : 0;
    // list
    boolean isBatch = "batch".equals(args[posFile]);
    posFile += isBatch ? 1 : 0;

    if (isGroup || isBatch) {
        // prepare the list
        List<File> ftp = listFiles(args[posFile]);
        int status = 0;
        if (!outputXml) {
            // simple list of files
            for (File file2 : ftp) {
                status |= runSimple(file2);
            }
            System.exit(status);
        } else {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            XmlResultParser xrp = new XmlResultParser();
            if (isGroup) {
                Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                Element root = document.createElement("preflights");
                document.appendChild(root);
                root.setAttribute("count", String.format("%d", ftp.size()));
                for (File file : ftp) {
                    Element result = xrp.validate(document, new FileDataSource(file));
                    root.appendChild(result);
                }
                transformer.transform(new DOMSource(document),
                        new StreamResult(new File(args[posFile] + ".preflight.xml")));
            } else {
                // isBatch
                for (File file : ftp) {
                    Element result = xrp.validate(new FileDataSource(file));
                    Document document = result.getOwnerDocument();
                    document.appendChild(result);
                    transformer.transform(new DOMSource(document),
                            new StreamResult(new File(file.getAbsolutePath() + ".preflight.xml")));
                }
            }
        }
    } else {
        if (!outputXml) {
            // simple validation 
            System.exit(runSimple(new File(args[posFile])));
        } else {
            // generate xml output
            XmlResultParser xrp = new XmlResultParser();
            Element result = xrp.validate(new FileDataSource(args[posFile]));
            Document document = result.getOwnerDocument();
            document.appendChild(result);
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            transformer.transform(new DOMSource(document), new StreamResult(System.out));
        }
    }

}

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

public StoredVMailMessageImpl(VMailBoxNode vmailBox, File messageFile, String senderPhoneNumber,
        Date messageDate) {/*from   w w w  . ja  v  a2  s.  c  o  m*/
    super(senderPhoneNumber, messageDate, new FileDataSource(messageFile));
    this.vmailBox = vmailBox;
    this.messageFile = messageFile;
}

From source file:org.pentaho.platform.repository2.unified.webservices.jaxws.SimpleRepositoryFileDataDto.java

/**
 * Converts SimpleRepositoryFileData to SimpleRepositoryFileDataDto. Does not use ByteArrayDataSource since that
 * implementation reads the entire stream into a byte array.
 *//*from ww  w  .  j a  v  a  2 s . co m*/
public static SimpleRepositoryFileDataDto convert(final SimpleRepositoryFileData simpleData) {
    FileOutputStream fout = null;
    boolean foutClosed = false;
    try {
        SimpleRepositoryFileDataDto simpleJaxWsData = new SimpleRepositoryFileDataDto();
        File tmpFile = File.createTempFile("pentaho-ws", null); //$NON-NLS-1$
        // TODO mlowery this might not delete files soon enough
        tmpFile.deleteOnExit();
        fout = FileUtils.openOutputStream(tmpFile);
        IOUtils.copy(simpleData.getStream(), fout);
        fout.close();
        foutClosed = true;
        simpleJaxWsData.dataHandler = new DataHandler(new FileDataSource(tmpFile));
        simpleJaxWsData.encoding = simpleData.getEncoding();
        simpleJaxWsData.mimeType = simpleData.getMimeType();
        return simpleJaxWsData;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (fout != null && !foutClosed) {
                fout.close();
            }
        } catch (Exception e) {
            // CHECKSTYLES IGNORE
        }
    }
}

From source file:org.ojbc.util.camel.processor.FileAttachmentProcessor.java

@Override
public void process(Exchange exchange) throws Exception {
    String currentXMLFilePath = (String) exchange.getProperty("currentXMLFilePath");
    log.debug("Attaching file.");
    log.debug("currentXMLFilePath=[" + currentXMLFilePath + "]");
    exchange.getIn().addAttachment("Bad.xml",
            new DataHandler(new FileDataSource(new File(currentXMLFilePath))));
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void sendGRUP(String from, String password, String bcc, String sub, String msg, String filename)
        throws Exception {
    //Get properties object    
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, password);
        }/*from   w  ww.j  av a  2 s. c o  m*/
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        //message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc));

        message.setSubject(sub);
        message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automat");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        //message.setContent(multipart);
        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File(filename)), writer);

        message.setContent(writer.toString(), "text/html");

        //send message  
        Transport.send(message);
        System.out.println("message sent successfully");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.apachecon.memories.hippocampus.MailConnectionTest.java

@Test
public void testMailEndpoint() throws Exception {
    Mailbox.clearAll();/*from   www.  j av  a2  s.com*/

    Endpoint endpoint = context.getEndpoint("{{mbox.smtp}}");
    assertNotNull(endpoint);

    Exchange ex1 = endpoint.createExchange();
    Message in = ex1.getIn();
    in.setBody("Hello World");
    in.addAttachment("feather-small.gif",
            new DataHandler(new FileDataSource("src/test/resources/img/feather-small.gif")));
    in.addAttachment("talend-logo",
            new DataHandler(new FileDataSource("src/test/resources/img/talend-logo.jpg")));

    Exchange ex2 = endpoint.createExchange();
    ex2.getIn().setBody("Bye World... without attachments");

    Producer producer = endpoint.createProducer();
    producer.start();
    producer.process(ex1);
    producer.process(ex2);
    producer.stop();
    Thread.sleep(5000);

    Endpoint target = context.getEndpoint("{{mail.target}}");
    if (target instanceof MockEndpoint) {
        MockEndpoint mock = (MockEndpoint) target;

        mock.expectedMessageCount(2);
        mock.assertIsSatisfied();

        assertTrue(mock.assertExchangeReceived(0).getIn().getBody() instanceof DataHandler);
        assertTrue(mock.assertExchangeReceived(1).getIn().getBody() instanceof DataHandler);
    }
}

From source file:org.wso2.carbon.appfactory.tenant.build.integration.uploder.DirectUploader.java

private static WebappUploadData getWebAppUploadDataItem(File fileToDeploy) {
    DataHandler dataHandler = new DataHandler(new FileDataSource(fileToDeploy));

    WebappUploadData webappUploadData = new WebappUploadData();
    webappUploadData.setDataHandler(dataHandler);
    webappUploadData.setFileName(fileToDeploy.getName());
    return webappUploadData;
}

From source file:org.apache.camel.component.mail.MailSplitAttachmentsTest.java

@Before
public void setup() {
    // create the exchange with the mail message that is multipart with a file and a Hello World text/plain message.
    endpoint = context.getEndpoint("smtp://james@mymailserver.com?password=secret");
    exchange = endpoint.createExchange();
    Message in = exchange.getIn();// ww  w  .  j av  a2 s  . co  m
    in.setBody("Hello World");
    in.addAttachment("logo.jpeg", new DataHandler(new FileDataSource("src/test/data/logo.jpeg")));
    in.addAttachment("license.txt",
            new DataHandler(new FileDataSource("src/main/resources/META-INF/LICENSE.txt")));
}