Example usage for org.w3c.dom Attr getNodeValue

List of usage examples for org.w3c.dom Attr getNodeValue

Introduction

In this page you can find the example usage for org.w3c.dom Attr getNodeValue.

Prototype

public String getNodeValue() throws DOMException;

Source Link

Document

The value of this node, depending on its type; see the table above.

Usage

From source file:org.apache.shindig.gadgets.templates.XmlTemplateLibrary.java

private void processTemplate(Builder<TagHandler> handlers, Element templateElement)
        throws TemplateParserException {
    Attr tagAttribute = templateElement.getAttributeNode(TAG_ATTRIBUTE);
    if (tagAttribute == null) {
        throw new TemplateParserException("Missing tag attribute on Template");
    }//  ww w. j ava2 s.c o m

    TagHandler handler = createHandler(tagAttribute.getNodeValue(), templateElement,
            ImmutableSet.<TemplateResource>of());
    if (handler != null) {
        handlers.add(handler);
    }
}

From source file:org.apache.sling.its.servlets.ItsImportServlet.java

/**
 * Creates the jcr node and appends the necessary properties.
 *
 * @param absPath//from   w  w  w.ja v  a  2s  . c  o m
 *         absolute path of the node.
 * @param attr
 *         attribute of the element
 * @param textContent
 *        text content of the element.
 */
private void output(final String absPath, final Attr attr, final String textContent) {
    javax.jcr.Node node = null;
    try {
        if (this.session.itemExists(absPath) && attr == null && textContent == null) {
            node = (javax.jcr.Node) this.session.getItem(absPath);
            node.remove();
        }
        node = JcrResourceUtil.createPath(absPath, "nt:unstructured", "nt:unstructured", this.session, false);

        if (textContent != null) {
            node.setProperty(SlingItsConstants.TEXT_CONTENT, textContent);
        }

        if (attr != null) {
            if (attr.getNodeName().startsWith(XMLConstants.XMLNS_ATTRIBUTE)) {
                node.setProperty(attr.getLocalName(), attr.getNodeValue());
                if (node.hasProperty(SlingItsConstants.NAMESPACE_DECLARATION)) {
                    final ArrayList<String> prefixes = new ArrayList<String>(ValueUtils.convertToArrayList(
                            node.getProperty(SlingItsConstants.NAMESPACE_DECLARATION).getValues()));
                    if (!prefixes.contains(attr.getLocalName())) {
                        prefixes.add(attr.getLocalName());
                        node.setProperty(SlingItsConstants.NAMESPACE_DECLARATION,
                                prefixes.toArray(new String[prefixes.size()]));
                    }
                } else {
                    node.setProperty(SlingItsConstants.NAMESPACE_DECLARATION,
                            new String[] { attr.getLocalName() });
                }
            } else if (StringUtils.equals(attr.getNodeName(), SlingItsConstants.XML_PRIMARY_TYPE_PROP)
                    || StringUtils.equals(attr.getNodeName(), SlingItsConstants.HTML_PRIMARY_TYPE_PROP)) {
                node.setPrimaryType(attr.getNodeValue());
            } else if (StringUtils.equals(attr.getNodeName(), SlingItsConstants.HTML_RESOURCE_TYPE_PROP)) {
                node.setProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, attr.getNodeValue());
            } else {
                node.setProperty(attr.getNodeName(), attr.getNodeValue());
            }
        }
        this.session.save();
    } catch (final RepositoryException e) {
        LOG.error("Unable to access repository to access or create node. Stack Trace: ", e);
    }
}

From source file:org.apache.ws.security.message.EnvelopeIdResolver.java

/**
 * This is the workhorse method used to resolve resources.
 * <p/>//from w ww.j a  v  a2 s  .co  m
 *
 * @param 
 * @param BaseURI
 * @return TODO
 * @throws ResourceResolverException
 */
