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:es.caib.sgtsic.xml.XmlManager.java

public DataHandler generateXml(List<T> items) throws JAXBException {

    byte[] b = generateXmlString(items).getBytes();
    String mimetype = "text/plain";
    DataSource ds = new ByteArrayDataSource(b, mimetype);
    return new DataHandler(ds);

}

From source file:com.googlecode.ddom.frontend.saaj.impl.SwAProfile.java

@Override
public MessageDeserializer createDeserializer(InputStream in) {
    // TODO: optimize this and add support for lazy loading of attachments
    final MultipartReader mpr = new MultipartReader(in, boundary);
    return new MessageDeserializer() {
        public MimeHeaders getSOAPPartHeaders() throws IOException, SOAPException {
            if (!mpr.nextPart()) {
                throw new SOAPException("Message has no SOAP part");
            }//from  w w w .  j  a  v  a 2s  .  c  om
            return readMimeHeaders(mpr);
        }

        public InputStream getSOAPPartInputStream() throws IOException, SOAPException {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(mpr.getContent(), baos);
            return new ByteArrayInputStream(baos.toByteArray());
        }

        public AttachmentSet getAttachments() throws IOException, SOAPException {
            AttachmentSet attachments = new SimpleAttachmentSet();
            while (mpr.nextPart()) {
                // TODO: shouldn't we have a factory method in AttachmentSet?
                AttachmentPartImpl attachment = new AttachmentPartImpl(readMimeHeaders(mpr));
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                IOUtils.copy(mpr.getContent(), baos);
                attachment.setDataHandler(new DataHandler(
                        new ByteArrayDataSource(baos.toByteArray(), attachment.getContentType())));
                attachments.add(attachment);
            }
            return attachments;
        }
    };
}

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

public static boolean prepareRequestPart(WsdlRequest wsdlRequest, MimeMultipart mp, RequestXmlPart requestPart,
        StringToStringMap contentIds) throws Exception, MessagingException {
    boolean isXop = false;

    XmlCursor cursor = requestPart.newCursor();

    try {//from  w  w  w  . ja v  a  2 s.c om
        while (!cursor.isEnddoc()) {
            if (cursor.isContainer()) {
                // could be an attachment part (as of "old" SwA specs which specify a content 
                // element referring to the attachment)
                if (requestPart.isAttachmentPart()) {
                    String href = cursor.getAttributeText(new QName("href"));
                    if (href != null && href.length() > 0) {
                        contentIds.put(requestPart.getPart().getName(), href);
                    }

                    break;
                }

                SchemaType schemaType = cursor.getObject().schemaType();
                if (isBinaryType(schemaType)) {
                    String contentType = getXmlMimeContentType(cursor);

                    // extract contentId
                    String textContent = cursor.getTextValue();
                    Attachment attachment = null;
                    boolean isXopAttachment = false;

                    // is content a reference to a file?
                    if (textContent.startsWith("file:")) {
                        String filename = textContent.substring(5);
                        if (contentType == null) {
                            inlineData(cursor, schemaType, new FileInputStream(filename));
                        } else if (wsdlRequest.isMtomEnabled()) {
                            MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                            part.setDataHandler(new DataHandler(
                                    new XOPPartDataSource(new File(filename), contentType, schemaType)));
                            part.setContentID("<" + filename + ">");
                            mp.addBodyPart(part);

                            isXopAttachment = true;
                        }
                    }
                    // is content a reference to an attachment?
                    else if (textContent.startsWith("cid:")) {
                        textContent = textContent.substring(4);
                        Attachment[] attachments = wsdlRequest.getAttachmentsForPart(textContent);
                        if (attachments.length == 1) {
                            attachment = attachments[0];
                        } else if (attachments.length > 1) {
                            attachment = buildMulitpartAttachment(attachments);
                        }

                        isXopAttachment = contentType != null;
                        contentIds.put(textContent, textContent);
                    }
                    // content should be binary data; is this an XOP element which should be serialized with MTOM?
                    else if (wsdlRequest.isMtomEnabled() && contentType != null) {
                        MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                        part.setDataHandler(
                                new DataHandler(new XOPPartDataSource(textContent, contentType, schemaType)));

                        textContent = "http://www.soapui.org/" + System.nanoTime();

                        part.setContentID("<" + textContent + ">");
                        mp.addBodyPart(part);

                        isXopAttachment = true;
                    }

                    // add XOP include?
                    if (isXopAttachment && wsdlRequest.isMtomEnabled()) {
                        buildXopInclude(cursor, textContent);
                        isXop = true;
                    }
                    // inline?
                    else if (attachment != null) {
                        inlineAttachment(cursor, schemaType, attachment);
                    }
                }
            }

            cursor.toNextToken();
        }
    } finally {
        cursor.dispose();
    }

    return isXop;
}

From source file:org.wso2.bps.integration.common.clients.bpmn.BPMNUploaderClient.java

private void deployPackage(String packageName, String resourceDir,
        BPMNUploaderServiceStub bpmnUploaderServiceStub) throws RemoteException, InterruptedException {

    String sampleArchiveName = packageName + ".bar";
    log.info(resourceDir + File.separator + sampleArchiveName);
    DataSource BPMNDataSource = new FileDataSource(resourceDir + File.separator + sampleArchiveName);
    UploadedFileItem[] uploadedFileItems = new UploadedFileItem[1];
    uploadedFileItems[0] = getUploadedFileItem(new DataHandler(BPMNDataSource), sampleArchiveName, "bar");
    log.info("Deploying " + sampleArchiveName);
    bpmnUploaderServiceStub.uploadService(uploadedFileItems);
}

