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:com.clustercontrol.ws.collect.CollectEndpoint.java

/**
 * ?DL?//from  ww  w . j  a v a  2 s  .c om
 *
 * CollectRead???
 *
 * @param filepath
 * @return
 * @throws InvalidRole
 * @throws InvalidUserPass
 * @throws HinemosUnknown
 */
@XmlMimeType("application/octet-stream")
public DataHandler downloadPerfFile(String fileName) throws InvalidUserPass, InvalidRole, HinemosUnknown {
    m_log.debug("downloadPerfFile() fileName = " + fileName);
    ArrayList<SystemPrivilegeInfo> systemPrivilegeList = new ArrayList<SystemPrivilegeInfo>();
    systemPrivilegeList.add(new SystemPrivilegeInfo(FunctionConstant.COLLECT, SystemPrivilegeMode.READ));
    HttpAuthenticator.authCheck(wsctx, systemPrivilegeList);

    // ???
    StringBuffer msg = new StringBuffer();
    msg.append(", FileName=");
    msg.append(fileName);

    String exportDirectory = HinemosPropertyUtil.getHinemosPropertyStr("performance.export.dir",
            HinemosPropertyDefault.getString(HinemosPropertyDefault.StringKey.PERFORMANCE_EXPORT_DIR));
    File file = new File(exportDirectory + fileName);
    if (!file.exists()) {
        m_log.info("file is not found : " + exportDirectory + fileName);
        m_opelog.warn(HinemosModuleConstant.LOG_PREFIX_PERFORMANCE
                + " Download Failed, Method=downloadPerfFile, User="
                + HttpAuthenticator.getUserAccountString(wsctx) + msg.toString());
        return null;
    }
    m_log.info("file is found : " + exportDirectory + fileName);
    m_opelog.info(HinemosModuleConstant.LOG_PREFIX_PERFORMANCE + " Download, Method=downloadPerfFile, User="
            + HttpAuthenticator.getUserAccountString(wsctx) + msg.toString());

    FileDataSource source = new FileDataSource(file);
    DataHandler dataHandler = new DataHandler(source);
    return dataHandler;
}

From source file:edu.xtec.colex.client.beans.ColexRecordBean.java

/**
 * Calls the web service operation/*from  www  . j a v a2 s. c o  m*/
 * <I>modifyRecord(User,Owner,Collection,Record) : void</I>
 *
 * @param r the Record to modify
 * @param vAttachments a Vector containing the Attachments of the Record
 * @throws java.lang.Exception when an Exception error occurs
 */
protected void modifyRecord(Record r, Vector vAttachments) throws Exception {
    User u = new User(getUserId());

    Collection c = new Collection("");

    c.setName(collection);

    try {
        smRequest = mf.createMessage();

        SOAPBodyElement sbeRequest = setRequestName(smRequest, "modifyRecord");

        addParam(sbeRequest, u);
        if (owner != null) {
            Owner oRequest = new Owner(owner);
            addParam(sbeRequest, oRequest);
        }
        addParam(sbeRequest, c);
        addParam(sbeRequest, r);

        for (int i = 0; i < vAttachments.size(); i++) {

            FileItem fi = (FileItem) vAttachments.get(i);

            String sNomFitxer = Utils.getFileName(fi.getName());

            File fTemp = File.createTempFile("attach", null);

            fi.write(fTemp);

            URL urlFile = new URL("file://" + fTemp.getPath());

            AttachmentPart ap = smRequest.createAttachmentPart(new DataHandler(urlFile));

            String fieldName = fi.getFieldName();

            ap.setContentId(fieldName + "/" + sNomFitxer);

            smRequest.addAttachmentPart(ap);
        }

        smRequest.saveChanges();

        SOAPMessage smResponse = sendMessage(smRequest,
                this.getJspProperties().getProperty("url.servlet.record"));

        SOAPBody sbResponse = smResponse.getSOAPBody();

        if (sbResponse.hasFault()) {
            checkFault(sbResponse, "modify");
        } else {

        }
    } catch (SOAPException se) {
        throw se;
    }
}

