Example usage for javax.xml.parsers DocumentBuilderFactory setXIncludeAware

List of usage examples for javax.xml.parsers DocumentBuilderFactory setXIncludeAware

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setXIncludeAware.

Prototype

public void setXIncludeAware(final boolean state) 

Source Link

Document

Set state of XInclude processing.

Usage

From source file:org.apache.hadoop.hdfs.server.hightidenode.ConfigManager.java

/**
 * Updates the in-memory data structures from the config file. This file is
 * expected to be in the following whitespace-separated format:
 * Blank lines and lines starting with # are ignored.
 *  //from w  w w.  java  2 s .  c  om
 * @throws IOException if the config file cannot be read.
 * @throws HighTideConfigurationException if configuration entries are invalid.
 * @throws ClassNotFoundException if user-defined policy classes cannot be loaded
 * @throws ParserConfigurationException if XML parser is misconfigured.
 * @throws SAXException if config file is malformed.
 * @returns A new set of policy categories.
 */
void reloadConfigs() throws IOException, ParserConfigurationException, SAXException, ClassNotFoundException,
        HighTideConfigurationException {

    if (configFileName == null) {
        return;
    }

    File file = new File(configFileName);
    if (!file.exists()) {
        throw new HighTideConfigurationException("Configuration file " + configFileName + " does not exist.");
    }

    // Read and parse the configuration file.
    // allow include files in configuration file
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setIgnoringComments(true);
    docBuilderFactory.setNamespaceAware(true);
    try {
        docBuilderFactory.setXIncludeAware(true);
    } catch (UnsupportedOperationException e) {
        LOG.error("Failed to set setXIncludeAware(true) for raid parser " + docBuilderFactory + ":" + e, e);
    }
    LOG.error("Reloading config file " + file);

    DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
    Document doc = builder.parse(file);
    Element root = doc.getDocumentElement();
    if (!"configuration".equalsIgnoreCase(root.getTagName()))
        throw new HighTideConfigurationException(
                "Bad configuration file: " + "top-level element not <configuration>");
    NodeList elements = root.getChildNodes();

    Set<PolicyInfo> existingPolicies = new HashSet<PolicyInfo>();

    // loop through all the configured source paths.
    for (int i = 0; i < elements.getLength(); i++) {
        Node node = elements.item(i);
        if (!(node instanceof Element)) {
            continue;
        }
        Element element = (Element) node;
        String elementTagName = element.getTagName();
        String policyName = null;
        if ("srcPath".equalsIgnoreCase(elementTagName)) {
            String srcPathPrefix = element.getAttribute("name");

            if (srcPathPrefix == null || srcPathPrefix.length() == 0) {
                throw new HighTideConfigurationException(
                        "Bad configuration file: " + "srcPath node does not have a path.");
            }
            PolicyInfo policyInfo = new PolicyInfo(srcPathPrefix, conf);
            policyName = srcPathPrefix;
            Properties policyProperties;

            // loop through all elements of this policy
            NodeList policies = element.getChildNodes();
            for (int j = 0; j < policies.getLength(); j++) {
                Node node1 = policies.item(j);
                if (!(node1 instanceof Element)) {
                    continue;
                }
                Element policy = (Element) node1;
                if ((!"property".equalsIgnoreCase(policy.getTagName()))
                        && (!"destPath".equalsIgnoreCase(policy.getTagName()))) {
                    throw new HighTideConfigurationException(
                            "Bad configuration file: " + "Expecting <property> or <destPath> for srcPath "
                                    + srcPathPrefix + " but found " + policy.getTagName());
                }

                // parse the <destPath> items
                if ("destPath".equalsIgnoreCase(policy.getTagName())) {
                    String destPath = policy.getAttribute("name");
                    if (destPath == null) {
                        throw new HighTideConfigurationException("Bad configuration file: "
                                + "<destPath> tag should have an attribute named 'name'.");
                    }
                    NodeList properties = policy.getChildNodes();
                    Properties destProperties = new Properties();
                    for (int k = 0; k < properties.getLength(); k++) {
                        Node node2 = properties.item(k);
                        if (!(node2 instanceof Element)) {
                            continue;
                        }
                        Element property = (Element) node2;
                        String propertyName = property.getTagName();
                        if (!("property".equalsIgnoreCase(propertyName))) {
                            throw new HighTideConfigurationException(
                                    "Bad configuration file: " + "<destPath> can have only <property> children."
                                            + " but found " + propertyName);
                        }
                        NodeList nl = property.getChildNodes();
                        String pname = null, pvalue = null;
                        for (int l = 0; l < nl.getLength(); l++) {
                            Node node3 = nl.item(l);
                            if (!(node3 instanceof Element)) {
                                continue;
                            }
                            Element item = (Element) node3;
                            String itemName = item.getTagName();
                            if ("name".equalsIgnoreCase(itemName)) {
                                pname = ((Text) item.getFirstChild()).getData().trim();
                            } else if ("value".equalsIgnoreCase(itemName)) {
                                pvalue = ((Text) item.getFirstChild()).getData().trim();
                            }
                        }
                        if (pname == null || pvalue == null) {
                            throw new HighTideConfigurationException("Bad configuration file: "
                                    + "All property for destPath " + destPath + "  must have name and value ");
                        }
                        LOG.info(policyName + "." + pname + " = " + pvalue);
                        destProperties.setProperty(pname, pvalue);
                    }
                    policyInfo.addDestPath(destPath, destProperties);

                } else if ("property".equalsIgnoreCase(policy.getTagName())) {
                    Element property = (Element) node1;
                    NodeList nl = property.getChildNodes();
                    String pname = null, pvalue = null;
                    for (int l = 0; l < nl.getLength(); l++) {
                        Node node3 = nl.item(l);
                        if (!(node3 instanceof Element)) {
                            continue;
                        }
                        Element item = (Element) node3;
                        String itemName = item.getTagName();
                        if ("name".equalsIgnoreCase(itemName)) {
                            pname = ((Text) item.getFirstChild()).getData().trim();
                        } else if ("value".equalsIgnoreCase(itemName)) {
                            pvalue = ((Text) item.getFirstChild()).getData().trim();
                        }
                    }
                    if (pname == null || pvalue == null) {
                        throw new HighTideConfigurationException("Bad configuration file: "
                                + "All property for srcPath " + srcPathPrefix + " must have name and value ");
                    }
                    LOG.info(policyName + "." + pname + " = " + pvalue);
                    policyInfo.setProperty(pname, pvalue);
                }
            }
            existingPolicies.add(policyInfo);
        } else {
            throw new HighTideConfigurationException("Bad configuration file: "
                    + "The top level item must be srcPath but found " + elementTagName);
        }
    }
    validateAllPolicies(existingPolicies);
    setAllPolicies(existingPolicies);
    return;
}

