Example usage for org.w3c.dom Element getNodeName

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

Introduction

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

Prototype

public String getNodeName();

Source Link

Document

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

Usage

From source file:app.MainPanel.java

private HashMap readNodes(NodeList hList) {
    HashMap<String, Object> returnValue = new HashMap<>();

    for (int temp = 0; temp < hList.getLength(); temp++) {
        Node hNode = hList.item(temp);

        if (hNode.getNodeType() == Node.ELEMENT_NODE) {
            Element hElement = (Element) hNode;

            returnValue.put(hElement.getNodeName(), hElement.getTextContent());
        }/*from  w  w  w  . j a  v  a2 s  .c  o m*/
    }
    return returnValue;
}

From source file:com.github.dozermapper.core.loader.xml.XMLParser.java

private void debugElement(Element element) {
    log.debug("config name: {}", element.getNodeName());
    log.debug("  value: {}", element.getFirstChild().getNodeValue());
}

From source file:com.alfaariss.oa.util.configuration.ConfigurationManager.java

private synchronized Element getSubSectionByID(Element eRootSection, String sSectionType, String sSectionID) {
    assert eRootSection != null : "Suplied root section is empty";
    //split sectionID (id=ticket) to key/value pair

    int iFirstEquals = sSectionID.indexOf("=");
    if (iFirstEquals == -1) {
        StringBuffer sbError = new StringBuffer("Invalid section ID (must contain a '='): ");
        sbError.append(sSectionID);/*from w  w  w . j av  a  2 s.c o  m*/
        _logger.debug(sbError.toString());
        throw new IllegalArgumentException("Invalid section ID (should be name=value)");
    }

    String sKey = sSectionID.substring(0, iFirstEquals);
    String sValue = sSectionID.substring(iFirstEquals + 1, sSectionID.length());

    //get all childnodes
    NodeList nlChilds = eRootSection.getChildNodes();
    for (int i = 0; i < nlChilds.getLength(); i++) {
        Node nCurrent = nlChilds.item(i);
        //white spaces not supported, so only element_node
        if (nCurrent.getNodeType() == Node.ELEMENT_NODE) {
            Element eCurrent = (Element) nCurrent;
            if (eCurrent.getNodeName().equalsIgnoreCase(sSectionType) && eCurrent.hasAttributes()) {
                //check if node has the strKey attribute and check if
                // its value = strvalue
                if (eCurrent.getAttribute(sKey).equalsIgnoreCase(sValue))
                    return eCurrent;
            }
        }
    }

    return null;
}

From source file:com.orient.lib.xbmc.addons.Addon.java

/**
 * Takes the ID of the addon and loads all properties from the corresponding
 * file structure.//from   www. ja v a2  s.  c o m
 * 
 * @param id
 * @return
 */
private boolean loadPropsByAddonId(String id) {

    if (!Addon.exists(id))
        return false;

    String path = Addon.getAddonXmlPath(id);

    if (path != null && !loadXMLDocument(path))
        return false;

    AddonProps props = new AddonProps();

    // Addon element
    //      Settings settings = Settings.getInstance();
    //      File addonDir = settings.getAddonDir();

    Element addonEl = document.getDocumentElement();

    if (addonEl == null || !addonEl.getNodeName().equals("addon"))
        return false;

    props.path = FilenameUtils.separatorsToSystem(Settings.getInstance().getAddonDirPath() + "\\" + id);

    props.id = XMLUtils.getAttribute(addonEl, "id");
    props.name = XMLUtils.getAttribute(addonEl, "name");
    props.version = XMLUtils.getAttribute(addonEl, "version");
    props.author = XMLUtils.getAttribute(addonEl, "provider-name");

    // extension element
    Element extensionEl = XMLUtils.getFirstChildElement(addonEl, "extension");

    while (extensionEl != null) {
        String point = XMLUtils.getAttribute(extensionEl, "point");

        if (point.equals("xbmc.addon.metadata")) {
            Element licenseEl = XMLUtils.getFirstChildElement(extensionEl, "license");

            if (licenseEl != null)
                props.license = licenseEl.getNodeValue();

            // TODO add other meta data
        } else {
            props.libname = XMLUtils.getAttribute(extensionEl, "library");
            props.type = getTranslateType(point);
        }

        extensionEl = XMLUtils.getNextSiblingElement(extensionEl, "extension");
    }

    // dependencies element
    Element requiresEl = XMLUtils.getFirstChildElement(addonEl, "requires");
    Element importEl = XMLUtils.getFirstChildElement(requiresEl, "import");

    while (importEl != null) {

        String addon = XMLUtils.getAttribute(importEl, "addon");

        if (addon != null)
            props.dependencies.add(addon);

        importEl = XMLUtils.getNextSiblingElement(importEl, "import");
    }

    this.props = props;

    return true;
}