public XMLSignatureInput engineResolve(Attr uri, String BaseURI) throws ResourceResolverException {

    doDebug = log.isDebugEnabled();

    String uriNodeValue = uri.getNodeValue();

    if (doDebug) {
        log.debug("enter engineResolve, look for: " + uriNodeValue);
    }

    Document doc = uri.getOwnerDocument();

    /*
     * URI="#chapter1"
     * Identifies a node-set containing the element with ID attribute
     * value 'chapter1' of the XML resource containing the signature.
     * XML Signature (and its applications) modify this node-set to
     * include the element plus all descendants including namespaces and
     * attributes -- but not comments.
     */

    /*
     * First check to see if the element that we require is a SecurityTokenReference
     * that is stored in WSDocInfo.
     */
    String id = uriNodeValue.substring(1);
    Element selectedElem = null;
    if (wsDocInfo != null) {
        selectedElem = wsDocInfo.getSecurityTokenReference(id);
    }

    /*
     * Then lookup the SOAP Body element (processed by default) and
     * check if it contains a matching Id
     */
    if (selectedElem == null) {
        SOAPConstants sc = WSSecurityUtil.getSOAPConstants(doc.getDocumentElement());
        selectedElem = WSSecurityUtil.findBodyElement(doc, sc);
        if (selectedElem == null) {
            throw new ResourceResolverException("generic.EmptyMessage",
                    new Object[] { "Body element not found" }, uri, BaseURI);
        }
        String cId = selectedElem.getAttributeNS(WSConstants.WSU_NS, "Id");

        /*
         * If Body Id match fails, look for a generic Id (without a namespace)
         * that matches the URI. If that lookup fails, try to get a namespace
         * qualified Id that matches the URI.
         */
        if (!id.equals(cId)) {
            cId = null;

            if ((selectedElem = WSSecurityUtil.getElementByWsuId(doc, uriNodeValue)) != null) {
                cId = selectedElem.getAttributeNS(WSConstants.WSU_NS, "Id");
            } else if ((selectedElem = WSSecurityUtil.getElementByGenId(doc, uriNodeValue)) != null) {
                cId = selectedElem.getAttribute("Id");
            }
            if (cId == null) {
                throw new ResourceResolverException("generic.EmptyMessage", new Object[] { "Id not found" },
                        uri, BaseURI);
            }
        }
    }

    XMLSignatureInput result = new XMLSignatureInput(selectedElem);
    result.setMIMEType("text/xml");
    try {
        URI uriNew = new URI(new URI(BaseURI), uri.getNodeValue());
        result.setSourceURI(uriNew.toString());
    } catch (URI.MalformedURIException ex) {
        result.setSourceURI(BaseURI);
    }
    if (doDebug) {
        log.debug("exit engineResolve, result: " + result);
    }
    return result;
}

From source file:org.apache.ws.security.message.EnvelopeIdResolver.java

/**
 * This method helps the ResourceResolver to decide whether a
 * ResourceResolverSpi is able to perform the requested action.
 * <p/>//w  w w.  j a  v  a  2 s. c  om
 *
 * @param uri
 * @param BaseURI
 * @return TODO
 */
public boolean engineCanResolve(Attr uri, String BaseURI) {
    if (uri == null) {
        return false;
    }
    String uriNodeValue = uri.getNodeValue();
    return uriNodeValue.startsWith("#");
}

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

public static String getPrefixNS(String uri, Node e) {
    while (e != null && (e.getNodeType() == Element.ELEMENT_NODE)) {
        NamedNodeMap attrs = e.getAttributes();
        for (int n = 0; n < attrs.getLength(); n++) {
            Attr a = (Attr) attrs.item(n);
            String name = a.getName();
            if (name.startsWith("xmlns:") && a.getNodeValue().equals(uri)) {
                return name.substring(6);
            }/*from   w  w w . jav a  2s.c  o  m*/
        }
        e = e.getParentNode();
    }
    return null;
}

From source file:org.apache.xml.security.c14n.implementations.Canonicalizer11.java

