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:com.aliyun.odps.conf.Configuration.java

private void loadResource(Properties properties, Object name, boolean quiet) {
    try {// w w  w  .j  ava2s . c om
        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 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 && value != null) {
                if (!finalParameters.contains(attr)) {
                    properties.setProperty(attr, value);
                    if (finalParameter) {
                        finalParameters.add(attr);
                    }
                } else {
                    LOG.warn(name + ":a attempt to override final parameter: " + attr + ";  Ignoring.");
                }
            }
        }

    } 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:com.evolveum.midpoint.prism.schema.SchemaToDomProcessor.java

/**
 * Adds XSD complexType definition from the midPoint Schema ComplexTypeDefinion object
 * @param definition midPoint Schema ComplexTypeDefinion object
 * @param parent element under which the definition will be added
 * @return created (and added) XSD complexType definition
 *//*from www .  j  a va 2 s  .  c  om*/
private Element addComplexTypeDefinition(ComplexTypeDefinition definition, Element parent) {

    if (definition == null) {
        // Nothing to do
        return null;
    }
    if (definition.getTypeName() == null) {
        throw new UnsupportedOperationException("Anonymous complex types as containers are not supported yet");
    }

    Element complexType = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "complexType"));
    parent.appendChild(complexType);
    // "typeName" should be used instead of "name" when defining a XSD type
    setAttribute(complexType, "name", definition.getTypeName().getLocalPart());
    Element annotation = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "annotation"));
    complexType.appendChild(annotation);

    Element containingElement = complexType;
    if (definition.getSuperType() != null) {
        Element complexContent = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "complexContent"));
        complexType.appendChild(complexContent);
        Element extension = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "extension"));
        complexContent.appendChild(extension);
        setQNameAttribute(extension, "base", definition.getSuperType());
        containingElement = extension;
    }

    Element sequence = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "sequence"));
    containingElement.appendChild(sequence);

    Collection<? extends ItemDefinition> definitions = definition.getDefinitions();
    for (ItemDefinition def : definitions) {
        if (def instanceof PrismPropertyDefinition) {
            addPropertyDefinition((PrismPropertyDefinition) def, sequence);
        } else if (def instanceof PrismContainerDefinition) {
            PrismContainerDefinition contDef = (PrismContainerDefinition) def;
            addContainerDefinition(contDef, sequence, parent);
        } else if (def instanceof PrismReferenceDefinition) {
            addReferenceDefinition((PrismReferenceDefinition) def, sequence);
        } else {
            throw new IllegalArgumentException("Uknown definition " + def + "(" + def.getClass().getName()
                    + ") in complex type definition " + def);
        }
    }

    if (definition.isXsdAnyMarker()) {
        addXsdAnyDefinition(sequence);
    }

    Element appinfo = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "appinfo"));
    annotation.appendChild(appinfo);

    if (definition.isObjectMarker()) {
        // annotation: propertyContainer
        addAnnotation(A_OBJECT, definition.getDisplayName(), appinfo);
    } else if (definition.isContainerMarker()) {
        // annotation: propertyContainer
        addAnnotation(A_PROPERTY_CONTAINER, definition.getDisplayName(), appinfo);
    }

    addCommonDefinitionAnnotations(definition, appinfo);

    SchemaDefinitionFactory definitionFactory = getDefinitionFactory();
    definitionFactory.addExtraComplexTypeAnnotations(definition, appinfo, this);

    if (!appinfo.hasChildNodes()) {
        // remove unneeded <annotation> element
        complexType.removeChild(annotation);
    }

    return complexType;
}

From source file:org.canova.api.conf.Configuration.java

private void loadResource(Properties properties, Object name, boolean quiet) {
    try {//from   w w w .j  a  va2 s  .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 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.error("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 && value != null) {
                if (!finalParameters.contains(attr)) {
                    properties.setProperty(attr, value);
                    if (storeResource) {
                        updatingResource.put(attr, name.toString());
                    }
                    if (finalParameter)
                        finalParameters.add(attr);
                } else {
                    LOG.warn(name + ":a attempt to override final parameter: " + attr + ";  Ignoring.");
                }
            }
        }

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

From source file:com.streamreduce.util.JiraClient.java

/**
 * Handles the auto-tags, extra metadata, to be added to the activity message for Jira issue activity.
 *
 * @param projectKey     the project key of the inventory item
 * @param activityObject the raw <activity:object /> element of the activity
 * @param entry          the root element for the activity entry
 * @param hashtags       the hashtags set we will manipulate
 */// w w w. j ava2s.  c  om
