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:test.saaj.TestAttachmentSerialization.java

public int saveMsgWithAttachments(OutputStream os) throws Exception {
    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage msg = mf.createMessage();

    SOAPPart sp = msg.getSOAPPart();
    SOAPEnvelope envelope = sp.getEnvelope();
    SOAPHeader header = envelope.getHeader();
    SOAPBody body = envelope.getBody();

    SOAPElement el = header.addHeaderElement(envelope.createName("field4", NS_PREFIX, NS_URI));
    SOAPElement el2 = el.addChildElement("field4b", NS_PREFIX);
    SOAPElement el3 = el2.addTextNode("field4value");

    el = body.addBodyElement(envelope.createName("bodyfield3", NS_PREFIX, NS_URI));
    el2 = el.addChildElement("bodyfield3a", NS_PREFIX);
    el2.addTextNode("bodyvalue3a");
    el2 = el.addChildElement("bodyfield3b", NS_PREFIX);
    el2.addTextNode("bodyvalue3b");
    el2 = el.addChildElement("datefield", NS_PREFIX);

    AttachmentPart ap = msg.createAttachmentPart();
    ap.setContent("some attachment text...", "text/plain");
    msg.addAttachmentPart(ap);/*  w ww  . j  a va2  s  .  c o  m*/

    String jpgfilename = "docs/images/axis.jpg";
    File myfile = new File(jpgfilename);
    FileDataSource fds = new FileDataSource(myfile);
    DataHandler dh = new DataHandler(fds);
    AttachmentPart ap2 = msg.createAttachmentPart(dh);
    ap2.setContentType("image/jpg");
    msg.addAttachmentPart(ap2);

    // Test for Bug #17664
    if (msg.saveRequired()) {
        msg.saveChanges();
    }
    MimeHeaders headers = msg.getMimeHeaders();
    assertTrue(headers != null);
    String[] contentType = headers.getHeader("Content-Type");
    assertTrue(contentType != null);

    msg.writeTo(os);
    os.flush();
    return msg.countAttachments();
}

From source file:edu.harvard.i2b2.fr.ws.FileRepositoryService.java

public OMElement recvfileRequest(OMElement request) {
    LoaderQueryRequestDelegate queryDelegate = new LoaderQueryRequestDelegate();
    OMElement responseElement = null;/*from   w  ww . j  a va2s  .  com*/

    FileDataSource fileDataSource;
    DataHandler fileDataHandler;

    try {
        String requestXml = request.toString();
        if (requestXml.indexOf("<soapenv:Body>") > -1) {
            requestXml = requestXml.substring(requestXml.indexOf("<soapenv:Body>") + 14,
                    requestXml.indexOf("</soapenv:Body>"));
        }
        RecvfileRequestHandler handler = new RecvfileRequestHandler(requestXml);
        String response = queryDelegate.handleRequest(requestXml, handler);

        String filename = handler.getFilename();
        // We can obtain the request (incoming) MessageContext as follows
        MessageContext inMessageContext = MessageContext.getCurrentMessageContext();
        // We can obtain the operation context from the request message
        // context
        OperationContext operationContext = inMessageContext.getOperationContext();
        MessageContext outMessageContext = operationContext
                .getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
        outMessageContext.setDoingSwA(true);
        outMessageContext.setDoingREST(false);
        if (!filename.equals("")) {
            fileDataSource = new FileDataSource(filename);
            fileDataHandler = new DataHandler(fileDataSource);
            // use requested filename as content ID
            outMessageContext.addAttachment(handler.getRequestedFilename(), fileDataHandler);
            outMessageContext.setDoingMTOM(false);
            outMessageContext.setDoingSwA(true);
            responseElement = buildOMElementFromString(response, fileDataHandler.getName());
        } else {
            log.error("where did the file go? ");
        }
    } catch (XMLStreamException e) {
        log.error("xml stream exception", e);
    } catch (I2B2Exception e) {
        log.error("i2b2 exception", e);
    } catch (Throwable e) {
        log.error("Throwable", e);
    }
    return responseElement;
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailSephoraPassed(String adresaSephora, String from, String grupTestContent,
        String grupSephora, String subject, String filename) throws FileNotFoundException, IOException {

    //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, "anda.cristea");
        }//from   ww w.  j  av a  2s  .  co m
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(grupTestContent));
        message.addRecipient(Message.RecipientType.BCC, new InternetAddress(grupSephora));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        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);

        //send message  
        Transport.send(message);
        //  System.out.println("message sent successfully");
    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}

From source file:de.cosmocode.palava.services.mail.EmailFactory.java

