Example usage for javax.xml.parsers SAXParserFactory setValidating

List of usage examples for javax.xml.parsers SAXParserFactory setValidating

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory setValidating.

Prototype


public void setValidating(boolean validating) 

Source Link

Document

Specifies that the parser produced by this code will validate documents as they are parsed.

Usage

From source file:org.apache.fop.fotreetest.FOTreeTestCase.java

/**
 * Runs a test.// w  ww. j  av a  2 s .  c  o m
 * @throws Exception if a test or FOP itself fails
 */
@Test
public void runTest() throws Exception {
    try {
        ResultCollector collector = ResultCollector.getInstance();
        collector.reset();

        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        spf.setValidating(false);
        SAXParser parser = spf.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        // Resetting values modified by processing instructions
        fopFactory.setBreakIndentInheritanceOnReferenceAreaBoundary(
                FopFactoryConfigurator.DEFAULT_BREAK_INDENT_INHERITANCE);
        fopFactory.setSourceResolution(FopFactoryConfigurator.DEFAULT_SOURCE_RESOLUTION);

        FOUserAgent ua = fopFactory.newFOUserAgent();
        ua.setBaseURL(testFile.getParentFile().toURI().toURL().toString());
        ua.setFOEventHandlerOverride(new DummyFOEventHandler(ua));
        ua.getEventBroadcaster().addEventListener(new ConsoleEventListenerForTests(testFile.getName()));

        // Used to set values in the user agent through processing instructions
        reader = new PIListener(reader, ua);

        Fop fop = fopFactory.newFop(ua);

        reader.setContentHandler(fop.getDefaultHandler());
        reader.setDTDHandler(fop.getDefaultHandler());
        reader.setErrorHandler(fop.getDefaultHandler());
        reader.setEntityResolver(fop.getDefaultHandler());
        try {
            reader.parse(testFile.toURI().toURL().toExternalForm());
        } catch (Exception e) {
            collector.notifyError(e.getLocalizedMessage());
            throw e;
        }

        List<String> results = collector.getResults();
        if (results.size() > 0) {
            for (int i = 0; i < results.size(); i++) {
                System.out.println((String) results.get(i));
            }
            throw new IllegalStateException((String) results.get(0));
        }
    } catch (Exception e) {
        org.apache.commons.logging.LogFactory.getLog(this.getClass()).info("Error on " + testFile.getName());
        throw e;
    }
}

From source file:org.apache.geode.internal.cache.xmlcache.CacheXmlParser.java

/**
 * Parses XML data and from it creates an instance of <code>CacheXmlParser</code> that can be used
 * to {@link #create}the {@link Cache}, etc.
 *
 * @param is the <code>InputStream</code> of XML to be parsed
 *
 * @return a <code>CacheXmlParser</code>, typically used to create a cache from the parsed XML
 *
 * @throws CacheXmlException Something went wrong while parsing the XML
 *
 * @since GemFire 4.0/*from  w w w. j a  v a  2  s . c om*/
 *
 */
public static CacheXmlParser parse(InputStream is) {

    /**
     * The API doc http://java.sun.com/javase/6/docs/api/org/xml/sax/InputSource.html for the SAX
     * InputSource says: "... standard processing of both byte and character streams is to close
     * them on as part of end-of-parse cleanup, so applications should not attempt to re-use such
     * streams after they have been handed to a parser."
     *
     * In order to block the parser from closing the stream, we wrap the InputStream in a filter,
     * i.e., UnclosableInputStream, whose close() function does nothing.
     * 
     */
    class UnclosableInputStream extends BufferedInputStream {
        public UnclosableInputStream(InputStream stream) {
            super(stream);
        }

        @Override
        public void close() {
        }
    }

    CacheXmlParser handler = new CacheXmlParser();
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setFeature(DISALLOW_DOCTYPE_DECL_FEATURE, true);
        factory.setValidating(true);
        factory.setNamespaceAware(true);
        UnclosableInputStream bis = new UnclosableInputStream(is);
        try {
            SAXParser parser = factory.newSAXParser();
            // Parser always reads one buffer plus a little extra worth before
            // determining that the DTD is there. Setting mark twice the parser
            // buffer size.
            bis.mark((Integer) parser.getProperty(BUFFER_SIZE) * 2);
            parser.setProperty(JAXP_SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
            parser.parse(bis, new DefaultHandlerDelegate(handler));
        } catch (CacheXmlException e) {
            if (null != e.getCause() && e.getCause().getMessage().contains(DISALLOW_DOCTYPE_DECL_FEATURE)) {
                // Not schema based document, try dtd.
                bis.reset();
                factory.setFeature(DISALLOW_DOCTYPE_DECL_FEATURE, false);
                SAXParser parser = factory.newSAXParser();
                parser.parse(bis, new DefaultHandlerDelegate(handler));
            } else {
                throw e;
            }
        }
        return handler;
    } catch (Exception ex) {
        if (ex instanceof CacheXmlException) {
            while (true /* ex instanceof CacheXmlException */) {
                Throwable cause = ex.getCause();
                if (!(cause instanceof CacheXmlException)) {
                    break;
                } else {
                    ex = (CacheXmlException) cause;
                }
            }
            throw (CacheXmlException) ex;
        } else if (ex instanceof SAXException) {
            // Silly JDK 1.4.2 XML parser wraps RunTime exceptions in a
            // SAXException. Pshaw!
            SAXException sax = (SAXException) ex;
            Exception cause = sax.getException();
            if (cause instanceof CacheXmlException) {
                while (true /* cause instanceof CacheXmlException */) {
                    Throwable cause2 = cause.getCause();
                    if (!(cause2 instanceof CacheXmlException)) {
                        break;
                    } else {
                        cause = (CacheXmlException) cause2;
                    }
                }
                throw (CacheXmlException) cause;
            }
        }
        throw new CacheXmlException(LocalizedStrings.CacheXmlParser_WHILE_PARSING_XML.toLocalizedString(), ex);
    }
}

