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: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;//from  ww  w. j a  va 2  s  . 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:com.jtstand.swing.Main.java

public Main(String[] args) {
    //BasicConfigurator.configure();

    options = new Options();
    options.addOption("help", false, "print this message");
    options.addOption("version", false, "print the version information and exit");
    options.addOption("s", true, "station host name");
    options.addOption("t", true, "title text");
    options.addOption("r", true, "revision number");
    options.addOption("v", true, "version");
    options.addOption("x", true, "schema file location");

    CommandLineParser parser = new PosixParser();
    try {/*w w w . j  a va 2s . co  m*/
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("jtstand", options);
            System.exit(0);
        } else if (cmd.hasOption("version")) {
            printVersion();
            System.exit(0);
        } else {
            if (cmd.getArgs() != null && cmd.getArgs().length > 0) {
                if (cmd.getArgs().length == 1) {
                    projectLocation = cmd.getArgs()[0];
                } else {
                    log.error("Only one argument is expected; the project location!");
                    log.error("Received arguments:");
                    for (int i = 0; i < cmd.getArgs().length; i++) {
                        log.error(cmd.getArgs()[i]);
                    }
                }
            }
            if (cmd.hasOption("s")) {
                station = cmd.getOptionValue("s");
            }
            if (cmd.hasOption("r")) {
                revision = Integer.parseInt(cmd.getOptionValue("r"));
            }
            if (cmd.hasOption("v")) {
                version = cmd.getOptionValue("v");
            }
            if (cmd.hasOption("t")) {
                title = cmd.getOptionValue("t");
            }
            if (cmd.hasOption("x")) {
                SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                String schemaLocation = cmd.getOptionValue("x");
                File schemaFile = new File(schemaLocation);
                if (schemaFile.isFile()) {
                    try {
                        TestProject.setSchema(schemaFactory.newSchema(schemaFile));
                    } catch (SAXException ex) {
                        log.fatal("Exception", ex);
                        javax.swing.JOptionPane.showMessageDialog(null,
                                "Schema file is invalid!\nPress OK to exit.", "Error",
                                javax.swing.JOptionPane.ERROR_MESSAGE);
                        System.exit(-1);
                    }
                } else {
                    javax.swing.JOptionPane.showMessageDialog(null,
                            "Schema file cannot be opened!\nPress OK to continue.", "Warning",
                            javax.swing.JOptionPane.WARNING_MESSAGE);
                }
            }
            startProject();
        }
    } catch (ParseException e) {
        log.fatal("Parsing failed" + e);
        System.exit(-1);
    }
}

From source file:org.openremote.beehive.configuration.www.UsersAPI.java

private File createControllerXmlFile(java.nio.file.Path temporaryFolder, Account account) {
    File controllerXmlFile = new File(temporaryFolder.toFile(), "controller.xml");

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

    try {/*from  w w  w .j av a 2s  .  c  o m*/
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        DOMImplementation domImplementation = documentBuilder.getDOMImplementation();
        Document document = domImplementation.createDocument(OPENREMOTE_NAMESPACE, "openremote", null);
        document.getDocumentElement().setAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
                "xsi:schemaLocation",
                "http://www.openremote.org http://www.openremote.org/schemas/controller.xsd");

        Element componentsElement = document.createElementNS(OPENREMOTE_NAMESPACE, "components");
        document.getDocumentElement().appendChild(componentsElement);
        writeSensors(document, document.getDocumentElement(), account, findHighestCommandId(account));
        writeCommands(document, document.getDocumentElement(), account);
        writeConfig(document, document.getDocumentElement(), account);

        // Document is fully built, validate against schema before writing to file
        URL xsdResource = UsersAPI.class.getResource(CONTROLLER_XSD_PATH);
        if (xsdResource == null) {
            log.error("Cannot find XSD schema ''{0}''. Disabling validation...", CONTROLLER_XSD_PATH);
        } else {
            String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
            SchemaFactory factory = SchemaFactory.newInstance(language);
            Schema schema = factory.newSchema(xsdResource);
            Validator validator = schema.newValidator();
            validator.validate(new DOMSource(document));
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        Result output = new StreamResult(controllerXmlFile);
        Source input = new DOMSource(document);
        transformer.transform(input, output);
    } catch (ParserConfigurationException e) {
        log.error("Error generating controller.xml file", e);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
    } catch (TransformerConfigurationException e) {
        log.error("Error generating controller.xml file", e);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
    } catch (TransformerException e) {
        log.error("Error generating controller.xml file", e);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
    } catch (SAXException e) {
        log.error("Error generating controller.xml file", e);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
    } catch (IOException e) {
        log.error("Error generating controller.xml file", e);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
    }

    return controllerXmlFile;
}

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

