Example usage for org.dom4j.io SAXReader setEntityResolver

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

Introduction

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

Prototype

public void setEntityResolver(EntityResolver entityResolver) 

Source Link

Document

Sets the entity resolver used to resolve entities.

Usage

From source file:org.talend.metadata.managment.ui.wizard.metadata.xml.utils.CopyDeleteFileUtilForWizard.java

License:Open Source License

public static List<String> getComplexNodes(String xsdFile) {
    List<String> attri = new ArrayList<String>();
    File file = new File(xsdFile);
    if (!file.exists()) {
        return attri;
    }/*from  ww w.j av  a  2  s  .  c  o m*/

    SAXReader saxReader = new SAXReader();
    Document doc;
    try {
        URL url = file.toURI().toURL();
        saxReader.setFeature("http://xml.org/sax/features/validation", false);

        saxReader.setEntityResolver(new EntityResolver() {

            String emptyDtd = "";

            ByteArrayInputStream bytes = new ByteArrayInputStream(emptyDtd.getBytes());

            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                File file = new File(systemId);
                if (file.exists()) {
                    return new InputSource(new FileInputStream(file));
                }
                // if no file, just set empty content for dtd
                return new InputSource(bytes);
            }
        });

        doc = saxReader.read(url.getFile());
        Element root = doc.getRootElement();
        List<Element> complexList = root.elements("complexType");
        if (complexList == null) {
            return attri;
        }
        for (Element n : complexList) {
            Attribute attr = n.attribute("name");
            if (attr != null) {
                attri.add(attr.getValue());
            }
        }
    } catch (DocumentException e) {
        ExceptionHandler.process(e);
    } catch (MalformedURLException e) {
        ExceptionHandler.process(e);
    } catch (SAXException e) {
        ExceptionHandler.process(e);
    }
    return attri;
}

From source file:org.unitime.banner.ant.MergeXml.java

License:Apache License

public void execute() throws BuildException {
    try {//www .ja va  2  s.c o m
        log("Merging " + iTarget + " with " + iSource);
        SAXReader sax = new SAXReader();
        sax.setEntityResolver(new EntityResolver() {
            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                    return new InputSource(getClass().getClassLoader()
                            .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
                } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                    return new InputSource(getClass().getClassLoader()
                            .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
                }
                return null;
            }
        });
        sax.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        Document targetDoc = sax.read(new File(iTarget));
        Document sourceDoc = sax.read(new File(iSource));

        merge(targetDoc.getRootElement(), sourceDoc.getRootElement());

        if (new File(iTarget).getName().equals("hibernate.cfg.xml")) {
            targetDoc.setDocType(sourceDoc.getDocType()); // Remove DOCTYPE
            Element sessionFactoryElement = targetDoc.getRootElement().element("session-factory");
            Vector<Element> mappings = new Vector<Element>();
            for (Iterator i = sessionFactoryElement.elementIterator("mapping"); i.hasNext();) {
                Element mappingElement = (Element) i.next();
                mappings.add(mappingElement);
                sessionFactoryElement.remove(mappingElement);
            }
            for (Iterator i = mappings.iterator(); i.hasNext();) {
                Element mappingElement = (Element) i.next();
                sessionFactoryElement.add(mappingElement);
            }
        }

        FileOutputStream fos = new FileOutputStream(iTarget);
        (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(targetDoc);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new BuildException(e);
    }
}

From source file:org.unitime.timetable.gwt.server.MenuServlet.java

License:Open Source License

public MenuServlet() {
    try {//ww  w  .  j  a v  a2 s .c om
        String menu = ApplicationProperties.getProperty("unitime.menu", "menu.xml");
        Document document = null;
        URL menuUrl = ApplicationProperties.class.getClassLoader().getResource(menu);
        SAXReader sax = new SAXReader();
        sax.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                if (publicId.equals("-//UniTime//UniTime Menu DTD/EN")) {
                    return new InputSource(
                            ApplicationProperties.class.getClassLoader().getResourceAsStream("menu.dtd"));
                }
                return null;
            }
        });
        if (menuUrl != null) {
            Debug.info("Reading menu from " + URLDecoder.decode(menuUrl.getPath(), "UTF-8") + " ...");
            document = sax.read(menuUrl.openStream());
        } else if (new File(menu).exists()) {
            Debug.info("Reading menu from " + menu + " ...");
            document = sax.read(new File(menu));
        }
        if (document == null)
            throw new ServletException("Unable to create menu, reason: resource " + menu + " not found.");

        if (!"unitime-menu".equals(document.getRootElement().getName()))
            throw new ServletException("Menu has an unknown format.");
        iRoot = document.getRootElement();

        String customMenu = ApplicationProperties.getProperty("unitime.menu.custom", "menu-custom.xml");
        Document customDocument = null;
        URL customMenuUrl = ApplicationProperties.class.getClassLoader().getResource(customMenu);
        if (customMenuUrl != null) {
            Debug.info(
                    "Reading custom menu from " + URLDecoder.decode(customMenuUrl.getPath(), "UTF-8") + " ...");
            customDocument = sax.read(customMenuUrl.openStream());
        } else if (new File(customMenu).exists()) {
            Debug.info("Reading custom menu from " + customMenu + " ...");
            customDocument = sax.read(new File(customMenu));
        }
        if (customDocument != null) {
            merge(iRoot, customDocument.getRootElement());
        }

    } catch (Exception e) {
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        throw new RuntimeException("Unable to initialize, reason: " + e.getMessage(), e);
    }
}

