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.openhealthtools.openatna.anom.codes.CodeParser.java

public static void parse(Collection<String> codes) {
    try {/*w ww.j  av a2 s.co m*/
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setValidating(false);
        javax.xml.parsers.SAXParser sp = spf.newSAXParser();
        Handler handler = new Handler();
        for (String code : codes) {
            try {
                URL url = new URL(code);
                InputSource input = new InputSource(url.openStream());
                input.setSystemId(code.toString());
                sp.parse(input, handler);
            } catch (Exception e) {
                log.warn("Error parsing codes at:" + code);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Error loading system codes", e);
    }
}

From source file:org.opennms.core.test.xml.XmlTest.java

protected void validateXmlString(final String xml) throws Exception {
    if (getSchemaFile() == null) {
        LOG.warn("skipping validation, schema file not set");
        return;//from  w  w  w .ja v a 2s. com
    }

    final SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    final File schemaFile = new File(getSchemaFile());
    LOG.debug("Validating using schema file: {}", schemaFile);
    final Schema schema = schemaFactory.newSchema(schemaFile);

    final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setValidating(true);
    saxParserFactory.setNamespaceAware(true);
    saxParserFactory.setSchema(schema);

    assertTrue("make sure our SAX implementation can validate", saxParserFactory.isValidating());

    final Validator validator = schema.newValidator();
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
    final Source source = new StreamSource(inputStream);

    validator.validate(source);
}

From source file:org.openqa.jetty.xml.XmlParser.java

/**
 * Construct/*from  www .ja va 2 s  .co m*/
 */
public XmlParser() {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        boolean notValidating = Boolean.getBoolean("org.openqa.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.plasma.sdo.helper.PlasmaXMLHelper.java

private void validateSAX(InputStream inputStream, String locationURI, XMLOptions options) throws IOException {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);/*from  ww w .j  a va  2 s. c  o m*/
    SAXParser parser;

    try {
        factory.setFeature("http://xml.org/sax/features/validation", true);
        factory.setFeature("http://apache.org/xml/features/validation/schema", true);
        factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
        parser = factory.newSAXParser();
        try {
            parser.setProperty(XMLConstants.JAXP_SCHEMA_LANGUAGE, SchemaConstants.XMLSCHEMA_NAMESPACE_URI);
        } catch (SAXNotRecognizedException e) {
            log.warn("parses does not support JAXP 1.2");
        }
        if (locationURI != null) {
            parser.setProperty(XMLConstants.JAXP_NO_NAMESPACE_SCHEMA_SOURCE, locationURI);
        }
        XMLReader xmlReader = parser.getXMLReader();
        //xmlReader.setEntityResolver(new SchemaLoader());
        if (options.getErrorHandler() == null)
            xmlReader.setErrorHandler(new DefaultErrorHandler(options));
        else
            xmlReader.setErrorHandler(options.getErrorHandler());
        if (log.isDebugEnabled())
            log.debug("validating...");
        xmlReader.parse(new InputSource(inputStream));

    } catch (SAXNotRecognizedException e) {
        throw new PlasmaDataObjectException(e);
    } catch (SAXNotSupportedException e) {
        throw new PlasmaDataObjectException(e);
    } catch (ParserConfigurationException e) {
        throw new PlasmaDataObjectException(e);
    } catch (SAXException e) {
        throw new PlasmaDataObjectException(e);
    }
}

From source file:org.roda.core.common.validation.ValidationUtils.java

public static ValidationReport isXMLValid(ContentPayload xmlPayload) {
    ValidationReport ret = new ValidationReport();

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);/*from w  w w  .  j  a v  a2 s. c om*/

    RodaErrorHandler errorHandler = new RodaErrorHandler();

    try (Reader reader = new InputStreamReader(new BOMInputStream(xmlPayload.createInputStream()))) {
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setEntityResolver(new RodaEntityResolver());
        InputSource inputSource = new InputSource(reader);

        xmlReader.setErrorHandler(errorHandler);
        xmlReader.parse(inputSource);
        ret.setValid(errorHandler.getErrors().isEmpty());
        for (SAXParseException saxParseException : errorHandler.getErrors()) {
            ret.addIssue(convertSAXParseException(saxParseException));
        }
    } catch (SAXException e) {
        ret.setValid(false);
        for (SAXParseException saxParseException : errorHandler.getErrors()) {
            ret.addIssue(convertSAXParseException(saxParseException));
        }
    } catch (IOException e) {
        ret.setValid(false);
        ret.setMessage(e.getMessage());
    }
    return ret;
}

From source file:org.sakaiproject.kernel.util.XSDValidator.java

/**
 * Validate a xml input stream against a supplied schema.
 * @param xml 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.
 *///ww  w.  jav a  2s .c o m
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();
        validator.validate(new StreamSource(xml));
    } catch (IOException e) {
        errors.append(e.getMessage()).append("\n");
    } catch (SAXException e) {
        errors.append(e.getMessage()).append("\n");
    }
    return errors.toString();
}

