Java Code Examples for org.apache.cxf.staxutils.StaxUtils#copy()

The following examples show how to use org.apache.cxf.staxutils.StaxUtils#copy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractBindingBuilder.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Element cloneElement(Element el) {
    Document doc = secHeader.getSecurityHeaderElement().getOwnerDocument();
    if (!doc.equals(el.getOwnerDocument())) {

        XMLStreamReader reader = StaxUtils.createXMLStreamReader(el);
        DocumentFragment fragment = doc.createDocumentFragment();
        W3CDOMStreamWriter writer = new W3CDOMStreamWriter(fragment);
        try {
            StaxUtils.copy(reader, writer);
            return (Element)fragment.getFirstChild();
        } catch (XMLStreamException ex) {
            LOG.log(Level.FINE, "Error cloning security element", ex);
        }
    }
    return el;
}
 
Example 2
Source File: StaxSerializer.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] serializeToByteArray(Element element) throws Exception {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(baos);
        StaxUtils.copy(element, writer);
        writer.close();
        return baos.toByteArray();
    }
}
 
Example 3
Source File: SourceProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
private InputStream getStreamFromReader(XMLStreamReader input)
    throws IOException {

    try (CachedOutputStream out = new CachedOutputStream()) {
        StaxUtils.copy(input, out);
        return out.getInputStream();
    } catch (XMLStreamException ex) {
        throw new IOException("XMLStreamException:" + ex.getMessage());
    }
}
 
Example 4
Source File: TunedDocumentLoader.java    From cxf with Apache License 2.0 5 votes vote down vote up
static Document loadFastinfosetDocument(URL url)
    throws IOException, ParserConfigurationException, XMLStreamException {
    InputStream is = url.openStream();
    InputStream in = new BufferedInputStream(is);
    XMLStreamReader staxReader = new StAXDocumentParser(in);
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    StaxUtils.copy(staxReader, writer);
    in.close();
    return writer.getDocument();
}
 
Example 5
Source File: AbstractSecurityTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected SoapMessage getSoapMessageForDom(Document doc, String protocol) throws Exception {
    SOAPMessage saajMsg = MessageFactory.newInstance(protocol).createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    SAAJStreamWriter writer = new SAAJStreamWriter(part);
    StaxUtils.copy(doc, writer);
    saajMsg.saveChanges();

    MessageImpl message = new MessageImpl();
    SoapMessage msg = new SoapMessage(message);
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);
    msg.setContent(SOAPMessage.class, saajMsg);

    return msg;
}
 
Example 6
Source File: SecurityToken.java    From steady with Apache License 2.0 5 votes vote down vote up
private static Element cloneElement(Element el) {
    try {
        W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
        writer.setNsRepairing(true);
        StaxUtils.copy(el, writer);
        return writer.getDocument().getDocumentElement();
    } catch (Exception ex) {
        //ignore
    }
    return el;
}
 
Example 7
Source File: ImportRepairTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void dumpSchema(Document document) throws Exception {
    if (!dumpSchemas) {
        return;
    }

    XMLStreamWriter xwriter = StaxUtils.createXMLStreamWriter(System.err);
    xwriter = new PrettyPrintXMLStreamWriter(xwriter, 2);
    StaxUtils.copy(new DOMSource(document), xwriter);
    xwriter.close();
}
 
Example 8
Source File: XMLStreamReaderType.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void writeObject(Object object,
                        MessageWriter writer,
                        Context context) throws DatabindingException {
    XMLStreamReader reader = (XMLStreamReader)object;

    try {
        StaxUtils.copy(reader, ((ElementWriter)writer).getXMLStreamWriter());
        reader.close();
    } catch (XMLStreamException e) {
        throw new DatabindingException("Could not write xml.", e);
    }
}
 
