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:de.extra_standard.namespace.webservice.ExtraServiceImpl.java

@Override
@WebMethod(action = "http://www.extra-standard.de/namespace/webservice/execute")
@WebResult(name = "Transport", targetNamespace = "http://www.extra-standard.de/namespace/response/1", partName = "response")
public ResponseTransport execute(
        @WebParam(name = "Transport", targetNamespace = "http://www.extra-standard.de/namespace/request/1", partName = "request") final de.drv.dsrv.extrastandard.namespace.request.RequestTransport request)
        throws ExtraFault {
    try {/*from   ww  w.  j a  va2 s  .c  om*/
        logger.info("receive Extra ResponseTransport");
        final Base64CharSequenceType base64CharSequence = request.getTransportBody().getData()
                .getBase64CharSequence();
        final DataHandler dataHandler = base64CharSequence.getValue();
        final InputStream inputStream = dataHandler.getInputStream();
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        final String dateSuffix = sdf.format(new Date(System.currentTimeMillis()));
        final String dataHandlerName = dataHandler.getName();
        logger.info("Receiving File : " + dataHandlerName);
        final File receivedFile = new File(outputDirectory, dataHandlerName + "_" + dateSuffix);
        final FileOutputStream fileOutputStream = new FileOutputStream(receivedFile);
        IOUtils.copyLarge(inputStream, fileOutputStream);
        logger.info("Input file is stored under " + receivedFile.getAbsolutePath());
        logger.info("ChecksumCRC32 " + FileUtils.checksumCRC32(receivedFile));
        logger.info("Filesize: " + FileUtils.sizeOf(receivedFile));
    } catch (final IOException e) {
        logger.error("IOException in Server:", e);
    }
    // TODO TestTransport erzeugen!!
    final ResponseTransport responseTransport = new ResponseTransport();
    final ResponseTransportBody responseTransportBody = new ResponseTransportBody();
    final DataType dataType = new DataType();
    final Base64CharSequenceType base64CharSequenceType = new Base64CharSequenceType();
    final DataSource ds = new FileDataSource(testDataFile);
    final DataHandler dataHandler = new DataHandler(ds);
    base64CharSequenceType.setValue(dataHandler);
    dataType.setBase64CharSequence(base64CharSequenceType);
    responseTransportBody.setData(dataType);
    responseTransport.setTransportBody(responseTransportBody);
    return responseTransport;
}

From source file:org.chenillekit.mail.services.TestMailService.java

@Test
public void send_plaintext_datasourceattachment_mail() throws URISyntaxException {
    MailMessageHeaders headers = new MailMessageHeaders();

    headers.setFrom("sender@example.com");
    headers.addTo("receiver@example.com");

    FileDataSource file = new FileDataSource(new File(new ClasspathResource("dummy.txt").toURL().toURI()));

    MailService mailService = registry.getService(MailService.class);
    boolean sended = mailService.sendPlainTextMail(headers, "THIS IS THE BODY", file);

    assertTrue(sended, "sended");
}

From source file:org.openiam.idm.srvc.msg.service.MailSenderClient.java

