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:eu.stratosphere.nephele.configuration.GlobalConfiguration.java

/**
 * Loads an XML document of key-values pairs.
 * //www. j a  v  a 2 s. c o m
 * @param file
 *        the XML document file
 */
private void loadResource(final File file) {

    final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    // Ignore comments in the XML file
    docBuilderFactory.setIgnoringComments(true);
    docBuilderFactory.setNamespaceAware(true);

    // TODO: Trying to set this option causes an exception. What do we need it for? (DW)
    /*
     * try {
     * docBuilderFactory.setXIncludeAware(true);
     * } catch (UnsupportedOperationException e) {
     * LOG.error("Failed to set setXIncludeAware(true) for parser " + docBuilderFactory + ":" + e, e);
     * }
     */

    try {

        final DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        Document doc = null;
        Element root = null;

        doc = builder.parse(file);

        if (doc == null) {
            LOG.warn("Cannot load configuration: doc is null");
            return;
        }

        root = doc.getDocumentElement();
        if (root == null) {
            LOG.warn("Cannot load configuration: root is null");
            return;
        }

        if (!"configuration".equals(root.getNodeName())) {
            LOG.warn("Cannot load configuration: unknown element " + root.getNodeName());
            return;
        }

        final NodeList props = root.getChildNodes();
        int propNumber = -1;

        synchronized (this.confData) {

            for (int i = 0; i < props.getLength(); i++) {

                final Node propNode = props.item(i);
                String key = null;
                String value = null;

                // Ignore text at this point
                if (propNode instanceof Text) {
                    continue;
                }

                if (!(propNode instanceof Element)) {
                    LOG.warn("Error while reading configuration: " + propNode.getNodeName()
                            + " is not of type element");
                    continue;
                }

                Element property = (Element) propNode;
                if (!"property".equals(property.getNodeName())) {
                    LOG.warn("Error while reading configuration: unknown element " + property.getNodeName());
                    continue;
                }

                propNumber++;
                final NodeList propChildren = property.getChildNodes();
                if (propChildren == null) {
                    LOG.warn("Error while reading configuration: property has no children, skipping...");
                    continue;
                }

                for (int j = 0; j < propChildren.getLength(); j++) {

                    final Node propChild = propChildren.item(j);
                    if (propChild instanceof Element) {
                        if ("key".equals(propChild.getNodeName())) {
                            if (propChild.getChildNodes() != null) {
                                if (propChild.getChildNodes().getLength() == 1) {
                                    if (propChild.getChildNodes().item(0) instanceof Text) {
                                        final Text t = (Text) propChild.getChildNodes().item(0);
                                        key = t.getTextContent();
                                    }
                                }
                            }
                        }

                        if ("value".equals(propChild.getNodeName())) {
                            if (propChild.getChildNodes() != null) {
                                if (propChild.getChildNodes().getLength() == 1) {
                                    if (propChild.getChildNodes().item(0) instanceof Text) {
                                        final Text t = (Text) propChild.getChildNodes().item(0);
                                        value = t.getTextContent();
                                    }
                                }
                            }
                        }
                    }
                }

                if (key != null && value != null) {
                    // Put key, value pair into the map
                    LOG.debug("Loading configuration property: " + key + ", " + value);
                    this.confData.put(key, value);
                } else {
                    LOG.warn("Error while reading configuration: Cannot read property " + propNumber);
                    continue;
                }
            }
        }

    } catch (ParserConfigurationException e) {
        LOG.warn("Cannot load configuration: " + StringUtils.stringifyException(e));
    } catch (IOException e) {
        LOG.warn("Cannot load configuration: " + StringUtils.stringifyException(e));
    } catch (SAXException e) {
        LOG.warn("Cannot load configuration: " + StringUtils.stringifyException(e));
    }
}

From source file:lineage2.gameserver.instancemanager.CursedWeaponsManager.java

/**
 * Method load.//from   ww  w .j  av a2s. co m
 */
