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:com.denimgroup.threadfix.importer.impl.upload.SSVLChannelImporter.java

@Nonnull
@Override//  www.j  ava2  s.  co  m
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);
    }
}

From source file:com.smartitengineering.cms.spi.impl.type.validator.XMLSchemaBasedTypeValidator.java

protected boolean isValid(Document document) throws Exception {
    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final InputStream xsdStream = getClass().getClassLoader().getResourceAsStream(XSD_LOCATION);
    // load a WXS schema, represented by a Schema instance
    Source schemaFile = new StreamSource(xsdStream);
    schemaFile.setSystemId(CONTENT_TYPE_SCHEMA_URI);
    Schema schema = factory.newSchema(schemaFile);
    // create a Validator instance, which can be used to validate an instance document
    Validator validator = schema.newValidator();
    // validate the DOM tree
    try {/* w  w w. j av  a 2  s  .  c om*/
        validator.validate(new DOMSource(document));
        return true;
    } catch (SAXException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.anodyneos.jse.cron.CronDaemon.java

public CronDaemon(InputSource source) throws JseException {

    Schedule schedule;//from   w  w w. j av a 2 s. c om

    // parse source
    try {

        JAXBContext jc = JAXBContext.newInstance("org.anodyneos.jse.cron.config");
        Unmarshaller u = jc.createUnmarshaller();
        //Schedule
        Source schemaSource = new StreamSource(Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("org/anodyneos/jse/cron/cron.xsd"));

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(schemaSource);
        u.setSchema(schema);
        ValidationEventCollector vec = new ValidationEventCollector();
        u.setEventHandler(vec);

        JAXBElement<?> rootElement;
        try {
            rootElement = ((JAXBElement<?>) u.unmarshal(source));
        } catch (UnmarshalException ex) {
            if (!vec.hasEvents()) {
                throw ex;
            } else {
                for (ValidationEvent ve : vec.getEvents()) {
                    ValidationEventLocator vel = ve.getLocator();
                    log.error("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                            + ve.getMessage());
                }
                throw new JseException("Validation failed for source publicId='" + source.getPublicId()
                        + "'; systemId='" + source.getSystemId() + "';");
            }
        }

        schedule = (Schedule) rootElement.getValue();

        if (vec.hasEvents()) {
            for (ValidationEvent ve : vec.getEvents()) {
                ValidationEventLocator vel = ve.getLocator();
                log.warn("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                        + ve.getMessage());
            }
        }

    } catch (JseException e) {
        throw e;
    } catch (Exception e) {
        throw new JseException("Cannot parse " + source + ".", e);
    }

    SpringHelper springHelper = new SpringHelper();

    ////////////////
    //
    // Configure Spring and Create Beans
    //
    ////////////////

    TimeZone defaultTimeZone;

    if (schedule.isSetTimeZone()) {
        defaultTimeZone = getTimeZone(schedule.getTimeZone());
    } else {
        defaultTimeZone = TimeZone.getDefault();
    }

    if (schedule.isSetSpringContext() && schedule.getSpringContext().isSetConfig()) {
        for (Config config : schedule.getSpringContext().getConfig()) {
            springHelper.addXmlClassPathConfigLocation(config.getClassPathResource());
        }
    }

    for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) {
        for (Job job : jobGroup.getJob()) {
            if (job.isSetBeanRef()) {
                if (job.isSetBean() || job.isSetClassName()) {
                    throw new JseException("Cannot set bean or class attribute for job when beanRef is set.");
                } // else config ok
            } else {
                if (!job.isSetClassName()) {
                    throw new JseException("must set either class or beanRef for job.");
                }
                GenericBeanDefinition beanDef = new GenericBeanDefinition();
                MutablePropertyValues propertyValues = new MutablePropertyValues();

                if (!job.isSetBean()) {
                    job.setBean(UUID.randomUUID().toString());
                }

                if (springHelper.containsBean(job.getBean())) {
                    throw new JseException(
                            "Bean name already used; overriding not allowed here: " + job.getBean());
                }

                beanDef.setBeanClassName(job.getClassName());

                for (Property prop : job.getProperty()) {
                    String value = null;
                    if (prop.isSetSystemProperty()) {
                        value = System.getProperty(prop.getSystemProperty());
                    }
                    if (null == value) {
                        value = prop.getValue();
                    }

                    propertyValues.addPropertyValue(prop.getName(), value);
                }

                beanDef.setPropertyValues(propertyValues);
                springHelper.registerBean(job.getBean(), beanDef);
                job.setBeanRef(job.getBean());
            }
        }
    }

    springHelper.init();

    ////////////////
    //
    // Configure Timer Services
    //
    ////////////////

    for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) {

        String jobGroupName;
        JseTimerService service = new JseTimerService();

        timerServices.add(service);

        if (jobGroup.isSetName()) {
            jobGroupName = jobGroup.getName();
        } else {
            jobGroupName = UUID.randomUUID().toString();
        }

        if (jobGroup.isSetMaxConcurrent()) {
            service.setMaxConcurrent(jobGroup.getMaxConcurrent());
        }

        for (Job job : jobGroup.getJob()) {

            TimeZone jobTimeZone = defaultTimeZone;

            if (job.isSetTimeZone()) {
                jobTimeZone = getTimeZone(job.getTimeZone());
            } else {
                jobTimeZone = defaultTimeZone;
            }

            Object obj;

            Date notBefore = null;
            Date notAfter = null;

            if (job.isSetNotBefore()) {
                notBefore = job.getNotBefore().toGregorianCalendar(jobTimeZone, null, null).getTime();
            }
            if (job.isSetNotAfter()) {
                notAfter = job.getNotAfter().toGregorianCalendar(jobTimeZone, null, null).getTime();
            }

            CronSchedule cs = new CronSchedule(job.getSchedule(), jobTimeZone, job.getMaxIterations(),
                    job.getMaxQueue(), notBefore, notAfter);

            obj = springHelper.getBean(job.getBeanRef());
            log.info("Adding job " + jobGroup.getName() + "/" + job.getName() + " using bean "
                    + job.getBeanRef());
            if (obj instanceof CronJob) {
                ((CronJob) obj).setCronContext(new CronContext(jobGroupName, job.getName(), cs));
            }
            if (obj instanceof JseDateAwareJob) {
                service.createTimer((JseDateAwareJob) obj, cs);
            } else if (obj instanceof Runnable) {
                service.createTimer((Runnable) obj, cs);
            } else {
                throw new JseException("Job must implement Runnable or JseDateAwareJob");
            }
        }
    }
}

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

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 ww  .  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, tfd));
}

