Java Code Examples for org.apache.cxf.helpers.DOMUtils#getFirstElement()

The following examples show how to use org.apache.cxf.helpers.DOMUtils#getFirstElement() . 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: AbstractSTSClient.java    From steady with Apache License 2.0 6 votes vote down vote up
protected String findMEXLocation(Element ref) {
    Element el = DOMUtils.getFirstElement(ref);
    while (el != null) {
        if (el.getLocalName().equals("Address")
            && VersionTransformer.isSupported(el.getNamespaceURI())
            && "MetadataReference".equals(ref.getLocalName())) {
            return DOMUtils.getContent(el);
        } else {
            String ad = findMEXLocation(el);
            if (ad != null) {
                return ad;
            }
        }
        el = DOMUtils.getNextElement(el);
    }
    return null;
}
 
Example 2
Source File: PolicyFeatureBeanDefinitionParser.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected void parseChildElements(Element e, ParserContext ctx, BeanDefinitionBuilder bean) {
    List<Element> ps = new ArrayList<>();
    List<Element> prs = new ArrayList<>();

    Element elem = DOMUtils.getFirstElement(e);
    while (elem != null) {
        if ("Policy".equals(elem.getLocalName())) {
            ps.add(elem);
        } else if ("PolicyReference".equals(elem.getLocalName())) {
            prs.add(elem);
        }
        elem = DOMUtils.getNextElement(elem);
    }
    bean.addPropertyValue("policyElements", ps);
    bean.addPropertyValue("policyReferenceElements", prs);

    super.parseChildElements(e, ctx, bean);
}
 
Example 3
Source File: JettyServerEngineFactoryParser.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Metadata parseEngineConnector(List<Element> engines, ComponentMetadata enclosingComponent,
                                        ParserContext context) {
    MutableMapMetadata map = context.createMetadata(MutableMapMetadata.class);
    map.setKeyType("java.lang.String");
    map.setValueType("org.eclipse.jetty.server.Connector");

    for (Element engine : engines) {
        String port = engine.getAttribute("port");
        ValueMetadata keyValue = createValue(context, port);
        Element connector = DOMUtils
            .getFirstChildWithName(engine, HTTPJettyTransportNamespaceHandler.JETTY_TRANSPORT,
                                   "connector");
        if (connector != null) {
            Element first = DOMUtils.getFirstElement(connector);
            Metadata valValue = context.parseElement(Metadata.class, enclosingComponent, first);
            map.addEntry(keyValue, valValue);
        }
    }

    return map;
}
 
Example 4
Source File: SimpleBatchSTSClient.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected String getIDFromSTR(Element el) {
    Element child = DOMUtils.getFirstElement(el);
    if (child == null) {
        return null;
    }
    QName elName = DOMUtils.getElementQName(child);
    if (elName.equals(new QName(WSS4JConstants.SIG_NS, "KeyInfo"))
        || elName.equals(new QName(WSS4JConstants.WSSE_NS, "KeyIdentifier"))) {
        return DOMUtils.getContent(child);
    } else if (elName.equals(Reference.TOKEN)) {
        return child.getAttributeNS(null, "URI");
    } else if (elName.equals(new QName(STSUtils.SCT_NS_05_02, "Identifier"))
               || elName.equals(new QName(STSUtils.SCT_NS_05_12, "Identifier"))) {
        return DOMUtils.getContent(child);
    }
    return null;
}
 
Example 5
Source File: IssuedTokenPolicyValidator.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Check the issued token template against the received BinarySecurityToken
 */
private boolean checkIssuedTokenTemplate(Element template, BinarySecurity binarySecurityToken) {
    Element child = DOMUtils.getFirstElement(template);
    while (child != null) {
        if ("TokenType".equals(child.getLocalName())) {
            String content = child.getTextContent();
            String valueType = binarySecurityToken.getValueType();
            if (!content.equals(valueType)) {
                return false;
            }
        }
        child = DOMUtils.getNextElement(child);
    }
    return true;
}
 
