Example usage for javax.xml.parsers DocumentBuilder setEntityResolver

List of usage examples for javax.xml.parsers DocumentBuilder setEntityResolver

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder setEntityResolver.

Prototype


public abstract void setEntityResolver(EntityResolver er);

Source Link

Document

Specify the EntityResolver to be used to resolve entities present in the XML document to be parsed.

Usage

From source file:org.kuali.rice.ken.util.Util.java

/**
 * This method uses DOM to parse the input source of XML.
 * @param source the input source// w w w . j  av  a 2  s . co  m
 * @param validate whether to turn on validation
 * @param namespaceAware whether to turn on namespace awareness
 * @return Document the parsed (possibly validated) document
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 */
public static Document parse(final InputSource source, boolean validate, boolean namespaceAware,
        EntityResolver entityResolver) throws ParserConfigurationException, IOException, SAXException {
    // TODO: optimize this
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(validate);
    dbf.setNamespaceAware(namespaceAware);
    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
    DocumentBuilder db = dbf.newDocumentBuilder();
    if (entityResolver != null) {
        db.setEntityResolver(entityResolver);
    }
    db.setErrorHandler(new ErrorHandler() {
        public void warning(SAXParseException se) {
            LOG.warn("Warning parsing xml doc " + source, se);
        }

        public void error(SAXParseException se) throws SAXException {
            LOG.error("Error parsing xml doc " + source, se);
            throw se;
        }

        public void fatalError(SAXParseException se) throws SAXException {
            LOG.error("Fatal error parsing xml doc " + source, se);
            throw se;
        }
    });
    return db.parse(source);
}

From source file:org.kuali.rice.ken.xpath.XPathTest.java

protected Document getDocument(boolean namespaceAware, boolean validate) throws Exception {
    // TODO: optimize this
    final InputSource source = getTestXMLInputSource();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(validate);//from  w  w  w.j a v  a 2s . co  m
    dbf.setNamespaceAware(namespaceAware);
    dbf.setAttribute(JAXPConstants.JAXP_SCHEMA_LANGUAGE, JAXPConstants.W3C_XML_SCHEMA);
    DocumentBuilder db = dbf.newDocumentBuilder();
    LOG.info("Setting entityresolver");
    db.setEntityResolver(Util.getNotificationEntityResolver(services.getNotificationContentTypeService()));
    db.setErrorHandler(new SimpleErrorHandler(LOG));
    return db.parse(source);
}

From source file:org.kuali.rice.kew.xml.DocumentTypeXmlParserTest.java

private boolean validate(String docName) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);/*  ww  w  . ja  v  a  2  s  .co  m*/
    dbf.setNamespaceAware(true);
    dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            XMLConstants.W3C_XML_SCHEMA_NS_URI);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new org.kuali.rice.core.impl.impex.xml.ClassLoaderEntityResolver());
    db.setErrorHandler(new DefaultHandler() {
        @Override
        public void error(SAXParseException e) throws SAXException {
            this.fatalError(e);
        }

        @Override
        public void fatalError(SAXParseException e) throws SAXException {
            super.fatalError(e);
        }
    });
    try {
        db.parse(getClass().getResourceAsStream(docName + ".xml"));
        return true;
    } catch (SAXException se) {
        log.error("Error validating " + docName + ".xml", se);
        return false;
    }
}

From source file:org.lockss.plugin.clockss.wolterskluwer.WoltersKluwerXPathXmlMetadataParser.java

@Override
protected DocumentBuilder makeDocumentBuilder(DocumentBuilderFactory dbf) throws ParserConfigurationException {
    DocumentBuilder db = super.makeDocumentBuilder(dbf);
    db.setEntityResolver(new EntityResolver() {
        @Override//from  w w  w  .  j  a v  a 2 s  .com
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            if (systemId.contains("ovidbase.dtd")) {
                return new InputSource(getClass().getResourceAsStream("sgmlentities.dtd"));
            }
            return null;
        }
    });
    return db;
}

From source file:org.mapfish.print.map.readers.WMSServerInfo.java

