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:gov.nih.nci.ncicb.tcga.dcc.common.util.BCRXMLFileReader.java

private void processXML(final InputStream in) throws SAXException, ParserConfigurationException, IOException {
    // Some of the following code is nabbed from http://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi.html
    final SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    final File schemaLocation = bcrXSD;
    final Schema schema;
    schema = factory.newSchema(schemaLocation);
    final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true); // never forget this
    final DocumentBuilder builder = domFactory.newDocumentBuilder();
    document = builder.parse(in);//  ww  w  .  j av  a2 s . co m
    final DOMSource source = new DOMSource(document);
    final Validator validator = schema.newValidator();
    //Check to see if we actually want to validate docs or just skip.
    if (isValidate()) {
        validator.validate(source);
    }
}

From source file:org.raml.parser.rule.SchemaRule.java

@Override
public List<ValidationResult> doValidateValue(ScalarNode node) {
    String value = node.getValue();
    List<ValidationResult> validationResults = super.doValidateValue(node);

    IncludeInfo globaSchemaIncludeInfo = null;
    ScalarNode schemaNode = getGlobalSchemaNode(value);
    if (schemaNode == null) {
        schemaNode = node;//from   w w w.ja v a  2s. co m
    } else {
        value = schemaNode.getValue();
        if (schemaNode.getTag().startsWith(INCLUDE_APPLIED_TAG)) {
            globaSchemaIncludeInfo = new IncludeInfo(schemaNode.getTag());
        }
    }
    if (value == null || isCustomTag(schemaNode.getTag())) {
        return validationResults;
    }

    String mimeType = ((ScalarNode) getParentTupleRule().getKey()).getValue();
    if (mimeType.contains("json")) {
        try {
            JsonNode jsonNode = JsonLoader.fromString(value);
            ProcessingReport report = VALIDATOR.validateSchema(jsonNode);
            if (!report.isSuccess()) {
                StringBuilder msg = new StringBuilder("invalid JSON schema");
                msg.append(getSourceErrorDetail(node));
                for (ProcessingMessage processingMessage : report) {
                    msg.append("\n").append(processingMessage.toString());
                }
                validationResults
                        .add(getErrorResult(msg.toString(), getLineOffset(schemaNode), globaSchemaIncludeInfo));
            }
        } catch (JsonParseException jpe) {
            String msg = "invalid JSON schema" + getSourceErrorDetail(node) + jpe.getOriginalMessage();
            JsonLocation loc = jpe.getLocation();
            validationResults.add(
                    getErrorResult(msg, getLineOffset(schemaNode) + loc.getLineNr(), globaSchemaIncludeInfo));
        } catch (IOException e) {
            String prefix = "invalid JSON schema" + getSourceErrorDetail(node);
            validationResults.add(getErrorResult(prefix + e.getMessage(), UNKNOWN, globaSchemaIncludeInfo));
        }
    } else if (mimeType.contains("xml")) {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {
            factory.newSchema(new StreamSource(new StringReader(value)));
        } catch (SAXParseException e) {
            String msg = "invalid XML schema" + getSourceErrorDetail(node) + e.getMessage();
            validationResults.add(
                    getErrorResult(msg, getLineOffset(schemaNode) + e.getLineNumber(), globaSchemaIncludeInfo));
        } catch (SAXException e) {
            String msg = "invalid XML schema" + getSourceErrorDetail(node);
            validationResults.add(getErrorResult(msg, getLineOffset(schemaNode), globaSchemaIncludeInfo));
        }
    }
    return validationResults;
}

From source file:org.ff4j.console.conf.XmlConfigurationParser.java

/**
 * Mthode permettant de crer le Unmarshaller pour le parsing du XML.
 * @param modelPackage/*from w w w .j  a v  a  2 s .  c o  m*/
 *            nom du package qui contient les beans utilises pour le parsing du fichier.
 * @param schemafile
 *            le fichier XSD pour la validation du XML.
 * @return Unmarshaller
 * @throws JAXBException
 * @throws SAXException
 */
public Unmarshaller getUnmarshaller(String modelPackage, File schemafile) throws JAXBException, SAXException {
    JAXBContext jc = JAXBContext.newInstance(modelPackage);
    SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(schemafile);
    Unmarshaller u = jc.createUnmarshaller();
    u.setSchema(schema);
    u.setEventHandler(new XmlConfigurationErrorHandler());
    return u;
}

From source file:org.ff4j.console.conf.XmlConfigurationParser.java

