Search in sources :

Example 11 with AttachmentImpl

use of org.apache.cxf.attachment.AttachmentImpl in project cxf by apache.

the class SwAOutInterceptor method processAttachments.

protected void processAttachments(SoapMessage message, SoapBodyInfo sbi) {
    Collection<Attachment> atts = setupAttachmentOutput(message);
    List<Object> outObjects = CastUtils.cast(message.getContent(List.class));
    for (MessagePartInfo mpi : sbi.getAttachments()) {
        String partName = mpi.getConcreteName().getLocalPart();
        String ct = (String) mpi.getProperty(Message.CONTENT_TYPE);
        String id = new StringBuilder().append(partName).append('=').append(UUID.randomUUID()).append("@apache.org").toString();
        // this assumes things are in order...
        int idx = mpi.getIndex();
        Object o = outObjects.get(idx);
        if (o == null) {
            continue;
        }
        outObjects.set(idx, null);
        DataHandler dh;
        // This code could probably be refactored out somewhere...
        if (o instanceof Source) {
            dh = new DataHandler(createDataSource((Source) o, ct));
        } else if (o instanceof Image) {
            final Image img = (Image) o;
            final String contentType = ct;
            dh = new DataHandler(o, ct) {

                @Override
                public InputStream getInputStream() throws IOException {
                    LoadingByteArrayOutputStream bout = new LoadingByteArrayOutputStream();
                    writeTo(bout);
                    return bout.createInputStream();
                }

                @Override
                public void writeTo(OutputStream out) throws IOException {
                    ImageWriter writer = null;
                    Iterator<ImageWriter> writers = ImageIO.getImageWritersByMIMEType(contentType);
                    if (writers.hasNext()) {
                        writer = writers.next();
                    }
                    if (writer != null) {
                        BufferedImage bimg = convertToBufferedImage(img);
                        ImageOutputStream iout = ImageIO.createImageOutputStream(out);
                        writer.setOutput(iout);
                        writer.write(bimg);
                        writer.dispose();
                        iout.flush();
                        out.flush();
                    }
                }
            };
        } else if (o instanceof DataHandler) {
            dh = (DataHandler) o;
            ct = dh.getContentType();
            try {
                if ("text/xml".equals(ct) && dh.getContent() instanceof Source) {
                    dh = new DataHandler(createDataSource((Source) dh.getContent(), ct));
                }
            } catch (IOException e) {
            // ignore, use same dh
            }
        } else if (o instanceof byte[]) {
            if (ct == null) {
                ct = "application/octet-stream";
            }
            dh = new DataHandler(new ByteDataSource((byte[]) o, ct));
        } else if (o instanceof String) {
            if (ct == null) {
                ct = "text/plain; charset=\'UTF-8\'";
            }
            dh = new DataHandler(new ByteDataSource(((String) o).getBytes(StandardCharsets.UTF_8), ct));
        } else {
            throw new Fault(new org.apache.cxf.common.i18n.Message("ATTACHMENT_NOT_SUPPORTED", LOG, o.getClass()));
        }
        AttachmentImpl att = new AttachmentImpl(id);
        att.setDataHandler(dh);
        att.setHeader("Content-Type", ct);
        att.setHeader("Content-ID", "<" + id + ">");
        atts.add(att);
    }
}
Also used : LoadingByteArrayOutputStream(org.apache.cxf.helpers.LoadingByteArrayOutputStream) ImageOutputStream(javax.imageio.stream.ImageOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ImageWriter(javax.imageio.ImageWriter) Attachment(org.apache.cxf.message.Attachment) Fault(org.apache.cxf.interceptor.Fault) DataHandler(javax.activation.DataHandler) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) MessagePartInfo(org.apache.cxf.service.model.MessagePartInfo) ByteDataSource(org.apache.cxf.attachment.ByteDataSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) DataSource(javax.activation.DataSource) BufferedImage(java.awt.image.BufferedImage) ByteDataSource(org.apache.cxf.attachment.ByteDataSource) LoadingByteArrayOutputStream(org.apache.cxf.helpers.LoadingByteArrayOutputStream) List(java.util.List) ArrayList(java.util.ArrayList) ImageOutputStream(javax.imageio.stream.ImageOutputStream) IOException(java.io.IOException) AttachmentImpl(org.apache.cxf.attachment.AttachmentImpl)

