Example usage for org.w3c.dom Element getAttributes

List of usage examples for org.w3c.dom Element getAttributes

Introduction

In this page you can find the example usage for org.w3c.dom Element getAttributes.

Prototype

public NamedNodeMap getAttributes();

Source Link

Document

A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

Usage

From source file:org.apache.camel.component.xmlsecurity.api.XAdESSignatureProperties.java

protected void replacePrefix(Element el, Input input) {
    replacePrefixForNode(el, input);/*w  w  w.j a  v a 2  s  .  c  o m*/
    NamedNodeMap nnm = el.getAttributes();
    List<Attr> xmlnsToBeRemoved = new ArrayList<Attr>(2);
    int length = nnm.getLength();
    for (int i = 0; i < length; i++) {
        Node attr = nnm.item(i);
        replacePrefixForNode(attr, input);
        if (attr.getNodeType() == Node.ATTRIBUTE_NODE) {
            if ("xmlns".equals(attr.getLocalName()) || "xmlns".equals(attr.getPrefix())) {
                if (XMLSignature.XMLNS.equals(attr.getTextContent())
                        || findNamespace(input.getMessage()).equals(attr.getTextContent())) {
                    xmlnsToBeRemoved.add((Attr) attr);
                }
            }
        }
    }
    // remove xml namespace declaration for XML signature and XAdES namespace
    for (Attr toBeRemoved : xmlnsToBeRemoved) {
        el.removeAttributeNode(toBeRemoved);
    }

}

From source file:org.apache.click.extras.control.MenuFactory.java

/**
 * Build a new Menu from the given menu item XML Element and recurse through
 * all the menu-items children. If the menuClass is specified, menus will
 * be created of that type, otherwise an instance of {@link Menu} will be
 * created.//  w  ww . j a  va 2 s. co  m
 *
 * @param menuElement the menu item XML Element
 * @param accessController the menu access controller
 * @param menuClass the menu class to instantiate
 * @return new Menu instance for the given XML menuElement
 */
protected Menu buildMenu(Element menuElement, AccessController accessController,
        Class<? extends Menu> menuClass) {

    Validate.notNull(menuElement, "Null menuElement parameter");
    Validate.notNull(accessController, "Null accessController parameter");

    Menu menu = null;
    if (menuClass == null) {
        menu = new Menu();
    } else {
        menu = createMenu(menuClass);
    }

    menu.setAccessController(accessController);

    String nameAtr = menuElement.getAttribute("name");
    if (StringUtils.isNotBlank(nameAtr)) {
        menu.setName(nameAtr);
    }

    String labelAtr = menuElement.getAttribute("label");
    if (StringUtils.isNotBlank(labelAtr)) {
        menu.setLabel(labelAtr);
    }

    String imageSrcAtr = menuElement.getAttribute("imageSrc");
    if (StringUtils.isNotBlank(imageSrcAtr)) {
        menu.setImageSrc(imageSrcAtr);
    }

    String pathAtr = menuElement.getAttribute("path");
    if (StringUtils.isNotBlank(pathAtr)) {
        menu.setPath(pathAtr);
    }

    String titleAtr = menuElement.getAttribute("title");
    if (StringUtils.isNotBlank(titleAtr)) {
        menu.setTitle(titleAtr);
    }

    String targetAtr = menuElement.getAttribute("target");
    if (StringUtils.isNotBlank(targetAtr)) {
        menu.setTarget(targetAtr);
    }

    String externalAtr = menuElement.getAttribute("external");
    if ("true".equalsIgnoreCase(externalAtr)) {
        menu.setExternal(true);
    }

    String separatorAtr = menuElement.getAttribute("separator");
    if ("true".equalsIgnoreCase(separatorAtr)) {
        menu.setSeparator(true);
    }

    /*
    String visibilityAtr = menuElement.getAttribute("visible");
    if ("false".equalsIgnoreCase(visibilityAtr)) {
    menu.setVisible(false);
    }
            
    String enablingAtr = menuElement.getAttribute("enabled");
    if ("false".equalsIgnoreCase(enablingAtr)) {
    menu.setEnabled(false);
    }*/

    String pagesValue = menuElement.getAttribute("pages");
    if (StringUtils.isNotBlank(pagesValue)) {
        StringTokenizer tokenizer = new StringTokenizer(pagesValue, ",");
        while (tokenizer.hasMoreTokens()) {
            String path = tokenizer.nextToken().trim();
            path = (path.startsWith("/")) ? path : "/" + path;
            menu.getPages().add(path);
        }
    }

    String rolesValue = menuElement.getAttribute("roles");
    if (StringUtils.isNotBlank(rolesValue)) {
        StringTokenizer tokenizer = new StringTokenizer(rolesValue, ",");
        while (tokenizer.hasMoreTokens()) {
            menu.getRoles().add(tokenizer.nextToken().trim());
        }
    }

    // Load other attributes
    NamedNodeMap attributeNodeMap = menuElement.getAttributes();
    for (int i = 0; i < attributeNodeMap.getLength(); i++) {
        Node attribute = attributeNodeMap.item(i);
        String name = attribute.getNodeName();
        if (!DEFAULT_ATTRIBUTES.contains(name)) {
            String value = attribute.getNodeValue();
            menu.getAttributes().put(name, value);
        }
    }

    NodeList childElements = menuElement.getChildNodes();
    for (int i = 0, size = childElements.getLength(); i < size; i++) {
        Node node = childElements.item(i);
        if (node instanceof Element) {
            Menu childMenu = buildMenu((Element) node, accessController, menuClass);
            menu.add(childMenu);
        }
    }
    return menu;
}