From source file:org.unitime.timetable.server.menu.MenuBackend.java

License:Open Source License

@Override
public void afterPropertiesSet() throws Exception {
    try {//  ww w  .  ja v a2  s.  co  m
        String menu = ApplicationProperty.MenuFile.value();
        Document document = null;
        URL menuUrl = ApplicationProperties.class.getClassLoader().getResource(menu);
        SAXReader sax = new SAXReader();
        sax.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                if (publicId.equals("-//UniTime//UniTime Menu DTD/EN")) {
                    return new InputSource(
                            ApplicationProperties.class.getClassLoader().getResourceAsStream("menu.dtd"));
                }
                return null;
            }
        });
        if (menuUrl != null) {
            sLog.info("Reading menu from " + URLDecoder.decode(menuUrl.getPath(), "UTF-8") + " ...");
            document = sax.read(menuUrl.openStream());
        } else if (new File(menu).exists()) {
            sLog.info("Reading menu from " + menu + " ...");
            document = sax.read(new File(menu));
        }
        if (document == null)
            throw new ServletException("Unable to create menu, reason: resource " + menu + " not found.");

        if (!"unitime-menu".equals(document.getRootElement().getName()))
            throw new ServletException("Menu has an unknown format.");
        iRoot = document.getRootElement();

        String customMenu = ApplicationProperty.CustomMenuFile.value();
        Document customDocument = null;
        URL customMenuUrl = ApplicationProperties.class.getClassLoader().getResource(customMenu);
        if (customMenuUrl != null) {
            sLog.info(
                    "Reading custom menu from " + URLDecoder.decode(customMenuUrl.getPath(), "UTF-8") + " ...");
            customDocument = sax.read(customMenuUrl.openStream());
        } else if (new File(customMenu).exists()) {
            sLog.info("Reading custom menu from " + customMenu + " ...");
            customDocument = sax.read(new File(customMenu));
        }
        if (customDocument != null) {
            merge(iRoot, customDocument.getRootElement());
        }

    } catch (Exception e) {
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        throw new RuntimeException("Unable to initialize, reason: " + e.getMessage(), e);
    }
}

From source file:pt.webdetails.cdf.dd.util.Utils.java

License:Open Source License

/**
 * Create a <code>Document</code> from the contents of a file.
 *
 * @param file/*from  w w w.  ja  v a2s.c om*/
 * @param resolver EntityResolver an instance of an EntityResolver that will resolve any external URIs. See the docs
 *                 on EntityResolver. null is an acceptable value.
 * @return <code>Document</code> initialized with the xml in <code>strXml</code>.
 * @throws DocumentException if the document isn't valid
 * @throws IOException       if the file doesn't exist
 */
public static Document getDocFromFile(final IBasicFile file, final EntityResolver resolver)
        throws DocumentException, IOException {
    SAXReader reader = new SAXReader();
    if (resolver != null) { //TODO: this is always being called with null
        reader.setEntityResolver(resolver);
    }
    return reader.read(file.getContents());
}

From source file:pt.webdetails.cpf.utils.XmlParserFactoryProducer.java

License:Open Source License

/**
 * Creates an instance of {@link SAXReader} class
 * with features that prevent from some XXE attacks (e.g. XML bomb)
 * See PPP-3506 for more details./*w  w w .j a v  a2s .  co  m*/
 * See also https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet
 *
 * @param resolver Is {@link EntityResolver} or null
 * @return {@link SAXReader}
 */
public static SAXReader getSAXReader(final EntityResolver resolver) {
    SAXReader reader = new SAXReader();
    if (resolver != null) {
        reader.setEntityResolver(resolver);
    }
    try {
        reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        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) {
        logger.error("Some parser properties are not supported.");
    }
    reader.setIncludeExternalDTDDeclarations(false);
    reader.setIncludeInternalDTDDeclarations(false);
    return reader;
}

From source file:routines.system.BigDataParserUtils.java

License:Open Source License

public static routines.system.Document parseTo_Document(String s, boolean ignoreDTD, String encoding)
        throws org.dom4j.DocumentException {
    if (isBlank(s)) {
        return null;
    }/*  w w  w  . j  a va 2  s .  c om*/
    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;
}

From source file:utils.SafeSAX.java

License:Open Source License

/**
 * Creates a new SAXReader and tries to load the given file into an XML
 * document. In case the dtd could not be loaded, the process is restarted
 * using a generic resolver/*from w  w w .  j  a v  a  2s  . c o  m*/
 * 
 * @param loadFile
 *            the file to be loaded from
 * @param reportError if false, errors will be swallowed
 * @return the XML document
 */
public static Document read(File loadFile, boolean reportError) {

    Document doc = null;
    boolean error = false;

    try {
        SAXReader xmlReader = new SAXReader(false);
        doc = xmlReader.read(loadFile);
    } catch (OutOfMemoryError mem) {
        System.err.println("Could not import! (Out of memory)");
    } catch (DocumentException e) {
        // System.err.println("Document type description could not be loaded (probably wrong path) - don't worry, using a generic dtd...");
        error = true;
    }

    if (error) {
        try {
            SAXReader xmlReader = new SAXReader(false);
            xmlReader.setEntityResolver(resolver);
            doc = xmlReader.read(loadFile);
        } catch (OutOfMemoryError mem) {
            System.err.println("Could not import! (Out of memory)");
        } catch (DocumentException e) {
            if (reportError) {
                String msg = e.getMessage();
                System.err.println("Error while import: DocumentException\n" + msg);
            }
            error = true;
        }
    }

    return doc;
}