Example usage for javax.xml.validation SchemaFactory newInstance

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

Introduction

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

Prototype

public static SchemaFactory newInstance(String schemaLanguage) 

Source Link

Document

Lookup an implementation of the SchemaFactory that supports the specified schema language and return it.

Usage

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();
    }//  w  w  w.j av a  2s. 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.
 *//* ww  w  .  j a v a2s  .  com*/
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  ww  .ja  v a 2 s.  com*/
        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;
}

From source file:org.sejda.core.context.XmlConfigurationStrategy.java

private void initializeSchemaValidation(DocumentBuilderFactory factory) throws SAXException {
    if (Boolean.getBoolean(Sejda.PERFORM_SCHEMA_VALIDATION_PROPERTY_NAME)) {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource(
                Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_SEJDA_CONFIG)) }));

        factory.setNamespaceAware(true);
    }//w ww.jav a  2s  . c  o m
}

From source file:org.silverpeas.core.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 JAXB
 * @return Un objet SilverPeasExchangeType contenant le mapping d'un fichier XML
 * @throws ImportExportException//w  ww .ja  v a  2 s.  c  o m
 */
private SilverPeasExchangeType loadSilverpeasExchange(String xmlFileName) throws ImportExportException {
    try {
        File xmlInputSource = new File(xmlFileName);
        String xsdSystemId = settings.getString("xsdDefaultSystemId");

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new URL(xsdSystemId));

        // Unmarshall the import model
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new ImportExportErrorHandler());
        SilverPeasExchangeType silverpeasExchange = (SilverPeasExchangeType) unmarshaller
                .unmarshal(xmlInputSource);

        return silverpeasExchange;

    } catch (JAXBException me) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange",
                "importExport.EX_UNMARSHALLING_FAILED",
                "XML Filename " + xmlFileName + ": " + me.getLocalizedMessage(), me);
    } catch (MalformedURLException ue) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange",
                "importExport.EX_UNMARSHALLING_FAILED",
                "XML Filename " + xmlFileName + ": " + ue.getLocalizedMessage(), ue);
    } catch (SAXException ve) {
        throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED",
                "XML Filename " + xmlFileName + ": " + ve.getLocalizedMessage(), ve);
    }
}

From source file:org.slc.sli.ingestion.parser.impl.EdfiRecordParserImpl.java

private static Schema initializeSchema(Resource schemaResource) throws XmlParseException {
    Schema schema;/*from   www .j  a v  a  2s . co  m*/
    try {
        schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(schemaResource.getURL());
    } catch (SAXException e) {
        throw new XmlParseException("Exception while initializing XSD schema", e);
    } catch (IOException e) {
        throw new XmlParseException("Exception while accessing XSD schema file", e);
    }
    return schema;
}

From source file:org.slc.sli.ingestion.parser.impl.EdfiRecordParserImpl2.java

public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider,
        RecordVisitor visitor) throws SAXException, IOException, XmlParseException {

    EdfiRecordParserImpl2 parser = new EdfiRecordParserImpl2();

    parser.addVisitor(visitor);/*from   w  w  w .jav a 2s. c o m*/
    parser.typeProvider = typeProvider;

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

    Schema schema = schemaFactory.newSchema(schemaResource.getURL());

    parser.parseAndValidate(input, schema);
}

From source file:org.sonar.plugins.xml.checks.XmlSchemaCheck.java

/**
 * Create xsd schema for a list of schema's.
 *///from   w ww  .  j  ava 2 s  .c o  m
private static Schema createSchema(String[] schemaList) {

    final String cacheKey = StringUtils.join(schemaList, ",");
    // first try to load a cached schema.
    Schema schema = cachedSchemas.get(cacheKey);
    if (schema != null) {
        return schema;
    }

    List<Source> schemaSources = new ArrayList<Source>();

    // load each schema in a StreamSource.
    for (String schemaReference : schemaList) {
        InputStream input = SchemaResolver.getBuiltinSchema(schemaReference);
        if (input == null) {
            throw new SonarException("Could not load schema: " + schemaReference);
        }
        schemaSources.add(new StreamSource(input));
    }

    // create a schema for the list of StreamSources.
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setResourceResolver(new SchemaResolver());

        schema = schemaFactory.newSchema(schemaSources.toArray(new Source[schemaSources.size()]));
        cachedSchemas.put(cacheKey, schema);
        return schema;
    } catch (SAXException e) {
        throw new SonarException(e);
    }
}

From source file:org.springframework.oxm.jaxb.Jaxb2Marshaller.java

@SuppressWarnings("deprecation") // on JDK 9
private Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException {
    if (logger.isDebugEnabled()) {
        logger.debug("Setting validation schema to "
                + StringUtils.arrayToCommaDelimitedString(this.schemaResources));
    }//from   w ww .  ja  va2  s  . com
    Assert.notEmpty(resources, "No resources given");
    Assert.hasLength(schemaLanguage, "No schema language provided");
    Source[] schemaSources = new Source[resources.length];
    XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
    xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    for (int i = 0; i < resources.length; i++) {
        Assert.notNull(resources[i], "Resource is null");
        Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist");
        InputSource inputSource = SaxResourceUtils.createInputSource(resources[i]);
        schemaSources[i] = new SAXSource(xmlReader, inputSource);
    }
    SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
    if (this.schemaResourceResolver != null) {
        schemaFactory.setResourceResolver(this.schemaResourceResolver);
    }
    return schemaFactory.newSchema(schemaSources);
}

From source file:org.sweble.wikitext.dumpreader.DumpReader.java

private void setSchema(URL schemaUrl) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);

    sf.setResourceResolver(new LSResourceResolverImplementation());

    Schema schema = sf.newSchema(schemaUrl);

    unmarshaller.setSchema(schema);// ww  w.j  a  va 2  s . co  m

    unmarshaller.setEventHandler(new ValidationEventHandler() {
        public boolean handleEvent(ValidationEvent ve) {
            try {
                return DumpReader.this.handleEvent(ve, ve.getLocator());
            } catch (RuntimeException e) {
                throw e;
            } catch (Exception e) {
                throw new WrappedException(e);
            }
        }
    });
}