From source file:org.apache.myfaces.test.AbstractClassElementTestCase.java

protected void setUp() throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(false);//from  w ww. j a v a  2s .  c  o  m

    SAXParser parser = factory.newSAXParser();
    ClassElementHandler handler = new DelegateEntityResolver();

    Iterator iterator = resource.iterator();

    while (iterator.hasNext()) {

        String resourceName = (String) iterator.next();

        InputStream is = getClass().getClassLoader().getResourceAsStream(resourceName);

        if (is == null)
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName);

        if (is == null)
            throw new Exception("Could not locate resource :" + resourceName);

        parser.parse(is, handler);

    }

    className.addAll(handler.getClassName());

}

From source file:org.apache.ojb.broker.metadata.RepositoryPersistor.java

/**
 * Read metadata by populating an instance of the target class
 * using SAXParser.// w  ww . j  a va  2s  .c  om
 */
private Object readMetadataFromXML(InputSource source, Class target)
        throws MalformedURLException, ParserConfigurationException, SAXException, IOException {
    // TODO: make this configurable
    boolean validate = false;

    // get a xml reader instance:
    SAXParserFactory factory = SAXParserFactory.newInstance();
    log.info("RepositoryPersistor using SAXParserFactory : " + factory.getClass().getName());
    if (validate) {
        factory.setValidating(true);
    }
    SAXParser p = factory.newSAXParser();
    XMLReader reader = p.getXMLReader();
    if (validate) {
        reader.setErrorHandler(new OJBErrorHandler());
    }

    Object result;
    if (DescriptorRepository.class.equals(target)) {
        // create an empty repository:
        DescriptorRepository repository = new DescriptorRepository();
        // create handler for building the repository structure
        ContentHandler handler = new RepositoryXmlHandler(repository);
        // tell parser to use our handler:
        reader.setContentHandler(handler);
        reader.parse(source);
        result = repository;
    } else if (ConnectionRepository.class.equals(target)) {
        // create an empty repository:
        ConnectionRepository repository = new ConnectionRepository();
        // create handler for building the repository structure
        ContentHandler handler = new ConnectionDescriptorXmlHandler(repository);
        // tell parser to use our handler:
        reader.setContentHandler(handler);
        reader.parse(source);
        //LoggerFactory.getBootLogger().info("loading XML took " + (stop - start) + " msecs");
        result = repository;
    } else
        throw new MetadataException(
                "Could not build a repository instance for '" + target + "', using source " + source);
    return result;
}

From source file:org.apache.shindig.social.opensocial.util.XSDValidator.java

/**
 * Validate a xml input stream against a supplied schema.
 *
 * @param xml//from  www  .  j  a v a  2s .  c  om
 *          a stream containing the xml
 * @param schema
 *          a stream containing the schema
 * @return a list of errors or warnings, a 0 lenght string if none.
 */
public static String validate(InputStream xml, InputStream schema) {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    final StringBuilder errors = new StringBuilder();
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA);
        Schema s = schemaFactory.newSchema(new StreamSource(schema));

        Validator validator = s.newValidator();
        final LSResourceResolver lsr = validator.getResourceResolver();
        validator.setResourceResolver(new LSResourceResolver() {

            public LSInput resolveResource(String arg0, String arg1, String arg2, String arg3, String arg4) {
                log.info("resolveResource(" + arg0 + ',' + arg1 + ',' + arg2 + ',' + arg3 + ',' + arg4 + ')');
                return lsr.resolveResource(arg0, arg1, arg2, arg3, arg4);
            }

        });

        validator.validate(new StreamSource(xml));
    } catch (IOException e) {
    } catch (SAXException e) {
        errors.append(e.getMessage()).append('\n');
    }

    return errors.toString();
}

