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:org.perfclipse.core.scenario.ScenarioManager.java

/**
 * The createXML method converts scenario model into XML representation 
 * according to PerfCake XML Schema and writes output to output stream out
 * @param model model to be converted//from  ww  w  . j a v a  2  s . co m
 * @param out OutputStream to which xml will be written
 * @throws ScenarioException
 */
public void createXML(org.perfcake.model.Scenario model, OutputStream out) throws ScenarioException {
    try {
        JAXBContext context = JAXBContext.newInstance(org.perfcake.model.Scenario.class);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        //obtain url to schema definition, which is located somewhere in PerfCakeBundle
        URL schemaUrl = SchemaScanner.getSchema();
        Schema schema = schemaFactory.newSchema(schemaUrl);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setSchema(schema);

        //add line breaks and indentation into output
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(model, out);
    } catch (JAXBException e) {
        log.error("JAXB error", e);
        throw new ScenarioException("JAXB error", e);
    } catch (MalformedURLException e) {
        log.error("Malformed url", e);
        throw new ScenarioException("Malformed url", e);
    } catch (SAXException e) {
        log.error("Cannot obtain schema definition", e);
        throw new ScenarioException("Cannot obtain schema definition", e);
    } catch (IOException e) {
        log.error("Cannot obtain XML schema file", e);
        throw new ScenarioException("Cannot obtain XML schema file", e);
    }
}

From source file:org.plasma.common.bind.ValidatingUnmarshaler.java

private Unmarshaller createUnmarshaler(URL url, JAXBContext context) throws JAXBException, SAXException {
    Unmarshaller u = context.createUnmarshaller();
    // adds a custom object factory
    // u.setProperty("com.sun.xml.bind.ObjectFactory",new
    // ObjectFactoryEx());
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    Schema schemaGrammar = schemaFactory.newSchema(url);
    u.setSchema(schemaGrammar);//www.  j ava2  s .  com

    return u;
}

From source file:org.plasma.common.bind.ValidatingUnmarshaler.java

/**
 * Creates an unmarshaler using the given factories and sream. Loads only
 * the given (subclass) schema as this is the "root" schema and it should
 * include any other schema resources it needs, and so on. Note all included
 * schemas MUST be found at the same class level as the root schema.
 * /*w  ww  . j av a 2 s  .  c  om*/
 * @param stream
 *            the Schema stream
 * @param context
 *            the SAXB context
 * @param handler
 *            the SAX handler
 * @param resolver
 *            the SAX resolver
 * @return the unmarshaler
 * @throws JAXBException
 * @throws SAXException
 */
private Unmarshaller createUnmarshaler(InputStream[] streams, JAXBContext context, Handler handler,
        Resolver resolver) throws JAXBException, SAXException {
    Unmarshaller u = context.createUnmarshaller();
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    StreamSource[] sources = new StreamSource[streams.length];
    for (int i = 0; i < streams.length; i++) {
        sources[i] = new StreamSource(streams[i]);
        //FIXME: will not resolve relative URI's (included schemas) without this
        //sources[i].setSystemId(systemId)
    }
    Schema schemaGrammar = schemaFactory.newSchema(sources);
    u.setSchema(schemaGrammar);
    Validator schemaValidator = schemaGrammar.newValidator();
    schemaValidator.setResourceResolver(resolver);
    schemaValidator.setErrorHandler(handler);

    return u;
}

From source file:org.raml.parser.visitor.SchemaCompiler.java

public Schema compile(String schema, String path) {
    Schema compiledSchema = null;
    String trimmedSchema = StringUtils.trimToEmpty(schema);
    if (trimmedSchema.startsWith("<") && trimmedSchema.endsWith(">")) {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        ContextPath actualContextPath = contextPath;
        if (path != null) {
            actualContextPath = new ContextPath(new IncludeInfo(path));
        }/*from   w  w w  . ja va 2 s .c  o  m*/
        factory.setResourceResolver(new XsdResourceResolver(actualContextPath, resourceLoader));
        try {
            compiledSchema = factory.newSchema(new StreamSource(new StringReader(trimmedSchema)));
        } catch (Exception e) {
            //ignore exception as the error is detected by the validator
            // and here we cannot tell if the schema is intended for xml or not
        }
    }
    return compiledSchema;
}

From source file:org.rhq.enterprise.server.xmlschema.ServerPluginDescriptorUtil.java

/**
 * This will return a JAXB unmarshaller that will enable the caller to parse a server plugin
 * descriptor. The returned unmarshaller will have a {@link ValidationEventCollector}
 * installed as an {@link Unmarshaller#getEventHandler() event handler} which can be used
 * to obtain error messages if the unmarshaller fails to parse an XML document.
 * /*from   ww w  .  j  a  v a 2  s. c  o m*/
 * @return a JAXB unmarshaller enabling the caller to parse server plugin descriptors
 * 
 * @throws Exception if an unmarshaller could not be created
 */
