Example usage for javax.activation DataHandler getDataSource

List of usage examples for javax.activation DataHandler getDataSource

Introduction

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

Prototype

public DataSource getDataSource() 

Source Link

Document

Return the DataSource associated with this instance of DataHandler.

Usage

From source file:org.apache.axis.attachments.AttachmentsImpl.java

/**
 * Write the content to the stream./*from   w w w  . ja  v a  2 s. c  om*/
 *
 * @param os
 *
 * @throws org.apache.axis.AxisFault
 */
public void writeContentToStream(java.io.OutputStream os) throws org.apache.axis.AxisFault {
    int sendtype = this.sendtype == SEND_TYPE_NOTSET ? SEND_TYPE_DEFAULT : this.sendtype;
    try {

        mergeinAttachments();
        if (sendtype == SEND_TYPE_MIME || sendtype == SEND_TYPE_MTOM) {
            org.apache.axis.attachments.MimeUtils.writeToMultiPartStream(os,
                    (multipart != null) ? multipart
                            : (multipart = org.apache.axis.attachments.MimeUtils
                                    .createMP(soapPart.getAsString(), orderedAttachments, getSendType())));

            for (java.util.Iterator i = orderedAttachments.iterator(); i.hasNext();) {
                AttachmentPart part = (AttachmentPart) i.next();
                DataHandler dh = AttachmentUtils.getActivationDataHandler(part);
                DataSource ds = dh.getDataSource();

                if ((ds != null) && (ds instanceof ManagedMemoryDataSource)) {
                    ((ManagedMemoryDataSource) ds).delete();
                }
            }
        } else if (sendtype == SEND_TYPE_DIME)
            createDimeMessage().write(os);
    } catch (Exception e) {
        throw org.apache.axis.AxisFault.makeFault(e);
    }
}

From source file:org.apache.axis.attachments.DimeBodyPart.java

protected long getDataSize(DataHandler dh) {
    long dataSize = -1L;

    try {/*from w  w  w  . j a va2s.co m*/
        DataSource ds = dh.getDataSource();

        //Do files our selfs since this is costly to read in. Ask the file system.
        // This is 90% of the use of attachments.
        if (ds instanceof javax.activation.FileDataSource) {
            javax.activation.FileDataSource fdh = (javax.activation.FileDataSource) ds;
            java.io.File df = fdh.getFile();

            if (!df.exists()) {
                throw new RuntimeException(Messages.getMessage("noFile", df.getAbsolutePath()));
            }
            dataSize = df.length();
        } else {
            dataSize = 0;
            java.io.InputStream in = ds.getInputStream();
            byte[] readbuf = new byte[64 * 1024];
            int bytesread;

            do {
                bytesread = in.read(readbuf);
                if (bytesread > 0)
                    dataSize += bytesread;
            } while (bytesread > -1);

            if (in.markSupported()) {
                //Leave the stream open for future reading
                // and reset the stream pointer to the first byte
                in.reset();
            } else {
                //FIXME: bug http://nagoya.apache.org/jira/secure/ViewIssue.jspa?key=AXIS-1126
                //if we close this then how can we read the file? eh?
                in.close();
            }
        }
    } catch (Exception e) {
        //TODO: why are exceptions swallowed here?
        log.error(Messages.getMessage("exception00"), e);
    }
    return dataSize;
}

From source file:org.apache.axis.attachments.MimeUtils.java

/**
 * Determine the length for the individual part.
 * @param bp is the part to be searched.
 * @return the length in bytes./*from ww  w  . ja va 2  s  .  co  m*/
 */
protected static long getContentLength(javax.mail.internet.MimeBodyPart bp) {

    long headerLength = -1L;
    long dataSize = -1L;

    try {
        headerLength = getHeaderLength(bp);

        javax.activation.DataHandler dh = bp.getDataHandler();
        javax.activation.DataSource ds = dh.getDataSource();

        // Do files our selfs since this is costly to read in. Ask the file system.
        // This is 90% of the use of attachments.
        if (ds instanceof javax.activation.FileDataSource) {
            javax.activation.FileDataSource fdh = (javax.activation.FileDataSource) ds;
            java.io.File df = fdh.getFile();

            if (!df.exists()) {
                throw new RuntimeException(Messages.getMessage("noFile", df.getAbsolutePath()));
            }

            dataSize = df.length();
        } else {
            dataSize = bp.getSize();

            if (-1 == dataSize) { // Data size is not known so read it the hard way...
                dataSize = 0;

                java.io.InputStream in = ds.getInputStream();
                byte[] readbuf = new byte[64 * 1024];
                int bytesread;

                do {
                    bytesread = in.read(readbuf);

                    if (bytesread > 0) {
                        dataSize += bytesread;
                    }
                } while (bytesread > -1);

                in.close();
            }
        }
    } catch (Exception e) {
        log.error(Messages.getMessage("exception00"), e);
    }

    return dataSize + headerLength;
}