/**
 * Returns the Attr[]s to be output for the given element.
 * <br>//from w w w  .  j  a v  a 2  s.  c o m
 * The code of this method is a copy of {@link #handleAttributes(Element,
 * NameSpaceSymbTable)},
 * whereas it takes into account that subtree-c14n is -- well -- 
 * subtree-based.
 * So if the element in question isRoot of c14n, it's parent is not in the
 * node set, as well as all other ancestors.
 *
 * @param element
 * @param ns
 * @return the Attr[]s to be output
 * @throws CanonicalizationException
 */
@Override
protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
        throws CanonicalizationException {
    if (!element.hasAttributes() && !firstCall) {
        return null;
    }
    // result will contain the attrs which have to be output
    final SortedSet<Attr> result = this.result;
    result.clear();

    if (element.hasAttributes()) {
        NamedNodeMap attrs = element.getAttributes();
        int attrsLength = attrs.getLength();

        for (int i = 0; i < attrsLength; i++) {
            Attr attribute = (Attr) attrs.item(i);
            String NUri = attribute.getNamespaceURI();
            String NName = attribute.getLocalName();
            String NValue = attribute.getValue();

            if (!XMLNS_URI.equals(NUri)) {
                // It's not a namespace attr node. Add to the result and continue.
                result.add(attribute);
            } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) {
                // The default mapping for xml must not be output.
                Node n = ns.addMappingAndRender(NName, NValue, attribute);

                if (n != null) {
                    // Render the ns definition
                    result.add((Attr) n);
                    if (C14nHelper.namespaceIsRelative(attribute)) {
                        Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
                        throw new CanonicalizationException("c14n.Canonicalizer.RelativeNamespace", exArgs);
                    }
                }
            }
        }
    }

    if (firstCall) {
        // It is the first node of the subtree
        // Obtain all the namespaces defined in the parents, and added to the output.
        ns.getUnrenderedNodes(result);
        // output the attributes in the xml namespace.
        xmlattrStack.getXmlnsAttr(result);
        firstCall = false;
    }

    return result.iterator();
}

From source file:org.apache.xml.security.c14n.implementations.Canonicalizer11.java

/**
 * Returns the Attr[]s to be output for the given element.
 * <br>/*w ww.  j  a va  2s.  c  o m*/
 * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a 
 * DOM which has been prepared using 
 * {@link org.apache.xml.security.utils.XMLUtils#circumventBug2650(
 * org.w3c.dom.Document)}.
 * 
 * @param element
 * @param ns
 * @return the Attr[]s to be output
 * @throws CanonicalizationException
 */
@Override
protected Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
        throws CanonicalizationException {
    // result will contain the attrs which have to be output
    xmlattrStack.push(ns.getLevel());
    boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1;
    final SortedSet<Attr> result = this.result;
    result.clear();

    if (element.hasAttributes()) {
        NamedNodeMap attrs = element.getAttributes();
        int attrsLength = attrs.getLength();

        for (int i = 0; i < attrsLength; i++) {
            Attr attribute = (Attr) attrs.item(i);
            String NUri = attribute.getNamespaceURI();
            String NName = attribute.getLocalName();
            String NValue = attribute.getValue();

            if (!XMLNS_URI.equals(NUri)) {
                //A non namespace definition node.
                if (XML_LANG_URI.equals(NUri)) {
                    if (NName.equals("id")) {
                        if (isRealVisible) {
                            // treat xml:id like any other attribute 
                            // (emit it, but don't inherit it)
                            result.add(attribute);
                        }
                    } else {
                        xmlattrStack.addXmlnsAttr(attribute);
                    }
                } else if (isRealVisible) {
                    //The node is visible add the attribute to the list of output attributes.
                    result.add(attribute);
                }
            } else if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) {
                /* except omit namespace node with local name xml, which defines
                 * the xml prefix, if its string value is 
                 * http://www.w3.org/XML/1998/namespace.
                 */
                // add the prefix binding to the ns symb table.
                if (isVisible(attribute)) {
                    if (isRealVisible || !ns.removeMappingIfRender(NName)) {
                        // The xpath select this node output it if needed.
                        Node n = ns.addMappingAndRender(NName, NValue, attribute);
                        if (n != null) {
                            result.add((Attr) n);
                            if (C14nHelper.namespaceIsRelative(attribute)) {
                                Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
                                throw new CanonicalizationException("c14n.Canonicalizer.RelativeNamespace",
                                        exArgs);
                            }
                        }
                    }
                } else {
                    if (isRealVisible && !XMLNS.equals(NName)) {
                        ns.removeMapping(NName);
                    } else {
                        ns.addMapping(NName, NValue, attribute);
                    }
                }
            }
        }
    }

    if (isRealVisible) {
        //The element is visible, handle the xmlns definition        
        Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS);
        Node n = null;
        if (xmlns == null) {
            //No xmlns def just get the already defined.
            n = ns.getMapping(XMLNS);
        } else if (!isVisible(xmlns)) {
            //There is a definition but the xmlns is not selected by the xpath.
            //then xmlns=""
            n = ns.addMappingAndRender(XMLNS, "", nullNode);
        }
        //output the xmlns def if needed.
        if (n != null) {
            result.add((Attr) n);
        }
        //Float all xml:* attributes of the unselected parent elements to this one. 
        xmlattrStack.getXmlnsAttr(result);
        ns.getUnrenderedNodes(result);
    }

    return result.iterator();
}

