Example usage for javax.xml.parsers DocumentBuilderFactory setIgnoringComments

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

Introduction

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

Prototype


public void setIgnoringComments(boolean ignoreComments) 

Source Link

Document

Specifies that the parser produced by this code will ignore comments.

Usage

From source file:lineage2.gameserver.Config.java

/**
 * Method loadGMAccess.//from  ww  w. j  a  va2  s.  c o m
 * @param file File
 */
public static void loadGMAccess(File file) {
    try {
        Field fld;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringComments(true);
        Document doc = factory.newDocumentBuilder().parse(file);
        for (Node z = doc.getFirstChild(); z != null; z = z.getNextSibling()) {
            for (Node n = z.getFirstChild(); n != null; n = n.getNextSibling()) {
                if (!n.getNodeName().equalsIgnoreCase("char")) {
                    continue;
                }
                PlayerAccess pa = new PlayerAccess();
                for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                    Class<?> cls = pa.getClass();
                    String node = d.getNodeName();
                    if (node.equalsIgnoreCase("#text")) {
                        continue;
                    }
                    try {
                        fld = cls.getField(node);
                    } catch (NoSuchFieldException e) {
                        _log.info("Not found desclarate ACCESS name: " + node + " in XML Player access Object");
                        continue;
                    }
                    if (fld.getType().getName().equalsIgnoreCase("boolean")) {
                        fld.setBoolean(pa,
                                Boolean.parseBoolean(d.getAttributes().getNamedItem("set").getNodeValue()));
                    } else if (fld.getType().getName().equalsIgnoreCase("int")) {
                        fld.setInt(pa, Integer.valueOf(d.getAttributes().getNamedItem("set").getNodeValue()));
                    }
                }
                gmlist.put(pa.PlayerID, pa);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.l2jfree.gameserver.datatables.RecipeTable.java

private void loadFromXML() throws SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);//from  w  w  w.  j  a v a 2  s .  co  m
    factory.setIgnoringComments(true);
    File file = new File(Config.DATAPACK_ROOT, "data/" + RECIPES_FILE);
    if (file.exists()) {
        Document doc = factory.newDocumentBuilder().parse(file);
        List<L2RecipeInstance> recipePartList = new FastList<L2RecipeInstance>();
        List<L2RecipeStatInstance> recipeStatUseList = new FastList<L2RecipeStatInstance>();
        List<L2RecipeStatInstance> recipeAltStatChangeList = new FastList<L2RecipeStatInstance>();

        for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
            if ("list".equalsIgnoreCase(n.getNodeName())) {
                recipesFile: for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                    if ("item".equalsIgnoreCase(d.getNodeName())) {
                        recipePartList.clear();
                        recipeStatUseList.clear();
                        recipeAltStatChangeList.clear();
                        NamedNodeMap attrs = d.getAttributes();
                        Node att;
                        int id = -1;
                        boolean haveRare = false;
                        StatsSet set = new StatsSet();

                        att = attrs.getNamedItem("id");
                        if (att == null) {
                            _log.fatal("Missing id for recipe item, skipping");
                            continue;
                        }
                        id = Integer.parseInt(att.getNodeValue());
                        set.set("id", id);

                        att = attrs.getNamedItem("recipeId");
                        if (att == null) {
                            _log.fatal("Missing recipeId for recipe item id: " + id + ", skipping");
                            continue;
                        }
                        set.set("recipeId", Integer.parseInt(att.getNodeValue()));

                        att = attrs.getNamedItem("name");
                        if (att == null) {
                            _log.fatal("Missing name for recipe item id: " + id + ", skipping");
                            continue;
                        }
                        set.set("recipeName", att.getNodeValue());

                        att = attrs.getNamedItem("craftLevel");
                        if (att == null) {
                            _log.fatal("Missing level for recipe item id: " + id + ", skipping");
                            continue;
                        }
                        set.set("craftLevel", Integer.parseInt(att.getNodeValue()));

                        att = attrs.getNamedItem("type");
                        if (att == null) {
                            _log.fatal("Missing type for recipe item id: " + id + ", skipping");
                            continue;
                        }
                        set.set("isDwarvenRecipe", att.getNodeValue().equalsIgnoreCase("dwarven"));

                        att = attrs.getNamedItem("successRate");
                        if (att == null) {
                            _log.fatal("Missing successRate for recipe item id: " + id + ", skipping");
                            continue;
                        }
                        set.set("successRate", Integer.parseInt(att.getNodeValue()));

                        for (Node c = d.getFirstChild(); c != null; c = c.getNextSibling()) {
                            if ("statUse".equalsIgnoreCase(c.getNodeName())) {
                                String statName = c.getAttributes().getNamedItem("name").getNodeValue();
                                int value = Integer
                                        .parseInt(c.getAttributes().getNamedItem("value").getNodeValue());
                                try {
                                    recipeStatUseList.add(new L2RecipeStatInstance(statName, value));
                                } catch (Exception e) {
                                    _log.fatal("Error in StatUse parameter for recipe item id: " + id
                                            + ", skipping", e);
                                    continue recipesFile;
                                }
                            } else if ("altStatChange".equalsIgnoreCase(c.getNodeName())) {
                                String statName = c.getAttributes().getNamedItem("name").getNodeValue();
                                int value = Integer
                                        .parseInt(c.getAttributes().getNamedItem("value").getNodeValue());
                                try {
                                    recipeAltStatChangeList.add(new L2RecipeStatInstance(statName, value));
                                } catch (Exception e) {
                                    _log.fatal("Error in AltStatChange parameter for recipe item id: " + id
                                            + ", skipping", e);
                                    continue recipesFile;
                                }
                            } else if ("ingredient".equalsIgnoreCase(c.getNodeName())) {
                                int ingId = Integer
                                        .parseInt(c.getAttributes().getNamedItem("id").getNodeValue());
                                int ingCount = Integer
                                        .parseInt(c.getAttributes().getNamedItem("count").getNodeValue());
                                recipePartList.add(new L2RecipeInstance(ingId, ingCount));
                            } else if ("production".equalsIgnoreCase(c.getNodeName())) {
                                set.set("itemId",
                                        Integer.parseInt(c.getAttributes().getNamedItem("id").getNodeValue()));
                                set.set("count", Integer
                                        .parseInt(c.getAttributes().getNamedItem("count").getNodeValue()));
                            } else if ("productionRare".equalsIgnoreCase(c.getNodeName())) {
                                set.set("rareItemId",
                                        Integer.parseInt(c.getAttributes().getNamedItem("id").getNodeValue()));
                                set.set("rareCount", Integer
                                        .parseInt(c.getAttributes().getNamedItem("count").getNodeValue()));
                                set.set("rarity", Integer
                                        .parseInt(c.getAttributes().getNamedItem("rarity").getNodeValue()));
                                haveRare = true;
                            }
                        }

                        L2RecipeList recipeList = new L2RecipeList(set, haveRare);
                        for (L2RecipeInstance recipePart : recipePartList)
                            recipeList.addRecipe(recipePart);
                        for (L2RecipeStatInstance recipeStatUse : recipeStatUseList)
                            recipeList.addStatUse(recipeStatUse);
                        for (L2RecipeStatInstance recipeAltStatChange : recipeAltStatChangeList)
                            recipeList.addAltStatChange(recipeAltStatChange);

                        _lists.put(recipeList.getId(), recipeList);
                    }
                }
            }
        }
    } else {
        _log.fatal("Recipes file (" + file.getAbsolutePath() + ") doesnt exists.");
    }
}

