Search in sources :

Example 1 with Schema

use of javax.xml.validation.Schema in project camel by apache.

the class ValidatingProcessor method doProcess.

protected void doProcess(Exchange exchange) throws Exception {
    Schema schema;
    if (isUseSharedSchema()) {
        schema = getSchema();
    } else {
        schema = createSchema();
    }
    Validator validator = schema.newValidator();
    // the underlying input stream, which we need to close to avoid locking files or other resources
    Source source = null;
    InputStream is = null;
    try {
        Result result = null;
        // only convert to input stream if really needed
        if (isInputStreamNeeded(exchange)) {
            is = getContentToValidate(exchange, InputStream.class);
            if (is != null) {
                source = getSource(exchange, is);
            }
        } else {
            Object content = getContentToValidate(exchange);
            if (content != null) {
                source = getSource(exchange, content);
            }
        }
        if (shouldUseHeader()) {
            if (source == null && isFailOnNullHeader()) {
                throw new NoXmlHeaderValidationException(exchange, headerName);
            }
        } else {
            if (source == null && isFailOnNullBody()) {
                throw new NoXmlBodyValidationException(exchange);
            }
        }
        //CAMEL-7036 We don't need to set the result if the source is an instance of StreamSource
        if (source instanceof DOMSource) {
            result = new DOMResult();
        } else if (source instanceof SAXSource) {
            result = new SAXResult();
        } else if (source instanceof StAXSource || source instanceof StreamSource) {
            result = null;
        }
        if (source != null) {
            // create a new errorHandler and set it on the validator
            // must be a local instance to avoid problems with concurrency (to be
            // thread safe)
            ValidatorErrorHandler handler = errorHandler.getClass().newInstance();
            validator.setErrorHandler(handler);
            try {
                LOG.trace("Validating {}", source);
                validator.validate(source, result);
                handler.handleErrors(exchange, schema, result);
            } catch (SAXParseException e) {
                // can be thrown for non well formed XML
                throw new SchemaValidationException(exchange, schema, Collections.singletonList(e), Collections.<SAXParseException>emptyList(), Collections.<SAXParseException>emptyList());
            }
        }
    } finally {
        IOHelper.close(is);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DOMResult(javax.xml.transform.dom.DOMResult) InputStream(java.io.InputStream) Schema(javax.xml.validation.Schema) StreamSource(javax.xml.transform.stream.StreamSource) StAXSource(javax.xml.transform.stax.StAXSource) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) SAXSource(javax.xml.transform.sax.SAXSource) StAXSource(javax.xml.transform.stax.StAXSource) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult) DOMResult(javax.xml.transform.dom.DOMResult) SAXSource(javax.xml.transform.sax.SAXSource) SAXResult(javax.xml.transform.sax.SAXResult) SAXParseException(org.xml.sax.SAXParseException) Validator(javax.xml.validation.Validator)

Example 2 with Schema

use of javax.xml.validation.Schema in project qi4j-sdk by Qi4j.

the class QuikitServlet method init.

@Override
public void init(ServletConfig config) throws ServletException {
    try {
        mountPoints = new TreeMap<String, Page>();
        documentFactory = DocumentBuilderFactory.newInstance();
        documentFactory.setNamespaceAware(true);
        ClassLoader cl = getClass().getClassLoader();
        SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        Source[] schemaSources = new Source[2];
        schemaSources[0] = new StreamSource(cl.getResourceAsStream("xhtml1-strict.xsd"));
        schemaSources[1] = new StreamSource(cl.getResourceAsStream("xml.xsd"));
        Schema schema = schemaFactory.newSchema(schemaSources);
        documentFactory.setSchema(schema);
        ApplicationAssembler assembler = createApplicationAssembler(config);
        Energy4Java qi4j = new Energy4Java();
        application = qi4j.newApplication(assembler);
        application.activate();
        Module module = application.findModule("WebLayer", "PagesModule");
        finder = module;
        if (application.mode() == Application.Mode.development) {
            DataInitializer initializer = module.newTransient(DataInitializer.class);
            initializer.initialize();
        }
        Iterable<ServiceReference<Page>> iterable = finder.findServices(Page.class);
        for (ServiceReference<Page> page : iterable) {
            PageMetaInfo pageMetaInfo = page.metaInfo(PageMetaInfo.class);
            String mountPoint = pageMetaInfo.mountPoint();
            mountPoints.put(mountPoint, page.get());
        }
    } catch (Exception e) {
        throw new ServletException("Can not initialize Qi4j.", e);
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) StreamSource(javax.xml.transform.stream.StreamSource) Schema(javax.xml.validation.Schema) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) TransformerException(javax.xml.transform.TransformerException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) ServiceReference(org.qi4j.api.service.ServiceReference) ServletException(javax.servlet.ServletException) ApplicationAssembler(org.qi4j.bootstrap.ApplicationAssembler) Energy4Java(org.qi4j.bootstrap.Energy4Java) Module(org.qi4j.api.structure.Module)

Example 3 with Schema

use of javax.xml.validation.Schema in project malmo by Microsoft.

the class SchemaHelper method deserialiseObject.

