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:eu.europa.esig.dss.validation.ValidationResourceManager.java

/**
 * This is the utility method that loads the data from the inputstream determined by the inputstream parameter into
 * a// ww w. j a v  a2  s . com
 * {@link ConstraintsParameters}.
 *
 * @param inputStream
 * @return
 */
public static ConstraintsParameters load(final InputStream inputStream) throws DSSException {
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new StreamSource(
                ValidationResourceManager.class.getResourceAsStream(defaultPolicyXsdLocation)));

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schema);

        return (ConstraintsParameters) unmarshaller.unmarshal(inputStream);
    } catch (Exception e) {
        throw new DSSException("Unable to load policy : " + e.getMessage(), e);
    }
}

From source file:io.inkstand.jcr.util.JCRContentLoaderTest.java

@Test
public void testLoadContent_validating_validResource() throws Exception {
    // prepare/*from ww  w  .  j  ava2 s.  c  o m*/
    final URL resource = getClass().getResource("test01_inkstandJcrImport_v1-0.xml");
    final Session actSession = repository.login("admin", "admin");
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = schemaFactory.newSchema(getClass().getResource("inkstandJcrImport_v1-0.xsd"));
    // act
    subject.setSchema(schema);
    subject.loadContent(actSession, resource);
    // assert
    final Session verifySession = repository.getRepository().login();
    verifySession.refresh(true);
    assertNodeExistByPath(verifySession, "/root");
    final Node root = verifySession.getNode("/root");
    assertPrimaryNodeType(root, "nt:unstructured");
    assertMixinNodeType(root, "mix:title");
    assertStringPropertyEquals(root, "jcr:title", "TestTitle");
}

From source file:ee.ria.xroad.opmonitordaemon.QueryRequestHandler.java

private static Schema createSchema() {
    try {/*from w w w. j a v a2s .c  o m*/
        return SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(ResourceUtils.getClasspathResource("op-monitoring.xsd"));
    } catch (SAXException e) {
        throw new CodedException(X_INTERNAL_ERROR, e);
    }
}

From source file:io.onedecision.engine.decisions.model.dmn.validators.SchemaValidator.java

public void validate(InputStream obj, Errors errors) {
    InputStream is = (InputStream) obj;

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new LocalResourceResolver());

    try {//from   w ww  . j a  v a 2  s .c om
        schemaFactory.newSchema(new StreamSource(getResourceAsStreamWrapper("schema/dmn.xsd")));
    } catch (SAXException e1) {
        errors.reject("Cannot find / read schema", "Exception: " + e1.getMessage());
    }

    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    // parserFactory.setValidating(true);
    parserFactory.setNamespaceAware(true);
    // parserFactory.setSchema(schema);

    SAXParser parser = null;
    try {
        parser = parserFactory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setErrorHandler(this);

        try {
            parser.parse(new InputSource(is), (DefaultHandler) null);
        } catch (Exception e) {
            String msg = "Schema validation failed";
            LOGGER.error(msg, e);
            errors.reject(msg, "Exception: " + e.getMessage());
        }
        if (this.errors.size() > 0) {
            errors.reject("Schema validation failed", this.errors.toString());
        }
    } catch (ParserConfigurationException e1) {
        errors.reject("Cannot create parser", "Exception: " + e1.getMessage());
    } catch (SAXException e1) {
        errors.reject("Parser cannot be created", "Exception: " + e1.getMessage());
    }
}

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);/*from ww w  .  j  a  va 2s . 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.anodyneos.jse.cron.CronDaemon.java

public CronDaemon(InputSource source) throws JseException {

    Schedule schedule;//from   ww w.java  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:io.github.mikesaelim.arxivoaiharvester.xml.XMLParser.java

/**
 * Constructs a new XML parser by initializing the JAXB unmarshaller and setting up the XML validation.
 *
 * @throws HarvesterError if there are any problems
 *//*from w w  w.j  a v a2s  .c  o  m*/
public XMLParser() {
    try {
        unmarshaller = JAXBContext.newInstance("org.openarchives.oai._2:org.arxiv.oai.arxivraw")
                .createUnmarshaller();
    } catch (JAXBException e) {
        throw new HarvesterError("Error creating JAXB unmarshaller", e);
    }

    ClassLoader classLoader = this.getClass().getClassLoader();
    List<Source> schemaSources = Lists.newArrayList(
            new StreamSource(classLoader.getResourceAsStream("OAI-PMH.xsd")),
            new StreamSource(classLoader.getResourceAsStream("arXivRaw.xsd")));
    try {
        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(schemaSources.toArray(new Source[schemaSources.size()]));
        unmarshaller.setSchema(schema);
    } catch (SAXException e) {
        throw new HarvesterError("Error creating validation schema", e);
    }
}

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

public void validar(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   www.j  a  v a2 s  . c  o  m
    validator.validate(new JAXBSource(CONTEXT, tfd));
}

From source file:com.predic8.membrane.core.interceptor.schemavalidation.SOAPMessageValidatorInterceptor.java

private List<Validator> getValidators() throws Exception {
    log.info("Get validators for WSDL: " + wsdl);
    WSDLParserContext ctx = new WSDLParserContext();
    ctx.setInput(wsdl);//from   w  ww  . j av  a  2  s . c  o  m
    SchemaFactory sf = SchemaFactory.newInstance(Constants.XSD_NS);
    sf.setResourceResolver(new SOAModelResourceResolver(wsdl));
    List<Validator> validators = new ArrayList<Validator>();
    for (Schema schema : getEmbeddedSchemas(ctx)) {
        log.info("Adding embedded schema: " + schema);
        Validator validator = sf
                .newSchema(new StreamSource(new ByteArrayInputStream(schema.getAsString().getBytes())))
                .newValidator();
        validator.setErrorHandler(new SchemaValidatorErrorHandler());
        validators.add(validator);
    }
    return validators;
}

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

/**
 *
 * @param operationName/*  ww  w.  j a va 2 s .c om*/
 * @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;
}