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:eu.elf.license.LicenseParser.java

/**
 * Parses a list of active licenses from GetLicenseReferences response string
 * /*from   w  w  w . j  a  va2 s . c  o m*/
 * @param xml   - xml response
 * @return      - ArrayList of license identifiers that are active
 * @throws Exception
 */
public static ArrayList<String> parseActiveLicensesFromGetLicenseReferencesResponse(String xml)
        throws Exception {
    ArrayList<String> activeLicenses = new ArrayList<String>();

    try {
        Document xmlDoc = createXMLDocumentFromString(xml);

        NodeList licenseReferenceList = xmlDoc.getElementsByTagNameNS("http://www.52north.org/license/0.3.2",
                "LicenseReference");

        for (int i = 0; i < licenseReferenceList.getLength(); i++) {
            Element licenseReferenceElement = (Element) licenseReferenceList.item(i);

            NodeList attributeElementList = licenseReferenceElement
                    .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Attribute");

            for (int j = 0; j < attributeElementList.getLength(); j++) {
                Element attributeElement = (Element) attributeElementList.item(j);
                Element attributeValueElement = (Element) attributeElement
                        .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "AttributeValue")
                        .item(0);

                NamedNodeMap attributeMap = attributeElement.getAttributes();

                for (int k = 0; k < attributeMap.getLength(); k++) {
                    Attr attrs = (Attr) attributeMap.item(k);
                    if (attrs.getNodeName().equals("Name")) {

                        if (attrs.getNodeValue().equals("urn:opengeospatial:ows4:geodrm:LicenseID")) {
                            activeLicenses.add(attributeValueElement.getTextContent());
                        }
                    }

                }

            }

        }

    } catch (Exception e) {
        throw e;
    }

    return activeLicenses;
}

From source file:com.amalto.core.history.UniqueIdTransformer.java

private void _addIds(org.w3c.dom.Document document, Element element, Stack<Integer> levels) {
    NamedNodeMap attributes = element.getAttributes();
    Attr id = document.createAttribute(ID_ATTRIBUTE_NAME);

    int thisElementId = levels.pop() + 1;
    StringBuilder builder;/*w ww . j  a va  2s.com*/
    {
        builder = new StringBuilder();
        for (Integer level : levels) {
            builder.append(level);
        }
    }
    String prefix = builder.toString().isEmpty() ? StringUtils.EMPTY : builder.toString() + '-';
    id.setValue(prefix + element.getNodeName() + '-' + thisElementId);
    attributes.setNamedItem(id);

    levels.push(thisElementId);
    {
        levels.push(0);
        NodeList children = element.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element child = (Element) children.item(i);
                _addIds(document, child, levels);
            }
        }
        levels.pop();
    }
}

From source file:DOMUtils.java