From source file:org.apache.synapse.mediators.builtin.ValidateMediator.java

public boolean mediate(SynapseContext synCtx) {

    ByteArrayInputStream baisFromSource = null;
    StringBuffer nsLocations = new StringBuffer();

    try {/*from w ww  . ja v a 2 s .  c  om*/
        // create a byte array output stream and serialize the source node into it
        ByteArrayOutputStream baosForSource = new ByteArrayOutputStream();
        XMLStreamWriter xsWriterForSource = XMLOutputFactory.newInstance().createXMLStreamWriter(baosForSource);

        // save the list of defined namespaces for validation against the schema
        OMNode sourceNode = getValidateSource(synCtx.getSynapseMessage());
        if (sourceNode instanceof OMElement) {
            Iterator iter = ((OMElement) sourceNode).getAllDeclaredNamespaces();
            while (iter.hasNext()) {
                OMNamespace omNS = (OMNamespace) iter.next();
                nsLocations.append(omNS.getName() + " " + getSchemaUrl());
            }
        }
        sourceNode.serialize(xsWriterForSource);
        baisFromSource = new ByteArrayInputStream(baosForSource.toByteArray());

    } catch (Exception e) {
        String msg = "Error accessing source element for validation : " + source;
        log.error(msg);
        throw new SynapseException(msg, e);
    }

    try {
        SAXParserFactory spFactory = SAXParserFactory.newInstance();
        spFactory.setNamespaceAware(true);
        spFactory.setValidating(true);
        SAXParser parser = spFactory.newSAXParser();

        parser.setProperty(VALIDATION, Boolean.TRUE);
        parser.setProperty(SCHEMA_VALIDATION, Boolean.TRUE);
        parser.setProperty(FULL_CHECKING, Boolean.TRUE);
        parser.setProperty(SCHEMA_LOCATION_NS, nsLocations.toString());
        parser.setProperty(SCHEMA_LOCATION_NO_NS, getSchemaUrl());

        Validator handler = new Validator();
        parser.parse(baisFromSource, handler);

        if (handler.isValidationError()) {
            log.debug("Validation failed :" + handler.getSaxParseException().getMessage());
            // super.mediate() invokes the "on-fail" sequence of mediators
            return super.mediate(synCtx);
        }

    } catch (Exception e) {
        String msg = "Error validating " + source + " against schema : " + schemaUrl + " : " + e.getMessage();
        log.error(msg);
        throw new SynapseException(msg, e);
    }

    return true;
}

From source file:org.apache.tapestry.util.xml.RuleDirectedParser.java

/**
 * Configures a {@link SAXParserFactory} before
 * {@link SAXParserFactory#newSAXParser()} is invoked.
 * The default implementation sets validating to true
 * and namespaceAware to false,//ww  w .ja va 2  s .  c o m
 */

protected void configureParserFactory(SAXParserFactory factory) {
    factory.setValidating(true);
    factory.setNamespaceAware(false);
}

From source file:org.browsermob.proxy.jetty.xml.XmlParser.java

/**
 * Construct/*from  w  ww .j ava  2s  . c  o m*/
 */
public XmlParser() {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        boolean notValidating = Boolean.getBoolean("org.browsermob.proxy.jetty.xml.XmlParser.NotValidating");
        factory.setValidating(!notValidating);
        _parser = factory.newSAXParser();
        try {
            if (!notValidating)
                _parser.getXMLReader().setFeature("http://apache.org/xml/features/validation/schema", true);
        } catch (Exception e) {
            log.warn("Schema validation may not be supported");
            log.debug("", e);
            notValidating = true;
        }
        _parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", !notValidating);
        _parser.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", !notValidating);
        _parser.getXMLReader().setFeature("http://xml.org/sax/features/namespace-prefixes", !notValidating);
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
        throw new Error(e.toString());
    }
}

From source file:org.chiba.xml.xforms.connector.SchemaValidator.java

/**
 * validate the instance according to the schema specified on the model
 *
 * @return false if the instance is not valid
 *///from  w ww .  ja  va  2  s .  c om
