Example usage for org.w3c.dom Node getAttributes

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

Introduction

In this page you can find the example usage for org.w3c.dom Node 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:Main.java

public static int getAllChildrenString(Node start, int offset) {
    //String spacers  = "                                                         ";
    String tagOpen = "<";
    String tagClose = ">";
    String tagEndOpen = "</";
    String tagEndClose = ">";
    String tagName = start.getNodeName();
    String tagValue = (start.getNodeValue() == null ? "" : start.getNodeValue());

    if (start.getNodeName().trim().equals("#text")) {
        tagOpen = "";
        tagClose = "";
        tagName = "";
        tagEndOpen = "";
        tagEndClose = "";
    }/* w w w .j  a v  a  2s.  c o  m*/
    if (offset == 0)
        HTMLString = "";
    else {
        HTMLString += //spacers.substring(0, offset) +
                tagOpen + tagName;

        if (start.getNodeType() == Element.ELEMENT_NODE) {
            NamedNodeMap startAttr = start.getAttributes();
            for (int i = 0; i < startAttr.getLength(); i++) {
                Node attr = startAttr.item(i);
                HTMLString += " " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"";
            }
        }
        HTMLString += tagClose + tagValue;
    }

    for (Node child = start.getFirstChild(); child != null; child = child.getNextSibling()) {
        getAllChildrenString(child, offset + 1);
    }

    if (offset > 0 && tagName.length() > 0) {
        HTMLString += //spacers.substring(0, offset) +
                tagEndOpen + tagName + tagEndClose;
    }

    return ++offset;
}

From source file:com.github.sevntu.checkstyle.internal.ChecksTest.java

private static void validateSonarFile(Document document, Set<Class<?>> modules) {
    final NodeList rules = document.getElementsByTagName("rule");

    for (int position = 0; position < rules.getLength(); position++) {
        final Node rule = rules.item(position);
        final Set<Node> children = XmlUtil.getChildrenElements(rule);

        final String key = SevntuXmlUtil.findElementByTag(children, "key").getTextContent();

        final Class<?> module = findModule(modules, key);
        modules.remove(module);//w w  w.  j av  a  2 s. c  om

        Assert.assertNotNull("Unknown class found in sonar: " + key, module);

        final String moduleName = module.getName();
        final Node name = SevntuXmlUtil.findElementByTag(children, "name");

        Assert.assertNotNull(moduleName + " requires a name in sonar", name);
        Assert.assertFalse(moduleName + " requires a name in sonar", name.getTextContent().isEmpty());

        final Node categoryNode = SevntuXmlUtil.findElementByTag(children, "category");

        String expectedCategory = module.getCanonicalName();
        final int lastIndex = expectedCategory.lastIndexOf('.');
        expectedCategory = expectedCategory.substring(expectedCategory.lastIndexOf('.', lastIndex - 1) + 1,
                lastIndex);

        Assert.assertNotNull(moduleName + " requires a category in sonar", categoryNode);

        final Node categoryAttribute = categoryNode.getAttributes().getNamedItem("name");

        Assert.assertNotNull(moduleName + " requires a category name in sonar", categoryAttribute);
        Assert.assertEquals(moduleName + " requires a valid category in sonar", expectedCategory,
                categoryAttribute.getTextContent());

        final Node description = SevntuXmlUtil.findElementByTag(children, "description");

        Assert.assertNotNull(moduleName + " requires a description in sonar", description);

        final Node configKey = SevntuXmlUtil.findElementByTag(children, "configKey");
        final String expectedConfigKey = "Checker/TreeWalker/" + key;

        Assert.assertNotNull(moduleName + " requires a configKey in sonar", configKey);
        Assert.assertEquals(moduleName + " requires a valid configKey in sonar", expectedConfigKey,
                configKey.getTextContent());

        validateSonarProperties(module, SevntuXmlUtil.findElementsByTag(children, "param"));
    }

    for (Class<?> module : modules) {
        Assert.fail("Module not found in sonar: " + module.getCanonicalName());
    }
}

From source file:isl.FIMS.utils.Utils.java