From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {// w w  w . j a  va2 s . co m
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}

From source file:org.wso2.appserver.integration.tests.jarservice.JARServiceTestCase.java

@Test(groups = "wso2.as", description = "Upload jar service and verify deployment")
public void jarServiceUpload() throws Exception {
    JARServiceUploaderClient jarServiceUploaderClient = new JARServiceUploaderClient(backendURL, sessionCookie);
    List<DataHandler> jarList = new ArrayList<DataHandler>();
    URL url = new URL("file://" + FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator
            + "AS" + File.separator + "jar" + File.separator + "artifact1" + File.separator + "JarService.jar");
    DataHandler dh = new DataHandler(url);
    jarList.add(dh);//from   w  w  w.j av a 2s. co m
    jarServiceUploaderClient.uploadJARServiceFile("", jarList, dh);
    isServiceDeployed(jarService);
    log.info("JarService.jar uploaded successfully");
}

From source file:common.email.MailServiceImpl.java

/**
 * this method sends email using a given template
 * @param subject subject of a mail//from   w  w  w  .  j av  a  2s  .  com
 * @param recipientEmail email receiver adress
 * @param mail mail text to send
 * @param from will be set
* @return true if send succeed
* @throws java.io.FileNotFoundException
 * @throws java.io.IOException
 */
protected boolean postMail(String subject, String recipientEmail, String from, String mail) throws IOException {
    try {
        Properties props = new Properties();
        //props.put("mailHost", mailHost);

        Session session = Session.getInstance(props);
        // construct the message
        javax.mail.Message msg = new javax.mail.internet.MimeMessage(session);
        if (from == null) {
            msg.setFrom();
        } else {
            try {
                msg.setFrom(new InternetAddress(from));
            } catch (MessagingException ex) {
                logger.error(ex);
            }
        }
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        //msg.setHeader("", user)
        msg.setDataHandler(new DataHandler(new ByteArrayDataSource(mail, "text/html; charset=UTF-8")));

        SMTPTransport t = (SMTPTransport) session.getTransport("smtp");
        t.connect(mailHost, user, password);
        Address[] a = msg.getAllRecipients();
        t.sendMessage(msg, a);
        t.close();
        return true;
    } catch (MessagingException ex) {
        logger.error(ex);
        ex.printStackTrace();
        return false;
    }

}

From source file:org.wso2.carbon.esb.security.policy.ESBJAVA3899_PolicyReferenceInWSDLBindingsTestCase.java

private void uploadResourcesToConfigRegistry() throws Exception {
    ResourceAdminServiceClient resourceAdminServiceStub = new ResourceAdminServiceClient(
            contextUrls.getBackEndUrl(), getSessionCookie());

    resourceAdminServiceStub.addResource("/_system/config/repository/server-policy.xml", "application/xml",
            "policy file", new DataHandler(new URL(
                    "file:///" + getESBResourceLocation() + "/security/ESBJAVA3899/server-policy.xml")));
    Thread.sleep(4000);/*from  ww w  .j  ava  2 s  . c o m*/
}

From source file:es.caib.sgtsic.xml.XmlManager.java

public DataHandler generateFlatXml(List<T> items) throws JAXBException {

    byte[] b = generateFlatXmlString(items).getBytes();
    String mimetype = "text/plain";
    DataSource ds = new ByteArrayDataSource(b, mimetype);
    return new DataHandler(ds);

}

From source file:de.kp.ames.web.function.transform.XslConsumer.java

/**
 * Attach XSL result (stream) to the target object
 * /*from w  w  w  .  j av  a2  s  .  c o  m*/
 * @param target
 * @param stream
 * @return
 * @throws Exception
 */
public String setRepositoryItem(String target, InputStream stream) throws Exception {
    /* 
     * Determine target object from unique identifier
     */
    RegistryObjectImpl ro = getRegistryObjectById(target);
    if (ro == null)
        throw new Exception("[XslConsumer] Target object not found.");

    String objectType = ro.getObjectType().getKey().getId();
    if (objectType.startsWith(EXTRINSIC_OBJECT)) {
        /*
         * The stream must be allocated to an existing extrinsic object
         */
        ExtrinsicObjectImpl eo = (ExtrinsicObjectImpl) ro;
        eo.setMimeType(GlobalConstants.MT_XML);

        /*
         * Create and set repository item
         */
        byte[] bytes = FileUtil.getByteArrayFromInputStream(stream);

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

        /*
         * Save extrinsic object
         */
        ArrayList<RegistryObjectImpl> objectsToSave = new ArrayList<RegistryObjectImpl>();
        objectsToSave.add(eo);

        saveObjects(objectsToSave, false, false);

        /*
         * Build response
         */
        JSONObject jResponse = new JSONObject();
        jResponse.put("uid", target);

        return jResponse.toString();

    } else {
        throw new Exception("[XslConsumer] The object type " + objectType + " is not supported.");

    }

}