private void handleJiraWikiAutotags(String projectKey, org.apache.abdera.model.Element activityObject,
        Entry entry, Set<String> hashtags) {
    // Right now, the only additional auto-tags we add for wiki activity are the page's labels.  To do this, we
    // parse the page id from ref attribute of the <thr:in-reply-to /> element.  Once we get this, we make a SOAP
    // call to get the page labels for that id.
    //
    // Note: This does not appear to work for blog/article entries.  The pageId we parse from the activity entry
    //       always returns an empty array response when gathering the labels.  We will still attempt to retrieve
    //       the labels for blog/article entries just in case it gets fixed.
    org.apache.abdera.model.Element thr = entry
            .getFirstChild(new QName("http://purl.org/syndication/thread/1.0", "in-reply-to", "thr"));

    if (thr != null) {
        String pageUrl = thr.getAttributeValue("ref");
        long pageId;

        // Just in case
        if (pageUrl == null) {
            LOGGER.error("Unable to parse the thr:in-reply-to of the Jira activity:object for: "
                    + JSONUtils.xmlToJSON(activityObject.toString()));
            return;
        }

        try {
            pageId = Long.valueOf(pageUrl.substring(pageUrl.lastIndexOf("/") + 1));
        } catch (NumberFormatException e) {
            // Not much we can do so log the error and continue processing
            LOGGER.error("Unexpected wiki page id when parsing activity URL (" + pageUrl + "): ",
                    e.getMessage());
            return;
        }

        try {
            List<org.w3c.dom.Element> labels = getWikiPageLabels(pageId);

            for (org.w3c.dom.Element label : labels) {
                // Confluence labels are returned as an array and we're only interested in ones that have children.
                //
                // Note: When a page has no labels, we get back an empty array element and so we need to check that
                //       the label has children before trying to use it.
                if (!label.hasChildNodes()) {
                    continue;
                }

                NodeList labelNames = label.getElementsByTagName("name");

                if (labelNames == null) {
                    // Not much we can do at this point but log the problem
                    LOGGER.error("Unexpected response when retrieving labels for wiki page with an " + "id of "
                            + pageId + " in the " + projectKey + " project.");
                } else {
                    hashtags.add(removeIllegalHashtagCharacters("#" + labelNames.item(0).getTextContent()));
                }
            }
        } catch (SOAPException e) {
            // Not much we can do at this point but log the problem
            LOGGER.error(
                    "Unable to make SOAP call to get wiki labels for " + projectKey + ": " + e.getMessage());
        }
    }
}

From source file:de.betterform.xml.xforms.model.submission.Submission.java