From source file:org.sonar.java.xml.XmlParser.java

private static void disableXmlValidation(SAXParserFactory factory)
        throws ParserConfigurationException, SAXException {
    factory.setValidating(false);
    factory.setFeature("http://xml.org/sax/features/validation", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
    factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
}

From source file:org.tonguetied.datatransfer.importing.ResourceImporter.java

@Override
protected void doImport(final byte[] input, final TranslationState state) throws ImportException {
    if (logger.isDebugEnabled())
        logger.debug("attempting import");
    ByteArrayInputStream bais = null;
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);/*from w  w  w . j a va2s  . c  o  m*/
    try {
        //            validate(bais);
        //            XMLReader reader = XMLReaderFactory.createXMLReader();
        //            reader.setContentHandler(new ResourceHandler(
        //                    getBundle(), getCountry(), getLanguage(), state, getKeywordService()));
        //            // Request validation
        //            reader.setFeature("http://xml.org/sax/features/validation", true);
        //            InputSource is = new InputSource(bais);
        //            reader.parse(is);

        SAXParser parser = factory.newSAXParser();

        bais = new ByteArrayInputStream(input);
        parser.parse(bais,
                new ResourceHandler(getBundle(), getCountry(), getLanguage(), state, getKeywordService()));
    } catch (SAXException saxe) {
        throw new ImportException(saxe);
    } catch (ParserConfigurationException pce) {
        throw new ImportException(pce);
    } catch (IOException ioe) {
        throw new ImportException(ioe);
    } finally {
        IOUtils.closeQuietly(bais);
    }
}

From source file:org.unitils.dbunit.datasetfactory.DataSetFactoryFactory.java

protected void disableValidation(SAXParserFactory saxParserFactory) {
    saxParserFactory.setValidating(false);
    try {/*w  w w . ja v a2 s. c  o  m*/
        saxParserFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    } catch (Exception e) {
        logger.debug(
                "Unable to set http://xml.org/sax/features/external-parameter-entities feature on SAX parser factory to false. Ignoring exception: "
                        + e.getMessage());
    }
    try {
        saxParserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (Exception e) {
        logger.debug(
                "Unable to set http://apache.org/xml/features/nonvalidating/load-external-dtd feature on SAX parser factory to false. Ignoring exception: "
                        + e.getMessage());
    }
}

From source file:org.unitils.dbunit.util.MultiSchemaXmlDataSetReader.java

/**
 * Disables validation on the given sax parser factory.
 *
 * @param saxParserFactory The factory, not null
 *///from  ww w.  ja  va2 s  .c  o  m
protected void disableValidation(SAXParserFactory saxParserFactory) {
    saxParserFactory.setValidating(false);
    try {
        saxParserFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    } catch (Exception e) {
        logger.debug(
                "Unable to set http://xml.org/sax/features/external-parameter-entities feature on SAX parser factory to false. Igoring exception: "
                        + e.getMessage());
    }
    try {
        saxParserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (Exception e) {
        logger.debug(
                "Unable to set http://apache.org/xml/features/nonvalidating/load-external-dtd feature on SAX parser factory to false. Igoring exception: "
                        + e.getMessage());
    }
}