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.sandesha2.mtom.MTOMRMTest.java

private void doInvocation(MessageContext mc) throws AxisFault {
    SOAPEnvelope envelope = mc.getEnvelope();

    assertNotNull(envelope);//from  w w  w  . jav a 2 s .  c  o  m

    SOAPBody body = envelope.getBody();

    OMElement payload = body.getFirstElement();
    OMElement attachmentElem = payload.getFirstChildWithName(new QName(applicationNamespaceName, Attachment));
    if (attachmentElem == null)
        throw new AxisFault("'Attachment' element is not present as a child of the 'Ping' element");

    OMText binaryElem = (OMText) attachmentElem.getFirstOMChild();

    binaryElem.setOptimize(true);
    DataHandler dataHandler = (DataHandler) binaryElem.getDataHandler();

    try {
        File destinationFile = new File(DESTINATION_IMAGE_FILE);
        if (destinationFile.exists())
            destinationFile.delete();

        FileOutputStream fileOutputStream = new FileOutputStream(DESTINATION_IMAGE_FILE);

        InputStream inputStream = dataHandler.getDataSource().getInputStream();
        byte[] bytes = new byte[5000];
        int length = inputStream.read(bytes);
        fileOutputStream.write(bytes, 0, length);
        fileOutputStream.close();

        destinationFile = new File(DESTINATION_IMAGE_FILE);
        assertTrue(destinationFile.exists());
        long destLength = destinationFile.length();
        assertEquals(sourceLength, destLength);

        destinationFile.delete();

    } catch (Exception e) {
        throw AxisFault.makeFault(e);
    }
}

From source file:org.apache.synapse.transport.passthru.util.ExpandingMessageFormatter.java

private void findAndWrite2OutputStream(MessageContext messageContext, OutputStream out, boolean preserve)
        throws AxisFault {
    try {/* w w  w .j a  va  2 s.  c o m*/
        SOAPEnvelope envelope = messageContext.getEnvelope();
        OMElement contentEle = envelope.getBody().getFirstElement();
        if (contentEle != null) {
            OMNode node = contentEle.getFirstOMChild();
            if (!(node instanceof OMText)) {
                String msg = "Wrong Input for the Validator, "
                        + "the content of the first child element of the Body " + "should have the zip file";
                log.error(msg);
                throw new AxisFault(msg);
            }
            OMText binaryDataNode = (OMText) node;
            DataHandler dh = (DataHandler) binaryDataNode.getDataHandler();

            DataSource dataSource = dh.getDataSource();
            //Ask the data source to stream, if it has not already cached the request
            if (!preserve && dataSource instanceof StreamingOnRequestDataSource) {
                ((StreamingOnRequestDataSource) dataSource).setLastUse(true);
            }
            dh.writeTo(out);
        }
    } catch (OMException e) {
        log.error(e);
        throw AxisFault.makeFault(e);
    } catch (IOException e) {
        log.error(e);
        throw AxisFault.makeFault(e);
    }
}

From source file:org.bimserver.shared.json.JsonConverter.java

public void toJson(Object object, JsonWriter out) throws IOException, SerializerException {
    if (object instanceof SBase) {
        SBase base = (SBase) object;//from  www .j a v a2s.com
        out.beginObject();
        out.name("__type");
        out.value(base.getSClass().getSimpleName());
        for (SField field : base.getSClass().getAllFields()) {
            out.name(field.getName());
            toJson(base.sGet(field), out);
        }
        out.endObject();
    } else if (object instanceof Collection) {
        Collection<?> collection = (Collection<?>) object;
        out.beginArray();
        for (Object value : collection) {
            toJson(value, out);
        }
        out.endArray();
    } else if (object instanceof Date) {
        out.value(((Date) object).getTime());
    } else if (object instanceof DataHandler) {
        DataHandler dataHandler = (DataHandler) object;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (dataHandler.getDataSource() instanceof CacheStoringEmfSerializerDataSource) {
            CacheStoringEmfSerializerDataSource cacheStoringEmfSerializerDataSource = (CacheStoringEmfSerializerDataSource) dataHandler
                    .getDataSource();
            cacheStoringEmfSerializerDataSource.writeToOutputStream(baos, null);
            out.value(new String(Base64.encodeBase64(baos.toByteArray()), Charsets.UTF_8));
        } else {
            InputStream inputStream = dataHandler.getInputStream();
            IOUtils.copy(inputStream, baos);
            out.value(new String(Base64.encodeBase64(baos.toByteArray()), Charsets.UTF_8));
        }
    } else if (object instanceof byte[]) {
        byte[] data = (byte[]) object;
        out.value(new String(Base64.encodeBase64(data), Charsets.UTF_8));
    } else if (object instanceof String) {
        out.value((String) object);
    } else if (object instanceof Number) {
        out.value((Number) object);
    } else if (object instanceof Enum) {
        out.value(object.toString());
    } else if (object instanceof Boolean) {
        out.value((Boolean) object);
    } else if (object == null) {
        out.nullValue();
    } else {
        throw new UnsupportedOperationException(object.toString());
    }
}