From source file:com.nridge.core.base.io.xml.DocumentReplyXML.java

/**
 * Parses an XML DOM element and loads it into a document list.
 *
 * @param anElement DOM element.//from  w w w.  j  a va  2 s. c o m
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void load(Element anElement) throws IOException {
    Attr nodeAttr;
    Node nodeItem;
    Document document;
    Element nodeElement;
    DocumentXML documentXML;
    String nodeName, nodeValue;

    nodeName = anElement.getNodeName();
    if (StringUtils.equalsIgnoreCase(nodeName, IO.XML_REPLY_NODE_NAME)) {
        mField.clearFeatures();
        String attrValue = anElement.getAttribute(Doc.FEATURE_OP_STATUS_CODE);
        if (StringUtils.isNotEmpty(attrValue)) {
            mField.setName(Doc.FEATURE_OP_STATUS_CODE);
            mField.setValue(attrValue);
            NamedNodeMap namedNodeMap = anElement.getAttributes();
            int attrCount = namedNodeMap.getLength();
            for (int attrOffset = 0; attrOffset < attrCount; attrOffset++) {
                nodeAttr = (Attr) namedNodeMap.item(attrOffset);
                nodeName = nodeAttr.getNodeName();
                nodeValue = nodeAttr.getNodeValue();

                if (StringUtils.isNotEmpty(nodeValue)) {
                    if ((!StringUtils.equalsIgnoreCase(nodeName, Doc.FEATURE_OP_STATUS_CODE))
                            && (!StringUtils.equalsIgnoreCase(nodeName, Doc.FEATURE_OP_COUNT)))
                        mField.addFeature(nodeName, nodeValue);
                }
            }
        }
        NodeList nodeList = anElement.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            nodeItem = nodeList.item(i);

            if (nodeItem.getNodeType() != Node.ELEMENT_NODE)
                continue;

            // We really do not know how the node was named, so we will just accept it.

            nodeElement = (Element) nodeItem;
            documentXML = new DocumentXML();
            documentXML.load(nodeElement);
            document = documentXML.getDocument();
            if (document != null)
                mDocumentList.add(document);
        }
    }
}

From source file:app.MainPanel.java

private void parseLatestValues() {
    pozycje = new HashMap<>();

    try {//from  ww w .j  a v  a  2 s  .c  o  m
        File file = new File("temp.xml");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(file);

        document.getDocumentElement().normalize();

        NodeList nList = document.getElementsByTagName("tabela_kursow").item(0).getChildNodes();

        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;

                if ("pozycja".equals(eElement.getNodeName())) {
                    NodeList hList = eElement.getChildNodes();

                    HashMap tempList = readNodes(hList);

                    pozycje.put(tempList.get("kod_waluty").toString(), tempList);
                }
            }
        }
    } catch (ParserConfigurationException | SAXException | IOException ex) {
        Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:de.eorganization.hoopla.server.servlets.TemplateImportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    DecisionTemplate newDecisionTemplate = new DecisionTemplate();
    DecisionTemplate decisionTemplate = null;
    try {/*from w w  w  .  j  av a2 s  . c o  m*/

        ServletFileUpload upload = new ServletFileUpload();
        resp.setContentType("text/plain");

        FileItemIterator itemIterator = upload.getItemIterator(req);
        while (itemIterator.hasNext()) {
            FileItemStream item = itemIterator.next();
            if (item.isFormField() && "substituteTemplateId".equals(item.getFieldName())) {
                log.warning("Got a form field: " + item.getFieldName());

                String itemContent = IOUtils.toString(item.openStream());
                try {
                    decisionTemplate = new HooplaServiceImpl()
                            .getDecisionTemplate(new Long(itemContent).longValue());
                    new HooplaServiceImpl().deleteDecisionTemplate(decisionTemplate);
                } catch (Exception e) {
                    log.log(Level.WARNING, e.getLocalizedMessage(), e);
                }
                if (decisionTemplate == null)
                    newDecisionTemplate.setKeyId(new Long(itemContent).longValue());
                else
                    newDecisionTemplate.setKeyId(decisionTemplate.getKeyId());
            } else {
                InputStream stream = item.openStream();

                log.info("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());

                Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(stream);

                // doc.getDocumentElement().normalize();

                Element decisionElement = doc.getDocumentElement();
                String rootName = decisionElement.getNodeName();
                if (rootName.equals("decision")) {
                    isDecisionTemplate = false;
                } else if (rootName.equals("decisionTemplate")) {
                    isDecisionTemplate = true;
                } else {
                    log.warning("This XML Document has a wrong RootElement: " + rootName
                            + ". It should be <decision> or <decisionTemplate>.");
                }

                NodeList decisionNodes = decisionElement.getChildNodes();
                for (int i = 0; i < decisionNodes.getLength(); i++) {
                    Node node = decisionNodes.item(i);

                    if (node instanceof Element) {
                        Element child = (Element) node;
                        if (child.getNodeName().equals("name") && !child.getTextContent().equals("")) {
                            newDecisionTemplate.setName(child.getTextContent());
                            log.info("Parsed decision name: " + newDecisionTemplate.getName());
                        }
                        if (child.getNodeName().equals("description") && !child.getTextContent().equals("")) {
                            newDecisionTemplate.setDescription(child.getTextContent());
                            log.info("Parsed decision description: " + newDecisionTemplate.getDescription());
                        }
                        if (isDecisionTemplate && child.getNodeName().equals("templateName")) {
                            newDecisionTemplate.setTemplateName(child.getTextContent());
                            log.info("Parsed decision TemplateName: " + newDecisionTemplate.getTemplateName());
                        }
                        if (child.getNodeName().equals("alternatives")) {
                            parseAlternatives(child.getChildNodes(), newDecisionTemplate);
                        }
                        if (child.getNodeName().equals("goals")) {
                            parseGoals(child.getChildNodes(), newDecisionTemplate);
                        }
                        if (child.getNodeName().equals("importanceGoals")) {
                            parseGoalImportances(child.getChildNodes(), newDecisionTemplate);
                        }
                    }
                }

                log.info("Fully parsed XML Upload: " + newDecisionTemplate.toString());

            }
        }

    } catch (Exception ex) {
        log.log(Level.WARNING, ex.getLocalizedMessage(), ex);
        resp.sendError(400);
        return;
    }

    try {
        new HooplaServiceImpl().storeDecisionTemplate(newDecisionTemplate);
    } catch (Exception e) {
        log.log(Level.WARNING, e.getLocalizedMessage(), e);
        resp.sendError(500);
        return;
    }

    log.info("returning to referer " + req.getHeader("referer"));
    resp.sendRedirect(
            req.getHeader("referer") != null && !"".equals(req.getHeader("referer")) ? req.getHeader("referer")
                    : "localhost:8088");
}