public static void copySchemaReferences(String schemaPath, String destination) {
    Document contents = ParseXMLFile.parseFile(schemaPath);
    String prefix = contents.getDocumentElement().getTagName().split(":")[0];
    NodeList includes = contents.getElementsByTagName(prefix + ":include");
    for (int i = 0; i < includes.getLength(); i++) {
        try {/*from   w w  w.  j a  v a2s  .c  o m*/
            Node include = includes.item(i);
            String schemaLocation = include.getAttributes().getNamedItem("schemaLocation").getNodeValue();
            if (schemaLocation != "") {
                File schemaFile = new File(Utils.schemaFolder + schemaLocation);
                FileUtils.copyFile(schemaFile,
                        new File(destination + System.getProperty("file.separator") + schemaLocation));
                copySchemaReferences(schemaFile.getAbsolutePath(), destination);
            }
        } catch (IOException ex) {
        }

    }

}

From source file:it.unibo.alchemist.language.EnvironmentBuilder.java

@SuppressWarnings("unchecked")
private static <E> E coreOperations(final Map<String, Object> environment, final Node root, final String type,
        final RandomGenerator random) throws InstantiationException, IllegalAccessException,
        InvocationTargetException, ClassNotFoundException {
    final NamedNodeMap atts = root.getAttributes();
    final Node nameNode = atts.getNamedItem(NAME);
    final String name = nameNode == null ? "" : nameNode.getNodeValue();
    if (!name.equals("") && atts.getLength() == 1 && environment.containsKey(name)) {
        return (E) environment.get(name);
    }/*from w  w w. ja  v  a2 s  .co m*/
    final Class<?> objClass = (Class<?>) Class.forName(type);
    final List<Constructor<E>> consList = unsafeExtractConstructors(objClass);
    final ArrayList<String> params = new ArrayList<String>();
    int index = 0;
    for (Node param = atts.getNamedItem("p0"); param != null; param = atts.getNamedItem("p" + (++index))) {
        params.add(param.getNodeValue());
    }
    params.trimToSize();
    final E res = tryToBuild(consList, params, environment, random);
    environment.put(name, res);
    return res;
}

From source file:it.unibo.alchemist.language.EnvironmentBuilder.java

private static Time buildTime(final Node son, final Map<String, Object> env, final RandomGenerator random)
        throws InstantiationException, IllegalAccessException, InvocationTargetException,
        ClassNotFoundException {// www . jav  a 2 s  .  c  o  m
    final NamedNodeMap attributes = son.getAttributes();
    String type = attributes.getNamedItem(TYPE).getNodeValue();
    type = type.contains(".") ? type : "it.unibo.alchemist.model.implementations.times." + type;
    return (Time) coreOperations(env, son, type, random);
}

From source file:be.ibridge.kettle.core.XMLHandler.java

public static final String getTagAttribute(Node node, String attribute) {
    String retval = null;/* w ww .j av a  2s .  c o m*/

    NamedNodeMap nnm = node.getAttributes();
    if (nnm != null) {
        Node attr = nnm.getNamedItem(attribute);
        if (attr != null) {
            retval = attr.getNodeValue();
        }
    }
    return retval;
}

From source file:com.photon.phresco.framework.commons.QualityUtil.java