From source file:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java

protected void addAttachments(MailTemplate template, WorkItem workItem, Multipart multipart,
        JCRSessionWrapper session) throws Exception {
    for (AttachmentTemplate attachmentTemplate : template.getAttachmentTemplates()) {
        BodyPart attachmentPart = new MimeBodyPart();

        // resolve description
        String description = attachmentTemplate.getDescription();
        if (description != null) {
            attachmentPart.setDescription(evaluateExpression(workItem, description, session));
        }//from  w  ww. j a  v  a2s .  co  m

        // obtain interface to data
        DataHandler dataHandler = createDataHandler(attachmentTemplate, workItem, session);
        attachmentPart.setDataHandler(dataHandler);

        // resolve file name
        String name = attachmentTemplate.getName();
        if (name != null) {
            attachmentPart.setFileName(evaluateExpression(workItem, name, session));
        } else {
            // fall back on data source
            DataSource dataSource = dataHandler.getDataSource();
            if (dataSource instanceof URLDataSource) {
                name = extractResourceName(((URLDataSource) dataSource).getURL());
            } else {
                name = dataSource.getName();
            }
            if (name != null) {
                attachmentPart.setFileName(name);
            }
        }

        multipart.addBodyPart(attachmentPart);
    }
}

From source file:org.jboss.bpm.console.server.FormProcessingFacade.java

private Response provideForm(FormAuthorityRef authorityRef) {
    DataHandler dh = getFormDispatcherPlugin().provideForm(authorityRef);

    if (null == dh) {
        throw new RuntimeException(
                "No UI associated with " + authorityRef.getType() + " " + authorityRef.getReferenceId());
    }/* w w w .  ja va  2s  .c o m*/

    return Response.ok(dh.getDataSource()).type("text/html").build();
}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest.java

protected MultipartRequestEntity createMultiPart(MuleMessage msg, EntityEnclosingMethod method)
        throws Exception {
    Part[] parts;//ww w.  j ava  2  s  .  c  o m
    int i = 0;
    if (msg.getPayload() instanceof NullPayload) {
        parts = new Part[msg.getOutboundAttachmentNames().size()];
    } else {
        parts = new Part[msg.getOutboundAttachmentNames().size() + 1];
        parts[i++] = new FilePart("payload", new ByteArrayPartSource("payload", msg.getPayloadAsBytes()));
    }

    for (final Iterator<String> iterator = msg.getOutboundAttachmentNames().iterator(); iterator
            .hasNext(); i++) {
        final String attachmentNames = iterator.next();
        String fileName = attachmentNames;
        final DataHandler dh = msg.getOutboundAttachment(attachmentNames);
        if (dh.getDataSource() instanceof StringDataSource) {
            final StringDataSource ds = (StringDataSource) dh.getDataSource();
            parts[i] = new StringPart(ds.getName(), IOUtils.toString(ds.getInputStream()));
        } else {
            if (dh.getDataSource() instanceof FileDataSource) {
                fileName = ((FileDataSource) dh.getDataSource()).getFile().getName();
            } else if (dh.getDataSource() instanceof URLDataSource) {
                fileName = ((URLDataSource) dh.getDataSource()).getURL().getFile();
                // Don't use the whole file path, just the file name
                final int x = fileName.lastIndexOf("/");
                if (x > -1) {
                    fileName = fileName.substring(x + 1);
                }
            }
            parts[i] = new FilePart(dh.getName(),
                    new ByteArrayPartSource(fileName, IOUtils.toByteArray(dh.getInputStream())),
                    dh.getContentType(), null);
        }
    }

    return new MultipartRequestEntity(parts, method.getParams());
}

From source file:org.openehealth.ipf.platform.camel.lbs.cxf.process.CxfPojoResourceHandler.java