From source file:de.interactive_instruments.etf.testdriver.te.TeTestTask.java

private void parseTestNgResult(final Document document) throws Exception {
    getLogger().info("Transforming results.");
    final Element result = document.getDocumentElement();
    if (!"testng-results".equals(result.getNodeName())) {
        throw new ParseException("Expected a TestNG result XML", document.getDocumentURI(), 0);
    }/*from  ww  w . ja va 2 s  .co m*/

    final String failedAssertions = XmlUtils.getAttribute(result, "failed");
    final String passedAssertions = XmlUtils.getAttribute(result, "passed");
    final Integer passedAssertionsInt = Integer.valueOf(passedAssertions);
    getLogger().info("{} of {} assertions passed", passedAssertionsInt,
            Integer.valueOf(passedAssertions + Integer.valueOf(failedAssertions)));

    final TestResultCollector resultCollector = getCollector();

    final Node suiteResult = XmlUtils.getFirstChildNodeOfType(result, ELEMENT_NODE, "suite");
    resultCollector.startTestTask(testTaskDto.getExecutableTestSuite().getId().getId(),
            getStartTimestamp(suiteResult));

    // Save result document as attachment
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final Source xmlSource = new DOMSource(document);
    final Result outputTarget = new StreamResult(outputStream);
    TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
    final InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    resultCollector.saveAttachment(inputStream, "TEAM Engine result", "text/xml", "TestNgResultXml");

    // Test Modules
    for (Node testModule = XmlUtils.getFirstChildNodeOfType(suiteResult, ELEMENT_NODE,
            "test"); testModule != null; testModule = XmlUtils.getNextSiblingOfType(testModule, ELEMENT_NODE,
                    "test")) {
        final String testModuleId = getItemID(testModule);
        resultCollector.startTestModule(testModuleId, getStartTimestamp(testModule));

        // Test Cases
        for (Node testCase = XmlUtils.getFirstChildNodeOfType(testModule, ELEMENT_NODE,
                "class"); testCase != null; testCase = XmlUtils.getNextSiblingOfType(testCase, ELEMENT_NODE,
                        "class")) {
            final String testCaseId = getItemID(testCase);

            // Get start timestamp from first test step
            final Node firstTestStep = XmlUtils.getFirstChildNodeOfType(testCase, ELEMENT_NODE, "test-method");
            if (firstTestStep != null) {
                resultCollector.startTestCase(testCaseId, getStartTimestamp(firstTestStep));
            } else {
                resultCollector.startTestCase(testCaseId);
            }
            long testCaseEndTimeStamp = 0;
            boolean testStepResultCollected = false;
            boolean oneSkippedOrNotApplicableConfigStepRecorded = false;

            // Test Steps (no Test Assertions are used)
            for (Node testStep = firstTestStep; testStep != null; testStep = XmlUtils
                    .getNextSiblingOfType(testStep, ELEMENT_NODE, "test-method")) {

                final long testStepEndTimestamp = getEndTimestamp(testStep);
                if (testCaseEndTimeStamp < testStepEndTimestamp) {
                    testCaseEndTimeStamp = testStepEndTimestamp;
                }

                final int status = mapStatus(testStep);
                final boolean configStep = "true"
                        .equals(XmlUtils.getAttributeOrDefault(testStep, "is-config", "false"));

                // output only failed steps or only one skipped or not applicable config test step
                if (!configStep || status == 1
                        || (!oneSkippedOrNotApplicableConfigStepRecorded && status == 2 || status == 3)) {
                    final long testStepStartTimestamp = getStartTimestamp(testStep);
                    final String testStepId = getItemID(testStep);
                    resultCollector.startTestStep(testStepId, testStepStartTimestamp);

                    final String message = getMessage(testStep);
                    if (!SUtils.isNullOrEmpty(message)) {
                        resultCollector.addMessage("TR.teamEngineError", "error", message);
                    }

                    // Attachments
                    for (Node attachments = XmlUtils.getFirstChildNodeOfType(testStep, ELEMENT_NODE,
                            "attributes"); attachments != null; attachments = XmlUtils
                                    .getNextSiblingOfType(attachments, ELEMENT_NODE, "attributes")) {
                        for (Node attachment = XmlUtils.getFirstChildNodeOfType(attachments, ELEMENT_NODE,
                                "attribute"); attachment != null; attachment = XmlUtils
                                        .getNextSiblingOfType(attachment, ELEMENT_NODE, "attribute")) {
                            final String type = XmlUtils.getAttribute(attachment, "name");
                            switch (type) {
                            case "response":
                                final String response = XmlUtils.nodeValue(attachment);
                                resultCollector.saveAttachment(IOUtils.toInputStream(response, "UTF-8"),
                                        "Service Response", XmlUtils.isWellFormed(response) ? "text/xml" : null,
                                        "ServiceResponse");
                                break;
                            case "request":
                                final String request = XmlUtils.nodeValue(attachment);
                                if (XmlUtils.isWellFormed(request)) {
                                    resultCollector.saveAttachment(
                                            IOUtils.toInputStream(XmlUtils.nodeValue(attachment), "UTF-8"),
                                            "Request Parameter", "text/xml", "PostData");
                                } else {
                                    resultCollector.saveAttachment(XmlUtils.nodeValue(attachment),
                                            "Request Parameter", "text/plain", "GetParameter");
                                }
                                break;
                            default:
                                resultCollector.saveAttachment(XmlUtils.nodeValue(attachment), type, null,
                                        type);
                            }
                        }
                    }
                    resultCollector.end(testStepId, status, testStepEndTimestamp);
                    if (configStep && (status == 2 || status == 3)) {
                        oneSkippedOrNotApplicableConfigStepRecorded = true;
                    }
                    testStepResultCollected = true;
                }
            }
            if (testStepResultCollected) {
                resultCollector.end(testCaseId, testCaseEndTimeStamp);
            } else {
                // only passed config steps collected,
                resultCollector.end(testCaseId, 0, testCaseEndTimeStamp);
            }
        }
        resultCollector.end(testModuleId, getEndTimestamp(testModule));
    }
    resultCollector.end(testTaskDto.getId().getId(), getEndTimestamp(suiteResult));
}

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

