Example usage for org.w3c.dom Element hasChildNodes

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

Introduction

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

Prototype

public boolean hasChildNodes();

Source Link

Document

Returns whether this node has any children.

Usage

From source file:lcmc.data.VMSXML.java

/** Add CPU match node. */
private void addCPUMatchNode(final Document doc, final Node root, final Map<String, String> parametersMap) {
    final String cpuMatch = parametersMap.get(VM_PARAM_CPU_MATCH);
    final Element cpuMatchNode = (Element) root.appendChild(doc.createElement("cpu"));
    if (!"".equals(cpuMatch)) {
        cpuMatchNode.setAttribute("match", cpuMatch);
    }/*from  w w w.j a va2s. co  m*/
    final String model = parametersMap.get(VM_PARAM_CPUMATCH_MODEL);
    if (!"".equals(model)) {
        final Node modelNode = (Element) cpuMatchNode.appendChild(doc.createElement("model"));
        modelNode.appendChild(doc.createTextNode(model));
    }
    final String vendor = parametersMap.get(VM_PARAM_CPUMATCH_VENDOR);
    if (!"".equals(vendor)) {
        final Node vendorNode = (Element) cpuMatchNode.appendChild(doc.createElement("vendor"));
        vendorNode.appendChild(doc.createTextNode(vendor));
    }
    final String sockets = parametersMap.get(VM_PARAM_CPUMATCH_TOPOLOGY_SOCKETS);
    final String cores = parametersMap.get(VM_PARAM_CPUMATCH_TOPOLOGY_CORES);
    final String threads = parametersMap.get(VM_PARAM_CPUMATCH_TOPOLOGY_THREADS);
    final boolean isSockets = !"".equals(sockets);
    final boolean isCores = !"".equals(cores);
    final boolean isThreads = !"".equals(threads);
    if (isSockets || isCores || isThreads) {
        final Element topologyNode = (Element) cpuMatchNode.appendChild(doc.createElement("topology"));
        if (isSockets) {
            topologyNode.setAttribute("sockets", sockets);
        }
        if (isCores) {
            topologyNode.setAttribute("cores", cores);
        }
        if (isThreads) {
            topologyNode.setAttribute("threads", threads);
        }
    }
    final String policy = parametersMap.get(VM_PARAM_CPUMATCH_FEATURE_POLICY);
    final String features = parametersMap.get(VM_PARAM_CPUMATCH_FEATURES);
    if (!"".equals(policy) && !"".equals(features)) {
        for (final String feature : features.split("\\s+")) {
            final Element featureNode = (Element) cpuMatchNode.appendChild(doc.createElement("feature"));
            featureNode.setAttribute("policy", policy);
            featureNode.setAttribute("name", feature);
        }
    }
    if (!cpuMatchNode.hasChildNodes()) {
        root.removeChild(cpuMatchNode);

    }
}

From source file:org.gvnix.web.menu.roo.addon.MenuEntryOperationsImpl.java

/**
 * Gets the selected info about the given menu entry Element.
 * <p>// w ww. j a va 2 s .  c  o  m
 * TODO: I think compact info better. See section "List menu structure" at
 * "docs/pd-addon-web-menu.rst". Note, it means we should refactor this
 * method in 2 methods: on for list command and other for info command
 * 
 * @param element
 * @param label
 * @param messageCode
 * @param destination
 * @param roles
 * @param tabSize
 * @return
 */