private void load() {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringComments(true);
        File file = new File(Config.DATAPACK_ROOT, "data/xml/other/cursed_weapons.xml");
        if (!file.exists()) {
            return;
        }
        Document doc = factory.newDocumentBuilder().parse(file);
        for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
            if ("list".equalsIgnoreCase(n.getNodeName())) {
                for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                    if ("item".equalsIgnoreCase(d.getNodeName())) {
                        NamedNodeMap attrs = d.getAttributes();
                        int id = Integer.parseInt(attrs.getNamedItem("id").getNodeValue());
                        int skillId = Integer.parseInt(attrs.getNamedItem("skillId").getNodeValue());
                        String name = "Unknown cursed weapon";
                        if (attrs.getNamedItem("name") != null) {
                            name = attrs.getNamedItem("name").getNodeValue();
                        } else if (ItemHolder.getInstance().getTemplate(id) != null) {
                            name = ItemHolder.getInstance().getTemplate(id).getName();
                        }
                        if (id == 0) {
                            continue;
                        }
                        CursedWeapon cw = new CursedWeapon(id, skillId, name);
                        for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) {
                            if ("dropRate".equalsIgnoreCase(cd.getNodeName())) {
                                cw.setDropRate(Integer
                                        .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue()));
                            } else if ("duration".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                cw.setDurationMin(Integer.parseInt(attrs.getNamedItem("min").getNodeValue()));
                                cw.setDurationMax(Integer.parseInt(attrs.getNamedItem("max").getNodeValue()));
                            } else if ("durationLost".equalsIgnoreCase(cd.getNodeName())) {
                                cw.setDurationLost(Integer
                                        .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue()));
                            } else if ("disapearChance".equalsIgnoreCase(cd.getNodeName())) {
                                cw.setDisapearChance(Integer
                                        .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue()));
                            } else if ("stageKills".equalsIgnoreCase(cd.getNodeName())) {
                                cw.setStageKills(Integer
                                        .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue()));
                            } else if ("transformationId".equalsIgnoreCase(cd.getNodeName())) {
                                cw.setTransformationId(Integer
                                        .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue()));
                            } else if ("transformationTemplateId".equalsIgnoreCase(cd.getNodeName())) {
                                cw.setTransformationTemplateId(Integer
                                        .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue()));
                            } else if ("transformationName".equalsIgnoreCase(cd.getNodeName())) {
                                cw.setTransformationName(cd.getAttributes().getNamedItem("val").getNodeValue());
                            }
                        }
                        _cursedWeaponsMap.put(id, cw);
                    }
                }
            }
        }
        _cursedWeapons = _cursedWeaponsMap.values(new CursedWeapon[_cursedWeaponsMap.size()]);
    } catch (Exception e) {
        _log.error("CursedWeaponsManager: Error parsing cursed_weapons file. " + e);
    }
}

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

private void parse() {
    for (File f : Util.getDatapackFiles("multisell", ".xml")) {
        try {/* w ww  .  j  a va  2 s .c o  m*/
            int id = Integer.parseInt(f.getName().replaceAll(".xml", ""));
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setIgnoringComments(true);
            Document doc = factory.newDocumentBuilder().parse(f);

            MultiSellListContainer list = parseDocument(doc);
            list.setListId(id);
            _entries.put(id, list);
        } catch (Exception e) {
            _log.fatal("Error in file " + f.getAbsolutePath(), e);
        }
    }
}

From source file:lineage2.gameserver.instancemanager.HellboundManager.java

/**
 * Method getHellboundSpawn.//  w ww.  j a va2s .  co  m
 */