Example 12 with AttachmentImpl

use of org.apache.cxf.attachment.AttachmentImpl in project cxf by apache.

the class PersistenceUtilsTest method addAttachment.

private static void addAttachment(Message msg) throws IOException {
    Collection<Attachment> attachments = new ArrayList<>();
    DataHandler dh = new DataHandler(new ByteArrayDataSource("hello world!", "text/plain"));
    Attachment a = new AttachmentImpl("test.xml", dh);
    attachments.add(a);
    msg.setAttachments(attachments);
}
Also used : ArrayList(java.util.ArrayList) Attachment(org.apache.cxf.message.Attachment) AttachmentImpl(org.apache.cxf.attachment.AttachmentImpl) DataHandler(javax.activation.DataHandler) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Example 13 with AttachmentImpl

use of org.apache.cxf.attachment.AttachmentImpl in project cxf by apache.

the class AttachmentCallbackHandlerTest method parseAttachment.

private void parseAttachment(String attachmentId) throws Exception {
    Attachment attachment = new AttachmentImpl(attachmentId);
    // Mock up a DataHandler for the Attachment
    DataHandler dataHandler = EasyMock.mock(DataHandler.class);
    dataHandler.setCommandMap(anyObject(CommandMap.class));
    EasyMock.expectLastCall();
    EasyMock.expect(dataHandler.getInputStream()).andReturn(null);
    EasyMock.expect(dataHandler.getContentType()).andReturn(null);
    EasyMock.replay(dataHandler);
    ((AttachmentImpl) attachment).setDataHandler(dataHandler);
    AttachmentCallbackHandler callbackHandler = new AttachmentCallbackHandler(Collections.singletonList(attachment));
    AttachmentRequestCallback attachmentRequestCallback = new AttachmentRequestCallback();
    attachmentRequestCallback.setAttachmentId(AttachmentUtils.getAttachmentId("cid:" + attachmentId));
    attachmentRequestCallback.setRemoveAttachments(false);
    callbackHandler.handle(new Callback[] { attachmentRequestCallback });
    List<org.apache.wss4j.common.ext.Attachment> attachments = attachmentRequestCallback.getAttachments();
    assertNotNull(attachments);
    assertEquals(1, attachments.size());
    EasyMock.verify(dataHandler);
}
Also used : AttachmentRequestCallback(org.apache.wss4j.common.ext.AttachmentRequestCallback) Attachment(org.apache.cxf.message.Attachment) AttachmentImpl(org.apache.cxf.attachment.AttachmentImpl) DataHandler(javax.activation.DataHandler) CommandMap(javax.activation.CommandMap)

Example 14 with AttachmentImpl

use of org.apache.cxf.attachment.AttachmentImpl in project camel by apache.

the class DefaultCxfBindingTest method testPopupalteExchangeFromCxfRequest.