public static PerformancResultInfo getPerformanceReport(Document document, String techId, String deviceId)
        throws Exception { // deviceid is the tag name for android
    String xpath = "/*/*"; // For other technologies
    String device = "*";/*from  w  w w . j  a v  a2s.co  m*/
    PerformancResultInfo performanceResultInfo = new PerformancResultInfo();
    TestResultInfo generateTestResultValues = new TestResultInfo();
    ;
    if (StringUtils.isNotEmpty(deviceId)) {
        device = "deviceInfo[@id='" + deviceId + "']";
    }
    if (TechnologyTypes.ANDROIDS.contains(techId)) {
        xpath = "/*/" + device + "/*";
    }
    NodeList nodeList = org.apache.xpath.XPathAPI.selectNodeList(document, xpath);
    Map<String, PerformanceTestResult> tempMap = new LinkedHashMap<String, PerformanceTestResult>(100);
    List<PerformanceTestResult> results = new ArrayList<PerformanceTestResult>();
    double maxTs = 0;
    double minTs = 0;
    int lastTime = 0;
    int noOfSamples = nodeList.getLength();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        NamedNodeMap nameNodeMap = node.getAttributes();
        Node timeAttr = nameNodeMap.getNamedItem(FrameworkConstants.ATTR_JM_TIME);
        int time = Integer.parseInt(timeAttr.getNodeValue());
        Node bytesAttr = nameNodeMap.getNamedItem(FrameworkConstants.ATTR_JM_BYTES);
        int bytes = Integer.parseInt(bytesAttr.getNodeValue());
        Node successFlagAttr = nameNodeMap.getNamedItem(FrameworkConstants.ATTR_JM_SUCCESS_FLAG);
        boolean success = Boolean.parseBoolean(successFlagAttr.getNodeValue()) ? true : false;
        Node labelAttr = nameNodeMap.getNamedItem(FrameworkConstants.ATTR_JM_LABEL);
        String label = labelAttr.getNodeValue();
        Node timeStampAttr = nameNodeMap.getNamedItem(FrameworkConstants.ATTR_JM_TIMESTAMP);
        double timeStamp = Long.parseLong(timeStampAttr.getNodeValue());
        boolean firstEntry = false;

        PerformanceTestResult performanceTestResult = tempMap.get(label);
        if (performanceTestResult == null) {
            performanceTestResult = new PerformanceTestResult();
            firstEntry = true;
        } else {
            firstEntry = false;
        }
        performanceTestResult.setLabel(label.trim());
        performanceTestResult.setNoOfSamples(performanceTestResult.getNoOfSamples() + 1);
        performanceTestResult.getTimes().add(time);
        performanceTestResult.setTotalTime(performanceTestResult.getTotalTime() + time);
        performanceTestResult.setTotalBytes(performanceTestResult.getTotalBytes() + bytes);

        if (time < performanceTestResult.getMin() || firstEntry) {
            performanceTestResult.setMin(time);
        }

        if (time > performanceTestResult.getMax()) {
            performanceTestResult.setMax(time);
        }

        // Error calculation
        if (!success) {
            performanceTestResult.setErr(performanceTestResult.getErr() + 1);
        }

        // Throughput calculation

        if (timeStamp >= performanceTestResult.getMaxTs()) {
            performanceTestResult.setMaxTs(timeStamp);
            performanceTestResult.setLastTime(time);
        }

        if (i == 0 || (performanceTestResult.getMaxTs() > maxTs)) {
            maxTs = performanceTestResult.getMaxTs();
            lastTime = performanceTestResult.getLastTime();
        }

        if (timeStamp < performanceTestResult.getMinTs() || firstEntry) {
            performanceTestResult.setMinTs(timeStamp);
        }

        if (i == 0) {
            minTs = performanceTestResult.getMinTs();
        } else if (performanceTestResult.getMinTs() < minTs) {
            minTs = performanceTestResult.getMinTs();
        }

        Double calThroughPut = new Double(performanceTestResult.getNoOfSamples());
        double timeSpan = performanceTestResult.getMaxTs() + performanceTestResult.getLastTime()
                - performanceTestResult.getMinTs();
        if (timeSpan > 0) {
            calThroughPut = calThroughPut / timeSpan;
        } else {
            calThroughPut = 0.0;
        }
        double throughPut = calThroughPut * 1000;
        performanceTestResult.setThroughtPut(throughPut);
        tempMap.put(label, performanceTestResult);
    }

    Set<String> keySet = tempMap.keySet();
    for (String label : keySet) {
        results.add(tempMap.get(label));
    }

    // Total Throughput calculation
    double totalThroughput;
    double timeSpan = ((maxTs + lastTime) - minTs);
    if (timeSpan > 0) {
        totalThroughput = (noOfSamples / timeSpan) * 1000;
    } else {
        totalThroughput = 0.0;
    }
    generateTestResultValues = setStdDevToResults(results, generateTestResultValues);
    generateTestResultValues = generateTestResultValues(results, totalThroughput, generateTestResultValues);
    setNewValuesToResults(results);
    performanceResultInfo.setPerfromanceTestResult(results);
    performanceResultInfo.setAggregateResult(generateTestResultValues);
    return performanceResultInfo;
}

From source file:edu.duke.cabig.c3pr.webservice.integration.XMLUtils.java