protected static WMSServerInfo parseCapabilities(InputStream stream)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

    //we don't want the DTD to be checked and it's the only way I found
    documentBuilder.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            return new InputSource(new StringReader(""));
        }/*ww  w  .  j a  va  2  s.co  m*/
    });

    Document doc = documentBuilder.parse(stream);

    NodeList tileSets = doc.getElementsByTagName("TileSet");
    boolean isTileCache = (tileSets.getLength() > 0);

    final WMSServerInfo result = new WMSServerInfo();

    if (isTileCache) {
        result.tileCacheLayers = new HashMap<String, TileCacheLayerInfo>();

        NodeList layers = doc.getElementsByTagName("Layer");
        for (int i = 0; i < tileSets.getLength(); ++i) {
            final Node tileSet = tileSets.item(i);
            final Node layer = layers.item(i + 1);
            String resolutions = DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet, "Resolutions"));
            int width = Integer.parseInt(DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet, "Width")));
            int height = Integer
                    .parseInt(DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet, "Height")));
            Element bbox = DOMUtil.getFirstChildElement(layer, "BoundingBox");
            float minX = Float.parseFloat(DOMUtil.getAttrValue(bbox, "minx"));
            float minY = Float.parseFloat(DOMUtil.getAttrValue(bbox, "miny"));
            float maxX = Float.parseFloat(DOMUtil.getAttrValue(bbox, "maxx"));
            float maxY = Float.parseFloat(DOMUtil.getAttrValue(bbox, "maxy"));
            String format = DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet, "Format"));

            String layerName = DOMUtil.getChildText(DOMUtil.getFirstChildElement(layer, "Name"));
            final TileCacheLayerInfo info = new TileCacheLayerInfo(resolutions, width, height, minX, minY, maxX,
                    maxY, format);
            result.tileCacheLayers.put(layerName, info);
        }
    }

    return result;
}

From source file:org.omegat.filters.TestFilterBase.java

/**
 * Remove version and toolname, then compare.
 *//*from   w w w  .j  av  a  2  s . com*/
protected void compareTMX(File f1, File f2) throws Exception {
    XPathExpression exprVersion = XPathFactory.newInstance().newXPath()
            .compile("/tmx/header/@creationtoolversion");
    XPathExpression exprTool = XPathFactory.newInstance().newXPath().compile("/tmx/header/@creationtool");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setEntityResolver(TMXReader2.TMX_DTD_RESOLVER);

    Document doc1 = builder.parse(f1);
    Document doc2 = builder.parse(f2);

    Node n;

    n = (Node) exprVersion.evaluate(doc1, XPathConstants.NODE);
    n.setNodeValue("");

    n = (Node) exprVersion.evaluate(doc2, XPathConstants.NODE);
    n.setNodeValue("");

    n = (Node) exprTool.evaluate(doc1, XPathConstants.NODE);
    n.setNodeValue("");

    n = (Node) exprTool.evaluate(doc2, XPathConstants.NODE);
    n.setNodeValue("");

    assertXMLEqual(doc1, doc2);
}

From source file:org.openmrs.migration.MigrationHelper.java

public static Document parseXml(String xml) throws ParserConfigurationException {
    DocumentBuilder builder = factory.newDocumentBuilder();
    try {// www. j  a  va 2s .c  om
        // Disable resolution of external entities. See TRUNK-3942 
        builder.setEntityResolver(new EntityResolver() {

            public InputSource resolveEntity(String publicId, String systemId) {
                return new InputSource(new StringReader(""));
            }
        });

        return builder.parse(new InputSource(new StringReader(xml)));
    } catch (IOException ex) {
        return null;
    } catch (SAXException e) {
        return null;
    }
}

From source file:org.openmrs.module.logmanager.util.LogManagerUtils.java

/**
 * Reads a DOM document from the given reader
 * @param reader the reader to read from
 * @param resolver the entity resolver (may be null)
 * @return the document or null if document could not be read
 *//*from  ww w .ja  v a 2  s. com*/
public static Document readDocument(Reader reader, EntityResolver resolver) {
    try {
        // Get input source
        InputSource source = new InputSource(reader);

        // Read into parser
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();

        // Optionally set the entity resolver
        if (resolver != null)
            builder.setEntityResolver(resolver);

        return builder.parse(source);
    } catch (Exception e) {
        log.error(e);
        return null;
    }
}