private String getFormatedInfo(Element element, boolean label, boolean message, boolean roles, I18n lang,
        int tabSize) {
    StringBuilder builder = new StringBuilder();
    StringBuilder indent = new StringBuilder();

    // tab string to align children
    for (int i = 0; i < tabSize; i++) {
        indent.append(" ");
    }

    // string containing "[ID]: "
    StringBuilder idInfo = new StringBuilder();
    idInfo.append("[").append(element.getAttribute("id")).append("]");

    // build Element info
    builder.append(indent).append(idInfo).append("\n");

    String url = element.getAttribute(URL);
    if (!StringUtils.isNotBlank(url)) {
        url = "No";
    }
    builder.append(indent).append("URL          : ").append(url).append("\n");

    if (label) {
        String labelCode = element.getAttribute(LABEL_CODE);
        String labelValue = null;

        // get label text from application.properties
        if (StringUtils.isNotBlank(labelCode)) {
            labelValue = propFileOperations.getProperty(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
                    "/WEB-INF/i18n/application.properties", labelCode);
        }
        builder.append(indent).append("Label Code   : ").append(labelCode).append("\n");
        builder.append(indent).append("Label        : ").append(labelValue != null ? labelValue : "")
                .append("\n");
    }
    if (message) {
        String messageCode = element.getAttribute(MESSAGE_CODE);
        String messageValue = null;

        // get message text from messages.properties
        if (StringUtils.isNotBlank(messageCode)) {

            if (lang != null) {
                String messageBundle = "/WEB-INF/i18n/messages_".concat(lang.getLocale().toString())
                        .concat(".properties");
                messageValue = propFileOperations.getProperty(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
                        messageBundle, messageCode);
            }

            // if no value for given lang, try default lang
            if (!StringUtils.isNotBlank(messageValue)) {
                String messageBundle = "/WEB-INF/i18n/messages.properties";
                messageValue = propFileOperations.getProperty(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
                        messageBundle, messageCode);
            }
        }
        builder.append(indent).append("Message Code : ").append(element.getAttribute(MESSAGE_CODE))
                .append("\n");
        builder.append(indent).append("Message      : ").append(messageValue != null ? messageValue : "")
                .append("\n");
    }
    if (roles) {
        builder.append(indent).append("Roles        : ").append(element.getAttribute("roles")).append("\n");
    }

    String hidden = element.getAttribute(HIDDEN);
    if (!StringUtils.isNotBlank(hidden)) {
        hidden = "false"; // visible by default
    }
    builder.append(indent).append("Hidden       : ").append(hidden).append("\n");

    // get children info
    if (element.hasChildNodes()) {
        builder.append(indent).append("Children     : ").append("\n");
        builder.append(getFormatedInfo(element.getChildNodes(), label, message, roles, lang, tabSize + 15)); // indent to the right
                                                                                                             // of
                                                                                                             // "Children     : "
                                                                                                             // (length 15 chars)
    } else {
        builder.append("\n"); // empty line
    }
    return builder.toString();
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

private void addElement(SOAPMessage responseMessage, SOAPEnvelope soapEnvelope, Context context,
        Element elementToAdd, SOAPElement soapElement) throws SOAPException {
    SOAPElement soapMethodResponseElement = (SOAPElement) soapEnvelope.getBody().getFirstChild();
    String targetNamespace = soapMethodResponseElement.getNamespaceURI();
    String prefix = soapMethodResponseElement.getPrefix();

    String nodeType = elementToAdd.getAttribute("type");
    SOAPElement childSoapElement = soapElement;

    boolean elementAdded = true;
    boolean bTable = false;

    if (nodeType.equals("table")) {
        bTable = true;//from   w w  w  .ja v  a2  s.  com
        /*childSoapElement = soapElement.addChildElement("ArrayOf" + context.transactionName + "_" + tableName + "_Row", "");
                
           if (!context.httpServletRequest.getServletPath().endsWith(".wsl")) {
              childSoapElement.addAttribute(soapEnvelope.createName("xsi:type"), "soapenc:Array");
           }*/
        childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());
    } else if (nodeType.equals("row")) {
        /*String elementType = context.transactionName + "_" + tableName + "_Row";
        childSoapElement = soapElement.addChildElement(elementType, "");*/
        childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());
    } else if (nodeType.equals("attachment")) {
        childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());

        if (context.requestedObject instanceof AbstractHttpTransaction) {
            AttachmentDetails attachment = AttachmentManager.getAttachment(elementToAdd);
            if (attachment != null) {
                byte[] raw = attachment.getData();
                if (raw != null)
                    childSoapElement.addTextNode(Base64.encodeBase64String(raw));
            }

            /* DON'T WORK YET *\
            AttachmentPart ap = responseMessage.createAttachmentPart(new ByteArrayInputStream(raw), elementToAdd.getAttribute("content-type"));
            ap.setContentId(key);
            ap.setContentLocation(elementToAdd.getAttribute("url"));
            responseMessage.addAttachmentPart(ap);
            \* DON'T WORK YET */
        }
    } else {
        String elementNodeName = elementToAdd.getNodeName();
        String elementNodeNsUri = elementToAdd.getNamespaceURI();
        String elementNodePrefix = getPrefix(context.projectName, elementNodeNsUri);

        XmlSchemaElement xmlSchemaElement = getXmlSchemaElementByName(context.projectName, elementNodeName);
        boolean isGlobal = xmlSchemaElement != null;
        if (isGlobal) {
            elementNodeNsUri = xmlSchemaElement.getQName().getNamespaceURI();
            elementNodePrefix = getPrefix(context.projectName, elementNodeNsUri);
        }

        // ignore original SOAP message response elements
        //         if ((elementNodeName.toUpperCase().indexOf("SOAP-ENV:") != -1) || ((elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("SOAP-ENV:") != -1)) ||
        //            (elementNodeName.toUpperCase().indexOf("SOAPENV:") != -1) || ((elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("SOAPENV:") != -1)) ||
        //            (elementNodeName.toUpperCase().indexOf("NS0:") != -1) || ((elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1))) {
        //            elementAdded = false;
        //         }
        if ("http://schemas.xmlsoap.org/soap/envelope/".equals(elementToAdd.getNamespaceURI())
                || "http://schemas.xmlsoap.org/soap/envelope/"
                        .equals(elementToAdd.getParentNode().getNamespaceURI())
                || elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1
                || elementNodeName.toUpperCase().indexOf("NS0:") != -1) {
            elementAdded = false;
        } else {
            if (XsdForm.qualified == context.project.getSchemaElementForm() || isGlobal) {
                if (elementNodePrefix == null) {
                    childSoapElement = soapElement
                            .addChildElement(soapEnvelope.createName(elementNodeName, prefix, targetNamespace));
                } else {
                    childSoapElement = soapElement.addChildElement(
                            soapEnvelope.createName(elementNodeName, elementNodePrefix, elementNodeNsUri));
                }
            } else {
                childSoapElement = soapElement.addChildElement(elementNodeName);
            }
        }
    }

    if (elementAdded && elementToAdd.hasAttributes()) {
        addAttributes(responseMessage, soapEnvelope, context, elementToAdd.getAttributes(), childSoapElement);
    }

    if (elementToAdd.hasChildNodes()) {
        NodeList childNodes = elementToAdd.getChildNodes();
        int len = childNodes.getLength();

        if (bTable) {
            /*if (!context.httpServletRequest.getServletPath().endsWith(".wsl")) {
               childSoapElement.addAttribute(soapEnvelope.createName("soapenc:arrayType"), context.projectName+"_ns:" + context.transactionName + "_" + tableName + "_Row[" + (len - 1) + "]");
            }*/
        }

        org.w3c.dom.Node node;
        Element childElement;
        for (int i = 0; i < len; i++) {
            node = childNodes.item(i);
            switch (node.getNodeType()) {
            case org.w3c.dom.Node.ELEMENT_NODE:
                childElement = (Element) node;
                addElement(responseMessage, soapEnvelope, context, childElement, childSoapElement);
                break;
            case org.w3c.dom.Node.CDATA_SECTION_NODE:
            case org.w3c.dom.Node.TEXT_NODE:
                String text = node.getNodeValue();
                text = (text == null) ? "" : text;
                childSoapElement.addTextNode(text);
                break;
            default:
                break;
            }
        }

        /*org.w3c.dom.Node node;
        Element childElement;
        for (int i = 0 ; i < len ; i++) {
           node = childNodes.item(i);
           if (node instanceof Element) {
              childElement = (Element) node;
              addElement(responseMessage, soapEnvelope, context, childElement, childSoapElement);
           }
           else if (node instanceof CDATASection) {
              Node textNode = XMLUtils.findChildNode(elementToAdd, org.w3c.dom.Node.CDATA_SECTION_NODE);
              String text = textNode.getNodeValue();
              if (text == null) {
          text = "";
              }
              childSoapElement.addTextNode(text);
           }
           else {
              Node textNode = XMLUtils.findChildNode(elementToAdd, org.w3c.dom.Node.TEXT_NODE);
              if (textNode != null) {
          String text = textNode.getNodeValue();
          if (text == null) {
             text = "";
          }
          childSoapElement.addTextNode(text);
              }
           }
        }*/
    }
}

