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.kuali.rice.krad.datadictionary.parse.CustomSchemaParser.java

/**
 * Parses the xml bean into a standard bean definition format and fills the information in the passed in definition
 * builder/*from w w w  .j a va2  s  .c o  m*/
 *
 * @param element - The xml bean being parsed.
 * @param parserContext - Provided information and functionality regarding current bean set.
 * @param bean - A definition builder used to build a new spring bean from the information it is filled with.
 */
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder bean) {
    // Retrieve custom schema information build from the annotations
    Map<String, Map<String, BeanTagAttributeInfo>> attributeProperties = CustomTagAnnotations
            .getAttributeProperties();
    Map<String, BeanTagAttributeInfo> entries = attributeProperties.get(element.getLocalName());

    // Log error if there are no attributes found for the bean tag
    if (entries == null) {
        LOG.error("Bean Tag not found " + element.getLocalName());
    }

    if (element.getTagName().equals(INC_TAG)) {
        String parentId = element.getAttribute("compId");
        bean.setParentName(parentId);

        return;
    }

    if (element.getTagName().equals("content")) {
        bean.setParentName("Uif-Content");

        String markup = nodesToString(element.getChildNodes());
        bean.addPropertyValue("markup", markup);

        return;
    }

    // Retrieve the information for the new bean tag and fill in the default parent if needed
    BeanTagInfo tagInfo = CustomTagAnnotations.getBeanTags().get(element.getLocalName());

    String elementParent = element.getAttribute("parent");
    if (StringUtils.isNotBlank(elementParent) && !StringUtils.equals(elementParent, tagInfo.getParent())) {
        bean.setParentName(elementParent);
    } else if (StringUtils.isNotBlank(tagInfo.getParent())) {
        bean.setParentName(tagInfo.getParent());
    }

    // Create the map for the attributes found in the tag and process them in to the definition builder.
    NamedNodeMap attributes = element.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        processSingleValue(attributes.item(i).getNodeName(), attributes.item(i).getNodeValue(), entries, bean);
    }

    ArrayList<Element> children = (ArrayList<Element>) DomUtils.getChildElements(element);

    // Process the children found in the xml tag
    for (int i = 0; i < children.size(); i++) {
        String tag = children.get(i).getLocalName();
        BeanTagAttributeInfo info = entries.get(tag);

        if (children.get(i).getTagName().equals("spring:property")
                || children.get(i).getTagName().equals("property")) {
            BeanDefinitionParserDelegate delegate = parserContext.getDelegate();
            delegate.parsePropertyElement(children.get(i), bean.getBeanDefinition());

            continue;
        }

        // Sets the property name to be used when adding the property value
        String propertyName;
        BeanTagAttribute.AttributeType type = null;
        if (info == null) {
            propertyName = CustomTagAnnotations.findPropertyByType(element.getLocalName(), tag);

            if (StringUtils.isNotBlank(propertyName)) {
                bean.addPropertyValue(propertyName, parseBean(children.get(i), bean, parserContext));

                continue;
            } else {
                // If the tag is not in the schema map let spring handle the value by forwarding the tag as the
                // propertyName
                propertyName = tag;
                type = findBeanType(children.get(i));
            }
        } else {
            // If the tag is found in the schema map use the connected name stored in the attribute information
            propertyName = info.getPropertyName();
            type = info.getType();
        }

        // Process the information stored in the child bean
        ArrayList<Element> grandChildren = (ArrayList<Element>) DomUtils.getChildElements(children.get(i));

        if (type == BeanTagAttribute.AttributeType.SINGLEVALUE) {
            String propertyValue = DomUtils.getTextValue(children.get(i));
            bean.addPropertyValue(propertyName, propertyValue);
        } else if (type == BeanTagAttribute.AttributeType.ANY) {
            String propertyValue = nodesToString(children.get(i).getChildNodes());
            bean.addPropertyValue(propertyName, propertyValue);
        } else if ((type == BeanTagAttribute.AttributeType.DIRECT)
                || (type == BeanTagAttribute.AttributeType.DIRECTORBYTYPE)) {
            boolean isPropertyTag = false;
            if ((children.get(i).getAttributes().getLength() == 0) && (grandChildren.size() == 1)) {
                String grandChildTag = grandChildren.get(0).getLocalName();

                Class<?> valueClass = info.getValueType();
                if (valueClass.isInterface()) {
                    try {
                        valueClass = Class.forName(valueClass.getName() + "Base");
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException("Unable to find impl class for interface", e);
                    }
                }

                Set<String> validTagNames = CustomTagAnnotations.getBeanTagsByClass(valueClass);
                if (validTagNames.contains(grandChildTag)) {
                    isPropertyTag = true;
                }
            }

            if (isPropertyTag) {
                bean.addPropertyValue(propertyName, parseBean(grandChildren.get(0), bean, parserContext));
            } else {
                bean.addPropertyValue(propertyName, parseBean(children.get(i), bean, parserContext));
            }
        } else if ((type == BeanTagAttribute.AttributeType.SINGLEBEAN)
                || (type == BeanTagAttribute.AttributeType.BYTYPE)) {
            bean.addPropertyValue(propertyName, parseBean(grandChildren.get(0), bean, parserContext));
        } else if (type == BeanTagAttribute.AttributeType.LISTBEAN) {
            bean.addPropertyValue(propertyName, parseList(grandChildren, children.get(i), bean, parserContext));
        } else if (type == BeanTagAttribute.AttributeType.LISTVALUE) {
            bean.addPropertyValue(propertyName, parseList(grandChildren, children.get(i), bean, parserContext));
        } else if (type == BeanTagAttribute.AttributeType.MAPVALUE) {
            bean.addPropertyValue(propertyName, parseMap(grandChildren, children.get(i), bean, parserContext));
        } else if (type == BeanTagAttribute.AttributeType.MAPBEAN) {
            bean.addPropertyValue(propertyName, parseMap(grandChildren, children.get(i), bean, parserContext));
        } else if (type == BeanTagAttribute.AttributeType.SETVALUE) {
            bean.addPropertyValue(propertyName, parseSet(grandChildren, children.get(i), bean, parserContext));
        } else if (type == BeanTagAttribute.AttributeType.SETBEAN) {
            bean.addPropertyValue(propertyName, parseSet(grandChildren, children.get(i), bean, parserContext));
        }
    }
}

