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.smartloli.kafka.eagle.api.email.MailServiceImpl.java

/** Send mail in HTML format */
private boolean sendHtmlMail(MailSenderInfo mailInfo) {
    boolean enableMailAlert = SystemConfigUtils.getBooleanProperty("kafka.eagle.mail.enable");
    if (enableMailAlert) {
        SaAuthenticatorInfo authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            authenticator = new SaAuthenticatorInfo(mailInfo.getUserName(), mailInfo.getPassword());
        }//from  w w  w .  j  a v a  2  s  .c o m
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            Message mailMessage = new MimeMessage(sendMailSession);
            Address from = new InternetAddress(mailInfo.getFromAddress());
            mailMessage.setFrom(from);
            Address[] to = new Address[mailInfo.getToAddress().split(",").length];
            int i = 0;
            for (String e : mailInfo.getToAddress().split(","))
                to[i++] = new InternetAddress(e);
            mailMessage.setRecipients(Message.RecipientType.TO, to);
            mailMessage.setSubject(mailInfo.getSubject());
            mailMessage.setSentDate(new Date());
            Multipart mainPart = new MimeMultipart();
            BodyPart html = new MimeBodyPart();
            html.setContent(mailInfo.getContent(), "text/html; charset=UTF-8");
            mainPart.addBodyPart(html);

            if (mailInfo.getImagesMap() != null && !mailInfo.getImagesMap().isEmpty()) {
                for (Entry<String, String> entry : mailInfo.getImagesMap().entrySet()) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    File file = new File(entry.getValue());
                    FileDataSource fds = new FileDataSource(file);
                    mbp.setDataHandler(new DataHandler(fds));
                    try {
                        mbp.setFileName(MimeUtility.encodeWord(entry.getKey(), "UTF-8", null));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mbp.setContentID(entry.getKey());
                    mbp.setHeader("Content-ID", "<image>");
                    mainPart.addBodyPart(mbp);
                }
            }

            List<File> list = mailInfo.getFileList();
            if (list != null && list.size() > 0) {
                for (File f : list) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(f.getAbsolutePath());
                    mbp.setDataHandler(new DataHandler(fds));
                    mbp.setFileName(f.getName());
                    mainPart.addBodyPart(mbp);
                }

                list.clear();
            }

            mailMessage.setContent(mainPart);
            // mailMessage.saveChanges();
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
    }
    return false;
}

From source file:de.kp.ames.web.function.domain.model.EvaluationObject.java

/**
 * Create EvaluationObject//from   ww w .ja  v a 2s  .co  m
 * 
 * @param source
 * @param reasoner
 * @param data
 * @param stream
 * @return
 * @throws Exception
 */