Example 6
Source File: JmsSubscription.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void onMessage(Message jmsMessage) {
    try {
        TextMessage text = (TextMessage) jmsMessage;
        XMLStreamReader reader = StaxUtils.createXMLStreamReader(new StringReader(text.getText()));
        Notify notify = (Notify) jaxbContext.createUnmarshaller()
                .unmarshal(reader);
        reader.close();
        for (Iterator<NotificationMessageHolderType> ith = notify.getNotificationMessage().iterator();
            ith.hasNext();) {
            NotificationMessageHolderType h = ith.next();
            Object content = h.getMessage().getAny();
            if (!(content instanceof Element)) {
                DocumentFragment doc = DOMUtils.getEmptyDocument().createDocumentFragment();
                jaxbContext.createMarshaller().marshal(content, doc);
                content = DOMUtils.getFirstElement(doc);
            }
            if (!doFilter((Element) content)) {
                ith.remove();
            } else {
                h.setTopic(topic);
                h.setSubscriptionReference(getEpr());
            }
        }
        if (!notify.getNotificationMessage().isEmpty()) {
            doNotify(notify);
        }
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Error notifying consumer", e);
    }
}
 
Example 7
Source File: EndpointReferenceTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Element fetchElementByNameAttribute(Element parent, String elementName, String nameValue) {
    if (elementName.equals(parent.getTagName())
        && parent.getAttribute("name").equals(nameValue)) {
        return parent;
    }
    Element elem = DOMUtils.getFirstElement(parent);
    while (elem != null) {
        Element el = fetchElementByNameAttribute(elem, elementName, nameValue);
        if (el != null) {
            return el;
        }
        elem = DOMUtils.getNextElement(elem);
    }
    return null;
}
 
Example 8
Source File: SamlTokenInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
private void processSamlToken(SoapMessage message) {
    Header h = findSecurityHeader(message, false);
    if (h == null) {
        return;
    }
    Element el = (Element)h.getObject();
    Element child = DOMUtils.getFirstElement(el);
    while (child != null) {
        if ("Assertion".equals(child.getLocalName())) {
            try {
                List<WSSecurityEngineResult> samlResults = processToken(child, message);
                if (samlResults != null) {
                    List<WSHandlerResult> results = CastUtils.cast((List<?>)message
                            .get(WSHandlerConstants.RECV_RESULTS));
                    if (results == null) {
                        results = new ArrayList<WSHandlerResult>();
                        message.put(WSHandlerConstants.RECV_RESULTS, results);
                    }
                    WSHandlerResult rResult = new WSHandlerResult(null, samlResults);
                    results.add(0, rResult);

                    assertSamlTokens(message);
                    
                    Principal principal = 
                        (Principal)samlResults.get(0).get(WSSecurityEngineResult.TAG_PRINCIPAL);
                    message.put(WSS4JInInterceptor.PRINCIPAL_RESULT, principal);                   
                    
                    SecurityContext sc = message.get(SecurityContext.class);
                    if (sc == null || sc.getUserPrincipal() == null) {
                        message.put(SecurityContext.class, new DefaultSecurityContext(principal, null));
                    }

                }
            } catch (WSSecurityException ex) {
                throw new Fault(ex);
            }
        }
        child = DOMUtils.getNextElement(child);
    }
}
 
Example 9
Source File: STSClient.java    From steady with Apache License 2.0 5 votes vote down vote up
private String getTokenTypeFromTemplate() {
    if (template != null && DOMUtils.getFirstElement(template) != null) {
        Element tl = DOMUtils.getFirstElement(template);
        while (tl != null) {
            if ("TokenType".equals(tl.getLocalName())) {
                return DOMUtils.getContent(tl);
            }
            tl = DOMUtils.getNextElement(tl);
        }
    }
    return null;
}
 
Example 10
Source File: PolicyConstants.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void findAllPolicyElementsOfLocalName(Element el, String localName, List<Element> val) {
    QName qn = DOMUtils.getElementQName(el);
    if (localName.equals(qn.getLocalPart()) && Constants.isInPolicyNS(qn)) {
        val.add(el);
    }
    el = DOMUtils.getFirstElement(el);
    while (el != null) {
        findAllPolicyElementsOfLocalName(el, localName, val);
        el = DOMUtils.getNextElement(el);
    }
}
 
