Example usage for javax.xml.parsers DocumentBuilderFactory setValidating

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

Introduction

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

Prototype


public void setValidating(boolean validating) 

Source Link

Document

Specifies that the parser produced by this code will validate documents as they are parsed.

Usage

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.impl.RwsDataConnector.java

/**
 * Initializes the connector/*ww w  .j  ava  2  s.  com*/
 */
@Override
protected void doInitialize() throws ComponentInitializationException {
    super.doInitialize();

    if (httpDataSource == null) {
        throw new ComponentInitializationException(getLogPrefix() + " no http data source was configured");
    }

    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(false); // parameter
        domFactory.setValidating(false);
        String feature = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
        domFactory.setFeature(feature, false);
        feature = "http://apache.org/xml/features/nonvalidating/load-dtd-grammar";
        domFactory.setFeature(feature, false);
        documentBuilder = domFactory.newDocumentBuilder();

    } catch (ParserConfigurationException e) {
        log.error("javax.xml.parsers.ParserConfigurationException: " + e);
    }

    for (int i = 0; i < rwsAttributes.size(); i++) {
        RwsAttribute attr = rwsAttributes.get(i);
        try {
            XPath xpath = XPathFactory.newInstance().newXPath();
            log.debug("xpath for {} is {}", attr.name, attr.xPath);
            attr.xpathExpression = xpath.compile(attr.xPath);
        } catch (XPathExpressionException e) {
            log.error("xpath expr: " + e);
        }
    }

    // initializeCache();

}

From source file:userinterface.graph.Graph.java

/**
 * Method to load a PRISM 'gra' file into the application.
 * @param file Name of the file to load.
 * @return The model of the graph contained in the file.
 * @throws GraphException if I/O errors have occurred.
 *//*from  w w w  .  j a  v  a2s. c o m*/
public static Graph load(File file) throws GraphException {

    Graph graph = new Graph();

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setValidating(true);
        factory.setIgnoringElementContentWhitespace(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(graph);
        Document doc = builder.parse(file);
        Element chartFormat = doc.getDocumentElement();

        graph.setTitle(chartFormat.getAttribute("graphTitle"));

        String titleFontName = chartFormat.getAttribute("titleFontName");
        String titleFontSize = chartFormat.getAttribute("titleFontSize");
        String titleFontStyle = chartFormat.getAttribute("titleFontStyle");

        Font titleFont = parseFont(titleFontName, titleFontStyle, titleFontSize);

        String titleFontColourR = chartFormat.getAttribute("titleFontColourR");
        String titleFontColourG = chartFormat.getAttribute("titleFontColourG");
        String titleFontColourB = chartFormat.getAttribute("titleFontColourB");
        Color titleFontColour = parseColor(titleFontColourR, titleFontColourG, titleFontColourB);

        graph.setTitleFont(new FontColorPair(titleFont, titleFontColour));
        graph.setLegendVisible(parseBoolean(chartFormat.getAttribute("legendVisible")));

        String legendPosition = chartFormat.getAttribute("legendPosition");

        // Facilitate for bugs export in previous prism versions.
        if (chartFormat.getAttribute("versionString").equals(""))
            graph.setLegendPosition(RIGHT);
        else {
            if (legendPosition.equals("left"))
                graph.setLegendPosition(LEFT);
            else if (legendPosition.equals("right"))
                graph.setLegendPosition(RIGHT);
            else if (legendPosition.equals("bottom"))
                graph.setLegendPosition(BOTTOM);
            else if (legendPosition.equals("top"))
                graph.setLegendPosition(TOP);
            else // Probably was manual, now depricated
                graph.setLegendPosition(RIGHT);
        }

        //Get the nodes used to describe the various parts of the graph
        NodeList rootChildren = chartFormat.getChildNodes();

        // Element layout is depricated for now. 
        Element layout = (Element) rootChildren.item(0);
        Element xAxis = (Element) rootChildren.item(1);
        Element yAxis = (Element) rootChildren.item(2);

        graph.getXAxisSettings().load(xAxis);
        graph.getYAxisSettings().load(yAxis);

        //Read the headings and widths for each series 
        for (int i = 3; i < rootChildren.getLength(); i++) {
            Element series = (Element) rootChildren.item(i);
            SeriesKey key = graph.addSeries(series.getAttribute("seriesHeading"));

            synchronized (graph.getSeriesLock()) {
                SeriesSettings seriesSettings = graph.getGraphSeries(key);
                seriesSettings.load(series);

                NodeList graphChildren = series.getChildNodes();

                //Read each series out of the file and add its points to the graph
                for (int j = 0; j < graphChildren.getLength(); j++) {
                    Element point = (Element) graphChildren.item(j);
                    graph.addPointToSeries(key, new XYDataItem(parseDouble(point.getAttribute("x")),
                            parseDouble(point.getAttribute("y"))));
                }
            }
        }

        //Return the model of the graph 
        return graph;
    } catch (Exception e) {
        throw new GraphException("Error in loading chart: " + e);
    }
}

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