private void getHellboundSpawn() {
    _list = new ArrayList<>();
    _spawnList = new ArrayList<>();
    try {
        File file = new File(Config.DATAPACK_ROOT + "/data/xml/other/hellbound_spawnlist.xml");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringComments(true);
        Document doc1 = factory.newDocumentBuilder().parse(file);
        int counter = 0;
        for (Node n1 = doc1.getFirstChild(); n1 != null; n1 = n1.getNextSibling()) {
            if ("list".equalsIgnoreCase(n1.getNodeName())) {
                for (Node d1 = n1.getFirstChild(); d1 != null; d1 = d1.getNextSibling()) {
                    if ("data".equalsIgnoreCase(d1.getNodeName())) {
                        counter++;
                        int npcId = Integer.parseInt(d1.getAttributes().getNamedItem("npc_id").getNodeValue());
                        Location spawnLoc = null;
                        if (d1.getAttributes().getNamedItem("loc") != null) {
                            spawnLoc = Location.parseLoc(d1.getAttributes().getNamedItem("loc").getNodeValue());
                        }
                        int count = 1;
                        if (d1.getAttributes().getNamedItem("count") != null) {
                            count = Integer.parseInt(d1.getAttributes().getNamedItem("count").getNodeValue());
                        }
                        int respawn = 60;
                        if (d1.getAttributes().getNamedItem("respawn") != null) {
                            respawn = Integer
                                    .parseInt(d1.getAttributes().getNamedItem("respawn").getNodeValue());
                        }
                        int respawnRnd = 0;
                        if (d1.getAttributes().getNamedItem("respawn_rnd") != null) {
                            respawnRnd = Integer
                                    .parseInt(d1.getAttributes().getNamedItem("respawn_rnd").getNodeValue());
                        }
                        Node att = d1.getAttributes().getNamedItem("stage");
                        StringTokenizer st = new StringTokenizer(att.getNodeValue(), ";");
                        int tokenCount = st.countTokens();
                        int[] stages = new int[tokenCount];
                        for (int i = 0; i < tokenCount; i++) {
                            Integer value = Integer.decode(st.nextToken().trim());
                            stages[i] = value;
                        }
                        Territory territory = null;
                        for (Node s1 = d1.getFirstChild(); s1 != null; s1 = s1.getNextSibling()) {
                            if ("territory".equalsIgnoreCase(s1.getNodeName())) {
                                Polygon poly = new Polygon();
                                for (Node s2 = s1.getFirstChild(); s2 != null; s2 = s2.getNextSibling()) {
                                    if ("add".equalsIgnoreCase(s2.getNodeName())) {
                                        int x = Integer
                                                .parseInt(s2.getAttributes().getNamedItem("x").getNodeValue());
                                        int y = Integer
                                                .parseInt(s2.getAttributes().getNamedItem("y").getNodeValue());
                                        int minZ = Integer.parseInt(
                                                s2.getAttributes().getNamedItem("zmin").getNodeValue());
                                        int maxZ = Integer.parseInt(
                                                s2.getAttributes().getNamedItem("zmax").getNodeValue());
                                        poly.add(x, y).setZmin(minZ).setZmax(maxZ);
                                    }
                                }
                                territory = new Territory().add(poly);
                                if (!poly.validate()) {
                                    _log.error("HellboundManager: Invalid spawn territory : " + poly + "!");
                                    continue;
                                }
                            }
                        }
                        if ((spawnLoc == null) && (territory == null)) {
                            _log.error("HellboundManager: no spawn data for npc id : " + npcId + "!");
                            continue;
                        }
                        HellboundSpawn hbs = new HellboundSpawn(npcId, spawnLoc, count, territory, respawn,
                                respawnRnd, stages);
                        _list.add(hbs);
                    }
                }
            }
        }
        _log.info("HellboundManager: Loaded " + counter + " spawn entries.");
    } catch (Exception e) {
        _log.warn("HellboundManager: Spawn table could not be initialized.");
        e.printStackTrace();
    }
}

From source file:de.knowwe.defi.usermanager.XMLUserDatabase.java

private void buildDOM() {
    // Read DOM/*from   w w w . j  a v  a2 s. c om*/
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    factory.setExpandEntityReferences(false);
    factory.setIgnoringComments(true);
    factory.setNamespaceAware(false);
    try {
        c_dom = factory.newDocumentBuilder().parse(c_file);
        Log.fine("Database successfully initialized");
        c_lastModified = c_file.lastModified();
        c_lastCheck = System.currentTimeMillis();
    } catch (ParserConfigurationException e) {
        Log.severe("Configuration error: " + e.getMessage());
    } catch (SAXException e) {
        Log.severe("SAX error: " + e.getMessage());
    } catch (FileNotFoundException e) {
        Log.info("User database not found; creating from scratch...");
    } catch (IOException e) {
        Log.severe("IO error: " + e.getMessage());
    }
    if (c_dom == null) {
        try {
            //
            //  Create the DOM from scratch
            //
            c_dom = factory.newDocumentBuilder().newDocument();
            c_dom.appendChild(c_dom.createElement("users"));
        } catch (ParserConfigurationException e) {
            Log.severe("Could not create in-memory DOM");
        }
    }
}

From source file:eu.stratosphere.configuration.GlobalConfiguration.java

/**
 * Loads an XML document of key-values pairs.
 * /*from   w  w w  . ja  va2  s .com*/
 * @param file
 *        the XML document file
 */