Example 11
Source File: DefaultClaimsPolicyValidator.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Validate a particular Claims policy against a received SAML Assertion. 
 * Return true if the policy is valid.
 */
public boolean validatePolicy(
    Element claimsPolicy,
    AssertionWrapper assertion
) {
    if (claimsPolicy == null) {
        return false;
    }
    
    String dialect = claimsPolicy.getAttributeNS(null, "Dialect");
    if (!DEFAULT_CLAIMS_NAMESPACE.equals(dialect)) {
        return false;
    }
    
    Element claimType = DOMUtils.getFirstElement(claimsPolicy);
    while (claimType != null) {
        if ("ClaimType".equals(claimType.getLocalName())) {
            String claimTypeUri = claimType.getAttributeNS(null, "Uri");
            String claimTypeOptional = claimType.getAttributeNS(null, "Optional");
            
            if (("".equals(claimTypeOptional) || !Boolean.parseBoolean(claimTypeOptional))
                && !findClaimInAssertion(assertion, URI.create(claimTypeUri))) {
                return false;
            }
        }
        
        claimType = DOMUtils.getNextElement(claimType);
    }
    
    return true;
}
 
Example 12
Source File: AlgorithmSuiteBuilder.java    From steady with Apache License 2.0 5 votes vote down vote up
public Assertion build(Element element, AssertionBuilderFactory factory)
    throws IllegalArgumentException {
    
    SPConstants consts = SP11Constants.SP_NS.equals(element.getNamespaceURI())
        ? SP11Constants.INSTANCE : SP12Constants.INSTANCE;

    AlgorithmSuiteLoader loader = bus.getExtension(AlgorithmSuiteLoader.class);
    if (loader == null) {
        loader = new DefaultAlgorithmSuiteLoader();
    } 
    Element policyElement = DOMUtils.getFirstElement(element);
    if (policyElement == null) {
        throw new IllegalArgumentException(
            "sp:AlgorithmSuite/wsp:Policy must have a value"
        );
    }
    AlgorithmSuite algorithmSuite = null;
    try {
        algorithmSuite = loader.getAlgorithmSuite(policyElement, consts);
    } catch (WSSPolicyException e) {
        throw new IllegalArgumentException(e);
    }
    
    if (algorithmSuite == null && consts != SP11Constants.INSTANCE) {
        String algorithmSuiteName = DOMUtils.getFirstElement(policyElement).getLocalName();
        throw new IllegalArgumentException(
            "Algorithm suite \"" + algorithmSuiteName + "\" is not registered"
        );
    }

    return algorithmSuite;
}
 
Example 13
Source File: DefaultClaimsPolicyValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Validate a particular Claims policy against a received SAML Assertion.
 * Return true if the policy is valid.
 */
public boolean validatePolicy(
    Element claimsPolicy,
    SamlAssertionWrapper assertion
) {
    if (claimsPolicy == null) {
        return false;
    }

    String dialect = claimsPolicy.getAttributeNS(null, "Dialect");
    if (!DEFAULT_CLAIMS_NAMESPACE.equals(dialect)) {
        return false;
    }

    Element claimType = DOMUtils.getFirstElement(claimsPolicy);
    while (claimType != null) {
        if ("ClaimType".equals(claimType.getLocalName())) {
            String claimTypeUri = claimType.getAttributeNS(null, "Uri");
            String claimTypeOptional = claimType.getAttributeNS(null, "Optional");

            if (("".equals(claimTypeOptional) || !Boolean.parseBoolean(claimTypeOptional))
                && !findClaimInAssertion(assertion, URI.create(claimTypeUri))) {
                return false;
            }
        }

        claimType = DOMUtils.getNextElement(claimType);
    }

    return true;
}
 
Example 14
Source File: LayoutBuilder.java    From steady with Apache License 2.0 5 votes vote down vote up
public void processAlternative(Element element, Layout parent, SPConstants consts) {
    Element polEl = PolicyConstants.findPolicyElement(element);
    if (polEl == null && consts != SP11Constants.INSTANCE) {
        throw new IllegalArgumentException(
            "sp:Layout/wsp:Policy must have a value"
        );
    }
    if (polEl != null) {
        Element child = DOMUtils.getFirstElement(polEl);
        if (child != null) {
            parent.setValue(SPConstants.Layout.valueOf(child.getLocalName()));
        }
    }
}
 
