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:Main.java

private static DocumentBuilder getBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from www  .  j a  v  a2s  .c  o m
    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 builder = factory.newDocumentBuilder();
    // prevent DTD entities from being resolved.
    builder.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            return new InputSource(new StringReader(""));
        }
    });

    return builder;
}

From source file:Main.java

public static Document getXmlDocFromURI(InputStream is) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from   w  w  w  .j  a  v a2 s  . com
    dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    DocumentBuilder builder = dbf.newDocumentBuilder();
    builder.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            return new InputSource(new StringReader(""));
        }
    });
    return builder.parse(is);
}

From source file:com.taobao.datasource.LoginConfigParser.java

@SuppressWarnings("unchecked")
public static Map<String, SecureIdentityLoginModule> parse(File file) throws DocumentException {
    SAXReader reader = new SAXReader();
    // Prevent from resolving dtd files
    reader.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            return new InputSource(
                    new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
        }//from w w w.  ja va  2  s  .  c o m
    });
    Document document = reader.read(file);
    List<Node> nodes = applicationPolicyPath.selectNodes(document);

    Map<String, SecureIdentityLoginModule> result = new HashMap<String, SecureIdentityLoginModule>();
    for (Node node : nodes) {
        createSecureIdentityLoginModule(result, node);
    }
    return result;
}

From source file:XMLBody.java

/**
 * Load XML document and parse it into DOM.
 * /*  w w w  .j a v  a 2 s .  co  m*/
 * @param input
 * @throws ParsingException
 */
public void loadXML(InputStream input) throws Exception {
    try {
        // Create Document Builder Factory
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();

        docFactory.setValidating(false);
        // Create Document Builder
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        docBuilder.isValidating();

        // Disable loading of external Entityes
        docBuilder.setEntityResolver(new EntityResolver() {
            // Dummi resolver - alvays do nothing
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                return new InputSource(new StringReader(""));
            }

        });

        // open and parse XML-file
        xmlDocument = docBuilder.parse(input);

        // Get Root xmlElement
        rootElement = xmlDocument.getDocumentElement();
    } catch (Exception e) {
        throw new Exception("Error load XML ", e);
    }

}

From source file:de.innovationgate.wga.common.beans.hdbmodel.ModelDefinition.java

public static ModelDefinition read(InputStream in) throws Exception {

    // First read XML manually and validate against the DTD provided in this OpenWGA distribution (to prevent it being loaded from the internet, which might not work, see #00003612) 
    SAXReader reader = new SAXReader();
    reader.setIncludeExternalDTDDeclarations(true);
    reader.setIncludeInternalDTDDeclarations(true);
    reader.setEntityResolver(new EntityResolver() {

        @Override/*from  w  w  w  .  j a  v  a2s  .c  om*/
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

            if (systemId.equals("http://doc.openwga.com/hdb-model-definition-6.0.dtd")) {
                return new InputSource(ModelDefinition.class.getClassLoader().getResourceAsStream(
                        WGUtils.getPackagePath(ModelDefinition.class) + "/hdb-model-definition-6.0.dtd"));
            } else {
                // use the default behaviour
                return null;
            }

        }

    });

    org.dom4j.Document domDoc = reader.read(in);

    // Remove doctype (we already have validated) and provide the resulting XML to the serializer
    domDoc.setDocType(null);
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out);
    writer.write(domDoc);
    String xml = out.toString();

    return _serializer.read(ModelDefinition.class, new StringReader(xml));
}

From source file:org.wildfly.extension.camel.SpringCamelContextFactory.java

private static CamelContext createSpringCamelContext(Resource resource, ClassLoader classLoader)
        throws Exception {
    GenericApplicationContext appContext = new GenericApplicationContext();
    appContext.setClassLoader(classLoader);
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(appContext) {
        @Override/*from   w w  w .  jav a2s  .  com*/
        protected NamespaceHandlerResolver createDefaultNamespaceHandlerResolver() {
            NamespaceHandlerResolver defaultResolver = super.createDefaultNamespaceHandlerResolver();
            return new CamelNamespaceHandlerResolver(defaultResolver);
        }
    };
    xmlReader.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            InputStream inputStream = null;
            if (CAMEL_SPRING_SYSTEM_ID.equals(systemId)) {
                inputStream = SpringCamelContext.class.getResourceAsStream("/camel-spring.xsd");
            } else if (SPRING_BEANS_SYSTEM_ID.equals(systemId)) {
                inputStream = XmlBeanDefinitionReader.class.getResourceAsStream("spring-beans-3.1.xsd");
            }
            InputSource result = null;
            if (inputStream != null) {
                result = new InputSource();
                result.setSystemId(systemId);
                result.setByteStream(inputStream);
            }
            return result;
        }
    });
    xmlReader.loadBeanDefinitions(resource);
    appContext.refresh();
    return SpringCamelContext.springCamelContext(appContext);
}

From source file:com.graphhopper.jsprit.core.algorithm.io.AlgorithmConfigXmlReader.java