Example 9
Source File: RMCaptureInInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private CachedOutputStream removeUnnecessarySoapHeaders(CachedOutputStream saved) {
    CachedOutputStream newSaved = new CachedOutputStream();

    try (InputStream is = saved.getInputStream()) {
        XMLStreamWriter capture = StaxUtils.createXMLStreamWriter(newSaved,
                                                                  StandardCharsets.UTF_8.name());
        Map<String, String> map = new HashMap<>();
        map.put("{http://schemas.xmlsoap.org/ws/2005/02/rm}Sequence", "");
        map.put("{http://schemas.xmlsoap.org/ws/2005/02/rm}SequenceAcknowledgement", "");
        map.put("{http://docs.oasis-open.org/ws-rx/wsrm/200702}Sequence", "");
        map.put("{http://docs.oasis-open.org/ws-rx/wsrm/200702}SequenceAcknowledgement", "");
        map.put("{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}Security",
                "");
        // attributes to be removed
        Map<String, String> amap = new HashMap<>();
        amap.put("{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd}Id",
                 "");

        capture = new OutTransformWriter(capture, map, Collections.<String, String> emptyMap(),
                                         Collections.<String> emptyList(), amap, false, null);
        StaxUtils.copy(new StreamSource(is), capture);
        capture.flush();
        capture.close();
        newSaved.flush();
        // hold temp file, otherwise it will be deleted in case msg was written to RMTxStore
        // or resend was executed
        newSaved.holdTempFile();
    } catch (IOException | XMLStreamException e) {
        throw new Fault(e);
    }
    return newSaved;
}
 
Example 10
Source File: RMCaptureInInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void handle(Message message) throws SequenceFault, RMException {

    // all messages are initially captured as they cannot be distinguished at this phase
    // Non application messages temp files are released (cos.releaseTempFileHold()) in RMInInterceptor
    if (!isGET(message) && !MessageUtils.getContextualBoolean(message, Message.ROBUST_ONEWAY, false)
        && (getManager().getStore() != null || (getManager().getDestinationPolicy() != null && getManager()
            .getDestinationPolicy().getRetryPolicy() != null))) {

        message.getInterceptorChain().add(new RMCaptureInEnd());
        XMLStreamReader reader = message.getContent(XMLStreamReader.class);

        if (null != reader) {
            CachedOutputStream saved = new CachedOutputStream();
            // REVISIT check factory for READER
            try {
                StaxUtils.copy(reader, saved);
                saved.flush();
                saved.holdTempFile();
                reader.close();
                LOG.fine("Create new XMLStreamReader");
                InputStream is = saved.getInputStream();
                // keep References to clean-up tmp files in RMDeliveryInterceptor
                setCloseable(message, saved, is);
                XMLStreamReader newReader = StaxUtils.createXMLStreamReader(is);
                StaxUtils.configureReader(reader, message);
                message.setContent(XMLStreamReader.class, newReader);
                LOG.fine("Capturing the original RM message");
                message.put(RMMessageConstants.SAVED_CONTENT, saved);
            } catch (XMLStreamException | IOException e) {
                throw new Fault(e);
            }
        } else {
            org.apache.cxf.common.i18n.Message msg = new org.apache.cxf.common.i18n.Message(
                              "No message found for redeliver", LOG, Collections.<String> emptyList());
            RMException ex = new RMException(msg);
            throw new Fault(ex);
        }
    }
}
 
Example 11
Source File: ParseBodyTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadSOAPFault() throws Exception {
    InputStream inStream = getClass().getResourceAsStream("soap12-fault.xml");
    Document doc = StaxUtils.read(inStream);

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);

    SOAPMessage saajMsg = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    SAAJStreamWriter writer = new SAAJStreamWriter(part);
    StaxUtils.copy(doc, writer);
    //Source s = new StaxSource(StaxUtils.createXMLStreamReader(doc));
    //part.setContent(s);
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);
    doc = part;

    // System.out.println("OUTPUT: " + StaxUtils.toString(doc));

    byte[] docbytes = getMessageBytes(doc);

    // System.out.println("OUTPUT: " + new String(docbytes));
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

}
 
