Search in sources :

Example 31 with Attachment

use of org.apache.cxf.message.Attachment in project camel by apache.

the class DefaultCxfBinding method populateExchangeFromCxfRequest.

/**
     * This method is called by {@link CxfConsumer}.
     */
public void populateExchangeFromCxfRequest(org.apache.cxf.message.Exchange cxfExchange, Exchange camelExchange) {
    Method method = null;
    QName operationName = null;
    ExchangePattern mep = ExchangePattern.InOut;
    // extract binding operation information
    BindingOperationInfo boi = camelExchange.getProperty(BindingOperationInfo.class.getName(), BindingOperationInfo.class);
    if (boi != null) {
        Service service = cxfExchange.get(Service.class);
        if (service != null) {
            MethodDispatcher md = (MethodDispatcher) service.get(MethodDispatcher.class.getName());
            if (md != null) {
                method = md.getMethod(boi);
            }
        }
        if (boi.getOperationInfo().isOneWay()) {
            mep = ExchangePattern.InOnly;
        }
        operationName = boi.getName();
    }
    // set operation name in header
    if (operationName != null) {
        camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAMESPACE, boi.getName().getNamespaceURI());
        camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, boi.getName().getLocalPart());
        if (LOG.isTraceEnabled()) {
            LOG.trace("Set IN header: {}={}", CxfConstants.OPERATION_NAMESPACE, boi.getName().getNamespaceURI());
            LOG.trace("Set IN header: {}={}", CxfConstants.OPERATION_NAME, boi.getName().getLocalPart());
        }
    } else if (method != null) {
        camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, method.getName());
        if (LOG.isTraceEnabled()) {
            LOG.trace("Set IN header: {}={}", CxfConstants.OPERATION_NAME, method.getName());
        }
    }
    // set message exchange pattern
    camelExchange.setPattern(mep);
    LOG.trace("Set exchange MEP: {}", mep);
    // propagate headers
    Message cxfMessage = cxfExchange.getInMessage();
    propagateHeadersFromCxfToCamel(cxfMessage, camelExchange.getIn(), camelExchange);
    // propagate the security subject from CXF security context
    SecurityContext securityContext = cxfMessage.get(SecurityContext.class);
    if (securityContext instanceof LoginSecurityContext && ((LoginSecurityContext) securityContext).getSubject() != null) {
        camelExchange.getIn().getHeaders().put(Exchange.AUTHENTICATION, ((LoginSecurityContext) securityContext).getSubject());
    } else if (securityContext != null) {
        Principal user = securityContext.getUserPrincipal();
        if (user != null) {
            Subject subject = new Subject();
            subject.getPrincipals().add(user);
            camelExchange.getIn().getHeaders().put(Exchange.AUTHENTICATION, subject);
        }
    }
    // Propagating properties from CXF Exchange to Camel Exchange has an  
    // side effect of copying reply side stuff when the producer is retried.
    // So, we do not want to do this.
    //camelExchange.getProperties().putAll(cxfExchange);
    // propagate request context
    Object value = cxfMessage.get(Client.REQUEST_CONTEXT);
    if (value != null && !headerFilterStrategy.applyFilterToExternalHeaders(Client.REQUEST_CONTEXT, value, camelExchange)) {
        camelExchange.getIn().setHeader(Client.REQUEST_CONTEXT, value);
        LOG.trace("Populate context from CXF message {} value={}", Client.REQUEST_CONTEXT, value);
    }
    // setup the charset from content-type header
    setCharsetWithContentType(camelExchange);
    // set body
    String encoding = (String) camelExchange.getProperty(Exchange.CHARSET_NAME);
    Object body = DefaultCxfBinding.getContentFromCxf(cxfMessage, camelExchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class), encoding);
    if (body != null) {
        camelExchange.getIn().setBody(body);
    }
    // propagate attachments if the data format is not POJO        
    if (cxfMessage.getAttachments() != null && !camelExchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class).equals(DataFormat.POJO)) {
        for (Attachment attachment : cxfMessage.getAttachments()) {
            camelExchange.getIn().addAttachmentObject(attachment.getId(), createCamelAttachment(attachment));
        }
    }
}
Also used : BindingOperationInfo(org.apache.cxf.service.model.BindingOperationInfo) Message(org.apache.cxf.message.Message) QName(javax.xml.namespace.QName) LoginSecurityContext(org.apache.cxf.security.LoginSecurityContext) Service(org.apache.cxf.service.Service) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) Attachment(org.apache.cxf.message.Attachment) Method(java.lang.reflect.Method) Subject(javax.security.auth.Subject) ExchangePattern(org.apache.camel.ExchangePattern) SecurityContext(org.apache.cxf.security.SecurityContext) LoginSecurityContext(org.apache.cxf.security.LoginSecurityContext) MethodDispatcher(org.apache.cxf.service.invoker.MethodDispatcher) Principal(java.security.Principal)