From source file:org.apache.axis.encoding.ser.MimeMultipartDataHandlerDeserializer.java

public void startElement(String namespace, String localName, String prefix, Attributes attributes,
        DeserializationContext context) throws SAXException {

    super.startElement(namespace, localName, prefix, attributes, context);

    if (getValue() instanceof DataHandler) {
        try {//from ww  w. j a v a  2  s.com
            DataHandler dh = (DataHandler) getValue();
            MimeMultipart mmp = new MimeMultipart(dh.getDataSource());
            if (mmp.getCount() == 0) {
                mmp = null;
            }
            setValue(mmp);
        } catch (Exception e) {
            throw new SAXException(e);
        }
    }
}

From source file:org.apache.axis2.databinding.utils.ConverterUtil.java

/**
 * Converts the given .datahandler to a string
 *
 * @return string// w w  w .  j a va2s . com
 */
public static String getStringFromDatahandler(DataHandler dataHandler) {
    try {
        InputStream inStream;
        if (dataHandler == null) {
            return "";
        }
        inStream = dataHandler.getDataSource().getInputStream();
        byte[] data = IOUtils.getStreamAsByteArray(inStream);
        return Base64.encode(data);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.axis2.jaxws.message.attachments.AttachmentUtils.java

/**
 * Process attachment's dataHandlers for CachedFileDataSource.
 * If exist, execute file.deleteOnExit() request on the cached
 * attachment file referenced by each CachedFileDataSource.
 * This will delete the cached attachment file on JVM exit.
 * /* w w  w . j  a va2  s  .c  o m*/
 * @param attachments
 */
public static void findCachedAttachment(Attachments attachments) {
    if (attachments == null) {
        return;
    }

    String[] contentIds = attachments.getAllContentIDs();
    if (contentIds.length > 0) {
        if (log.isDebugEnabled()) {
            log.debug("Attachments exist....");
        }
        for (int i = 0; i < contentIds.length; i++) {
            DataHandler dh = attachments.getDataHandler(contentIds[i]);
            if (dh != null) {
                DataSource dataSource = dh.getDataSource();
                if (dh != null && dataSource instanceof CachedFileDataSource) {
                    if (log.isDebugEnabled()) {
                        log.debug("Attachment's DataHandler uses CachedFileDataSource...");
                    }
                    File file = ((CachedFileDataSource) dataSource).getFile();
                    if (log.isDebugEnabled()) {
                        log.debug(" Making file.deleteOnExit() request on " + file.getAbsolutePath());
                    }
                    file.deleteOnExit();
                }
            }
        }
    }
}

From source file:org.apache.axis2.mtom.EchoRawMTOMTest.java

public void testEchoXMLSync() throws Exception {
    OMElement payload = createEnvelope();
    Options options = new Options();
    options.setTo(targetEPR);/* w  w  w.j  ava2  s  . com*/
    options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
    options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
    options.setSoapVersionURI(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
            TestingUtils.prefixBaseDirectory("target/test-resources/integrationRepo"), null);

    ServiceClient sender = new ServiceClient(configContext, null);
    options.setAction(Constants.AXIS2_NAMESPACE_URI + "/" + operationName.getLocalPart());
    sender.setOptions(options);
    options.setTo(targetEPR);
    OMElement result = sender.sendReceive(payload);

    OMElement ele = (OMElement) result.getFirstOMChild();
    OMText binaryNode = (OMText) ele.getFirstOMChild();

    // to the assert equal
    compareWithCreatedOMText(binaryNode);

    // Save the image
    DataHandler actualDH;
    actualDH = (DataHandler) binaryNode.getDataHandler();
    ImageIO.read(actualDH.getDataSource().getInputStream());
}

From source file:org.apache.camel.component.jetty.MultiPartFormTest.java

protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        public void configure() throws Exception {
            // START SNIPPET: e1
            // Set the jetty temp directory which store the file for multi part form
            // camel-jetty will clean up the file after it handled the request.
            // The option works rightly from Camel 2.4.0
            getContext().getProperties().put("CamelJettyTempDir", "target");

            from("jetty://http://localhost:{{port}}/test").process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    Message in = exchange.getIn();
                    assertEquals("Get a wrong attachement size", 1, in.getAttachments().size());
                    // The file name is attachment id
                    DataHandler data = in.getAttachment("NOTICE.txt");

                    assertNotNull("Should get the DataHandle NOTICE.txt", data);
                    // This assert is wrong, but the correct content-type (application/octet-stream)
                    // will not be returned until Jetty makes it available - currently the content-type
                    // returned is just the default for FileDataHandler (for the implentation being used)
                    //assertEquals("Get a wrong content type", "text/plain", data.getContentType());
                    assertEquals("Got the wrong name", "NOTICE.txt", data.getName());

                    assertTrue("We should get the data from the DataHandle",
                            data.getDataSource().getInputStream().available() > 0);

                    // The other form date can be get from the message header
                    exchange.getOut().setBody(in.getHeader("comment"));
                }// ww w .j a  v  a 2 s.co  m

            });
            // END SNIPPET: e1
        }
    };
}

