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:org.apache.tuscany.sca.implementation.bpel.ode.ODEExternalService.java

/**
 * Get payload from a given ODEMessage//from  www  .  j a  v a  2s  .c  o  m
 * @param odeMessage - the ODE message
 * @return the payload of the Message, as a DOM Element
 */
private Element getPayload(Message odeMessage) {
    Element payload = null;

    // Get the message parts - these correspond to the message parts for the invocation
    // as defined in the WSDL for the service operation being invoked
    List<String> parts = odeMessage.getParts();
    if (parts.size() == 0)
        return null;

    // For the present, just deal with the ** FIRST ** part
    // TODO Deal with operations that have messages with multiple parts
    // - that will require returning an array of Elements, one for each part      
    Element part = odeMessage.getPart(parts.get(0));

    // Get the payload which is the First child 
    if (part != null && part.hasChildNodes()) {
        payload = (Element) part.getFirstChild();
    }

    return payload;
}

From source file:org.apache.xml.security.utils.XMLUtils.java

/**
 * This is the work horse for {@link #circumventBug2650}.
 *
 * @param node//  ww w .  j av a2  s  .  c  o m
 * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
 * Namespace axis resolution is not XPath compliant </A>
 */
private static void circumventBug2650internal(Node node) {
    Node parent = null;
    Node sibling = null;
    final String namespaceNs = Constants.NamespaceSpecNS;
    do {
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE:
            Element element = (Element) node;
            if (!element.hasChildNodes()) {
                break;
            }
            if (element.hasAttributes()) {
                NamedNodeMap attributes = element.getAttributes();
                int attributesLength = attributes.getLength();

                for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {

                    if (child.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    Element childElement = (Element) child;

                    for (int i = 0; i < attributesLength; i++) {
                        Attr currentAttr = (Attr) attributes.item(i);
                        if (!namespaceNs.equals(currentAttr.getNamespaceURI()))
                            continue;
                        if (childElement.hasAttributeNS(namespaceNs, currentAttr.getLocalName())) {
                            continue;
                        }
                        childElement.setAttributeNS(namespaceNs, currentAttr.getName(),
                                currentAttr.getNodeValue());
                    }
                }
            }
        case Node.ENTITY_REFERENCE_NODE:
            parent = node;
            sibling = node.getFirstChild();
            break;
        case Node.DOCUMENT_NODE:
            parent = node;
            sibling = node.getFirstChild();
            break;
        }
        while ((sibling == null) && (parent != null)) {
            sibling = parent.getNextSibling();
            parent = parent.getParentNode();
        }
        if (sibling == null) {
            return;
        }

        node = sibling;
        sibling = node.getNextSibling();
    } while (true);
}

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