/**
 * Does deep comparison of two DOM trees represented by the given
 * {@link Element}s. Elements are considered root nodes of the trees. <br>
 * <br>/* w w  w.  j  a  v  a 2  s  .  c om*/
 * This version of the method will <b>only</b> process elements of types
 * {@link Node#ELEMENT_NODE},{@link Node#TEXT_NODE},
 * {@link Node#CDATA_SECTION_NODE}; others will be ignored. Content of text
 * nodes is normalized before comparison. <br>
 * <br>
 * When comparing two elements, their local names, namespaces, and
 * attributes (except <code>xmlns* and xsi:type</code>) are accounted for. <br>
 * <br>
 * Due to issues with using
 * <code>setIgnoringElementContentWhitespace(true)</code>, which does not
 * seem to work, this method will throw out empty text nodes when comparing
 * children.
 * 
 * @since 1.0
 * @param e1
 * @param e2
 * @return
 */
public static boolean isDeepEqual(Node n1, Node n2) {
    if (!StringUtils.equals(n1.getLocalName(), n2.getLocalName())) {
        log.info("Node local names are not equal: " + n1.getLocalName() + " " + n2.getLocalName());
        return false;
    }
    if (!StringUtils.equals(n1.getNamespaceURI(), n2.getNamespaceURI())) {
        log.info("Node namespaces are not equal: " + n1.getNamespaceURI() + " " + n2.getNamespaceURI());
        return false;
    }
    if (n1.getNodeType() != n2.getNodeType()) {
        log.info("Node types are not equal: " + n1.getNodeType() + " " + n2.getNodeType());
        return false;
    }
    // check attributes equality.
    NamedNodeMap attrs1 = n1.getAttributes();
    NamedNodeMap attrs2 = n2.getAttributes();
    if (!isEqual(attrs1, attrs2)) {
        return false;
    }

    short nodeType = n1.getNodeType();
    switch (nodeType) {
    case Node.ELEMENT_NODE:
        return isDeepEqual(filterOutEmptyTextNodes(n1.getChildNodes()),
                filterOutEmptyTextNodes(n2.getChildNodes()));
    case Node.TEXT_NODE:
        return isTextNodeEqual(n1, n2);
    case Node.CDATA_SECTION_NODE:
        return isTextNodeEqual(n1, n2);
    default:
        break;
    }
    return true;
}

From source file:AndroidUninstallStock.java

public static HashMap<String, String> getXmlAttributes(Node node) {
    HashMap<String, String> res = new HashMap<String, String>();
    NamedNodeMap attrs = node.getAttributes();
    if (attrs == null) {
        return res;
    }//  w w  w  . j  a va  2  s.c  o m
    for (int x = attrs.getLength() - 1; x > -1; x--) {
        res.put(attrs.item(x).getNodeName(), attrs.item(x).getNodeValue());
    }
    return res;
}

From source file:com.esri.geoevent.solutions.adapter.cot.CoTUtilities.java

private static ArrayList<CoTTypeDef> typeBreakdown(Node n) {

    ArrayList<CoTTypeDef> hash = new ArrayList<CoTTypeDef>();

    try {/*  w w w . j a  v  a 2  s  .  c om*/

        String name = n.getNodeName();

        if (name.startsWith("#")) {
            // no match here
            return new ArrayList<CoTTypeDef>();

        }
        StringBuffer sb = new StringBuffer();
        sb.append('<').append(name);

        NamedNodeMap attrs = n.getAttributes();
        if (attrs != null) {

            if (attrs.getLength() >= 3 && name.equals("cot")) {
                String zero = attrs.item(0).getNodeName();
                String one = attrs.item(1).getNodeName();
                String two = attrs.item(2).getNodeName();

                // for some reason the attributes are not coming back in
                // order. make sure we get the ones we want
                int k = 0;
                int v = 1;
                if (zero.equals("cot")) {
                    k = 0;
                } else if (one.equals("cot")) {
                    k = 1;
                } else if (two.equals("cot")) {
                    k = 2;
                }

                if (zero.equals("desc")) {
                    v = 0;
                } else if (one.equals("desc")) {
                    v = 1;
                } else if (two.equals("desc")) {
                    v = 2;
                }
                hash.add(new CoTTypeDef("^" + attrs.item(k).getNodeValue() + "$", attrs.item(v).getNodeValue(),
                        false));

            } else if (attrs.getLength() == 2 && name.equals("cot")) {
                String zero = attrs.item(0).getNodeName();

                // make sure we are grabbing the elements in the right order
                int k = 0;
                int v = 1;
                if (zero.equals("cot")) {
                    k = 0;
                    v = 1;
                } else {
                    k = 1;
                    v = 0;
                }
                hash.add(new CoTTypeDef("^" + attrs.item(k).getNodeValue() + "$", attrs.item(v).getNodeValue(),
                        false));

            } else if (attrs.getLength() == 2 && name.equals("weapon")) {

                String zero = attrs.item(0).getNodeName();

                // make sure we are grabbing the elements in the right order
                int k = 0;
                int v = 1;
                if (zero.equals("cot")) {
                    k = 0;
                    v = 1;
                } else {
                    k = 1;
                    v = 0;
                }
                hash.add(new CoTTypeDef("^" + attrs.item(k).getNodeValue() + "$", attrs.item(v).getNodeValue(),
                        false));

            } else if (attrs.getLength() == 2 && name.equals("relation")) {

                String zero = attrs.item(0).getNodeName();
                // make sure we are grabbing the elements in the right order
                int k = 0;
                int v = 1;
                if (zero.equals("cot")) {
                    k = 0;
                    v = 1;
                } else {
                    k = 1;
                    v = 0;
                }
                hash.add(new CoTTypeDef("^" + attrs.item(k).getNodeValue() + "$", attrs.item(v).getNodeValue(),
                        false));

            } else if (attrs.getLength() == 2 && name.equals("how")) {

                String zero = attrs.item(0).getNodeName();
                // make sure we are grabbing the elements in the right order
                int k = 0;
                int v = 1;
                if (zero.equals("value")) {
                    k = 0;
                    v = 1;
                } else {
                    k = 1;
                    v = 0;
                }

                hash.add(new CoTTypeDef("^" + attrs.item(k).getNodeValue() + "$", attrs.item(v).getNodeValue(),
                        false));

            } else if (attrs.getLength() == 2 && name.equals("is")) {
                String zero = attrs.item(0).getNodeName();
                // make sure we are grabbing the elements in the right order
                int k = 0;
                int v = 1;
                if (zero.equals("match")) {
                    k = 0;
                    v = 1;
                } else {
                    k = 1;
                    v = 0;
                }
                String s = attrs.item(v).getNodeValue();
                if (!(s.equals("true") || s.equals("false") || s.equals("spare") || s.equals("any")
                        || s.equals("atoms"))) {
                    hash.add(new CoTTypeDef(attrs.item(k).getNodeValue(), attrs.item(v).getNodeValue(), true));

                }
            } else if (attrs.getLength() == 2 && name.equals("how")) {
                String zero = attrs.item(0).getNodeName();
                // make sure we are grabbing the elements in the right order
                int k = 0;
                int v = 1;
                if (zero.equals("value")) {
                    k = 0;
                    v = 1;
                } else {
                    k = 1;
                    v = 0;
                }
                String s = attrs.item(v).getNodeValue();
                if (!(s.equals("true") || s.equals("false") || s.equals("spare") || s.equals("any")
                        || s.equals("atoms"))) {
                    hash.add(new CoTTypeDef(attrs.item(k).getNodeValue(), attrs.item(v).getNodeValue(), false));

                }
            }

        }

        String textContent = null;
        NodeList children = n.getChildNodes();

        if (children.getLength() == 0) {
            if ((textContent = n.getTextContent()) != null && !"".equals(textContent)) {

            } else {

            }
        } else {

            boolean hasValidChildren = false;
            for (int i = 0; i < children.getLength(); i++) {
                ArrayList<CoTTypeDef> childHash = typeBreakdown(children.item(i));

                if (childHash.size() > 0) {

                    hash.addAll(childHash);
                    hasValidChildren = true;
                }
            }

            if (!hasValidChildren && ((textContent = n.getTextContent()) != null)) {

            }

        }

        return hash;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return hash;
    }

}