public static void compareNodes(Node expected, Node actual) throws Exception {
    if (expected.getNodeType() != actual.getNodeType()) {
        throw new Exception("Different types of nodes: " + expected + " " + actual);
    }//  w w w.j  av a2s  .c  o m
    if (expected instanceof Document) {
        Document expectedDoc = (Document) expected;
        Document actualDoc = (Document) actual;
        compareNodes(expectedDoc.getDocumentElement(), actualDoc.getDocumentElement());
    } else if (expected instanceof Element) {
        Element expectedElement = (Element) expected;
        Element actualElement = (Element) actual;

        // compare element names
        if (!expectedElement.getLocalName().equals(actualElement.getLocalName())) {
            throw new Exception("Element names do not match: " + expectedElement.getLocalName() + " "
                    + actualElement.getLocalName());
        }
        // compare element ns
        String expectedNS = expectedElement.getNamespaceURI();
        String actualNS = actualElement.getNamespaceURI();
        if ((expectedNS == null && actualNS != null) || (expectedNS != null && !expectedNS.equals(actualNS))) {
            throw new Exception("Element namespaces names do not match: " + expectedNS + " " + actualNS);
        }

        String elementName = "{" + expectedElement.getNamespaceURI() + "}" + actualElement.getLocalName();

        // compare attributes
        NamedNodeMap expectedAttrs = expectedElement.getAttributes();
        NamedNodeMap actualAttrs = actualElement.getAttributes();
        if (countNonNamespaceAttribures(expectedAttrs) != countNonNamespaceAttribures(actualAttrs)) {
            throw new Exception(elementName + ": Number of attributes do not match up: "
                    + countNonNamespaceAttribures(expectedAttrs) + " "
                    + countNonNamespaceAttribures(actualAttrs));
        }
        for (int i = 0; i < expectedAttrs.getLength(); i++) {
            Attr expectedAttr = (Attr) expectedAttrs.item(i);
            if (expectedAttr.getName().startsWith("xmlns")) {
                continue;
            }
            Attr actualAttr = null;
            if (expectedAttr.getNamespaceURI() == null) {
                actualAttr = (Attr) actualAttrs.getNamedItem(expectedAttr.getName());
            } else {
                actualAttr = (Attr) actualAttrs.getNamedItemNS(expectedAttr.getNamespaceURI(),
                        expectedAttr.getLocalName());
            }
            if (actualAttr == null) {
                throw new Exception(elementName + ": No attribute found:" + expectedAttr);
            }
            if (!expectedAttr.getValue().equals(actualAttr.getValue())) {
                throw new Exception(elementName + ": Attribute values do not match: " + expectedAttr.getValue()
                        + " " + actualAttr.getValue());
            }
        }

        // compare children
        NodeList expectedChildren = expectedElement.getChildNodes();
        NodeList actualChildren = actualElement.getChildNodes();
        if (expectedChildren.getLength() != actualChildren.getLength()) {
            throw new Exception(elementName + ": Number of children do not match up: "
                    + expectedChildren.getLength() + " " + actualChildren.getLength());
        }
        for (int i = 0; i < expectedChildren.getLength(); i++) {
            Node expectedChild = expectedChildren.item(i);
            Node actualChild = actualChildren.item(i);
            compareNodes(expectedChild, actualChild);
        }
    } else if (expected instanceof Text) {
        String expectedData = ((Text) expected).getData().trim();
        String actualData = ((Text) actual).getData().trim();

        if (!expectedData.equals(actualData)) {
            throw new Exception("Text does not match: " + expectedData + " " + actualData);
        }
    }
}

From source file:org.carewebframework.shell.BaseXmlParser.java

/**
 * Adds all attributes of the specified elements as properties in the current builder.
 * //from  w  w  w .  j  a va  2  s .  c  o m
 * @param element Element whose attributes are to be added.
 * @param builder Target builder.
 */
protected void addProperties(Element element, BeanDefinitionBuilder builder) {
    NamedNodeMap attributes = element.getAttributes();

    for (int i = 0; i < attributes.getLength(); i++) {
        Node node = attributes.item(i);
        String attrName = getNodeName(node);
        attrName = "class".equals(attrName) ? "clazz" : attrName;
        builder.addPropertyValue(attrName, node.getNodeValue());
    }
}

From source file:com.sap.research.connectivity.gw.parsers.MetadataXMLParser.java

private String getNodeAttributeValue(Element ele, String attributeName) throws Exception {
    return ((Attr) ele.getAttributes().getNamedItem(attributeName)).getValue().toString();
}

From source file:eu.elf.license.LicenseParser.java