From source file:edu.wustl.bulkoperator.templateImport.AbstractImportBulkOperation.java

/**
 *
 * @param operationName/* www .  j  a va 2s.co  m*/
 * @param dropdownName
 * @param csvFile
 * @param xmlFile
 * @param mappingXml
 * @return
 * @throws BulkOperationException
 * @throws SQLException
 * @throws IOException
 * @throws DAOException
 */
protected Set<String> validate(String operationName, String dropdownName, String csvFile, String xmlFile,
        String mappingXml, String xsdLocation)
        throws BulkOperationException, SQLException, IOException, DAOException {
    Set<String> errorList = null;
    CsvReader csvReader = null;
    try {
        csvReader = CsvFileReader.createCsvFileReader(csvFile, true);

    } catch (Exception exp) {
        ErrorKey errorkey = ErrorKey.getErrorKey("bulk.error.incorrect.csv.file");
        throw new BulkOperationException(errorkey, exp, "");
    }
    BulkOperationMetaData bulkOperationMetaData = null;
    try {
        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        File schemaLocation = new File(xsdLocation);
        Schema schema = factory.newSchema(schemaLocation);
        DigesterLoader digesterLoader = DigesterLoader.newLoader(new XmlRulesModule(mappingXml));
        Digester digester = digesterLoader.newDigester();
        digester.setValidating(true);
        digester.setXMLSchema(schema);
        Validator validator = schema.newValidator();
        Source xmlFileForValidation = new StreamSource(new File(xmlFile));
        validator.validate(xmlFileForValidation);
        InputStream inputStream = new FileInputStream(xmlFile);
        bulkOperationMetaData = digester.parse(inputStream);
    } catch (SAXException e) {
        logger.debug(e.getMessage());
        ErrorKey errorkey = ErrorKey.getErrorKey("bulk.error.xml.template");
        throw new BulkOperationException(errorkey, e, e.getMessage());
    }
    Collection<BulkOperationClass> classList = bulkOperationMetaData.getBulkOperationClass();
    if (classList == null) {
        ErrorKey errorkey = ErrorKey.getErrorKey("bulk.no.templates.loaded.message");
        throw new BulkOperationException(errorkey, null, "");
    } else {
        Iterator<BulkOperationClass> iterator = classList.iterator();
        if (iterator.hasNext()) {
            BulkOperationClass bulkOperationClass = iterator.next();
            TemplateValidator templateValidator = new TemplateValidator();
            errorList = templateValidator.validateXmlAndCsv(bulkOperationClass, operationName, csvReader);
        }
    }
    return errorList;
}

From source file:cz.cas.lib.proarc.common.workflow.profile.WorkflowProfiles.java

private Unmarshaller getUnmarshaller() throws JAXBException {
    JAXBContext jctx = JAXBContext.newInstance(WorkflowDefinition.class);
    Unmarshaller unmarshaller = jctx.createUnmarshaller();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = WorkflowDefinition.class.getResource("workflow.xsd");
    Schema schema = null;/*w ww .  j  ava2s.com*/
    try {
        schema = sf.newSchema(new StreamSource(schemaUrl.toExternalForm()));
    } catch (SAXException ex) {
        throw new JAXBException("Missing schema workflow.xsd!", ex);
    }
    unmarshaller.setSchema(schema);
    ValidationEventCollector errors = new ValidationEventCollector() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            super.handleEvent(event);
            return true;
        }

    };
    unmarshaller.setEventHandler(errors);
    return unmarshaller;
}

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

public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source[] schemas = new Source[] { new StreamSource(getClass().getResourceAsStream(XSD)),
            new StreamSource(getClass().getResourceAsStream(XSD_TFD)) };
    Schema schema = sf.newSchema(schemas);
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }//from www .  j  ava2 s .  c  o  m
    validator.validate(new JAXBSource(context, document));
}

From source file:mx.bigdata.sat.cfd.CFDv22.java

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 va2 s . 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: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:cz.cas.lib.proarc.common.imports.TiffImporterTest.java

@Test
public void testConsume() throws Exception {
    temp.setDeleteOnExit(true);/*from w ww  . java2 s .c  o  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());
}