Example 12
Source File: STSRESTTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testValidateSAML2Token() throws Exception {
    WebClient client = webClient()
        .path("saml2.0")
        .accept(MediaType.APPLICATION_XML);

    // 1. Get a token via GET
    Document assertionDoc = client.get(Document.class);
    assertNotNull(assertionDoc);

    // 2. Now validate it in the STS using POST
    client = webClient()
        .query("action", "validate")
        .type(MediaType.APPLICATION_XML)
        .accept(MediaType.APPLICATION_XML);

    // Create RequestSecurityToken
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", WST_NS_05_12);

    writer.writeStartElement("wst", "RequestType", WST_NS_05_12);
    writer.writeCharacters(WST_NS_05_12 + "/Validate");
    writer.writeEndElement();

    writer.writeStartElement("wst", "TokenType", WST_NS_05_12);
    String tokenType = WST_NS_05_12 + "/RSTR/Status";
    writer.writeCharacters(tokenType);
    writer.writeEndElement();

    writer.writeStartElement("wst", "ValidateTarget", WST_NS_05_12);
    StaxUtils.copy(assertionDoc.getDocumentElement(), writer);
    writer.writeEndElement();

    writer.writeEndElement();

    RequestSecurityTokenResponseType securityResponse = client.post(
        new DOMSource(writer.getDocument().getDocumentElement()),
        RequestSecurityTokenResponseType.class);

    assertTrue(getValidationStatus(securityResponse));
}
 
Example 13
Source File: IssuedToken.java    From steady with Apache License 2.0 4 votes vote down vote up
public void serialize(XMLStreamWriter writer) throws XMLStreamException {
    String localname = getRealName().getLocalPart();
    String namespaceURI = getRealName().getNamespaceURI();

    String prefix;
    String writerPrefix = writer.getPrefix(namespaceURI);

    if (writerPrefix == null) {
        prefix = getRealName().getPrefix();
        writer.setPrefix(prefix, namespaceURI);

    } else {
        prefix = writerPrefix;
    }

    // <sp:IssuedToken>
    writer.writeStartElement(prefix, localname, namespaceURI);

    if (writerPrefix == null) {
        writer.writeNamespace(prefix, namespaceURI);
    }

    String inclusion;

    inclusion = constants.getAttributeValueFromInclusion(getInclusion());

    if (inclusion != null) {
        writer.writeAttribute(prefix, namespaceURI, SPConstants.ATTR_INCLUDE_TOKEN, inclusion);
    }

    if (issuerEpr != null) {
        JAXBElement<EndpointReferenceType> elem 
            = new JAXBElement<EndpointReferenceType>(new QName(namespaceURI, SPConstants.ISSUER), 
                EndpointReferenceType.class, issuerEpr);
        try {
            ContextUtils.getJAXBContext().createMarshaller().marshal(elem, writer);
        } catch (JAXBException e) {
            //ignore
        }
    }

    if (rstTemplate != null) {
        // <sp:RequestSecurityTokenTemplate>
        StaxUtils.copy(rstTemplate, writer);
    }

    String policyLocalName = SPConstants.POLICY.getLocalPart();
    String policyNamespaceURI = SPConstants.POLICY.getNamespaceURI();

    String wspPrefix;

    String wspWriterPrefix = writer.getPrefix(policyNamespaceURI);

    if (wspWriterPrefix == null) {
        wspPrefix = SPConstants.POLICY.getPrefix();
        writer.setPrefix(wspPrefix, policyNamespaceURI);
    } else {
        wspPrefix = wspWriterPrefix;
    }

    if (isRequireExternalReference() || isRequireInternalReference() || this.isDerivedKeys()) {

        // <wsp:Policy>
        writer.writeStartElement(wspPrefix, policyLocalName, policyNamespaceURI);

        if (wspWriterPrefix == null) {
            // xmlns:wsp=".."
            writer.writeNamespace(wspPrefix, policyNamespaceURI);
        }

        if (isRequireExternalReference()) {
            // <sp:RequireExternalReference />
            writer.writeEmptyElement(prefix, SPConstants.REQUIRE_EXTERNAL_REFERENCE, namespaceURI);
        }

        if (isRequireInternalReference()) {
            // <sp:RequireInternalReference />
            writer.writeEmptyElement(prefix, SPConstants.REQUIRE_INTERNAL_REFERENCE, namespaceURI);
        }

        if (this.isDerivedKeys()) {
            // <sp:RequireDerivedKeys />
            writer.writeEmptyElement(prefix, SPConstants.REQUIRE_DERIVED_KEYS, namespaceURI);
        }

        // <wsp:Policy>
        writer.writeEndElement();
    }

    // </sp:IssuedToken>
    writer.writeEndElement();
}
 
Example 14
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Make an "Validate" invocation and return the response as a STSResponse Object
 */