public RegistryObjectImpl create(String source, String reasoner, String data, InputStream stream)
        throws Exception {

    /*
     * Initialize data
     */
    JSONObject jForm = new JSONObject(data);

    /* 
     * Create extrinsic object that serves as a wrapper 
     * for the respective evaluation
     */
    // 
    ExtrinsicObjectImpl eo = jaxrLCM.createExtrinsicObject();
    if (eo == null)
        throw new JAXRException("[EvaluationObject] Creation of ExtrinsicObject failed.");

    /* 
     * Identifier
     */
    String eid = JaxrIdentity.getInstance().getPrefixUID(FncConstants.EVALUATION_PRE);

    eo.setLid(eid);
    eo.getKey().setId(eid);

    /* 
     * Home url
     */
    String home = jaxrHandle.getEndpoint().replace("/saml", "");
    eo.setHome(home);

    /*
     * Name & description
     */
    String name = jForm.getString(RIM_NAME);
    String desc = jForm.getString(RIM_DESC);

    String dtime = jForm.getString(RIM_DATE);
    name = name.trim() + ", " + dtime.trim();

    eo.setName(jaxrLCM.createInternationalString(name));
    eo.setDescription(jaxrLCM.createInternationalString(desc));

    /*
     * Associations
     */

    /*
     * Build directed graph between evaluation and its source
     */
    RegistryObjectImpl sourceObject = jaxrLCM.getRegistryObjectById(source);
    if (sourceObject == null)
        throw new JAXRException("[EvaluationObject] RegistryObject with id <." + source + "> does not exist.");

    AssociationImpl sourceAssociation = jaxrLCM.createAssociation_RelatedTo(sourceObject);
    eo.addAssociation(sourceAssociation);

    /*
     * Build directed graph between evaluation and its reasoner
     */
    RegistryObjectImpl reasonerObject = jaxrLCM.getRegistryObjectById(reasoner);
    if (reasonerObject == null)
        throw new JAXRException(
                "[EvaluationObject] RegistryObject with id <." + reasoner + "> does not exist.");

    AssociationImpl reasonerAssociation = jaxrLCM.createAssociation_RelatedTo(reasonerObject);
    eo.addAssociation(reasonerAssociation);

    /*
     * Classifications
     */
    ClassificationImpl classification = jaxrLCM.createClassification(ClassificationConstants.FNC_ID_Evaluation);
    eo.addClassification(classification);

    /*
     * Mimetype & repository item
     */
    String mimetype = GlobalConstants.MT_XML;
    eo.setMimeType(mimetype);

    byte[] bytes = FileUtil.getByteArrayFromInputStream(stream);

    DataHandler handler = new DataHandler(FileUtil.createByteArrayDataSource(bytes, mimetype));
    eo.setRepositoryItem(handler);

    /*
    * Indicate as created
    */
    this.created = true;

    return eo;

}

From source file:de.kp.ames.web.function.domain.model.DocumentObject.java

/**
 * Create RegistryObject representation of DocumentObject
 * //from   w ww . j a va  2  s .c  om
 * @param data
 * @return
 * @throws Exception
 */
public RegistryObjectImpl create(JSONObject jForm) throws Exception {

    /* 
     * Create extrinsic object that serves as a wrapper 
     * for the respective document
     */
    // 
    ExtrinsicObjectImpl eo = jaxrLCM.createExtrinsicObject();
    if (eo == null)
        throw new JAXRException("[DocumentObject] Creation of ExtrinsicObject failed.");

    /* 
     * Identifier
     */
    String eid = JaxrIdentity.getInstance().getPrefixUID(FncConstants.DOCUMENT_PRE);

    eo.setLid(eid);
    eo.getKey().setId(eid);

    /* 
     * Home url
     */
    String home = jaxrHandle.getEndpoint().replace("/saml", "");
    eo.setHome(home);

    /* 
     * The document is actually transient and managed by the document cache
     */

    DocumentCacheManager cacheManager = DocumentCacheManager.getInstance();

    String key = jForm.getString(JsonConstants.J_KEY);
    DmsDocument document = (DmsDocument) cacheManager.getFromCache(key);

    if (document == null)
        throw new Exception("[DocumentObject] Document with id <" + key + "> not found.");

    /*
     * Name & description
     */
    String name = jForm.has(RIM_NAME) ? jForm.getString(RIM_NAME) : null;
    String desc = jForm.has(RIM_DESC) ? jForm.getString(RIM_DESC) : null;

    name = (name == null) ? document.getName() : name;

    int pos = name.lastIndexOf(".");
    if (pos != -1)
        name = name.substring(0, pos);

    eo.setName(jaxrLCM.createInternationalString(name));

    desc = (desc == null) ? FncMessages.NO_DESCRIPTION_DESC : desc;
    eo.setDescription(jaxrLCM.createInternationalString(desc));

    /*
     * Classifications
     */
    JSONArray jClases = jForm.has(RIM_CLAS) ? new JSONArray(jForm.getString(RIM_CLAS)) : null;
    if (jClases != null) {

        List<ClassificationImpl> classifications = createClassifications(jClases);
        /*
         * Set composed object
         */
        eo.addClassifications(classifications);

    }

    /* 
     * Create slots
     */
    JSONObject jSlots = jForm.has(RIM_SLOT) ? new JSONObject(jForm.getString(RIM_SLOT)) : null;
    if (jSlots != null) {

        List<SlotImpl> slots = createSlots(jSlots);
        /*
         * Set composed object
         */
        eo.addSlots(slots);

    }

    /*
     * Mimetype & repository item
     */
    String mimetype = document.getMimetype();
    DataHandler handler = new DataHandler(FileUtil.createByteArrayDataSource(document.getBytes(), mimetype));

    eo.setMimeType(mimetype);
    eo.setRepositoryItem(handler);

    /*
     * Indicate as created
     */
    this.created = true;

    return eo;

}

