Java Code Examples for javax.xml.parsers.SAXParserFactory#setSchema()

The following examples show how to use javax.xml.parsers.SAXParserFactory#setSchema() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TicketParser.java    From nordpos with GNU General Public License v3.0 6 votes vote down vote up
public void printTicket(Reader in) throws TicketPrinterException {
    try {
        if (m_sp == null) {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            spf.setValidating(false);
            spf.setNamespaceAware(true);
            SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
            spf.setSchema(schemaFactory.newSchema(new Source[]{new StreamSource(shemaFile)}));
            m_sp = spf.newSAXParser();
            m_sr = m_sp.getXMLReader();
        }
        m_sr.setContentHandler(this);
        m_sr.parse(new InputSource(in));
    } catch (ParserConfigurationException ePC) {
        throw new TicketPrinterException(LocalRes.getIntString("exception.parserconfig"), ePC);
    } catch (SAXException eSAX) {
        throw new TicketPrinterException(LocalRes.getIntString("exception.xmlfile"), eSAX);
    } catch (IOException eIO) {
        throw new TicketPrinterException(LocalRes.getIntString("exception.iofile"), eIO);
    }
}
 
Example 2
Source File: PropertiesConfig.java    From nordpos with GNU General Public License v3.0 6 votes vote down vote up
public PropertiesConfig(String configXML) {

        if (configXML != null) {
            try {
                if (m_sp == null) {
                SAXParserFactory spf = SAXParserFactory.newInstance();
                spf.setValidating(false);
                spf.setNamespaceAware(true);
                SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
                InputStream = getClass().getResourceAsStream("/com/openbravo/pos/templates/Schema.Ticket.xsd");
                spf.setSchema(schemaFactory.newSchema(new Source[]{new StreamSource(InputStream)}));
                m_sp = spf.newSAXParser();
                m_sr = m_sp.getXMLReader();
                m_sr.setContentHandler(new ConfigurationHandler());
                }
                m_sp.parse(new InputSource(new StringReader(configXML)), new ConfigurationHandler());
                m_sr.parse(new InputSource(new StringReader(configXML)));
            } catch (ParserConfigurationException ePC) {
                logger.log(Level.WARNING, LocalRes.getIntString("exception.parserconfig"), ePC);
            } catch (SAXException eSAX) {
                logger.log(Level.WARNING, LocalRes.getIntString("exception.xmlfile"), eSAX);
            } catch (IOException eIO) {
                logger.log(Level.WARNING, LocalRes.getIntString("exception.iofile"), eIO);
            }
        }
    }
 
Example 3
Source File: Parser.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private XMLReader createReader() throws SAXException {
    try {
        SAXParserFactory pfactory = SAXParserFactory.newInstance();
        pfactory.setValidating(true);
        pfactory.setNamespaceAware(true);

        // Enable schema validation
        SchemaFactory sfactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        InputStream stream = Parser.class.getResourceAsStream("graphdocument.xsd");
        pfactory.setSchema(sfactory.newSchema(new Source[]{new StreamSource(stream)}));

        return pfactory.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException ex) {
        throw new SAXException(ex);
    }
}
 
Example 4
Source File: Bug6946312Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test() throws SAXException, ParserConfigurationException, IOException {
    Schema schema = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema").newSchema(new StreamSource(new StringReader(xmlSchema)));

    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setNamespaceAware(true);
    saxParserFactory.setSchema(schema);
    // saxParserFactory.setFeature("http://java.sun.com/xml/schema/features/report-ignored-element-content-whitespace",
    // true);

    SAXParser saxParser = saxParserFactory.newSAXParser();

    XMLReader xmlReader = saxParser.getXMLReader();

    xmlReader.setContentHandler(new MyContentHandler());

    // InputStream input =
    // ClassLoader.getSystemClassLoader().getResourceAsStream("test/test.xml");

    InputStream input = getClass().getResourceAsStream("Bug6946312.xml");
    System.out.println("Parse InputStream:");
    xmlReader.parse(new InputSource(input));
    if (!charEvent) {
        Assert.fail("missing character event");
    }
}
 