protected STSResponse validate(SecurityToken tok, String tokentype) 
    throws Exception {
    createClient();
    
    if (tokentype == null) {
        tokentype = tokenType;
    }
    if (tokentype == null) {
        tokentype = namespace + "/RSTR/Status";
    }

    if (addressingNamespace == null) {
        addressingNamespace = "http://www.w3.org/2005/08/addressing";
    }

    Policy validatePolicy = new Policy();
    ExactlyOne one = new ExactlyOne();
    validatePolicy.addPolicyComponent(one);
    All all = new All();
    one.addPolicyComponent(all);
    all.addAssertion(getAddressingAssertion());

    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, tok);
    BindingOperationInfo boi = findOperation("/RST/Validate");
    if (boi == null) {
        boi = findOperation("/RST/Issue");
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, validatePolicy);
    }
    
    client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, 
                                   namespace + "/RST/Validate");

    
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Validate");
    writer.writeEndElement();

    writer.writeStartElement("wst", "TokenType", namespace);
    writer.writeCharacters(tokentype);
    writer.writeEndElement();

    writer.writeStartElement("wst", "ValidateTarget", namespace);

    Element el = tok.getToken();
    StaxUtils.copy(el, writer);

    writer.writeEndElement();
    writer.writeEndElement();

    Object o[] = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    
    return new STSResponse((DOMSource)o[0], null);
}
 
Example 15
Source File: AbstractBPBeanDefinitionParser.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void mapElementToJaxbProperty(ParserContext ctx,
                                        MutableBeanMetadata bean,
                                        Element data,
                                        String propertyName,
                                        Class<?> c) {
    try {
        XMLStreamWriter xmlWriter = null;
        Unmarshaller u = null;
        try {
            StringWriter writer = new StringWriter();
            xmlWriter = StaxUtils.createXMLStreamWriter(writer);
            StaxUtils.copy(data, xmlWriter);
            xmlWriter.flush();


            MutableBeanMetadata factory = ctx.createMetadata(MutableBeanMetadata.class);
            factory.setClassName(c.getName());
            factory.setFactoryComponent(createPassThrough(ctx, new JAXBBeanFactory(getContext(c), c)));
            factory.setFactoryMethod("createJAXBBean");
            factory.addArgument(createValue(ctx, writer.toString()), String.class.getName(), 0);
            bean.addProperty(propertyName, factory);

        } catch (Exception ex) {
            u = getContext(c).createUnmarshaller();
            u.setEventHandler(null);
            Object obj;
            if (c != null) {
                obj = u.unmarshal(data, c);
            } else {
                obj = u.unmarshal(data);
            }
            if (obj instanceof JAXBElement<?>) {
                JAXBElement<?> el = (JAXBElement<?>)obj;
                obj = el.getValue();
            }
            if (obj != null) {
                MutablePassThroughMetadata value = ctx.createMetadata(MutablePassThroughMetadata.class);
                value.setObject(obj);
                bean.addProperty(propertyName, value);
            }
        } finally {
            StaxUtils.close(xmlWriter);
            JAXBUtils.closeUnmarshaller(u);
        }
    } catch (JAXBException e) {
        throw new RuntimeException("Could not parse configuration.", e);
    }
}
 
Example 16
Source File: SchemaSerializer.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void writeXml(Node n, PrintWriter pw) throws XMLStreamException {
    XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(pw);
    writer = new PrettyPrintXMLStreamWriter(writer, 2);
    StaxUtils.copy(new DOMSource(n), writer);
    writer.close();
}
 