From source file:com.clustercontrol.infra.session.InfraControllerBean.java

public DataHandler downloadTransferFile(String fileName) {
    m_log.info("downloadTransferFile fileName=" + fileName);
    String infraDirectory = HinemosPropertyUtil.getHinemosPropertyStr("infra.transfer.dir",
            HinemosPropertyDefault.getString(HinemosPropertyDefault.StringKey.INFRA_TRANSFER_DIR))
            + File.separator + "send" + File.separator;
    FileDataSource fileData = new FileDataSource(infraDirectory + fileName);
    return new DataHandler(fileData);
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java

/**
 * Adds a mulitpart MimeBodyPart from an array of attachments
 *///  w  w  w. jav  a2 s .c  o  m

public static void addMultipartAttachment(MimeMultipart mp, StringToStringMap contentIds,
        List<Attachment> attachments) throws MessagingException {
    MimeMultipart multipart = new MimeMultipart("mixed");
    long totalSize = 0;

    for (int c = 0; c < attachments.size(); c++) {
        Attachment att = attachments.get(c);
        String contentType = att.getContentType();
        totalSize += att.getSize();

        MimeBodyPart part = contentType.startsWith("text/") ? new MimeBodyPart()
                : new PreencodedMimeBodyPart("binary");

        part.setDataHandler(new DataHandler(new AttachmentDataSource(att)));
        initPartContentId(contentIds, part, att, false);
        multipart.addBodyPart(part);
    }

    MimeBodyPart part = new PreencodedMimeBodyPart("binary");

    if (totalSize > MAX_SIZE_IN_MEMORY_ATTACHMENT) {
        part.setDataHandler(new DataHandler(new MultipartAttachmentFileDataSource(multipart)));
    } else {
        part.setDataHandler(new DataHandler(new MultipartAttachmentDataSource(multipart)));
    }

    Attachment attachment = attachments.get(0);
    initPartContentId(contentIds, part, attachment, true);

    mp.addBodyPart(part);
}

From source file:org.sakaiproject.tool.mailtool.Mailtool.java

public String processSendEmail() {
    /* EmailUser */ selected = m_recipientSelector.getSelectedUsers();
    if (m_selectByTree) {
        selectedGroupAwareRoleUsers = m_recipientSelector1.getSelectedUsers();
        selectedGroupUsers = m_recipientSelector2.getSelectedUsers();
        selectedSectionUsers = m_recipientSelector3.getSelectedUsers();

        selected.addAll(selectedGroupAwareRoleUsers);
        selected.addAll(selectedGroupUsers);
        selected.addAll(selectedSectionUsers);
    }/*from ww w .jav a2s. co m*/
    // Put everyone in a set so the same person doesn't get multiple emails.
    Set emailusers = new TreeSet();
    if (isAllUsersSelected()) { // the button for this is inactivated ... leave for future 
        for (Iterator i = getEmailGroups().iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            emailusers.addAll(group.getEmailusers());
        }
    }
    if (isAllGroupSelected()) {
        for (Iterator i = getEmailGroupsByType("section").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("section")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    if (isAllSectionSelected()) {
        for (Iterator i = getEmailGroupsByType("group").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("group")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    if (isAllGroupAwareRoleSelected()) {
        for (Iterator i = getEmailGroupsByType("role_groupaware").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("role_groupaware")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    emailusers = new TreeSet(selected); // convert List to Set (remove duplicates)

    m_subjectprefix = getSubjectPrefixFromConfig();

    EmailUser curUser = getCurrentUser();

    String fromEmail = "";
    String fromDisplay = "";
    if (curUser != null) {
        fromEmail = curUser.getEmail();
        fromDisplay = curUser.getDisplayname();
    }
    String fromString = fromDisplay + " <" + fromEmail + ">";

    m_results = "Message sent to: <br>";

    String subject = m_subject;

    //Should we append this to the archive?
    String emailarchive = "/mailarchive/channel/" + m_siteid + "/main";
    if (m_archiveMessage && isEmailArchiveInSite()) {
        String attachment_info = "<br/>";
        Attachment a = null;
        Iterator iter = attachedFiles.iterator();
        int i = 0;
        while (iter.hasNext()) {
            a = (Attachment) iter.next();
            attachment_info += "<br/>";
            attachment_info += "Attachment #" + (i + 1) + ": " + a.getFilename() + "(" + a.getSize()
                    + " Bytes)";
            i++;
        }
        this.appendToArchive(emailarchive, fromString, subject, m_body + attachment_info);
    }
    List headers = new ArrayList();
    if (getTextFormat().equals("htmltext"))
        headers.add("content-type: text/html");
    else
        headers.add("content-type: text/plain");

    String smtp_server = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
    //String smtp_port = ServerConfigurationService.getString("smtp.port");
    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", smtp_server);
        //props.put("mail.smtp.port", smtp_port);
        Session s = Session.getInstance(props, null);

        MimeMessage message = new MimeMessage(s);

        InternetAddress from = new InternetAddress(fromString);
        message.setFrom(from);
        String reply = getReplyToSelected().trim().toLowerCase();
        if (reply.equals("yes")) {
            // "reply to sender" is default. So do nothing
        } else if (reply.equals("no")) {
            String noreply = getSiteTitle() + " <noreply@" + smtp_server + ">";
            InternetAddress noreplyemail = new InternetAddress(noreply);
            message.setFrom(noreplyemail);
        } else if (reply.equals("otheremail") && getReplyToOtherEmail().equals("") != true) {
            // need input(email) validation
            InternetAddress replytoList[] = { new InternetAddress(getConfigParam("replyto").trim()) };
            message.setReplyTo(replytoList);
        }
        message.setSubject(subject);
        String text = m_body;
        String attachmentdirectory = getUploadDirectory();

        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        String messagetype = "";

        if (getTextFormat().equals("htmltext")) {
            messagetype = "text/html";
        } else {
            messagetype = "text/plain";
        }
        messageBodyPart.setContent(text, messagetype);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        Attachment a = null;
        Iterator iter = attachedFiles.iterator();
        while (iter.hasNext()) {
            a = (Attachment) iter.next();
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(
                    attachmentdirectory + this.getCurrentUser().getUserid() + "-" + a.getFilename());
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(a.getFilename());
            multipart.addBodyPart(messageBodyPart);
        }
        message.setContent(multipart);

        //Send the emails
        String recipientsString = "";
        for (Iterator i = emailusers.iterator(); i.hasNext(); recipientsString += ",") {
            EmailUser euser = (EmailUser) i.next();
            String toEmail = euser.getEmail(); // u.getEmail();
            String toDisplay = euser.getDisplayname(); // u.getDisplayName();
            // if AllUsers are selected, do not add current user's email to recipients
            if (isAllUsersSelected() && getCurrentUser().getEmail().equals(toEmail)) {
                // don't add sender to recipients
            } else {
                recipientsString += toEmail;
                m_results += toDisplay + (i.hasNext() ? "<br/>" : "");
            }
            //               InternetAddress to[] = {new InternetAddress(toEmail) };
            //               Transport.send(message,to);
        }
        if (m_otheremails.trim().equals("") != true) {
            //
            // multiple email validation is needed here
            //
            String refinedOtherEmailAddresses = m_otheremails.trim().replace(';', ',');
            recipientsString += refinedOtherEmailAddresses;
            m_results += "<br/>" + refinedOtherEmailAddresses;
            //               InternetAddress to[] = {new InternetAddress(refinedOtherEmailAddresses) };
            //               Transport.send(message, to);
        }
        if (m_sendmecopy) {
            message.addRecipients(Message.RecipientType.CC, fromEmail);
            // trying to solve SAK-7410
            // recipientsString+=fromEmail;
            //               InternetAddress to[] = {new InternetAddress(fromEmail) };
            //               Transport.send(message, to);
        }
        //            message.addRecipients(Message.RecipientType.TO, recipientsString);
        message.addRecipients(Message.RecipientType.BCC, recipientsString);

        Transport.send(message);
    } catch (Exception e) {
        log.debug("Mailtool Exception while trying to send the email: " + e.getMessage());
    }

    //   Clear the Subject and Body of the Message
    m_subject = getSubjectPrefix().equals("") ? getSubjectPrefixFromConfig() : getSubjectPrefix();
    m_otheremails = "";
    m_body = "";
    num_files = 0;
    attachedFiles.clear();
    m_recipientSelector = null;
    m_recipientSelector1 = null;
    m_recipientSelector2 = null;
    m_recipientSelector3 = null;
    setAllUsersSelected(false);
    setAllGroupSelected(false);
    setAllSectionSelected(false);

    //  Display Users with Bad Emails if the option is turned on.
    boolean showBadEmails = getDisplayInvalidEmailAddr();
    if (showBadEmails == true) {
        m_results += "<br/><br/>";

        List /* String */ badnames = new ArrayList();

        for (Iterator i = selected.iterator(); i.hasNext();) {
            EmailUser user = (EmailUser) i.next();
            /* This check should maybe be some sort of regular expression */
            if (user.getEmail().equals("")) {
                badnames.add(user.getDisplayname());
            }
        }
        if (badnames.size() > 0) {
            m_results += "The following users do not have valid email addresses:<br/>";
            for (Iterator i = badnames.iterator(); i.hasNext();) {
                String name = (String) i.next();
                if (i.hasNext() == true)
                    m_results += name + "/ ";
                else
                    m_results += name;
            }
        }
    }
    return "results";
}

From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java

@Override
public void send(List<String> to, List<String> cc, List<String> bcc, String subject, String body,
        List<NodeRef> attachments, boolean html) throws Exception {
    EmailConfig config = getConfig();/*from   w w w  . j ava 2  s.c  o  m*/
    EmailProvider provider = getEmailProvider(config.getProviderId());
    Properties props = System.getProperties();
    String prefix = "mail." + provider.getOutgoingProto() + ".";
    props.put(prefix + "host", provider.getOutgoingServer());
    props.put(prefix + "port", provider.getOutgoingPort());
    props.put(prefix + "auth", "true");
    Session session = Session.getInstance(props, null);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(config.getAddress(), config.getRealName()));
    if (to != null) {
        InternetAddress[] recipients = new InternetAddress[to.size()];
        for (int i = 0; i < to.size(); i++)
            recipients[i] = new InternetAddress(to.get(i));
        msg.setRecipients(Message.RecipientType.TO, recipients);
    }

    if (cc != null) {
        InternetAddress[] recipients = new InternetAddress[cc.size()];
        for (int i = 0; i < cc.size(); i++)
            recipients[i] = new InternetAddress(cc.get(i));
        msg.setRecipients(Message.RecipientType.CC, recipients);
    }

    if (bcc != null) {
        InternetAddress[] recipients = new InternetAddress[bcc.size()];
        for (int i = 0; i < bcc.size(); i++)
            recipients[i] = new InternetAddress(bcc.get(i));
        msg.setRecipients(Message.RecipientType.BCC, recipients);
    }

    msg.setSubject(subject);
    msg.setHeader("X-Mailer", "Alvex Emailer");
    msg.setSentDate(new Date());

    MimeBodyPart messageBodyPart = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();

    if (body != null) {
        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body, "utf-8", html ? "html" : "plain");
        multipart.addBodyPart(messageBodyPart);
    }

    if (attachments != null)
        for (NodeRef att : attachments) {
            messageBodyPart = new MimeBodyPart();
            String fileName = (String) nodeService.getProperty(att, AlvexContentModel.PROP_EMAIL_REAL_NAME);
            messageBodyPart
                    .setDataHandler(new DataHandler(new RepositoryDataSource(att, fileName, contentService)));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
        }

    msg.setContent(multipart);

    SMTPTransport t = (SMTPTransport) session.getTransport(provider.getOutgoingProto());
    t.connect(config.getUsername(), config.getPassword());
    t.sendMessage(msg, msg.getAllRecipients());
    t.close();
}

From source file:org.apache.axiom.attachments.Attachments.java

/**
 * @return the Next valid MIME part + store the Part in the Parts List
 * @throws OMException throw if content id is null or if two MIME parts contain the same
 *                     content-ID & the exceptions throws by getPart()
 */// ww  w. ja va2s  . c o  m
private DataHandler getNextPartDataHandler() throws OMException {
    if (endOfStreamReached) {
        return null;
    }
    Part nextPart;
    nextPart = getPart();
    if (nextPart == null) {
        return null;
    } else
        try {
            long size = nextPart.getSize();
            String partContentID;
            DataHandler dataHandler;
            try {
                partContentID = nextPart.getContentID();

                if (partContentID == null & partIndex == 1) {
                    String id = "firstPart_" + UIDGenerator.generateContentId();
                    firstPartId = id;
                    if (size > 0) {
                        dataHandler = nextPart.getDataHandler();
                    } else {
                        // Either the mime part is empty or the stream ended without having 
                        // a MIME message terminator
                        dataHandler = new DataHandler(new ByteArrayDataSource(new byte[] {}));
                    }
                    addDataHandler(id, dataHandler);
                    return dataHandler;
                }
                if (partContentID == null) {
                    throw new OMException("Part content ID cannot be blank for non root MIME parts");
                }
                if ((partContentID.indexOf("<") > -1) & (partContentID.indexOf(">") > -1)) {
                    partContentID = partContentID.substring(1, (partContentID.length() - 1));

                }
                if (partIndex == 1) {
                    firstPartId = partContentID;
                }
                if (attachmentsMap.containsKey(partContentID)) {
                    throw new OMException("Two MIME parts with the same Content-ID not allowed.");
                }
                if (size > 0) {
                    dataHandler = nextPart.getDataHandler();
                } else {
                    // Either the mime part is empty or the stream ended without having 
                    // a MIME message terminator
                    dataHandler = new DataHandler(new ByteArrayDataSource(new byte[] {}));
                }
                addDataHandler(partContentID, dataHandler);
                return dataHandler;
            } catch (MessagingException e) {
                throw new OMException("Error reading Content-ID from the Part." + e);
            }
        } catch (MessagingException e) {
            throw new OMException(e);
        }
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!//from w w  w.j  av  a2s  . c  o  m
 *
 * @param multipart DOCUMENT ME!
 * @param part DOCUMENT ME!
 * @param charset DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void attach(MimeMultipart multipart, Part part, String charset) throws MessagingException {
    MimeBodyPart xbody = new MimeBodyPart();
    PartDataSource xds = new PartDataSource(part);
    DataHandler xdh = new DataHandler(xds);
    xbody.setDataHandler(xdh);

    int xid = multipart.getCount() + 1;
    String xtext;

    // UNDONE
    //xbody.setContentLanguage( String ); // this could be language from Locale
    //xbody.setContentMD5( String md5 ); // don't know about this yet
    xtext = part.getDescription();

    if (xtext == null) {
        xtext = "Part Attachment: " + xid;
    }

    xbody.setDescription(xtext, charset);

    xtext = getContentDisposition(part).getType();
    xbody.setDisposition(xtext);

    xtext = MessageUtilities.getFileName(part);

    if ((xtext == null) || (xtext.length() < 1)) {
        xtext = "PART" + xid;
    }

    MessageUtilities.setFileName(xbody, xtext, charset);

    multipart.addBodyPart(xbody);
}

From source file:com.aimluck.eip.mail.util.ALMailUtils.java

/**
 * ??? Part#setText() ???????????//www .j  a v  a 2 s.  c  o  m
 */
public static void setTextContent(Part p, String s) throws MessagingException {
    p.setDataHandler(new DataHandler(new JISDataSource(s)));
    p.setHeader(ALLocalMailMessage.CONTENT_TRANSFER_ENCORDING, "7bit");
}

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

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

    try {//  ww  w. ja  va 2 s . c  om
        call.removeAllParameters();

        call.setTargetEndpointAddress(new java.net.URL(endpoint));
        call.setOperationName("createDocument");

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

        Document document = (Document) call.invoke(new Object[] { ticket, docProperties });
        return document;
    } 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 {
            throw new RepositoryException(fault.getFaultString());
        }
    }
}