Example usage for javax.activation DataHandler DataHandler

List of usage examples for javax.activation DataHandler DataHandler

Introduction

In this page you can find the example usage for javax.activation DataHandler DataHandler.

Prototype

public DataHandler(URL url) 

Source Link

Document

Create a DataHandler instance referencing a URL.

Usage

From source file:org.olat.modules.vitero.manager.ViteroManager.java

protected boolean storePortrait(Identity identity, int userId) throws VmsNotAvailableException {
    try {/*  ww  w . jav a  2 s. c o m*/
        File portrait = DisplayPortraitManager.getInstance().getBigPortrait(identity.getName());
        if (portrait != null && portrait.exists()) {
            Mtom mtomWs = getMtomWebService();

            CompleteAvatarWrapper avatar = new CompleteAvatarWrapper();

            avatar.setType(BigInteger.ZERO);
            avatar.setUserid(BigInteger.valueOf(userId));
            avatar.setFilename(portrait.getName());

            DataHandler portraitHandler = new DataHandler(new FileDataSource(portrait));
            avatar.setFile(portraitHandler);

            mtomWs.storeAvatar(avatar);
            return true;
        }
        return false;
    } catch (SOAPFaultException f) {
        ErrorCode code = handleAxisFault(f);
        switch (code) {
        default:
            logAxisError("Cannot store the portrait of " + userId, f);
        }
        return false;
    } catch (WebServiceException e) {
        if (e.getCause() instanceof ConnectException) {
            throw new VmsNotAvailableException();
        }
        logError("Cannot store the portrait of " + userId, e);
        return false;
    }
}

From source file:org.wso2.carbon.am.tests.APIManagerIntegrationTest.java

protected DataHandler setEndpoints(DataHandler dataHandler) throws XMLStreamException, IOException {

    String config = readInputStreamAsString(dataHandler.getInputStream());
    config = replaceEndpoints(config);//from   ww  w  .  ja  va  2  s  .c o  m
    ByteArrayDataSource dbs = new ByteArrayDataSource(config.getBytes());
    return new DataHandler(dbs);
}

From source file:com.youxifan.utils.EMail.java

/**
 *   Set the message content/*  w ww .  ja v a2 s .  co  m*/
 *    @throws MessagingException
 *    @throws IOException
 */
private void setContent() throws MessagingException, IOException {
    //   Local Character Set
    String charSetName;
    if (m_encoding == null) {
        charSetName = System.getProperty("file.encoding"); //   Cp1252
        if (charSetName == null || charSetName.length() == 0)
            charSetName = "UTF-8"; // WebEnv.ENCODING - alternative iso-8859-1
    } else {
        charSetName = m_encoding;
    }
    m_msg.setSubject(getSubject(), charSetName);

    //   Simple Message
    if (m_attachments == null || m_attachments.size() == 0) {
        if (m_messageHTML == null || m_messageHTML.length() == 0)
            m_msg.setText(getMessageCRLF(), charSetName);
        else
            m_msg.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(m_messageHTML, charSetName, "text/html")));
        //
        log.info("(simple) " + getSubject());
    } else //   Multi part message   ***************************************
    {
        //   First Part - Message
        MimeBodyPart mbp_1 = new MimeBodyPart();
        mbp_1.setText("");
        if (m_messageHTML == null || m_messageHTML.length() == 0)
            mbp_1.setText(getMessageCRLF(), charSetName);
        else
            mbp_1.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(m_messageHTML, charSetName, "text/html")));

        // Create Multipart and its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp_1);
        log.info("(multi) " + getSubject() + " - " + mbp_1);

        //   for all attachments
        for (int i = 0; i < m_attachments.size(); i++) {
            Object attachment = m_attachments.get(i);
            DataSource ds = null;
            if (attachment instanceof File) {
                File file = (File) attachment;
                if (file.exists())
                    ds = new FileDataSource(file);
                else {
                    log.warn("File does not exist: " + file);
                    continue;
                }
            } else if (attachment instanceof URL) {
                URL url = (URL) attachment;
                ds = new URLDataSource(url);
            } else if (attachment instanceof DataSource)
                ds = (DataSource) attachment;
            else {
                log.warn("Attachement type unknown: " + attachment);
                continue;
            }
            //   Attachment Part
            MimeBodyPart mbp_2 = new MimeBodyPart();
            mbp_2.setDataHandler(new DataHandler(ds));
            mbp_2.setFileName(ds.getName());
            log.info("Added Attachment " + ds.getName() + " - " + mbp_2);
            mp.addBodyPart(mbp_2);
        }

        //   Add to Message
        m_msg.setContent(mp);
    } //   multi=part
}

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * This Method convert a UrlAttachmentDataSource to a ByteArrayDataSource
 * and used MailAttachmentCacheService for caching resource.
 * @param urlAttachement {@link UrlAttachment}
 * @return a {@link ByteArrayDataSource}
 *//* ww  w  . jav a 2  s.co m*/
