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:i5.las2peer.services.mobsos.surveys.SurveyService.java

/**
 * Initialize XML parser and validator for questionnaire forms and answers
 * /*from  w ww.j a  v  a 2  s .  c o  m*/
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private void initXMLInfrastructure() throws SAXException, ParserConfigurationException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = factory.newSchema(new File(questionnaireSchemaPath));
    validator = schema.newValidator();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setSchema(schema);
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);

    parser = dbf.newDocumentBuilder();
}

From source file:net.sourceforge.pmd.testframework.RuleTst.java

public RuleTst() {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema;/*www .j  a va2 s. co  m*/
    try {
        schema = schemaFactory.newSchema(RuleTst.class.getResource("/rule-tests_1_0_0.xsd"));
        dbf.setSchema(schema);
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = dbf.newDocumentBuilder();
        builder.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw exception;
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                throw exception;
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw exception;
            }
        });
        documentBuilder = builder;
    } catch (SAXException | ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:nl.armatiek.xslweb.configuration.Context.java

private void initXMLSchemas() throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    File schemaFile = new File(homeDir, "config/xsd/xslweb/webapp.xsd");
    if (!schemaFile.isFile()) {
        logger.warn(String.format("XML Schema \"%s\" not found", schemaFile.getAbsolutePath()));
    } else {// w w  w.j av a2 s . c o m
        webAppSchema = factory.newSchema(schemaFile);
    }
}

From source file:nl.b3p.viewer.admin.stripes.GeoServiceActionBean.java

public Resolution validateSldXml() {
    Resolution jsp = new ForwardResolution(JSP_EDIT_SLD);
    Document sldXmlDoc = null;/*from   w  ww .  j  a va2s.  c  om*/
    String stage = "Fout bij parsen XML document";
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();

        sldXmlDoc = db.parse(new ByteArrayInputStream(sld.getSldBody().getBytes("UTF-8")));

        stage = "Fout bij controleren SLD";

        Element root = sldXmlDoc.getDocumentElement();
        if (!"StyledLayerDescriptor".equals(root.getLocalName())) {
            throw new Exception("Root element moet StyledLayerDescriptor zijn");
        }
        String version = root.getAttribute("version");
        if (version == null || !("1.0.0".equals(version) || "1.1.0".equals(version))) {
            throw new Exception("Geen of ongeldige SLD versie!");
        }

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema s = sf
                .newSchema(new URL("http://schemas.opengis.net/sld/" + version + "/StyledLayerDescriptor.xsd"));
        s.newValidator().validate(new DOMSource(sldXmlDoc));

    } catch (Exception e) {
        String extra = "";
        if (e instanceof SAXParseException) {
            SAXParseException spe = (SAXParseException) e;
            if (spe.getLineNumber() != -1) {
                extra = " (regel " + spe.getLineNumber();
                if (spe.getColumnNumber() != -1) {
                    extra += ", kolom " + spe.getColumnNumber();
                }
                extra += ")";
            }
        }
        getContext().getValidationErrors()
                .addGlobalError(new SimpleError("{2}: {3}{4}", stage, ExceptionUtils.getMessage(e), extra));
        return jsp;
    }

    getContext().getMessages().add(new SimpleMessage("SLD is valide!"));

    return jsp;
}

From source file:nl.clockwork.mule.common.filter.AbstractXSDValidationFilter.java

public void setXsdFile(String xsdFile) {
    try {/* ww w  . j a  v a 2  s  .c o m*/
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        //schema = factory.newSchema(new StreamSource(this.getClass().getResourceAsStream(xsdFile)));
        String systemId = this.getClass().getResource(xsdFile).toString();
        schema = factory.newSchema(new StreamSource(this.getClass().getResourceAsStream(xsdFile), systemId));
    } catch (SAXException e) {
        logger.fatal("", e);
        throw new RuntimeException(e);
    }
}

From source file:nl.nn.adapterframework.align.Json2Xml.java