Example 5
Source File: Bug6974551Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSAX() {
    try {
        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new StreamSource(_xsd));
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        spf.setValidating(true);
        spf.setSchema(schema);
        SAXParser parser = spf.newSAXParser();
        MyErrorHandler errorHandler = new MyErrorHandler();
        parser.parse(_xml, errorHandler);
        if (!errorHandler.errorOccured) {
            Assert.fail("should report error");
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
 
Example 6
Source File: Issue682Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test() {
    try {
        Schema schema = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema").newSchema(new StreamSource(testFile));
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(true);
        saxParserFactory.setSchema(schema);
        // saxParserFactory.setFeature("http://java.sun.com/xml/schema/features/report-ignored-element-content-whitespace",
        // true);
        SAXParser saxParser = saxParserFactory.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setContentHandler(new DefaultHandler());
        // InputStream input =
        // ClassLoader.getSystemClassLoader().getResourceAsStream("test/test.xml");
        InputStream input = getClass().getResourceAsStream("Issue682.xml");
        System.out.println("Parse InputStream:");
        xmlReader.parse(new InputSource(input));
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail(ex.toString());
    }

}
 
Example 7
Source File: ProductImportParser.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Parse the given XML string an create/update the corresponding entities
 * 
 * @param xml
 *            the XML string
 * @return the parse return code
 * @throws Exception
 */
public int parse(byte[] xml) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    SchemaFactory sf = SchemaFactory
            .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try (InputStream inputStream = ResourceLoader.getResourceAsStream(
            getClass(), getSchemaName())) {
        Schema schema = sf.newSchema(new StreamSource(inputStream));
        spf.setSchema(schema);
    }
    SAXParser saxParser = spf.newSAXParser();
    XMLReader reader = saxParser.getXMLReader();
    reader.setFeature(Constants.XERCES_FEATURE_PREFIX
            + Constants.DISALLOW_DOCTYPE_DECL_FEATURE, true);
    reader.setContentHandler(this);
    reader.parse(new InputSource(new ByteArrayInputStream(xml)));
    return 0;
}
 
Example 8
Source File: Bug6564400.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConformantSAX() throws ParserConfigurationException, SAXException, IOException {
    InputStream xmlFile = getClass().getResourceAsStream("Bug6564400.xml");

    // Parse with SAX
    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    saxFactory.setSchema(schema);
    saxFactory.setFeature("http://java.sun.com/xml/schema/features/report-ignored-element-content-whitespace", true);

    SAXParser saxparser = saxFactory.newSAXParser();

    sawIgnorable = false;
    saxparser.parse(xmlFile, new MyHandler());
    Assert.assertEquals(false, sawIgnorable);
}
 
Example 9
Source File: DomLoader.java    From metafacture-core with Apache License 2.0 5 votes vote down vote up
private static XMLReader createSaxReader(Schema schema) {
    final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    parserFactory.setSchema(schema);
    parserFactory.setNamespaceAware(true);
    parserFactory.setXIncludeAware(true);
    try {
        return parserFactory.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException | SAXException e) {
        throw new MetafactureException(e);
    }
}
 
Example 10
Source File: XmlUtil.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static SAXParser newSAXParser(boolean namespaceAware, boolean validating, Schema schema1) throws ParserConfigurationException, SAXException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(validating);
    factory.setNamespaceAware(namespaceAware);
    factory.setSchema(schema1);
    return factory.newSAXParser();
}
 
Example 11
Source File: XmlUtil.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Factory method to create a SAXParser configured to validate according to a particular schema language and
 * optionally providing the schema sources to validate with.
 *
 * @param schemaLanguage the schema language used, e.g. XML Schema or RelaxNG (as per the String representation in javax.xml.XMLConstants)
 * @param namespaceAware will the parser be namespace aware
 * @param validating     will the parser also validate against DTDs
 * @param schemas        the schemas to validate against
 * @return the created SAXParser
 * @throws SAXException
 * @throws ParserConfigurationException
 * @since 1.8.7
 */