public static Object readObjectFromXml(Element node) throws Exception {
    String nodeName = node.getNodeName();
    String nodeValue = ((Element) node).getAttribute("value");

    if (nodeName.equals("java.lang.Boolean")) {
        return new Boolean(nodeValue);
    } else if (nodeName.equals("java.lang.Byte")) {
        return new Byte(nodeValue);
    } else if (nodeName.equals("java.lang.Character")) {
        return new Character(nodeValue.charAt(0));
    } else if (nodeName.equals("java.lang.Integer")) {
        return new Integer(nodeValue);
    } else if (nodeName.equals("java.lang.Double")) {
        return new Double(nodeValue);
    } else if (nodeName.equals("java.lang.Float")) {
        return new Float(nodeValue);
    } else if (nodeName.equals("java.lang.Long")) {
        return new Long(nodeValue);
    } else if (nodeName.equals("java.lang.Short")) {
        return new Short(nodeValue);
    } else if (nodeName.equals("java.lang.String")) {
        return nodeValue;
    } else if (nodeName.equals("array")) {
        String className = node.getAttribute("classname");
        String length = node.getAttribute("length");
        int len = (new Integer(length)).intValue();

        Object array;/*from   ww  w. j av  a  2 s  .  co m*/
        if (className.equals("byte")) {
            array = new byte[len];
        } else if (className.equals("boolean")) {
            array = new boolean[len];
        } else if (className.equals("char")) {
            array = new char[len];
        } else if (className.equals("double")) {
            array = new double[len];
        } else if (className.equals("float")) {
            array = new float[len];
        } else if (className.equals("int")) {
            array = new int[len];
        } else if (className.equals("long")) {
            array = new long[len];
        } else if (className.equals("short")) {
            array = new short[len];
        } else {
            array = Array.newInstance(Class.forName(className), len);
        }

        Node xmlNode = null;
        NodeList nl = node.getChildNodes();
        int len_nl = nl.getLength();
        int i = 0;
        for (int j = 0; j < len_nl; j++) {
            xmlNode = nl.item(j);
            if (xmlNode.getNodeType() == Node.ELEMENT_NODE) {
                Object o = XMLUtils.readObjectFromXml((Element) xmlNode);
                Array.set(array, i, o);
                i++;
            }
        }

        return array;
    }
    // XMLization
    else if (nodeName.equals("xmlizable")) {
        String className = node.getAttribute("classname");

        Node xmlNode = findChildNode(node, Node.ELEMENT_NODE);
        Object xmlizable = Class.forName(className).newInstance();
        ((XMLizable) xmlizable).readXml(xmlNode);

        return xmlizable;
    }
    // Serialization
    else if (nodeName.equals("serializable")) {
        Node cdata = findChildNode(node, Node.CDATA_SECTION_NODE);
        String objectSerializationData = cdata.getNodeValue();
        Engine.logEngine.debug("Object serialization data:\n" + objectSerializationData);
        byte[] objectBytes = org.apache.commons.codec.binary.Base64.decodeBase64(objectSerializationData);

        // We read the object to a bytes array
        ByteArrayInputStream inputStream = new ByteArrayInputStream(objectBytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        Object object = objectInputStream.readObject();
        inputStream.close();

        return object;
    }

    return null;
}

From source file:com.github.dozermapper.core.loader.xml.XMLParser.java

/**
 * Builds object representation of mappings based on content of Xml document
 *
 * @return mapping container/*from w  w w  .  j  av a  2s  . co  m*/
 */
public MappingFileData read(Document document) {
    DozerBuilder builder = new DozerBuilder(beanContainer, destBeanCreator, propertyDescriptorFactory);

    Element theRoot = document.getDocumentElement();
    NodeList nl = theRoot.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element ele = (Element) node;
            log.debug("name: {}", ele.getNodeName());
            if (CONFIGURATION_ELEMENT.equals(ele.getNodeName())) {
                parseConfiguration(ele, builder);
            } else if (MAPPING_ELEMENT.equals(ele.getNodeName())) {
                parseMapping(ele, builder);
            }
        }
    }

    return builder.build();
}