private static ByteArrayDataSource convertUrlAttachmentDataSourceToByteArrayDataSource(
        UrlAttachment urlAttachement) {
    String strKey = MailAttachmentCacheService.getInstance().getKey(urlAttachement.getUrlData().toString());
    ByteArrayDataSource urlAttachmentDataSource = null;

    if (!MailAttachmentCacheService.getInstance().isCacheEnable()
            || (MailAttachmentCacheService.getInstance().getFromCache(strKey) == null)) {
        DataHandler handler = new DataHandler(urlAttachement.getUrlData());
        ByteArrayOutputStream bo = null;
        InputStream input = null;
        String strType = null;

        try {
            Object o = handler.getContent();
            strType = handler.getContentType();

            if (o != null) {
                if (o instanceof InputStream) {
                    input = (InputStream) o;
                    bo = new ByteArrayOutputStream();

                    int read;
                    byte[] tab = new byte[CONSTANTE_FILE_ATTACHMET_BUFFER];

                    do {
                        read = input.read(tab);

                        if (read > 0) {
                            bo.write(tab, 0, read);
                        }
                    } while (read > 0);
                }
            }
        } catch (IOException e) {
            // Document is ignored
            AppLogService.info(urlAttachement.getContentLocation() + MSG_ATTACHMENT_NOT_FOUND);
        } finally {
            //closed inputstream and outputstream 
            try {
                if (input != null) {
                    input.close();
                }

                if (bo != null) {
                    bo.close();
                    urlAttachmentDataSource = new ByteArrayDataSource(bo.toByteArray(), strType);
                }
            } catch (IOException e) {
                AppLogService.error(e);
            }
        }

        if (MailAttachmentCacheService.getInstance().isCacheEnable()) {
            //add resource in cache
            MailAttachmentCacheService.getInstance().putInCache(strKey, urlAttachmentDataSource);
        }
    } else {
        //used the resource store in cache
        urlAttachmentDataSource = (ByteArrayDataSource) MailAttachmentCacheService.getInstance()
                .getFromCache(strKey);
    }

    return urlAttachmentDataSource;
}

From source file:org.jasig.portlet.blackboardvcportlet.service.impl.SessionServiceImpl.java

private BlackboardMultimediaResponse createSessionMultimedia(Session session, ConferenceUser conferenceUser,
        MultipartFile file) {//from   w  w  w. j av  a  2  s .  c  o  m
    final String filename = FilenameUtils.getName(file.getOriginalFilename());

    File multimediaFile = null;
    try {
        //Transfer the uploaded file to our own temp file so we can use a FileDataSource
        multimediaFile = File.createTempFile(filename, ".tmp", this.tempDir);
        file.transferTo(multimediaFile);

        //Upload the file to BB
        return this.multimediaWSDao.createSessionMultimedia(session.getBbSessionId(),
                conferenceUser.getUniqueId(), filename, "",
                new DataHandler(new FileDataSource(multimediaFile)));
    } catch (IOException e) {
        throw new RuntimeException("Failed to upload multimedia file '" + filename + "'", e);
    } finally {
        FileUtils.deleteQuietly(multimediaFile);
    }
}

From source file:org.jasig.portlet.blackboardvcportlet.service.impl.SessionServiceImpl.java

private BlackboardPresentationResponse createSessionPresentation(Session session, ConferenceUser conferenceUser,
        MultipartFile file) {//from  www  .  ja va  2s.  com
    final String filename = FilenameUtils.getName(file.getOriginalFilename());

    File multimediaFile = null;
    try {
        //Transfer the uploaded file to our own temp file so we can use a FileDataSource
        multimediaFile = File.createTempFile(filename, ".tmp", this.tempDir);
        file.transferTo(multimediaFile);

        //Upload the file to BB
        return this.presentationWSDao.uploadPresentation(session.getBbSessionId(), conferenceUser.getUniqueId(),
                filename, "", new DataHandler(new FileDataSource(multimediaFile)));
    } catch (IOException e) {
        throw new RuntimeException("Failed to upload multimedia file '" + filename + "'", e);
    } finally {
        FileUtils.deleteQuietly(multimediaFile);
    }
}

From source file:org.jlibrary.core.axis.client.AxisRepositoryDelegate.java

