Search in sources :

Example 21 with Attachment

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

the class AbstractSTSClient method issue.

/**
 * Make an "Issue" invocation and return the response as a STSResponse Object
 */
protected STSResponse issue(String appliesTo, String action, String requestType, String binaryExchange) throws Exception {
    createClient();
    BindingOperationInfo boi = findOperation("/RST/Issue");
    client.getRequestContext().putAll(ctx);
    if (action != null) {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, action);
    } else if (isSecureConv) {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, namespace + "/RST/SCT");
    } else {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, namespace + "/RST/Issue");
    }
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    if (context != null) {
        writer.writeAttribute(null, "Context", context);
    }
    boolean wroteKeySize = false;
    String keyTypeTemplate = null;
    String sptt = null;
    if (template != null && DOMUtils.getFirstElement(template) != null) {
        if (this.useSecondaryParameters()) {
            writer.writeStartElement("wst", "SecondaryParameters", namespace);
        }
        Element tl = DOMUtils.getFirstElement(template);
        while (tl != null) {
            StaxUtils.copy(tl, writer);
            if ("KeyType".equals(tl.getLocalName())) {
                keyTypeTemplate = DOMUtils.getContent(tl);
            } else if ("KeySize".equals(tl.getLocalName())) {
                wroteKeySize = true;
                keySize = Integer.parseInt(DOMUtils.getContent(tl));
            } else if ("TokenType".equals(tl.getLocalName())) {
                sptt = DOMUtils.getContent(tl);
            }
            tl = DOMUtils.getNextElement(tl);
        }
        if (this.useSecondaryParameters()) {
            writer.writeEndElement();
        }
    }
    if (isSpnego) {
        tokenType = STSUtils.getTokenTypeSCT(namespace);
        sendKeyType = false;
    }
    if (sptt == null) {
        addTokenType(writer);
    }
    addRequestType(requestType, writer);
    if (enableAppliesTo) {
        addAppliesTo(writer, appliesTo);
    }
    addClaims(writer);
    if (isSecureConv || enableLifetime) {
        addLifetime(writer);
    }
    // Write out renewal semantics
    writeRenewalSemantics(writer);
    Element onBehalfOfToken = getOnBehalfOfToken();
    if (onBehalfOfToken != null) {
        writer.writeStartElement("wst", "OnBehalfOf", namespace);
        StaxUtils.copy(onBehalfOfToken, writer);
        writer.writeEndElement();
    }
    if (keyTypeTemplate == null) {
        keyTypeTemplate = writeKeyType(writer, keyType);
    }
    byte[] requestorEntropy = null;
    X509Certificate cert = null;
    Crypto crypto = null;
    if (keySize <= 0) {
        keySize = 256;
    }
    if (keyTypeTemplate != null && keyTypeTemplate.endsWith("SymmetricKey")) {
        requestorEntropy = writeElementsForRSTSymmetricKey(writer, wroteKeySize);
    } else if (keyTypeTemplate != null && keyTypeTemplate.endsWith("PublicKey")) {
        // Use the given cert, or else get it from a Crypto instance
        if (useKeyCertificate != null) {
            cert = useKeyCertificate;
        } else {
            crypto = createCrypto(false);
            cert = getCert(crypto);
        }
        writeElementsForRSTPublicKey(writer, cert);
    } else if (isSpnego || isSecureConv) {
        addKeySize(keySize, writer);
    }
    if (binaryExchange != null) {
        addBinaryExchange(binaryExchange, writer);
    }
    Element actAsSecurityToken = getActAsToken();
    if (actAsSecurityToken != null) {
        writer.writeStartElement(STSUtils.WST_NS_08_02, "ActAs");
        StaxUtils.copy(actAsSecurityToken, writer);
        writer.writeEndElement();
    }
    Element customElement = getCustomContent();
    if (customElement != null) {
        StaxUtils.copy(customElement, writer);
    }
    writer.writeEndElement();
    Object[] obj = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    @SuppressWarnings("unchecked") Collection<Attachment> attachments = (Collection<Attachment>) client.getResponseContext().get(Message.ATTACHMENTS);
    return new STSResponse((DOMSource) obj[0], requestorEntropy, cert, crypto, attachments);
}
Also used : W3CDOMStreamWriter(org.apache.cxf.staxutils.W3CDOMStreamWriter) BindingOperationInfo(org.apache.cxf.service.model.BindingOperationInfo) DOMSource(javax.xml.transform.dom.DOMSource) ExtensibilityElement(javax.wsdl.extensions.ExtensibilityElement) Element(org.w3c.dom.Element) Attachment(org.apache.cxf.message.Attachment) X509Certificate(java.security.cert.X509Certificate) Crypto(org.apache.wss4j.common.crypto.Crypto) Collection(java.util.Collection) ClaimCollection(org.apache.cxf.rt.security.claims.ClaimCollection)