Example 15
Source File: WSS11Builder.java    From steady with Apache License 2.0 5 votes vote down vote up
private void processAlternative(Element element, Wss11 parent, SPConstants consts) {
    Element polEl = PolicyConstants.findPolicyElement(element);
    if (polEl != null) {
        Element child = DOMUtils.getFirstElement(polEl);
        while (child != null) {
            String name = child.getLocalName();

            if (SPConstants.MUST_SUPPORT_REF_KEY_IDENTIFIER.equals(name)) {
                parent.setMustSupportRefKeyIdentifier(true);
            } else if (SPConstants.MUST_SUPPORT_REF_ISSUER_SERIAL.equals(name)) {
                parent.setMustSupportRefIssuerSerial(true);
            } else if (SPConstants.MUST_SUPPORT_REF_EXTERNAL_URI.equals(name)) {
                parent.setMustSupportRefExternalURI(true);
            } else if (SPConstants.MUST_SUPPORT_REF_EMBEDDED_TOKEN.equals(name)) {
                parent.setMustSupportRefEmbeddedToken(true);

            } else if (SPConstants.MUST_SUPPORT_REF_THUMBPRINT.equals(name)) {
                parent.setMustSupportRefThumbprint(true);

            } else if (SPConstants.MUST_SUPPORT_REF_ENCRYPTED_KEY.equals(name)) {
                parent.setMustSupportRefEncryptedKey(true);

            } else if (SPConstants.REQUIRE_SIGNATURE_CONFIRMATION.equals(name)) {
                parent.setRequireSignatureConfirmation(true);
            } 
            child = DOMUtils.getNextElement(child);
        }
    }
}
 
Example 16
Source File: SamlTokenBuilder.java    From steady with Apache License 2.0 4 votes vote down vote up
public Assertion build(Element element, AssertionBuilderFactory factory) {
    
    SPConstants consts = SP11Constants.SP_NS.equals(element.getNamespaceURI())
        ? SP11Constants.INSTANCE : SP12Constants.INSTANCE;

    SamlToken samlToken = new SamlToken(consts);
    samlToken.setOptional(PolicyConstants.isOptional(element));
    samlToken.setIgnorable(PolicyConstants.isIgnorable(element));

    String attribute = element.getAttributeNS(element.getNamespaceURI(), SPConstants.ATTR_INCLUDE_TOKEN);
    if (attribute != null) {
        samlToken.setInclusion(consts.getInclusionFromAttributeValue(attribute));
    }
    
    Element child = DOMUtils.getFirstElement(element);
    boolean foundPolicy = false;
    while (child != null) {
        String ln = child.getLocalName();
        if (org.apache.neethi.Constants.ELEM_POLICY.equals(ln)) {
            foundPolicy = true;
            NodeList policyChildren = child.getChildNodes();
            if (policyChildren != null) {
                for (int i = 0; i < policyChildren.getLength(); i++) {
                    Node policyChild = policyChildren.item(i);
                    if (policyChild instanceof Element) {
                        QName qname = 
                            new QName(policyChild.getNamespaceURI(), policyChild.getLocalName());
                        String localname = qname.getLocalPart();
                        if (SPConstants.SAML_11_TOKEN_10.equals(localname)) {
                            samlToken.setUseSamlVersion11Profile10(true);
                        } else if (SPConstants.SAML_11_TOKEN_11.equals(localname)) {
                            samlToken.setUseSamlVersion11Profile11(true);
                        } else if (SPConstants.SAML_20_TOKEN_11.equals(localname)) {
                            samlToken.setUseSamlVersion20Profile11(true);
                        } else if (SPConstants.REQUIRE_DERIVED_KEYS.equals(localname)) {
                            samlToken.setDerivedKeys(true);
                        } else if (SPConstants.REQUIRE_EXPLICIT_DERIVED_KEYS.equals(localname)) {
                            samlToken.setExplicitDerivedKeys(true);
                        } else if (SPConstants.REQUIRE_IMPLIED_DERIVED_KEYS.equals(localname)) {
                            samlToken.setImpliedDerivedKeys(true);
                        } else if (SPConstants.REQUIRE_KEY_IDENTIFIER_REFERENCE.equals(localname)) {
                            samlToken.setRequireKeyIdentifierReference(true);
                        }
                    }
                }
            }
        }
        child = DOMUtils.getNextElement(child);
    }
    
    if (!foundPolicy && consts != SP11Constants.INSTANCE) {
        throw new IllegalArgumentException(
            "sp:SpnegoContextToken/wsp:Policy must have a value"
        );
    }
    
    return samlToken;
}
 