private Resource loadResource(Properties properties, Resource wrapper, boolean quiet) {
    String name = UNKNOWN_RESOURCE;
    try {// www .ja  v a2 s .  com
        Object resource = wrapper.getResource();
        name = wrapper.getName();

        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;
        boolean returnCachedProperties = false;

        if (resource instanceof URL) { // an URL resource
            doc = parse(builder, (URL) resource);
        } else if (resource instanceof String) { // a CLASSPATH resource
            URL url = getResource((String) resource);
            doc = parse(builder, url);
        } else if (resource 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) resource).toUri().getPath()).getAbsoluteFile();
            if (file.exists()) {
                if (!quiet) {
                    LOG.debug("parsing File " + file);
                }
                doc = parse(builder, new BufferedInputStream(new FileInputStream(file)),
                        ((Path) resource).toString());
            }
        } else if (resource instanceof InputStream) {
            doc = parse(builder, (InputStream) resource, null);
            returnCachedProperties = true;
        } else if (resource instanceof Properties) {
            overlay(properties, (Properties) resource);
        } else if (resource instanceof Element) {
            root = (Element) resource;
        }

        if (root == null) {
            if (doc == null) {
                if (quiet) {
                    return null;
                }
                throw new RuntimeException(resource + " not found");
            }
            root = doc.getDocumentElement();
        }
        Properties toAddTo = properties;
        if (returnCachedProperties) {
            toAddTo = new Properties();
        }
        if (!"configuration".equals(root.getTagName())) {
            LOG.fatal("bad conf file: top-level element not <configuration>");
        }
        NodeList props = root.getChildNodes();
        DeprecationContext deprecations = deprecationContext.get();
        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(toAddTo, new Resource(prop, name), 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;
            LinkedList<String> source = new LinkedList<String>();
            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 = StringInterner.weakIntern(((Text) field.getFirstChild()).getData().trim());
                }
                if ("value".equals(field.getTagName()) && field.hasChildNodes()) {
                    value = StringInterner.weakIntern(((Text) field.getFirstChild()).getData());
                }
                if ("final".equals(field.getTagName()) && field.hasChildNodes()) {
                    finalParameter = "true".equals(((Text) field.getFirstChild()).getData());
                }
                if ("source".equals(field.getTagName()) && field.hasChildNodes()) {
                    source.add(StringInterner.weakIntern(((Text) field.getFirstChild()).getData()));
                }
            }
            source.add(name);

            // Ignore this parameter if it has already been marked as 'final'
            if (attr != null) {
                if (deprecations.getDeprecatedKeyMap().containsKey(attr)) {
                    DeprecatedKeyInfo keyInfo = deprecations.getDeprecatedKeyMap().get(attr);
                    keyInfo.clearAccessed();
                    for (String key : keyInfo.newKeys) {
                        // update new keys with deprecated key's value
                        loadProperty(toAddTo, name, key, value, finalParameter,
                                source.toArray(new String[source.size()]));
                    }
                } else {
                    loadProperty(toAddTo, name, attr, value, finalParameter,
                            source.toArray(new String[source.size()]));
                }
            }
        }

        if (returnCachedProperties) {
            overlay(properties, toAddTo);
            return new Resource(toAddTo, name);
        }
        return null;
    } catch (IOException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    } catch (DOMException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    } catch (SAXException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    }
}

From source file:org.cauldron.einstein.ri.core.model.data.xml.dom.DOMUtil.java

@Post
@Pre/*  w  w  w  .ja va  2  s . c om*/
public static DocumentFragment buildFragmentFromNode(DocumentBuilder docBuilder, Node node)
        throws IOException, TransformerException, SAXException {
    Document doc;
    DocumentFragment fragment;
    /*
    I know this is convoluted but it's very difficult to actually add a bunch of random nodes to
    a document fragment without getting errors. XML DOM APIs are bloomin sketchy so this guarantees
    that the node can be added.  Need to throw this rubbish away and use a better XML API really.
     */
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byteArrayOutputStream.write("<dummy>".getBytes());
    Transformer xformer = transformerFactory.newTransformer();
    xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    Source source = new DOMSource(node);
    Result result = new StreamResult(byteArrayOutputStream);
    xformer.transform(source, result);
    byteArrayOutputStream.write("</dummy>".getBytes());

    log.debug("Dumy node {0}.", byteArrayOutputStream);

    doc = docBuilder.parse(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
    fragment = doc.createDocumentFragment();
    final Element element = doc.getDocumentElement();
    if (element.hasChildNodes()) {
        //has child nodes, not text.
        NodeList nodeList = element.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            log.debug("Moving temporary node.");
            final Node newNode = nodeList.item(i);
            doc.adoptNode(newNode);
            fragment.appendChild(newNode);
        }
    }

    log.debug("Fragment is now {0}.", ReflectionToStringBuilder.reflectionToString(fragment));
    return fragment;
}

From source file:org.cloudata.core.common.conf.CloudataConf.java