Example 22 with Attachment

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

the class MtomServerTest method testURLBasedAttachment.

@Test
public void testURLBasedAttachment() throws Exception {
    JaxWsServerFactoryBean sf = new JaxWsServerFactoryBean();
    sf.setServiceBean(new EchoService());
    sf.setBus(getStaticBus());
    String address = "http://localhost:" + PORT2 + "/EchoService";
    sf.setAddress(address);
    Map<String, Object> props = new HashMap<>();
    props.put(Message.MTOM_ENABLED, "true");
    sf.setProperties(props);
    Server server = sf.create();
    server.getEndpoint().getService().getDataBinding().setMtomThreshold(0);
    servStatic(getClass().getResource("mtom-policy.xml"), "http://localhost:" + PORT2 + "/policy.xsd");
    EndpointInfo ei = new EndpointInfo(null, HTTP_ID);
    ei.setAddress(address);
    ConduitInitiatorManager conduitMgr = getStaticBus().getExtension(ConduitInitiatorManager.class);
    ConduitInitiator conduitInit = conduitMgr.getConduitInitiator("http://schemas.xmlsoap.org/soap/http");
    Conduit conduit = conduitInit.getConduit(ei, getStaticBus());
    TestUtilities.TestMessageObserver obs = new TestUtilities.TestMessageObserver();
    conduit.setMessageObserver(obs);
    Message m = new MessageImpl();
    String ct = "multipart/related; type=\"application/xop+xml\"; " + "start=\"<soap.xml@xfire.codehaus.org>\"; " + "start-info=\"text/xml; charset=utf-8\"; " + "boundary=\"----=_Part_4_701508.1145579811786\"";
    m.put(Message.CONTENT_TYPE, ct);
    conduit.prepare(m);
    OutputStream os = m.getContent(OutputStream.class);
    InputStream is = testUtilities.getResourceAsStream("request-url-attachment");
    if (is == null) {
        throw new RuntimeException("Could not find resource " + "request");
    }
    try (ByteArrayOutputStream bout = new ByteArrayOutputStream()) {
        IOUtils.copy(is, bout);
        String s = bout.toString(StandardCharsets.UTF_8.name());
        s = s.replaceAll(":9036/", ":" + PORT2 + "/");
        os.write(s.getBytes(StandardCharsets.UTF_8));
    }
    os.flush();
    is.close();
    os.close();
    byte[] res = obs.getResponseStream().toByteArray();
    MessageImpl resMsg = new MessageImpl();
    resMsg.setContent(InputStream.class, new ByteArrayInputStream(res));
    resMsg.put(Message.CONTENT_TYPE, obs.getResponseContentType());
    resMsg.setExchange(new ExchangeImpl());
    AttachmentDeserializer deserializer = new AttachmentDeserializer(resMsg);
    deserializer.initializeAttachments();
    Collection<Attachment> attachments = resMsg.getAttachments();
    assertNotNull(attachments);
    assertEquals(1, attachments.size());
    Attachment inAtt = attachments.iterator().next();
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        IOUtils.copy(inAtt.getDataHandler().getInputStream(), out);
        assertTrue("Wrong size: " + out.size() + "\n" + out.toString(), out.size() > 970 && out.size() < 1020);
    }
    unregisterServStatic("http://localhost:" + PORT2 + "/policy.xsd");
}
Also used : Server(org.apache.cxf.endpoint.Server) Message(org.apache.cxf.message.Message) AttachmentDeserializer(org.apache.cxf.attachment.AttachmentDeserializer) HashMap(java.util.HashMap) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) Attachment(org.apache.cxf.message.Attachment) EndpointInfo(org.apache.cxf.service.model.EndpointInfo) ConduitInitiator(org.apache.cxf.transport.ConduitInitiator) JaxWsServerFactoryBean(org.apache.cxf.jaxws.JaxWsServerFactoryBean) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) TestUtilities(org.apache.cxf.test.TestUtilities) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) Conduit(org.apache.cxf.transport.Conduit) ConduitInitiatorManager(org.apache.cxf.transport.ConduitInitiatorManager) MessageImpl(org.apache.cxf.message.MessageImpl) ExchangeImpl(org.apache.cxf.message.ExchangeImpl) Test(org.junit.Test)