private void submitReplaceEmbedXForms(Map response) throws XFormsException {
    // check for targetid
    String targetid = getXFormsAttribute(TARGETID_ATTRIBUTE);
    String resource = getResource();
    Map eventInfo = new HashMap();
    String error = null;/* ww  w. j av a  2 s.c  o  m*/
    if (targetid == null) {
        error = "targetId";
    } else if (resource == null) {
        error = "resource";
    }

    if (error != null && error.length() > 0) {
        eventInfo.put(XFormsConstants.ERROR_TYPE, "no " + error + "defined for submission resource");
        this.container.dispatch(this.target, XFormsEventNames.SUBMIT_ERROR, eventInfo);
        return;
    }

    Document result = getResponseAsDocument(response);
    Node embedElement = result.getDocumentElement();

    if (resource.indexOf("#") != -1) {
        // detected a fragment so extract that from our result Document

        String fragmentid = resource.substring(resource.indexOf("#") + 1);
        if (fragmentid.indexOf("?") != -1) {
            fragmentid = fragmentid.substring(0, fragmentid.indexOf("?"));
        }
        embedElement = DOMUtil.getById(result, fragmentid);
    }

    Element embeddedNode = null;
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("get target element for id: " + targetid);
    }
    Element targetElem = this.container.getElementById(targetid);
    DOMResult domResult = new DOMResult();
    //Test if targetElem exist.
    if (targetElem != null) {
        // destroy existing embedded form within targetNode
        if (targetElem.hasChildNodes()) {
            // destroyembeddedModels(targetElem);
            Initializer.disposeUIElements(targetElem);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("destroyed any existing ui elements for target elem");
        }

        // import referenced embedded form into host document
        embeddedNode = (Element) this.container.getDocument().importNode(embedElement, true);

        //import namespaces
        NamespaceResolver.applyNamespaces(targetElem.getOwnerDocument().getDocumentElement(),
                (Element) embeddedNode);

        // keep original targetElem id within hostdoc
        embeddedNode.setAttributeNS(null, "id", targetElem.getAttributeNS(null, "id"));
        //copy all Attributes that might have been on original mountPoint to embedded node
        DOMUtil.copyAttributes(targetElem, embeddedNode, null);
        targetElem.getParentNode().replaceChild(embeddedNode, targetElem);
        //create model for it
        Initializer.initializeUIElements(model, embeddedNode, null, null);

        try {
            CachingTransformerService transformerService = new CachingTransformerService(
                    new ClasspathResourceResolver("unused"));
            // TODO: MUST BE GENERIFIED USING USERAGENT MECHANISM
            //TODO: check exploded mode!!!
            String path = getClass().getResource("/META-INF/resources/xslt/xhtml.xsl").getPath();

            //String xslFilePath = "file:" + path;
            transformerService.getTransformer(new URI(path));
            XSLTGenerator generator = new XSLTGenerator();
            generator.setTransformerService(transformerService);
            generator.setStylesheetURI(new URI(path));
            generator.setInput(embeddedNode);
            generator.setOutput(domResult);
            generator.generate();
        } catch (TransformerException e) {
            throw new XFormsException(
                    "Transformation error while executing 'Submission.submitReplaceEmbedXForms'", e);
        } catch (URISyntaxException e) {
            throw new XFormsException(
                    "Malformed URI throwed URISyntaxException in 'Submission.submitReplaceEmbedXForms'", e);
        }
    }

    // Map eventInfo = constructEventInfo(response);
    OutputStream outputStream = new ByteArrayOutputStream();
    try {
        DOMUtil.prettyPrintDOM(domResult.getNode(), outputStream);
    } catch (TransformerException e) {
        throw new XFormsException(e);
    }

    eventInfo.put(EMBEDNODE, outputStream.toString());
    eventInfo.put("embedTarget", targetid);
    eventInfo.put("embedXForms", true);

    // dispatch xforms-submit-done
    this.container.dispatch(this.target, XFormsEventNames.SUBMIT_DONE, eventInfo);

}

From source file:jef.tools.XMLUtils.java

/**
 * (???)//from w  ww.java2s. c  o m
 * 
 * @param e
 *            
 * @param attributeName
 *            ??
 * @return ??List
 */
public static List<String> attribs(Element e, String attributeName) {
    List<String> _list = new ArrayList<String>();
    if (e.hasAttribute(attributeName)) {
        String text = e.getAttribute(attributeName);
        _list.add((text == null) ? null : StringEscapeUtils.unescapeHtml(text.trim()));
    }
    if (e.hasChildNodes()) {
        NodeList nds = e.getChildNodes();
        for (int i = 0; i < nds.getLength(); i++) {
            Node child = nds.item(i);
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                _list.addAll(attribs((Element) child, attributeName));
            }
        }
    }
    return _list;
}

From source file:com.evolveum.midpoint.prism.schema.SchemaToDomProcessor.java

/**
 * Adds XSD element definition created from the midPoint PropertyDefinition.
 * @param definition midPoint PropertyDefinition
 * @param parent element under which the definition will be added
 *//*from w ww  . ja  v a  2s . com*/
