Example usage for javax.xml.validation SchemaFactory newSchema

List of usage examples for javax.xml.validation SchemaFactory newSchema

Introduction

In this page you can find the example usage for javax.xml.validation SchemaFactory newSchema.

Prototype

public abstract Schema newSchema(Source[] schemas) throws SAXException;

Source Link

Document

Parses the specified source(s) as a schema and returns it as a schema.

Usage

From source file:nl.armatiek.xslweb.configuration.WebApp.java

public Schema trySchemaCache(Collection<String> schemaPaths, ErrorListener errorListener) throws Exception {
    String key = StringUtils.join(schemaPaths, ";");
    Schema schema = schemaCache.get(key);
    if (schema == null) {
        logger.info("Compiling and caching schema(s) \"" + key + "\" ...");
        try {// w w w. ja v a  2 s .  c  o  m
            ArrayList<Source> schemaSources = new ArrayList<Source>();
            for (String path : schemaPaths) {
                File file = new File(path);
                if (!file.isFile()) {
                    throw new FileNotFoundException(
                            "XML Schema file \"" + file.getAbsolutePath() + "\" not found");
                }
                schemaSources.add(new StreamSource(file));
            }
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setErrorHandler(new ValidatorErrorHandler("Schema file(s)"));
            schema = schemaFactory.newSchema(schemaSources.toArray(new Source[schemaSources.size()]));
        } catch (Exception e) {
            logger.error("Error compiling schema(s) \"" + key + "\"", e);
            throw e;
        }
        if (!developmentMode) {
            schemaCache.put(key, schema);
        }
    }
    return schema;
}

From source file:org.eclipse.winery.repository.client.WineryRepositoryClient.java

/**
 * @param useProxy if a debugging proxy should be used
 *
 * @throws IllegalStateException if DOM parser could not be created
 *///w ww.j  av a 2 s  .  c  o m
public WineryRepositoryClient(boolean useProxy) {
    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getClasses().add(JacksonJsonProvider.class);
    if (useProxy) {
        URLConnectionClientHandler ch = new URLConnectionClientHandler(new ConnectionFactory());
        this.client = new Client(ch, clientConfig);
    } else {
        this.client = Client.create(clientConfig);
    }

    this.entityTypeDataCache = new HashMap<>();
    this.nameCache = new HashMap<>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    if (WineryRepositoryClient.VALIDATING) {
        factory.setValidating(true);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema;
        URL resource = this.getClass().getResource("/TOSCA-v1.0.xsd");
        try {
            schema = schemaFactory.newSchema(resource);
        } catch (SAXException e) {
            throw new IllegalStateException("Schema could not be initalized", e);
        }
        factory.setSchema(schema);
    }
    try {
        this.toscaDocumentBuilder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException("document builder could not be initalized", e);
    }
    /*
     TODO: include this somehow - in the case of VALIDATING
            
     Does not work with TTopolgoyTemplate as this is not allowed in the root of an XML document
    this.toscaDocumentBuilder.setErrorHandler(new ErrorHandler() {
            
       @Override
       public void warning(SAXParseException arg0) throws SAXException {
    throw arg0;
       }
            
       @Override
       public void fatalError(SAXParseException arg0) throws SAXException {
    throw arg0;
       }
            
       @Override
       public void error(SAXParseException arg0) throws SAXException {
    throw arg0;
       }
    });
    */
}

From source file:com.netxforge.oss2.core.xml.JaxbUtils.java

private static Schema getValidatorFor(final Class<?> origClazz) {
    final Class<?> clazz = (Class<?>) (origClazz instanceof Class<?> ? origClazz : origClazz.getClass());
    LogUtils.tracef(clazz, "finding XSD for class %s", clazz);

    if (m_schemas.containsKey(clazz)) {
        return m_schemas.get(clazz);
    }/*w ww .  jav a 2  s . c  o m*/

    final ValidateUsing schemaFileAnnotation = clazz.getAnnotation(ValidateUsing.class);
    if (schemaFileAnnotation == null || schemaFileAnnotation.value() == null) {
        return null;
    }

    final String schemaFileName = schemaFileAnnotation.value();
    InputStream schemaInputStream = null;
    try {
        final SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        if (schemaInputStream == null) {
            final File schemaFile = new File(
                    System.getProperty("opennms.home") + "/share/xsds/" + schemaFileName);
            if (schemaFile.exists()) {
                LogUtils.tracef(clazz, "using file %s", schemaFile);
                schemaInputStream = new FileInputStream(schemaFile);
            }
            ;
        }
        if (schemaInputStream == null) {
            final File schemaFile = new File("target/xsds/" + schemaFileName);
            if (schemaFile.exists()) {
                LogUtils.tracef(clazz, "using file %s", schemaFile);
                schemaInputStream = new FileInputStream(schemaFile);
            }
            ;
        }
        if (schemaInputStream == null) {
            final URL schemaResource = Thread.currentThread().getContextClassLoader()
                    .getResource("xsds/" + schemaFileName);
            if (schemaResource == null) {
                LogUtils.debugf(clazz, "Unable to load resource xsds/%s from the classpath.", schemaFileName);
            } else {
                LogUtils.tracef(clazz, "using resource %s from classpath", schemaResource);
                schemaInputStream = schemaResource.openStream();
            }
        }
        if (schemaInputStream == null) {
            LogUtils.tracef(clazz, "Did not find a suitable XSD.  Skipping.");
            return null;
        }
        final Schema schema = factory.newSchema(new StreamSource(schemaInputStream));
        m_schemas.put(clazz, schema);
        return schema;
    } catch (final Throwable t) {
        LogUtils.warnf(clazz, t, "an error occurred while attempting to load %s for validation",
                schemaFileName);
        return null;
    } finally {
        IOUtils.closeQuietly(schemaInputStream);
    }
}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Loads the schema for the {@link Entity} class.
 *
 * @param schemaFile the path to the schema file
 *
 * @return the loaded schema//  ww w .j av  a 2  s. co m
 *
 * @throws SAXException if any error occurs during loading the schema
 */
