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:mitm.application.djigzo.ca.PFXMailBuilder.java

private void replacePFX(MimeMessage message) throws MessagingException {
    Multipart mp;/*  w  w  w  . jav a  2 s.c o m*/

    try {
        mp = (Multipart) message.getContent();
    } catch (IOException e) {
        throw new MessagingException("Error getting message content.", e);
    }

    BodyPart pfxPart = null;

    /*
     * Fallback in case the template does not contain a DjigzoHeader.MARKER
     */
    BodyPart octetStreamPart = null;

    /*
     * Try to find the first attachment with X-Djigzo-Marker attachment header which should be the attachment
     * we should replace (we should replace the content and keep the headers)
     */
    for (int i = 0; i < mp.getCount(); i++) {
        BodyPart part = mp.getBodyPart(i);

        if (ArrayUtils.contains(part.getHeader(DjigzoHeader.MARKER), DjigzoHeader.ATTACHMENT_MARKER_VALUE)) {
            pfxPart = part;

            break;
        }

        /*
         * Fallback scanning for octet-stream in case the template does not contain a DjigzoHeader.MARKER
         */
        if (part.isMimeType("application/octet-stream")) {
            octetStreamPart = part;
        }
    }

    if (pfxPart == null) {
        if (octetStreamPart != null) {
            logger.info("Marker not found. Using ocet-stream instead.");

            /*
             * Use the octet-stream part
             */
            pfxPart = octetStreamPart;
        } else {
            throw new MessagingException("Unable to find the attachment part in the template.");
        }
    }

    pfxPart.setDataHandler(new DataHandler(new ByteArrayDataSource(pfx, "application/octet-stream")));
}

From source file:org.bimserver.shared.pb.ProtocolBuffersConverter.java

private Object convertFieldValue(SField field, Object val) throws ConvertException {
    if (val instanceof EnumValueDescriptor) {
        EnumValueDescriptor enumValueDescriptor = (EnumValueDescriptor) val;
        Class<?> enumClass;
        try {/*w  w  w  .j a  v a2  s.co  m*/
            enumClass = Class
                    .forName("org.bimserver.interfaces.objects." + enumValueDescriptor.getType().getName());
            for (Object v : enumClass.getEnumConstants()) {
                Enum<?> e = (Enum<?>) v;
                if (e.ordinal() == enumValueDescriptor.getNumber()) {
                    val = e;
                    break;
                }
            }
        } catch (ClassNotFoundException e) {
            LOGGER.error("", e);
        }
        return val;
    } else if (field.getType().getInstanceClass() == Date.class) {
        return new Date((Long) val);
    } else if (field.getType().getInstanceClass() == DataHandler.class) {
        ByteString byteString = (ByteString) val;
        ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource("test", byteString.toByteArray());
        return new DataHandler(byteArrayDataSource);
    } else if (val instanceof DynamicMessage) {
        return convertProtocolBuffersMessageToSObject((DynamicMessage) val, null,
                field.isAggregate() ? field.getGenericType() : field.getType());
    } else {
        return val;
    }
}

From source file:org.freebxml.omar.server.repository.filesystem.FileSystemRepositoryManager.java