From source file:com.collabnet.ccf.teamforge.TFAttachmentHandler.java

/**
 * This method uploads the file and gets the new file descriptor returned
 * from the TF system. It then associates the file descriptor to the
 * artifact there by adding the attachment to the artifact.
 * /*  w ww  . j a  v  a 2  s . c o  m*/
 * @param sessionId
 *            - The current session id
 * @param artifactId
 *            - The artifact's id to which the attachment should be added.
 * @param comment
 *            - Comment for the attachment addition
 * @param fileName
 *            - Name of the file that is attached to this artifact
 * @param mimeType
 *            - MIME type of the file that is being attached.
 * @param att
 *            - the file content
 * @param linkUrl
 * 
 * @throws RemoteException
 *             - if any SOAP api call fails
 * @throws PlanningFolderRuleViolationException
 */
public ArtifactDO attachFileToArtifact(Connection connection, String artifactId, String comment,
        String fileName, String mimeType, GenericArtifact att, byte[] linkUrl)
        throws RemoteException, PlanningFolderRuleViolationException {
    ArtifactDO soapDo = null;
    String attachmentDataFileName = GenericArtifactHelper
            .getStringGAField(AttachmentMetaData.ATTACHMENT_DATA_FILE, att);
    boolean retryCall = true;
    while (retryCall) {
        retryCall = false;
        String fileDescriptor = null;
        try {
            byte[] data = null;
            if (StringUtils.isEmpty(attachmentDataFileName)) {
                if (linkUrl == null) {
                    data = att.getRawAttachmentData();
                } else {
                    data = linkUrl;
                }
                fileDescriptor = connection.getFileStorageClient().startFileUpload();
                connection.getFileStorageClient().write(fileDescriptor, data);
                connection.getFileStorageClient().endFileUpload(fileDescriptor);
            } else {
                try {
                    DataSource dataSource = new FileDataSource(new File(attachmentDataFileName));
                    DataHandler dataHandler = new DataHandler(dataSource);
                    fileDescriptor = connection.getFileStorageClient().uploadFile(dataHandler);
                } catch (IOException e) {
                    String message = "Exception while uploading the attachment " + attachmentDataFileName;
                    log.error(message, e);
                    throw new CCFRuntimeException(message, e);
                }
            }

            soapDo = connection.getTrackerClient().getArtifactData(artifactId);
            boolean fileAttached = true;
            while (fileAttached) {
                try {
                    fileAttached = false;
                    connection.getTrackerClient().setArtifactData(soapDo, comment, fileName, mimeType,
                            fileDescriptor);
                } catch (AxisFault e) {
                    javax.xml.namespace.QName faultCode = e.getFaultCode();
                    if (!faultCode.getLocalPart().equals("VersionMismatchFault")) {
                        throw e;
                    }
                    logConflictResolutor.warn("Stale attachment update, trying again ...:", e);
                    soapDo = connection.getTrackerClient().getArtifactData(artifactId);
                    fileAttached = true;
                }
            }
        } catch (AxisFault e) {
            javax.xml.namespace.QName faultCode = e.getFaultCode();
            if (!faultCode.getLocalPart().equals("InvalidSessionFault")) {
                throw e;
            }
            if (connectionManager.isEnableReloginAfterSessionTimeout()
                    && (!connectionManager.isUseStandardTimeoutHandlingCode())) {
                log.warn("While uploading an attachment, the session id became invalid, trying again", e);
                retryCall = true;
            } else {
                throw e;
            }
        }
    }
    // we have to increase the version after the update
    // TODO Find out whether this really works if last modified date differs
    // from actual last modified date
    soapDo.setVersion(soapDo.getVersion() + 1);
    return soapDo;
}

