Search in sources :

Example 6 with EntityResolver

use of org.xml.sax.EntityResolver in project bazel by bazelbuild.

the class XMLPropertyListParser method getDocBuilder.

/**
     * Gets a DocumentBuilder to parse a XML property list.
     * As DocumentBuilders are not thread-safe a new DocBuilder is generated for each request.
     *
     * @return A new DocBuilder that can parse property lists w/o an internet connection.
     * @throws javax.xml.parsers.ParserConfigurationException If a document builder for parsing a XML property list
     *                                                        could not be created. This should not occur.
     */
private static synchronized DocumentBuilder getDocBuilder() throws ParserConfigurationException {
    if (docBuilderFactory == null)
        initDocBuilderFactory();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    docBuilder.setEntityResolver(new EntityResolver() {

        public InputSource resolveEntity(String publicId, String systemId) {
            if (// older publicId
            "-//Apple Computer//DTD PLIST 1.0//EN".equals(publicId) || "-//Apple//DTD PLIST 1.0//EN".equals(publicId)) {
                // it from the network.
                return new InputSource(new ByteArrayInputStream(new byte[0]));
            }
            return null;
        }
    });
    return docBuilder;
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) EntityResolver(org.xml.sax.EntityResolver)

Example 7 with EntityResolver

use of org.xml.sax.EntityResolver in project commons-gdx by gemserk.

the class DocumentParser method parse.

/**
	 * Returns an XML Document from an InputStream using a DocumentBuilder with the specified validation and namespaceaware flags.
	 * 
	 * @param schema
	 *            The Schema to be used to parse the Document, null if no Schema wanted.
	 * @param is
	 *            The InputStream to be processed.
	 * @param validating
	 *            If the document should be validated or not
	 * @param namespaceaware
	 *            If the document should be processed with name space awareness or not.
	 */
public Document parse(Schema schema, InputStream is, boolean validating, boolean namespaceaware) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        if (schema != null)
            factory.setSchema(schema);
        factory.setValidating(validating);
        factory.setNamespaceAware(namespaceaware);
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler(new DefaultErrorHandler());
        builder.setEntityResolver(new EntityResolver() {

            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                return new InputSource(new ByteArrayInputStream(new byte[0]));
            }
        });
        return builder.parse(is);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) EntityResolver(org.xml.sax.EntityResolver) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException)

Example 8 with EntityResolver

use of org.xml.sax.EntityResolver in project XobotOS by xamarin.

the class Properties method loadFromXML.

/**
     * Loads the properties from an {@code InputStream} containing the
     * properties in XML form. The XML document must begin with (and conform to)
     * following DOCTYPE:
     *
     * <pre>
     * &lt;!DOCTYPE properties SYSTEM &quot;http://java.sun.com/dtd/properties.dtd&quot;&gt;
     * </pre>
     *
     * Also the content of the XML data must satisfy the DTD but the xml is not
     * validated against it. The DTD is not loaded from the SYSTEM ID. After
     * this method returns the InputStream is not closed.
     *
     * @param in the InputStream containing the XML document.
     * @throws IOException in case an error occurs during a read operation.
     * @throws InvalidPropertiesFormatException if the XML data is not a valid
     *             properties file.
     */
public synchronized void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException {
    if (in == null) {
        throw new NullPointerException();
    }
    if (builder == null) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new Error(e);
        }
        builder.setErrorHandler(new ErrorHandler() {

            public void warning(SAXParseException e) throws SAXException {
                throw e;
            }

            public void error(SAXParseException e) throws SAXException {
                throw e;
            }

            public void fatalError(SAXParseException e) throws SAXException {
                throw e;
            }
        });
        builder.setEntityResolver(new EntityResolver() {

            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                if (systemId.equals(PROP_DTD_NAME)) {
                    InputSource result = new InputSource(new StringReader(PROP_DTD));
                    result.setSystemId(PROP_DTD_NAME);
                    return result;
                }
                throw new SAXException("Invalid DOCTYPE declaration: " + systemId);
            }
        });
    }
    try {
        Document doc = builder.parse(in);
        NodeList entries = doc.getElementsByTagName("entry");
        if (entries == null) {
            return;
        }
        int entriesListLength = entries.getLength();
        for (int i = 0; i < entriesListLength; i++) {
            Element entry = (Element) entries.item(i);
            String key = entry.getAttribute("key");
            String value = entry.getTextContent();
            /*
                 * key != null & value != null but key or(and) value can be
                 * empty String
                 */
            put(key, value);
        }
    } catch (IOException e) {
        throw e;
    } catch (SAXException e) {
        throw new InvalidPropertiesFormatException(e);
    }
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) EntityResolver(org.xml.sax.EntityResolver) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) SAXParseException(org.xml.sax.SAXParseException) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 9 with EntityResolver

use of org.xml.sax.EntityResolver in project XobotOS by xamarin.

the class ExpatParser method handleExternalEntity.

/**
     * Handles an external entity.
     *
     * @param context to be passed back to Expat when we parse the entity
     * @param publicId the publicId of the entity
     * @param systemId the systemId of the entity
     */