private Schema loadSchema(String schemaFile) throws SAXException {

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

    return schemaFactory.newSchema(getClass().getResource(schemaFile));
}

From source file:eu.europa.ec.fisheries.uvms.rules.service.bean.RulesMessageServiceBean.java

private Schema getSchemaForXsd(String xsdLocation) throws SAXException {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL resource = getClass().getClassLoader().getResource(xsdLocation);
    return sf.newSchema(resource);
}

From source file:integration.AbstractTest.java

/**
 * Parses the specified file and returns the document.
 * /*from  w w w.  j  a  v a  2  s . c  o  m*/
 * @param file The file to parse.
 * @param schemaStreamArray The schema as array of stream sources used to validate the specified file.
 * @return
 * @throws Exception Thrown if an error occurred.
 */
protected Document parseFileWithStreamArray(File file, StreamSource[] schemaStreamArray) throws Exception {
    if (file == null)
        throw new IllegalArgumentException("No file to parse.");

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true); // This must be set to avoid error : cvc-elt.1: Cannot find the declaration of element 'OME'.
    SchemaFactory sFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SchemaResolver theTestClassResolver = new SchemaResolver();
    sFactory.setResourceResolver(theTestClassResolver);

    Schema theSchema = sFactory.newSchema(schemaStreamArray);

    /*
    // Version - one step parse and validate (print error to stdErr)
    dbf.setSchema(theSchema);
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document theDoc = builder.parse(file);
    */

    // Version - two step parse then validate (throws error as exception)
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document theDoc = builder.parse(file);
    Validator validator = theSchema.newValidator();
    validator.validate(new DOMSource(theDoc));
    return theDoc;
}

From source file:com.thoughtworks.go.config.MagicalGoConfigXmlWriterTest.java

@Test
public void shouldBeAValidXSD() throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    factory.newSchema(new StreamSource(getClass().getResourceAsStream("/cruise-config.xsd")));
}

From source file:fll.scheduler.TournamentSchedule.java

/**
 * Validate the schedule XML document./*ww w  .  ja  v a 2  s .co m*/
 * 
 * @throws SAXException on an error
 */
public static void validateXML(final org.w3c.dom.Document document) throws SAXException {
    try {
        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Source schemaFile = new StreamSource(
                classLoader.getResourceAsStream("fll/resources/schedule.xsd"));
        final Schema schema = factory.newSchema(schemaFile);

        final Validator validator = schema.newValidator();
        validator.validate(new DOMSource(document));
    } catch (final IOException e) {
        throw new RuntimeException("Internal error, should never get IOException here", e);
    }

}

From source file:org.keycloak.testsuite.adapter.servlet.AbstractSAMLServletsAdapterTest.java

private void validateXMLWithSchema(String xml, String schemaFileName) throws SAXException, IOException {
    URL schemaFile = getClass().getResource(schemaFileName);

    Source xmlFile = new StreamSource(new ByteArrayInputStream(xml.getBytes()), xml);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    try {//  www. j a  v a2s .com
        validator.validate(xmlFile);
        System.out.println(xmlFile.getSystemId() + " is valid");
    } catch (SAXException e) {
        System.out.println(xmlFile.getSystemId() + " is NOT valid");
        System.out.println("Reason: " + e.getLocalizedMessage());
        Assert.fail();
    }
}

From source file:edu.unc.lib.dl.ingest.sip.METSPackageSIPProcessor.java

private void xsdValidate(File metsFile2) throws IngestException {
    // TODO can reuse schema object, it is thread safe
    javax.xml.validation.SchemaFactory schemaFactory = javax.xml.validation.SchemaFactory
            .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    StreamSource xml = new StreamSource(getClass().getResourceAsStream(schemaPackage + "xml.xsd"));
    StreamSource xlink = new StreamSource(getClass().getResourceAsStream(schemaPackage + "xlink.xsd"));
    StreamSource mets = new StreamSource(getClass().getResourceAsStream(schemaPackage + "mets.xsd"));
    StreamSource premis = new StreamSource(getClass().getResourceAsStream(schemaPackage + "premis-v2-0.xsd"));
    StreamSource mods = new StreamSource(getClass().getResourceAsStream(schemaPackage + "mods-3-4.xsd"));
    StreamSource acl = new StreamSource(getClass().getResourceAsStream(schemaPackage + "acl.xsd"));
    Schema schema;/*w ww . j a  va  2  s  .c om*/
    try {
        Source[] sources = { xml, xlink, mets, premis, mods, acl };
        schema = schemaFactory.newSchema(sources);
    } catch (SAXException e) {
        throw new Error("Cannot locate METS schema in classpath.", e);
    }

    Validator metsValidator = schema.newValidator();
    METSParseException handler = new METSParseException("There was a problem parsing METS XML.");
    metsValidator.setErrorHandler(handler);
    // TODO get a Result document for reporting error
    try {
        metsValidator.validate(new StreamSource(metsFile2));
    } catch (SAXException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        }
        throw handler;
    } catch (IOException e) {
        throw new IngestException("The supplied METS file is not readable.", e);
    }
}