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:net.sf.l2j.gameserver.instancemanager.DimensionalRiftManager.java

public void loadSpawns() {
    int countGood = 0, countBad = 0;
    try {//from  w  w w  . j  a va 2  s. com
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringComments(true);
        File file = new File(Config.DATAPACK_ROOT + "/data/dimensionalRift.xml");
        if (!file.exists())
            throw new IOException();
        Document doc = factory.newDocumentBuilder().parse(file);
        NamedNodeMap attrs;
        byte type, roomId;
        int mobId, x, y, z, delay, count;
        L2Spawn spawnDat;
        L2NpcTemplate template;
        for (Node rift = doc.getFirstChild(); rift != null; rift = rift.getNextSibling()) {
            if ("rift".equalsIgnoreCase(rift.getNodeName())) {
                for (Node area = rift.getFirstChild(); area != null; area = area.getNextSibling()) {
                    if ("area".equalsIgnoreCase(area.getNodeName())) {
                        attrs = area.getAttributes();
                        type = Byte.parseByte(attrs.getNamedItem("type").getNodeValue());
                        for (Node room = area.getFirstChild(); room != null; room = room.getNextSibling()) {
                            if ("room".equalsIgnoreCase(room.getNodeName())) {
                                attrs = room.getAttributes();
                                roomId = Byte.parseByte(attrs.getNamedItem("id").getNodeValue());
                                for (Node spawn = room.getFirstChild(); spawn != null; spawn = spawn
                                        .getNextSibling()) {
                                    if ("spawn".equalsIgnoreCase(spawn.getNodeName())) {
                                        attrs = spawn.getAttributes();
                                        mobId = Integer.parseInt(attrs.getNamedItem("mobId").getNodeValue());
                                        delay = Integer.parseInt(attrs.getNamedItem("delay").getNodeValue());
                                        count = Integer.parseInt(attrs.getNamedItem("count").getNodeValue());
                                        template = NpcTable.getInstance().getTemplate(mobId);
                                        if (template == null)
                                            _log.warn("Template " + mobId + " not found!");
                                        if (!_rooms.containsKey(type))
                                            _log.warn("Type " + type + " not found!");
                                        else if (!_rooms.get(type).containsKey(roomId))
                                            _log.warn("Room " + roomId + " in Type " + type + " not found!");
                                        for (int i = 0; i < count; i++) {
                                            DimensionalRiftRoom riftRoom = _rooms.get(type).get(roomId);
                                            x = riftRoom.getRandomX();
                                            y = riftRoom.getRandomY();
                                            z = riftRoom.getTeleportCoords()[2];
                                            if (template != null && _rooms.containsKey(type)
                                                    && _rooms.get(type).containsKey(roomId)) {
                                                spawnDat = new L2Spawn(template);
                                                spawnDat.setAmount(1);
                                                spawnDat.setLocx(x);
                                                spawnDat.setLocy(y);
                                                spawnDat.setLocz(z);
                                                spawnDat.setHeading(-1);
                                                spawnDat.setRespawnDelay(delay);
                                                SpawnTable.getInstance().addNewSpawn(spawnDat, false);
                                                _rooms.get(type).get(roomId).getSpawns().add(spawnDat);
                                                countGood++;
                                            } else {
                                                countBad++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        _log.warn("Error on loading dimensional rift spawns: " + e);
        e.printStackTrace();
    }
    _log.info("DimensionalRiftManager: Loaded " + countGood + " dimensional rift spawns, " + countBad
            + " errors.");
}

From source file:com.l2jfree.gameserver.instancemanager.MapRegionManager.java

private void load() {
    for (File xml : Util.getDatapackFiles("mapregion", ".xml")) {
        Document doc = null;/*from   w  ww .java2  s  .  co m*/

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            factory.setValidating(true);
            factory.setIgnoringComments(true);

            doc = factory.newDocumentBuilder().parse(xml);
        } catch (Exception e) {
            _log.warn("MapRegionManager: Error while loading XML definition: " + xml.getName() + e, e);
            return;
        }

        try {
            parseDocument(doc);
        } catch (Exception e) {
            _log.warn("MapRegionManager: Error in XML definition: " + xml.getName() + e, e);
            return;
        }
    }
}

From source file:com.ecyrd.jspwiki.auth.authorize.XMLGroupDatabase.java

private void buildDOM() throws WikiSecurityException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);/*from   w w w . ja  v  a2s  . c  om*/
    factory.setExpandEntityReferences(false);
    factory.setIgnoringComments(true);
    factory.setNamespaceAware(false);
    try {
        m_dom = factory.newDocumentBuilder().parse(m_file);
        log.debug("Database successfully initialized");
        m_lastModified = m_file.lastModified();
        m_lastCheck = System.currentTimeMillis();
    } catch (ParserConfigurationException e) {
        log.error("Configuration error: " + e.getMessage());
    } catch (SAXException e) {
        log.error("SAX error: " + e.getMessage());
    } catch (FileNotFoundException e) {
        log.info("Group database not found; creating from scratch...");
    } catch (IOException e) {
        log.error("IO error: " + e.getMessage());
    }
    if (m_dom == null) {
        try {
            //
            // Create the DOM from scratch
            //
            m_dom = factory.newDocumentBuilder().newDocument();
            m_dom.appendChild(m_dom.createElement("groups"));
        } catch (ParserConfigurationException e) {
            log.fatal("Could not create in-memory DOM");
        }
    }

    // Ok, now go and read this sucker in
    if (m_dom != null) {
        NodeList groupNodes = m_dom.getElementsByTagName(GROUP_TAG);
        for (int i = 0; i < groupNodes.getLength(); i++) {
            Element groupNode = (Element) groupNodes.item(i);
            String groupName = groupNode.getAttribute(GROUP_NAME);
            if (groupName == null) {
                log.warn("Detected null group name in XMLGroupDataBase. Check your group database.");
            } else {
                Group group = buildGroup(groupNode, groupName);
                m_groups.put(groupName, group);
            }
        }
    }
}

From source file:com.l2jfree.gameserver.instancemanager.CursedWeaponsManager.java

private final void load() {
    Connection con = null;/*from   ww  w.j a v a 2 s .co  m*/

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

        File file = new File(Config.DATAPACK_ROOT, "data/cursedWeapons.xml");
        if (!file.exists())
            throw new IOException();

        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 = attrs.getNamedItem("name").getNodeValue();

                        CursedWeapon cw = new CursedWeapon(id, skillId, name);

                        int val;
                        for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) {
                            if ("dropRate".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                                cw.setDropRate(val);
                            } else if ("duration".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                                cw.setDuration(val);
                            } else if ("durationLost".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                                cw.setDurationLost(val);
                            } else if ("disapearChance".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                                cw.setDisapearChance(val);
                            } else if ("stageKills".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                                cw.setStageKills(val);
                            } else if ("transformId".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                                cw.setTransformId(val);
                            }
                        }

                        // Store cursed weapon
                        _cursedWeapons.put(id, cw);
                    }
                }
            }
        }

        // Retrieve the L2Player from the characters table of the database
        con = L2DatabaseFactory.getInstance().getConnection();

        if (Config.ALLOW_CURSED_WEAPONS) {
            PreparedStatement statement = con.prepareStatement(
                    "SELECT itemId, charId, playerKarma, playerPkKills, nbKills, endTime FROM cursed_weapons");
            ResultSet rset = statement.executeQuery();

            while (rset.next()) {
                int itemId = rset.getInt("itemId");
                int playerId = rset.getInt("charId");
                int playerKarma = rset.getInt("playerKarma");
                int playerPkKills = rset.getInt("playerPkKills");
                int nbKills = rset.getInt("nbKills");
                long endTime = rset.getLong("endTime");

                CursedWeapon cw = _cursedWeapons.get(itemId);
                cw.setPlayerId(playerId);
                cw.setPlayerKarma(playerKarma);
                cw.setPlayerPkKills(playerPkKills);
                cw.setNbKills(nbKills);
                cw.setEndTime(endTime);
                cw.reActivate();
            }

            rset.close();
            statement.close();
        } else {
            PreparedStatement statement = con.prepareStatement("TRUNCATE TABLE cursed_weapons");
            ResultSet rset = statement.executeQuery();
            rset.close();
            statement.close();
        }

        //L2DatabaseFactory.close(con);

        // Retrieve the L2Player from the characters table of the database
        //con = L2DatabaseFactory.getInstance().getConnection(con);

        for (CursedWeapon cw : _cursedWeapons.values()) {
            if (cw.isActivated())
                continue;

            // Do an item check to be sure that the cursed weapon isn't hold by someone
            int itemId = cw.getItemId();
            try {
                PreparedStatement statement = con
                        .prepareStatement("SELECT owner_id FROM items WHERE item_id=?");
                statement.setInt(1, itemId);
                ResultSet rset = statement.executeQuery();

                if (rset.next()) {
                    // A player has the cursed weapon in his inventory ...
                    int playerId = rset.getInt("owner_id");
                    _log.info("PROBLEM : Player " + playerId + " owns the cursed weapon " + itemId
                            + " but he shouldn't.");

                    // Delete the item
                    PreparedStatement statement2 = con
                            .prepareStatement("DELETE FROM items WHERE owner_id=? AND item_id=?");
                    statement2.setInt(1, playerId);
                    statement2.setInt(2, itemId);
                    if (statement2.executeUpdate() != 1) {
                        _log.warn("Error while deleting cursed weapon " + itemId + " from userId " + playerId);
                    }
                    statement2.close();

                    // Delete the skill
                    /*
                    statement = con.prepareStatement("DELETE FROM character_skills WHERE charId=? AND skill_id=");
                    statement.setInt(1, playerId);
                    statement.setInt(2, cw.getSkillId());
                    if (statement.executeUpdate() != 1)
                    {
                        _log.warn("Error while deleting cursed weapon "+itemId+" skill from userId "+playerId);
                    }
                    */
                    // Restore the player's old karma and pk count
                    statement2 = con
                            .prepareStatement("UPDATE characters SET karma=?, pkkills=? WHERE charId = ?");
                    statement2.setInt(1, cw.getPlayerKarma());
                    statement2.setInt(2, cw.getPlayerPkKills());
                    statement2.setInt(3, playerId);
                    if (statement2.executeUpdate() != 1) {
                        _log.warn("Error while updating karma & pkkills for charId " + cw.getPlayerId());
                    }
                    statement2.close();
                    // clean up the cursedweapons table.
                    removeFromDb(itemId);
                }
                rset.close();
                statement.close();
            } catch (Exception e) {
                _log.warn("", e);
            }
        }
    } catch (Exception e) {
        _log.warn("Could not load CursedWeapons data: ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }

    _log.info("CursedWeaponsManager: loaded " + _cursedWeapons.size() + " cursed weapon(s).");
}

From source file:gov.nasa.ensemble.core.jscience.csvxml.ProfileLoader.java

private Document loadColumnDefinitions(InputStream stream)
        throws FileNotFoundException, SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    docBuilderFactory.setIgnoringComments(true);
    docBuilderFactory.setIgnoringElementContentWhitespace(true);
    CensoringInputStream fileContentsWithoutCsv = new CensoringInputStream(stream);
    Document document = docBuilder.parse(new InputSource(fileContentsWithoutCsv));
    nCharactersPrecedingData = fileContentsWithoutCsv.getNCharactersPrecedingData();
    return document;
}

From source file:com.l2jfree.gameserver.instancemanager.DimensionalRiftManager.java

public void load() {
    int countGood = 0, countBad = 0;
    try {/*from   w  w w . java 2  s  . c  om*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        factory.setIgnoringComments(true);

        File file = new File(Config.DATAPACK_ROOT, "data/dimensionalRift.xml");
        if (!file.exists())
            throw new IOException();

        Document doc = factory.newDocumentBuilder().parse(file);
        NamedNodeMap attrs;
        byte type, roomId;
        int mobId, x, y, z, delay, count;
        L2Spawn spawnDat;
        L2NpcTemplate template;
        int xMin = 0, xMax = 0, yMin = 0, yMax = 0, zMin = 0, zMax = 0, xT = 0, yT = 0, zT = 0;
        boolean isBossRoom;

        for (Node rift = doc.getFirstChild(); rift != null; rift = rift.getNextSibling()) {
            if ("rift".equalsIgnoreCase(rift.getNodeName())) {
                for (Node area = rift.getFirstChild(); area != null; area = area.getNextSibling()) {
                    if ("area".equalsIgnoreCase(area.getNodeName())) {
                        attrs = area.getAttributes();
                        type = Byte.parseByte(attrs.getNamedItem("type").getNodeValue());

                        for (Node room = area.getFirstChild(); room != null; room = room.getNextSibling()) {
                            if ("room".equalsIgnoreCase(room.getNodeName())) {
                                attrs = room.getAttributes();
                                roomId = Byte.parseByte(attrs.getNamedItem("id").getNodeValue());
                                Node boss = attrs.getNamedItem("isBossRoom");
                                isBossRoom = boss != null && Boolean.parseBoolean(boss.getNodeValue());

                                for (Node coord = room.getFirstChild(); coord != null; coord = coord
                                        .getNextSibling()) {
                                    if ("teleport".equalsIgnoreCase(coord.getNodeName())) {
                                        attrs = coord.getAttributes();
                                        xT = Integer.parseInt(attrs.getNamedItem("x").getNodeValue());
                                        yT = Integer.parseInt(attrs.getNamedItem("y").getNodeValue());
                                        zT = Integer.parseInt(attrs.getNamedItem("z").getNodeValue());
                                    } else if ("zone".equalsIgnoreCase(coord.getNodeName())) {
                                        attrs = coord.getAttributes();
                                        xMin = Integer.parseInt(attrs.getNamedItem("xMin").getNodeValue());
                                        xMax = Integer.parseInt(attrs.getNamedItem("xMax").getNodeValue());
                                        yMin = Integer.parseInt(attrs.getNamedItem("yMin").getNodeValue());
                                        yMax = Integer.parseInt(attrs.getNamedItem("yMax").getNodeValue());
                                        zMin = Integer.parseInt(attrs.getNamedItem("zMin").getNodeValue());
                                        zMax = Integer.parseInt(attrs.getNamedItem("zMax").getNodeValue());
                                    }
                                }

                                if (!_rooms.containsKey(type))
                                    _rooms.put(type, new FastMap<Byte, DimensionalRiftRoom>());

                                _rooms.get(type).put(roomId, new DimensionalRiftRoom(type, roomId, xMin, xMax,
                                        yMin, yMax, zMin, zMax, xT, yT, zT, isBossRoom));

                                for (Node spawn = room.getFirstChild(); spawn != null; spawn = spawn
                                        .getNextSibling()) {
                                    if ("spawn".equalsIgnoreCase(spawn.getNodeName())) {
                                        attrs = spawn.getAttributes();
                                        mobId = Integer.parseInt(attrs.getNamedItem("mobId").getNodeValue());
                                        delay = Integer.parseInt(attrs.getNamedItem("delay").getNodeValue());
                                        count = Integer.parseInt(attrs.getNamedItem("count").getNodeValue());

                                        template = NpcTable.getInstance().getTemplate(mobId);
                                        if (template == null) {
                                            _log.warn("Template " + mobId + " not found!");
                                        }
                                        if (!_rooms.containsKey(type)) {
                                            _log.warn("Type " + type + " not found!");
                                        } else if (!_rooms.get(type).containsKey(roomId)) {
                                            _log.warn("Room " + roomId + " in Type " + type + " not found!");
                                        }

                                        for (int i = 0; i < count; i++) {
                                            DimensionalRiftRoom riftRoom = _rooms.get(type).get(roomId);
                                            x = riftRoom.getRandomX();
                                            y = riftRoom.getRandomY();
                                            z = riftRoom.getTeleportCoords()[2];

                                            if (template != null && _rooms.containsKey(type)
                                                    && _rooms.get(type).containsKey(roomId)) {
                                                spawnDat = new L2Spawn(template);
                                                spawnDat.setAmount(1);
                                                spawnDat.setLocx(x);
                                                spawnDat.setLocy(y);
                                                spawnDat.setLocz(z);
                                                spawnDat.setHeading(-1);
                                                spawnDat.setRespawnDelay(delay);
                                                SpawnTable.getInstance().addNewSpawn(spawnDat, false);
                                                _rooms.get(type).get(roomId).getSpawns().add(spawnDat);
                                                countGood++;
                                            } else {
                                                countBad++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        _log.warn("Error on loading dimensional rift spawns: ", e);
    }
    int typeSize = _rooms.keySet().size();
    int roomSize = 0;

    for (Byte b : _rooms.keySet())
        roomSize += _rooms.get(b).keySet().size();

    _log.info("DimensionalRiftManager: Loaded " + typeSize + " room types with " + roomSize + " rooms.");
    _log.info("DimensionalRiftManager: Loaded " + countGood + " dimensional rift spawns, " + countBad
            + " errors.");
}

From source file:org.opendatakit.aggregate.externalservice.REDCapServer.java

private void submitPost(String actionType, HttpEntity postentity, List<NameValuePair> qparam,
        CallingContext cc) {//from   ww w  .jav  a2 s. c o m

    try {
        HttpResponse response = this.sendHttpRequest(POST, getUrl(), postentity, qparam, cc);
        int statusCode = response.getStatusLine().getStatusCode();
        String responseString = WebUtils.readResponse(response);

        if (responseString.length() != 0) {
            DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();
            xmlFactory.setNamespaceAware(true);
            xmlFactory.setIgnoringComments(true);
            xmlFactory.setCoalescing(true);
            DocumentBuilder builder = xmlFactory.newDocumentBuilder();
            InputStream is = new ByteArrayInputStream(responseString.getBytes(UTF_CHARSET));
            Document doc;
            try {
                doc = builder.parse(is);
            } finally {
                is.close();
            }
            Element root = doc.getDocumentElement();

            NodeList errorNodes = root.getElementsByTagName("error");
            StringBuilder b = new StringBuilder();
            if (errorNodes != null) {
                for (int i = 0; i < errorNodes.getLength(); ++i) {
                    if (i != 0) {
                        b.append("\n");
                    }
                    Element e = (Element) errorNodes.item(i);
                    b.append(e.getTextContent());
                }
                String error = b.toString();
                if (error.length() != 0) {
                    throw new IllegalArgumentException(actionType + " to REDCap server failed. statusCode: "
                            + statusCode + " error: " + error);
                }
            }
        } else {
            // this seems to be the common case???
            logger.info(actionType + " to REDCap server returned no body");
        }

        if (statusCode != HttpStatus.SC_OK) {
            throw new IllegalArgumentException(
                    actionType + " to REDCap server failed - but no error content. Reason: "
                            + response.getStatusLine().getReasonPhrase() + " status code: " + statusCode);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalArgumentException(actionType + " to REDCap server failed - " + e.toString());
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        throw new IllegalArgumentException(actionType + " to REDCap server failed - " + e.toString());
    } catch (SAXException e) {
        e.printStackTrace();
        throw new IllegalArgumentException(actionType + " to REDCap server failed - " + e.toString());
    }
}

From source file:com.l2jfree.gameserver.model.entity.Instance.java

public void loadInstanceTemplate(String filename) {
    Document doc = null;/*from   ww  w .ja  va2 s.c  om*/
    File xml = new File(Config.DATAPACK_ROOT, "data/instances/" + filename);

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false); // DTD isn't used
        factory.setIgnoringComments(true);
        // Such validation will not find element 'instance'
        //SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        //factory.setSchema(sf.newSchema(new File(Config.DATAPACK_ROOT, "data/templates/instances.xsd")));
        doc = factory.newDocumentBuilder().parse(xml);

        for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
            if ("instance".equalsIgnoreCase(n.getNodeName())) {
                parseInstance(n);
            }
        }
    } catch (IOException e) {
        _log.warn("Instance: can not find " + xml.getAbsolutePath() + " !", e);
    } catch (Exception e) {
        _log.warn("Instance: error while loading " + xml.getAbsolutePath() + " !", e);
    }
}