public void send(Message msg) {
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.transport.protocol", "smtp");

    if (username != null && !username.isEmpty()) {
        properties.setProperty("mail.user", username);
        properties.setProperty("mail.password", password);
    }// w  w w . j a v a  2  s. co  m

    if (port != null && !port.isEmpty()) {
        properties.setProperty("mail.smtp.port", port);
    }

    Session session = Session.getDefaultInstance(properties);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(msg.getFrom());
        if (msg.getTo().size() > 1) {
            List<InternetAddress> addresses = msg.getTo();
            message.addRecipients(TO, addresses.toArray(new Address[addresses.size()]));
        } else {
            message.addRecipient(TO, msg.getTo().get(0));
        }
        if (msg.getBcc() != null && msg.getBcc().size() != 0) {
            if (msg.getTo().size() > 1) {
                List<InternetAddress> addresses = msg.getBcc();
                message.addRecipients(BCC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(TO, msg.getBcc().get(0));
            }
        }
        if (msg.getCc() != null && msg.getCc().size() > 0) {
            if (msg.getCc().size() > 1) {
                List<InternetAddress> addresses = msg.getCc();
                message.addRecipients(CC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(CC, msg.getCc().get(0));
            }
        }
        message.setSubject(msg.getSubject(), "UTF-8");
        MimeBodyPart mbp1 = new MimeBodyPart();
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();

        if (msg.getBodyType() == Message.BodyType.HTML_TEXT) {
            mbp1.setContent(msg.getBody(), "text/html");
        } else {
            mbp1.setText(msg.getBody(), "UTF-8");
        }
        if (port != null && !port.isEmpty()) {
            properties.setProperty("mail.smtp.port", port);
        }
        mp.addBodyPart(mbp1);
        if (msg.getAttachments().size() > 0) {
            for (String fileName : msg.getAttachments()) {
                // create the second message part
                MimeBodyPart mbpFile = new MimeBodyPart();
                // attach the file to the message
                FileDataSource fds = new FileDataSource(fileName);
                mbpFile.setDataHandler(new DataHandler(fds));
                mbpFile.setFileName(fds.getName());

                mp.addBodyPart(mbpFile);
            }
        }
        // add the Multipart to the message
        message.setContent(mp);

        if (username != null && !username.isEmpty()) {
            properties.setProperty("mail.user", username);
            properties.setProperty("mail.password", password);
            properties.put("mail.smtp.auth", auth);
            properties.put("mail.smtp.starttls.enable", starttls);
            Transport mailTransport = session.getTransport();
            mailTransport.connect(host, username, password);
            mailTransport.sendMessage(message, message.getAllRecipients());

        } else {
            Transport.send(message);
            log.debug("Message successfully sent.");
        }
    } catch (Throwable e) {
        log.error("Exception while sending mail", e);
    }
}

From source file:ebay.dts.client.FileTransferActions.java

public UploadFileResponse uploadFile2(String xmlFile, String jobId, String fileReferenceId)
        throws EbayConnectorException {

    String callName = "uploadFile";
    UploadFileResponse response = null;// ww w. j  a v  a 2 s  . c  o  m
    File fileToUpload = null;

    try {

        String compressedFileName = compressFileToGzip(xmlFile);
        if (compressedFileName == null) {
            logger.error("Failed to compress your XML file into gzip file. Aborted.");
            return null;
        }
        FileTransferServicePort port = call.setFTSMessageContext(callName);
        UploadFileRequest request = new UploadFileRequest();
        FileAttachment attachment = new FileAttachment();
        fileToUpload = new File(compressedFileName);
        DataHandler dh = new DataHandler(new FileDataSource(fileToUpload));
        attachment.setData(dh);
        attachment.setSize(fileToUpload.length());
        String fileFormat = "gzip";
        request.setFileFormat(fileFormat);
        /*
         * For instance, the Bulk Data Exchange Service uses a job ID as a
         * primary identifier, so, if you're using the Bulk Data Exchange
         * Service, enter the job ID as the taskReferenceId.
         */

        request.setTaskReferenceId(jobId);
        request.setFileReferenceId(fileReferenceId);
        request.setFileAttachment(attachment);
        // request.
        if (port != null && request != null) {
            response = port.uploadFile(request);
        }

        return response;

    } catch (Exception e) {
        logger.error(e.getMessage());
        throw new EbayConnectorException(e.getMessage(), e);
    } finally {
        if (fileToUpload != null && fileToUpload.exists()) {
            fileToUpload.delete();
        }
    }

}

From source file:com.tdclighthouse.commons.mail.util.MailClient.java

protected void addAtachments(String[] attachments, Multipart multipart)
        throws MessagingException, AddressException {
    for (int i = 0; i < attachments.length; i++) {
        String filename = attachments[i];
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();

        // use a JAF FileDataSource as it does MIME type detection
        DataSource source = new FileDataSource(filename);
        attachmentBodyPart.setDataHandler(new DataHandler(source));

        // assume that the filename you want to send is the same as the
        // actual file name - could alter this to remove the file path
        attachmentBodyPart.setFileName(filename);

        // add the attachment
        multipart.addBodyPart(attachmentBodyPart);
    }/*from  ww w.j  av  a 2 s.co  m*/
}

From source file:com.tangfan.test.UserServiceTest.java

/**
 * testBinary webservice?/*  w w  w.  jav  a2 s.co m*/
 */
@Test
public void testBinary() {
    DataHandler file = new DataHandler(
            new FileDataSource(new File("C:/Users/Administrator/Pictures/QQ20150206132707.jpg")));
    port.binary(file);
}

From source file:org.apache.axis2.swa.EchoRawSwATest.java

public void testEchoXMLSync() throws Exception {

    Options options = new Options();
    options.setTo(targetEPR);/*from  w  w w .j  a  v  a  2 s.co  m*/
    options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);
    options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
    options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    options.setTimeOutInMilliSeconds(100000);
    options.setAction(Constants.AXIS2_NAMESPACE_URI + "/" + operationName.getLocalPart());
    options.setTo(targetEPR);

    ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
            TestingUtils.prefixBaseDirectory("target/test-resources/integrationRepo"), null);

    ServiceClient sender = new ServiceClient(configContext, null);
    sender.setOptions(options);
    OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);

    MessageContext mc = new MessageContext();
    mc.setEnvelope(createEnvelope());
    FileDataSource fileDataSource = new FileDataSource(
            TestingUtils.prefixBaseDirectory("test-resources/mtom/test.jpg"));
    DataHandler dataHandler = new DataHandler(fileDataSource);
    mc.addAttachment("FirstAttachment", dataHandler);

    mepClient.addMessageContext(mc);
    mepClient.execute(true);
    MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
    DataHandler dataHandler2 = response.getAttachment("FirstAttachment");
    assertNotNull(dataHandler);
    compareDataHandlers(dataHandler, dataHandler2);
}