public static UserLicenses parseUserLicensesAsLicenseModelGroupList(String xml, String userid)
        throws Exception {
    UserLicenses userLicenses = new UserLicenses();

    try {//from  w  w  w  . ja v a  2  s .  com
        Document xmlDoc = createXMLDocumentFromString(xml);

        Element ordersElement = (Element) xmlDoc
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "orders").item(0);
        NodeList orderList = ordersElement.getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "order");

        for (int i = 0; i < orderList.getLength(); i++) {
            UserLicense userLicense = new UserLicense();
            try {
                Element orderElement = (Element) orderList.item(i);
                Element productionElement = (Element) orderElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "production").item(0);
                Element productionItemElement = (Element) productionElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "productionItem").item(0);
                Element LicenseReferenceElement = (Element) productionItemElement
                        .getElementsByTagNameNS("http://www.52north.org/license/0.3.2", "LicenseReference")
                        .item(0);
                Element attributeStatementElement = (Element) LicenseReferenceElement
                        .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "AttributeStatement")
                        .item(0);

                NodeList attributeElementList = attributeStatementElement
                        .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Attribute");

                for (int j = 0; j < attributeElementList.getLength(); j++) {
                    Element attributeElement = (Element) attributeElementList.item(j);
                    Element AttributeValueElement = (Element) attributeElement
                            .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "AttributeValue")
                            .item(0);

                    NamedNodeMap attributeMap = attributeElement.getAttributes();
                    for (int k = 0; k < attributeMap.getLength(); k++) {
                        Attr attrs = (Attr) attributeMap.item(k);
                        if ("Name".equals(attrs.getNodeName())) {

                            if ("urn:opengeospatial:ows4:geodrm:NotOnOrAfter".equals(attrs.getNodeValue())) {
                                userLicense.setValidTo(AttributeValueElement.getTextContent());
                            }
                            if ("urn:opengeospatial:ows4:geodrm:LicenseID".equals(attrs.getNodeValue())) {
                                userLicense.setLicenseId(AttributeValueElement.getTextContent());
                            }
                        }
                    }
                    userLicense.setSecureServiceURL("/httpauth/licid-" + userLicense.getLicenseId());
                }

                Element orderContentElement = (Element) orderElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "orderContent").item(0);
                Element catalogElement = (Element) orderContentElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "catalog").item(0);
                NodeList productGroupElementList = catalogElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "productGroup");

                // setup user license flags in models
                List<LicenseModelGroup> list = createLicenseModelGroupList(productGroupElementList);
                for (LicenseModelGroup group : list) {
                    group.setUserLicense(true);
                }
                userLicense.setLmgList(list);

                String WSS_URL = findWssUrlFromUserLicenseParamList(userLicense.getLmgList());

                //Remove WSS from the WSS-url string
                WSS_URL = WSS_URL.substring(0, WSS_URL.lastIndexOf("/"));

                userLicense.setSecureServiceURL(WSS_URL + userLicense.getSecureServiceURL());

                userLicenses.addUserLicense(userLicense);
            } catch (Exception e) {
                // Sometimes we get results without LicenseReference element: order/production/productionItem/LicenseReference
                // there might be valid results in the same response. Skipping the invalid ones.
                LOG.warn("Error while parsing user licenses");
            }

        }

        return userLicenses;

    } catch (Exception e) {
        throw e;
    }
}

From source file:com.predic8.membrane.core.config.spring.AbstractParser.java

protected void setProperties(String prop, Element e, BeanDefinitionBuilder builder) {
    NamedNodeMap attributes = e.getAttributes();
    HashMap<String, String> attrs = new HashMap<String, String>();
    for (int i = 0; i < attributes.getLength(); i++) {
        Attr item = (Attr) attributes.item(i);
        if (item.getLocalName() != null)
            attrs.put(item.getLocalName(), item.getValue());
    }/*ww w .  j a  va 2 s.  c  om*/
    builder.addPropertyValue(prop, attrs);
}

From source file:com.centeractive.ws.builder.soap.SchemaUtils.java

/**
 * Returns a map mapping urls to corresponding XmlSchema XmlObjects for the
 * specified wsdlUrl/*from  ww w  . j a  v  a2 s.c  o  m*/
 */