From source file:org.mule.transport.email.transformers.ObjectToMimeMessage.java

protected BodyPart getPayloadBodyPart(Object payload, String contentType)
        throws MessagingException, TransformerException, IOException {
    DataHandler handler;//from w  w w.  j ava  2 s. c  o  m
    if (payload instanceof String) {
        handler = new DataHandler(new ByteArrayDataSource((String) payload, contentType));
    } else if (payload instanceof byte[]) {
        handler = new DataHandler(new ByteArrayDataSource((byte[]) payload, contentType));
    } else if (payload instanceof Serializable) {
        handler = new DataHandler(new ByteArrayDataSource(
                (byte[]) new SerializableToByteArray().transform(payload), contentType));
    } else {
        throw new IllegalArgumentException();
    }
    BodyPart part = new MimeBodyPart();
    part.setDataHandler(handler);
    part.setDescription("Payload");
    return part;
}

From source file:org.shredzone.cilla.ws.impl.HeaderWsImpl.java

@Override
public DataHandler getFullImage(long headerId, ImageProcessing process) throws CillaServiceException {
    Header hdr = headerDao.fetch(headerId);
    if (hdr == null) {
        throw new CillaNotFoundException("header", headerId);
    }// ww  w  . java2s. c o m

    return new DataHandler(headerService.getFullImage(hdr, process));
}

From source file:org.bimserver.client.Client.java