/*package*/
void handleExternalEntity(String context, String publicId, String systemId) throws SAXException, IOException {
    EntityResolver entityResolver = xmlReader.entityResolver;
    if (entityResolver == null) {
        return;
    }
    /*
         * The spec. is terribly under-specified here. It says that if the
         * systemId is a URL, we should try to resolve it, but it doesn't
         * specify how to tell whether or not the systemId is a URL let alone
         * how to resolve it.
         *
         * Other implementations do various insane things. We try to keep it
         * simple: if the systemId parses as a URI and it's relative, we try to
         * resolve it against the parent document's systemId. If anything goes
         * wrong, we go with the original systemId. If crazybob had designed
         * the API, he would have left all resolving to the EntityResolver.
         */
    if (this.systemId != null) {
        try {
            URI systemUri = new URI(systemId);
            if (!systemUri.isAbsolute() && !systemUri.isOpaque()) {
                // It could be relative (or it may not be a URI at all!)
                URI baseUri = new URI(this.systemId);
                systemUri = baseUri.resolve(systemUri);
                // Replace systemId w/ resolved URI
                systemId = systemUri.toString();
            }
        } catch (Exception e) {
            System.logI("Could not resolve '" + systemId + "' relative to" + " '" + this.systemId + "' at " + locator, e);
        }
    }
    InputSource inputSource = entityResolver.resolveEntity(publicId, systemId);
    if (inputSource == null) {
        /*
             * The spec. actually says that we should try to treat systemId
             * as a URL and download and parse its contents here, but an
             * entity resolver can easily accomplish the same by returning
             * new InputSource(systemId).
             *
             * Downloading external entities by default would result in several
             * unwanted DTD downloads, not to mention pose a security risk
             * when parsing untrusted XML -- see for example
             * http://archive.cert.uni-stuttgart.de/bugtraq/2002/10/msg00421.html --
             * so we just do nothing instead. This also enables the user to
             * opt out of entity parsing when using
             * {@link org.xml.sax.helpers.DefaultHandler}, something that
             * wouldn't be possible otherwise.
             */
        return;
    }
    String encoding = pickEncoding(inputSource);
    int pointer = createEntityParser(this.pointer, context);
    try {
        EntityParser entityParser = new EntityParser(encoding, xmlReader, pointer, inputSource.getPublicId(), inputSource.getSystemId());
        parseExternalEntity(entityParser, inputSource);
    } finally {
        releaseParser(pointer);
    }
}
Also used : InputSource(org.xml.sax.InputSource) EntityResolver(org.xml.sax.EntityResolver) URI(java.net.URI) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException)

Example 10 with EntityResolver

use of org.xml.sax.EntityResolver in project jangaroo-tools by CoreMedia.

the class ExmlValidator method setupSAXParser.

private SAXParser setupSAXParser() throws IOException {
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        ExmlSchemaResolver exmlSchemaResolver = new ExmlSchemaResolver();
        schemaFactory.setResourceResolver(exmlSchemaResolver);
        List<Source> schemas = new ArrayList<Source>();
        schemas.add(new StreamSource(getClass().getResourceAsStream(Exmlc.EXML_SCHEMA_LOCATION), "exml"));
        schemas.add(new StreamSource(getClass().getResourceAsStream(Exmlc.EXML_UNTYPED_SCHEMA_LOCATION), "untyped"));
        Collection<ExmlSchemaSource> exmlSchemaSources = exmlSchemaSourceByNamespace.values();
        for (ExmlSchemaSource exmlSchemaSource : exmlSchemaSources) {
            schemas.add(exmlSchemaSource.newStreamSource());
        }
        Schema exmlSchema = schemaFactory.newSchema(schemas.toArray(new Source[schemas.size()]));
        final SAXParserFactory saxFactory = SAXParserFactory.newInstance();
        saxFactory.setNamespaceAware(true);
        saxFactory.setSchema(exmlSchema);
        SAXParser saxParser = saxFactory.newSAXParser();
        saxParser.getXMLReader().setEntityResolver(new EntityResolver() {

            @Override
            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                //To change body of implemented methods use File | Settings | File Templates.
                return null;
            }
        });
        return saxParser;
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException("A default dom builder should be provided.", e);
    } catch (SAXParseException e) {
        // SAX parser error while parsing EXML schemas: log only, will cause error or warning, depending on configuration:
        logSAXParseException(null, e, true);
        return null;
    } catch (SAXException e) {
        throw new IllegalStateException("SAX parser does not support validation.", e);
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) InputSource(org.xml.sax.InputSource) StreamSource(javax.xml.transform.stream.StreamSource) Schema(javax.xml.validation.Schema) ArrayList(java.util.ArrayList) EntityResolver(org.xml.sax.EntityResolver) IOException(java.io.IOException) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) SAXException(org.xml.sax.SAXException) SAXParseException(org.xml.sax.SAXParseException) SAXParser(javax.xml.parsers.SAXParser) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

EntityResolver (org.xml.sax.EntityResolver)24 InputSource (org.xml.sax.InputSource)19 SAXException (org.xml.sax.SAXException)16 IOException (java.io.IOException)12 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)10 DocumentBuilder (javax.xml.parsers.DocumentBuilder)9 SAXParseException (org.xml.sax.SAXParseException)9 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)7 Document (org.w3c.dom.Document)6 ErrorHandler (org.xml.sax.ErrorHandler)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 StringReader (java.io.StringReader)4 SAXBuilder (org.jdom.input.SAXBuilder)4 NodeList (org.w3c.dom.NodeList)4 Document (org.jdom.Document)3 Element (org.w3c.dom.Element)3 MockResolver (tests.api.org.xml.sax.support.MockResolver)3 URI (java.net.URI)2 ArrayList (java.util.ArrayList)2 SAXParser (javax.xml.parsers.SAXParser)2