From source file:com.edgenius.wiki.rss.RSSServiceImpl.java

/**
 * @param spaceUid/*  www .j  a v a  2  s.com*/
 * @param spaceUname
 * @param viewer
 * @param skipSecurityCheck 
 * @return
 * @throws FeedException
 */
private Document getFeedDom(Integer spaceUid, String spaceUname, User viewer, boolean skipSecurityCheck)
        throws FeedException {
    ReentrantReadWriteLock lock = null;
    Document dom;
    try {

        File feedFile = new File(FileUtil.getFullPath(rssRoot.getFile().getAbsolutePath(), spaceUid + ".xml"));
        if (!feedFile.exists()) {
            createFeed(spaceUname);
        }

        //do read lock! must after createFeed possibility, otherwise, deadlock 
        lock = lockMap.get(spaceUid.toString());
        if (lock == null) {
            lock = new ReentrantReadWriteLock();
            lockMap.put(spaceUid.toString(), lock);
        }
        lock.readLock().lock();
        //!!! DON'T USE JDOM - although I test DOM, JDOM, DOM4J: JDOM is fastest. And DOM and DOM4J almost 2 time slow. But
        //!!! JDOM is not thread safe, an infinite looping can happen while this method reading different XML source, 
        //in different thread, and SAXBuild are different instance! The problem is mostly caused by NameSpace.getNamespace(), 
        //which using static HashMap and cause HashMap dead lock!!!
        DocumentBuilder builder = xmlBuilderPool.poll();
        if (builder == null) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setCoalescing(true);
            factory.setIgnoringComments(true);
            builder = factory.newDocumentBuilder();
        }
        dom = builder.parse(feedFile);
        xmlBuilderPool.add(builder);

    } catch (Exception e) {
        log.error("Unable get feed " + spaceUname + " with excpetion ", e);
        throw new FeedException("Unable get feed " + spaceUname + " with excpetion " + e);
    } finally {
        if (lock != null)
            lock.readLock().unlock();
    }
    if (dom == null) {
        log.error("Unable get feed " + spaceUname);
        throw new FeedException("Unable get feed " + spaceUname);
    }

    //~~~~~~~~~~~~ Security filter
    if (!skipSecurityCheck) {
        //need filter out the page that viewer has not permission to read.  
        List<Node> forbidPageUuidList = new ArrayList<Node>();
        String pageUuid;
        Node ele;
        NodeList list = dom.getElementsByTagName(PageRSSModule.NS_PREFIX + ":" + PageRSSModule.PAGE_UUID);
        int len = list.getLength();
        for (int idx = 0; idx < len; idx++) {
            ele = list.item(idx);
            pageUuid = ele.getTextContent();
            if (!securityService.isAllowPageReading(spaceUname, pageUuid, viewer)) {
                log.info("User " + (viewer == null ? "anonymous" : viewer.getUsername())
                        + "  has not reading permission for pageUuid " + pageUuid + " on space " + spaceUname
                        + ". Feed item of this page is removed from RSS output.");
                forbidPageUuidList.add(ele.getParentNode());
            }

        }
        if (forbidPageUuidList.size() > 0) {
            NodeList cl = dom.getElementsByTagName(PageRSSModule.CHANNEL);
            if (cl.getLength() > 0) {
                //only one channel tag!
                Node channel = cl.item(0);
                for (Node element : forbidPageUuidList) {
                    channel.removeChild(element);
                }
            }
        }
    }
    return dom;
}