Example 17
Source File: IssuedToken.java    From steady with Apache License 2.0 4 votes vote down vote up
public void serialize(XMLStreamWriter writer) throws XMLStreamException {
    String localname = getRealName().getLocalPart();
    String namespaceURI = getRealName().getNamespaceURI();

    String prefix;
    String writerPrefix = writer.getPrefix(namespaceURI);

    if (writerPrefix == null) {
        prefix = getRealName().getPrefix();
        writer.setPrefix(prefix, namespaceURI);

    } else {
        prefix = writerPrefix;
    }

    // <sp:IssuedToken>
    writer.writeStartElement(prefix, localname, namespaceURI);

    if (writerPrefix == null) {
        writer.writeNamespace(prefix, namespaceURI);
    }

    String inclusion;

    inclusion = constants.getAttributeValueFromInclusion(getInclusion());

    if (inclusion != null) {
        writer.writeAttribute(prefix, namespaceURI, SPConstants.ATTR_INCLUDE_TOKEN, inclusion);
    }

    if (issuerEpr != null) {
        JAXBElement<EndpointReferenceType> elem 
            = new JAXBElement<EndpointReferenceType>(new QName(namespaceURI, SPConstants.ISSUER), 
                EndpointReferenceType.class, issuerEpr);
        try {
            ContextUtils.getJAXBContext().createMarshaller().marshal(elem, writer);
        } catch (JAXBException e) {
            //ignore
        }
    }

    if (rstTemplate != null) {
        // <sp:RequestSecurityTokenTemplate>
        StaxUtils.copy(rstTemplate, writer);
    }

    String policyLocalName = SPConstants.POLICY.getLocalPart();
    String policyNamespaceURI = SPConstants.POLICY.getNamespaceURI();

    String wspPrefix;

    String wspWriterPrefix = writer.getPrefix(policyNamespaceURI);

    if (wspWriterPrefix == null) {
        wspPrefix = SPConstants.POLICY.getPrefix();
        writer.setPrefix(wspPrefix, policyNamespaceURI);
    } else {
        wspPrefix = wspWriterPrefix;
    }

    if (isRequireExternalReference() || isRequireInternalReference() || this.isDerivedKeys()) {

        // <wsp:Policy>
        writer.writeStartElement(wspPrefix, policyLocalName, policyNamespaceURI);

        if (wspWriterPrefix == null) {
            // xmlns:wsp=".."
            writer.writeNamespace(wspPrefix, policyNamespaceURI);
        }

        if (isRequireExternalReference()) {
            // <sp:RequireExternalReference />
            writer.writeEmptyElement(prefix, SPConstants.REQUIRE_EXTERNAL_REFERENCE, namespaceURI);
        }

        if (isRequireInternalReference()) {
            // <sp:RequireInternalReference />
            writer.writeEmptyElement(prefix, SPConstants.REQUIRE_INTERNAL_REFERENCE, namespaceURI);
        }

        if (this.isDerivedKeys()) {
            // <sp:RequireDerivedKeys />
            writer.writeEmptyElement(prefix, SPConstants.REQUIRE_DERIVED_KEYS, namespaceURI);
        }

        // <wsp:Policy>
        writer.writeEndElement();
    }

    // </sp:IssuedToken>
    writer.writeEndElement();
}
 
Example 18
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Make an "Cancel" invocation and return the response as a STSResponse Object
 */
protected STSResponse cancel(SecurityToken token) throws Exception {
    createClient();

    if (addressingNamespace == null) {
        addressingNamespace = "http://www.w3.org/2005/08/addressing";
    }

    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, token);
    
    BindingOperationInfo boi = findOperation("/RST/Cancel");
    boolean attachTokenDirectly = true;
    if (boi == null) {
        attachTokenDirectly = false;
        boi = findOperation("/RST/Issue");
        
        Policy cancelPolicy = new Policy();
        ExactlyOne one = new ExactlyOne();
        cancelPolicy.addPolicyComponent(one);
        All all = new All();
        one.addPolicyComponent(all);
        all.addAssertion(getAddressingAssertion());
        
        PolicyBuilder pbuilder = bus.getExtension(PolicyBuilder.class);
        SymmetricBinding binding = new SymmetricBinding(pbuilder);
        all.addAssertion(binding);
        all.addAssertion(getAddressingAssertion());
        ProtectionToken ptoken = new ProtectionToken(pbuilder);
        binding.setProtectionToken(ptoken);
        binding.setIncludeTimestamp(true);
        binding.setEntireHeadersAndBodySignatures(true);
        binding.setTokenProtection(false);
        AlgorithmSuite suite = new AlgorithmSuite();
        binding.setAlgorithmSuite(suite);
        SecureConversationToken sct = new SecureConversationToken();
        sct.setOptional(true);
        ptoken.setToken(sct);
        
        SignedEncryptedParts parts = new SignedEncryptedParts(true);
        parts.setOptional(true);
        parts.setBody(true);
        parts.addHeader(new Header("To", addressingNamespace));
        parts.addHeader(new Header("From", addressingNamespace));
        parts.addHeader(new Header("FaultTo", addressingNamespace));
        parts.addHeader(new Header("ReplyTo", addressingNamespace));
        parts.addHeader(new Header("Action", addressingNamespace));
        parts.addHeader(new Header("MessageID", addressingNamespace));
        parts.addHeader(new Header("RelatesTo", addressingNamespace));
        all.addPolicyComponent(parts);
        
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, cancelPolicy);
    }
    
    if (isSecureConv) {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION,
                                       namespace + "/RST/SCT/Cancel");
    } else {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, 
                                       namespace + "/RST/Cancel");            
    }

    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Cancel");
    writer.writeEndElement();

    writer.writeStartElement("wst", "CancelTarget", namespace);
    Element el = null;
    if (attachTokenDirectly) {
        el = token.getToken();
    } else {
        el = token.getUnattachedReference();
        if (el == null) {
            el = token.getAttachedReference();
        }
    }
    StaxUtils.copy(el, writer);

    writer.writeEndElement();
    writer.writeEndElement();

    Object[] obj = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    return new STSResponse((DOMSource)obj[0], null);
}
 