From source file:com.warsaw.data.controller.LoginController.java

private Message buildEmail(Session session, String to) throws Exception {
    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(EMAIL));

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

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

    // This mail has 2 part, the BODY and the embedded image
    MimeMultipart multipart = new MimeMultipart("related");

    // first part (the html)
    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<img style='width:800px' src=\"cid:image1\"><br/>" + "Dzie dobry,<br/><br/>"
            + "witamy na portalu TrasyPoWarszawsku.pl, na ktrym zostalo "
            + "zaoone konto<br/> dla osoby o danych: Jan Marian Ptak. W celu zakoczenia procesu tworzenia "
            + "konta prosimy uy linku aktywacyjnego:<br/><br/>"
            + "<a href='https://test.puesc.gov.pl?link=Gkhh&%JK.'>https://test.puesc.gov.pl?link=Gkhh&%JK.</a><br/><br/>"
            + "Na wywietlonym ekranie prosz wprowadzi zdefiniowane przez siebie haso awaryjne. Po prawidowym"
            + " wprowadzeniu danych<br/> oraz  ustawieniu nowego  hasa dostpowego  konto  na portalu PUESC zostanie aktywowane.<br/>"
            + "Link aktywacyjny pozostanie wany przez 24 godziny od momentu  otrzymania niniejszej wiadomoci.<br/><br/>"
            + "<img style='width:800px' src=\"cid:image2\"><br/><br/>" + "Z powaaniem<br/><br/>"
            + "Zesp portalu PUESC<br/>" + "puesc@mofnet.gov.pl<br/>"
            + "<a href='http://puesc.gov.pl'>http://puesc.gov.pl</a>";

    messageBodyPart.setContent(htmlText, "text/html; charset=ISO-8859-2");
    // add it// w ww. ja  va  2  s. c  om
    multipart.addBodyPart(messageBodyPart);

    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource("C:\\Users\\Pawel\\Desktop\\header.png");

    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image1>");

    // add image to the multipart
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    //  URL url = new URL("http://ns3342351.ovh.net:8080/seap_lf_graphicsLayout_theme/images/refresh.png");
    // URLDataSource fds1 =new URLDataSource(url);
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image2>");
    multipart.addBodyPart(messageBodyPart);

    // put everything together
    message.setContent(multipart);

    ByteArrayOutputStream b = new ByteArrayOutputStream();
    try {
        message.writeTo(b);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return message;
}

