Example usage for org.xml.sax EntityResolver EntityResolver

List of usage examples for org.xml.sax EntityResolver EntityResolver

Introduction

In this page you can find the example usage for org.xml.sax EntityResolver EntityResolver.

Prototype

EntityResolver

Source Link

Usage

From source file:org.openstreetmap.josm.tools.ImageProvider.java

/**
 * Reads the wiki page on a certain file in html format in order to find the real image URL.
 *///from  w  w  w . j  a v a 2  s. c  o m
private static String getImgUrlFromWikiInfoPage(final String base, final String fn) {

    /** Quit parsing, when a certain condition is met */
    class SAXReturnException extends SAXException {
        private String result;

        public SAXReturnException(String result) {
            this.result = result;
        }

        public String getResult() {
            return result;
        }
    }

    try {
        final XMLReader parser = XMLReaderFactory.createXMLReader();
        parser.setContentHandler(new DefaultHandler() {
            @Override
            public void startElement(String uri, String localName, String qName, Attributes atts)
                    throws SAXException {
                System.out.println();
                if (localName.equalsIgnoreCase("img")) {
                    String val = atts.getValue("src");
                    if (val.endsWith(fn))
                        throw new SAXReturnException(val); // parsing done, quit early
                }
            }
        });

        parser.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                return new InputSource(new ByteArrayInputStream(new byte[0]));
            }
        });

        parser.parse(new InputSource(new MirroredInputStream(base + fn,
                new File(Main.pref.getPreferencesDir(), "images").toString())));
    } catch (SAXReturnException r) {
        return r.getResult();
    } catch (Exception e) {
        System.out.println("INFO: parsing " + base + fn + " failed:\n" + e);
        return null;
    }
    System.out.println("INFO: parsing " + base + fn + " failed: Unexpected content.");
    return null;
}

From source file:org.overlord.commons.karaf.commands.configure.AbstractConfigureCommand.java

/**
 * Applies XSLT to the given XML file. Note that the transformation is
 * *in-place*! It will simply overwrite the original file!
 *
 * @param xmlFile//from  w w w  .  j  a  v  a  2s .c om
 * @param xsltFile
 * @throws Exception
 */
protected void applyXslt(File xmlFile, InputStream xsltFile) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String pid, String sid) throws SAXException {
            return new InputSource(
                    AbstractConfigureCommand.class.getClassLoader().getResourceAsStream("xslt/configure.dtd")); //$NON-NLS-1$
        }
    });
    Document d = db.parse(xmlFile);
    DOMSource xml = new DOMSource(d);

    Source xslt = new StreamSource(xsltFile);
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(xslt);
    Result result = new StreamResult(xmlFile);
    transformer.transform(xml, result);
}

From source file:org.tolven.plugin.registry.xml.ManifestParser.java

private static EntityResolver getXSDEntityResolver() {
    EntityResolver e = 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 (TPFXSD == null) {
                return null;
            } else {
                return new InputSource(new StringReader(TPFXSD));
            }
        }
    };
    return e;
}

From source file:org.unitime.commons.hibernate.util.HibernateUtil.java

