Example usage for org.dom4j.io SAXReader setFeature

List of usage examples for org.dom4j.io SAXReader setFeature

Introduction

In this page you can find the example usage for org.dom4j.io SAXReader setFeature.

Prototype

public void setFeature(String name, boolean value) throws SAXException 

Source Link

Document

Sets a SAX feature on the underlying SAX parser.

Usage

From source file:org.b5chat.crossfire.core.plugin.PluginServlet.java

License:Open Source License

/**
 * Registers all JSP page servlets for a plugin.
 *
 * @param manager the plugin manager.//from w  w  w  .  j  a v a 2 s.c o m
 * @param plugin the plugin.
 * @param webXML the web.xml file containing JSP page names to servlet class file
 *      mappings.
 */
public static void registerServlets(PluginManager manager, IPlugin plugin, File webXML) {
    pluginManager = manager;
    if (!webXML.exists()) {
        Log.error("Could not register plugin servlets, file " + webXML.getAbsolutePath() + " does not exist.");
        return;
    }
    // Find the name of the plugin directory given that the webXML file
    // lives in plugins/[pluginName]/web/web.xml
    String pluginName = webXML.getParentFile().getParentFile().getParentFile().getName();
    try {
        // Make the reader non-validating so that it doesn't try to resolve external
        // DTD's. Trying to resolve external DTD's can break on some firewall configurations.
        SAXReader saxReader = new SAXReader(false);
        try {
            saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        } catch (SAXException e) {
            Log.warn("Error setting SAXReader feature", e);
        }
        Document doc = saxReader.read(webXML);
        // Find all <servlet> entries to discover name to class mapping.
        @SuppressWarnings("unchecked")
        List<Element> classes = doc.selectNodes("//servlet");
        Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
        for (int i = 0; i < classes.size(); i++) {
            Element servletElement = classes.get(i);
            String name = servletElement.element("servlet-name").getTextTrim();
            String className = servletElement.element("servlet-class").getTextTrim();
            classMap.put(name, manager.loadClass(plugin, className));
        }
        // Find all <servelt-mapping> entries to discover name to URL mapping.
        @SuppressWarnings("unchecked")
        List<Element> names = doc.selectNodes("//servlet-mapping");
        for (int i = 0; i < names.size(); i++) {
            Element nameElement = names.get(i);
            String name = nameElement.element("servlet-name").getTextTrim();
            String url = nameElement.element("url-pattern").getTextTrim();
            // Register the servlet for the URL.
            Class<?> servletClass = classMap.get(name);
            if (servletClass == null) {
                Log.error("Unable to load servlet, " + name + ", servlet-class not found.");
                continue;
            }
            Object instance = servletClass.newInstance();
            if (instance instanceof GenericServlet) {
                // Initialize the servlet then add it to the map..
                ((GenericServlet) instance).init(servletConfig);
                servlets.put(pluginName + url, (GenericServlet) instance);
            } else {
                Log.warn("Could not load " + (pluginName + url) + ": not a servlet.");
            }
        }
    } catch (Throwable e) {
        Log.error(e.getMessage(), e);
    }
}

From source file:org.b5chat.crossfire.core.plugin.PluginServlet.java

License:Open Source License

/**
 * Unregisters all JSP page servlets for a plugin.
 *
 * @param webXML the web.xml file containing JSP page names to servlet class file
 *               mappings.//ww w. j  av  a 2s.  com
 */
public static void unregisterServlets(File webXML) {
    if (!webXML.exists()) {
        Log.error(
                "Could not unregister plugin servlets, file " + webXML.getAbsolutePath() + " does not exist.");
        return;
    }
    // Find the name of the plugin directory given that the webXML file
    // lives in plugins/[pluginName]/web/web.xml
    String pluginName = webXML.getParentFile().getParentFile().getParentFile().getName();
    try {
        SAXReader saxReader = new SAXReader(false);
        saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        Document doc = saxReader.read(webXML);
        // Find all <servelt-mapping> entries to discover name to URL mapping.
        @SuppressWarnings("unchecked")
        List<Element> names = doc.selectNodes("//servlet-mapping");
        for (int i = 0; i < names.size(); i++) {
            Element nameElement = names.get(i);
            String url = nameElement.element("url-pattern").getTextTrim();
            // Destroy the servlet than remove from servlets map.
            GenericServlet servlet = servlets.get(pluginName + url);
            if (servlet != null) {
                servlet.destroy();
            }
            servlets.remove(pluginName + url);
            servlet = null;
        }
    } catch (Throwable e) {
        Log.error(e.getMessage(), e);
    }
}