public boolean validateSchema(Model model, Node instance) throws XFormsException {
    boolean valid = true;
    String message;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("SchemaValidator.validateSchema: validating instance");

    //needed if we want to load schemas from Model + set it as "schemaLocation" attribute
    String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema");
    if (schemas != null && !schemas.equals("")) {
        //          valid=false;

        //add schemas to element
        //shouldn't it be done on a copy of the doc ?
        Element el = null;
        if (instance.getNodeType() == Node.ELEMENT_NODE)
            el = (Element) instance;
        else if (instance.getNodeType() == Node.DOCUMENT_NODE)
            el = ((Document) instance).getDocumentElement();
        else {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("instance node type is: " + instance.getNodeType());
        }

        String prefix = NamespaceResolver.getPrefix(el, XMLSCHEMA_INSTANCE_NS);
        //test if with targetNamespace or not
        //if more than one schema : namespaces are mandatory ! (optional only for 1)
        StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false);
        String schemaLocations = null;
        String noNamespaceSchemaLocation = null;
        while (tokenizer.hasMoreElements()) {
            String token = (String) tokenizer.nextElement();
            //check that it is an URL
            URI uri = null;
            try {
                uri = new java.net.URI(token);
            } catch (java.net.URISyntaxException ex) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(token + " is not an URI");
            }

            if (uri != null) {
                String ns;
                try {
                    ns = this.getSchemaNamespace(uri);

                    if (ns != null && !ns.equals("")) {
                        if (schemaLocations == null)
                            schemaLocations = ns + " " + token;
                        else
                            schemaLocations = schemaLocations + " " + ns + " " + token;

                        ///add the namespace declaration if it is not on the instance?
                        //TODO: how to know with which prefix ?
                        String nsPrefix = NamespaceResolver.getPrefix(el, ns);
                        if (nsPrefix == null) { //namespace not declared !
                            LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token
                                    + " is not declared in instance: declaring it as default...");
                            el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns);
                        }
                    } else if (noNamespaceSchemaLocation == null)
                        noNamespaceSchemaLocation = token;
                    else { //we have more than one schema without namespace
                        LOGGER.warn("SchemaValidator: There is more than one schema without namespace !");
                    }
                } catch (Exception ex) {
                    LOGGER.warn(
                            "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(),
                            ex);
                    //in case there was an exception: do nothing, do not set the schema
                }
            }
        }
        //write schemaLocations found
        if (schemaLocations != null && !schemaLocations.equals(""))
            el.setAttributeNS(XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation", schemaLocations);
        if (noNamespaceSchemaLocation != null)
            el.setAttributeNS(XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation",
                    noNamespaceSchemaLocation);

        //save and parse the doc
        ValidationErrorHandler handler = null;
        File f;
        try {
            //save document
            f = File.createTempFile("instance", ".xml");
            f.deleteOnExit();
            TransformerFactory trFact = TransformerFactory.newInstance();
            Transformer trans = trFact.newTransformer();
            DOMSource source = new DOMSource(el);
            StreamResult result = new StreamResult(f);
            trans.transform(source, result);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath());

            //parse it with error handler to validate it
            handler = new ValidationErrorHandler();
            SAXParserFactory parserFact = SAXParserFactory.newInstance();
            parserFact.setValidating(true);
            parserFact.setNamespaceAware(true);
            SAXParser parser = parserFact.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            //validation activated
            reader.setFeature("http://xml.org/sax/features/validation", true);
            //schema validation activated
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            //used only to validate the schema, not the instance
            //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true);
            //validate only if there is a grammar
            reader.setFeature("http://apache.org/xml/features/validation/dynamic", true);

            parser.parse(f, handler);
        } catch (Exception ex) {
            LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex);
            //throw new XFormsException("XMLSchema validation failed. "+message);
        }

        //if no exception
        if (handler != null && handler.isValid())
            valid = true;
        else {
            message = handler.getMessage();
            //TODO: find a way to get the error message displayed
            throw new XFormsException("XMLSchema validation failed. " + message);
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Validator.validateSchema: result=" + valid);

    }

    return valid;
}

From source file:org.codehaus.enunciate.config.EnunciateConfiguration.java

/**
 * Create the digester./*  w w w.j av a  2s .  com*/
 *
 * @return The digester that was created.
 */
protected Digester createDigester() throws SAXException {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(false);
        factory.setValidating(false);

        Properties properties = new Properties();
        properties.put("SAXParserFactory", factory);
        //      properties.put("schemaLocation", EnunciateConfiguration.class.getResource("enunciate.xsd").toString());
        //      properties.put("schemaLanguage", "http://www.w3.org/2001/XMLSchema");

        SAXParser parser = GenericParser.newSAXParser(properties);
        return new Digester(parser);
    } catch (ParserConfigurationException e) {
        throw new SAXException(e);
    }
}