public static SAXParser newSAXParser(String schemaLanguage, boolean namespaceAware, boolean validating, Source... schemas) throws SAXException, ParserConfigurationException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(validating);
    factory.setNamespaceAware(namespaceAware);
    if (schemas.length != 0) {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
        factory.setSchema(schemaFactory.newSchema(schemas));
    }
    SAXParser saxParser = factory.newSAXParser();
    if (schemas.length == 0) {
        saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", schemaLanguage);
    }
    return saxParser;
}
 
Example 12
Source File: ServiceProvisioningServiceBeanImportExportSchemaIT.java    From development with Apache License 2.0 5 votes vote down vote up
private void verifyXML(byte[] xml) throws IOException, SAXException,
        ParserConfigurationException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);

    SchemaFactory sf = SchemaFactory
            .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    ClassLoader classLoader = Thread.currentThread()
            .getContextClassLoader();
    if (classLoader == null) {
        classLoader = getClass().getClassLoader();
    }

    final Schema schema;
    try (InputStream inputStream = ResourceLoader.getResourceAsStream(
            getClass(), "TechnicalServices.xsd")) {
        schema = sf.newSchema(new StreamSource(inputStream));
    }
    spf.setSchema(schema);

    SAXParser saxParser = spf.newSAXParser();
    XMLReader reader = saxParser.getXMLReader();
    ErrorHandler errorHandler = new MyErrorHandler();
    reader.setErrorHandler(errorHandler);
    reader.parse(new InputSource(new ByteArrayInputStream(xml)));
}
 
Example 13
Source File: GenerateJfrFiles.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
Metadata(File metadataXml, File metadataSchema) throws ParserConfigurationException, SAXException, FileNotFoundException, IOException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setSchema(schemaFactory.newSchema(metadataSchema));
    SAXParser sp = factory.newSAXParser();
    sp.parse(metadataXml, new MetadataHandler(this));
}
 
Example 14
Source File: Bug6564400.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testSAX() throws ParserConfigurationException, SAXException, IOException {
    InputStream xmlFile = getClass().getResourceAsStream("Bug6564400.xml");

    // Parse with SAX
    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    saxFactory.setSchema(schema);

    SAXParser saxparser = saxFactory.newSAXParser();

    sawIgnorable = false;
    saxparser.parse(xmlFile, new MyHandler());
    Assert.assertEquals(true, sawIgnorable);
}
 
Example 15
Source File: GenerateJfrFiles.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
Metadata(File metadataXml, File metadataSchema) throws ParserConfigurationException, SAXException, FileNotFoundException, IOException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setSchema(schemaFactory.newSchema(metadataSchema));
    SAXParser sp = factory.newSAXParser();
    sp.parse(metadataXml, new MetadataHandler(this));
}
 
Example 16
Source File: TestPrintXML.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... args) throws Throwable {

        Path recordingFile = ExecuteHelper.createProfilingRecording().toAbsolutePath();

        OutputAnalyzer output = ExecuteHelper.jfr("print", "--xml", "--stack-depth", "9999", recordingFile.toString());
        System.out.println(recordingFile);
        String xml = output.getStdout();

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File(System.getProperty("test.src"), "jfr.xsd"));

        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setSchema(schema);
        factory.setNamespaceAware(true);

        SAXParser sp = factory.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        RecordingHandler handler = new RecordingHandler();
        xr.setContentHandler(handler);
        xr.setErrorHandler(handler);
        xr.parse(new InputSource(new StringReader(xml)));

        // Verify that all data was written correctly
        List<RecordedEvent> events = RecordingFile.readAllEvents(recordingFile);
        Collections.sort(events, (e1, e2) -> e1.getEndTime().compareTo(e2.getEndTime()));
        Iterator<RecordedEvent> it = events.iterator();
        for (XMLEvent xmlEvent : handler.events) {
            RecordedEvent re = it.next();
            if (!compare(re, xmlEvent.values)) {
                System.out.println("Expected:");
                System.out.println("----------------------");
                System.out.println(re);
                System.out.println();
                System.out.println("Was (XML)");
                System.out.println("----------------------");
                System.out.println(xmlEvent);
                System.out.println();
                throw new Exception("Event doesn't match");
            }
        }

    }
 