From source file:com.hp.hpl.inkml.InkMLDOMParser.java

/**
 * Method to parse the InkML string markup data identified by the inkmlStr given
 * //from w  w w.j  av a 2  s . co m
 * @param inkmlStr String markup data
 * @throws InkMLException
 */
public void parseInkMLString(final String inkmlStrParam) throws InkMLException {
    final String inkmlStr;
    if (inkmlStrParam.indexOf("ink") == -1) {
        // the given welformed inkmlStr does not contain complete <ink> document as string.
        // wrap it with a false root element, <inkMLFramgment>. It is called as fragment.
        inkmlStr = "<inkMLFramgment>" + inkmlStrParam + " </inkMLFramgment>";
    } else {
        inkmlStr = inkmlStrParam;
    }
    InkMLDOMParser.LOG.fine(inkmlStr);

    try {
        final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setIgnoringComments(true);
        dbFactory.setIgnoringElementContentWhitespace(true);
        dbFactory.setValidating(false);
        InkMLDOMParser.LOG.info("Validation using schema is disabled.");
        final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        this.inkmlDOMDocument = dBuilder.parse(inkmlStr);
        this.bindData(this.inkMLProcessor.getInk());
    } catch (final ParserConfigurationException e) {
        throw new InkMLException("Error in parsing Input InkML XML file.\n Message: " + e.getMessage(), e);
    } catch (final SAXException e) {
        throw new InkMLException("Error in parsing Input InkML XML file.\n Message: " + e.getMessage(), e);
    } catch (final IOException e) {
        throw new InkMLException("I/O error while parsing Input InkML XML file.\n Message: " + e.getMessage(),
                e);
    }
}