Example 32 with Attachment

use of org.apache.cxf.message.Attachment in project tomee by apache.

the class LazyAttachmentCollection method iterator.

public Iterator<Attachment> iterator() {
    return new Iterator<Attachment>() {

        int current;

        boolean removed;

        public boolean hasNext() {
            if (attachments.size() > current) {
                return true;
            }
            // check if there is another attachment
            try {
                Attachment a = deserializer.readNext();
                if (a == null) {
                    return false;
                }
                attachments.add(a);
                return true;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public Attachment next() {
            Attachment a = attachments.get(current);
            current++;
            removed = false;
            return a;
        }

        @Override
        public void remove() {
            if (removed) {
                throw new IllegalStateException();
            }
            attachments.remove(--current);
            removed = true;
        }
    };
}
Also used : Iterator(java.util.Iterator) Attachment(org.apache.cxf.message.Attachment) IOException(java.io.IOException)

Example 33 with Attachment

use of org.apache.cxf.message.Attachment in project tomee by apache.

the class AbstractHTTPDestination method cacheInput.

/**
 * On first write, we need to make sure any attachments and such that are still on the incoming stream
 * are read in.  Otherwise we can get into a deadlock where the client is still trying to send the
 * request, but the server is trying to send the response.   Neither side is reading and both blocked
 * on full buffers.  Not a good situation.
 * @param outMessage
 */
private void cacheInput(Message outMessage) {
    if (outMessage.getExchange() == null) {
        return;
    }
    Message inMessage = outMessage.getExchange().getInMessage();
    if (inMessage == null) {
        return;
    }
    Object o = inMessage.get("cxf.io.cacheinput");
    DelegatingInputStream in = inMessage.getContent(DelegatingInputStream.class);
    if (PropertyUtils.isTrue(o)) {
        Collection<Attachment> atts = inMessage.getAttachments();
        if (atts != null) {
            for (Attachment a : atts) {
                if (a.getDataHandler().getDataSource() instanceof AttachmentDataSource) {
                    try {
                        ((AttachmentDataSource) a.getDataHandler().getDataSource()).cache(inMessage);
                    } catch (IOException e) {
                        throw new Fault(e);
                    }
                }
            }
        }
        if (in != null) {
            in.cacheInput();
        }
    } else if (in != null) {
        // However, also don't want to consume indefinitely.   We'll limit to 16M.
        try {
            IOUtils.consume(in, 16 * 1024 * 1024);
        } catch (Exception ioe) {
        // ignore
        }
    }
}
Also used : Message(org.apache.cxf.message.Message) DelegatingInputStream(org.apache.cxf.io.DelegatingInputStream) AttachmentDataSource(org.apache.cxf.attachment.AttachmentDataSource) Attachment(org.apache.cxf.message.Attachment) Fault(org.apache.cxf.interceptor.Fault) IOException(java.io.IOException) Base64Exception(org.apache.cxf.common.util.Base64Exception) SuspendedInvocationException(org.apache.cxf.continuations.SuspendedInvocationException) IOException(java.io.IOException)

Example 34 with Attachment

use of org.apache.cxf.message.Attachment in project cxf by apache.

the class AttachmentSerializer method writeAttachments.

/**
 * Write the end of the body boundary and any attachments included.
 * @throws IOException
 */
public void writeAttachments() throws IOException {
    if (message.getAttachments() != null) {
        for (Attachment a : message.getAttachments()) {
            StringWriter writer = new StringWriter();
            writer.write("\r\n--");
            writer.write(bodyBoundary);
            final Map<String, List<String>> headers;
            Iterator<String> it = a.getHeaderNames();
            if (it.hasNext()) {
                headers = new LinkedHashMap<>();
                while (it.hasNext()) {
                    String key = it.next();
                    headers.put(key, Collections.singletonList(a.getHeader(key)));
                }
            } else {
                headers = Collections.emptyMap();
            }
            DataHandler handler = a.getDataHandler();
            handler.setCommandMap(AttachmentUtil.getCommandMap());
            writeHeaders(handler.getContentType(), a.getId(), headers, writer);
            out.write(writer.getBuffer().toString().getBytes(encoding));
            if ("base64".equals(contentTransferEncoding)) {
                try (InputStream inputStream = handler.getInputStream()) {
                    encodeBase64(inputStream, out, IOUtils.DEFAULT_BUFFER_SIZE);
                }
            } else {
                handler.writeTo(out);
            }
        }
    }
    StringWriter writer = new StringWriter();
    writer.write("\r\n--");
    writer.write(bodyBoundary);
    writer.write("--");
    out.write(writer.getBuffer().toString().getBytes(encoding));
    out.flush();
}
Also used : StringWriter(java.io.StringWriter) InputStream(java.io.InputStream) Attachment(org.apache.cxf.message.Attachment) List(java.util.List) DataHandler(javax.activation.DataHandler)

Example 35 with Attachment

use of org.apache.cxf.message.Attachment in project cxf by apache.

the class AttachmentSerializerTest method doTestMessageWrite.

private void doTestMessageWrite(boolean xop, String soapContentType) throws Exception {
    MessageImpl msg = new MessageImpl();
    Collection<Attachment> atts = new ArrayList<>();
    AttachmentImpl a = new AttachmentImpl("test.xml");
    InputStream is = getClass().getResourceAsStream("my.wav");
    ByteArrayDataSource ds = new ByteArrayDataSource(is, "application/octet-stream");
    a.setDataHandler(new DataHandler(ds));
    atts.add(a);
    msg.setAttachments(atts);
    // Set the SOAP content type
    msg.put(Message.CONTENT_TYPE, soapContentType);
    final String soapCtType;
    final String soapCtParams;
    final String soapCtParamsEscaped;
    int p = soapContentType.indexOf(';');
    if (p != -1) {
        soapCtParams = soapContentType.substring(p);
        soapCtParamsEscaped = escapeQuotes(soapCtParams);
        soapCtType = soapContentType.substring(0, p);
    } else {
        soapCtParams = "";
        soapCtParamsEscaped = "";
        soapCtType = soapContentType;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.setContent(OutputStream.class, out);
    AttachmentSerializer serializer = new AttachmentSerializer(msg);
    if (!xop) {
        // default is "on"
        serializer.setXop(xop);
    }
    serializer.writeProlog();
    // we expect the following rules at the package header level
    // - the package header must have media type multipart/related.
    // - the start-info property must be present for mtom but otherwise optional. its
    // value must contain the content type associated with the root content's xml serialization,
    // including its parameters as appropriate.
    // - the action property should not appear directly in the package header level
    // - the type property must contain the media type type/subtype of the root content part.
    // namely application/xop+xml for mtom but otherwise text/xml or application/soap+xml
    // depending on the soap version 1.1 or 1.2, respectively.
    String ct = (String) msg.get(Message.CONTENT_TYPE);
    assertTrue(ct.indexOf("multipart/related;") == 0);
    assertTrue(ct.indexOf("start=\"<root.message@cxf.apache.org>\"") > -1);
    assertTrue(ct.indexOf("start-info=\"" + soapCtType + soapCtParamsEscaped + "\"") > -1);
    assertTrue(ct.indexOf("action=\"") == -1);
    if (xop) {
        assertTrue(ct.indexOf("type=\"application/xop+xml\"") > -1);
    } else {
        assertTrue(ct.indexOf("type=\"" + soapCtType + "\"") > -1);
    }
    out.write("<soap:Body/>".getBytes());
    serializer.writeAttachments();
    out.flush();
    DataSource source = new ByteArrayDataSource(new ByteArrayInputStream(out.toByteArray()), ct);
    MimeMultipart mpart = new MimeMultipart(source);
    Session session = Session.getDefaultInstance(new Properties());
    MimeMessage inMsg = new MimeMessage(session);
    inMsg.setContent(mpart);
    inMsg.addHeaderLine("Content-Type: " + ct);
    MimeMultipart multipart = (MimeMultipart) inMsg.getContent();
    MimeBodyPart part = (MimeBodyPart) multipart.getBodyPart(0);
    // - the action must appear if it was present in the original message (i.e., for soap 1.2)
    if (xop) {
        assertEquals("application/xop+xml; charset=UTF-8; type=\"" + soapCtType + soapCtParamsEscaped + "\"", part.getHeader("Content-Type")[0]);
    } else {
        assertEquals(soapCtType + "; charset=UTF-8" + soapCtParams, part.getHeader("Content-Type")[0]);
    }
    assertEquals("binary", part.getHeader("Content-Transfer-Encoding")[0]);
    assertEquals("<root.message@cxf.apache.org>", part.getHeader("Content-ID")[0]);
    InputStream in = part.getDataHandler().getInputStream();
    ByteArrayOutputStream bodyOut = new ByteArrayOutputStream();
    IOUtils.copy(in, bodyOut);
    out.close();
    in.close();
    assertEquals("<soap:Body/>", bodyOut.toString());
    MimeBodyPart part2 = (MimeBodyPart) multipart.getBodyPart(1);
    assertEquals("application/octet-stream", part2.getHeader("Content-Type")[0]);
    assertEquals("binary", part2.getHeader("Content-Transfer-Encoding")[0]);
    assertEquals("<test.xml>", part2.getHeader("Content-ID")[0]);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Attachment(org.apache.cxf.message.Attachment) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Properties(java.util.Properties) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource) ByteArrayInputStream(java.io.ByteArrayInputStream) MimeMultipart(javax.mail.internet.MimeMultipart) MimeMessage(javax.mail.internet.MimeMessage) MimeBodyPart(javax.mail.internet.MimeBodyPart) MessageImpl(org.apache.cxf.message.MessageImpl) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) Session(javax.mail.Session)

Aggregations

Attachment (org.apache.cxf.message.Attachment)51 DataHandler (javax.activation.DataHandler)18 Test (org.junit.Test)18 InputStream (java.io.InputStream)14 Message (org.apache.cxf.message.Message)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 AttachmentImpl (org.apache.cxf.attachment.AttachmentImpl)12 ByteArrayOutputStream (java.io.ByteArrayOutputStream)11 IOException (java.io.IOException)11 ArrayList (java.util.ArrayList)11 MessageImpl (org.apache.cxf.message.MessageImpl)11 HashMap (java.util.HashMap)10 List (java.util.List)9 PushbackInputStream (java.io.PushbackInputStream)7 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)6 Fault (org.apache.cxf.interceptor.Fault)6 BindingOperationInfo (org.apache.cxf.service.model.BindingOperationInfo)6 Map (java.util.Map)5 OutputStream (java.io.OutputStream)4 TreeMap (java.util.TreeMap)4