Example usage for javax.xml.parsers SAXParserFactory setSchema

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

Introduction

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

Prototype

public void setSchema(Schema schema) 

Source Link

Document

Set the Schema to be used by parsers created from this factory.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
    SchemaFactory factory = SchemaFactory.newInstance(language);
    Schema schema = factory.newSchema(new File("yourSchema"));

    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setSchema(schema);

    SAXParser parser = spf.newSAXParser();

    // parser.parse(...);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String xml = "<?xml version='1.0'?><test><test2></test2></test>";
    String schemaString = //
            "<?xml version='1.0'?>"//
                    + "<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' elementFormDefault='unqualified' attributeFormDefault='unqualified'>"//
                    + "<xsd:element name='test' type='Test'/>"//
                    + "<xsd:element name='test2' type='Test2'/>"//
                    + "<xsd:complexType name='Test'>"//
                    + "<xsd:sequence>"//
                    + "<xsd:element ref='test2' minOccurs='1' maxOccurs='unbounded'/>"//
                    + "</xsd:sequence>"//
                    + "</xsd:complexType>"//
                    + "<xsd:simpleType name='Test2'>"//
                    + "<xsd:restriction base='xsd:string'><xsd:minLength value='1'/></xsd:restriction>"//
                    + "</xsd:simpleType>"//
                    + "</xsd:schema>";

    Source schemaSource = new StreamSource(new StringReader(schemaString));
    Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaSource);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);//from w ww  . j ava 2 s . co m
    factory.setSchema(schema);
    SAXParser parser = factory.newSAXParser();
    MyContentHandler handler = new MyContentHandler();
    parser.parse(new InputSource(new StringReader(xml)), handler);

}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser parser = null;//from   w  w w .  ja  va 2 s  . c om
    spf.setNamespaceAware(true);
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        spf.setSchema(sf.newSchema(new SAXSource(new InputSource(new StringReader(schemaString)))));

        parser = spf.newSAXParser();
    } catch (SAXException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    } catch (ParserConfigurationException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
    MySAXHandler handler = new MySAXHandler();
    System.out.println(schemaString);
    parser.parse(new InputSource(new StringReader(xmlString)), handler);
}

From source file:no.uis.service.studinfo.commons.StudinfoValidator.java

protected List<String> validate(String studieinfoXml, StudinfoType infoType, int year, FsSemester semester,
        String language) throws Exception {

    // save xml//  w  ww . j a va 2  s  . c om
    File outFile = new File("target/out", infoType.toString() + year + semester + language + ".xml");
    if (outFile.exists()) {
        outFile.delete();
    } else {
        outFile.getParentFile().mkdirs();
    }
    File outBackup = new File("target/out", infoType.toString() + year + semester + language + "_orig.xml");
    Writer backupWriter = new OutputStreamWriter(new FileOutputStream(outBackup), IOUtils.UTF8_CHARSET);
    backupWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    IOUtils.copy(new StringReader(studieinfoXml), backupWriter, IOBUFFER_SIZE);
    backupWriter.flush();
    backupWriter.close();

    TransformerFactory trFactory = TransformerFactory.newInstance();
    Source schemaSource = new StreamSource(getClass().getResourceAsStream("/fspreprocess.xsl"));
    Transformer stylesheet = trFactory.newTransformer(schemaSource);

    Source input = new StreamSource(new StringReader(studieinfoXml));

    Result result = new StreamResult(outFile);
    stylesheet.transform(input, result);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory
            .newSchema(new Source[] { new StreamSource(new File("src/main/xsd/studinfo.xsd")) });

    factory.setSchema(schema);

    SAXParser parser = factory.newSAXParser();

    XMLReader reader = parser.getXMLReader();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler(infoType, year, semester, language);
    reader.setErrorHandler(errorHandler);
    reader.setContentHandler(errorHandler);
    try {
        reader.parse(
                new InputSource(new InputStreamReader(new FileInputStream(outFile), IOUtils.UTF8_CHARSET)));
    } catch (SAXException ex) {
        // do nothing. The error is handled in the error handler
    }
    return errorHandler.getMessages();
}