From source file:org.xwiki.mail.internal.AttachmentMimeBodyPartFactory.java

private DataSource createTemporaryAttachmentDataSource(Attachment attachment) throws MessagingException {
    File temporaryAttachmentFile;
    FileOutputStream fos = null;//from ww  w .  java 2 s  . co m
    try {
        temporaryAttachmentFile = File.createTempFile("attachment", ".tmp", this.temporaryDirectory);
        temporaryAttachmentFile.deleteOnExit();
        fos = new FileOutputStream(temporaryAttachmentFile);
        fos.write(attachment.getContent());
    } catch (Exception e) {
        throw new MessagingException(
                String.format("Failed to save attachment [%s] to the file system", attachment.getFilename()),
                e);
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            // Only an error at closing, we continue
            this.logger.warn("Failed to close the temporary file attachment when sending an email. "
                    + "Root reason: [{}]", ExceptionUtils.getRootCauseMessage(e));
        }
    }
    return new FileDataSource(temporaryAttachmentFile);
}

From source file:org.wso2.carbon.humantask.ui.fileupload.HumanTaskUploadExecutor.java

public boolean execute(HttpServletRequest request, HttpServletResponse response)
        throws CarbonException, IOException {
    String errMsg;/* w ww.j av  a  2s . 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;
    }
    HIUploaderClient uploaderClient = new HIUploaderClient(configurationContext,
            serverURL + HumanTaskUIConstants.SERVICE_NAMES.HUMANTASK_UPLOADER_SERVICE_NAME, cookie);

    try {

        for (FileItemData fieldData : fileItemsMap.get("humantaskFileName")) {
            String fileName = getFileName(fieldData.getFileItem().getName());
            //Check filename for \ charactors. This cannot be handled at the lower stages.
            if (fileName.matches("(.*[\\\\].*[/].*|.*[/].*[\\\\].*)")) {
                log.error(
                        "HumanTask Package Validation Failure: one or many of the following illegal characters are in "
                                + "the package.\n ~!@#$;%^*()+={}[]| \\<>");
                throw new Exception(
                        "HumanTask Package Validation Failure: one or many 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 ("humantaskFileName".equals(fieldData.getFileItem().getFieldName())) {
                SaveExtractReturn uploadedFiles = saveAndExtractUploadedFile(fieldData.getFileItem());

                validateHumanTaskPackage(uploadedFiles.extractedFile);
                DataSource dataSource = new FileDataSource(uploadedFiles.zipFile);
                uploaderClient.addUploadedFileItem(new DataHandler(dataSource), fileName, "zip");
            }
        }

        uploaderClient.uploadFileItems();

        String msg = "Your HumanTask package been uploaded successfully. Please refresh this page in a"
                + " while to see the status of the new package.";
        CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.INFO, request, response,
                getContextRoot(request) + "/" + webContext + HumanTaskUIConstants.PAGES.PACKAGE_LIST_PAGE);

        return true;
    } catch (Exception e) {
        errMsg = "File upload failed :" + e.getMessage();
        log.error(errMsg, e);
        // Removing <, > and </ characters from Error message, in order to provide accurate error message.
        // TODO : FIX this correctly. Identify why latest browsers unable to render HTML encoded string. Eg: &lt; with <
        String encodedErrMsg = errMsg.replace("</", " ").replace(">", " ").replace("<", " ");
        CarbonUIMessage.sendCarbonUIMessage(encodedErrMsg, CarbonUIMessage.ERROR, request, response,
                getContextRoot(request) + "/" + webContext + HumanTaskUIConstants.PAGES.UPLOAD_PAGE);
    }

    return false;
}