private void loadXMLResource(final File file) {

    final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    // Ignore comments in the XML file
    docBuilderFactory.setIgnoringComments(true);
    docBuilderFactory.setNamespaceAware(true);

    try {

        final DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        Document doc = null;
        Element root = null;

        doc = builder.parse(file);

        if (doc == null) {
            LOG.warn("Cannot load configuration: doc is null");
            return;
        }

        root = doc.getDocumentElement();
        if (root == null) {
            LOG.warn("Cannot load configuration: root is null");
            return;
        }

        if (!"configuration".equals(root.getNodeName())) {
            LOG.warn("Cannot load configuration: unknown element " + root.getNodeName());
            return;
        }

        final NodeList props = root.getChildNodes();
        int propNumber = -1;

        synchronized (this.confData) {

            for (int i = 0; i < props.getLength(); i++) {

                final Node propNode = props.item(i);
                String key = null;
                String value = null;

                // Ignore text at this point
                if (propNode instanceof Text) {
                    continue;
                }

                if (!(propNode instanceof Element)) {
                    LOG.warn("Error while reading configuration: " + propNode.getNodeName()
                            + " is not of type element");
                    continue;
                }

                Element property = (Element) propNode;
                if (!"property".equals(property.getNodeName())) {
                    LOG.warn("Error while reading configuration: unknown element " + property.getNodeName());
                    continue;
                }

                propNumber++;
                final NodeList propChildren = property.getChildNodes();
                if (propChildren == null) {
                    LOG.warn("Error while reading configuration: property has no children, skipping...");
                    continue;
                }

                for (int j = 0; j < propChildren.getLength(); j++) {

                    final Node propChild = propChildren.item(j);
                    if (propChild instanceof Element) {
                        if ("key".equals(propChild.getNodeName())) {
                            if (propChild.getChildNodes() != null) {
                                if (propChild.getChildNodes().getLength() == 1) {
                                    if (propChild.getChildNodes().item(0) instanceof Text) {
                                        final Text t = (Text) propChild.getChildNodes().item(0);
                                        key = t.getTextContent();
                                    }
                                }
                            }
                        }

                        if ("value".equals(propChild.getNodeName())) {
                            if (propChild.getChildNodes() != null) {
                                if (propChild.getChildNodes().getLength() == 1) {
                                    if (propChild.getChildNodes().item(0) instanceof Text) {
                                        final Text t = (Text) propChild.getChildNodes().item(0);
                                        value = t.getTextContent();
                                    }
                                }
                            }
                        }
                    }
                }

                if (key != null && value != null) {
                    // Put key, value pair into the map
                    LOG.debug("Loading configuration property: " + key + ", " + value);
                    this.confData.put(key, value);
                } else {
                    LOG.warn("Error while reading configuration: Cannot read property " + propNumber);
                    continue;
                }
            }
        }

    } catch (ParserConfigurationException e) {
        LOG.warn("Cannot load configuration: " + StringUtils.stringifyException(e));
    } catch (IOException e) {
        LOG.warn("Cannot load configuration: " + StringUtils.stringifyException(e));
    } catch (SAXException e) {
        LOG.warn("Cannot load configuration: " + StringUtils.stringifyException(e));
    }
}

From source file:fr.lirmm.yamplusplus.yampponline.YamFileHandler.java

/**
 * Take a OAEI AlignmentAPI string and use classic XML parser. To return a
 * JSONObject with onto URIs and containing a JSONArray with the data of the
 * alignment Format of the array: {srcOntologyURI: "http://onto1.fr",
 * tarOntologyUri; "http://onto2.fr", entities: [{"index": 1, "entity1":
 * "http://entity1.fr", "entity2": "http://entity2.fr", "relation":
 * "skos:exactMatch", "measure": 0.34, }]} We can't use AlignmentAPI parser
 * because of the "valid" property (trigger error at load
 *
 * @param oaeiResult/*from  w ww. j  a v a  2  s . c  o m*/
 * @return JSONObject
 * @throws org.xml.sax.SAXException
 * @throws java.io.IOException
 */