From source file:org.apache.cocoon.forms.util.DomHelper.java

private static Map addLocalNSDeclarations(Element elm, Map nsDeclarations) {
    NamedNodeMap atts = elm.getAttributes();
    int attsSize = atts.getLength();

    for (int i = 0; i < attsSize; i++) {
        Attr attr = (Attr) atts.item(i);
        if (XMLNS_URI.equals(attr.getNamespaceURI())) {
            String nsUri = attr.getValue();
            String pfx = attr.getLocalName();
            if (nsDeclarations == null)
                nsDeclarations = new HashMap();
            nsDeclarations.put(nsUri, pfx);
        }//from   ww  w .  j  a  va2  s  .  com
    }
    return nsDeclarations;
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Compare all attributes of two elements.
 * This method returns true only if both nodes have the same number of
 * attributes and the same attributes with equal values.
 * Namespace definition nodes are ignored
 *///from  w w w.  jav a 2  s.c  om
public static boolean compareAttributes(Element first, Element second) {
    NamedNodeMap attr1 = first.getAttributes();
    NamedNodeMap attr2 = second.getAttributes();
    String value;

    if (attr1 == null && attr2 == null)
        return true;
    int attr1Len = (attr1 == null ? 0 : attr1.getLength());
    int attr2Len = (attr2 == null ? 0 : attr2.getLength());
    if (attr1Len > 0) {
        int l = attr1.getLength();
        for (int i = 0; i < l; i++) {
            if (attr1.item(i).getNodeName().startsWith("xmlns:") == true)
                attr1Len--;
        }
    }
    if (attr2Len > 0) {
        int l = attr2.getLength();
        for (int i = 0; i < l; i++) {
            if (attr2.item(i).getNodeName().startsWith("xmlns:") == true)
                attr2Len--;
        }
    }
    if (attr1Len != attr2Len)
        return false;
    int i, l;
    int m, l2;
    i = 0;
    l = attr1.getLength();
    l2 = attr2.getLength();
    boolean ok = true;
    // each attribute of first must be in second with the same value
    while (i < l && ok == true) {
        value = attr1.item(i).getNodeName();
        if (value.startsWith("xmlns:") == false) {
            ok = false;
            m = 0;
            while (m < l2 && ok == false) {
                if (attr2.item(m).getNodeName().equals(value) == true) {
                    // same name, same value?
                    ok = attr1.item(i).getNodeValue().equals(attr2.item(m).getNodeValue());
                }
                m++;
            }
        }

        i++;
    }
    return ok;
}

From source file:org.apache.geode.management.internal.configuration.utils.XmlUtils.java

static String findPrefix(final Element root, final String namespaceUri) {
    // Look for all of the attributes of cache that start with xmlns
    NamedNodeMap attributes = root.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node item = attributes.item(i);
        if (item.getNodeName().startsWith("xmlns")) {
            if (item.getNodeValue().equals(namespaceUri)) {
                String[] splitName = item.getNodeName().split(":");
                if (splitName.length > 1) {
                    return splitName[1];
                } else {
                    return "";
                }/*from   ww  w .j  a v  a  2 s  .c  o  m*/
            }
        }
    }
    return null;
}