From source file:org.openmrs.module.ModuleFileParser.java

/**
 * Get the module/* ww  w. j av a 2 s .  c om*/
 *
 * @return new module object
 */
public Module parse() throws ModuleException {

    Module module = null;
    JarFile jarfile = null;
    InputStream configStream = null;

    try {
        try {
            jarfile = new JarFile(moduleFile);
        } catch (IOException e) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.cannotGetJarFile"),
                    moduleFile.getName(), e);
        }

        // look for config.xml in the root of the module
        ZipEntry config = jarfile.getEntry("config.xml");
        if (config == null) {
            throw new ModuleException(Context.getMessageSourceService().getMessage("Module.error.noConfigFile"),
                    moduleFile.getName());
        }

        // get a config file stream
        try {
            configStream = jarfile.getInputStream(config);
        } catch (IOException e) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.cannotGetConfigFileStream"),
                    moduleFile.getName(), e);
        }

        // turn the config file into an xml document
        Document configDoc = null;
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            db.setEntityResolver(new EntityResolver() {

                @Override
                public InputSource resolveEntity(String publicId, String systemId)
                        throws SAXException, IOException {
                    // When asked to resolve external entities (such as a
                    // DTD) we return an InputSource
                    // with no data at the end, causing the parser to ignore
                    // the DTD.
                    return new InputSource(new StringReader(""));
                }
            });

            configDoc = db.parse(configStream);
        } catch (Exception e) {
            log.error("Error parsing config.xml: " + configStream.toString(), e);

            OutputStream out = null;
            String output = "";
            try {
                out = new ByteArrayOutputStream();
                // Now copy bytes from the URL to the output stream
                byte[] buffer = new byte[4096];
                int bytes_read;
                while ((bytes_read = configStream.read(buffer)) != -1) {
                    out.write(buffer, 0, bytes_read);
                }
                output = out.toString();
            } catch (Exception e2) {
                log.warn("Another error parsing config.xml", e2);
            } finally {
                try {
                    out.close();
                } catch (Exception e3) {
                }
            }

            log.error("config.xml content: " + output);
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.cannotParseConfigFile"),
                    moduleFile.getName(), e);
        }

        Element rootNode = configDoc.getDocumentElement();

        String configVersion = rootNode.getAttribute("configVersion").trim();

        if (!validConfigVersions.contains(configVersion)) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.invalidConfigVersion",
                            new Object[] { configVersion }, Context.getLocale()),
                    moduleFile.getName());
        }

        String name = getElement(rootNode, configVersion, "name").trim();
        String moduleId = getElement(rootNode, configVersion, "id").trim();
        String packageName = getElement(rootNode, configVersion, "package").trim();
        String author = getElement(rootNode, configVersion, "author").trim();
        String desc = getElement(rootNode, configVersion, "description").trim();
        String version = getElement(rootNode, configVersion, "version").trim();

        // do some validation
        if (name == null || name.length() == 0) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.nameCannotBeEmpty"),
                    moduleFile.getName());
        }
        if (moduleId == null || moduleId.length() == 0) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.idCannotBeEmpty"), name);
        }
        if (packageName == null || packageName.length() == 0) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.packageCannotBeEmpty"), name);
        }

        // create the module object
        module = new Module(name, moduleId, packageName, author, desc, version);

        // find and load the activator class
        module.setActivatorName(getElement(rootNode, configVersion, "activator").trim());

        module.setRequireDatabaseVersion(
                getElement(rootNode, configVersion, "require_database_version").trim());
        module.setRequireOpenmrsVersion(getElement(rootNode, configVersion, "require_version").trim());
        module.setUpdateURL(getElement(rootNode, configVersion, "updateURL").trim());
        module.setRequiredModulesMap(getRequiredModules(rootNode, configVersion));
        module.setAwareOfModulesMap(getAwareOfModules(rootNode, configVersion));
        module.setStartBeforeModulesMap(getStartBeforeModules(rootNode, configVersion));

        module.setAdvicePoints(getAdvice(rootNode, configVersion, module));
        module.setExtensionNames(getExtensions(rootNode, configVersion));

        module.setPrivileges(getPrivileges(rootNode, configVersion));
        module.setGlobalProperties(getGlobalProperties(rootNode, configVersion));

        module.setMessages(getMessages(rootNode, configVersion, jarfile, moduleId, version));

        module.setMappingFiles(getMappingFiles(rootNode, configVersion, jarfile));
        module.setPackagesWithMappedClasses(getPackagesWithMappedClasses(rootNode, configVersion));

        module.setConfig(configDoc);

        module.setMandatory(getMandatory(rootNode, configVersion, jarfile));

        module.setFile(moduleFile);

        module.setConditionalResources(getConditionalResources(rootNode));
    } finally {
        try {
            jarfile.close();
        } catch (Exception e) {
            log.warn("Unable to close jarfile: " + jarfile, e);
        }
        if (configStream != null) {
            try {
                configStream.close();
            } catch (Exception io) {
                log.error("Error while closing config stream for module: " + moduleFile.getAbsolutePath(), io);
            }
        }
    }

    return module;
}