public static Unmarshaller getServerPluginDescriptorUnmarshaller() throws Exception {

    // create the JAXB context with all the generated plugin packages in it
    JAXBContext jaxbContext;
    try {
        jaxbContext = JAXBContext.newInstance(PLUGIN_CONTEXT_PATH);
    } catch (Exception e) {
        throw new Exception("Failed to create JAXB Context.", e);
    }

    // create the unmarshaller that can be used to parse XML documents containing server plugin descriptors
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    // enable schema validation to ensure the XML documents parsed by the unmarshaller are valid descriptors
    ClassLoader cl = ServerPluginDescriptorUtil.class.getClassLoader();
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    StreamSource[] schemaSources = new StreamSource[PLUGIN_SCHEMA_PACKAGES.size()];
    int i = 0;
    for (String schemaPath : PLUGIN_SCHEMA_PACKAGES.keySet()) {
        URL schemaURL = cl.getResource(schemaPath);
        schemaSources[i++] = new StreamSource(schemaURL.toExternalForm());
    }

    Schema pluginSchema = schemaFactory.newSchema(schemaSources);
    unmarshaller.setSchema(pluginSchema);

    ValidationEventCollector vec = new ValidationEventCollector();
    unmarshaller.setEventHandler(vec);

    return unmarshaller;
}

From source file:org.rimudb.configuration.AbstractXmlLoader.java

/**
 * @param document/*w ww  . j  av a  2 s  . co  m*/
 * @param compoundDbSchemaUrl
 * @return SAXParseException
 * @throws Exception 
 */
protected SAXParseException validate(Document document, String compoundDbSchemaUrl) throws Exception {
    // Compile a schema for the XSD
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // Look up the schema URL and find it's local resource file 
    URL schemaURL = null;
    String schemaPath = RimuDBNamespace.lookupInternalSchema(compoundDbSchemaUrl);
    if (schemaPath != null) {
        schemaURL = getClass().getClassLoader().getResource(schemaPath);
    } else {
        schemaURL = new URL(compoundDbSchemaUrl);
    }

    Schema schema = schemaFactory.newSchema(schemaURL);

    // Validate the document against the schema
    Validator validator = schema.newValidator();
    validator.setErrorHandler(new StrictErrorHandler());
    try {
        validator.validate(new DOMSource(document), new DOMResult());
    } catch (SAXParseException e) {
        return e;
    }

    return null;
}

From source file:org.roda.core.common.PremisV3Utils.java

public static boolean isPremisV2(Binary binary) throws IOException, SAXException {
    boolean premisV2 = true;
    InputStream inputStream = binary.getContent().createInputStream();
    InputStream schemaStream = RodaCoreFactory.getConfigurationFileAsStream("schemas/premis-v2-0.xsd");
    Source xmlFile = new StreamSource(inputStream);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream));
    Validator validator = schema.newValidator();
    RodaErrorHandler errorHandler = new RodaErrorHandler();
    validator.setErrorHandler(errorHandler);
    try {//w w w  .ja v a  2 s  .  c o  m
        validator.validate(xmlFile);
        List<SAXParseException> errors = errorHandler.getErrors();
        if (!errors.isEmpty()) {
            premisV2 = false;
        }
    } catch (SAXException e) {
        premisV2 = false;
    }
    IOUtils.closeQuietly(inputStream);
    IOUtils.closeQuietly(schemaStream);
    return premisV2;
}

From source file:org.roda.core.SchemasCacheLoader.java

@Override
public Optional<Schema> load(Pair<String, String> pair) throws Exception {
    String metadataType = pair.getFirst();
    String metadataTypeLowerCase = metadataType.toLowerCase();
    String metadataVersion = pair.getSecond();
    String metadataVersionLowerCase = "";
    if (metadataVersion != null) {
        metadataVersionLowerCase = metadataVersion.toLowerCase();
    }//www.  j ava2s. c  om

    String schemaFileName;
    if (StringUtils.isNotEmpty(metadataVersion)) {
        schemaFileName = metadataTypeLowerCase + RodaConstants.METADATA_VERSION_SEPARATOR
                + metadataVersionLowerCase + ".xsd";
    } else {
        schemaFileName = metadataTypeLowerCase + ".xsd";
    }

    String schemaPath = RodaConstants.CORE_SCHEMAS_FOLDER + "/" + schemaFileName;

    InputStream schemaStream = RodaCoreFactory.getConfigurationFileAsStream(schemaPath);

    Schema xmlSchema = null;
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(RodaConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setResourceResolver(new ResourceResolver());
        xmlSchema = schemaFactory.newSchema(new StreamSource(schemaStream));
    } finally {
        RodaUtils.closeQuietly(schemaStream);
    }

    return Optional.ofNullable(xmlSchema);
}

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.
 *//*from  w  w w . j  ava2s.  co 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.sakaiproject.tool.assessment.qti.helper.AuthoringHelper.java

private boolean validateImportXml(Document doc) throws SAXException, IOException {
    // 1. Lookup a factory for the W3C XML Schema language
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    // 2. Compile the schema.
    // Here the schema is loaded from a java.io.File, but you could use
    // a java.net.URL or a javax.xml.transform.Source instead.
    String schemaFile = VALIDATE_XSD_PATH + "qtiv1p2.xsd";
    log.debug("schemaFile = " + schemaFile);
    Schema schema = factory.newSchema(
            new StreamSource(AuthoringHelper.class.getClassLoader().getResourceAsStream(schemaFile)));

    // 3. Get a validator from the schema.
    Validator validator = schema.newValidator();

    // 4. Parse the document you want to check.
    Source source = new DOMSource(doc);

    // 5. Check the document
    try {/*from  w w w  .  j ava2  s  . c  o m*/
        validator.validate(source);
        log.debug("The xml is valid.");
        return true;
    } catch (SAXException ex) {
        log.debug("The xml is not valid QTI format.", ex);
    }
    return false;
}