From source file:org.apache.hadoop.mapred.QueueConfigurationParser.java

/**
 * Method to load the resource file.// w ww.  j  a v a2  s .com
 * generates the root.
 * 
 * @param resourceInput InputStream that provides the XML to parse
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
protected Queue loadResource(InputStream resourceInput)
        throws ParserConfigurationException, SAXException, IOException {
    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.info("Failed to set setXIncludeAware(true) for parser " + docBuilderFactory + NAME_SEPARATOR + e);
    }
    DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
    Document doc = null;
    Element queuesNode = null;

    doc = builder.parse(resourceInput);
    queuesNode = doc.getDocumentElement();
    return this.parseResource(queuesNode);
}

From source file:org.apache.hadoop.raid.ConfigManager.java

void reloadXmlConfigs() throws IOException, ParserConfigurationException, SAXException, ClassNotFoundException,
        RaidConfigurationException {// w  ww .  jav a2  s .c  o m

    if (configFileName == null) {
        return;
    }

    File file = new File(configFileName);
    if (!file.exists()) {
        throw new RaidConfigurationException("Configuration file " + configFileName + " does not exist.");
    }

    // Create some temporary hashmaps to hold the new allocs, and we only save
    // them in our fields if we have parsed the entire allocs file successfully.
    List<PolicyInfo> all = new ArrayList<PolicyInfo>();
    long periodicityValue = periodicity;

    // Read and parse the configuration file.
    // allow include files in configuration file
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setIgnoringComments(true);
    docBuilderFactory.setNamespaceAware(true);
    try {
        docBuilderFactory.setXIncludeAware(true);
    } catch (UnsupportedOperationException e) {
        LOG.error("Failed to set setXIncludeAware(true) for raid parser " + docBuilderFactory + ":" + e, e);
    }
    LOG.info("Reloading config file " + file);

    DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
    Document doc = builder.parse(file);
    Element root = doc.getDocumentElement();
    if (!"configuration".equalsIgnoreCase(root.getTagName()))
        throw new RaidConfigurationException(
                "Bad configuration file: " + "top-level element not <configuration>");
    NodeList policies = root.getChildNodes();

    Map<String, PolicyInfo> existingPolicies = new HashMap<String, PolicyInfo>();
    // loop through all the configured policies.
    for (int i = 0; i < policies.getLength(); i++) {
        Node node = policies.item(i);
        if (!(node instanceof Element)) {
            continue;
        }
        Element policy = (Element) node;
        if ("policy".equalsIgnoreCase(policy.getTagName())) {
            String policyName = policy.getAttribute("name");
            PolicyInfo curr = new PolicyInfo(policyName, conf);
            PolicyInfo parent = null;
            NodeList policyElements = policy.getChildNodes();
            for (int j = 0; j < policyElements.getLength(); j++) {
                Node node1 = policyElements.item(j);
                if (!(node1 instanceof Element)) {
                    continue;
                }
                Element property = (Element) node1;
                String propertyName = property.getTagName();
                if ("srcPath".equalsIgnoreCase(propertyName)) {
                    String srcPathPrefix = property.getAttribute("prefix");
                    if (srcPathPrefix != null && srcPathPrefix.length() > 0) {
                        curr.setSrcPath(srcPathPrefix);
                    }
                } else if ("fileList".equalsIgnoreCase(propertyName)) {
                    String text = ((Text) property.getFirstChild()).getData().trim();
                    LOG.info(policyName + ".fileList = " + text);
                    curr.setFileListPath(new Path(text));
                } else if ("codecId".equalsIgnoreCase(propertyName)) {
                    String text = ((Text) property.getFirstChild()).getData().trim();
                    LOG.info(policyName + ".codecId = " + text);
                    curr.setCodecId(text);
                } else if ("shouldRaid".equalsIgnoreCase(propertyName)) {
                    String text = ((Text) property.getFirstChild()).getData().trim();
                    curr.setShouldRaid(Boolean.parseBoolean(text));
                } else if ("description".equalsIgnoreCase(propertyName)) {
                    String text = ((Text) property.getFirstChild()).getData().trim();
                    curr.setDescription(text);
                } else if ("parentPolicy".equalsIgnoreCase(propertyName)) {
                    String text = ((Text) property.getFirstChild()).getData().trim();
                    parent = existingPolicies.get(text);
                } else if ("property".equalsIgnoreCase(propertyName)) {
                    NodeList nl = property.getChildNodes();
                    String pname = null, pvalue = null;
                    for (int l = 0; l < nl.getLength(); l++) {
                        Node node3 = nl.item(l);
                        if (!(node3 instanceof Element)) {
                            continue;
                        }
                        Element item = (Element) node3;
                        String itemName = item.getTagName();
                        if ("name".equalsIgnoreCase(itemName)) {
                            pname = ((Text) item.getFirstChild()).getData().trim();
                        } else if ("value".equalsIgnoreCase(itemName)) {
                            pvalue = ((Text) item.getFirstChild()).getData().trim();
                        }
                    }
                    if (pname != null && pvalue != null) {
                        LOG.info(policyName + "." + pname + " = " + pvalue);
                        curr.setProperty(pname, pvalue);
                    }
                } else {
                    LOG.info("Found bad property " + propertyName + " policy name " + policyName
                            + ". Ignoring.");
                }
            } // done with all properties of this policy
            PolicyInfo pinfo;
            if (parent != null) {
                pinfo = new PolicyInfo(policyName, conf);
                pinfo.copyFrom(parent);
                pinfo.copyFrom(curr);
            } else {
                pinfo = curr;
            }
            if (pinfo.getSrcPath() != null || pinfo.getFileListPath() != null) {
                all.add(pinfo);
            }
            existingPolicies.put(policyName, pinfo);
        }
    }
    setAllPolicies(all);
    periodicity = periodicityValue;
    return;
}

From source file:org.apache.juddi.mapping.MappingModelToApi.java

private static Object convertDataToTransformContent(String type, byte[] xformBytes) throws RuntimeException {
    Object transformObject;/*from  w ww  . j  a va 2  s  .  c  o  m*/
    if (type.equals(String.class.getSimpleName())) {
        try {
            transformObject = new String(xformBytes, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("Error decoding string due to: " + e.getMessage(), e);
        }
    } else if (type.equals(byte[].class.getSimpleName())) {
        transformObject = xformBytes;
    } else if (type.equals(Element.class.getCanonicalName())) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setXIncludeAware(true);
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new ByteArrayInputStream(xformBytes));
            transformObject = doc.getDocumentElement();
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse element due to: " + e.getMessage(), e);
        }
    } else {
        throw new RuntimeException("Unrecognized type: " + type);
    }
    return transformObject;
}

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