public JSONObject parseOaeiAlignmentFormat(String oaeiResult) throws SAXException, IOException {
    JSONObject jObjectAlign = new JSONObject();
    JSONObject jObject = null;
    JSONArray jArray = new JSONArray();

    /*<onto1>
    <Ontology rdf:about="http://chu-rouen.fr/cismef/CIF">
      <location>http://chu-rouen.fr/cismef/CIF</location>
    </Ontology>
    </onto1>
    <onto2>
    <Ontology rdf:about="http://chu-rouen.fr/cismef/MedlinePlus">
      <location>http://chu-rouen.fr/cismef/MedlinePlus</location>
    </Ontology>
    </onto2>*/
    // We need to iterate the XML file to add the valid field
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = null;
    try {
        docBuilder = docBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex);
    }

    docBuilderFactory.setIgnoringComments(true);
    DocumentBuilder builder = null;
    try {
        builder = docBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex);
    }
    Document doc = null;
    // Read OAEI alignment
    InputSource is = new InputSource(new StringReader(oaeiResult));

    doc = builder.parse(is);

    // Get source and target ontology URI
    Element srcOntoElem = (Element) doc.getElementsByTagName("onto1").item(0);
    jObjectAlign.put("srcOntologyURI", srcOntoElem.getElementsByTagName("Ontology").item(0).getAttributes()
            .getNamedItem("rdf:about").getNodeValue());

    Element tarOntoElem = (Element) doc.getElementsByTagName("onto2").item(0);
    jObjectAlign.put("tarOntologyURI", tarOntoElem.getElementsByTagName("Ontology").item(0).getAttributes()
            .getNamedItem("rdf:about").getNodeValue());

    // Iterate over Cell XML elements to get if valid or not
    int index = 0;
    NodeList nodes = doc.getElementsByTagName("Cell");
    for (int i = 0; i < nodes.getLength(); i++) {
        Element cellElem = (Element) nodes.item(i);

        // Get first node for each field (entities, relation, valid) in the Cell node
        // And add it to the JSON Array
        jObject = new JSONObject();
        jObject.put("index", index);
        jObject.put("entity1", cellElem.getElementsByTagName("entity1").item(0).getAttributes()
                .getNamedItem("rdf:resource").getNodeValue());
        jObject.put("entity2", cellElem.getElementsByTagName("entity2").item(0).getAttributes()
                .getNamedItem("rdf:resource").getNodeValue());
        jObject.put("relation", cellElem.getElementsByTagName("relation").item(0).getTextContent());
        jObject.put("measure",
                round(Double.parseDouble(cellElem.getElementsByTagName("measure").item(0).getTextContent())));

        index += 1;
        jArray.add(jObject);
    }
    // Put the array of entities in the alignment JSON object
    jObjectAlign.put("entities", jArray);
    return jObjectAlign;
}

From source file:dip.world.variant.VariantManager.java

/** 
 *   Initiaize the VariantManager. /*w ww.jav a  2s.  c o  m*/
 *   <p>
 *   An exception is thrown if no File paths are specified. A "." may be used
 *   to specify th ecurrent directory.
 *   <p>
 *   Loaded XML may be validated if the isValidating flag is set to true.
 *
 */