private SpringApplicationService parse(final InputStream xml) throws JAXBException {
    Assert.notNull(xml);//www.  j  a  va2 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:com.predic8.membrane.core.interceptor.schemavalidation.AbstractXMLSchemaValidator.java

protected List<Validator> createValidators() throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(Constants.XSD_NS);
    List<Validator> validators = new ArrayList<Validator>();
    for (Schema schema : getSchemas()) {
        log.debug("Creating validator for schema: " + schema);
        StreamSource ss = new StreamSource(new StringReader(schema.getAsString()));
        ss.setSystemId(location);/*w  ww  . ja v  a 2 s. c  o m*/
        sf.setResourceResolver(resourceResolver.toLSResourceResolver());
        Validator validator = sf.newSchema(ss).newValidator();
        validator.setResourceResolver(resourceResolver.toLSResourceResolver());
        validator.setErrorHandler(new SchemaValidatorErrorHandler());
        validators.add(validator);
    }
    return validators;
}

From source file:hydrograph.ui.propertywindow.widgets.customwidgets.schema.GridRowLoader.java

private boolean validateXML(InputStream xml, InputStream xsd) {
    try {// w  w w  .  ja va  2s.c o  m
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        javax.xml.validation.Schema schema = factory.newSchema(new StreamSource(xsd));
        Validator validator = schema.newValidator();

        validator.validate(new StreamSource(xml));
        return true;
    } catch (SAXException | IOException ex) {
        MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error",
                Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage());
        logger.error(Messages.IMPORT_XML_FORMAT_ERROR);
        return false;
    }
}

From source file:com.panet.imeta.job.entries.xsdvalidator.JobEntryXSDValidator.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);// w  ww  . j  av  a  2  s .  c o  m

    String realxmlfilename = getRealxmlfilename();
    String realxsdfilename = getRealxsdfilename();

    FileObject xmlfile = null;
    FileObject xsdfile = null;

    try

    {

        if (xmlfilename != null && xsdfilename != null) {
            xmlfile = KettleVFS.getFileObject(realxmlfilename);
            xsdfile = KettleVFS.getFileObject(realxsdfilename);

            if (xmlfile.exists() && xsdfile.exists()) {

                SchemaFactory factorytXSDValidator_1 = SchemaFactory
                        .newInstance("http://www.w3.org/2001/XMLSchema");

                // Get XSD File
                File XSDFile = new File(KettleVFS.getFilename(xsdfile));
                Schema SchematXSD = factorytXSDValidator_1.newSchema(XSDFile);

                Validator XSDValidator = SchematXSD.newValidator();

                // Get XML File
                File xmlfiletXSDValidator_1 = new File(KettleVFS.getFilename(xmlfile));

                Source sourcetXSDValidator_1 = new StreamSource(xmlfiletXSDValidator_1);

                XSDValidator.validate(sourcetXSDValidator_1);

                // Everything is OK
                result.setResult(true);

            } else {

                if (!xmlfile.exists()) {
                    log.logError(toString(),
                            Messages.getString("JobEntryXSDValidator.FileDoesNotExist1.Label") + realxmlfilename
                                    + Messages.getString("JobEntryXSDValidator.FileDoesNotExist2.Label"));
                }
                if (!xsdfile.exists()) {
                    log.logError(toString(),
                            Messages.getString("JobEntryXSDValidator.FileDoesNotExist1.Label") + realxsdfilename
                                    + Messages.getString("JobEntryXSDValidator.FileDoesNotExist2.Label"));
                }
                result.setResult(false);
                result.setNrErrors(1);
            }

        } else {
            log.logError(toString(), Messages.getString("JobEntryXSDValidator.AllFilesNotNull.Label"));
            result.setResult(false);
            result.setNrErrors(1);
        }

    }

    catch (SAXException ex) {
        log.logError(toString(), "Error :" + ex.getMessage());
    } catch (Exception e) {

        log.logError(toString(),
                Messages.getString("JobEntryXSDValidator.ErrorXSDValidator.Label")
                        + Messages.getString("JobEntryXSDValidator.ErrorXML1.Label") + realxmlfilename
                        + Messages.getString("JobEntryXSDValidator.ErrorXML2.Label")
                        + Messages.getString("JobEntryXSDValidator.ErrorXSD1.Label") + realxsdfilename
                        + Messages.getString("JobEntryXSDValidator.ErrorXSD2.Label") + e.getMessage());
        result.setResult(false);
        result.setNrErrors(1);
    } finally {
        try {
            if (xmlfile != null)
                xmlfile.close();

            if (xsdfile != null)
                xsdfile.close();

        } catch (IOException e) {
        }
    }

    return result;
}