private final void load() {
    Connection con = null;/*from w w  w . j av a2s .  c  om*/

    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:com.l2jfree.gameserver.instancemanager.DimensionalRiftManager.java

public void load() {
    int countGood = 0, countBad = 0;
    try {/*  w  w  w  .  ja  v a2  s  .  c o  m*/
        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:com.interface21.beans.factory.xml.XmlBeanFactory.java

/**
 * Load definitions from the given input stream and close it.
 * @param is InputStream containing XML/*from w ww .java2s  .  c om*/
 */
public void loadBeanDefinitions(InputStream is) throws BeansException {
    if (is == null)
        throw new BeanDefinitionStoreException("InputStream cannot be null: expected an XML file", null);

    try {
        logger.info("Loading XmlBeanFactory from InputStream [" + is + "]");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        logger.debug("Using JAXP implementation [" + factory + "]");
        factory.setValidating(true);
        DocumentBuilder db = factory.newDocumentBuilder();
        db.setErrorHandler(new BeansErrorHandler());
        db.setEntityResolver(this.entityResolver != null ? this.entityResolver : new BeansDtdResolver());
        Document doc = db.parse(is);
        loadBeanDefinitions(doc);
    } catch (ParserConfigurationException ex) {
        throw new BeanDefinitionStoreException("ParserConfiguration exception parsing XML", ex);
    } catch (SAXException ex) {
        throw new BeanDefinitionStoreException("XML document is invalid", ex);
    } catch (IOException ex) {
        throw new BeanDefinitionStoreException("IOException parsing XML document", ex);
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException ex) {
            throw new FatalBeanException("IOException closing stream for XML document", ex);
        }
    }
}

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

/**
 * @param spaceUid/* www .  j a va2 s.co m*/
 * @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:com.l2jfree.gameserver.model.entity.Instance.java

public void loadInstanceTemplate(String filename) {
    Document doc = null;/*ww w.j a v  a2s  .  c  o  m*/
    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:org.squale.squaleweb.applicationlayer.action.export.ppt.PPTData.java

/**
 * Create a document with mapping file/*from ww  w. j  a  v  a  2  s. c  o m*/
 * 
 * @param mappingStream stream of mapping file
 * @throws PPTGeneratorException if error while parsing mapping file
 */
public void setMapping(InputStream mappingStream) throws PPTGeneratorException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new XmlResolver(PUBLIC_ID, DTD_LOCATION));
        db.setErrorHandler(new ParsingHandler(LOGGER, errors));
        mapping = db.parse(mappingStream);
        if (errors.length() > 0) {
            handleException("export.audit_report.mapping.error", new String[] { errors.toString() });
        }
    } catch (ParserConfigurationException e) {
        handleException("export.audit_report.mapping.error", new String[] { e.getMessage() });
    } catch (SAXException e) {
        handleException("export.audit_report.mapping.error", new String[] { e.getMessage() });
    } catch (IOException e) {
        handleException("export.audit_report.mapping.error", new String[] { e.getMessage() });
    }
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static Document parse(InputStream inputStream) throws IOException {
    try {/* w w  w. j a va 2  s  .  c o  m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setFeature("http://xml.org/sax/features/namespaces", true);
        // voodoo to turn off reading of DTDs during parsing. This is needed e.g. to pre-parse schemas
        factory.setValidating(false);
        factory.setFeature("http://xml.org/sax/features/validation", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        DocumentBuilder loader = factory.newDocumentBuilder();
        return loader.parse(inputStream);
    } catch (SAXException ex) {
        throw new IllegalStateException("Error parsing XML document " + ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        throw new IllegalStateException("Error parsing XML document " + ex.getMessage(), ex);
    }
}

From source file:com.ironiacorp.persistence.datasource.HibernateConfigurationUtil.java

/**
 * Load the current hibernate.cfg.xml./*w w w  .  ja  va  2s. c  om*/
 */
public void load() {
    File configFile = new File(contextPath + configFileSufix);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = null;

    log.debug("Loading configuration from file " + configFile.getAbsolutePath());
    try {
        factory.setValidating(true);
        factory.setNamespaceAware(false);
        // BUG 1: It try to validate.
        // BUG 2: 'null', following the specification, is a valid value.
        // Unfortunately,
        // the current implementation fails on it.
        // factory.setSchema( null );
        parser = factory.newDocumentBuilder();
        //         parser.setEntityResolver(new DTDEntityResolver());
        config = parser.parse(configFile);
    } catch (Exception e) {
        log.debug("Error loading the configuration: ", e);
    }
    NodeList propertiesNodes = config.getElementsByTagName("property");
    for (int i = 0; i < propertiesNodes.getLength(); i++) {
        Node propertyNode = propertiesNodes.item(i);

        // Get the property name
        NamedNodeMap attributesNodes = propertyNode.getAttributes();
        Node attributeNode = attributesNodes.getNamedItem("name");
        String property = attributeNode.getNodeValue();

        // Get the property value
        NodeList childrenNodes = propertyNode.getChildNodes();
        String value = null;
        for (int j = 0; j < childrenNodes.getLength(); j++) {
            Node childNode = childrenNodes.item(j);
            if (childNode.getNodeType() == Node.TEXT_NODE) {
                value = childNode.getNodeValue();
                break;
            }
        }

        if (property.equals("connection.driver_class") || property.equals("connection.url")
                || property.equals("connection.username") || property.equals("connection.password")
                || property.equals("dialect") || property.equals("hibernate.connection.datasource")
                || property.equals("hibernate.connection.username")
                || property.equals("hibernate.connection.password")) {
            preferences.put(property, value);
        }
    }
}