public static synchronized void init(final List<File> searchPaths, boolean isValidating)
        throws javax.xml.parsers.ParserConfigurationException, NoVariantsException {
    long ttime = System.currentTimeMillis();
    long vptime = ttime;
    Log.println("VariantManager.init()");

    if (searchPaths == null || searchPaths.isEmpty()) {
        throw new IllegalArgumentException();
    }

    if (vm != null) {
        // perform cleanup
        vm.variantMap.clear();
        vm.variants = new ArrayList<Variant>();
        vm.currentUCL = null;
        vm.currentPackageURL = null;

        vm.symbolPacks = new ArrayList<SymbolPack>();
        vm.symbolMap.clear();
    }

    vm = new VariantManager();

    // find plugins, create plugin loader
    final List<URL> pluginURLs = vm.searchForFiles(searchPaths, VARIANT_EXTENSIONS);

    // setup document builder
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {
        // this may improve performance, and really only apply to Xerces
        dbf.setAttribute("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.FALSE);
        dbf.setAttribute("http://apache.org/xml/properties/input-buffer-size", new Integer(4096));
        dbf.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
    } catch (Exception e) {
        Log.println("VM: Could not set XML feature.", e);
    }

    dbf.setValidating(isValidating);
    dbf.setCoalescing(false);
    dbf.setIgnoringComments(true);

    // setup variant parser
    XMLVariantParser variantParser = new XMLVariantParser(dbf);

    // for each plugin, attempt to find the "variants.xml" file inside. 
    // if it does not exist, we will not load the file. If it does, we will parse it,
    // and associate the variant with the URL in a hashtable.
    for (final URL pluginURL : pluginURLs) {
        URLClassLoader urlCL = new URLClassLoader(new URL[] { pluginURL });
        URL variantXMLURL = urlCL.findResource(VARIANT_FILE_NAME);
        if (variantXMLURL != null) {
            String pluginName = getFile(pluginURL);

            // parse variant description file, and create hash entry of variant object -> URL
            InputStream is = null;
            try {
                is = new BufferedInputStream(variantXMLURL.openStream());
                variantParser.parse(is, pluginURL);
                final List<Variant> variants = variantParser.getVariants();

                // add variants; variants with same name (but older versions) are
                // replaced with same-name newer versioned variants
                for (final Variant variant : variants) {
                    addVariant(variant, pluginName, pluginURL);
                }
            } catch (IOException e) {
                // display error dialog
                ErrorDialog.displayFileIO(null, e, pluginURL.toString());
            } catch (org.xml.sax.SAXException e) {
                // display error dialog
                ErrorDialog.displayGeneral(null, e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    // if we are in webstart, search for variants within webstart jars
    Enumeration<URL> enum2 = null;
    ClassLoader cl = null;

    if (vm.isInWebstart) {
        cl = vm.getClass().getClassLoader();

        try {
            enum2 = cl.getResources(VARIANT_FILE_NAME);
        } catch (IOException e) {
            enum2 = null;
        }

        if (enum2 != null) {
            while (enum2.hasMoreElements()) {
                URL variantURL = enum2.nextElement();

                // parse variant description file, and create hash entry of variant object -> URL
                InputStream is = null;
                String pluginName = getWSPluginName(variantURL);

                try {
                    is = new BufferedInputStream(variantURL.openStream());

                    variantParser.parse(is, variantURL);
                    final List<Variant> variants = variantParser.getVariants();

                    // add variants; variants with same name (but older versions) are
                    // replaced with same-name newer versioned variants
                    for (final Variant variant : variants) {
                        addVariant(variant, pluginName, variantURL);
                    }
                } catch (IOException e) {
                    // display error dialog
                    ErrorDialog.displayFileIO(null, e, variantURL.toString());
                } catch (org.xml.sax.SAXException e) {
                    // display error dialog
                    ErrorDialog.displayGeneral(null, e);
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        } // if(enum2 != null)
    }

    // check: did we find *any* variants? Throw an exception.
    if (vm.variantMap.isEmpty()) {
        StringBuffer msg = new StringBuffer(256);
        msg.append("No variants found on path: ");
        for (final File searchPath : searchPaths) {
            msg.append(searchPath);
            msg.append("; ");
        }

        throw new NoVariantsException(msg.toString());
    }

    Log.printTimed(vptime, "VariantManager: variant parsing time: ");

    ///////////////// SYMBOLS /////////////////////////

    // now, parse symbol packs
    XMLSymbolParser symbolParser = new XMLSymbolParser(dbf);

    // find plugins, create plugin loader
    final List<URL> pluginURLs2 = vm.searchForFiles(searchPaths, SYMBOL_EXTENSIONS);

    // for each plugin, attempt to find the "variants.xml" file inside. 
    // if it does not exist, we will not load the file. If it does, we will parse it,
    // and associate the variant with the URL in a hashtable.
    for (final URL pluginURL : pluginURLs2) {
        URLClassLoader urlCL = new URLClassLoader(new URL[] { pluginURL });
        URL symbolXMLURL = urlCL.findResource(SYMBOL_FILE_NAME);
        if (symbolXMLURL != null) {
            String pluginName = getFile(pluginURL);

            // parse variant description file, and create hash entry of variant object -> URL
            InputStream is = null;
            try {
                is = new BufferedInputStream(symbolXMLURL.openStream());
                symbolParser.parse(is, pluginURL);
                addSymbolPack(symbolParser.getSymbolPack(), pluginName, pluginURL);
            } catch (IOException e) {
                // display error dialog
                ErrorDialog.displayFileIO(null, e, pluginURL.toString());
            } catch (org.xml.sax.SAXException e) {
                // display error dialog
                ErrorDialog.displayGeneral(null, e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    // if we are in webstart, search for variants within webstart jars      
    enum2 = null;
    cl = null;

    if (vm.isInWebstart) {
        cl = vm.getClass().getClassLoader();

        try {
            enum2 = cl.getResources(SYMBOL_FILE_NAME);
        } catch (IOException e) {
            enum2 = null;
        }

        if (enum2 != null) {
            while (enum2.hasMoreElements()) {
                URL symbolURL = enum2.nextElement();

                // parse variant description file, and create hash entry of variant object -> URL
                InputStream is = null;
                String pluginName = getWSPluginName(symbolURL);

                try {
                    is = new BufferedInputStream(symbolURL.openStream());
                    symbolParser.parse(is, symbolURL);
                    addSymbolPack(symbolParser.getSymbolPack(), pluginName, symbolURL);
                } catch (IOException e) {
                    // display error dialog
                    ErrorDialog.displayFileIO(null, e, symbolURL.toString());
                } catch (org.xml.sax.SAXException e) {
                    // display error dialog
                    ErrorDialog.displayGeneral(null, e);
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        } // if(enum2 != null)
    } // if(isInWebStart)      

    // check: did we find *any* symbol packs? Throw an exception.
    if (vm.symbolMap.isEmpty()) {
        StringBuffer msg = new StringBuffer(256);
        msg.append("No SymbolPacks found on path: ");
        for (final File searchPath : searchPaths) {
            msg.append(searchPath);
            msg.append("; ");
        }

        throw new NoVariantsException(msg.toString());
    }
    Log.printTimed(ttime, "VariantManager: total parsing time: ");
}

From source file:com.connexta.arbitro.ConfigurationStore.java

/**
 * Private helper that parses the file and sets up the DOM tree.
 *///from  w w  w  . j  a  v  a 2s.  c o  m
private Node getRootNode(File configFile) throws ParsingException {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

    dbFactory.setIgnoringComments(true);
    dbFactory.setNamespaceAware(false);
    dbFactory.setValidating(false);

    DocumentBuilder db = null;
    try {
        db = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException pce) {
        throw new ParsingException("couldn't get a document builder", pce);
    }

    Document doc = null;
    InputStream stream = null;
    try {
        stream = new FileInputStream(configFile);
        doc = db.parse(stream);
    } catch (IOException ioe) {
        throw new ParsingException("failed to load the file ", ioe);
    } catch (SAXException saxe) {
        throw new ParsingException("error parsing the XML tree", saxe);
    } catch (IllegalArgumentException iae) {
        throw new ParsingException("no data to parse", iae);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                logger.error("Error while closing input stream");
            }
        }
    }

    Element root = doc.getDocumentElement();

    if (!root.getTagName().equals("config"))
        throw new ParsingException("unknown document type: " + root.getTagName());

    return root;
}

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

@SuppressWarnings("unchecked")
private final void load() {
    // Load the skillmap
    // Note: the skillmap data is only used when generating new augmentations
    // the client expects a different id in order to display the skill in the
    // items description...
    try {/*from   w w  w .j ava2  s.c om*/
        int badAugmantData = 0;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        factory.setIgnoringComments(true);

        File file = new File(Config.DATAPACK_ROOT + "/data/stats/augmentation/augmentation_skillmap.xml");
        if (!file.exists()) {
            _log.warn("The augmentation skillmap file is missing.");
            return;
        }

        Document doc = factory.newDocumentBuilder().parse(file);

        for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
            if ("list".equalsIgnoreCase(n.getNodeName())) {
                for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                    if ("augmentation".equalsIgnoreCase(d.getNodeName())) {
                        NamedNodeMap attrs = d.getAttributes();
                        int skillId = 0,
                                augmentationId = Integer.parseInt(attrs.getNamedItem("id").getNodeValue());
                        int skillLvL = 0;
                        String type = "blue";

                        for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) {
                            if ("skillId".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                skillId = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                            } else if ("skillLevel".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                skillLvL = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                            } else if ("type".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                type = attrs.getNamedItem("val").getNodeValue();
                            }
                        }
                        if (skillId == 0) {
                            _log.warn("Bad skillId in augmentation_skillmap.xml in the augmentationId:"
                                    + augmentationId);
                            badAugmantData++;
                            continue;
                        } else if (skillLvL == 0) {
                            _log.warn("Bad skillLevel in augmentation_skillmap.xml in the augmentationId:"
                                    + augmentationId);
                            badAugmantData++;
                            continue;
                        }
                        int k = (augmentationId - BLUE_START) / SKILLS_BLOCKSIZE;

                        if (type.equalsIgnoreCase("blue"))
                            ((ArrayList<Integer>) _blueSkills[k]).add(augmentationId);
                        else if (type.equalsIgnoreCase("purple"))
                            ((ArrayList<Integer>) _purpleSkills[k]).add(augmentationId);
                        else
                            ((ArrayList<Integer>) _redSkills[k]).add(augmentationId);

                        _allSkills.put(augmentationId, new augmentationSkill(skillId, skillLvL));
                    }
                }
            }
        }
        if (badAugmantData != 0)
            _log.info("AugmentationData: " + badAugmantData + " bad skill(s) were skipped.");
    } catch (Exception e) {
        _log.error("Error parsing augmentation_skillmap.xml.", e);
        return;
    }

    // Load the stats from xml
    for (int i = 1; i < 5; i++) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setIgnoringComments(true);

            File file = new File(
                    Config.DATAPACK_ROOT + "/data/stats/augmentation/augmentation_stats" + i + ".xml");
            if (!file.exists()) {
                _log.warn("The augmentation stat data file " + i + " is missing.");
                return;
            }

            Document doc = factory.newDocumentBuilder().parse(file);

            for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
                if ("list".equalsIgnoreCase(n.getNodeName())) {
                    for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                        if ("stat".equalsIgnoreCase(d.getNodeName())) {
                            NamedNodeMap attrs = d.getAttributes();
                            String statName = attrs.getNamedItem("name").getNodeValue();
                            float soloValues[] = null, combinedValues[] = null;

                            for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) {
                                if ("table".equalsIgnoreCase(cd.getNodeName())) {
                                    attrs = cd.getAttributes();
                                    String tableName = attrs.getNamedItem("name").getNodeValue();

                                    StringTokenizer data = new StringTokenizer(
                                            cd.getFirstChild().getNodeValue());
                                    FastList<Float> array = new FastList<Float>();
                                    while (data.hasMoreTokens())
                                        array.add(Float.parseFloat(data.nextToken()));

                                    if (tableName.equalsIgnoreCase("#soloValues")) {
                                        soloValues = new float[array.size()];
                                        int x = 0;
                                        for (float value : array)
                                            soloValues[x++] = value;
                                    } else {
                                        combinedValues = new float[array.size()];
                                        int x = 0;
                                        for (float value : array)
                                            combinedValues[x++] = value;
                                    }
                                }
                            }
                            // store this stat
                            ((ArrayList<augmentationStat>) _augStats[(i - 1)]).add(new augmentationStat(
                                    Stats.valueOfXml(statName), soloValues, combinedValues));
                        }
                    }
                }
            }
        } catch (Exception e) {
            _log.error("Error parsing augmentation_stats" + i + ".xml.", e);
            return;
        }

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setIgnoringComments(true);

            File file = new File(
                    Config.DATAPACK_ROOT + "/data/stats/augmentation/augmentation_jewel_stats" + i + ".xml");

            if (!file.exists()) {
                _log.warn("The jewel augmentation stat data file " + i + " is missing.");
                return;
            }

            Document doc = factory.newDocumentBuilder().parse(file);

            for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
                if ("list".equalsIgnoreCase(n.getNodeName())) {
                    for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                        if ("stat".equalsIgnoreCase(d.getNodeName())) {
                            NamedNodeMap attrs = d.getAttributes();
                            String statName = attrs.getNamedItem("name").getNodeValue();
                            float soloValues[] = null, combinedValues[] = null;

                            for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) {
                                if ("table".equalsIgnoreCase(cd.getNodeName())) {
                                    attrs = cd.getAttributes();
                                    String tableName = attrs.getNamedItem("name").getNodeValue();

                                    StringTokenizer data = new StringTokenizer(
                                            cd.getFirstChild().getNodeValue());
                                    FastList<Float> array = new FastList<Float>();
                                    while (data.hasMoreTokens())
                                        array.add(Float.parseFloat(data.nextToken()));

                                    if (tableName.equalsIgnoreCase("#soloValues")) {
                                        soloValues = new float[array.size()];
                                        int x = 0;
                                        for (float value : array)
                                            soloValues[x++] = value;
                                    } else {
                                        combinedValues = new float[array.size()];
                                        int x = 0;
                                        for (float value : array)
                                            combinedValues[x++] = value;
                                    }
                                }
                            }
                            // store this stat
                            ((ArrayList<augmentationStat>) _augAccStats[(i - 1)]).add(new augmentationStat(
                                    Stats.valueOfXml(statName), soloValues, combinedValues));
                        }
                    }
                }
            }
        } catch (Exception e) {
            _log.error("Error parsing jewel augmentation_stats" + i + ".xml.", e);
            return;
        }
    }
}