From source file:org.openmrs.module.SqlDiffFileParser.java

/**
 * Get the diff map. Return a sorted map&lt;version, sql statements&gt;
 *
 * @return SortedMap&lt;String, String&gt;
 * @throws ModuleException//from   w w w  .ja  v a 2 s  .c  o  m
 */
public static SortedMap<String, String> getSqlDiffs(Module module) throws ModuleException {
    if (module == null) {
        throw new ModuleException("Module cannot be null");
    }

    SortedMap<String, String> map = new TreeMap<String, String>(new VersionComparator());

    InputStream diffStream = null;

    // get the diff stream
    JarFile jarfile = null;
    try {
        try {
            jarfile = new JarFile(module.getFile());
        } catch (IOException e) {
            throw new ModuleException("Unable to get jar file", module.getName(), e);
        }

        diffStream = ModuleUtil.getResourceFromApi(jarfile, module.getModuleId(), module.getVersion(),
                SQLDIFF_CHANGELOG_FILENAME);
        if (diffStream == null) {
            // Try the old way. Loading from the root of the omod
            ZipEntry diffEntry = jarfile.getEntry(SQLDIFF_CHANGELOG_FILENAME);
            if (diffEntry == null) {
                log.debug("No sqldiff.xml found for module: " + module.getName());
                return map;
            } else {
                try {
                    diffStream = jarfile.getInputStream(diffEntry);
                } catch (IOException e) {
                    throw new ModuleException("Unable to get sql diff file stream", module.getName(), e);
                }
            }
        }

        try {
            // turn the diff stream into an xml document
            Document diffDoc = null;
            try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                db.setEntityResolver(new EntityResolver() {

                    @Override
                    public InputSource resolveEntity(String publicId, String systemId)
                            throws SAXException, IOException {
                        // When asked to resolve external entities (such as a DTD) we return an InputSource
                        // with no data at the end, causing the parser to ignore the DTD.
                        return new InputSource(new StringReader(""));
                    }
                });
                diffDoc = db.parse(diffStream);
            } catch (Exception e) {
                throw new ModuleException("Error parsing diff sqldiff.xml file", module.getName(), e);
            }

            Element rootNode = diffDoc.getDocumentElement();

            String diffVersion = rootNode.getAttribute("version");

            if (!validConfigVersions().contains(diffVersion)) {
                throw new ModuleException("Invalid config version: " + diffVersion, module.getModuleId());
            }

            NodeList diffNodes = getDiffNodes(rootNode, diffVersion);

            if (diffNodes != null && diffNodes.getLength() > 0) {
                int i = 0;
                while (i < diffNodes.getLength()) {
                    Element el = (Element) diffNodes.item(i++);
                    String version = getElement(el, diffVersion, "version");
                    String sql = getElement(el, diffVersion, "sql");
                    map.put(version, sql);
                }
            }
        } catch (ModuleException e) {
            if (diffStream != null) {
                try {
                    diffStream.close();
                } catch (IOException io) {
                    log.error("Error while closing config stream for module: " + module.getModuleId(), io);
                }
            }

            // rethrow the moduleException
            throw e;
        }

    } finally {
        try {
            if (jarfile != null) {
                jarfile.close();
            }
        } catch (IOException e) {
            log.warn("Unable to close jarfile: " + jarfile.getName());
        }
    }
    return map;
}