From source file:com.silverpeas.importExport.control.ImportExport.java

/**
 * Mthode retournant l'arbre des objets mapps sur le fichier xml pass en paramtre.
 *
 * @param xmlFileName le fichier xml interprt par Castor
 * @return Un objet SilverPeasExchangeType contenant le mapping d'un fichier XML Castor
 * @throws ImportExportException/*from www  . java  2 s .c  o  m*/
 */
SilverPeasExchangeType loadSilverpeasExchange(String xmlFileName) throws ImportExportException {
    SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange",
            "root.MSG_GEN_ENTER_METHOD", "xmlFileName = " + xmlFileName);

    try {
        InputSource xmlInputSource = new InputSource(xmlFileName);
        String xsdPublicId = settings.getString("xsdPublicId");
        String xsdSystemId = settings.getString("xsdDefaultSystemId");

        // Load and parse default XML schema for import/export
        SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema",
                "com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory", null);
        Schema schema = schemaFactory.newSchema(new StreamSource(xsdSystemId));

        // Create an XML parser for loading XML import file
        SAXParserFactory factory = SAXParserFactory
                .newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null);
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        factory.setSchema(schema);
        SAXParser parser = factory.newSAXParser();

        // First try to determine to load the XML file using the default
        // XML-Schema
        ImportExportErrorHandler errorHandler = new ImportExportErrorHandler();
        XMLReader xmlReader = parser.getXMLReader();
        xmlReader.setErrorHandler(errorHandler);

        try {
            xmlReader.parse(xmlInputSource);

        } catch (SAXException ex) {
            SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange",
                    "root.MSG_GEN_PARAM_VALUE", (new StringBuilder("XML File ")).append(xmlFileName)
                            .append(" is not valid according to default schema").toString());

            // If case the default schema is not the one specified by the
            // XML import file, try to get the right XML-schema and
            // namespace (this is done by parsing without validation)
            ImportExportNamespaceHandler nsHandler = new ImportExportNamespaceHandler();
            factory.setSchema(null);
            parser = factory.newSAXParser();
            xmlReader = parser.getXMLReader();
            xmlReader.setContentHandler(nsHandler);
            xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
            xmlReader.parse(xmlInputSource);

            // If OK, extract the name and location of the schema
            String nsSpec = nsHandler.getNsSpec();
            if (nsSpec == null || xsdPublicId.equals(nsSpec)) {
                throw ex;
            }

            String nsVersion = extractUriNameIndex(nsSpec);
            if (nsVersion.length() == 0) {
                throw ex;
            }

            String altXsdSystemId = settings.getStringWithParam("xsdSystemId", nsVersion);
            if ((altXsdSystemId == null) || (altXsdSystemId.equals(xsdSystemId))) {
                throw ex;
            }

            SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange",
                    "root.MSG_GEN_PARAM_VALUE",
                    (new StringBuilder("Trying again using schema specification located at "))
                            .append(altXsdSystemId).toString());

            // Try again to load, parse and validate the XML import file,
            // using the new schema specification
            schema = schemaFactory.newSchema(new StreamSource(altXsdSystemId));
            factory.setSchema(schema);
            parser = factory.newSAXParser();
            xmlReader = parser.getXMLReader();
            xmlReader.setErrorHandler(errorHandler);
            xmlReader.parse(xmlInputSource);
        }

        SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange",
                "root.MSG_GEN_PARAM_VALUE", "XML Validation complete");

        // Mapping file for Castor
        String mappingDir = settings.getString("mappingDir");
        String mappingFileName = settings.getString("importExportMapping");
        String mappingFile = mappingDir + mappingFileName;
        Mapping mapping = new Mapping();

        // Load mapping and instantiate a Unmarshaller
        mapping.loadMapping(mappingFile);
        Unmarshaller unmar = new Unmarshaller(SilverPeasExchangeType.class);
        unmar.setMapping(mapping);
        unmar.setValidation(false);

        // Unmarshall the process model
        SilverPeasExchangeType silverpeasExchange = (SilverPeasExchangeType) unmar.unmarshal(xmlInputSource);
        SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange",
                "root.MSG_GEN_PARAM_VALUE", "Unmarshalling complete");
        return silverpeasExchange;

    } catch (MappingException me) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange",
                "importExport.EX_LOADING_XML_MAPPING_FAILED",
                "XML Filename " + xmlFileName + ": " + me.getLocalizedMessage(), me);
    } catch (MarshalException me) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange",
                "importExport.EX_UNMARSHALLING_FAILED",
                "XML Filename " + xmlFileName + ": " + me.getLocalizedMessage(), me);
    } catch (ValidationException ve) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED",
                "XML Filename " + xmlFileName + ": " + ve.getLocalizedMessage(), ve);
    } catch (IOException ioe) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange",
                "importExport.EX_LOADING_XML_MAPPING_FAILED",
                "XML Filename " + xmlFileName + ": " + ioe.getLocalizedMessage(), ioe);
    } catch (ParserConfigurationException ex) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED",
                "XML Filename " + xmlFileName + ": " + ex.getLocalizedMessage(), ex);
    } catch (SAXNotRecognizedException snre) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED",
                "XML Filename " + xmlFileName + ": " + snre.getLocalizedMessage(), snre);
    } catch (SAXNotSupportedException snse) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED",
                "XML Filename " + xmlFileName + ": " + snse.getLocalizedMessage(), snse);
    } catch (SAXException se) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED",
                "XML Filename " + xmlFileName + ": " + se.getLocalizedMessage(), se);
    }
}