/** Attempt to construct the specified object from this XML string
     * @param xml the XML string to parse
     * @param xsdFile the name of the XSD schema that defines the object
     * @param objclass the class of the object requested
     * @return if successful, an instance of class objclass that captures the data in the XML string
     */
public static Object deserialiseObject(String xml, String xsdFile, Class<?> objclass) throws JAXBException, SAXException, XMLStreamException {
    Object obj = null;
    JAXBContext jaxbContext = getJAXBContext(objclass);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final String schemaResourceFilename = new String(xsdFile);
    URL schemaURL = MalmoMod.class.getClassLoader().getResource(schemaResourceFilename);
    Schema schema = schemaFactory.newSchema(schemaURL);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    jaxbUnmarshaller.setSchema(schema);
    StringReader stringReader = new StringReader(xml);
    XMLInputFactory xif = XMLInputFactory.newFactory();
    xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    XMLStreamReader XMLreader = xif.createXMLStreamReader(stringReader);
    obj = jaxbUnmarshaller.unmarshal(XMLreader);
    return obj;
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) XMLStreamReader(javax.xml.stream.XMLStreamReader) Schema(javax.xml.validation.Schema) StringReader(java.io.StringReader) JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller) MalmoMod(com.microsoft.Malmo.MalmoMod) URL(java.net.URL) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 4 with Schema

use of javax.xml.validation.Schema in project OpenAttestation by OpenAttestation.

the class ReadXmlTest method createValidator.

@BeforeClass
public static void createValidator() throws Exception {
    InputStream xsd = ReadXmlTest.class.getResourceAsStream("/jaxb/mtwilson-tag-selection/mtwilson-tag-selection.xsd");
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(xsd));
        validator = schema.newValidator();
    } catch (Exception e) {
        throw e;
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) InputStream(java.io.InputStream) Schema(javax.xml.validation.Schema) StreamSource(javax.xml.transform.stream.StreamSource) IOException(java.io.IOException) JAXBException(javax.xml.bind.JAXBException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) BeforeClass(org.junit.BeforeClass)

Example 5 with Schema

use of javax.xml.validation.Schema in project Openfire by igniterealtime.

the class UserSchemaValidator method validateAndParse.

/**
   * Perform a validate and a parse of the specified source document.
   * Validating is done with the specified schemafiles.
   * 
   * @return A Document when the validation s successful.
   */
Document validateAndParse() {
    ValidatorErrorHandler handler = new ValidatorErrorHandler();
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setXIncludeAware(true);
        documentBuilderFactory.setValidating(false);
        // We don't want xml:base and xml:lang attributes in the output.
        documentBuilderFactory.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false);
        documentBuilderFactory.setFeature("http://apache.org/xml/features/xinclude/fixup-language", false);
        if (schemaSources.length > 0) {
            Log.info("Checking Schema's");
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setErrorHandler(handler);
            Schema schema = schemaFactory.newSchema(schemaSources);
            documentBuilderFactory.setSchema(schema);
            Log.info("Start validating document");
        } else {
            Log.info("Loading document");
        }
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        handler.reset();
        // Communicate some info about the Xincludes in the imported file. These imports should be resolvable by the server. 
        documentBuilder.setEntityResolver(new EntityResolver() {

            @Override
            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                Log.info(String.format("resolved Entity:%s %s", (publicId != null ? publicId : ""), systemId));
                return null;
            }
        });
        documentBuilder.setErrorHandler(handler);
        Document result = documentBuilder.parse(source);
        if (result != null && handler.isValid()) {
            return result;
        } else {
            Log.warn(String.format("document is invalid. %1$d errors found.", handler.getNrOfErrors()));
            return null;
        }
    } catch (Exception e) {
        Log.warn(String.format("document validation failed. %1$d errors found.", handler.getNrOfErrors()));
        Log.debug("", e);
        return null;
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Schema(javax.xml.validation.Schema) EntityResolver(org.xml.sax.EntityResolver) IOException(java.io.IOException) Document(org.w3c.dom.Document) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) SAXException(org.xml.sax.SAXException) DocumentBuilder(javax.xml.parsers.DocumentBuilder)

Aggregations

Schema (javax.xml.validation.Schema)102 SchemaFactory (javax.xml.validation.SchemaFactory)72 Validator (javax.xml.validation.Validator)51 StreamSource (javax.xml.transform.stream.StreamSource)45 SAXException (org.xml.sax.SAXException)35 Source (javax.xml.transform.Source)29 DOMSource (javax.xml.transform.dom.DOMSource)25 IOException (java.io.IOException)22 JAXBContext (javax.xml.bind.JAXBContext)18 Document (org.w3c.dom.Document)18 InputStream (java.io.InputStream)17 File (java.io.File)15 URL (java.net.URL)15 DocumentBuilder (javax.xml.parsers.DocumentBuilder)14 JAXBException (javax.xml.bind.JAXBException)13 Unmarshaller (javax.xml.bind.Unmarshaller)13 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)13 InputSource (org.xml.sax.InputSource)13 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)12 SAXParseException (org.xml.sax.SAXParseException)9