public static void getSchemas(String wsdlUrl, Map<String, XmlObject> existing, SchemaLoader loader,
        String tns) {
    if (existing.containsKey(wsdlUrl)) {
        return;
    }

    // if( add )
    // existing.put( wsdlUrl, null );

    log.info("Getting schema " + wsdlUrl);

    ArrayList<?> errorList = new ArrayList<Object>();

    Map<String, XmlObject> result = new HashMap<String, XmlObject>();

    boolean common = false;

    try {
        XmlOptions options = new XmlOptions();
        options.setCompileNoValidation();
        options.setSaveUseOpenFrag();
        options.setErrorListener(errorList);
        options.setSaveSyntheticDocumentElement(new QName(Constants.XSD_NS, "schema"));

        XmlObject xmlObject = loader.loadXmlObject(wsdlUrl, options);
        if (xmlObject == null)
            throw new Exception("Failed to load schema from [" + wsdlUrl + "]");

        Document dom = (Document) xmlObject.getDomNode();
        Node domNode = dom.getDocumentElement();

        // is this an xml schema?
        if (domNode.getLocalName().equals("schema") && Constants.XSD_NS.equals(domNode.getNamespaceURI())) {
            // set targetNamespace (this happens if we are following an include
            // statement)
            if (tns != null) {
                Element elm = ((Element) domNode);
                if (!elm.hasAttribute("targetNamespace")) {
                    common = true;
                    elm.setAttribute("targetNamespace", tns);
                }

                // check for namespace prefix for targetNamespace
                NamedNodeMap attributes = elm.getAttributes();
                int c = 0;
                for (; c < attributes.getLength(); c++) {
                    Node item = attributes.item(c);
                    if (item.getNodeName().equals("xmlns"))
                        break;

                    if (item.getNodeValue().equals(tns) && item.getNodeName().startsWith("xmlns"))
                        break;
                }

                if (c == attributes.getLength())
                    elm.setAttribute("xmlns", tns);
            }

            if (common && !existing.containsKey(wsdlUrl + "@" + tns))
                result.put(wsdlUrl + "@" + tns, xmlObject);
            else
                result.put(wsdlUrl, xmlObject);
        } else {
            existing.put(wsdlUrl, null);

            XmlObject[] schemas = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:schema");

            for (int i = 0; i < schemas.length; i++) {
                XmlCursor xmlCursor = schemas[i].newCursor();
                String xmlText = xmlCursor.getObject().xmlText(options);
                // schemas[i] = XmlObject.Factory.parse( xmlText, options );
                schemas[i] = XmlUtils.createXmlObject(xmlText, options);
                schemas[i].documentProperties().setSourceName(wsdlUrl);

                result.put(wsdlUrl + "@" + (i + 1), schemas[i]);
            }

            XmlObject[] wsdlImports = xmlObject
                    .selectPath("declare namespace s='" + Constants.WSDL11_NS + "' .//s:import/@location");
            for (int i = 0; i < wsdlImports.length; i++) {
                String location = ((SimpleValue) wsdlImports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] wadl10Imports = xmlObject.selectPath(
                    "declare namespace s='" + Constants.WADL10_NS + "' .//s:grammars/s:include/@href");
            for (int i = 0; i < wadl10Imports.length; i++) {
                String location = ((SimpleValue) wadl10Imports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] wadlImports = xmlObject.selectPath(
                    "declare namespace s='" + Constants.WADL11_NS + "' .//s:grammars/s:include/@href");
            for (int i = 0; i < wadlImports.length; i++) {
                String location = ((SimpleValue) wadlImports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

        }

        existing.putAll(result);

        XmlObject[] schemas = result.values().toArray(new XmlObject[result.size()]);

        for (int c = 0; c < schemas.length; c++) {
            xmlObject = schemas[c];

            XmlObject[] schemaImports = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:import/@schemaLocation");
            for (int i = 0; i < schemaImports.length; i++) {
                String location = ((SimpleValue) schemaImports[i]).getStringValue();
                Element elm = ((Attr) schemaImports[i].getDomNode()).getOwnerElement();

                if (location != null && !defaultSchemas.containsKey(elm.getAttribute("namespace"))) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] schemaIncludes = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:include/@schemaLocation");
            for (int i = 0; i < schemaIncludes.length; i++) {
                String location = ((SimpleValue) schemaIncludes[i]).getStringValue();
                if (location != null) {
                    String targetNS = getTargetNamespace(xmlObject);

                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, targetNS);
                }
            }
        }
    } catch (Exception e) {
        throw new SoapBuilderException(e);
    }
}

From source file:org.apache.sling.launchpad.SmokeIT.java

@Test
public void ensureRepositoryIsStarted() throws Exception {
    try (CloseableHttpClient client = newClient()) {

        HttpGet get = new HttpGet("http://localhost:" + LAUNCHPAD_PORT + "/server/default/jcr:root");

        try (CloseableHttpResponse response = client.execute(get)) {

            if (response.getStatusLine().getStatusCode() != 200) {
                fail("Unexpected status line " + response.getStatusLine());
            }//from  ww  w  .  j  ava  2s  . c o  m

            Header contentType = response.getFirstHeader("Content-Type");
            assertThat("Content-Type header", contentType.getValue(), equalTo("text/xml"));

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(response.getEntity().getContent());

            Element docElement = document.getDocumentElement();
            NamedNodeMap attrs = docElement.getAttributes();

            Node nameAttr = attrs.getNamedItemNS("http://www.jcp.org/jcr/sv/1.0", "name");
            assertThat("no 'name' attribute found", nameAttr, notNullValue());
            assertThat("Invalid name attribute value", nameAttr.getNodeValue(), equalTo("jcr:root"));
        }
    }
}

From source file:org.jolokia.jvmagent.spring.config.ConfigBeanDefinitionParser.java

@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    Map<String, Object> config = new HashMap<String, Object>();
    builder.addPropertyValue("config", createConfigMap(element.getAttributes()));
    String order = element.getAttribute("order");
    if (StringUtils.hasText(order)) {
        builder.addPropertyValue("order", Integer.parseInt(order));
    }//from   w w  w  .  ja v  a2  s  . co  m
}