Example 17
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);
}
 
Example 18
Source File: SpnegoContextTokenBuilder.java    From steady with Apache License 2.0 4 votes vote down vote up
public Assertion build(Element element, AssertionBuilderFactory factory)
    throws IllegalArgumentException {
    SPConstants consts = SP11Constants.SP_NS.equals(element.getNamespaceURI())
            ? SP11Constants.INSTANCE : SP12Constants.INSTANCE;
    
    SpnegoContextToken spnegoContextToken = new SpnegoContextToken(consts);
    spnegoContextToken.setOptional(PolicyConstants.isOptional(element));
    spnegoContextToken.setIgnorable(PolicyConstants.isIgnorable(element));
    
    String attribute = DOMUtils.getAttribute(element, consts.getIncludeToken());
    if (attribute != null) {
        spnegoContextToken.setInclusion(consts.getInclusionFromAttributeValue(attribute.trim()));
    }

    Element elem = DOMUtils.getFirstElement(element);
    boolean foundPolicy = false;
    while (elem != null) {
        QName qn = DOMUtils.getElementQName(elem);
        if (Constants.isPolicyElement(qn)) {
            foundPolicy = true;
            if (DOMUtils.getFirstChildWithName(elem, consts.getNamespace(),
                    SPConstants.REQUIRE_DERIVED_KEYS) != null) {
                spnegoContextToken.setDerivedKeys(true);
            } else if (DOMUtils.getFirstChildWithName(elem, 
                    SP12Constants.REQUIRE_IMPLIED_DERIVED_KEYS) != null) {
                spnegoContextToken.setImpliedDerivedKeys(true);
            } else if (DOMUtils.getFirstChildWithName(elem, 
                    SP12Constants.REQUIRE_EXPLICIT_DERIVED_KEYS) != null) {
                spnegoContextToken.setExplicitDerivedKeys(true);
            }
        } else if (consts.getNamespace().equals(qn.getNamespaceURI())
                && SPConstants.ISSUER.equals(qn.getLocalPart())) {
            spnegoContextToken.setIssuerEpr(DOMUtils.getFirstElement(elem));
        }
        elem = DOMUtils.getNextElement(elem);
    }
    
    if (!foundPolicy && consts != SP11Constants.INSTANCE) {
        throw new IllegalArgumentException(
            "sp:SpnegoContextToken/wsp:Policy must have a value"
        );
    }
    return spnegoContextToken;
}
 