private void loadResource(Properties properties, Object name, boolean quiet) {
    try {/*from ww  w  .ja  v a  2  s  .  co  m*/
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = 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 GPath) { // 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(((GPath) 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();
                }
            }
        }

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

        Element 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 (!"property".equals(prop.getTagName()))
                LOG.warn("bad conf file: element not <property>");
            NodeList fields = prop.getChildNodes();
            String attr = null;
            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) {
                properties.setProperty(attr, value);
            }
        }

    } catch (Exception e) {
        e.printStackTrace(System.out);
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    }

}

From source file:org.dita.dost.reader.ChunkMapReader.java

private void processTopicref(final Element topicref) {
    final String xtrfValue = getValue(topicref, ATTRIBUTE_NAME_XTRF);
    if (xtrfValue != null && xtrfValue.contains(ATTR_XTRF_VALUE_GENERATED)) {
        return;/* w ww  .j  a  v  a  2  s .co  m*/
    }

    final Collection<String> chunkValue = split(getValue(topicref, ATTRIBUTE_NAME_CHUNK));

    if (topicref.getAttributeNode(ATTRIBUTE_NAME_HREF) == null && chunkValue.contains(CHUNK_TO_CONTENT)) {
        generateStumpTopic(topicref);
    }

    final URI hrefValue = toURI(getValue(topicref, ATTRIBUTE_NAME_HREF));
    final URI copytoValue = toURI(getValue(topicref, ATTRIBUTE_NAME_COPY_TO));
    final String scopeValue = getCascadeValue(topicref, ATTRIBUTE_NAME_SCOPE);
    final String chunkByToken = getChunkByToken(chunkValue, "by-", defaultChunkByToken);

    if (ATTR_SCOPE_VALUE_EXTERNAL.equals(scopeValue)
            || (hrefValue != null && !resolve(fileDir, hrefValue.toString()).exists())
            || (chunkValue.isEmpty() && hrefValue == null)) {
        processChildTopicref(topicref);
    } else if (chunkValue.contains(CHUNK_TO_CONTENT)
            && (hrefValue != null || copytoValue != null || topicref.hasChildNodes())) {
        if (chunkValue.contains(CHUNK_BY_TOPIC)) {
            logger.warn(MessageUtils.getInstance().getMessage("DOTJ064W").setLocation(topicref).toString());
        }
        processChunk(topicref, false);
    } else if (chunkValue.contains(CHUNK_TO_NAVIGATION) && supportToNavigation) {
        processChildTopicref(topicref);
        processNavitation(topicref);
    } else if (chunkByToken.equals(CHUNK_BY_TOPIC)) {
        processChunk(topicref, true);
        processChildTopicref(topicref);
    } else { // chunkByToken.equals(CHUNK_BY_DOCUMENT)
        String currentPath = null;
        if (copytoValue != null) {
            currentPath = resolve(fileDir, copytoValue).getPath();
        } else if (hrefValue != null) {
            currentPath = resolve(fileDir, hrefValue).getPath();
        }
        if (currentPath != null) {
            if (changeTable.containsKey(currentPath)) {
                changeTable.remove(currentPath);
            }
            final String processingRole = getCascadeValue(topicref, ATTRIBUTE_NAME_PROCESSING_ROLE);
            if (!ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(processingRole)) {
                changeTable.put(currentPath, currentPath);
            }
        }
        processChildTopicref(topicref);
    }
}

From source file:org.dita.dost.reader.ChunkMapReader.java

/**
 * get topicmeta's child(e.g navtitle, shortdesc) tag's value(text-only).
 * @param element input element/*from www.j  ava 2  s . c om*/
 * @return text value
 */
private String getChildElementValueOfTopicmeta(final Element element, final DitaClass classValue) {
    if (element.hasChildNodes()) {
        final Element topicMeta = getElementNode(element, MAP_TOPICMETA);
        if (topicMeta != null) {
            final Element elem = getElementNode(topicMeta, classValue);
            if (elem != null) {
                return getText(elem);
            }
        }
    }
    return null;
}