private void loadResource(Properties properties, Object name, boolean quiet) {
    try {/*w  ww .  j  av  a 2 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 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 && 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:org.apache.oozie.cli.OozieCLI.java

private Properties parse(InputStream is, Properties conf) throws IOException {
    try {//from  ww w .j  a  va2  s  .  c o m
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setNamespaceAware(true);
        // support for includes in the xml file
        docBuilderFactory.setXIncludeAware(true);
        // ignore all comments inside the xml file
        docBuilderFactory.setIgnoringComments(true);
        docBuilderFactory.setExpandEntityReferences(false);
        docBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        Document doc = builder.parse(is);
        return parseDocument(doc, conf);
    } catch (SAXException e) {
        throw new IOException(e);
    } catch (ParserConfigurationException e) {
        throw new IOException(e);
    }
}

From source file:org.apache.rahas.TrustUtil.java

/**
 * Create DocumentBuilderFactory with the XXE and XEE prevention measurements
 *
 * @return DocumentBuilderFactory instance
 *//* www  .j  a  va 2s  . c  o m*/
public static DocumentBuilderFactory getSecuredDocumentBuilderFactory() {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    try {
        dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);
        dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);
        dbf.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (ParserConfigurationException e) {
        logger.error("Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE
                + " or " + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or "
                + Constants.LOAD_EXTERNAL_DTD_FEATURE + "or secure-processing.");
    }

    SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
    dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager);

    return dbf;
}