private void addPropertyDefinition(PrismPropertyDefinition definition, Element parent) {
    Element property = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "element"));
    // Add to document first, so following methods will be able to resolve namespaces
    parent.appendChild(property);

    String attrNamespace = definition.getName().getNamespaceURI();
    if (attrNamespace != null && attrNamespace.equals(getNamespace())) {
        setAttribute(property, "name", definition.getName().getLocalPart());
        setQNameAttribute(property, "type", definition.getTypeName());
    } else {
        setQNameAttribute(property, "ref", definition.getName());
    }

    if (definition.getMinOccurs() != 1) {
        setAttribute(property, "minOccurs", Integer.toString(definition.getMinOccurs()));
    }

    if (definition.getMaxOccurs() != 1) {
        String maxOccurs = definition.getMaxOccurs() == XSParticle.UNBOUNDED ? MAX_OCCURS_UNBOUNDED
                : Integer.toString(definition.getMaxOccurs());
        setAttribute(property, "maxOccurs", maxOccurs);
    }

    Element annotation = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "annotation"));
    property.appendChild(annotation);
    Element appinfo = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "appinfo"));
    annotation.appendChild(appinfo);

    addCommonDefinitionAnnotations(definition, appinfo);

    if (!definition.canAdd() || !definition.canRead() || !definition.canModify()) {
        // read-write-create attribute is the default. If any of this flags is missing, we must
        // add appropriate annotations.
        if (definition.canAdd()) {
            addAnnotation(A_ACCESS, A_ACCESS_CREATE, appinfo);
        }
        if (definition.canRead()) {
            addAnnotation(A_ACCESS, A_ACCESS_READ, appinfo);
        }
        if (definition.canModify()) {
            addAnnotation(A_ACCESS, A_ACCESS_UPDATE, appinfo);
        }
    }

    if (definition.isIndexed() != null) {
        addAnnotation(A_INDEXED, XmlTypeConverter.toXmlTextContent(definition.isIndexed(), A_INDEXED), appinfo);
    }

    SchemaDefinitionFactory definitionFactory = getDefinitionFactory();
    definitionFactory.addExtraPropertyAnnotations(definition, appinfo, this);

    if (!appinfo.hasChildNodes()) {
        // remove unneeded <annotation> element
        property.removeChild(annotation);
    }
}

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

private Criterion createCriterion(Element criterionElement) {
    NodeList criterionTags = criterionElement.getChildNodes();
    Criterion newCriterion = new Criterion();

    for (int i = 0; i < criterionTags.getLength(); i++) {
        Node criterionTagNode = criterionTags.item(i);
        if (criterionTagNode instanceof Element) {
            Element criterionTagElement = (Element) criterionTagNode;

            if (criterionTagElement.getNodeName().equals("name")) {
                newCriterion.setName(criterionTagElement.getTextContent());
            }//from ww w.j a  va2  s.  c o m

            if (criterionTagElement.getNodeName().equals("description")) {
                newCriterion.setDescription(criterionTagElement.getTextContent());
            }

            if (criterionTagElement.getNodeName().equals("type")) {
                if (criterionTagElement.getTextContent().equals("quantitative")) {
                    newCriterion.setType(CriterionType.QUANTITATIVE);
                } else if (criterionTagElement.getTextContent().equals("qualitative")) {
                    newCriterion.setType(CriterionType.QUALITATIVE);
                } else if (criterionTagElement.getTextContent().equals("benchmark")) {
                    newCriterion.setType(CriterionType.BENCHMARK);
                }
            }

            if (criterionTagElement.getNodeName().equals("weight")
                    && !criterionTagElement.getTextContent().equals("")) {
                try {
                    newCriterion.setWeight(Double.valueOf(criterionTagElement.getTextContent()));
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

            if (criterionTagElement.getNodeName().equals("children")) {
                if (criterionTagElement.hasChildNodes()) {
                    NodeList criterionChildNodes = criterionTagElement.getChildNodes();
                    for (int x = 0; x < criterionChildNodes.getLength(); x++) {
                        Node criterionChildNode = criterionChildNodes.item(x);
                        if (criterionChildNode instanceof Element) {
                            newCriterion.addChild(createCriterion((Element) criterionChildNode));
                        }
                    }
                }
            }

            if (criterionTagElement.getNodeName().equals("importanceChildren")) {
                if (criterionTagElement.hasChildNodes()) {
                    parseImportanceChildren(criterionTagElement.getChildNodes(), newCriterion);
                }
            }
        }
    }
    log.info("Parsed Criterion: " + newCriterion.toString());
    return newCriterion;
}

From source file:com.glaf.core.config.Configuration.java

private Resource loadResource(Properties properties, Resource wrapper, boolean quiet) {
    String name = UNKNOWN_RESOURCE;
    try {//from ww w  . ja  va2  s  .c  om
        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 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();

        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) {
                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:co.cask.cdap.common.conf.Configuration.java

private void loadResource(Properties properties, Object name, boolean quiet) {
    try {/* w  w  w . j a v  a2 s  .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 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 (deprecatedKeyMap.containsKey(attr)) {
                    DeprecatedKeyInfo keyInfo = deprecatedKeyMap.get(attr);
                    keyInfo.accessed = false;
                    for (String key : keyInfo.newKeys) {
                        // update new keys with deprecated key's value
                        loadProperty(properties, name, key, value, finalParameter);
                    }
                } else {
                    loadProperty(properties, name, attr, value, finalParameter);
                }
            }
        }

    } 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);
    }
}