From source file:eu.stratosphere.nephele.plugins.PluginManager.java

@SuppressWarnings("unchecked")
private Map<String, AbstractPluginLoader> loadPlugins(final File configFile,
        final PluginLookupService pluginLookupService) {

    final Map<String, AbstractPluginLoader> tmpPluginList = new LinkedHashMap<String, AbstractPluginLoader>();

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

    try {/*from w  ww  .  j av  a  2 s  . c  o m*/

        final DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        final Document doc = builder.parse(configFile);

        if (doc == null) {
            LOG.error("Unable to load plugins: doc is null");
            return Collections.emptyMap();
        }

        final Element root = doc.getDocumentElement();
        if (root == null) {
            LOG.error("Unable to load plugins: root is null");
            return Collections.emptyMap();
        }

        if (!"plugins".equals(root.getNodeName())) {
            LOG.error("Unable to load plugins: unknown element " + root.getNodeName());
            return Collections.emptyMap();
        }

        final NodeList pluginNodes = root.getChildNodes();

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

            final Node pluginNode = pluginNodes.item(i);

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

            if (!"plugin".equals(pluginNode.getNodeName())) {
                LOG.error("Unable to load plugins: unknown element " + pluginNode.getNodeName());
                continue;
            }

            // Increase plugin counter
            ++pluginCounter;

            final NodeList pluginChildren = pluginNode.getChildNodes();
            String pluginName = null;
            String pluginClass = null;
            Configuration pluginConfiguration = null;

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

                final Node pluginChild = pluginChildren.item(j);

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

                if ("name".equals(pluginChild.getNodeName())) {
                    pluginName = getTextChild(pluginChild);
                    if (pluginName == null) {
                        LOG.error("Skipping plugin " + pluginCounter
                                + " from configuration because it does not provide a proper name");
                        continue;
                    }
                }

                if ("class".equals(pluginChild.getNodeName())) {
                    pluginClass = getTextChild(pluginChild);
                    if (pluginClass == null) {
                        LOG.error("Skipping plugin " + pluginCounter
                                + " from configuration because it does not provide a loader class");
                        continue;
                    }
                }

                if ("configuration".equals(pluginChild.getNodeName())) {

                    pluginConfiguration = new Configuration();

                    final NodeList configurationNodes = pluginChild.getChildNodes();
                    for (int k = 0; k < configurationNodes.getLength(); ++k) {

                        final Node configurationNode = configurationNodes.item(k);

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

                        if (!"property".equals(configurationNode.getNodeName())) {
                            LOG.error("Unexpected node " + configurationNode.getNodeName() + ", skipping...");
                            continue;
                        }

                        String key = null;
                        String value = null;

                        final NodeList properties = configurationNode.getChildNodes();
                        for (int l = 0; l < properties.getLength(); ++l) {

                            final Node property = properties.item(l);

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

                            if ("key".equals(property.getNodeName())) {
                                key = getTextChild(property);
                                if (key == null) {
                                    LOG.warn("Skipping configuration entry for plugin " + pluginName
                                            + " because of invalid key");
                                    continue;
                                }
                            }

                            if ("value".equals(property.getNodeName())) {
                                value = getTextChild(property);
                                if (value == null) {
                                    LOG.warn("Skipping configuration entry for plugin " + pluginName
                                            + " because of invalid value");
                                    continue;
                                }
                            }
                        }

                        if (key != null && value != null) {
                            pluginConfiguration.setString(key, value);
                        }
                    }

                }
            }

            if (pluginName == null) {
                LOG.error("Plugin " + pluginCounter + " does not provide a name, skipping...");
                continue;
            }

            if (pluginClass == null) {
                LOG.error("Plugin " + pluginCounter + " does not provide a loader class, skipping...");
                continue;
            }

            if (pluginConfiguration == null) {
                LOG.warn("Plugin " + pluginCounter
                        + " does not provide a configuration, using default configuration");
                pluginConfiguration = new Configuration();
            }

            Class<? extends AbstractPluginLoader> loaderClass;

            try {
                loaderClass = (Class<? extends AbstractPluginLoader>) Class.forName(pluginClass);
            } catch (ClassNotFoundException e) {
                LOG.error("Unable to load plugin " + pluginName + ": " + StringUtils.stringifyException(e));
                continue;
            }

            if (loaderClass == null) {
                LOG.error("Unable to load plugin " + pluginName + ": loaderClass is null");
                continue;
            }

            Constructor<? extends AbstractPluginLoader> constructor;
            try {
                constructor = (Constructor<? extends AbstractPluginLoader>) loaderClass
                        .getConstructor(String.class, Configuration.class, PluginLookupService.class);
            } catch (SecurityException e) {
                LOG.error("Unable to load plugin " + pluginName + ": " + StringUtils.stringifyException(e));
                continue;
            } catch (NoSuchMethodException e) {
                LOG.error("Unable to load plugin " + pluginName + ": " + StringUtils.stringifyException(e));
                continue;
            }

            if (constructor == null) {
                LOG.error("Unable to load plugin " + pluginName + ": constructor is null");
                continue;
            }

            AbstractPluginLoader pluginLoader = null;

            try {
                pluginLoader = constructor.newInstance(pluginName, pluginConfiguration, pluginLookupService);
            } catch (IllegalArgumentException e) {
                LOG.error("Unable to load plugin " + pluginName + ": " + StringUtils.stringifyException(e));
                continue;
            } catch (InstantiationException e) {
                LOG.error("Unable to load plugin " + pluginName + ": " + StringUtils.stringifyException(e));
                continue;
            } catch (IllegalAccessException e) {
                LOG.error("Unable to load plugin " + pluginName + ": " + StringUtils.stringifyException(e));
                continue;
            } catch (InvocationTargetException e) {
                LOG.error("Unable to load plugin " + pluginName + ": " + StringUtils.stringifyException(e));
                continue;
            }

            if (pluginLoader == null) {
                LOG.error("Unable to load plugin " + pluginName + ": pluginLoader is null");
                continue;
            }

            LOG.info("Successfully loaded plugin " + pluginName);
            tmpPluginList.put(pluginName, pluginLoader);
        }

    } catch (IOException e) {
        LOG.error("Error while loading plugins: " + StringUtils.stringifyException(e));
    } catch (SAXException e) {
        LOG.error("Error while loading plugins: " + StringUtils.stringifyException(e));
    } catch (ParserConfigurationException e) {
        LOG.error("Error while loading plugins: " + StringUtils.stringifyException(e));
    }

    return Collections.unmodifiableMap(tmpPluginList);
}