From source file:com.hp.hpl.inkml.InkMLDOMParser.java

/**
 * Method to parse the InkML file identified by the inkmlFilename given in the parameter and creates data objects. It performs validation with schema. It
 * must have "ink" as root element with InkML name space specified with xmlns="http://www.w3.org/2003/InkML". The schema location may be specified. If it is
 * not specified or if relative path of the InkML.xsd file is specified, then the InkML.xsd file path must be added to * CLASSPATH for the parser to locate
 * it. An example of a typical header is, <ink xmlns="http://www.w3.org/2003/InkML" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 * xsi:schemaLocation="http://www.w3.org/2003/InkML C:\project\schema\inkml.xsd">
 * /*  www  .  j a va2  s. co m*/
 * @param inkmlFileName
 * @throws InkMLException
 */
public void parseInkMLFile(final InputStream inputStream) throws InkMLException {

    // Get the DOM document object by parsing the InkML input file
    try {
        final InputSource input = new InputSource(inputStream);

        // get the DOM document object of the input InkML XML file.
        final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setIgnoringComments(true);
        dbFactory.setNamespaceAware(true);
        dbFactory.setIgnoringElementContentWhitespace(true);
        dbFactory.setValidating(false);
        if (this.isSchemaValidationEnabled()) {
            InkMLDOMParser.LOG.info("Validation using schema is enabled.");
            dbFactory.setSchema(this.schemaFactory
                    .newSchema(new StreamSource(this.getClass().getResourceAsStream("/schema/inkml.xsd"))));
        } else {
            InkMLDOMParser.LOG.info("Validation using schema is disabled.");
        }
        final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        dBuilder.setErrorHandler(this);
        this.inkmlDOMDocument = dBuilder.parse(input);
        InkMLDOMParser.LOG.info("\nInput InkML XML file parsing is completed.\n");
        this.inkMLProcessor.beginInkSession();
        this.bindData(this.inkMLProcessor.getInk());
    } catch (final ParserConfigurationException e) {
        throw new InkMLException("Error in parsing Input InkML XML file.\n Message: " + e.getMessage(), e);
    } catch (final SAXException e) {
        throw new InkMLException("Error in parsing Input InkML XML file.\n Message: " + e.getMessage(), e);
    } catch (final IOException e) {
        throw new InkMLException("I/O error while parsing Input InkML XML file.\n Message: " + e.getMessage(),
                e);
    }
}

From source file:com.silverwrist.venice.std.TrackbackManager.java

/**
 * Only one instance of this class can/should exist.
 *//*w w  w .j a va  2s. c o m*/