From source file:org.kuali.rice.krad.datadictionary.parse.CustomSchemaParser.java

/**
 * Parses a bean of the spring namespace.
 *
 * @param tag - The Element to be parsed.
 * @return The parsed bean.//from www  . ja va  2 s  .com
 */
protected Object parseSpringBean(Element tag, ParserContext parserContext) {
    if (tag.getLocalName().compareTo("ref") == 0) {
        // Create the referenced bean by creating a new bean and setting its parent to the referenced bean
        // then replace grand child with it
        Element temp = tag.getOwnerDocument().createElement("bean");
        temp.setAttribute("parent", tag.getAttribute("bean"));
        tag = temp;
        return new RuntimeBeanReference(tag.getAttribute("parent"));
    }

    //peel off p: properties an make them actual property nodes - p-namespace does not work properly (unknown cause)
    Document document = tag.getOwnerDocument();
    NamedNodeMap attributes = tag.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        String name = attribute.getNodeName();
        if (name.startsWith("p:")) {
            Element property = document.createElement("property");
            property.setAttribute("name", StringUtils.removeStart(name, "p:"));
            property.setAttribute("value", attribute.getTextContent());

            if (tag.getFirstChild() != null) {
                tag.insertBefore(property, tag.getFirstChild());
            } else {
                tag.appendChild(property);
            }
        }
    }

    // Create the bean definition for the grandchild and return it.
    BeanDefinitionParserDelegate delegate = parserContext.getDelegate();
    BeanDefinitionHolder bean = delegate.parseBeanDefinitionElement(tag);

    // Creates a custom name for the new bean.
    String name = bean.getBeanDefinition().getParentName() + "$Customchild" + beanNumber;
    if (tag.getAttribute("id") != null && !StringUtils.isEmpty(tag.getAttribute("id"))) {
        name = tag.getAttribute("id");
    } else {
        beanNumber++;
    }

    return new BeanDefinitionHolder(bean.getBeanDefinition(), name);
}