public static void configureHibernate(Properties properties) throws Exception {
    if (sSessionFactory != null) {
        sSessionFactory.close();// w w w .  j  a  v  a2 s .co  m
        sSessionFactory = null;
    }

    if (!NamingManager.hasInitialContextFactoryBuilder())
        NamingManager.setInitialContextFactoryBuilder(new LocalContext(null));

    sLog.info("Connecting to " + getProperty(properties, "connection.url"));
    ClassLoader classLoader = HibernateUtil.class.getClassLoader();
    sLog.debug("  -- class loader retrieved");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    sLog.debug("  -- document factory created");
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) {
            if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Mapping DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            }
            return null;
        }
    });
    sLog.debug("  -- document builder created");
    Document document = builder.parse(classLoader.getResource("hibernate.cfg.xml").openStream());
    sLog.debug("  -- hibernate.cfg.xml parsed");

    String dialect = getProperty(properties, "dialect");
    if (dialect != null)
        setProperty(document, "dialect", dialect);

    String idgen = getProperty(properties, "tmtbl.uniqueid.generator");
    if (idgen != null)
        setProperty(document, "tmtbl.uniqueid.generator", idgen);

    if (ApplicationProperty.HibernateClusterEnabled.isFalse())
        setProperty(document, "net.sf.ehcache.configurationResourceName", "ehcache-nocluster.xml");

    // Remove second level cache
    setProperty(document, "hibernate.cache.use_second_level_cache", "false");
    setProperty(document, "hibernate.cache.use_query_cache", "false");
    removeProperty(document, "hibernate.cache.region.factory_class");

    for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        if (name.startsWith("hibernate.") || name.startsWith("connection.")
                || name.startsWith("tmtbl.hibernate.")) {
            String value = properties.getProperty(name);
            if ("NULL".equals(value))
                removeProperty(document, name);
            else
                setProperty(document, name, value);
            if (!name.equals("connection.password"))
                sLog.debug("  -- set " + name + ": " + value);
            else
                sLog.debug("  -- set " + name + ": *****");
        }
    }

    String default_schema = getProperty(properties, "default_schema");
    if (default_schema != null)
        setProperty(document, "default_schema", default_schema);

    sLog.debug("  -- hibernate.cfg.xml altered");

    Configuration cfg = new Configuration();
    sLog.debug("  -- configuration object created");

    cfg.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) {
            if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Mapping DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            }
            return null;
        }
    });
    sLog.debug("  -- added entity resolver");

    cfg.configure(document);
    sLog.debug("  -- hibernate configured");

    fixSchemaInFormulas(cfg);

    UniqueIdGenerator.configure(cfg);

    (new _BaseRootDAO() {
        void setConf(Configuration cfg) {
            _BaseRootDAO.sConfiguration = cfg;
        }

        protected Class getReferenceClass() {
            return null;
        }
    }).setConf(cfg);
    sLog.debug("  -- configuration set to _BaseRootDAO");

    sSessionFactory = cfg.buildSessionFactory();
    sLog.debug("  -- session factory created");

    (new _BaseRootDAO() {
        void setSF(SessionFactory fact) {
            _BaseRootDAO.sSessionFactory = fact;
        }

        protected Class getReferenceClass() {
            return null;
        }
    }).setSF(sSessionFactory);
    sLog.debug("  -- session factory set to _BaseRootDAO");

    addBitwiseOperationsToDialect();
    sLog.debug("  -- bitwise operation added to the dialect if needed");

    DatabaseUpdate.update();
}

From source file:org.unitime.commons.hibernate.util.HibernateUtil.java

public static void configureHibernateFromRootDAO(String cfgName, Configuration cfg) {
    try {/*w  w w. j a v a  2  s. co  m*/
        EntityResolver entityResolver = new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                    return new InputSource(HibernateUtil.class.getClassLoader()
                            .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
                } else if (publicId.equals("-//Hibernate/Hibernate Mapping DTD//EN")) {
                    return new InputSource(HibernateUtil.class.getClassLoader()
                            .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
                } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                    return new InputSource(HibernateUtil.class.getClassLoader()
                            .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
                } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD//EN")) {
                    return new InputSource(HibernateUtil.class.getClassLoader()
                            .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
                }
                return null;
            }
        };

        cfg.setEntityResolver(entityResolver);
        sLog.debug("  -- added entity resolver");

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        sLog.debug("  -- document factory created");
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(entityResolver);
        sLog.debug("  -- document builder created");
        Document document = builder
                .parse(ConfigHelper.getConfigStream(cfgName == null ? "hibernate.cfg.xml" : cfgName));

        String dialect = ApplicationProperty.DatabaseDialect.value();
        if (dialect != null)
            setProperty(document, "dialect", dialect);

        String default_schema = ApplicationProperty.DatabaseSchema.value();
        if (default_schema != null)
            setProperty(document, "default_schema", default_schema);

        String idgen = ApplicationProperty.DatabaseUniqueIdGenerator.value();
        if (idgen != null)
            setProperty(document, "tmtbl.uniqueid.generator", idgen);

        if (ApplicationProperty.HibernateClusterEnabled.isFalse())
            setProperty(document, "net.sf.ehcache.configurationResourceName", "ehcache-nocluster.xml");

        for (Enumeration e = ApplicationProperties.getProperties().propertyNames(); e.hasMoreElements();) {
            String name = (String) e.nextElement();
            if (name.startsWith("hibernate.") || name.startsWith("connection.")
                    || name.startsWith("tmtbl.hibernate.")) {
                String value = ApplicationProperties.getProperty(name);
                if ("NULL".equals(value))
                    removeProperty(document, name);
                else
                    setProperty(document, name, value);
                if (!name.equals("connection.password"))
                    sLog.debug("  -- set " + name + ": " + value);
                else
                    sLog.debug("  -- set " + name + ": *****");
            }
        }

        cfg.configure(document);
        sLog.debug("  -- hibernate configured");

        HibernateUtil.fixSchemaInFormulas(cfg);
        sLog.debug("  -- %SCHEMA% in formulas changed to " + cfg.getProperty("default_schema"));

        UniqueIdGenerator.configure(cfg);
        sLog.debug("  -- UniquId generator configured");
    } catch (Exception e) {
        sLog.error("Unable to configure hibernate, reason: " + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.dataservices.core.XSLTTransformer.java

/**
 * This method provides a secured document builder which will secure XXE attacks.
 *
 * @param setIgnoreComments whether to set setIgnoringComments in DocumentBuilderFactory.
 * @return DocumentBuilder//from ww  w.j  av a 2  s . c o m
 * @throws javax.xml.parsers.ParserConfigurationException
 */
private static DocumentBuilder getSecuredDocumentBuilder(boolean setIgnoreComments)
        throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setIgnoringComments(setIgnoreComments);
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setExpandEntityReferences(false);
    documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    documentBuilder.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            throw new SAXException("Possible XML External Entity (XXE) attack. Skip resolving entity");
        }
    });
    return documentBuilder;
}