From source file:no.sesat.search.query.analyser.AnalysisRuleFactory.java

private Predicate readPredicate(final Element element, final Map<String, Predicate> predicateMap,
        final Map<String, Predicate> inheritedPredicates) {

    Predicate result = null;//from   w  w w .  j a v  a2 s .  co m

    final boolean hasId = element.hasAttribute("id");
    final boolean hasContent = element.hasChildNodes();

    if (hasId && !hasContent) {
        // it's an already defined predicate
        final String id = element.getAttribute("id");

        result = findPredicate(id, predicateMap, inheritedPredicates);

    } else {
        // we must create it
        final NodeList operators = element.getChildNodes();
        for (int i = 0; i < operators.getLength(); ++i) {
            final Node operator = operators.item(i);
            if (operator != null && operator instanceof Element) {

                result = createPredicate((Element) operator, predicateMap, inheritedPredicates);
                break;
            }
        }

        if (hasId) {
            // its got an ID so we must remember it.
            final String id = element.getAttribute("id");
            predicateMap.put(id, result);
            LOG.debug(DEBUG_CREATED_PREDICATE + id + " " + result);
        }
    }

    return result;
}

From source file:openblocks.yacodeblocks.BlockSaveFileTest.java

private void assertElementContainsOnlyAsciiCharacters(Element element) throws Exception {
    assertStringContainsOnlyAsciiCharacters(element.getNodeName(), "name", element);

    if (element.hasAttributes()) {
        NamedNodeMap attributes = element.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            assertNodeContainsOnlyAsciiCharacters(attributes.item(i));
        }/*w w w . ja v  a 2  s  .c  om*/
    }

    if (element.hasChildNodes()) {
        NodeList childNodes = element.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            assertNodeContainsOnlyAsciiCharacters(childNodes.item(i));
        }
    }
}

