Example usage for org.w3c.dom Node getLocalName

List of usage examples for org.w3c.dom Node getLocalName

Introduction

In this page you can find the example usage for org.w3c.dom Node getLocalName.

Prototype

public String getLocalName();

Source Link

Document

Returns the local part of the qualified name of this node.

Usage

From source file:org.apache.ws.security.saml.SAMLUtil.java

private static String[] getValidityPeriod(Element assertion) {
    String[] validityPeriod = new String[2];
    for (Node currentChild = assertion.getFirstChild(); currentChild != null; currentChild = currentChild
            .getNextSibling()) {/*from  w w w. java 2s  .  c  o m*/
        if (WSConstants.SAML_CONDITION.equals(currentChild.getLocalName())
                && WSConstants.SAML_NS.equals(currentChild.getNamespaceURI())) {
            NamedNodeMap attributes = currentChild.getAttributes();
            for (int i = 0; i < attributes.getLength(); i++) {
                Node attr = attributes.item(i);
                if (WSConstants.SAML_NOT_BEFORE.equals(attr.getLocalName())) {
                    validityPeriod[0] = attr.getNodeValue();
                } else if (WSConstants.SAML_NOT_AFTER.equals(attr.getLocalName())) {
                    validityPeriod[1] = attr.getNodeValue();
                }
            }

            break;
        }
    }

    return validityPeriod;
}

From source file:org.apache.ws.security.util.WSSecurityUtil.java

/**
 * Returns the first element that matches <code>name</code> and
 * <code>namespace</code>. <p/> This is a replacement for a XPath lookup
 * <code>//name</code> with the given namespace. It's somewhat faster than
 * XPath, and we do not deal with prefixes, just with the real namespace URI
 * /*from   w  ww . jav a  2 s.  c o  m*/
 * @param startNode Where to start the search
 * @param name Local name of the element
 * @param namespace Namespace URI of the element
 * @return The found element or <code>null</code>
 */
public static Node findElement(Node startNode, String name, String namespace) {
    //
    // Replace the formerly recursive implementation with a depth-first-loop
    // lookup
    //
    if (startNode == null) {
        return null;
    }
    Node startParent = startNode.getParentNode();
    Node processedNode = null;

    while (startNode != null) {
        // start node processing at this point
        if (startNode.getNodeType() == Node.ELEMENT_NODE && startNode.getLocalName().equals(name)) {
            String ns = startNode.getNamespaceURI();
            if (ns != null && ns.equals(namespace)) {
                return startNode;
            }

            if ((namespace == null || namespace.length() == 0) && (ns == null || ns.length() == 0)) {
                return startNode;
            }
        }
        processedNode = startNode;
        startNode = startNode.getFirstChild();

        // no child, this node is done.
        if (startNode == null) {
            // close node processing, get sibling
            startNode = processedNode.getNextSibling();
        }
        // no more siblings, get parent, all children
        // of parent are processed.
        while (startNode == null) {
            processedNode = processedNode.getParentNode();
            if (processedNode == startParent) {
                return null;
            }
            // close parent node processing (processed node now)
            startNode = processedNode.getNextSibling();
        }
    }
    return null;
}

From source file:org.apache.ws.security.WSSecurityEngine.java