Example 19
Source File: TransportBindingBuilder.java    From steady with Apache License 2.0 4 votes vote down vote up
private void processAlternative(Element element, 
                                TransportBinding parent,
                                SPConstants consts,
                                AssertionBuilderFactory factory) {
    Element polEl = DOMUtils.getFirstElement(element);
    boolean foundTransportToken = false;
    boolean foundAlgorithmSuite = false;
    while (polEl != null) {
        if (Constants.isPolicyElement(new QName(polEl.getNamespaceURI(),
                                                   polEl.getLocalName()))) {
            Element child = DOMUtils.getFirstElement(polEl);
            while (child != null) {
                String name = child.getLocalName();
                if (name.equals(SPConstants.ALGO_SUITE)) {
                    foundAlgorithmSuite = true;
                    parent.setAlgorithmSuite((AlgorithmSuite)new AlgorithmSuiteBuilder(bus)
                        .build(child, factory));
                } else if (name.equals(SPConstants.TRANSPORT_TOKEN)) {
                    foundTransportToken = true;
                    parent.setTransportToken((TransportToken)new TransportTokenBuilder(builder)
                                                    .build(child, factory));
                } else if (name.equals(SPConstants.INCLUDE_TIMESTAMP)) {
                    parent.setIncludeTimestamp(true);
                } else if (name.equals(SPConstants.LAYOUT)) {
                    parent.setLayout((Layout)new LayoutBuilder().build(child, factory));
                } else if (name.equals(SPConstants.SIGNED_SUPPORTING_TOKENS)
                    || name.equals(SPConstants.SIGNED_ENDORSING_SUPPORTING_TOKENS)) {
                    
                    if (consts.getVersion() == SPConstants.Version.SP_V11) {
                        parent.setSignedSupportingToken((SupportingToken)
                                                        new SupportingTokensBuilder(builder)
                                                        .build(child, factory));
                    } else {
                        parent.setSignedSupportingToken((SupportingToken)
                                                        new SupportingTokens12Builder(builder)
                                                            .build(child, factory));
                    }
                }
                child = DOMUtils.getNextElement(child);
            }
        }
        polEl = DOMUtils.getNextElement(polEl);
    }
    
    if (!foundTransportToken && consts != SP11Constants.INSTANCE) {
        throw new IllegalArgumentException(
            "sp:TransportBinding/wsp:Policy/sp:TransportToken must have a value"
        );
    }
    if (!foundAlgorithmSuite && consts != SP11Constants.INSTANCE) {
        throw new IllegalArgumentException(
            "sp:TransportBinding/wsp:Policy/sp:AlgorithmSuite must have a value"
        );
    }
    
}
 
Example 20
Source File: IssuedTokenBuilder.java    From steady with Apache License 2.0 4 votes vote down vote up
public Assertion build(Element element, AssertionBuilderFactory factory)
    throws IllegalArgumentException {
    
    SPConstants consts = SP11Constants.SP_NS.equals(element.getNamespaceURI())
        ? SP11Constants.INSTANCE : SP12Constants.INSTANCE;


    IssuedToken issuedToken = new IssuedToken(consts);
    issuedToken.setOptional(PolicyConstants.isOptional(element));
    issuedToken.setIgnorable(PolicyConstants.isIgnorable(element));

    String includeAttr = DOMUtils.getAttribute(element, consts.getIncludeToken());
    if (includeAttr != null) {
        issuedToken.setInclusion(consts.getInclusionFromAttributeValue(includeAttr));
    }
    
    Element child = DOMUtils.getFirstElement(element);
    boolean foundPolicy = false;
    boolean foundRST = false;
    while (child != null) {
        String ln = child.getLocalName();
        if (SPConstants.ISSUER.equals(ln)) {
            try {
                EndpointReferenceType epr = VersionTransformer.parseEndpointReference(child);
                issuedToken.setIssuerEpr(epr);
            } catch (JAXBException e) {
                throw new IllegalArgumentException(e);
            }
        } else if (SPConstants.REQUEST_SECURITY_TOKEN_TEMPLATE.equals(ln)) {
            foundRST = true;
            issuedToken.setRstTemplate(child);
        } else if (org.apache.neethi.Constants.ELEM_POLICY.equals(ln)) {
            foundPolicy = true;
            Policy policy = builder.getPolicy(child);
            policy = policy.normalize(builder.getPolicyRegistry(), false);

            for (Iterator<List<Assertion>> iterator = policy.getAlternatives(); iterator.hasNext();) {
                processAlternative(iterator.next(), issuedToken);
                break; // since there should be only one alternative ..
            }                
        } else if (SPConstants.ISSUER_NAME.equals(ln)) {
            String issuerName = child.getNodeValue();
            issuedToken.setIssuerName(issuerName);
        }
        
        child = DOMUtils.getNextElement(child);
    }
    
    if (!foundPolicy && consts != SP11Constants.INSTANCE) {
        throw new IllegalArgumentException(
            "sp:IssuedToken/wsp:Policy must have a value"
        );
    }
    if (!foundRST) {
        throw new IllegalArgumentException(
            "sp:IssuedToken/sp:RequestSecurityTokenTemplate must have a value"
        );
    }
    
    return issuedToken;
}