From source file:org.lilyproject.runtime.tools.plugin.genclassloader.ClassloaderMojo.java

private void parseClassloaderTemplate(File file) {
    DOMResult domResult = null;/*from www.j  a  v  a 2 s  .  c om*/
    Transformer transformer = null;
    try {
        Source xmlSource = new StreamSource(file);
        TransformerFactory tfFactory = TransformerFactory.newInstance();
        if (tfFactory.getFeature(DOMResult.FEATURE)) {
            transformer = tfFactory.newTransformer();
            domResult = new DOMResult();
            transformer.transform(xmlSource, domResult);
        }
    } catch (TransformerException ex) {
        throw new RuntimeException("Error parsing file '" + file + "'.");
    }
    if (domResult != null && transformer != null) {
        Document docu = (Document) domResult.getNode();
        Element classpath;
        NodeList list;

        String shareSelf = docu.getDocumentElement().getAttribute("share-self").trim();
        if (shareSelf.length() > 0) {
            this.shareSelf = shareSelf;
        }

        try {
            classpath = (Element) docu.getElementsByTagName("classpath").item(0);
            list = classpath.getElementsByTagName("artifact");
        } catch (NullPointerException npex) {
            throw new RuntimeException("Classloader template is invalid.");
        }
        NamedNodeMap map;
        Entry entry;
        String groupId;
        String classifier;
        String artifactId;
        Element domArtifact;
        for (int i = 0; i < list.getLength(); i++) {
            domArtifact = (Element) list.item(i);
            map = domArtifact.getAttributes();
            groupId = extractAttVal(map, "groupId");
            artifactId = extractAttVal(map, "artifactId");
            classifier = extractAttVal(map, "classifier");
            entry = new Entry(groupId, artifactId, classifier);
            entryMap.put(entry, domArtifact);
        }
    }

}

From source file:org.mskcc.cbio.oncokb.quest.VariantAnnotationXMLV2.java