/**
 * Process the security header given the <code>wsse:Security</code> DOM
 * Element. /* ww  w .  j  av a 2s  .  co  m*/
 * 
 * This function loops over all direct child elements of the
 * <code>wsse:Security</code> header. If it finds a known element, it
 * transfers control to the appropriate handling function. The method
 * processes the known child elements in the same order as they appear in
 * the <code>wsse:Security</code> element. This is in accordance to the WS
 * Security specification. <p/>
 * 
 * Currently the functions can handle the following child elements:
 * 
 * <ul>
 * <li>{@link #SIGNATURE <code>ds:Signature</code>}</li>
 * <li>{@link #ENCRYPTED_KEY <code>xenc:EncryptedKey</code>}</li>
 * <li>{@link #REFERENCE_LIST <code>xenc:ReferenceList</code>}</li>
 * <li>{@link #usernameToken <code>wsse:UsernameToken</code>}</li>
 * <li>{@link #timeStamp <code>wsu:Timestamp</code>}</li>
 * </ul>
 *
 * Note that additional child elements can be processed if appropriate
 * Processors have been registered with the WSSCondig instance set
 * on this class.
 *
 * @param securityHeader the <code>wsse:Security</code> header element
 * @param cb             a callback hander to the caller to resolve passwords during
 *                       encryption and {@link UsernameToken}handling
 * @param sigCrypto      the object that implements the access to the keystore and the
 *                       handling of certificates used for Signature
 * @param decCrypto      the object that implements the access to the keystore and the
 *                       handling of certificates used for Decryption
 * @return a Vector of {@link WSSecurityEngineResult}. Each element in the
 *         the Vector represents the result of a security action. The elements
 *         are ordered according to the sequence of the security actions in the
 *         wsse:Signature header. The Vector maybe empty if no security processing
 *         was performed.
 * @throws WSSecurityException
 */
protected Vector processSecurityHeader(Element securityHeader, CallbackHandler cb, Crypto sigCrypto,
        Crypto decCrypto) throws WSSecurityException {

    long t0 = 0, t1 = 0, t2 = 0;
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }
    /*
     * Gather some info about the document to process and store
     * it for retrieval. Store the implementation of signature crypto
     * (no need for encryption --- yet)
     */
    WSDocInfo wsDocInfo = new WSDocInfo(securityHeader.getOwnerDocument());
    wsDocInfo.setCrypto(sigCrypto);

    NodeList list = securityHeader.getChildNodes();
    int len = list.getLength();
    Node elem;
    if (tlog.isDebugEnabled()) {
        t1 = System.currentTimeMillis();
    }
    Vector returnResults = new Vector();

    for (int i = 0; i < len; i++) {
        elem = list.item(i);
        if (elem.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        QName el = new QName(elem.getNamespaceURI(), elem.getLocalName());
        final WSSConfig cfg = getWssConfig();
        Processor p = cfg.getProcessor(el);
        /*
         * Call the processor for this token. After the processor returns, 
         * store it for later retrieval. The token processor may store some
         * information about the processed token
         */
        if (p != null) {
            p.handleToken((Element) elem, sigCrypto, decCrypto, cb, wsDocInfo, returnResults, cfg);
            wsDocInfo.setProcessor(p);
        } else {
            /*
             * Add check for a BinarySecurityToken, add info to WSDocInfo. If BST is
             * found before a Signature token this would speed up (at least a little
             * bit) the processing of STR Transform.
             */
            if (doDebug) {
                log.debug("Unknown Element: " + elem.getLocalName() + " " + elem.getNamespaceURI());
            }
        }
    }
    if (tlog.isDebugEnabled()) {
        t2 = System.currentTimeMillis();
        tlog.debug("processHeader: total " + (t2 - t0) + ", prepare " + (t1 - t0) + ", handle " + (t2 - t1));
    }
    return returnResults;
}

From source file:org.apache.xml.security.Init.java

/**
 * Initialise the library from a configuration file
 *///from  w ww.  j  a  va 2s .c o m
private static void fileInit(InputStream is) {
    try {
        /* read library configuration file */
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

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

        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(is);
        Node config = doc.getFirstChild();
        for (; config != null; config = config.getNextSibling()) {
            if ("Configuration".equals(config.getLocalName())) {
                break;
            }
        }
        if (config == null) {
            log.error("Error in reading configuration file - Configuration element not found");
            return;
        }
        for (Node el = config.getFirstChild(); el != null; el = el.getNextSibling()) {
            if (el == null || Node.ELEMENT_NODE != el.getNodeType()) {
                continue;
            }
            String tag = el.getLocalName();
            if (tag.equals("ResourceBundles")) {
                Element resource = (Element) el;
                /* configure internationalization */
                Attr langAttr = resource.getAttributeNode("defaultLanguageCode");
                Attr countryAttr = resource.getAttributeNode("defaultCountryCode");
                String languageCode = (langAttr == null) ? null : langAttr.getNodeValue();
                String countryCode = (countryAttr == null) ? null : countryAttr.getNodeValue();
                I18n.init(languageCode, countryCode);
            }

            if (tag.equals("CanonicalizationMethods")) {
                Element[] list = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "CanonicalizationMethod");

                for (int i = 0; i < list.length; i++) {
                    String URI = list[i].getAttributeNS(null, "URI");
                    String JAVACLASS = list[i].getAttributeNS(null, "JAVACLASS");
                    try {
                        Canonicalizer.register(URI, JAVACLASS);
                        if (log.isDebugEnabled()) {
                            log.debug("Canonicalizer.register(" + URI + ", " + JAVACLASS + ")");
                        }
                    } catch (ClassNotFoundException e) {
                        Object exArgs[] = { URI, JAVACLASS };
                        log.error(I18n.translate("algorithm.classDoesNotExist", exArgs));
                    }
                }
            }

            if (tag.equals("TransformAlgorithms")) {
                Element[] tranElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "TransformAlgorithm");

                for (int i = 0; i < tranElem.length; i++) {
                    String URI = tranElem[i].getAttributeNS(null, "URI");
                    String JAVACLASS = tranElem[i].getAttributeNS(null, "JAVACLASS");
                    try {
                        Transform.register(URI, JAVACLASS);
                        if (log.isDebugEnabled()) {
                            log.debug("Transform.register(" + URI + ", " + JAVACLASS + ")");
                        }
                    } catch (ClassNotFoundException e) {
                        Object exArgs[] = { URI, JAVACLASS };

                        log.error(I18n.translate("algorithm.classDoesNotExist", exArgs));
                    } catch (NoClassDefFoundError ex) {
                        log.warn("Not able to found dependencies for algorithm, I'll keep working.");
                    }
                }
            }

            if ("JCEAlgorithmMappings".equals(tag)) {
                Node algorithmsNode = ((Element) el).getElementsByTagName("Algorithms").item(0);
                if (algorithmsNode != null) {
                    Element[] algorithms = XMLUtils.selectNodes(algorithmsNode.getFirstChild(), CONF_NS,
                            "Algorithm");
                    for (int i = 0; i < algorithms.length; i++) {
                        Element element = algorithms[i];
                        String id = element.getAttribute("URI");
                        JCEMapper.register(id, new JCEMapper.Algorithm(element));
                    }
                }
            }

            if (tag.equals("SignatureAlgorithms")) {
                Element[] sigElems = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "SignatureAlgorithm");

                for (int i = 0; i < sigElems.length; i++) {
                    String URI = sigElems[i].getAttributeNS(null, "URI");
                    String JAVACLASS = sigElems[i].getAttributeNS(null, "JAVACLASS");

                    /** $todo$ handle registering */

                    try {
                        SignatureAlgorithm.register(URI, JAVACLASS);
                        if (log.isDebugEnabled()) {
                            log.debug("SignatureAlgorithm.register(" + URI + ", " + JAVACLASS + ")");
                        }
                    } catch (ClassNotFoundException e) {
                        Object exArgs[] = { URI, JAVACLASS };

                        log.error(I18n.translate("algorithm.classDoesNotExist", exArgs));
                    }
                }
            }

            if (tag.equals("ResourceResolvers")) {
                Element[] resolverElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver");

                for (int i = 0; i < resolverElem.length; i++) {
                    String JAVACLASS = resolverElem[i].getAttributeNS(null, "JAVACLASS");
                    String Description = resolverElem[i].getAttributeNS(null, "DESCRIPTION");

                    if ((Description != null) && (Description.length() > 0)) {
                        if (log.isDebugEnabled()) {
                            log.debug("Register Resolver: " + JAVACLASS + ": " + Description);
                        }
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Register Resolver: " + JAVACLASS + ": For unknown purposes");
                        }
                    }
                    try {
                        ResourceResolver.register(JAVACLASS);
                    } catch (Throwable e) {
                        log.warn("Cannot register:" + JAVACLASS + " perhaps some needed jars are not installed",
                                e);
                    }
                }
            }

            if (tag.equals("KeyResolver")) {
                Element[] resolverElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver");
                List<String> classNames = new ArrayList<String>(resolverElem.length);
                for (int i = 0; i < resolverElem.length; i++) {
                    String JAVACLASS = resolverElem[i].getAttributeNS(null, "JAVACLASS");
                    String Description = resolverElem[i].getAttributeNS(null, "DESCRIPTION");

                    if ((Description != null) && (Description.length() > 0)) {
                        if (log.isDebugEnabled()) {
                            log.debug("Register Resolver: " + JAVACLASS + ": " + Description);
                        }
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Register Resolver: " + JAVACLASS + ": For unknown purposes");
                        }
                    }
                    classNames.add(JAVACLASS);
                }
                KeyResolver.registerClassNames(classNames);
            }

            if (tag.equals("PrefixMappings")) {
                if (log.isDebugEnabled()) {
                    log.debug("Now I try to bind prefixes:");
                }

                Element[] nl = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "PrefixMapping");

                for (int i = 0; i < nl.length; i++) {
                    String namespace = nl[i].getAttributeNS(null, "namespace");
                    String prefix = nl[i].getAttributeNS(null, "prefix");
                    if (log.isDebugEnabled()) {
                        log.debug("Now I try to bind " + prefix + " to " + namespace);
                    }
                    ElementProxy.setDefaultPrefix(namespace, prefix);
                }
            }
        }
    } catch (Exception e) {
        log.error("Bad: ", e);
        e.printStackTrace();
    }
}