/**
 * Mthode permettant de crer le Unmarshaller pour le parsing du XML.
 * @param modelPackage/*from  w ww . j ava2s  .  c o m*/
 *            nom du package qui contient les beans utilises pour le parsing du fichier.
 * @param schemafile
 *            le fichier XSD pour la validation du XML.
 * @return Unmarshaller
 * @throws JAXBException
 * @throws SAXException
 */
public Unmarshaller getUnmarshaller(String modelPackage, InputStream schemaStream)
        throws JAXBException, SAXException {
    JAXBContext jc = JAXBContext.newInstance(modelPackage);
    SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new StreamSource(schemaStream));
    Unmarshaller u = jc.createUnmarshaller();
    u.setSchema(schema);
    u.setEventHandler(new XmlConfigurationErrorHandler());
    return u;
}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Validates given XML file against an XSD schema
 *
 * @param file/*ww  w  .jav a  2 s  .  c o m*/
 * @param xsd
 * @return
 */
public static List<String> validateAgainstXSD(File file, InputStream xsd) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setResourceResolver(MetsLSResolver.getInstance());
    Schema schema = factory.newSchema(new StreamSource(xsd));
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setValidating(false);
    dbfactory.setNamespaceAware(true);
    dbfactory.setSchema(schema);
    DocumentBuilder documentBuilder = dbfactory.newDocumentBuilder();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler();
    documentBuilder.setErrorHandler(errorHandler);
    documentBuilder.parse(file);
    return errorHandler.getValidationErrors();
}

From source file:mx.bigdata.cfdi.TFDv1.java

public void validate(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(getClass().getResource(XSD));
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }/*from w w  w. j a v a 2  s .  c o m*/
    validator.validate(new JAXBSource(CONTEXT, tfd));
}

From source file:com.edmunds.etm.common.xml.XmlValidator.java

/**
 * Creates schema factory, opens schema file and initializes schema rulesConfigValidator.
 *
 * @param schemaFileName XSD schema file name.
 * @return validator object.// w  w  w . j  a  va  2  s.  com
 * @throws org.xml.sax.SAXException when parser error occurs.
 * @throws java.io.IOException      when IO error occurs.
 */
private Validator initValidator(String schemaFileName) throws SAXException, IOException {
    InputStream is = null;
    try {
        SchemaFactory factory = SchemaFactory.newInstance(W3_ORG_XMLSCHEMA);
        is = getClass().getResourceAsStream(schemaFileName);
        Source source = new StreamSource(is);
        Schema schema = factory.newSchema(source);
        return schema.newValidator();
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:ar.com.tadp.xml.rinzo.core.resources.validation.XMLStringValidator.java

private Validator createValidator(StreamSource[] sources) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    sf.setFeature("http://apache.org/xml/features/xinclude", true);
    Schema schema = sf.newSchema(sources);
    return schema.newValidator();
}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Validates given document agains an XSD schema
 *
 * @param document//from w w w . ja v  a 2s. c  o m
 * @param xsd
 * @return
 */
public static List<String> validateAgainstXSD(Document document, InputStream xsd) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setResourceResolver(MetsLSResolver.getInstance());
    Schema schema = factory.newSchema(new StreamSource(xsd));
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    DOMSource domSource = new DOMSource(document);
    StreamResult sResult = new StreamResult();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    sResult.setOutputStream(bos);
    transformer.transform(domSource, sResult);
    InputStream is = new ByteArrayInputStream(bos.toByteArray());
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setValidating(false);
    dbfactory.setNamespaceAware(true);
    dbfactory.setSchema(schema);
    DocumentBuilder documentBuilder = dbfactory.newDocumentBuilder();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler();
    documentBuilder.setErrorHandler(errorHandler);
    documentBuilder.parse(is);
    return errorHandler.getValidationErrors();
}

From source file:de.drv.dsrv.spoc.web.webservice.jax.ExtraSchemaValidationHandler.java

private void validateExtraRequest(final Node transportNode, final ServletContext servletContext)
        throws Exception {

    // Validator-Objekt mit eXTra-Schema als Basis erstellen
    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = factory.newSchema(servletContext.getResource(SCHEMA_PATH));
    final Validator validator = schema.newValidator();

    try {//w  ww . ja v  a  2 s.co m
        // Validiere Transport-Element gegen eXTra-Schema
        validator.validate(new DOMSource(transportNode));
    } catch (final SAXException e) {
        // Falls MTOM-Attachement, dann den Fehler bzgl. cid-Referenz
        // ignorieren
        if (!(e.getMessage().contains("cid:") && e.getMessage().contains("'base64Binary'"))) {
            LOG.warn("Fehler bei der XML-Validierung: " + e.getMessage());
            throw new InvalidExtraRequestException(e.getMessage());
        }
    }
}