@SuppressWarnings("unchecked")
Email build(Document document, Embedder embed) throws EmailException, FileNotFoundException {
    /* CHECKSTYLE:ON */

    final Element root = document.getRootElement();

    final List<Element> messages = root.getChildren("message");
    if (messages.isEmpty())
        throw new IllegalArgumentException("No messages found");

    final List<Element> attachments = root.getChildren("attachment");

    final Map<ContentType, String> available = new HashMap<ContentType, String>();

    for (Element element : messages) {
        final String type = element.getAttributeValue("type");
        final ContentType messageType = StringUtils.equals(type, "html") ? ContentType.HTML : ContentType.PLAIN;
        if (available.containsKey(messageType)) {
            throw new IllegalArgumentException("Two messages with the same types have been defined.");
        }//w w w.j  a  v  a  2s  .  c  o  m
        available.put(messageType, element.getText());
    }

    final Email email;

    if (available.containsKey(ContentType.HTML) || attachments.size() > 0) {
        final HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setCharset(CHARSET);

        if (embed.hasEmbeddings()) {
            htmlEmail.setSubType("related");
        } else if (attachments.size() > 0) {
            htmlEmail.setSubType("related");
        } else {
            htmlEmail.setSubType("alternative");
        }

        /**
         * Add html message
         */
        if (available.containsKey(ContentType.HTML)) {
            htmlEmail.setHtmlMsg(available.get(ContentType.HTML));
        }

        /**
         * Add plain text alternative
         */
        if (available.containsKey(ContentType.PLAIN)) {
            htmlEmail.setTextMsg(available.get(ContentType.PLAIN));
        }

        /**
         * Embedded binary data
         */
        for (Map.Entry<String, String> entry : embed.getEmbeddings().entrySet()) {
            final String path = entry.getKey();
            final String cid = entry.getValue();
            final String name = embed.name(path);

            final File file;

            if (path.startsWith(File.separator)) {
                file = new File(path);
            } else {
                file = new File(embed.getResourcePath(), path);
            }

            if (file.exists()) {
                htmlEmail.embed(new FileDataSource(file), name, cid);
            } else {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
        }

        /**
         * Attached binary data
         */
        for (Element attachment : attachments) {
            final String name = attachment.getAttributeValue("name", "");
            final String description = attachment.getAttributeValue("description", "");
            final String path = attachment.getAttributeValue("path");

            if (path == null)
                throw new IllegalArgumentException("Attachment path was not set");
            File file = new File(path);

            if (!file.exists())
                file = new File(embed.getResourcePath(), path);

            if (file.exists()) {
                htmlEmail.attach(new FileDataSource(file), name, description);
            } else {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
        }

        email = htmlEmail;
    } else if (available.containsKey(ContentType.PLAIN)) {
        email = new SimpleEmail();
        email.setCharset(CHARSET);
        email.setMsg(available.get(ContentType.PLAIN));
    } else {
        throw new IllegalArgumentException("No valid message found in template.");
    }

    final String subject = root.getChildText("subject");
    email.setSubject(subject);

    final Element from = root.getChild("from");
    final String fromAddress = from == null ? null : from.getText();
    final String fromName = from == null ? fromAddress : from.getAttributeValue("name", fromAddress);
    email.setFrom(fromAddress, fromName);

    final Element to = root.getChild("to");
    if (to != null) {
        final String toAddress = to.getText();
        if (StringUtils.isNotBlank(toAddress) && toAddress.contains(EMAIL_SEPARATOR)) {
            final String[] toAddresses = toAddress.split(EMAIL_SEPARATOR);
            for (String address : toAddresses) {
                email.addTo(address);
            }
        } else if (StringUtils.isNotBlank(toAddress)) {
            final String toName = to.getAttributeValue("name", toAddress);
            email.addTo(toAddress, toName);
        }
    }

    final Element cc = root.getChild("cc");
    if (cc != null) {
        final String ccAddress = cc.getText();
        if (StringUtils.isNotBlank(ccAddress) && ccAddress.contains(EMAIL_SEPARATOR)) {
            final String[] ccAddresses = ccAddress.split(EMAIL_SEPARATOR);
            for (String address : ccAddresses) {
                email.addCc(address);
            }
        } else if (StringUtils.isNotBlank(ccAddress)) {
            final String ccName = cc.getAttributeValue("name", ccAddress);
            email.addCc(ccAddress, ccName);
        }
    }

    final Element bcc = root.getChild("bcc");
    if (bcc != null) {
        final String bccAddress = bcc.getText();
        if (StringUtils.isNotBlank(bccAddress) && bccAddress.contains(EMAIL_SEPARATOR)) {
            final String[] bccAddresses = bccAddress.split(EMAIL_SEPARATOR);
            for (String address : bccAddresses) {
                email.addBcc(address);
            }
        } else if (StringUtils.isNotBlank(bccAddress)) {
            final String bccName = bcc.getAttributeValue("name", bccAddress);
            email.addBcc(bccAddress, bccName);
        }
    }

    final Element replyTo = root.getChild("replyTo");
    if (replyTo != null) {
        final String replyToAddress = replyTo.getText();
        if (StringUtils.isNotBlank(replyToAddress) && replyToAddress.contains(EMAIL_SEPARATOR)) {
            final String[] replyToAddresses = replyToAddress.split(EMAIL_SEPARATOR);
            for (String address : replyToAddresses) {
                email.addReplyTo(address);
            }
        } else if (StringUtils.isNotBlank(replyToAddress)) {
            final String replyToName = replyTo.getAttributeValue("name", replyToAddress);
            email.addReplyTo(replyToAddress, replyToName);
        }
    }

    return email;
}

From source file:com.clustercontrol.ws.cloud.CloudCommonEndpoint.java

/**
 * [Template] ?//from  w ww  .  ja  v  a2s .c o  m
 * 
 * HinemosAgentAccess???
 * 
 * @throws HinemosUnknown
 * @throws InvalidRole
 * @throws InvalidUserPass
 */
@XmlMimeType("application/octet-stream")
public DataHandler downloadScripts(String filename) throws InvalidUserPass, InvalidRole, HinemosUnknown {
    ArrayList<SystemPrivilegeInfo> systemPrivilegeList = new ArrayList<SystemPrivilegeInfo>();
    systemPrivilegeList
            .add(new SystemPrivilegeInfo(FunctionConstant.CLOUDMANAGEMENT, SystemPrivilegeMode.READ));
    HttpAuthenticator.authCheck(wsctx, systemPrivilegeList);

    String homeDir = System.getProperty("hinemos.manager.home.dir");
    String filepath = homeDir + "/var/cloud/" + filename;
    File file = new File(filepath);
    if (!file.exists()) {
        m_log.error("file not found : " + filepath);
        return null;
    }
    FileDataSource source = new FileDataSource(file);
    DataHandler dataHandler = new DataHandler(source);
    return dataHandler;
}

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

@Test
public void testExtractAttachments() throws Exception {

    // set the expression to extract the attachments as byte[]s
    splitAttachmentsExpression.setExtractAttachments(true);

    Producer producer = endpoint.createProducer();
    producer.start();/* w  w  w.j  a va  2s.co  m*/
    producer.process(exchange);

    Thread.sleep(2000);

    MockEndpoint mock = getMockEndpoint("mock:split");
    mock.expectedMessageCount(2);

    mock.assertIsSatisfied();

    Message first = mock.getReceivedExchanges().get(0).getIn();
    Message second = mock.getReceivedExchanges().get(1).getIn();

    // check it's no longer an attachment, but is the message body
    assertEquals(0, first.getAttachments().size());
    assertEquals(0, second.getAttachments().size());

    assertEquals("logo.jpeg", first.getHeader("CamelSplitAttachmentId"));
    assertEquals("license.txt", second.getHeader("CamelSplitAttachmentId"));

    byte[] expected1 = IOUtils.toByteArray(new FileDataSource("src/test/data/logo.jpeg").getInputStream());
    byte[] expected2 = IOUtils
            .toByteArray(new FileDataSource("src/main/resources/META-INF/LICENSE.txt").getInputStream());

    assertArrayEquals(expected1, (byte[]) first.getBody());
    assertArrayEquals(expected2, (byte[]) second.getBody());
}

From source file:org.apache.padaf.integration.TestValidFiles.java

@Test()
public void validate() throws Exception {
    if (path == null) {
        logger.warn("This is an empty test");
        return;//from w  w  w  .  j av a2  s . c om
    }
    ValidationResult result = null;
    try {
        FileDataSource bds = new FileDataSource(path);
        result = validator.validate(bds);
        Assert.assertFalse(path + " : Isartor file should be invalid (" + path + ")", result.isValid());
        Assert.assertTrue(path + " : Should find at least one error", result.getErrorsList().size() > 0);
        // could contain more than one error
        if (result.getErrorsList().size() > 0) {
            Assert.fail("File expected valid : " + path.getAbsolutePath());
        }
    } catch (ValidationException e) {
        throw new Exception(path + " :" + e.getMessage(), e);
    } finally {
        if (result != null) {
            result.closePdf();
        }
    }
}

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

@Test
public void saveNewMessageTest() throws Exception {
    Date date = new Date();
    vbox.addMessage(new NewVMailMessageImpl("123", "222", date, new FileDataSource(testFile)));

    vbox.getNewMessages().get(0).save();
    String filename = new SimpleDateFormat(VMailBoxNode.DATE_PATTERN).format(date) + "-" + "222.wav";
    File savedMessFile = new File(
            manager.getVMailBoxDir(vbox).getSavedMessagesDir() + File.separator + filename);
    assertTrue(savedMessFile.exists());//w ww  . ja  v a2s  . com
    assertTrue(FileUtils.contentEquals(testFile, savedMessFile));
    assertEquals(0, vbox.getNewMessagesCount());
    assertEquals(1, vbox.getSavedMessagesCount());
}

From source file:it.cnr.icar.eric.client.xml.registry.infomodel.ExtrinsicObjectImpl.java

public ExtrinsicObjectImpl(LifeCycleManagerImpl lcm, ExtrinsicObjectType ebExtrinsicObj) throws JAXRException {
    super(lcm, ebExtrinsicObj);

    mimeType = ebExtrinsicObj.getMimeType();
    opaque = ebExtrinsicObj.isIsOpaque();
    contentVersionInfo = ebExtrinsicObj.getContentVersionInfo();

    try {/* ww  w.  j  a  va 2 s .c  o m*/
        HashMap<String, Serializable> slotsMap = BindingUtility.getInstance()
                .getSlotsFromRegistryObject(ebExtrinsicObj);
        @SuppressWarnings("static-access")
        String slotName = BindingUtility.getInstance().CANONICAL_SLOT_EXTRINSIC_OBJECT_REPOSITORYITEM_URL;
        if (slotsMap.containsKey(slotName)) {
            String riURLStr = (String) slotsMap.get(slotName);
            File riFile = new File(riURLStr);
            repositoryItem = new DataHandler(new FileDataSource(riFile));

            //Remove transient slot
            this.removeSlot(slotName);
        }
    } catch (JAXBException e) {
        throw new JAXRException(e);
    }
}

From source file:org.wso2.carbon.event.simulator.ui.fileupload.CSVUploadExecutor.java

@Override
public boolean execute(HttpServletRequest request, HttpServletResponse response)
        throws CarbonException, IOException {
    String errMsg;//from w  w  w .  j a va  2  s .  c  o m

    response.setContentType("text/html; charset=utf-8");
    PrintWriter out = response.getWriter();
    String webContext = (String) request.getAttribute(CarbonConstants.WEB_CONTEXT);
    String serverURL = (String) request.getAttribute(CarbonConstants.SERVER_URL);
    String cookie = (String) request.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);

    Map<String, ArrayList<FileItemData>> fileItemsMap = getFileItemsMap();

    if (fileItemsMap == null || fileItemsMap.isEmpty()) {
        String msg = "File uploading failed.";
        log.error(msg);
        out.write("<textarea>" + "(function(){i18n.fileUplodedFailed();})();" + "</textarea>");
        return true;
    }

    CSVUploaderClient uploaderClient = new CSVUploaderClient(configurationContext,
            serverURL + "EventSimulatorAdminService.EventSimulatorAdminServiceHttpsSoap12Endpoint", cookie);

    File uploadedTempFile;
    try {
        for (FileItemData fileData : fileItemsMap.get("csvFileName")) {
            String fileName = getFileName(fileData.getFileItem().getName());

            //Check filename for \ charactors. This cannot be handled at the lower stages.
            if (fileName.matches("(.*[\\\\].*[/].*|.*[/].*[\\\\].*)")) {
                log.error("CSV file Validation Failure: one or more of the following illegal characters are in "
                        + "the package.\n ~!@#$;%^*()+={}[]| \\<>");
                throw new Exception(
                        "CSV file Validation Failure: one or more of the following illegal characters "
                                + "are in the package. ~!@#$;%^*()+={}[]| \\<>");
            }

            //Check file extension.
            checkServiceFileExtensionValidity(fileName, ALLOWED_FILE_EXTENSIONS);

            if (fileName.lastIndexOf('\\') != -1) {
                int indexOfColon = fileName.lastIndexOf('\\') + 1;
                fileName = fileName.substring(indexOfColon, fileName.length());
            }

            if (fileData.getFileItem().getFieldName().equals("csvFileName")) {
                EventSimulatorUIUtils.validatePath(fileName);
                uploadedTempFile = new File(CarbonUtils.getTmpDir(), fileName);
                fileData.getFileItem().write(uploadedTempFile);
                DataSource dataSource = new FileDataSource(uploadedTempFile);
                uploaderClient.addUploadedFileItem(new DataHandler(dataSource), fileName, "csv");
            }

        }

        uploaderClient.uploadFileItems();
        String msg = "Your CSV file has been uploaded successfully. Please refresh this page to configure and play the file";

        CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.INFO, request, response,
                getContextRoot(request) + "/" + webContext + "/eventsimulator/index.jsp");

        return true;

    } catch (Exception e) {
        errMsg = "File upload failed :" + e.getMessage();
        log.error(errMsg, e);
        CarbonUIMessage.sendCarbonUIMessage(errMsg, CarbonUIMessage.ERROR, request, response,
                getContextRoot(request) + "/" + webContext + "/eventsimulator/index.jsp");
    }

    return false;
}