From source file:org.codehaus.cargo.util.Dom4JUtil.java

License:Apache License

/**
 * Turn off anything that would make this class touch the outside world.
 * //  w w  w  .  j a  v  a 2s  . c o  m
 * @param reader what to disable external fetches from.
 */
private void setDontAccessExternalResources(SAXReader reader) {
    try {
        reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
        reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (SAXException e) {
        throw new CargoException("Error disabling external xml resources", e);
    }
}

From source file:org.craftercms.core.store.impl.AbstractFileBasedContentStoreAdapter.java

License:Open Source License

/**
 * Creates and configures an XML SAX reader.
 *//*from  ww  w  .j ava2  s. c o m*/
protected SAXReader createXmlReader() {
    SAXReader xmlReader = new SAXReader();
    xmlReader.setMergeAdjacentText(true);
    xmlReader.setStripWhitespaceText(true);
    xmlReader.setIgnoreComments(true);

    try {
        xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
        xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    } catch (SAXException ex) {
        LOGGER.error("Unable to turn off external entity loading, This could be a security risk.", ex);
    }

    return xmlReader;
}

From source file:org.craftercms.search.service.impl.SolrDocumentBuilderImpl.java

License:Open Source License

protected SAXReader createSAXReader() {
    SAXReader reader = new SAXReader();
    reader.setEncoding(CharEncoding.UTF_8);
    reader.setMergeAdjacentText(true);/* ww w .j  a v  a2s . c o  m*/
    try {
        reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
        reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    } catch (SAXException ex) {
        logger.error("Unable to turn off external entity loading, This could be a security risk.", ex);
    }
    return reader;
}

From source file:org.dentaku.gentaku.tools.cgen.plugin.GenGenPlugin.java

License:Apache License

private Document validate(Document xsdDoc, Reader fileReader)
        throws IOException, SAXException, DocumentException {
    File temp = File.createTempFile("schema", ".xsd");
    temp.deleteOnExit();/*ww  w .  j a  v a2s.c om*/
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write(xsdDoc.asXML());
    out.flush();
    out.close();

    SAXReader saxReader = new SAXReader(true);
    saxReader.setFeature("http://apache.org/xml/features/validation/schema", true);
    URL schemaPath = temp.toURL();
    saxReader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
            schemaPath.toString());
    return saxReader.read(fileReader);
}

From source file:org.directwebremoting.convert.DOM4JConverter.java

License:Apache License

public Object convertInbound(Class<?> paramType, InboundVariable data) throws ConversionException {
    if (data.isNull()) {
        return null;
    }/*  w  ww  .j ava 2 s  . c o  m*/

    String value = data.urlDecode();

    try {
        SAXReader xmlReader = new SAXReader();

        // Protect us from hackers, see:
        // https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Processing
        xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
        xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        try {
            xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        } catch (Exception ex) {
            // XML parser doesn't have this setting, never mind
        }

        // Extra protection from external entity hacking
        xmlReader.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                return new InputSource(); // no lookup, just return empty
            }
        });

        Document doc = xmlReader.read(new StringReader(value));

        if (paramType == Document.class) {
            return doc;
        } else if (paramType == Element.class) {
            return doc.getRootElement();
        }

        throw new ConversionException(paramType);
    } catch (ConversionException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ConversionException(paramType, ex);
    }
}

From source file:org.guzz.builder.GuzzConfigFileBuilder.java

License:Apache License

protected Document loadFullConfigFile(Resource resource, String encoding)
        throws DocumentException, IOException, SAXException {
    SAXReader reader = null;
    Document document = null;/*from  w ww .  j a  v  a  2 s.  com*/

    reader = new SAXReader();
    reader.setValidation(false);
    // http://apache.org/xml/features/nonvalidating/load-external-dtd"  
    reader.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);

    InputStreamReader isr = new InputStreamReader(resource.getInputStream(), encoding);

    document = reader.read(isr);
    final Element root = document.getRootElement();

    List list = document.selectNodes("//import");

    for (int i = 0; i < list.size(); i++) {
        Element n = (Element) list.get(i);

        String file = n.attribute("resource").getValue();

        //load included xml file.
        FileResource fr = new FileResource(resource, file);
        Document includedDoc = null;

        try {
            includedDoc = loadFullConfigFile(fr, encoding);
        } finally {
            CloseUtil.close(fr);
        }

        List content = root.content();
        int indexOfPos = content.indexOf(n);

        content.remove(indexOfPos);

        //appends included docs
        Element ie = includedDoc.getRootElement();
        List ie_children = ie.content();

        for (int k = ie_children.size() - 1; k >= 0; k--) {
            content.add(indexOfPos, ie_children.get(k));
        }
    }

    return document;
}