From source file:opendial.modules.core.RemoteConnector.java

/**
 * Sends the updated variables through the socket connection.
 *///from  w w w  .  ja v  a 2 s  . c  om
@Override
public void trigger(DialogueState state, Collection<String> updatedVars) {
    if (skipNextTrigger) {
        skipNextTrigger = false;
        return;
    } else if (paused || system.getSettings().remoteConnections.isEmpty()) {
        return;
    }
    try {
        // creating an XML document with the updated variables
        Document xmlDoc = XMLUtils.newXMLDocument();
        Element root = xmlDoc.createElement("update");
        xmlDoc.appendChild(root);
        updatedVars.stream().filter(v -> state.hasChanceNode(v))
                .filter(v -> !v.equals(system.getSettings().userSpeech))
                .map(v -> state.queryProb(v).generateXML(xmlDoc)).forEach(n -> root.appendChild(n));

        // if the resulting document is non-empty, forward it through the socket
        if (root.hasChildNodes()) {
            InputStream content = IOUtils.toInputStream(XMLUtils.serialise(xmlDoc));
            forwardContent(MessageType.XML, content);
            return;
        }

        // if the content is a user speech signal, send it as a stream
        String speechVar = system.getSettings().userSpeech;
        if (updatedVars.contains(speechVar) && system.getState().hasChanceNode(speechVar)) {
            Value val = system.getContent(speechVar).toDiscrete().getBest();
            if (val instanceof SpeechStream) {
                forwardContent(MessageType.STREAM, (SpeechStream) val);
            }
        }
    } catch (DialException e) {
        log.warning("cannot update remote connector: " + e);
    }
}

From source file:org.apache.axis.message.MessageElement.java

protected String getValueDOM() {
    try {/*w  ww . j a  va 2 s. c om*/
        Element element = getAsDOM();
        if (element.hasChildNodes()) {
            Node node = element.getFirstChild();
            if (node.getNodeType() == Node.TEXT_NODE) {
                return node.getNodeValue();
            }
        }
    } catch (Exception t) {
        log.debug("getValue()", t);
    }
    return null;
}

From source file:org.apache.beehive.netui.util.config.internal.catalog.CatalogParser.java

private static CatalogConfig parseCatalog(Element catalogElement) {
    CatalogConfig catalogConfig = null;// ww  w. j av a2 s. c  om
    if (catalogElement != null && catalogElement.hasChildNodes()) {
        catalogConfig = new CatalogConfig();
        NodeList nodeList = catalogElement.getChildNodes();
        if (nodeList != null) {
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (!(node.getNodeType() == Node.ELEMENT_NODE))
                    continue;

                if (node.getNodeName().equals("chain")) {
                    Element element = (Element) node;
                    String name = element.getAttribute("name");
                    ChainConfig chainConfig = new ChainConfig();
                    chainConfig.setName(name);

                    NodeList commandList = element.getElementsByTagName("command");
                    if (commandList != null) {
                        for (int j = 0; j < commandList.getLength(); j++) {
                            Element commandElement = (Element) commandList.item(j);
                            CommandConfig commandConfig = parseCommand(commandElement);
                            chainConfig.addCommand(commandConfig);
                        }
                    }
                    catalogConfig.addCommand(chainConfig);
                } else if (node.getNodeName().equals("command")) {
                    Element element = (Element) node;
                    CommandConfig commandConfig = parseCommand(element);
                    catalogConfig.addCommand(commandConfig);
                }
            }
        }
    }

    return catalogConfig;
}

From source file:org.apache.hadoop.conf.Configuration.java