@Test
public void testPopupalteExchangeFromCxfRequest() {
    DefaultCxfBinding cxfBinding = new DefaultCxfBinding();
    cxfBinding.setHeaderFilterStrategy(new DefaultHeaderFilterStrategy());
    Exchange exchange = new DefaultExchange(context);
    org.apache.cxf.message.Exchange cxfExchange = new org.apache.cxf.message.ExchangeImpl();
    exchange.setProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.PAYLOAD);
    org.apache.cxf.message.Message cxfMessage = new org.apache.cxf.message.MessageImpl();
    Map<String, List<String>> headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
    headers.put("content-type", Arrays.asList("text/xml;charset=UTF-8"));
    headers.put("Content-Length", Arrays.asList("241"));
    headers.put("soapAction", Arrays.asList("urn:hello:world"));
    headers.put("myfruitheader", Arrays.asList("peach"));
    headers.put("mybrewheader", Arrays.asList("cappuccino", "espresso"));
    cxfMessage.put(org.apache.cxf.message.Message.PROTOCOL_HEADERS, headers);
    Set<Attachment> attachments = new HashSet<Attachment>();
    AttachmentImpl attachment = new AttachmentImpl("att-1", new DataHandler(new FileDataSource("pom.xml")));
    attachment.setHeader("attachment-header", "value 1");
    attachments.add(attachment);
    cxfMessage.setAttachments(attachments);
    cxfExchange.setInMessage(cxfMessage);
    cxfBinding.populateExchangeFromCxfRequest(cxfExchange, exchange);
    Map<String, Object> camelHeaders = exchange.getIn().getHeaders();
    assertNotNull(camelHeaders);
    assertEquals("urn:hello:world", camelHeaders.get("soapaction"));
    assertEquals("urn:hello:world", camelHeaders.get("SoapAction"));
    assertEquals("text/xml;charset=UTF-8", camelHeaders.get("content-type"));
    assertEquals("241", camelHeaders.get("content-length"));
    assertEquals("peach", camelHeaders.get("MyFruitHeader"));
    assertEquals(Arrays.asList("cappuccino", "espresso"), camelHeaders.get("MyBrewHeader"));
    Map<String, org.apache.camel.Attachment> camelAttachments = exchange.getIn().getAttachmentObjects();
    assertNotNull(camelAttachments);
    assertNotNull(camelAttachments.get("att-1"));
    assertEquals("value 1", camelAttachments.get("att-1").getHeader("attachment-header"));
}
Also used : DefaultHeaderFilterStrategy(org.apache.camel.impl.DefaultHeaderFilterStrategy) Attachment(org.apache.cxf.message.Attachment) DataHandler(javax.activation.DataHandler) FileDataSource(javax.activation.FileDataSource) List(java.util.List) HashSet(java.util.HashSet) DefaultExchange(org.apache.camel.impl.DefaultExchange) Message(org.apache.cxf.message.Message) TreeMap(java.util.TreeMap) Exchange(org.apache.camel.Exchange) DefaultExchange(org.apache.camel.impl.DefaultExchange) AttachmentImpl(org.apache.cxf.attachment.AttachmentImpl) MessageImpl(org.apache.cxf.message.MessageImpl) Test(org.junit.Test)

Example 15 with AttachmentImpl

use of org.apache.cxf.attachment.AttachmentImpl in project camel by apache.

the class DefaultCxfBinding method populateCxfResponseFromExchange.

/**
     * This method is called by {@link CxfConsumer} to populate a CXF response exchange 
     * from a Camel exchange.
     */