Example 23 with Attachment

use of org.apache.cxf.message.Attachment 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 24 with Attachment

use of org.apache.cxf.message.Attachment 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 25 with Attachment

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

the class MtomPolicyTest method sendMtomMessage.

private void sendMtomMessage(String a) throws Exception {
    EndpointInfo ei = new EndpointInfo(null, "http://schemas.xmlsoap.org/wsdl/http");
    ei.setAddress(a);
    ConduitInitiatorManager conduitMgr = getStaticBus().getExtension(ConduitInitiatorManager.class);
    ConduitInitiator conduitInit = conduitMgr.getConduitInitiator("http://schemas.xmlsoap.org/soap/http");
    Conduit conduit = conduitInit.getConduit(ei, getStaticBus());
    TestUtilities.TestMessageObserver obs = new TestUtilities.TestMessageObserver();
    conduit.setMessageObserver(obs);
    Message m = new MessageImpl();
    String ct = "multipart/related; type=\"application/xop+xml\"; " + "start=\"<soap.xml@xfire.codehaus.org>\"; " + "start-info=\"text/xml; charset=utf-8\"; " + "boundary=\"----=_Part_4_701508.1145579811786\"";
    m.put(Message.CONTENT_TYPE, ct);
    conduit.prepare(m);
    OutputStream os = m.getContent(OutputStream.class);
    InputStream is = testUtilities.getResourceAsStream("request");
    if (is == null) {
        throw new RuntimeException("Could not find resource " + "request");
    }
    IOUtils.copy(is, os);
    os.flush();
    is.close();
    os.close();
    byte[] res = obs.getResponseStream().toByteArray();
    MessageImpl resMsg = new MessageImpl();
    resMsg.setContent(InputStream.class, new ByteArrayInputStream(res));
    resMsg.put(Message.CONTENT_TYPE, obs.getResponseContentType());
    resMsg.setExchange(new ExchangeImpl());
    AttachmentDeserializer deserializer = new AttachmentDeserializer(resMsg);
    deserializer.initializeAttachments();
    Collection<Attachment> attachments = resMsg.getAttachments();
    assertNotNull(attachments);
    assertEquals(1, attachments.size());
    Attachment inAtt = attachments.iterator().next();
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        IOUtils.copy(inAtt.getDataHandler().getInputStream(), out);
        assertEquals(27364, out.size());
    }
}
Also used : Message(org.apache.cxf.message.Message) AttachmentDeserializer(org.apache.cxf.attachment.AttachmentDeserializer) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) TestUtilities(org.apache.cxf.test.TestUtilities) Attachment(org.apache.cxf.message.Attachment) ByteArrayOutputStream(java.io.ByteArrayOutputStream) EndpointInfo(org.apache.cxf.service.model.EndpointInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) Conduit(org.apache.cxf.transport.Conduit) ConduitInitiatorManager(org.apache.cxf.transport.ConduitInitiatorManager) ConduitInitiator(org.apache.cxf.transport.ConduitInitiator) MessageImpl(org.apache.cxf.message.MessageImpl) ExchangeImpl(org.apache.cxf.message.ExchangeImpl)

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