private TrackbackManager() {
    m_page_cache = new HashMap();
    m_item_cache = new HashMap();
    m_end_recognizers = new HashMap();
    m_http_client = new HttpClient();

    try { // create the XML parsers we use
        DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
        fact.setCoalescing(true);
        fact.setExpandEntityReferences(true);
        fact.setIgnoringComments(true);
        fact.setNamespaceAware(true);
        fact.setValidating(false);
        m_rdf_parser = fact.newDocumentBuilder();
        fact.setCoalescing(true);
        fact.setExpandEntityReferences(true);
        fact.setIgnoringComments(true);
        fact.setNamespaceAware(false);
        fact.setValidating(false);
        m_tbresp_parser = fact.newDocumentBuilder();

    } // end try
    catch (ParserConfigurationException e) { // this is bad!
        logger.fatal("XML parser creation failed", e);

    } // end catch

}

From source file:com.edgenius.wiki.installation.UpgradeServiceImpl.java

/**
 * @param root//  w ww .  ja  v  a  2  s  .  c  om
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
private void mergeCustomizedThemesOnVersion2180(String root)
        throws ParserConfigurationException, SAXException, IOException {

    File rootFile = FileUtil.getFile(root);
    File dir = new File(rootFile, "data/themes/customized");
    if (dir.exists() && dir.isDirectory()) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setCoalescing(true);
        factory.setIgnoringComments(true);
        DocumentBuilder builder = factory.newDocumentBuilder();

        Map<Integer, List<PageTheme>> map = new HashMap<Integer, List<PageTheme>>();
        File[] files = dir.listFiles((FilenameFilter) FileFilterUtils.suffixFileFilter(".xml"));
        for (File file : files) {
            //get space setting - file.getName();
            //parse customized theme, and get back the 
            List<PageTheme> list = new ArrayList<PageTheme>();
            Document dom = builder.parse(file);
            NodeList elements = dom.getElementsByTagName("com.edgenius.wiki.PageTheme");
            for (int idx = 0; idx < elements.getLength(); idx++) {
                PageTheme pTheme = new PageTheme();
                Node element = elements.item(idx);
                NodeList children = element.getChildNodes();

                for (int idj = 0; idj < children.getLength(); idj++) {
                    String value = children.item(idj).getTextContent();
                    if ("bodyMarkup".equals(children.item(idj).getNodeName())) {
                        pTheme.setBodyMarkup(value);
                    } else if ("sidebarMarkup".equals(children.item(idj).getNodeName())) {
                        pTheme.setSidebarMarkup(value);
                    } else if ("welcome".equals(children.item(idj).getNodeName())) {
                        pTheme.setWelcome(value);
                    } else if ("type".equals(children.item(idj).getNodeName())) {
                        String scope;
                        if ("0".equals(value)) {
                            scope = PageTheme.SCOPE_DEFAULT;
                        } else if ("1".equals(value)) {
                            scope = PageTheme.SCOPE_HOME;
                        } else {
                            scope = value;
                        }
                        pTheme.setScope(scope);
                    }
                }
                list.add(pTheme);
            }
            if (!file.delete()) {
                file.deleteOnExit();
            }
            if (list.size() > 0) {
                int uid = NumberUtils.toInt(file.getName().substring(0, file.getName().length() - 4), -1);
                if (uid != -1) {
                    map.put(uid, list);
                }
            }

        }
        //Convert  <com.edgenius.wiki.PageTheme> to <PageTheme>
        Server server = new Server();
        Properties prop = FileUtil.loadProperties(root + Server.FILE);
        server.syncFrom(prop);
        String type = server.getDbType();

        DBLoader loader = new DBLoader();
        ConnectionProxy conn = null;

        XStream xs = new XStream();
        xs.processAnnotations(PageTheme.class);
        xs.processAnnotations(BlogMeta.class);
        xs.processAnnotations(BlogCategory.class);

        try {
            conn = loader.getConnection(type, server.getDbUrl(), server.getDbSchema(), server.getDbUsername(),
                    server.getDbPassword());
            for (Entry<Integer, List<PageTheme>> entry : map.entrySet()) {
                PreparedStatement stat1 = null, stat2 = null;
                ResultSet rs = null;
                try {
                    stat1 = conn.prepareStatement("select f.PUID, f.SETTING_VALUE,s.PUID  "
                            + "from EDG_CONF as f, EDG_SPACES as s where f.SETTING_TYPE='com.edgenius.wiki.SpaceSetting' "
                            + "and s.CONFIGURATION_PUID=f.PUID and s.PUID=?");
                    stat2 = conn.prepareStatement("update EDG_CONF set SETTING_VALUE=? where PUID=?");
                    stat1.setInt(1, entry.getKey());
                    rs = stat1.executeQuery();
                    if (rs.next()) {
                        int ID = rs.getInt(1);
                        SpaceSetting setting = (SpaceSetting) xs
                                .fromXML(StringUtils.trimToEmpty(rs.getString(2)));
                        setting.setPageThemes(entry.getValue());
                        String content = xs.toXML(setting);
                        //update
                        stat2.setString(1, content);
                        stat2.setInt(2, ID);
                        stat2.executeUpdate();
                        log.info("Update space setting  {} for page theme ", ID);
                    }
                } catch (Exception e) {
                    log.error("Update space setting failed " + entry.getKey(), e);
                } finally {
                    if (rs != null)
                        rs.close();
                    if (stat1 != null)
                        stat1.close();
                    if (stat2 != null)
                        stat2.close();
                }
            }
        } catch (Exception e) {
            log.error("update space setting failed with PageTheme", e);
        } finally {
            if (conn != null)
                conn.close();
        }

        //delete unnecessary files
        File f1 = new File(rootFile, "data/themes/defaultwiki.xml");
        f1.delete();
        File f2 = new File(rootFile, "data/themes/defaultblog.xml");
        f2.delete();
        File f3 = new File(rootFile, "data/themes/customized");
        if (f3.isDirectory() && f3.list().length == 0) {
            f3.delete();
        }

    } else {
        log.error("Unable to parse out theme directory {}", (root + "data/themes/customized"));
    }
}

From source file:com.aliyun.odps.conf.Configuration.java

private void loadResource(Properties properties, Object name, boolean quiet) {
    try {/*from   w  w  w  .jav a 2  s  .com*/
        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:org.canova.api.conf.Configuration.java