private ResourceDataSource getResource(DataHandler handler) {
    DataSource dataSource = handler.getDataSource();
    if (dataSource instanceof ResourceDataSource) {
        return (ResourceDataSource) dataSource;
    }//from  ww  w . j a  v a 2  s  . c o m
    return null;
}

From source file:org.paxle.core.doc.impl.jaxb.JaxbFileAdapter.java

/**
 * Converts the {@link DataHandler} into a {@link File}.
 * The file is created via the {@link ITempFileManager}.
 *///from   w w w . j ava 2s  .c  o m
@Override
public File unmarshal(DataHandler dataHandler) throws Exception {
    if (dataHandler == null)
        return null;

    final DataSource dataSource = dataHandler.getDataSource();
    if (dataSource != null) {
        String cid = null;

        // avoid deserializing a file twice
        for (Entry<String, DataHandler> attachment : attachments.entrySet()) {
            if (attachment.getValue().equals(dataHandler)) {
                cid = attachment.getKey();
                break;
            }
        }

        if (cid != null && this.cidFileMap.containsKey(cid)) {
            return this.cidFileMap.get(cid);
        }

        File tempFile = null;
        InputStream input = null;
        OutputStream output = null;

        try {
            // getting the input stream
            input = dataSource.getInputStream();

            // getting the output stream
            tempFile = this.tempFileManager.createTempFile();
            output = new BufferedOutputStream(new FileOutputStream(tempFile));

            // copy data
            long byteCount = IOUtils.copy(input, output);
            if (this.logger.isDebugEnabled()) {
                this.logger.debug(String.format("%d bytes copied from the data-source into the temp-file '%s'.",
                        Long.valueOf(byteCount), tempFile.getName()));
            }

            if (cid != null) {
                this.cidFileMap.put(cid, tempFile);
            }
            return tempFile;
        } catch (IOException e) {
            this.logger.error(String.format("Unexpected '%s' while loading datasource '%s' (CID=%s).",
                    e.getClass().getName(), dataSource.getName(), cid), e);

            // delete the temp file on errors
            if (tempFile != null && this.tempFileManager.isKnown(tempFile)) {
                this.tempFileManager.releaseTempFile(tempFile);
            }

            // re-throw exception
            throw e;
        } finally {
            // closing streams
            if (input != null)
                input.close();
            if (output != null)
                output.close();
        }
    }
    return null;
}

From source file:org.simplejavamail.internal.util.MimeMessageParser.java

/**
 * Parses the MimePart to create a DataSource.
 *
 * @param part   the current part to be processed
 * @return the DataSource/*from   w  ww .j  a  va 2 s . com*/
 * @throws MessagingException creating the DataSource failed
 * @throws IOException        creating the DataSource failed
 */
private static DataSource createDataSource(final MimePart part) throws MessagingException, IOException {
    final DataHandler dataHandler = part.getDataHandler();
    final DataSource dataSource = dataHandler.getDataSource();
    final String contentType = getBaseMimeType(dataSource.getContentType());
    final byte[] content = MimeMessageParser.getContent(dataSource.getInputStream());
    final ByteArrayDataSource result = new ByteArrayDataSource(content, contentType);
    final String dataSourceName = getDataSourceName(part, dataSource);

    result.setName(dataSourceName);
    return result;
}

From source file:org.wso2.appserver.integration.tests.wsdl2java.HelloServiceCodeGenTestCase.java

@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = "wso2.as", description = "generate client code HelloWorld service")
public void testGeneratedClass() throws Exception {

    WSDL2CodeClient wsdl2CodeClient = new WSDL2CodeClient(backendURL, sessionCookie);
    String wsdlURL = asServer.getContextUrls().getServiceUrl() + "/HelloService?wsdl";
    log.info("Service URL -" + wsdlURL);
    String[] options = new String[] { "-gid", "WSO2", "-aid", "WSO2-Axis2-Client", "-vn", "0.0.1-SNAPSHOT",
            "-uri", wsdlURL, "-l", "java", "-d", "adb", "-wv", "1.1" };
    DataHandler dataHandler = wsdl2CodeClient.codeGen(options);
    InputStream in = null;/*  w w w. j a v  a 2 s.c o  m*/
    OutputStream outputStream = null;

    try {
        in = dataHandler.getDataSource().getInputStream();
        //save generated zip
        outputStream = new FileOutputStream(new File(baseDir + File.separator + "generated.zip"));

        int read;
        byte[] bytes = new byte[1024];

        while ((read = in.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
    } finally {
        assert in != null;
        in.close();
        assert outputStream != null;
        outputStream.close();
    }
    log.info("Done!");
}