From source file:org.apache.camel.component.jetty.MultiPartFormTestWithCustomFilter.java

protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        public void configure() throws Exception {
            // START SNIPPET: e1
            // Set the jetty temp directory which store the file for multi part form
            // camel-jetty will clean up the file after it handled the request.
            // The option works rightly from Camel 2.4.0
            getContext().getProperties().put("CamelJettyTempDir", "target");

            from("jetty://http://localhost:9080/test?multipartFilterRef=myMultipartFilter")
                    .process(new Processor() {
                        public void process(Exchange exchange) throws Exception {
                            Message in = exchange.getIn();
                            assertEquals("Get a wrong attachement size", 1, in.getAttachments().size());
                            // The file name is attachment id
                            DataHandler data = in.getAttachment("NOTICE.txt");

                            assertNotNull("Should get the DataHandle NOTICE.txt", data);
                            assertEquals("Get a wrong content type", "text/plain", data.getContentType());
                            assertEquals("Got the wrong name", "NOTICE.txt", data.getName());

                            assertTrue("We should get the data from the DataHandle",
                                    data.getDataSource().getInputStream().available() > 0);

                            // The other form date can be get from the message header
                            exchange.getOut().setBody(in.getHeader("comment"));
                        }/*from w  w w. j  av  a 2 s. co  m*/
                    });
            // END SNIPPET: e1

            // Test to ensure that setting a multipartFilterRef overrides the enableMultipartFilter=false parameter
            from("jetty://http://localhost:9080/test2?multipartFilterRef=myMultipartFilter&enableMultipartFilter=false")
                    .process(new Processor() {
                        public void process(Exchange exchange) throws Exception {
                            Message in = exchange.getIn();
                            assertEquals("Get a wrong attachement size", 1, in.getAttachments().size());
                            DataHandler data = in.getAttachment("NOTICE.txt");

                            assertNotNull("Should get the DataHandle NOTICE.txt", data);
                            // The other form date can be get from the message header
                            exchange.getOut().setBody(in.getHeader("comment"));
                        }
                    });
        }
    };
}

From source file:org.apache.camel.component.jetty.MultiPartFormWithCustomFilterTest.java

protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        public void configure() throws Exception {
            // START SNIPPET: e1
            // Set the jetty temp directory which store the file for multi part form
            // camel-jetty will clean up the file after it handled the request.
            // The option works rightly from Camel 2.4.0
            getContext().getProperties().put("CamelJettyTempDir", "target");

            from("jetty://http://localhost:{{port}}/test?multipartFilterRef=myMultipartFilter")
                    .process(new Processor() {
                        public void process(Exchange exchange) throws Exception {
                            Message in = exchange.getIn();
                            assertEquals("Get a wrong attachement size", 1, in.getAttachments().size());
                            // The file name is attachment id
                            DataHandler data = in.getAttachment("NOTICE.txt");

                            assertNotNull("Should get the DataHandle NOTICE.txt", data);
                            // This assert is wrong, but the correct content-type (application/octet-stream)
                            // will not be returned until Jetty makes it available - currently the content-type
                            // returned is just the default for FileDataHandler (for the implentation being used)
                            //assertEquals("Get a wrong content type", "text/plain", data.getContentType());
                            assertEquals("Got the wrong name", "NOTICE.txt", data.getName());

                            assertTrue("We should get the data from the DataHandle",
                                    data.getDataSource().getInputStream().available() > 0);

                            // The other form date can be get from the message header
                            exchange.getOut().setBody(in.getHeader("comment"));
                        }// w  w w .j av a 2s  .com
                    });
            // END SNIPPET: e1

            // Test to ensure that setting a multipartFilterRef overrides the enableMultipartFilter=false parameter
            from("jetty://http://localhost:{{port}}/test2?multipartFilterRef=myMultipartFilter&enableMultipartFilter=false")
                    .process(new Processor() {
                        public void process(Exchange exchange) throws Exception {
                            Message in = exchange.getIn();
                            assertEquals("Get a wrong attachement size", 1, in.getAttachments().size());
                            DataHandler data = in.getAttachment("NOTICE.txt");

                            assertNotNull("Should get the DataHandle NOTICE.txt", data);
                            // The other form date can be get from the message header
                            exchange.getOut().setBody(in.getHeader("comment"));
                        }
                    });
        }
    };
}