From source file:org.apache.xml.security.utils.ElementProxy.java

/**
 * Method length/*w w  w . j  ava  2  s .c o  m*/
 *
 * @param namespace
 * @param localname
 * @return the number of elements {namespace}:localname under this element
 */
public int length(String namespace, String localname) {
    int number = 0;
    Node sibling = this.constructionElement.getFirstChild();
    while (sibling != null) {
        if (localname.equals(sibling.getLocalName()) && namespace.equals(sibling.getNamespaceURI())) {
            number++;
        }
        sibling = sibling.getNextSibling();
    }
    return number;
}

From source file:org.apache.xml.security.utils.XMLUtils.java

/**
 * @param sibling// w  ww  . j av a  2  s. co  m
 * @param nodeName
 * @param number
 * @return nodes with the constraint
 */
public static Element selectDsNode(Node sibling, String nodeName, int number) {
    while (sibling != null) {
        if (Constants.SignatureSpecNS.equals(sibling.getNamespaceURI())
                && sibling.getLocalName().equals(nodeName)) {
            if (number == 0) {
                return (Element) sibling;
            }
            number--;
        }
        sibling = sibling.getNextSibling();
    }
    return null;
}

From source file:org.apache.xml.security.utils.XMLUtils.java

/**
 * @param sibling// w w w  .j av  a2  s.  co m
 * @param nodeName
 * @param number
 * @return nodes with the constrain
 */