private void loadResource(Properties properties, Object name, boolean quiet) {
    try {/*from  w ww. j  av  a2s .  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.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:jef.tools.XMLUtils.java

private static DocumentBuilderFactory initFactory(boolean ignorComments, boolean namespaceAware) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setValidating(false); // DTD
    dbf.setIgnoringComments(ignorComments);
    dbf.setNamespaceAware(namespaceAware);
    // dbf.setCoalescing(true);//CDATA
    // ?Text???/*ww w. j  a v  a 2 s.  c o  m*/
    try {
        // dbf.setFeature("http://xml.org/sax/features/namespaces", false);
        // dbf.setFeature("http://xml.org/sax/features/validation", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (ParserConfigurationException e) {
        log.warn(
                "Your xerces implemention is too old to support 'load-dtd-grammar' and 'load-external-dtd' feature. Please upgrade xercesImpl.jar to 2.6.2 or above.");
    } catch (AbstractMethodError e) {
        log.warn(
                "Your xerces implemention is too old to support 'load-dtd-grammar' and 'load-external-dtd' feature. Please upgrade xercesImpl.jar to 2.6.2 or above.");
    }

    try {
        dbf.setAttribute("http://xml.org/sax/features/external-general-entities", false);
    } catch (IllegalArgumentException e) {
        log.warn("Your xerces implemention is too old to support 'external-general-entities' attribute.");
    }
    try {
        dbf.setAttribute("http://xml.org/sax/features/external-parameter-entities", false);
    } catch (IllegalArgumentException e) {
        log.warn("Your xerces implemention is too old to support 'external-parameter-entities' attribute.");
    }
    try {
        dbf.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (IllegalArgumentException e) {
        log.warn("Your xerces implemention is too old to support 'load-external-dtd' attribute.");
    }
    return dbf;
}

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

private Resource loadResource(Properties properties, Resource wrapper, boolean quiet) {
    String name = UNKNOWN_RESOURCE;
    try {/*from w  w w.  j a  v a 2  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 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);
    }
}