From source file:nl.nn.adapterframework.validation.JavaxXmlValidator.java

@Override
public XMLReader createValidatingParser(IPipeLineSession session, ValidationContext context)
        throws XmlValidatorException, PipeRunException {
    SAXParser parser;// w w  w  .  j a v  a 2 s .c  o m
    try {
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setValidating(false);
        parserFactory.setNamespaceAware(true);
        parserFactory.setFeature(PARSING_FEATURE_SECURE, true);
        //parserFactory.setFeature(PARSING_FEATURE_EXTERNAL_GENERAL_ENTITIES, false);
        //parserFactory.setFeature(PARSING_FEATURE_EXTERNAL_PARAMETER_ENTITIES, false);
        //parserFactory.setFeature(PARSING_FEATURE_DISALLOW_INLINE_DOCTYPE, true);

        Schema schema = getSchemaObject(context.getSchemasId(), schemasProvider.getSchemas(session));
        parserFactory.setSchema(schema);

        parser = parserFactory.newSAXParser();
        return parser.getXMLReader();
    } catch (ParserConfigurationException e) {
        throw new XmlValidatorException(logPrefix + "cannot configure parser", e);
    } catch (ConfigurationException e) {
        throw new XmlValidatorException(logPrefix + "cannot configure parser", e);
    } catch (SAXException e) {
        throw new XmlValidatorException(logPrefix + "cannot create parser", e);
    }
}

From source file:org.openbravo.test.webservice.BaseWSTest.java

/**
 * Validates the xml against the generated schema.
 * /*w  w  w.ja  v a 2  s.co m*/
 * @param xml
 *          the xml to validate
 */
protected void validateXML(String xml) {
    final Reader schemaReader = new StringReader(getXMLSchema());
    final Reader xmlReader = new StringReader(xml);
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);

        SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

        factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource(schemaReader) }));

        SAXParser parser = factory.newSAXParser();

        XMLReader reader = parser.getXMLReader();
        reader.setErrorHandler(new SimpleErrorHandler());
        reader.parse(new InputSource(xmlReader));
    } catch (Exception e) {
        throw new OBException(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 .j a  v a 2 s  .c  o m*/
    }

    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);
}