public void checkin(SProject project, DataSource dataSource, long fileSize) {
    String comment = JOptionPane.showInputDialog(Client.this, "Please give a short description of your changes",
            "Checkin", JOptionPane.OK_OPTION | JOptionPane.INFORMATION_MESSAGE);
    try {//  w w  w  .  j  a  v a  2 s  .  c  o  m
        DataHandler ifcFile = new DataHandler(dataSource);
        int checkinId = serviceHolder.getService().checkin(project.getOid(), comment, "TODO", fileSize, ifcFile,
                false, true);
        SCheckinResult sCheckinResult = serviceHolder.getService().getCheckinState(checkinId);
        JOptionPane.showMessageDialog(this, "New revision number: " + sCheckinResult.getRevisionId(),
                "Checkin successful", JOptionPane.OK_OPTION | JOptionPane.INFORMATION_MESSAGE);
        revisionPanel.showProject(project);
    } catch (ServiceException e) {
        JOptionPane.showMessageDialog(this, e.getUserMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.jbpm.integration.console.forms.AbstractFormDispatcher.java

protected DataHandler processTemplate(final String name, InputStream src, Map<String, Object> renderContext) {
    DataHandler merged = null;//from   ww w .j ava 2 s. c  o m
    try {
        freemarker.template.Configuration cfg = new freemarker.template.Configuration();
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        cfg.setTemplateUpdateDelay(0);
        Template temp = new Template(name, new InputStreamReader(src), cfg);
        final ByteArrayOutputStream bout = new ByteArrayOutputStream();
        Writer out = new OutputStreamWriter(bout);
        temp.process(renderContext, out);
        out.flush();
        merged = new DataHandler(new DataSource() {
            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream(bout.toByteArray());
            }

            public OutputStream getOutputStream() throws IOException {
                return bout;
            }

            public String getContentType() {
                return "*/*";
            }

            public String getName() {
                return name + "_DataSource";
            }
        });
    } catch (Exception e) {
        throw new RuntimeException("Failed to process form template", e);
    }
    return merged;
}

From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java

/**
 * @param runner/*from  w  w  w  .java 2  s .  co m*/
 * @param resultDir
 * @throws MessagingException
 * @throws IOException
 */
public void send(MultiHTMLSuiteRunner runner, File resultDir) throws MessagingException, IOException {

    MimeMessage mimeMessage = new MimeMessage(session);

    mimeMessage.setHeader("Content-Transfer-Encoding", "7bit");

    // To
    mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(config.getTo()));

    // From
    mimeMessage.setFrom(new InternetAddress(config.getFrom()));

    HashMap<String, Object> context = new HashMap<String, Object>();
    context.put("result", runner.getResult() ? "passed" : "failed");
    context.put("passedCount", new Integer(runner.getPassedCount()));
    context.put("failedCount", new Integer(runner.getFailedCount()));
    context.put("totalCount", new Integer(runner.getHtmlSuiteList().size()));
    context.put("startTime", new Date(runner.getStartTime()));
    context.put("endTime", new Date(runner.getEndTime()));
    context.put("htmlSuites", runner.getHtmlSuiteList());

    // subject
    mimeMessage.setSubject(TemplateUtils.merge(config.getSubject(), context), config.getCharset());

    // multipart message
    MimeMultipart content = new MimeMultipart();

    MimeBodyPart body = new MimeBodyPart();
    body.setText(TemplateUtils.merge(config.getBody(), context), config.getCharset());
    content.addBodyPart(body);

    File resultArchive = createResultArchive(resultDir);

    MimeBodyPart attachmentFile = new MimeBodyPart();
    attachmentFile.setDataHandler(new DataHandler(new FileDataSource(resultArchive)));
    attachmentFile.setFileName(RESULT_ARCHIVE_FILE);
    content.addBodyPart(attachmentFile);

    mimeMessage.setContent(content);

    // send mail
    _send(mimeMessage);
}

From source file:org.infoglue.common.util.mail.MailService.java

/**
 * @param attachments /*from  ww  w.  j  a  v  a  2 s. co  m*/
 *
 */
private Message createMessage(String from, String to, String bcc, String subject, String content,
        String contentType, String encoding, List attachments) throws SystemException {
    try {
        final Message message = new MimeMessage(this.session);
        String contentTypeWithEncoding = contentType + ";charset=" + encoding;

        // message.setContent(content, contentType);
        message.setFrom(createInternetAddress(from));
        //message.setRecipient(Message.RecipientType.TO,
        //      createInternetAddress(to));
        message.setRecipients(Message.RecipientType.TO, createInternetAddresses(to));
        if (bcc != null)
            message.setRecipients(Message.RecipientType.BCC, createInternetAddresses(bcc));
        // message.setSubject(subject);

        ((MimeMessage) message).setSubject(subject, encoding);
        MimeMultipart mp = new MimeMultipart();
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setDataHandler(new DataHandler(new StringDataSource(content, contentTypeWithEncoding, encoding)));
        mp.addBodyPart(mbp1);
        if (attachments != null) {
            for (Iterator it = attachments.iterator(); it.hasNext();) {
                File attachmentFile = (File) it.next();
                if (attachmentFile.exists()) {
                    MimeBodyPart attachment = new MimeBodyPart();
                    attachment.setFileName(attachmentFile.getName());
                    attachment.setDataHandler(new DataHandler(new FileDataSource(attachmentFile)));
                    mp.addBodyPart(attachment);
                }
            }
        }
        message.setContent(mp);
        // message.setText(content);
        // message.setDataHandler(new DataHandler(new
        // StringDataSource(content, contentTypeWithEncoding, encoding)));
        // message.setText(content);
        // message.setDataHandler(new DataHandler(new
        // StringDataSource(content, "text/html")));

        return message;
    } catch (MessagingException e) {
        throw new SystemException("Unable to create the message.", e);
    }
}