Example usage for javax.xml.validation Schema newValidator

List of usage examples for javax.xml.validation Schema newValidator

Introduction

In this page you can find the example usage for javax.xml.validation Schema newValidator.

Prototype

public abstract Validator newValidator();

Source Link

Document

Creates a new Validator for this Schema .

Usage

From source file:eu.planets_project.tb.gui.backing.exp.utils.ExpTypeWeeUtils.java

private void checkValidXMLConfig(InputStream xmlWFConfig) throws Exception {
    InputStream bis = getClass().getClassLoader().getResourceAsStream("planets_wdt.xsd");
    try {/*from w w w .ja  v a 2  s . c o  m*/
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(bis));
        Validator validator = schema.newValidator();
        // Validate file against schema
        XMLOutputter outputter = new XMLOutputter();
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(xmlWFConfig);
        validator.validate(new StreamSource(new StringReader(outputter.outputString(doc.getRootElement()))));
    } catch (Exception e) {
        String err = "The provided xmlWFConfig is not valid against the currently used planets_wdt_xsd schema";
        log.debug(err, e);
        throw new Exception(err, e);
    } finally {
        bis.close();
    }
}

From source file:be.fedict.eid.dss.document.xml.XMLDSSDocumentService.java

public void checkIncomingDocument(byte[] document) throws Exception {

    LOG.debug("checking incoming document");
    ByteArrayInputStream documentInputStream = new ByteArrayInputStream(document);
    Document dom = this.documentBuilder.parse(documentInputStream);

    String namespace = dom.getDocumentElement().getNamespaceURI();
    if (null == namespace) {
        LOG.debug("no namespace defined");
        return;// www  . ja  v  a2s. co m
    }

    byte[] xsd = this.context.getXmlSchema(namespace);
    if (null == xsd) {
        LOG.debug("no XML schema available for namespace: " + namespace);
        return;
    }

    LOG.debug("validating against XML schema: " + namespace);
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    schemaFactory.setResourceResolver(new SignatureServiceLSResourceResolver(this.context));
    StreamSource schemaSource = new StreamSource(new ByteArrayInputStream(xsd));
    Schema schema = schemaFactory.newSchema(schemaSource);
    Validator validator = schema.newValidator();
    DOMSource domSource = new DOMSource(dom);
    validator.validate(domSource);
}

From source file:org.motechproject.mobile.web.ivr.intellivr.IntellIVRController.java

public void init() {
    Resource schemaResource = resourceLoader.getResource("classpath:intellivr-in.xsd");
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    try {/* www  .j  av  a 2s  .  c  o  m*/
        Schema schema = factory.newSchema(schemaResource.getFile());
        parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        validator = schema.newValidator();
    } catch (SAXException e) {
        log.error("Error initializing controller:", e);
    } catch (IOException e) {
        log.error("Error initializing controller:", e);
    } catch (ParserConfigurationException e) {
        log.error("Error initializing controller:", e);
    } catch (FactoryConfigurationError e) {
        log.error("Error initializing controller:", e);
    }
    try {
        JAXBContext jaxbc = JAXBContext.newInstance("org.motechproject.mobile.omp.manager.intellivr");
        marshaller = jaxbc.createMarshaller();
        unmarshaller = jaxbc.createUnmarshaller();
    } catch (JAXBException e) {
        log.error("Error initializing controller:", e);
    }
}

From source file:com.amalto.core.schema.validation.XmlSchemaValidator.java

private javax.xml.validation.Validator getValidator() {
    javax.xml.validation.Validator validator;
    synchronized (schemaCache) {
        try {/*from   w  w w . j  a  v  a 2s .  co  m*/
            validator = (javax.xml.validation.Validator) validatorCache.get(dataModelName,
                    Thread.currentThread());
            if (validator != null) {
                return validator;
            }
            Schema parsedSchema = schemaCache.get(dataModelName);
            if (parsedSchema == null) {
                parsedSchema = schemaFactory.newSchema(new StreamSource(schemaAsStream));
                schemaCache.put(dataModelName, parsedSchema);
            }
            validator = parsedSchema.newValidator();
            validatorCache.put(dataModelName, Thread.currentThread(), validator);
        } catch (SAXException e) {
            throw new RuntimeException("Exception occurred during XML schema parsing.", e);
        }
    }
    return validator;
}