From source file:org.apache.rampart.util.Axis2Util.java

/**
 * Create DocumentBuilderFactory with the XXE prevention measurements
 *
 * @return DocumentBuilderFactory instance
 *//*  www  . j a v a 2 s .co  m*/
public static DocumentBuilderFactory getSecuredDocumentBuilderFactory() {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    try {
        dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);
        dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);
        dbf.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (ParserConfigurationException e) {
        logger.error("Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE
                + " or " + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or "
                + Constants.LOAD_EXTERNAL_DTD_FEATURE);
    }

    SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
    dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager);

    return dbf;
}

From source file:org.apache.safe.service.Configuration.java

private void loadResource(Properties properties, Object name) {
    try {/*from   w ww.  j  av  a 2 s .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) {
                doc = builder.parse(url.toString());
            }
        } else if (name instanceof String) { // a CLASSPATH resource
            URL url = getResource((String) name);
            if (url != null) {
                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) {
            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);
                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) {
                    properties.setProperty(attr, value);
                }
            }

        }

    } 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.safe.service.FileBasedAuthorizationService.java

void loadResource(InputStream input) {
    try {/*from www .  ja  va 2  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;

        try {
            doc = builder.parse((InputStream) input);
        } finally {
            ((InputStream) input).close();
        }

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

        if (root == null) {
            root = doc.getDocumentElement();
        }
        if (!"acls".equals(root.getTagName()))
            LOG.fatal("bad conf file: top-level element not <acls>");
        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 (!"acl".equals(prop.getTagName()))
                LOG.warn("bad conf file: element not <acl>");
            NodeList fields = prop.getChildNodes();
            String key = null;
            String users = null;
            String groups = null;
            for (int j = 0; j < fields.getLength(); j++) {
                Node fieldNode = fields.item(j);
                if (!(fieldNode instanceof Element))
                    continue;
                Element field = (Element) fieldNode;
                if ("key".equals(field.getTagName()) && field.hasChildNodes())
                    key = ((Text) field.getFirstChild()).getData().trim();
                if ("users".equals(field.getTagName()) && field.hasChildNodes())
                    users = ((Text) field.getFirstChild()).getData().trim();
                if ("groups".equals(field.getTagName()) && field.hasChildNodes())
                    groups = ((Text) field.getFirstChild()).getData();

                if (key != null) {
                    Set<String> userSet = null;
                    Set<String> groupSet = null;

                    if (users != null && !users.isEmpty()) {
                        userSet = new HashSet<String>(Arrays.asList(users.split(",")));
                    }
                    if (groups != null && !groups.isEmpty()) {
                        groupSet = new HashSet<String>(Arrays.asList(groups.split(",")));
                    }
                    ACL acl = new ACL(userSet, groupSet);
                    acls.put(key, acl);
                }
            }
        }
    } 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);
    }
}