private void loadResource(Properties properties, Object name, boolean quiet) {
    try {// w ww  .jav  a  2s  .  c  o m
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        //ignore all comments inside the xml file
        docBuilderFactory.setIgnoringComments(true);

        //allow includes in the xml file
        docBuilderFactory.setNamespaceAware(true);
        try {
            docBuilderFactory.setXIncludeAware(true);
        } catch (UnsupportedOperationException e) {
            LOG.error("Failed to set setXIncludeAware(true) for parser " + docBuilderFactory + ":" + e, e);
        }
        DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        Document doc = null;
        Element root = null;

        if (name instanceof URL) { // an URL resource
            URL url = (URL) name;
            if (url != null) {
                if (!quiet) {
                    LOG.info("parsing " + url);
                }
                doc = builder.parse(url.toString());
            }
        } else if (name instanceof String) { // a CLASSPATH resource
            URL url = getResource((String) name);
            if (url != null) {
                if (!quiet) {
                    LOG.info("parsing " + url);
                }
                doc = builder.parse(url.toString());
            }
        } else if (name instanceof Path) { // a file resource
            // Can't use FileSystem API or we get an infinite loop
            // since FileSystem uses Configuration API.  Use java.io.File instead.
            File file = new File(((Path) name).toUri().getPath()).getAbsoluteFile();
            if (file.exists()) {
                if (!quiet) {
                    LOG.info("parsing " + file);
                }
                InputStream in = new BufferedInputStream(new FileInputStream(file));
                try {
                    doc = builder.parse(in);
                } finally {
                    in.close();
                }
            }
        } else if (name instanceof InputStream) {
            try {
                doc = builder.parse((InputStream) name);
            } finally {
                ((InputStream) name).close();
            }
        } else if (name instanceof Element) {
            root = (Element) name;
        }

        if (doc == null && root == null) {
            if (quiet)
                return;
            throw new RuntimeException(name + " not found");
        }

        if (root == null) {
            root = doc.getDocumentElement();
        }
        if (!"configuration".equals(root.getTagName()))
            LOG.fatal("bad conf file: top-level element not <configuration>");
        NodeList props = root.getChildNodes();
        for (int i = 0; i < props.getLength(); i++) {
            Node propNode = props.item(i);
            if (!(propNode instanceof Element))
                continue;
            Element prop = (Element) propNode;
            if ("configuration".equals(prop.getTagName())) {
                loadResource(properties, prop, quiet);
                continue;
            }
            if (!"property".equals(prop.getTagName()))
                LOG.warn("bad conf file: element not <property>");
            NodeList fields = prop.getChildNodes();
            String attr = null;
            String value = null;
            boolean finalParameter = false;
            for (int j = 0; j < fields.getLength(); j++) {
                Node fieldNode = fields.item(j);
                if (!(fieldNode instanceof Element))
                    continue;
                Element field = (Element) fieldNode;
                if ("name".equals(field.getTagName()) && field.hasChildNodes())
                    attr = ((Text) field.getFirstChild()).getData().trim();
                if ("value".equals(field.getTagName()) && field.hasChildNodes())
                    value = ((Text) field.getFirstChild()).getData();
                if ("final".equals(field.getTagName()) && field.hasChildNodes())
                    finalParameter = "true".equals(((Text) field.getFirstChild()).getData());
            }

            // Ignore this parameter if it has already been marked as 'final'
            if (attr != null) {
                if (value != null) {
                    if (!finalParameters.contains(attr)) {
                        properties.setProperty(attr, value);
                        if (storeResource) {
                            updatingResource.put(attr, name.toString());
                        }
                    } else if (!value.equals(properties.getProperty(attr))) {
                        LOG.warn(name + ":a attempt to override final parameter: " + attr + ";  Ignoring.");
                    }
                }
                if (finalParameter) {
                    finalParameters.add(attr);
                }
            }
        }

    } catch (IOException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    } catch (DOMException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    } catch (SAXException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.hadoop.hbase.mapred.IndexConfiguration.java

private void propertyFromXML(Element prop, Properties properties) {
    NodeList fields = prop.getChildNodes();
    String attr = null;/* www  . ja v  a2  s  .c o m*/
    String value = null;

    for (int j = 0; j < fields.getLength(); j++) {
        Node fieldNode = fields.item(j);
        if (!(fieldNode instanceof Element)) {
            continue;
        }

        Element field = (Element) fieldNode;
        if ("name".equals(field.getTagName())) {
            attr = ((Text) field.getFirstChild()).getData();
        }
        if ("value".equals(field.getTagName()) && field.hasChildNodes()) {
            value = ((Text) field.getFirstChild()).getData();
        }
    }

    if (attr != null && value != null) {
        if (properties == null) {
            set(attr, value);
        } else {
            properties.setProperty(attr, value);
        }
    }
}