From source file:cz.cas.lib.proarc.common.imports.TiffImporterTest.java

@Test
public void testConsume() throws Exception {
    temp.setDeleteOnExit(true);/*w  ww  .  j  a v  a  2  s.  co m*/
    File targetFolder = ImportProcess.createTargetFolder(temp.getRoot());
    assertTrue(targetFolder.exists());

    String mimetype = ImportProcess.findMimeType(tiff1);
    assertNotNull(mimetype);

    ImportOptions ctx = new ImportOptions(tiff1.getParentFile(), "scanner:scanner1", true, junit,
            config.getImportConfiguration());
    ctx.setTargetFolder(targetFolder);
    Batch batch = new Batch();
    batch.setId(1);
    batch.setFolder(ibm.relativizeBatchFile(tiff1.getParentFile()));
    ctx.setBatch(batch);
    FileSet fileSet = ImportFileScanner.getFileSets(Arrays.asList(tiff1, ocr1, alto1, ac1, uc1)).get(0);
    ctx.setJhoveContext(jhoveContext);

    TiffImporter instance = new TiffImporter(ibm);
    BatchItemObject result = instance.consume(fileSet, ctx);
    String pid = result.getPid();
    assertTrue(pid.startsWith("uuid"));

    assertEquals(ObjectState.LOADED, result.getState());

    File foxml = result.getFile();
    assertTrue(foxml.toString(), foxml.exists());

    File rootFoxml = new File(foxml.getParent(), ImportBatchManager.ROOT_ITEM_FILENAME);
    assertTrue(rootFoxml.toString(), rootFoxml.exists());

    File raw1 = new File(targetFolder, "img1.full.jpg");
    assertTrue(raw1.exists() && raw1.length() > 0);

    File preview1 = new File(targetFolder, "img1.preview.jpg");
    assertTrue(preview1.exists() && preview1.length() > 0);

    File thumb1 = new File(targetFolder, "img1.thumb.jpg");
    assertTrue(thumb1.exists() && thumb1.length() > 0);

    // validate FOXML
    SchemaFactory sfactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL foxmlXsdUrl = ObjectFactory.class.getResource("/xsd/foxml/foxml1-1.xsd");
    assertNotNull(foxmlXsdUrl);
    Schema foxmlXsd = sfactory.newSchema(foxmlXsdUrl);
    foxmlXsd.newValidator().validate(new StreamSource(foxml));

    // check datastreams with xpath
    HashMap<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("f", "info:fedora/fedora-system:def/foxml#");
    XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces));
    String foxmlSystemId = foxml.toURI().toASCIIString();
    XMLAssert.assertXpathExists(streamXPath(ModsStreamEditor.DATASTREAM_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(DcStreamEditor.DATASTREAM_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(StringEditor.OCR_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(AltoDatastream.ALTO_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(RelationEditor.DATASTREAM_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(BinaryEditor.FULL_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(BinaryEditor.PREVIEW_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(BinaryEditor.THUMB_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(BinaryEditor.RAW_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(MixEditor.RAW_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(BinaryEditor.NDK_ARCHIVAL_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(BinaryEditor.NDK_USER_ID), new InputSource(foxmlSystemId));
    XMLAssert.assertXpathExists(streamXPath(MixEditor.NDK_ARCHIVAL_ID), new InputSource(foxmlSystemId));

    String rootSystemId = rootFoxml.toURI().toASCIIString();
    XMLAssert.assertXpathExists(streamXPath(RelationEditor.DATASTREAM_ID), new InputSource(rootSystemId));
    EasyMock.verify(toVerify.toArray());
}

From source file:com.azaptree.services.spring.application.config.SpringApplicationServiceConfig.java

private SpringApplicationService parse(final InputStream xml) throws JAXBException {
    Assert.notNull(xml);/*  ww w .j ava2 s  .  c o m*/
    final JAXBContext jc = JAXBContext.newInstance(SpringApplicationService.class);
    final Unmarshaller u = jc.createUnmarshaller();
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final ByteArrayOutputStream bos = new ByteArrayOutputStream(512);
    generateSchema(bos);
    try {
        final SpringApplicationService springApplicationService = (SpringApplicationService) u.unmarshal(xml);
        final Schema schema = schemaFactory
                .newSchema(new StreamSource(new ByteArrayInputStream(bos.toByteArray())));
        final Validator validator = schema.newValidator();
        validator.validate(new JAXBSource(jc, springApplicationService));
        return springApplicationService;
    } catch (SAXException | IOException e) {
        throw new IllegalArgumentException(
                "Failed to parse XML. The XML must conform to the following schema:\n" + bos, e);
    }
}

From source file:de.fzi.ALERT.actor.MessageObserver.ComplexEventObserver.JMSMessageParser.java

public void validateXml(Schema schema, org.w3c.dom.Document doc) {
    try {// w w w . j  a v  a  2s  .com
        // creating a Validator instance
        Validator validator = schema.newValidator();
        System.out.println();
        System.out.println("Validator Class: " + validator.getClass().getName());

        // setting my own error handler
        validator.setErrorHandler(new MyErrorHandler());

        // validating the document against the schema
        validator.validate(new DOMSource(doc));
        System.out.println();
        if (errorCount > 0) {
            System.out.println("Failed with errors: " + errorCount);
        } else {
            System.out.println("Passed.");
        }

    } catch (Exception e) {
        // catching all validation exceptions
        System.out.println();
        System.out.println(e.toString());
    }
}

From source file:io.aino.agents.wso2.mediator.factory.AinoMediatorFactory.java

private void validateXml(OMElement element, String schemaPath) throws SAXException, IOException {
    OMFactory doomFactory = DOOMAbstractFactory.getOMFactory();

    StAXOMBuilder doomBuilder = new StAXOMBuilder(doomFactory, element.getXMLStreamReader());

    Element domElement = (Element) doomBuilder.getDocumentElement();

    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source source = new StreamSource(this.getClass().getResourceAsStream(schemaPath));

    Schema schema = factory.newSchema(source);

    Validator validator = schema.newValidator();
    validator.validate(new DOMSource(domElement));
}

From source file:mx.bigdata.sat.cfdi.CFDv33.java

@Override
public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source[] schemas = new Source[XSD.length];
    for (int i = 0; i < XSD.length; i++) {
        schemas[i] = new StreamSource(getClass().getResourceAsStream(XSD[i]));
    }//from w  w w . ja v  a  2s .  c o  m
    Schema schema = sf.newSchema(schemas);
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }
    validator.validate(new JAXBSource(context, document));
}

From source file:com.denimgroup.threadfix.importer.impl.upload.SSVLChannelImporter.java

@Nonnull
@Override//w w  w .j  av  a  2s .c om
public ScanCheckResultBean checkFile() {

    boolean valid = false;
    String[] schemaList = new String[] { "ssvl.xsd", "ssvl_v0.3.xsd" };

    for (String schemaFilePath : schemaList) {

        try {
            URL schemaFile = ResourceUtils.getResourceAsUrl(schemaFilePath);

            if (schemaFile == null) {
                throw new IllegalStateException("ssvl.xsd file not available from ClassLoader. Fix that.");
            }

            if (inputFileName == null) {
                throw new IllegalStateException("inputFileName was null, unable to load scan file.");
            }

            Source xmlFile = new StreamSource(new File(inputFileName));
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(schemaFile);
            Validator validator = schema.newValidator();
            validator.validate(xmlFile);

            valid = true;
            log.info(xmlFile.getSystemId() + " is valid");
            break;

        } catch (MalformedURLException e) {
            log.error("Code contained an incorrect path to the XSD file.", e);
        } catch (SAXException e) {
            log.warn("SAX Exception encountered, ", e);
        } catch (IOException e) {
            log.warn("IOException encountered, ", e);
        }
    }

    if (valid) {
        return testSAXInput(new SSVLChannelSAXValidator());
    } else {
        return new ScanCheckResultBean(ScanImportStatus.FAILED_XSD);
    }
}