private static List<Alteration> getAlterationOrderByLevelOfEvidence(Map<Alteration, String> mapAlterationXml) {
    //sort the variant based on the highest level in the order of: 0 > 1 > R1 > 2A > 2B > R2 > 3A > 3B > R3 > 4
    String[] levels = { "0", "1", "R1", "2A", "2B", "R2", "3A", "3B", "R3", "4" };
    ArrayList<Alteration> alterations = new ArrayList<Alteration>(mapAlterationXml.keySet());
    final Map<Alteration, Integer> mapAlterationLevel = new LinkedHashMap<Alteration, Integer>();
    String relevant = "", tempLevel = "";
    Integer levelIndex, lowestLevelIndex;
    for (int i = 0; i < alterations.size(); i++) {
        levelIndex = -1;// w  w  w.  j a  v a  2  s  . c  o m
        lowestLevelIndex = -1;
        String tempXMLString = "<xml>" + mapAlterationXml.get(alterations.get(i)) + "</xml>";
        try {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource src = new InputSource();
            src.setCharacterStream(new StringReader(tempXMLString));
            org.w3c.dom.Document doc = builder.parse(src);
            NodeList cancerTypeNodes = doc.getElementsByTagName("cancer_type");
            for (int j = 0; j < cancerTypeNodes.getLength(); j++) {
                Element currentNode = (Element) cancerTypeNodes.item(j);
                relevant = currentNode.getAttributes().getNamedItem("relevant_to_patient_disease")
                        .getNodeValue();
                NodeList levelNodes = currentNode.getElementsByTagName("level");
                if (relevant.equalsIgnoreCase("Yes")
                        && currentNode.getElementsByTagName("level").getLength() > 0) {
                    levelIndex = 100;
                    for (int k = 0; k < levelNodes.getLength(); k++) {
                        tempLevel = levelNodes.item(k).getTextContent().toUpperCase();
                        lowestLevelIndex = ArrayUtils.indexOf(levels, tempLevel);
                        if (lowestLevelIndex < levelIndex)
                            levelIndex = lowestLevelIndex;
                    }
                }
            }
            mapAlterationLevel.put(alterations.get(i), levelIndex);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    Collections.sort(alterations, new Comparator<Alteration>() {
        public int compare(Alteration a1, Alteration a2) {
            Integer aLevel = mapAlterationLevel.get(a1), bLevel = mapAlterationLevel.get(a2);
            if (aLevel == -1)
                return 1;
            if (bLevel == -1)
                return -1;
            return aLevel - bLevel;
        }
    });

    return alterations;
}

From source file:org.mule.config.spring.parsers.AbstractMuleBeanDefinitionParser.java

/**
 * Parse the supplied {@link Element} and populate the supplied
 * {@link BeanDefinitionBuilder} as required.
 * <p>/* w ww  . ja v a2 s. c  o m*/
 * The default implementation delegates to the <code>doParse</code> version
 * without ParserContext argument.
 *
 * @param element the XML element being parsed
 * @param context the object encapsulating the current state of the parsing
 *            process
 * @param builder used to define the <code>BeanDefinition</code>
 */
protected void doParse(Element element, ParserContext context, BeanDefinitionBuilder builder) {
    if (deprecationWarning != null && logger.isWarnEnabled()) {
        logger.warn("Schema warning: Use of element <" + element.getLocalName() + "> is deprecated.  "
                + deprecationWarning);
    }

    BeanAssembler assembler = getBeanAssembler(element, builder);
    NamedNodeMap attributes = element.getAttributes();
    for (int x = 0; x < attributes.getLength(); x++) {
        Attr attribute = (Attr) attributes.item(x);
        processProperty(attribute, assembler);
    }
    postProcess(getParserContext(), assembler, element);
}

From source file:org.mule.module.extension.internal.config.XmlExtensionParserUtils.java

private static void parseElementDescriptorAttributes(Element element, BeanDefinitionBuilder builder) {
    ManagedMap<String, String> managedAttributes = new ManagedMap<>();
    NamedNodeMap attributes = element.getAttributes();

    for (int i = 0; i < attributes.getLength(); i++) {
        String name = attributes.item(i).getLocalName();
        managedAttributes.put(name, element.getAttribute(name));
    }//from   ww w. j a  v a2s.c om

    builder.addConstructorArgValue(managedAttributes);
}

From source file:org.odk.aggregate.parser.SubmissionParser.java

/**
 * Recursive function that prints the nodes from an XML tree
 * //from w  w w .ja  v a  2s  . c  o m
 * @param node xml node to be recursively printed
 */
private void printNode(Element node) {
    System.out.println(ParserConsts.NODE_FORMATTED + node.getTagName());
    if (node.hasAttributes()) {
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attr = attributes.item(i);
            System.out.println(ParserConsts.ATTRIBUTE_FORMATTED + attr.getNodeName() + BasicConsts.EQUALS
                    + attr.getNodeValue());
        }
    }
    if (node.hasChildNodes()) {
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                printNode((Element) child);
            } else if (child.getNodeType() == Node.TEXT_NODE) {
                String value = child.getNodeValue().trim();
                if (value.length() > 0) {
                    System.out.println(ParserConsts.VALUE_FORMATTED + value);
                }
            }
        }
    }

}

From source file:org.ojbc.util.xml.TestOjbcNamespaceContext.java