From source file:org.wso2.carbon.task.ui.internal.TaskManagementHelper.java

/**
 * This method provides a secured document builder which will secure XXE attacks.
 *
 * @param setIgnoreComments whether to set setIgnoringComments in DocumentBuilderFactory.
 * @return DocumentBuilder/*from   w ww . j  a  v  a 2 s  .c o  m*/
 * @throws javax.xml.parsers.ParserConfigurationException
 */
public static DocumentBuilder getSecuredDocumentBuilder(boolean setIgnoreComments)
        throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setIgnoringComments(setIgnoreComments);
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setExpandEntityReferences(false);
    documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    documentBuilderFactory.setXIncludeAware(false);
    org.apache.xerces.util.SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(0);
    documentBuilderFactory.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY,
            securityManager);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    documentBuilder.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            throw new SAXException("Possible XML External Entity (XXE) attack. Skipping entity resolving");
        }
    });
    return documentBuilder;
}

From source file:org.xwiki.resource.internal.entity.DefaultEntityResourceActionLister.java

@Override
public void initialize() throws InitializationException {
    // Parse the Struts config file (struts-config.xml) to extract all available actions
    List<String> actionNames = new ArrayList<>();
    SAXBuilder builder = new SAXBuilder();

    // Make sure we don't require an Internet Connection to parse the Struts config file!
    builder.setEntityResolver(new EntityResolver() {
        @Override/*ww  w.ja  va2 s .  c om*/
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            return new InputSource(new StringReader(""));
        }
    });

    // Step 1: Get a stream on the Struts config file if it exists
    InputStream strutsConfigStream = this.environment.getResourceAsStream(getStrutsConfigResource());

    if (strutsConfigStream != null) {
        // Step 2: Parse the Strust config file, looking for action names
        Document document;
        try {
            document = builder.build(strutsConfigStream);
        } catch (JDOMException | IOException e) {
            throw new InitializationException(
                    String.format("Failed to parse Struts Config file [%s]", getStrutsConfigResource()), e);
        }
        Element mappingElement = document.getRootElement().getChild("action-mappings");
        for (Element element : mappingElement.getChildren("action")) {
            // We extract the action name from the path mapping. Note that we cannot use the "name" attribute since
            // it's not reliable (it's not unique) and for example the sanveandcontinue action uses "save" as its
            // "name" element value.
            actionNames.add(StringUtils.strip(element.getAttributeValue("path"), "/"));
        }
    }

    this.strutsActionNames = actionNames;
}

From source file:petascope.util.XMLUtil.java

private static Builder newBuilder(boolean ignoreDTD) {
    XMLReader xmlReader = null;/*from   w w w .  j a va 2 s. co  m*/
    try {
        xmlReader = factory.newSAXParser().getXMLReader();
        if (ignoreDTD) {
            xmlReader.setEntityResolver(new EntityResolver() {

                public InputSource resolveEntity(String publicId, String systemId)
                        throws SAXException, IOException {
                    return new InputSource(new StringReader(""));
                }
            });
            xmlReader.setErrorHandler(new ErrorHandler() {

                @Override
                public void warning(SAXParseException saxpe) throws SAXException {
                    log.warn("XML parser warning: ", saxpe.getMessage());
                }

                @Override
                public void error(SAXParseException saxpe) throws SAXException {
                    throw saxpe;
                }

                @Override
                public void fatalError(SAXParseException saxpe) throws SAXException {
                    throw saxpe;
                }
            });
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return new Builder(xmlReader);
}

From source file:routines.system.BigDataParserUtils.java

public static routines.system.Document parseTo_Document(String s, boolean ignoreDTD, String encoding)
        throws org.dom4j.DocumentException {
    if (isBlank(s)) {
        return null;
    }/*from   ww w. j av a  2s . com*/
    routines.system.Document theDoc = new routines.system.Document();
    org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();

    if (ignoreDTD) {
        reader.setEntityResolver(new EntityResolver() {

            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                return new org.xml.sax.InputSource(
                        new java.io.ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
            }
        });
    }

    org.dom4j.Document document = reader.read(new java.io.StringReader(s));
    if (encoding != null && !("".equals(encoding))) {
        document.setXMLEncoding(encoding);
    }
    theDoc.setDocument(document);
    return theDoc;
}