public static Element selectXencNode(Node sibling, String nodeName, int number) {
    while (sibling != null) {
        if (EncryptionConstants.EncryptionSpecNS.equals(sibling.getNamespaceURI())
                && sibling.getLocalName().equals(nodeName)) {
            if (number == 0) {
                return (Element) sibling;
            }
            number--;
        }
        sibling = sibling.getNextSibling();
    }
    return null;
}

From source file:org.asimba.wa.integrationtest.saml2.model.Assertion.java

private void parseAttributes() {
    String xpathQuery = "/saml2p:Response/saml2:Assertion/saml2:AttributeStatement/saml2:Attribute";

    if (_responseDocument == null) {
        _logger.error("No document specified.");
        return;/*w  w w.  ja va2s .c  o  m*/
    }

    Map<String, String> attributeMap = new HashMap<>();

    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new SimpleSAMLNamespaceContext(null));

    try {
        NodeList nodes = (NodeList) xpath.compile(xpathQuery).evaluate(_responseDocument,
                XPathConstants.NODESET);
        if (nodes != null) {
            for (int i = 0; i < nodes.getLength(); i++) {
                // get value of @Name attribute
                Node n = nodes.item(i);

                String name = n.getAttributes().getNamedItem("Name").getNodeValue();

                // get the first AttributeValue childnode
                NodeList valueNodes = n.getChildNodes();
                for (int ci = 0; ci < valueNodes.getLength(); ci++) {
                    Node cn = valueNodes.item(ci);
                    String nodename = cn.getLocalName();
                    if ("AttributeValue".equals(nodename)) {
                        String value = cn.getTextContent().trim();
                        attributeMap.put(name, value);
                    }
                }
            }
        }
    } catch (XPathExpressionException e) {
        _logger.error("Exception when getting attributes: {}", e.getMessage(), e);
        return;
    }

    _responseAttributes = attributeMap;
}