public void read(URL url) {
    log.debug("read algorithm: " + url);
    algorithmConfig.getXMLConfiguration().setURL(url);
    algorithmConfig.getXMLConfiguration().setAttributeSplittingDisabled(true);
    algorithmConfig.getXMLConfiguration().setDelimiterParsingDisabled(true);

    if (schemaValidation) {
        final InputStream resource = Resource.getAsInputStream("algorithm_schema.xsd");
        if (resource != null) {
            EntityResolver resolver = new EntityResolver() {

                @Override/*from  ww  w  . j a v a 2s  .c om*/
                public InputSource resolveEntity(String publicId, String systemId)
                        throws SAXException, IOException {
                    {
                        InputSource is = new InputSource(resource);
                        return is;
                    }
                }
            };
            algorithmConfig.getXMLConfiguration().setEntityResolver(resolver);
            algorithmConfig.getXMLConfiguration().setSchemaValidation(true);
        } else {
            log.warn(
                    "cannot find schema-xsd file (algorithm_xml_schema.xsd). try to read xml without xml-file-validation.");
        }
    }
    try {
        algorithmConfig.getXMLConfiguration().load();
    } catch (ConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.tbuchloh.kiskis.persistence.exporter.XMLTransformer.java

/**
 * @param stylesheet//from w w w. j av a 2  s  . c om
 *            is the stylesheet to use.
 * @param is
 *            is the input source.
 * @param os
 *            is the output sink.
 */
public void transform(final URL stylesheet, final InputStream is, final OutputStream os)
        throws TransformException {
    try {
        LOG.debug("transforming with stylesheet=" + stylesheet);

        final XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setEntityResolver(new EntityResolver() {
            @Override
            public InputSource resolveEntity(final String publicId, final String systemId)
                    throws SAXException, IOException {
                if (systemId == null) {
                    throw new IllegalArgumentException("systemId must not be null!");
                }
                final int pos = systemId.lastIndexOf(File.separator);
                String resource = systemId;
                if (pos >= 0) {
                    resource = resource.substring(pos + 1);
                }
                final URL dtd = ClassLoader.getSystemResource(resource);

                LOG.debug("Resolving " + "systemId=" + systemId + ", resource=" + resource + ", dtd=" + dtd);

                return new InputSource(dtd.openStream());
            }
        });
        try {
            final Builder builder = new Builder(reader, false);
            final Document s = builder.build(stylesheet.openStream());

            final Document source = builder.build(is);

            final XSLTransform transform = new XSLTransform(s);
            final Document target = XSLTransform.toDocument(transform.transform(source));

            final Serializer ser = new Serializer(os);
            ser.setIndent(2);
            ser.write(target);
        } catch (final Exception e) {
            LOG.error(e, e);
            throw new XMLException(e.getMessage());
        }
    } catch (final Exception e) {
        throw new TransformException(e.getMessage(), e);
    }
}

From source file:io.wcm.devops.conga.plugins.aem.validator.AnyValidator.java

@Override
public Void apply(FileContext file, ValidatorContext context) throws ValidationException {
    Parser parser = new Parser(new BaseHandler());

    // set resource expander and entity resolver that do not resolve anything
    // just make sure they are in place to allow any parser parsing files with include directives
    parser.setResourceExpander(new ResourceExpander() {
        @Override//from  w  w  w.  j  av  a2s .  co  m
        public String[] expand(String arg0) {
            return new String[0];
        }
    });
    parser.setEnitiyResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            return null;
        }
    });

    // read any file
    try {
        String anyFileContent = FileUtils.readFileToString(file.getFile(), file.getCharset());
        anyFileContent = replaceTicks(anyFileContent);
        try (Reader reader = new StringReader(anyFileContent)) {
            parser.parse(new InputSource(reader));
        }
    }
    /*CHECKSTYLE:OFF*/ catch (Exception ex) { /*CHECKSTYLE:ON*/
        throw new ValidationException("ANY file is not valid: " + ex.getMessage(), ex);
    }
    return null;
}

From source file:cucumber.templates.xml.DataAccessContextLocalTestHelper.java

/**
 * Creates and configures a new Digester instance.
 * @return such instance./*from w  w  w.  ja  v a2s . co  m*/
 */
@NotNull
public Digester buildDataAccessContextLocalDigester() {
    @NotNull
    final Digester result = new Digester();

    // To avoid fetching external DTDs
    result.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(final String publicId, final String systemId)
                throws SAXException, IOException {
            return new InputSource(new ByteArrayInputStream("".getBytes()));
        }
    });
    // <beans>

    //   <bean>
    result.addFactoryCreate("beans/bean", new BeanElementFactory());

    //     <property>
    result.addFactoryCreate("beans/bean/property", new PropertyElementFactory());

    //     <value>
    result.addRule("beans/bean/property/value", new UntrimmedCallMethodRule("setValue", 0));
    //     </value>

    //     <ref>
    result.addFactoryCreate("beans/bean/property/ref", new RefElementFactory());
    //     </ref>

    result.addSetNext("beans/bean/property", "add");

    //   </property>

    result.addSetNext("beans/bean", "add");
    // </beans>

    return result;
}