@Test
public void testRootNamespacePopulationWithEmbeddedNamespaceDeclarations() throws Exception {

    Document d = db.newDocument();
    Element root = d.createElementNS(OjbcNamespaceContext.NS_PERSON_SEARCH_RESULTS_EXT, "e1");
    root.setPrefix(OjbcNamespaceContext.NS_PREFIX_PERSON_SEARCH_RESULTS_EXT);
    d.appendChild(root);//from  w w  w. j av a 2  s.  c  o m
    Element child = XmlUtils.appendElement(root, OjbcNamespaceContext.NS_JXDM_41, "foo");
    XmlUtils.addAttribute(child, OjbcNamespaceContext.NS_STRUCTURES, "id", "I1");
    child = XmlUtils.appendElement(child, OjbcNamespaceContext.NS_JXDM_41, "foo2");
    XmlUtils.addAttribute(child, OjbcNamespaceContext.NS_STRUCTURES, "id", "I2");
    XmlUtils.OJBC_NAMESPACE_CONTEXT.populateRootNamespaceDeclarations(child);
    //XmlUtils.printNode(d);
    XmlUtils.OJBC_NAMESPACE_CONTEXT.populateRootNamespaceDeclarations(root);
    //XmlUtils.printNode(d);
    NamedNodeMap attrs = root.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        assertFalse("null".equals(attrs.item(i).getLocalName()) && "xmlns".equals(attrs.item(i).getPrefix()));
    }

}

From source file:org.ojbc.util.xml.TestXmlUtils.java

@Test
public void testAddAttribute() throws Exception {
    Document d = db.newDocument();
    Element e1 = d.createElementNS(OjbcNamespaceContext.NS_PERSON_SEARCH_RESULTS_EXT, "e1");
    d.appendChild(e1);/* w  w w  . j av  a 2s . co  m*/
    XmlUtils.addAttribute(e1, "foo", "a", "baz");
    NamedNodeMap aa = e1.getAttributes();
    assertEquals(1, aa.getLength());
    Node n = aa.getNamedItemNS("foo", "a");
    assertNotNull(n);
    assertEquals("baz", n.getNodeValue());
}

From source file:org.openanzo.jdbc.opgen.RdbStatement.java

/**
 * Create a new RdbStatement from the given XML emement data
 * //from  ww w.j a va2s .  c o  m
 * @param sqlPackageName
 *            package name for statement
 * @param xmlElement
 *            XML element containing data
 */
public RdbStatement(String sqlPackageName, Element xmlElement) {
    this.sqlPackageName = sqlPackageName;
    if (!xmlElement.getNodeName().equals(element))
        throw new InvalidParameterException("XML element not of type '" + element + "'");
    sql = getText(xmlElement);
    if (sql == null)
        throw new InvalidParameterException("Node has no text: " + xmlElement);
    if (sql.trim().equals("EMPTY")) {
        sql = "";
    }
    Node nameNode = xmlElement.getAttributes().getNamedItem(nameAttribute);
    if (nameNode == null)
        throw new InvalidParameterException(
                "'" + nameAttribute + "' is a required attribute for '" + element + "' element.");
    name = nameNode.getNodeValue();
    Node inputsNode = xmlElement.getAttributes().getNamedItem(inputsAttribute);
    if (inputsNode != null) {
        String paramList = inputsNode.getNodeValue();
        inputs = getParams(paramList);
    } else {
        inputs = new ArrayList<Parameter>(0);
    }
    Node templateParamsNode = xmlElement.getAttributes().getNamedItem(templateParamsAttribute);
    if (templateParamsNode != null) {
        String paramList = templateParamsNode.getNodeValue();
        templateParams = getParams(paramList);
    } else {
        templateParams = new ArrayList<Parameter>(0);
    }
    Node outputsNode = xmlElement.getAttributes().getNamedItem(outputsAttribute);
    if (outputsNode != null) {
        String paramList = outputsNode.getNodeValue();
        outputs = getParams(paramList);
    } else {
        outputs = new ArrayList<Parameter>(0);
    }
    Node resultsNode = xmlElement.getAttributes().getNamedItem(resultsAttribute);
    if (resultsNode != null) {
        results = Result.getResultsEnum(resultsNode);
    }
    Node dpNode = xmlElement.getAttributes().getNamedItem(PREPARE);
    if (dpNode != null) {
        prepare = Boolean.parseBoolean(dpNode.getNodeValue());
    }
    initialize();
}