From source file:org.guzz.builder.HbmXMLBuilder.java

License:Apache License

public static POJOBasedObjectMapping parseHbmStream(final GuzzContextImpl gf, String dbGroupName,
        BusinessValidChecker checker, String businessName, Class overridedDomainClass, Class interpreterClass,
        InputStream is) throws DocumentException, IOException, SAXException, ClassNotFoundException {

    SAXReader reader = null;
    Document document = null;/*from  w w  w .j  a v  a2  s  . co m*/

    reader = new SAXReader();
    reader.setValidation(false);
    // http://apache.org/xml/features/nonvalidating/load-external-dtd"  
    reader.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);

    document = reader.read(is);
    final Element root = document.getRootElement();

    if (StringUtil.isEmpty(dbGroupName)) {
        dbGroupName = getDomainClassDbGroup(root);
    }
    if (StringUtil.isEmpty(dbGroupName)) {
        dbGroupName = "default";
    }

    final DBGroup dbGroup = gf.getDBGroup(dbGroupName);

    final SimpleTable st = new SimpleTable(dbGroup.getDialect());
    final POJOBasedObjectMapping map = new POJOBasedObjectMapping(gf, dbGroup, st);

    if (overridedDomainClass == null) {//hbm?className
        String m_class = HbmXMLBuilder.getDomainClassName(root);

        overridedDomainClass = ClassUtil.getClass(m_class);
    }

    if (checker != null && !checker.shouldParse(overridedDomainClass)) {
        return null;
    }

    if (StringUtil.isEmpty(businessName)) {
        businessName = getDomainClassBusinessName(root);
    }

    final Business business = gf.instanceNewGhost(businessName, dbGroup.getGroupName(), interpreterClass,
            overridedDomainClass);
    if (business.getInterpret() == null) {
        throw new GuzzException("cann't create new instance of business: " + business.getName());
    }

    business.setTable(st);
    business.setMapping(map);

    //?business??
    if (business.getName() != null) {
        st.setBusinessName(business.getName());
    } else {
        st.setBusinessName(business.getDomainClass().getName());
    }

    //properties defined.
    final LinkedList props = new LinkedList();

    Visitor visitor = new VisitorSupport() {

        private String packageName;

        public void visit(Element e) {

            //package
            if ("hibernate-mapping".equalsIgnoreCase(e.getName())
                    || "guzz-mapping".equalsIgnoreCase(e.getName())) {
                this.packageName = e.attributeValue("package");

            } else if ("class".equalsIgnoreCase(e.getName())) {
                String className = e.attributeValue("name");
                String tableName = e.attributeValue("table");
                String shadow = e.attributeValue("shadow");
                boolean dynamicUpdate = StringUtil.toBoolean(e.attributeValue("dynamic-update"), false);

                if (StringUtil.notEmpty(this.packageName)) {
                    className = this.packageName + "." + className;
                }

                //business????hbml.xml?class namebusinessclass
                Class cls = business.getDomainClass();
                if (cls == null) { //?business?domainClassName
                    cls = ClassUtil.getClass(className);
                }

                Assert.assertNotNull(cls, "invalid class name");
                Assert.assertNotEmpty(tableName, "invalid table name");

                JavaBeanWrapper configBeanWrapper = BeanWrapper.createPOJOWrapper(cls);
                business.setDomainClass(cls);
                business.setConfiguredBeanWrapper(configBeanWrapper);

                map.setBusiness(business);

                //shadow?tableName?
                if (StringUtil.notEmpty(shadow)) {
                    ShadowTableView sv = (ShadowTableView) BeanCreator.newBeanInstance(shadow);
                    sv.setConfiguredTableName(tableName);

                    //CustomTableViewShadowTableView
                    if (sv instanceof CustomTableView) {
                        CustomTableView ctv = (CustomTableView) sv;
                        ctv.setConfiguredObjectMapping(map);

                        st.setCustomTableView(ctv);
                    }

                    st.setShadowTableView(sv);
                    gf.registerShadowTableView(sv);
                }

                //TODO: ???
                st.setTableName(tableName);
                st.setDynamicUpdate(dynamicUpdate);

            } else if ("id".equalsIgnoreCase(e.getName())) {
                String name = e.attributeValue("name");
                String type = e.attributeValue("type");
                String column = null;

                Element columnE = (Element) e.selectSingleNode("column");
                if (columnE != null) {
                    column = columnE.attributeValue("name");
                }

                if (StringUtil.isEmpty(column)) {
                    column = e.attributeValue("column");
                }

                if (StringUtil.isEmpty(column)) {
                    column = name;
                }

                props.addLast(name);

                TableColumn col = ObjectMappingUtil.createTableColumn(gf, map, name, column, type, null);

                st.addPKColumn(col);

            } else if ("version".equalsIgnoreCase(e.getName())) {
                //see: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html 5.1.9. Version (optional)
                //TODO: annotation?version?

                String name = e.attributeValue("name");
                String type = e.attributeValue("type");
                boolean insertIt = StringUtil.toBoolean(e.attributeValue("insert"), true);
                String column = null;

                Element columnE = (Element) e.selectSingleNode("column");
                if (columnE != null) {
                    column = columnE.attributeValue("name");
                }

                if (StringUtil.isEmpty(column)) {
                    column = e.attributeValue("column");
                }

                if (StringUtil.isEmpty(column)) {
                    column = name;
                }

                props.addLast(name);

                TableColumn col = ObjectMappingUtil.createTableColumn(gf, map, name, column, type, null);
                col.setAllowInsert(insertIt);

                st.addVersionColumn(col);

            } else if ("property".equalsIgnoreCase(e.getName())) {
                String name = e.attributeValue("name");
                String type = e.attributeValue("type");
                String nullValue = e.attributeValue("null");
                String lazy = e.attributeValue("lazy");
                String loader = e.attributeValue("loader");

                boolean insertIt = StringUtil.toBoolean(e.attributeValue("insert"), true);
                boolean updateIt = StringUtil.toBoolean(e.attributeValue("update"), true);

                String column = null;

                Element columnE = (Element) e.selectSingleNode("column");
                if (columnE != null) {
                    column = columnE.attributeValue("name");
                }

                if (StringUtil.isEmpty(column)) {
                    column = e.attributeValue("column");
                }

                if (StringUtil.isEmpty(column)) {
                    column = name;
                }

                props.addLast(name);

                TableColumn col = ObjectMappingUtil.createTableColumn(gf, map, name, column, type, loader);
                col.setNullValue(nullValue);
                col.setAllowInsert(insertIt);
                col.setAllowUpdate(updateIt);
                col.setLazy("true".equalsIgnoreCase(lazy));

                st.addColumn(col);
            }
        }
    };

    root.accept(visitor);

    //?generator
    //?generator?
    List generator = root.selectNodes("//class/id/generator");
    if (generator.size() != 1) {
        throw new GuzzException("id generator is not found for business: " + business);
    }

    Element ge = (Element) generator.get(0);

    String m_clsName = ge.attributeValue("class");

    if ("native".equalsIgnoreCase(m_clsName)) { //nativegeneratordialect?
        m_clsName = dbGroup.getDialect().getNativeIDGenerator();
    }

    String realClassName = (String) IdentifierGeneratorFactory.getGeneratorClass(m_clsName);
    if (realClassName == null) {
        realClassName = m_clsName;
    }

    IdentifierGenerator ig = (IdentifierGenerator) BeanCreator.newBeanInstance(realClassName);

    //?generator??      
    List m_params = ge.selectNodes("param");
    Properties p = new Properties();
    for (int i = 0; i < m_params.size(); i++) {
        Element mp = (Element) m_params.get(i);
        p.put(mp.attributeValue("name"), mp.getTextTrim());
    }

    if (ig instanceof Configurable) {
        ((Configurable) ig).configure(dbGroup.getDialect(), map, p);
    }

    //register callback for GuzzContext's full starting.
    if (ig instanceof GuzzContextAware) {
        gf.registerContextStartedAware((GuzzContextAware) ig);
    }

    st.setIdentifierGenerator(ig);

    return map;
}

From source file:org.guzz.service.core.impl.FileDynamicSQLServiceImpl.java

License:Apache License

protected CompiledSQL loadCSFromStream(String id, InputStream is) throws Exception {
    SAXReader reader = null;
    Document document = null;//from w  ww . j a v a 2 s .com

    reader = new SAXReader();
    reader.setValidation(false);

    //http://apache.org/xml/features/nonvalidating/load-external-dtd"  
    reader.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);

    InputStreamReader isr = new InputStreamReader(is, encoding);

    document = reader.read(isr);
    final Element root = document.getRootElement();

    CompiledSQL cs = loadCompiledSQL(id, root);

    return cs;
}