public void populateCxfResponseFromExchange(Exchange camelExchange, org.apache.cxf.message.Exchange cxfExchange) {
    if (cxfExchange.isOneWay()) {
        return;
    }
    // create response context
    Map<String, Object> responseContext = new HashMap<String, Object>();
    org.apache.camel.Message response;
    if (camelExchange.getPattern().isOutCapable()) {
        if (camelExchange.hasOut()) {
            response = camelExchange.getOut();
            LOG.trace("Get the response from the out message");
        } else {
            // Take the in message as a fall back
            response = camelExchange.getIn();
            LOG.trace("Get the response from the in message as a fallback");
        }
    } else {
        response = camelExchange.getIn();
        LOG.trace("Get the response from the in message");
    }
    // propagate response context
    Map<String, Object> camelHeaders = response.getHeaders();
    extractInvocationContextFromCamel(camelExchange, camelHeaders, responseContext, Client.RESPONSE_CONTEXT);
    propagateHeadersFromCamelToCxf(camelExchange, camelHeaders, cxfExchange, responseContext);
    // create out message
    Endpoint ep = cxfExchange.get(Endpoint.class);
    Message outMessage = ep.getBinding().createMessage();
    cxfExchange.setOutMessage(outMessage);
    DataFormat dataFormat = camelExchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class);
    // make sure the "requestor role" property does not get propagated as we do switch role
    responseContext.remove(Message.REQUESTOR_ROLE);
    outMessage.putAll(responseContext);
    // Do we still need to put the response context back like this
    outMessage.put(Client.RESPONSE_CONTEXT, responseContext);
    LOG.trace("Set out response context = {}", responseContext);
    // set body
    Object outBody = DefaultCxfBinding.getBodyFromCamel(response, dataFormat);
    if (outBody != null) {
        if (dataFormat == DataFormat.PAYLOAD) {
            CxfPayload<?> payload = (CxfPayload<?>) outBody;
            outMessage.setContent(List.class, getResponsePayloadList(cxfExchange, payload.getBodySources()));
            outMessage.put(Header.HEADER_LIST, payload.getHeaders());
        } else {
            if (responseContext.get(Header.HEADER_LIST) != null) {
                outMessage.put(Header.HEADER_LIST, responseContext.get(Header.HEADER_LIST));
            }
            MessageContentsList resList = null;
            // Create a new MessageContentsList to avoid OOM from the HolderOutInterceptor
            if (outBody instanceof List) {
                resList = new MessageContentsList((List<?>) outBody);
            } else if (outBody.getClass().isArray()) {
                resList = new MessageContentsList((Object[]) outBody);
            } else {
                resList = new MessageContentsList(outBody);
            }
            if (resList != null) {
                outMessage.setContent(List.class, resList);
                LOG.trace("Set Out CXF message content = {}", resList);
            }
        }
    } else if (!cxfExchange.isOneWay() && cxfExchange.getInMessage() != null && MessageUtils.isTrue(cxfExchange.getInMessage().getContextualProperty("jaxws.provider.interpretNullAsOneway"))) {
        // treat this non-oneway call as oneway when the provider returns a null
        changeToOneway(cxfExchange);
        return;
    }
    // propagate attachments
    Set<Attachment> attachments = null;
    boolean isXop = Boolean.valueOf(camelExchange.getProperty(Message.MTOM_ENABLED, String.class));
    for (Map.Entry<String, org.apache.camel.Attachment> entry : camelExchange.getOut().getAttachmentObjects().entrySet()) {
        if (attachments == null) {
            attachments = new HashSet<Attachment>();
        }
        AttachmentImpl attachment = new AttachmentImpl(entry.getKey());
        org.apache.camel.Attachment camelAttachment = entry.getValue();
        attachment.setDataHandler(camelAttachment.getDataHandler());
        for (String name : camelAttachment.getHeaderNames()) {
            attachment.setHeader(name, camelAttachment.getHeader(name));
        }
        attachment.setXOP(isXop);
        attachments.add(attachment);
    }
    if (attachments != null) {
        outMessage.setAttachments(attachments);
    }
    BindingOperationInfo boi = cxfExchange.get(BindingOperationInfo.class);
    if (boi != null) {
        cxfExchange.put(BindingMessageInfo.class, boi.getOutput());
    }
}
Also used : BindingOperationInfo(org.apache.cxf.service.model.BindingOperationInfo) Message(org.apache.cxf.message.Message) MessageContentsList(org.apache.cxf.message.MessageContentsList) HashMap(java.util.HashMap) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) Attachment(org.apache.cxf.message.Attachment) Endpoint(org.apache.cxf.endpoint.Endpoint) MessageContentsList(org.apache.cxf.message.MessageContentsList) List(java.util.List) ArrayList(java.util.ArrayList) AttachmentImpl(org.apache.cxf.attachment.AttachmentImpl) Map(java.util.Map) HashMap(java.util.HashMap) NamedNodeMap(org.w3c.dom.NamedNodeMap) TreeMap(java.util.TreeMap)

Aggregations

AttachmentImpl (org.apache.cxf.attachment.AttachmentImpl)20 DataHandler (javax.activation.DataHandler)15 Attachment (org.apache.cxf.message.Attachment)12 HashMap (java.util.HashMap)7 ArrayList (java.util.ArrayList)6 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)6 List (java.util.List)5 Message (org.apache.cxf.message.Message)5 Test (org.junit.Test)5 Map (java.util.Map)4 TreeMap (java.util.TreeMap)4 DataSource (javax.activation.DataSource)3 ByteDataSource (org.apache.cxf.attachment.ByteDataSource)3 MessageImpl (org.apache.cxf.message.MessageImpl)3 HashSet (java.util.HashSet)2 LinkedList (java.util.LinkedList)2 FileDataSource (javax.activation.FileDataSource)2 Exchange (org.apache.camel.Exchange)2 DefaultAttachment (org.apache.camel.impl.DefaultAttachment)2 DefaultExchange (org.apache.camel.impl.DefaultExchange)2