From source file:eu.delving.test.TestMappingEngine.java

private Validator validator(SchemaVersion schemaVersion) {
    try {//from   w  w  w. j av a2  s  .com
        SchemaFactory factory = XMLToolFactory.schemaFactory(schemaVersion.getPrefix());
        factory.setResourceResolver(new CachedResourceResolver());
        String validationXsd = schemaRepo.getSchema(schemaVersion, SchemaType.VALIDATION_SCHEMA)
                .getSchemaText();
        if (validationXsd == null)
            throw new RuntimeException("Unable to find validation schema " + schemaVersion);
        Schema schema = factory.newSchema(new StreamSource(new StringReader(validationXsd)));
        return schema.newValidator();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.googlecode.l10nmavenplugin.validators.property.HtmlValidator.java

/**
 * Initialize using XML schema//from  ww  w  . j av a 2s.c  o  m
 * 
 * @param xhtmlSchema
 * @param logger
 */
public HtmlValidator(File xhtmlSchema, L10nValidatorLogger logger, L10nValidator<Property> spellCheckValidator,
        String[] htmlKeys, Formatter formattingParametersExtractor,
        InnerResourcesFormatter innerResourceFormatter) {
    super(logger, htmlKeys);
    this.spellCheckValidator = spellCheckValidator;
    this.formattingParametersExtractor = formattingParametersExtractor;
    this.innerResourceFormatter = innerResourceFormatter;

    try {
        // SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        // Need to use XERCES so that XHTML5 schema passes validation
        SchemaFactory factory = new XMLSchemaFactory();
        factory.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING, false);

        Schema schema = null;
        if (xhtmlSchema.exists()) {
            // Load custom schema
            schema = factory.newSchema(xhtmlSchema);
        } else {
            // Try to load a pre-defined schemas from classpath
            URL schemaURL = this.getClass().getClassLoader().getResource(xhtmlSchema.getName());

            if (schemaURL == null) {
                logger.getLogger()
                        .error("Could not load XML schema from file <" + xhtmlSchema.getAbsolutePath()
                                + "> and <" + xhtmlSchema.getName() + "> is not a default schema either ("
                                + Arrays.toString(PREDEFINED_XSD) + "), thus defaulting to "
                                + XHTML1_TRANSITIONAL.getName());
                schemaURL = this.getClass().getClassLoader().getResource(XHTML1_TRANSITIONAL.getName());
            }
            schema = factory.newSchema(schemaURL);
        }
        xhtmlValidator = schema.newValidator();

        // Initialize SAX parser
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        parser = saxParserFactory.newSAXParser();

    } catch (SAXException e) {
        logger.getLogger().error("Could not initialize HtmlValidator", e);

    } catch (ParserConfigurationException e) {
        logger.getLogger().error("Could not initialize HtmlValidator", e);
    }
}

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