From source file:org.apache.hadoop.mapred.QueueConfigurationParser.java

private Queue parseResource(Element queuesNode) {
    Queue rootNode = null;/*from w  w w  .j  av  a  2  s . c  om*/
    try {
        if (!QUEUES_TAG.equals(queuesNode.getTagName())) {
            LOG.info("Bad conf file: top-level element not <queues>");
            throw new RuntimeException("No queues defined ");
        }
        NamedNodeMap nmp = queuesNode.getAttributes();
        Node acls = nmp.getNamedItem(ACLS_ENABLED_TAG);

        if (acls != null) {
            LOG.warn("Configuring " + ACLS_ENABLED_TAG + " flag in " + QueueManager.QUEUE_CONF_FILE_NAME
                    + " is not valid. " + "This tag is ignored. Configure " + MRConfig.MR_ACLS_ENABLED
                    + " in mapred-site.xml. See the " + " documentation of " + MRConfig.MR_ACLS_ENABLED
                    + ", which is used for enabling job level authorization and "
                    + " queue level authorization.");
        }

        NodeList props = queuesNode.getChildNodes();
        if (props == null || props.getLength() <= 0) {
            LOG.info(" Bad configuration no queues defined ");
            throw new RuntimeException(" No queues defined ");
        }

        //We have root level nodes.
        for (int i = 0; i < props.getLength(); i++) {
            Node propNode = props.item(i);
            if (!(propNode instanceof Element)) {
                continue;
            }

            if (!propNode.getNodeName().equals(QUEUE_TAG)) {
                LOG.info("At root level only \" queue \" tags are allowed ");
                throw new RuntimeException("Malformed xml document no queue defined ");
            }

            Element prop = (Element) propNode;
            //Add children to root.
            Queue q = createHierarchy("", prop);
            if (rootNode == null) {
                rootNode = new Queue();
                rootNode.setName("");
            }
            rootNode.addChild(q);
        }
        return rootNode;
    } catch (DOMException e) {
        LOG.info("Error parsing conf file: " + e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.QueuePlacementRule.java

public void initializeFromXml(Element el) throws AllocationConfigurationException {
    boolean create = true;
    NamedNodeMap attributes = el.getAttributes();
    Map<String, String> args = new HashMap<String, String>();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node node = attributes.item(i);
        String key = node.getNodeName();
        String value = node.getNodeValue();
        if (key.equals("create")) {
            create = Boolean.parseBoolean(value);
        } else {/*w ww  . j av  a  2s . c om*/
            args.put(key, value);
        }
    }
    initialize(create, args);
}

From source file:org.apache.nutch.searcher.response.xml.XMLResponseWriter.java

/**
 * Adds an attribute name and value to a node Element in the XML document.
 * //from   w  w w.j av  a  2s  .c om
 * @param doc The XML document.
 * @param node The node Element on which to attach the attribute.
 * @param name The name of the attribute.
 * @param value The value of the attribute.
 */
private static void addAttribute(Document doc, Element node, String name, String value) {
    Attr attribute = doc.createAttribute(name);
    attribute.setValue(getLegalXml(value));
    node.getAttributes().setNamedItem(attribute);
}

From source file:org.apache.ode.axis2.httpbinding.HttpHelper.java

public static void configure(HttpClient client, URI targetURI, Element authPart, HttpParams params)
        throws URIException {
    if (log.isDebugEnabled())
        log.debug("Configuring http client...");

    /* Do not forget to wire params so that endpoint properties are passed around
       Down the road, when the request will be executed, the hierarchy of parameters will be the following:
     (-> means "is parent of")//from  w  w  w.  j a v a 2  s .com
     default params -> params from endpoint properties -> HttpClient -> HostConfig -> Method
       This wiring is done by HttpClient.
    */
    client.getParams().setDefaults(params);

    // Here we make sure HttpClient will not handle the default headers.
    // Actually HttpClient *appends* default headers while we want them to be ignored if the process assign them
    client.getParams().setParameter(HostParams.DEFAULT_HEADERS, Collections.EMPTY_LIST);

    // proxy configuration
    if (ProxyConf.isProxyEnabled(params, targetURI.getHost())) {
        if (log.isDebugEnabled())
            log.debug("ProxyConf");
        ProxyConf.configure(client.getHostConfiguration(), client.getState(),
                (HttpTransportProperties.ProxyProperties) params
                        .getParameter(Properties.PROP_HTTP_PROXY_PREFIX));
    }

    // security
    // ...

    // authentication
    /*
    We're expecting the following element:
    <xs:complexType name="credentialType">
    <xs:attribute name="scheme" type="xs:string" default="server-decide" />
    <xs:attribute name="username" type="xs:string" />
    <xs:attribute name="password" type="xs:string" />
    </xs:complexType>
    <xs:element type="rest_connector:credentialType" name="credentials" />
     */
    if (authPart != null) {
        // the part must be defined with an element, so take the fist child
        Element credentialsElement = DOMUtils.getFirstChildElement(authPart);
        if (credentialsElement != null && credentialsElement.getAttributes().getLength() != 0) {
            String scheme = DOMUtils.getAttribute(credentialsElement, "scheme");
            String username = DOMUtils.getAttribute(credentialsElement, "username");
            String password = DOMUtils.getAttribute(credentialsElement, "password");

            if (scheme != null && !"server-decides".equalsIgnoreCase(scheme)
                    && !"basic".equalsIgnoreCase(scheme) && !"digest".equalsIgnoreCase(scheme)) {
                throw new IllegalArgumentException("Unknown Authentication scheme: [" + scheme
                        + "] Accepted values are: Basic, Digest, Server-Decides");
            } else {
                if (log.isDebugEnabled())
                    log.debug("credentials provided: scheme=" + scheme + " user=" + username
                            + " password=********");
                client.getState().setCredentials(
                        new AuthScope(targetURI.getHost(), targetURI.getPort(), AuthScope.ANY_REALM, scheme),
                        new UsernamePasswordCredentials(username, password));
                // save one round trip if basic
                client.getParams().setAuthenticationPreemptive("basic".equalsIgnoreCase(scheme));
            }
        }
    }
}

From source file:org.apache.ode.bpel.rtrep.v1.ASSIGN.java

private Element replaceElement(Element lval, Element ptr, Element src, boolean keepSrcElement) {
    Document doc = ptr.getOwnerDocument();
    Node parent = ptr.getParentNode();
    if (keepSrcElement) {
        Element replacement = (Element) doc.importNode(src, true);
        parent.replaceChild(replacement, ptr);
        return (lval == ptr) ? replacement : lval;
    }// ww  w . j av  a 2s. c  om

    Element replacement = doc.createElementNS(ptr.getNamespaceURI(), ptr.getLocalName());
    NodeList nl = src.getChildNodes();
    for (int i = 0; i < nl.getLength(); ++i)
        replacement.appendChild(doc.importNode(nl.item(i), true));
    NamedNodeMap attrs = src.getAttributes();
    for (int i = 0; i < attrs.getLength(); ++i) {
        Attr attr = (Attr) attrs.item(i);
        if (!attr.getName().startsWith("xmlns")) {
            replacement.setAttributeNodeNS((Attr) doc.importNode(attrs.item(i), true));
            // Case of qualified attribute values, we're forced to add corresponding namespace declaration manually
            int colonIdx = attr.getValue().indexOf(":");
            if (colonIdx > 0) {
                String prefix = attr.getValue().substring(0, colonIdx);
                String attrValNs = src.lookupPrefix(prefix);
                if (attrValNs != null)
                    replacement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:" + prefix, attrValNs);
            }
        }
    }
    parent.replaceChild(replacement, ptr);
    DOMUtils.copyNSContext(ptr, replacement);

    return (lval == ptr) ? replacement : lval;
}