Example 19
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Make an "Validate" invocation and return the response as a STSResponse Object
 */
protected STSResponse validate(SecurityToken tok, String tokentype) 
    throws Exception {
    createClient();
    
    if (tokentype == null) {
        tokentype = tokenType;
    }
    if (tokentype == null) {
        tokentype = namespace + "/RSTR/Status";
    }

    if (addressingNamespace == null) {
        addressingNamespace = "http://www.w3.org/2005/08/addressing";
    }

    Policy validatePolicy = new Policy();
    ExactlyOne one = new ExactlyOne();
    validatePolicy.addPolicyComponent(one);
    All all = new All();
    one.addPolicyComponent(all);
    all.addAssertion(getAddressingAssertion());

    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, tok);
    BindingOperationInfo boi = findOperation("/RST/Validate");
    if (boi == null) {
        boi = findOperation("/RST/Issue");
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, validatePolicy);
    }
    
    client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, 
                                   namespace + "/RST/Validate");

    
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Validate");
    writer.writeEndElement();

    writer.writeStartElement("wst", "TokenType", namespace);
    writer.writeCharacters(tokentype);
    writer.writeEndElement();

    writer.writeStartElement("wst", "ValidateTarget", namespace);

    Element el = tok.getToken();
    StaxUtils.copy(el, writer);

    writer.writeEndElement();
    writer.writeEndElement();

    Object o[] = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    
    return new STSResponse((DOMSource)o[0], null);
}
 
Example 20
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Make an "Renew" invocation and return the response as a STSResponse Object
 */
public STSResponse renew(SecurityToken tok) throws Exception {
    createClient();
    BindingOperationInfo boi = findOperation("/RST/Renew");

    client.getRequestContext().putAll(ctx);
    if (isSecureConv) {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, namespace + "/RST/SCT/Renew");
    } else {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, namespace + "/RST/Renew");
    }

    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    if (context != null) {
        writer.writeAttribute(null, "Context", context);
    }
    
    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 ("TokenType".equals(tl.getLocalName())) {
                sptt = DOMUtils.getContent(tl);
            }
            tl = DOMUtils.getNextElement(tl);
        }
        
        if (this.useSecondaryParameters()) {
            writer.writeEndElement();
        }
    }
    
    if (isSpnego) {
        tokenType = STSUtils.getTokenTypeSCT(namespace);
    }

    addRequestType("/Renew", writer);
    if (enableAppliesTo) {
        addAppliesTo(writer, tok.getIssuerAddress());
    }
    
    if (sptt == null) {
        addTokenType(writer);
    }
    if (isSecureConv || enableLifetime) {
        addLifetime(writer);
    }

    writer.writeStartElement("wst", "RenewTarget", namespace);
    client.getRequestContext().put(SecurityConstants.TOKEN, tok);
    StaxUtils.copy(tok.getToken(), writer);
    writer.writeEndElement();
    
    writer.writeEndElement();

    Object obj[] = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));

    return new STSResponse((DOMSource)obj[0], null);
}