From source file:org.etudes.tool.melete.ViewSectionsPage.java

private Node getNextNode(Element secElement) {
    if (secElement.hasChildNodes()) {
        return secElement.getFirstChild();
    } else {/*w w w  .  ja va 2s  .c  om*/
        if (secElement.getNextSibling() != null) {
            return secElement.getNextSibling();
        } else {
            if (secElement.getParentNode() != null) {
                if (secElement.getParentNode().getNodeName().equals("module")) {
                    return null;
                } else {
                    return getParentsNextSibling(secElement);
                }
            } else {
                return null;
            }
        }
    }
}

From source file:org.gvnix.addon.datatables.addon.DatatablesOperationsImpl.java

/**
 * {@inheritDoc}//from w  ww.  ja  va  2 s  .c om
 * 
 * This includes:
 * <ol>
 * <li>Install <code>applicationConversionService</code> bean if missing</li>
 * <li>Install <code>DatatablesCriteriasResolver<code> bean</li>
 * <li>Install <code>EntityManagerProvider<code> service</li>
 * <li>Install <code>DatatablesUtilService<code> service</li>
 * <li>Install <code>QueryDSLUtilService<code> service</li>
 * </ol>
 * 
 */
@Override
public void updateWebMvcConfigFile(JavaPackage destinationPackage) {
    LogicalPath webappPath = WebProjectUtils.getWebappPath(getProjectOperations());
    String webMvcXmlPath = getProjectOperations().getPathResolver().getIdentifier(webappPath,
            "WEB-INF/spring/webmvc-config.xml");
    Validate.isTrue(fileManager.exists(webMvcXmlPath), "webmvc-config.xml not found");

    MutableFile webMvcXmlMutableFile = null;
    Document webMvcXml;

    try {
        webMvcXmlMutableFile = fileManager.updateFile(webMvcXmlPath);
        webMvcXml = XmlUtils.getDocumentBuilder().parse(webMvcXmlMutableFile.getInputStream());
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    Element root = webMvcXml.getDocumentElement();

    // Get annotation-driven for conversion service
    List<Element> annotationDrivenFound = XmlUtils
            .findElements("annotation-driven[@conversion-service='applicationConversionService']", root);

    if (annotationDrivenFound.isEmpty()) {
        // Delegate on Roo install operation
        if (destinationPackage == null) {
            throw new IllegalStateException(
                    "No conversion service found on webmvc-config.xml: package parameter is required.");
        }
        getWebMvcOperations().installConversionService(destinationPackage);

        // commit fileManager changes (so get final webmvc-config.xml
        // content)
        fileManager.commit();

        // reload xml file after Roo update it
        try {
            webMvcXmlMutableFile = fileManager.updateFile(webMvcXmlPath);
            webMvcXml = XmlUtils.getDocumentBuilder().parse(webMvcXmlMutableFile.getInputStream());
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
        root = webMvcXml.getDocumentElement();

        // Get annotation-driven for conversion service
        annotationDrivenFound = XmlUtils
                .findElements("annotation-driven[@conversion-service='applicationConversionService']", root);
    }
    Validate.isTrue(!annotationDrivenFound.isEmpty(),
            "mvc:annotation-driven conversion-service=\"applicationConversionService\" tag not found in webmvc-config.xml");

    Validate.isTrue(annotationDrivenFound.size() == 1,
            "too much (1 expected) mvc:annotation-driven conversion-service=\"applicationConversionService\" tag found in webmvc-config.xml");

    Element annotationDriven = annotationDrivenFound.get(0);
    Element argumentResolver = null;
    Element bean = null;
    boolean addBean = false;
    // Check tag contents
    if (!annotationDriven.hasChildNodes()) {
        // No children: add bean
        addBean = true;
    } else {
        // Look for bean
        bean = XmlUtils.findFirstElement(
                "argument-resolvers/bean[@class='".concat(DATATABLES_CRITERIA_RESOLVER).concat("']"),
                annotationDriven);
        if (bean == null) {
            addBean = true;
            // get argument-resolvers tag (if any)
            argumentResolver = XmlUtils.findFirstElement(ARGUMENT_RESOLVERS, annotationDriven);
        }
    }
    boolean writeFile = false;
    if (addBean) {
        if (argumentResolver == null) {
            // Add missing argument-resolvers tag to annotation driven tag
            argumentResolver = webMvcXml.createElement("mvc:" + ARGUMENT_RESOLVERS);
            annotationDriven.appendChild(argumentResolver);
        }
        // add bean tag to argument-resolvers
        bean = webMvcXml.createElement("bean");
        bean.setAttribute("class", DATATABLES_CRITERIA_RESOLVER);

        argumentResolver.appendChild(bean);
        writeFile = true;
    }

    // Register EntityManagerProvider Service
    Element entityManagerProvBeanElement = XmlUtils.findFirstElement("bean[@id='entityManagerProvider']", root);
    if (entityManagerProvBeanElement == null) {
        entityManagerProvBeanElement = webMvcXml.createElement("bean");
        entityManagerProvBeanElement.setAttribute("id", "entityManagerProvider");
        entityManagerProvBeanElement.setAttribute("class",
                "org.gvnix.web.datatables.util.impl.EntityManagerProviderImpl");
        root.appendChild(entityManagerProvBeanElement);
        writeFile = true;
    }

    // Register DatatableUtilBean bean
    Element DatatableUtilsBeanElement = XmlUtils.findFirstElement("bean[@id='datatableUtilsBean']", root);
    if (DatatableUtilsBeanElement == null) {
        DatatableUtilsBeanElement = webMvcXml.createElement("bean");
        DatatableUtilsBeanElement.setAttribute("id", "datatableUtilsBean");
        DatatableUtilsBeanElement.setAttribute("class",
                "org.gvnix.web.datatables.util.impl.DatatablesUtilsBeanImpl");
        root.appendChild(DatatableUtilsBeanElement);
        writeFile = true;
    }

    // Register QuerydslUtilBean bean
    Element QuerydslUtilBeanElement = XmlUtils.findFirstElement("bean[@id='querydslUtilsBean']", root);
    if (QuerydslUtilBeanElement == null) {
        QuerydslUtilBeanElement = webMvcXml.createElement("bean");
        QuerydslUtilBeanElement.setAttribute("id", "querydslUtilsBean");
        QuerydslUtilBeanElement.setAttribute("class",
                "org.gvnix.web.datatables.util.impl.QuerydslUtilsBeanImpl");
        root.appendChild(QuerydslUtilBeanElement);
        writeFile = true;
    }

    if (writeFile) {
        XmlUtils.writeXml(webMvcXmlMutableFile.getOutputStream(), webMvcXml);
    }
}

From source file:org.infoglue.calendar.controllers.ContentTypeDefinitionController.java

/**
 * This method adds a parameter node with some default values if not allready existing.
 *//* w w  w. j a va2  s. c o m*/

private boolean addParameterElement(Element parent, String name, String inputTypeId, String value,
        boolean isAllreadyModified) {
    boolean isModified = isAllreadyModified;

    NodeList titleNodeList = parent.getElementsByTagName(name);
    if (titleNodeList != null && titleNodeList.getLength() > 0) {
        Element titleElement = (Element) titleNodeList.item(0);
        if (!titleElement.hasChildNodes()) {
            titleElement.appendChild(parent.getOwnerDocument().createTextNode(value));
            isModified = true;
        }
    } else {
        Element title = parent.getOwnerDocument().createElement(name);
        title.appendChild(parent.getOwnerDocument().createTextNode(value));
        parent.appendChild(title);
        isModified = true;
    }

    return isModified;
}