From source file:org.asimba.wa.integrationtest.util.SignatureHelper.java

/** 
 * ensures that the ID can be found as ID-attribute
 * @param xmlDoc Document to tag ID-elements of 
 *//*from w  w  w  .j a v a 2 s  . c o  m*/
public void tagIdAttributes(Document xmlDoc) {
    NodeList nodeList = xmlDoc.getElementsByTagName("*");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getAttributes().getNamedItem("ID") != null) {
                _logger.info("Tagging {} with ID attribute.", node.getLocalName());
                ((Element) node).setIdAttribute("ID", true);
            }
        }
    }
}

From source file:org.chiba.xml.xforms.ui.Switch.java

/**
 * Initializes the Case elements.//from  w ww.  ja va  2s  . c  om
 * <p/>
 * If multiple Cases within a Switch are selected, the first selected Case
 * remains and all others are deselected. If none are selected, the first
 * becomes selected.
 */
protected final void initializeSwitch() throws XFormsException {
    NodeList childNodes = getElement().getChildNodes();
    List cases = new ArrayList(childNodes.getLength());

    Node node;
    Case caseElement;
    String selectedAttribute;
    int selection = -1;

    for (int index = 0; index < childNodes.getLength(); index++) {
        node = childNodes.item(index);

        if (node.getNodeType() == Node.ELEMENT_NODE
                && NamespaceConstants.XFORMS_NS.equals(node.getNamespaceURI())
                && CASE.equals(node.getLocalName())) {
            caseElement = (Case) ((NodeImpl) node).getUserData();
            cases.add(caseElement);

            selectedAttribute = caseElement.getXFormsAttribute(SELECTED_ATTRIBUTE);
            if ((selection == -1) && ("true").equals(selectedAttribute)) {
                // keep *first* selected case position
                selection = cases.size() - 1;
            }
        }
    }

    if (selection == -1) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug(this + " init: choosing first case for selection by default");
        }

        // select first case if none is selected
        selection = 0;
    }

    // perform selection/deselection
    for (int index = 0; index < cases.size(); index++) {
        caseElement = (Case) cases.get(index);

        if (index == selection) {
            if (getLogger().isDebugEnabled()) {
                getLogger().debug(this + " init: selecting case '" + caseElement.getId() + "'");
            }
            caseElement.select();
        } else {
            if (getLogger().isDebugEnabled()) {
                getLogger().debug(this + " init: deselecting case '" + caseElement.getId() + "'");
            }
            caseElement.deselect();
        }
    }

    // set state for updateSwitch()
    this.initAfterReady = this.model.isReady();
}