/**
* Returns the RepositoryItem with the given unique ID.
*
* @param id Unique id for repository item
* @return RepositoryItem instance//  w  w w.j  a  v a  2s  .c o m
* @exception RegistryException
*/
public RepositoryItem getRepositoryItem(String id) throws RegistryException {
    RepositoryItem repositoryItem = null;
    String origId = id;

    // Strip off the "urn:uuid:"
    id = Utility.getInstance().stripId(id);

    try {
        String path = getRepositoryItemPath(id);
        File riFile = new File(path);

        if (!riFile.exists()) {
            String errmsg = ServerResourceBundle.getInstance().getString("message.RepositoryItemDoesNotExist",
                    new Object[] { id });
            log.error(errmsg);
            throw new RegistryException(errmsg);
        }

        DataHandler contentDataHandler = new DataHandler(new FileDataSource(riFile));

        Element sigElement = null;
        path += ".sig";

        File sigFile = new File(path);

        if (!sigFile.exists()) {
            String errmsg = "Payload signature for repository item id=\"" + id + "\" does not exist!";
            //log.error(errmsg);

            throw new RegistryException(errmsg);
        } else {

            javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory
                    .newInstance();
            dbf.setNamespaceAware(true);
            javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
            org.w3c.dom.Document sigDoc = db.parse(new FileInputStream(sigFile));

            repositoryItem = new RepositoryItemImpl(id, sigDoc.getDocumentElement(), contentDataHandler);
        }

    } catch (RegistryException e) {
        throw e;
    } catch (Exception e) {
        throw new RegistryException(e);
    }

    return repositoryItem;
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Uncompresses message data*/
public byte[] decompressData(AS2MessageInfo info, byte[] data, String contentType) throws Exception {
    MimeBodyPart compressedPart = new MimeBodyPart();
    compressedPart.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    compressedPart.setHeader("content-type", contentType);
    return (this.decompressData(info, new SMIMECompressed(compressedPart), compressedPart.getSize()));
}

From source file:com.github.thorqin.toolkit.mail.MailService.java

private void sendMail(Mail mail) {
    long beginTime = System.currentTimeMillis();
    Properties props = new Properties();
    final Session session;
    props.put("mail.smtp.auth", String.valueOf(setting.auth));
    // If want to display SMTP protocol detail then uncomment following statement
    // props.put("mail.debug", "true");
    props.put("mail.smtp.host", setting.host);
    props.put("mail.smtp.port", setting.port);
    if (setting.secure.equals(SECURE_STARTTLS)) {
        props.put("mail.smtp.starttls.enable", "true");

    } else if (setting.secure.equals(SECURE_SSL)) {
        props.put("mail.smtp.socketFactory.port", setting.port);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
    }/*from   w  ww. j a v  a  2s .  c  o m*/
    if (!setting.auth)
        session = Session.getInstance(props);
    else
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(setting.user, setting.password);
            }
        });

    if (setting.debug)
        session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    StringBuilder mailTo = new StringBuilder();
    try {
        if (mail.from != null)
            message.setFrom(new InternetAddress(mail.from));
        else if (setting.from != null)
            message.setFrom(new InternetAddress(setting.from));
        if (mail.to != null) {
            for (String to : mail.to) {
                if (mailTo.length() > 0)
                    mailTo.append(",");
                mailTo.append(to);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }
        }
        if (mail.subject != null)
            message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?=");
        message.setSentDate(new Date());

        BodyPart bodyPart = new MimeBodyPart();
        if (mail.htmlBody != null)
            bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8");
        else if (mail.textBody != null)
            bodyPart.setText(mail.textBody);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (mail.attachments != null) {
            for (String attachment : mail.attachments) {
                BodyPart attachedBody = new MimeBodyPart();
                File attachedFile = new File(attachment);
                DataSource source = new FileDataSource(attachedFile);
                attachedBody.setDataHandler(new DataHandler(source));
                attachedBody.setDisposition(MimeBodyPart.ATTACHMENT);
                String filename = attachedFile.getName();
                attachedBody.setFileName(
                        "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?=");
                multipart.addBodyPart(attachedBody);
            }
        }

        message.setContent(multipart);
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect();

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        if (setting.trace && tracer != null) {
            Tracer.Info info = new Tracer.Info();
            info.catalog = "mail";
            info.name = "send";
            info.put("sender", StringUtils.join(message.getFrom()));
            info.put("recipients", mail.to);
            info.put("SMTPServer", setting.host);
            info.put("SMTPAccount", setting.user);
            info.put("subject", mail.subject);
            info.put("startTime", beginTime);
            info.put("runningTime", System.currentTimeMillis() - beginTime);
            tracer.trace(info);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Send mail failed!", ex);
    }
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.ws.impl.MultimediaWSDaoTestBase.java

protected BlackboardMultimediaResponse createRepoMultimedia() throws Exception {
    InputStream is = new ByteArrayInputStream("fdsdfsfsdadsfasfda".getBytes());
    ByteArrayDataSource rawData = new ByteArrayDataSource(is, "video/mpeg");
    DataHandler dataHandler = new DataHandler(rawData);

    BlackboardMultimediaResponse uploadRepositoryMultimedia = dao.uploadRepositoryMultimedia(user.getEmail(),
            "test.mpeg", "aliens", dataHandler);
    multimedias.add(uploadRepositoryMultimedia.getMultimediaId());
    return uploadRepositoryMultimedia;
}

From source file:it.cnr.icar.eric.common.Utility.java

/**
 * Create a RepositoryItem containing provided content.
 *
 * @param id the id of the created ExtrinsicObject created for the RepositoryItem
 * @param content contents of the created RepositoryItem
 *
 * @return a <code>RepositoryItem</code> value
 * @throws IOException encountered during IO operations
 *//* w w w  .  ja v a  2s  .c  o  m*/
public RepositoryItem createRepositoryItem(String id, String content) throws IOException {
    File file = createTempFile(content, true);

    DataHandler dh = new DataHandler(new FileDataSource(file));
    RepositoryItem ri = new RepositoryItemImpl(id, dh);
    return ri;
}

From source file:org.bimserver.servlets.UploadServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getHeader("Origin") != null
            && !getBimServer().getServerSettingsCache().isHostAllowed(request.getHeader("Origin"))) {
        response.setStatus(403);//  www .  j ava 2s  . c  o  m
        return;
    }
    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");

    String token = (String) request.getSession().getAttribute("token");

    ObjectNode result = OBJECT_MAPPER.createObjectNode();
    response.setContentType("text/json");
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        long poid = -1;
        String comment = null;
        if (isMultipart) {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(request);
            InputStream in = null;
            String name = "";
            long deserializerOid = -1;
            boolean merge = false;
            boolean sync = false;
            String compression = null;
            String action = null;
            long topicId = -1;
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (item.isFormField()) {
                    if ("action".equals(item.getFieldName())) {
                        action = Streams.asString(item.openStream());
                    } else if ("token".equals(item.getFieldName())) {
                        token = Streams.asString(item.openStream());
                    } else if ("poid".equals(item.getFieldName())) {
                        poid = Long.parseLong(Streams.asString(item.openStream()));
                    } else if ("comment".equals(item.getFieldName())) {
                        comment = Streams.asString(item.openStream());
                    } else if ("topicId".equals(item.getFieldName())) {
                        topicId = Long.parseLong(Streams.asString(item.openStream()));
                    } else if ("sync".equals(item.getFieldName())) {
                        sync = Streams.asString(item.openStream()).equals("true");
                    } else if ("merge".equals(item.getFieldName())) {
                        merge = Streams.asString(item.openStream()).equals("true");
                    } else if ("compression".equals(item.getFieldName())) {
                        compression = Streams.asString(item.openStream());
                    } else if ("deserializerOid".equals(item.getFieldName())) {
                        deserializerOid = Long.parseLong(Streams.asString(item.openStream()));
                    }
                } else {
                    name = item.getName();
                    in = item.openStream();

                    if ("file".equals(action)) {
                        ServiceInterface serviceInterface = getBimServer().getServiceFactory()
                                .get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                        SFile file = new SFile();
                        byte[] data = IOUtils.toByteArray(in);
                        file.setData(data);
                        file.setSize(data.length);
                        file.setFilename(name);
                        file.setMime(item.getContentType());
                        result.put("fileId", serviceInterface.uploadFile(file));
                    } else if (poid != -1) {
                        InputStream realStream = null;
                        if ("gzip".equals(compression)) {
                            realStream = new GZIPInputStream(in);
                        } else if ("deflate".equals(compression)) {
                            realStream = new InflaterInputStream(in);
                        } else {
                            realStream = in;
                        }
                        InputStreamDataSource inputStreamDataSource = new InputStreamDataSource(realStream);
                        inputStreamDataSource.setName(name);
                        DataHandler ifcFile = new DataHandler(inputStreamDataSource);

                        if (token != null) {
                            if (topicId == -1) {
                                ServiceInterface service = getBimServer().getServiceFactory()
                                        .get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                                long newTopicId = service.checkin(poid, comment, deserializerOid, -1L, name,
                                        ifcFile, merge, sync);
                                result.put("topicId", newTopicId);
                            } else {
                                ServiceInterface service = getBimServer().getServiceFactory()
                                        .get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                                long newTopicId = service.checkinInitiated(topicId, poid, comment,
                                        deserializerOid, -1L, name, ifcFile, merge, true);
                                result.put("topicId", newTopicId);
                            }
                        }
                    } else {
                        result.put("exception", "No poid");
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("", e);
        sendException(response, e);
        return;
    }
    response.getWriter().write(result.toString());
}

From source file:mitm.djigzo.web.pages.admin.backup.BackupManager.java

private Object restore() {
    Check.notNull(file, "file");

    Object result = null;//  w w w.jav  a2s. com

    restoreFailure = false;

    try {
        DataSource source = new ByteArrayDataSource(file.getStream(), file.getContentType());
        DataHandler dataHandler = new DataHandler(source);

        BinaryDTO backup = new BinaryDTO(dataHandler);

        backupWS.restore(backup, password);

        result = Restarting.class;
    } catch (IOException e) {
        restoreFailure(e);
    } catch (WebServiceCheckedException e) {
        restoreFailure(e);
    }

    return result;
}

From source file:org.pentaho.platform.repository.subscription.SubscriptionEmailContent.java

public boolean send() {
    String cc = null;// w ww  .  ja va2s  .  co m
    String bcc = null;
    String from = props.getProperty("mail.from.default");
    String to = props.getProperty("to");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + "with the subject '" + subject
            + "' and the body " + body);

    try {
        // Get a Session object
        Session session;

        if (authenticate) {
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        Multipart multipart = new MimeMultipart();

        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        if (body != null) {
            MimeBodyPart textBodyPart = new MimeBodyPart();
            textBodyPart.setContent(body, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
            multipart.addBodyPart(textBodyPart);
        }

        // need to create a multi-part message...
        // create the Multipart and add its parts to it

        // create and fill the first message part
        IPentahoStreamSource source = attachment;
        if (source == null) {
            logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
            return false;
        }
        DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);

        // create the second message part
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();

        // attach the file to the message
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(attachmentName);

        multipart.addBodyPart(attachmentBodyPart);

        // add the Multipart to the message
        msg.setContent(multipart);

        msg.setHeader("X-Mailer", SubscriptionEmailContent.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
        // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$

    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}