public Document updateDocument(Ticket ticket, DocumentProperties docProperties)
        throws RepositoryException, SecurityException, ResourceLockedException {

    //DefaultRepositoryServiceImpl.getInstance().updateDocument(properties,docId,docProperties);

    try {// ww  w.  jav a  2 s. c o  m
        call.removeAllParameters();

        call.setTargetEndpointAddress(new java.net.URL(endpoint));
        call.setOperationName("updateDocument");
        call.addParameter("ticket", XMLType.XSD_ANY, ParameterMode.IN);
        call.addParameter("docProperties", XMLType.XSD_ANY, ParameterMode.IN);

        call.setReturnType(XMLType.XSD_ANY);

        // Change the binary property for an attachment
        byte[] content = (byte[]) docProperties.getProperty(DocumentProperties.DOCUMENT_CONTENT).getValue();
        if (content != null) {
            docProperties.setProperty(DocumentProperties.DOCUMENT_CONTENT, null);
            DataHandler handler = new DataHandler(new ByteArrayDataSource(content, "application/octet-stream"));
            call.addAttachmentPart(handler);
        }
        return (Document) call.invoke(new Object[] { ticket, docProperties });

    } catch (Exception e) {
        // I don't know if there is a better way to do this
        AxisFault fault = (AxisFault) e;
        if (fault.getFaultString().indexOf("SecurityException") != -1) {
            throw new SecurityException(fault.getFaultString());
        } else if (fault.getFaultString().indexOf("ResourceLockedException") != -1) {
            // Create a virtual lock for info
            String docId = docProperties.getProperty(DocumentProperties.DOCUMENT_ID).getValue().toString();
            Lock lock = lookForLock(ticket, docId);
            throw new ResourceLockedException(lock);
        } else {
            throw new RepositoryException(fault.getFaultString());
        }
    }

}

From source file:lucee.runtime.net.smtp.SMTPClient.java

private void fillHTMLText(MimePart mp) throws MessagingException {
    mp.setDataHandler(new DataHandler(new StringDataSource(htmlText, TEXT_HTML, htmlTextCharset, 76)));
    //mp.setHeader("Content-Transfer-Encoding", "7bit");
    mp.setHeader("Content-Type", TEXT_HTML + "; charset=" + htmlTextCharset);
}

From source file:edu.sdsc.nbcr.opal.OpalClient.java

/**
 * this function returns an array of InputFileType containing all the files
 * selected by the user// w  w w . jav  a  2s  .co  m
  *
  * If the server is Opal2 the file are sent using attachment...
 */
private InputFileType[] _getInputFiles() throws IllegalActionException {
    InputFileType inputFile = null;
    ArrayList files = new ArrayList();
    // complex submission form
    Attribute[] opalAttrs = _getOpalAttributes();
    for (int i = 0; i < opalAttrs.length; i++) {
        if (opalAttrs[i] instanceof FilePortParameter) {
            // simple case
            File file = ((FilePortParameter) opalAttrs[i]).asFile();
            if (file == null)
                continue;
            if (file.exists()) {
                inputFile = new InputFileType();
                if (_appMetadata.isOpal2()) {
                    //use attachment to sent the file
                    DataHandler dh = new DataHandler(new FileDataSource(file));
                    inputFile.setName(file.getName());
                    inputFile.setAttachment(dh);
                    log.info("Uploading file using attahcment: " + inputFile.getName());
                } else {
                    //use inline to sent the file
                    byte[] fileByte = new byte[(int) file.length()];// this is nasty
                    inputFile.setName(file.getName());
                    try {
                        (new FileInputStream(file)).read(fileByte);
                    } catch (Exception e) {
                        throw new IllegalActionException("Unable to read input file: " + file.getName());
                    }
                    inputFile.setContents(fileByte);
                    log.info("Uploading file using base64 encoding: " + inputFile.getName());
                }
                files.add(inputFile);
            } else {
                // the file does not exist
                throw new IllegalActionException("Unable to read input file: " + file.getName());
            }
        }
    }
    log.info("we are returning " + files.size() + " file(s)");
    return (InputFileType[]) files.toArray(new InputFileType[files.size()]);
}

From source file:lucee.runtime.net.smtp.SMTPClient.java

private void fillPlainText(MimePart mp) throws MessagingException {
    mp.setDataHandler(new DataHandler(new StringDataSource(plainText, TEXT_PLAIN, plainTextCharset, 980)));
    //mp.setHeader("Content-Transfer-Encoding", "7bit");
    mp.setHeader("Content-Type", TEXT_PLAIN + "; charset=" + plainTextCharset);
}