From source file:org.apache.xml.security.c14n.implementations.Canonicalizer11.java

protected void handleParent(Element e, NameSpaceSymbTable ns) {
    if (!e.hasAttributes() && e.getNamespaceURI() == null) {
        return;// w w  w  .  j  av  a 2s .c  o m
    }
    xmlattrStack.push(-1);
    NamedNodeMap attrs = e.getAttributes();
    int attrsLength = attrs.getLength();
    for (int i = 0; i < attrsLength; i++) {
        Attr attribute = (Attr) attrs.item(i);
        String NName = attribute.getLocalName();
        String NValue = attribute.getNodeValue();

        if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) {
            if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
                ns.addMapping(NName, NValue, attribute);
            }
        } else if (!"id".equals(NName) && XML_LANG_URI.equals(attribute.getNamespaceURI())) {
            xmlattrStack.addXmlnsAttr(attribute);
        }
    }
    if (e.getNamespaceURI() != null) {
        String NName = e.getPrefix();
        String NValue = e.getNamespaceURI();
        String Name;
        if (NName == null || NName.equals("")) {
            NName = "xmlns";
            Name = "xmlns";
        } else {
            Name = "xmlns:" + NName;
        }
        Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name);
        n.setValue(NValue);
        ns.addMapping(NName, NValue, n);
    }
}

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

/**
 * Initialise the library from a configuration file
 *//*from w w w.  jav a 2  s .  c  om*/
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.samples.utils.resolver.OfflineResolver.java

/**
 * Method engineResolve//ww  w.ja v  a 2s.  c  o  m
 *
 * @param uri
 * @param BaseURI
 *
 * @throws ResourceResolverException
 */
public XMLSignatureInput engineResolve(Attr uri, String BaseURI) throws ResourceResolverException {

    try {
        String URI = uri.getNodeValue();

        if (OfflineResolver._uriMap.containsKey(URI)) {
            String newURI = (String) OfflineResolver._uriMap.get(URI);

            log.debug("Mapped " + URI + " to " + newURI);

            InputStream is = new FileInputStream(newURI);

            log.debug("Available bytes = " + is.available());

            XMLSignatureInput result = new XMLSignatureInput(is);

            // XMLSignatureInput result = new XMLSignatureInput(inputStream);
            result.setSourceURI(URI);
            result.setMIMEType((String) OfflineResolver._mimeMap.get(URI));

            return result;
        } else {
            Object exArgs[] = { "The URI " + URI + " is not configured for offline work" };

            throw new ResourceResolverException("generic.EmptyMessage", exArgs, uri, BaseURI);
        }
    } catch (IOException ex) {
        throw new ResourceResolverException("generic.EmptyMessage", ex, uri, BaseURI);
    }
}