Example 17
Source File: QuarkusLiquibaseConnectionProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void baseLiquibaseInitialization(KeycloakSession session) {
    resourceAccessor = new ClassLoaderResourceAccessor(getClass().getClassLoader());
    FastServiceLocator locator = (FastServiceLocator) ServiceLocator.getInstance();

    JpaConnectionProviderFactory jpaConnectionProvider = (JpaConnectionProviderFactory) session
            .getKeycloakSessionFactory().getProviderFactory(JpaConnectionProvider.class);

    // register our custom databases
    locator.register(new PostgresPlusDatabase());
    locator.register(new UpdatedMySqlDatabase());
    locator.register(new UpdatedMariaDBDatabase());
    
    // registers only the database we are using
    try (Connection connection = jpaConnectionProvider.getConnection()) {
        Database database = DatabaseFactory.getInstance()
                .findCorrectDatabaseImplementation(new JdbcConnection(connection));
        if (database.getDatabaseProductName().equals(MySQLDatabase.PRODUCT_NAME)) {
            // Adding CustomVarcharType for MySQL 8 and newer
            DataTypeFactory.getInstance().register(MySQL8VarcharType.class);
        } else if (database.getDatabaseProductName().equals(MariaDBDatabase.PRODUCT_NAME)) {
            // Adding CustomVarcharType for MySQL 8 and newer
            DataTypeFactory.getInstance().register(MySQL8VarcharType.class);
        }

        DatabaseFactory.getInstance().clearRegistry();
        locator.register(database);
    } catch (Exception cause) {
        throw new RuntimeException("Failed to configure Liquibase database", cause);
    }

    // disables XML validation
    for (ChangeLogParser parser : ChangeLogParserFactory.getInstance().getParsers()) {
        if (parser instanceof XMLChangeLogSAXParser) {
            Method getSaxParserFactory = null;
            try {
                getSaxParserFactory = XMLChangeLogSAXParser.class.getDeclaredMethod("getSaxParserFactory");
                getSaxParserFactory.setAccessible(true);
                SAXParserFactory saxParserFactory = (SAXParserFactory) getSaxParserFactory.invoke(parser);
                saxParserFactory.setValidating(false);
                saxParserFactory.setSchema(null);
            } catch (Exception e) {
                logger.warnf("Failed to disable liquibase XML validations");
            } finally {
                if (getSaxParserFactory != null) {
                    getSaxParserFactory.setAccessible(false);
                }
            }
        }
    }
}
 
Example 18
Source File: TestPrintXML.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... args) throws Throwable {

        Path recordingFile = ExecuteHelper.createProfilingRecording().toAbsolutePath();

        OutputAnalyzer output = ExecuteHelper.jfr("print", "--xml", "--stack-depth", "9999", recordingFile.toString());
        System.out.println(recordingFile);
        String xml = output.getStdout();

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File(System.getProperty("test.src"), "jfr.xsd"));

        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setSchema(schema);
        factory.setNamespaceAware(true);

        SAXParser sp = factory.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        RecordingHandler handler = new RecordingHandler();
        xr.setContentHandler(handler);
        xr.setErrorHandler(handler);
        xr.parse(new InputSource(new StringReader(xml)));

        // Verify that all data was written correctly
        List<RecordedEvent> events = RecordingFile.readAllEvents(recordingFile);
        Collections.sort(events, (e1, e2) -> e1.getEndTime().compareTo(e2.getEndTime()));
        Iterator<RecordedEvent> it = events.iterator();
        for (XMLEvent xmlEvent : handler.events) {
            RecordedEvent re = it.next();
            if (!compare(re, xmlEvent.values)) {
                System.out.println("Expected:");
                System.out.println("----------------------");
                System.out.println(re);
                System.out.println();
                System.out.println("Was (XML)");
                System.out.println("----------------------");
                System.out.println(xmlEvent);
                System.out.println();
                throw new Exception("Event doesn't match");
            }
        }

    }