public static String translate(JsonStructure json, URL schemaURL, boolean compactJsonArrays, String rootElement,
        boolean strictSyntax, boolean deepSearch, String targetNamespace, Map<String, Object> overrideValues)
        throws SAXException, IOException {

    // create the ValidatorHandler
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(schemaURL);
    ValidatorHandler validatorHandler = schema.newValidatorHandler();

    // create the XSModel
    XMLSchemaLoader xsLoader = new XMLSchemaLoader();
    XSModel xsModel = xsLoader.loadURI(schemaURL.toExternalForm());
    List<XSModel> schemaInformation = new LinkedList<XSModel>();
    schemaInformation.add(xsModel);/*from   w w  w  . j ava  2  s  . com*/

    // create the validator, setup the chain
    Json2Xml j2x = new Json2Xml(validatorHandler, schemaInformation, compactJsonArrays, rootElement,
            strictSyntax);
    if (overrideValues != null) {
        j2x.setOverrideValues(overrideValues);
    }
    if (targetNamespace != null) {
        //if (DEBUG) System.out.println("setting targetNamespace ["+targetNamespace+"]");
        j2x.setTargetNamespace(targetNamespace);
    }
    j2x.setDeepSearch(deepSearch);
    Source source = j2x.asSource(json);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    String xml = null;
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(source, result);
        writer.flush();
        xml = writer.toString();
    } catch (TransformerConfigurationException e) {
        SAXException se = new SAXException(e);
        se.initCause(e);
        throw se;
    } catch (TransformerException e) {
        SAXException se = new SAXException(e);
        se.initCause(e);
        throw se;
    }
    return xml;
}

From source file:nl.nn.adapterframework.align.XmlTo.java

public static void translate(String xml, URL schemaURL, DocumentContainer documentContainer)
        throws SAXException, IOException {

    // create the ValidatorHandler
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(schemaURL);
    ValidatorHandler validatorHandler = schema.newValidatorHandler();

    // create the parser, setup the chain
    XMLReader parser = new SAXParser();
    XmlAligner aligner = new XmlAligner(validatorHandler);
    XmlTo<DocumentContainer> xml2object = new XmlTo<DocumentContainer>(aligner, documentContainer);
    parser.setContentHandler(validatorHandler);
    aligner.setContentHandler(xml2object);

    // start translating
    InputSource is = new InputSource(new StringReader(xml));
    parser.parse(is);//from   w  ww  .j  a v  a2s  . c om
}

From source file:nl.nn.adapterframework.validation.JavaxXmlValidator.java

/**
 * Returns the {@link Schema} associated with this validator. This is an XSD schema containing knowledge about the
 * schema source as returned by {@link #getSchemaSources(List)}
 *///from   www. jav  a 2  s.c  o m
protected synchronized Schema getSchemaObject(String schemasId,
        List<nl.nn.adapterframework.validation.Schema> schemas) throws ConfigurationException {
    Schema schema = javaxSchemas.get(schemasId);
    if (schema == null) {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        factory.setResourceResolver(new LSResourceResolver() {
            public LSInput resolveResource(String s, String s1, String s2, String s3, String s4) {
                return null;
            }
        });
        try {
            Collection<Source> sources = getSchemaSources(schemas);
            schema = factory.newSchema(sources.toArray(new Source[sources.size()]));
            javaxSchemas.put(schemasId, schema);
        } catch (Exception e) {
            throw new ConfigurationException("cannot read schema's [" + schemasId + "]", e);
        }
    }
    return schema;
}

From source file:nl.ordina.bag.etl.xml.BatchExtractParser.java

public BatchExtractParser() {
    try {// w w  w  .  j  a v a 2  s. c o m
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schema = schemaFactory.newSchema(new StreamSource(SchemaValidator.class.getResourceAsStream(XSD_FILE),
                SchemaValidator.class.getResource(XSD_FILE).toString()));
        objectBuilder = XMLMessageBuilder.getInstance(BAGExtractDeelbestandLVC.class);
    } catch (Exception e) {
        throw new ParserException(e);
    }
}

From source file:org.accada.epcis.repository.capture.CaptureOperationsModule.java

/**
 * Initializes the EPCIS schema used for validating incoming capture
 * requests. Loads the WSDL and XSD files from the classpath (the schema is
 * bundled with epcis-commons.jar).//from  w  ww.  j  a va2  s  .  c o  m
 * 
 * @return An instantiated schema validation object.
 */
private Schema initEpcisSchema(String xsdFile) {
    InputStream is = this.getClass().getResourceAsStream(xsdFile);
    if (is != null) {
        try {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Source schemaSrc = new StreamSource(is);
            schemaSrc.setSystemId(CaptureOperationsServlet.class.getResource(xsdFile).toString());
            Schema schema = schemaFactory.newSchema(schemaSrc);
            LOG.debug("EPCIS schema file initialized and loaded successfully");
            return schema;
        } catch (Exception e) {
            LOG.warn("Unable to load or parse the EPCIS schema", e);
        }
    } else {
        LOG.error("Unable to load the EPCIS schema file from classpath: cannot find resource " + xsdFile);
    }
    LOG.warn("Schema validation will not be available!");
    return null;
}