Example usage for javax.xml.validation SchemaFactory setResourceResolver

List of usage examples for javax.xml.validation SchemaFactory setResourceResolver

Introduction

In this page you can find the example usage for javax.xml.validation SchemaFactory setResourceResolver.

Prototype

public abstract void setResourceResolver(LSResourceResolver resourceResolver);

Source Link

Document

Sets the LSResourceResolver to customize resource resolution when parsing schemas.

Usage

From source file:org.codice.ddf.spatial.ogc.wfs.catalog.endpoint.writer.TestFeatureCollectionMessageBodyWriter.java

@Test
public void testWriteToGeneratesGMLConformantXml() throws IOException, WebApplicationException, SAXException {

    FeatureCollectionMessageBodyWriter wtr = new FeatureCollectionMessageBodyWriter();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    wtr.writeTo(getWfsFeatureCollection(), null, null, null, null, null, stream);
    String actual = stream.toString();

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

        private Map<String, String> schemaLocations;

        private Map<String, LSInput> inputs;

        {// www  .  j  a v  a 2 s. c om
            inputs = new HashMap<String, LSInput>();

            schemaLocations = new HashMap<String, String>();

            schemaLocations.put("xml.xsd", "/w3/1999/xml.xsd");
            schemaLocations.put("xlink.xsd", "/w3/1999/xlink.xsd");
            schemaLocations.put("geometry.xsd", "/gml/2.1.2/geometry.xsd");
            schemaLocations.put("feature.xsd", "/gml/2.1.2/feature.xsd");
            schemaLocations.put("gml.xsd", "/gml/2.1.2/gml.xsd");
            schemaLocations.put("expr.xsd", "/filter/1.0.0/expr.xsd");
            schemaLocations.put("filter.xsd", "/filter/1.0.0/filter.xsd");
            schemaLocations.put("filterCapabilities.xsd", "/filter/1.0.0/filterCapabilties.xsd");
            schemaLocations.put("WFS-capabilities.xsd", "/wfs/1.0.0/WFS-capabilities.xsd");
            schemaLocations.put("OGC-exception.xsd", "/wfs/1.0.0/OGC-exception.xsd");
            schemaLocations.put("WFS-basic.xsd", "/wfs/1.0.0/WFS-basic.xsd");
            schemaLocations.put("WFS-transaction.xsd", "/wfs/1.0.0/WFS-transaction.xsd");
            schemaLocations.put("wfs.xsd", "/wfs/1.0.0/wfs.xsd");
        }

        @Override
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            String fileName = new java.io.File(systemId).getName();
            if (inputs.containsKey(fileName)) {
                return inputs.get(fileName);
            }

            LSInput input = new DOMInputImpl();
            InputStream is = getClass().getResourceAsStream(schemaLocations.get(fileName));
            input.setByteStream(is);
            input.setBaseURI(baseURI);
            input.setSystemId(systemId);
            inputs.put(fileName, input);
            return input;
        }
    });

    Source wfsSchemaSource = new StreamSource(getClass().getResourceAsStream("/wfs/1.0.0/wfs.xsd"));
    Source testSchemaSource = new StreamSource(getClass().getResourceAsStream("/schema.xsd"));

    Schema schema = schemaFactory.newSchema(new Source[] { wfsSchemaSource, testSchemaSource });

    try {
        schema.newValidator().validate(new StreamSource(new StringReader(actual)));
    } catch (Exception e) {
        fail("Generated GML Response does not conform to WFS Schema" + e.getMessage());
    }
}

From source file:org.eclipse.mdht.dita.ui.util.DitaUtil.java

public static void validate(IPath tmpFileInWorkspaceDir)
        throws IOException, ParserConfigurationException, SAXException, URISyntaxException {

    // TODO delete commented out code which was used for debugging (debug code needs to stay at least two releases after 2.5.9)
    // Get the XSD file
    Bundle bundle = Platform.getBundle("org.eclipse.mdht.dita.ui");
    // Path ditaSchemadirPath = new Path("DITA-OT/schema/technicalContent/xsd/topic.xsd");
    // URL ditaXSD = FileLocator.toFileURL(FileLocator.find(bundle, ditaSchemadirPath, null));
    Path ditaFolderPath = new Path("DITA-OT");
    URL ditaFolder = FileLocator.toFileURL(FileLocator.find(bundle, ditaFolderPath, null));
    // System.out.println(ditaFolder);

    // Create DBF and ignore DTD
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/* w  w  w.j a v a  2 s .  c  o m*/
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    DocumentBuilder parser = dbf.newDocumentBuilder();
    Document document = parser.parse(tmpFileInWorkspaceDir.toFile());

    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // Use catalog
    // Path ditaCatalogPath = new Path("DITA-OT/schema/catalog.xml");
    // URL ditaCatalog = FileLocator.toFileURL(FileLocator.find(bundle, ditaCatalogPath, null));
    File ditaCatalogFile = new File(ditaFolder.getFile(), "schema/catalog.xml");
    // System.out.println(ditaCatalogFile);
    // System.out.println(ditaCatalogFile.exists());
    XMLCatalogResolver resolver = new XMLCatalogResolver(new String[] { ditaCatalogFile.getAbsolutePath() });
    schemaFactory.setResourceResolver(resolver);

    // load a WXS schema, represented by a Schema instance
    File ditaSchemaFile = new File(ditaFolder.getFile(), "schema/technicalContent/xsd/topic.xsd");

    // System.out.println(ditaSchemaFile);
    // System.out.println(ditaSchemaFile.exists());
    Source schemaFile = new StreamSource(ditaSchemaFile);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();

    DOMSource dom = new DOMSource(document);
    validator.validate(dom);
}

From source file:org.eclipse.smila.connectivity.framework.schema.internal.JaxbPluginContext.java

/**
 * Creates the validating unmarshaller./* w ww  .j ava2 s  .c  o m*/
 * 
 * @return the unmarshaller
 * 
 * @throws JAXBException
 *           the JAXB exception
 * @throws SchemaNotFoundException
 *           the index order schema not found exception
 */
public Unmarshaller createValidatingUnmarshaller() throws JAXBException, SchemaNotFoundException {
    initilize();
    assertNotNull(_context);
    final Unmarshaller unmarshaller = _context.createUnmarshaller();
    final SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    try {
        sf.setResourceResolver(new XSDContextURIResolver(sf.getResourceResolver()));
        final javax.xml.validation.Schema schema = sf
                .newSchema(Platform.getBundle(_id).getEntry(_plugIn.getSchemaLocation()));
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(final ValidationEvent ve) {
                if (ve.getSeverity() != ValidationEvent.WARNING) {
                    final ValidationEventLocator vel = ve.getLocator();
                    _log.error("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                            + ve.getMessage());
                    return false;
                }
                return true;
            }
        });
    } catch (final org.xml.sax.SAXException se) {
        throw new SchemaRuntimeException("Unable to validate due to following error.", se);
    }
    return unmarshaller;
}

From source file:org.jboss.cdi.tck.test.shrinkwrap.descriptors.ejb.EjbJarDescriptorBuilderTest.java

@Test
public void testDescriptorIsValid()
        throws ParserConfigurationException, SAXException, DescriptorExportException, IOException {

    EjbJarDescriptor ejbJarDescriptor = new EjbJarDescriptorBuilder().messageDrivenBeans(
            newMessageDriven("TestQueue", QueueMessageDrivenBean.class.getName())
                    .addActivationConfigProperty("acknowledgeMode", "Auto-acknowledge")
                    .addActivationConfigProperty("destinationType", "javax.jms.Queue")
                    .addActivationConfigProperty("destinationLookup", "test_queue"),
            newMessageDriven("TestTopic", TopicMessageDrivenBean.class.getName())
                    .addActivationConfigProperty("acknowledgeMode", "Auto-acknowledge")
                    .addActivationConfigProperty("destinationType", "javax.jms.Topic")
                    .addActivationConfigProperty("destinationLookup", "test_topic"))
            .build();/*w w  w.  j  av a2s  . c o  m*/

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

        @Override
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            try {
                if (systemId.startsWith("http")) {
                    // Ugly workaround for xml.xsd
                    systemId = StringUtils.substringAfterLast(systemId, "/");
                }
                return new Input(publicId, systemId,
                        new FileInputStream(new File("src/test/resources/xsd", systemId)));
            } catch (FileNotFoundException e) {
                throw new IllegalStateException();
            }
        }
    });
    schemaFactory.setErrorHandler(new ErrorHandler() {

        @Override
        public void warning(SAXParseException exception) throws SAXException {
        }

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

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

    Source schemaFile = new StreamSource(
            new FileInputStream(new File("src/test/resources/xsd", "ejb-jar_3_1.xsd")));
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    validator
            .validate(new StreamSource(new ByteArrayInputStream(ejbJarDescriptor.exportAsString().getBytes())));
}

From source file:org.mule.module.xml.filters.SchemaValidationFilter.java

public void initialise() throws InitialisationException {
    super.initialise();

    if (getSchemaObject() == null) {
        if (schemaLocations == null) {
            throw new InitialisationException(CoreMessages.objectIsNull("schemaLocations"), this);
        }/*from   www.  j  a  v a2  s . c o  m*/

        String[] split = StringUtils.splitAndTrim(schemaLocations, ",");
        Source[] schemas = new Source[split.length];
        for (int i = 0; i < split.length; i++) {
            String loc = split[i];
            InputStream schemaStream;
            try {
                schemaStream = loadSchemaStream(loc);
            } catch (IOException e) {
                throw new InitialisationException(e, this);
            }

            if (schemaStream == null) {
                throw new InitialisationException(CoreMessages.failedToLoad(loc), this);
            }

            schemas[i] = new StreamSource(schemaStream);
        }

        SchemaFactory schemaFactory = SchemaFactory.newInstance(getSchemaLanguage());

        if (logger.isInfoEnabled()) {
            logger.info("Schema factory implementation: " + schemaFactory);
        }

        if (this.errorHandler != null) {
            schemaFactory.setErrorHandler(this.errorHandler);
        }

        if (this.resourceResolver != null) {
            schemaFactory.setResourceResolver(this.resourceResolver);
        }

        Schema schema;
        try {
            schema = schemaFactory.newSchema(schemas);
        } catch (SAXException e) {
            throw new InitialisationException(e, this);
        }

        setSchemaObject(schema);
    }

    if (getSchemaObject() == null) {
        throw new InitialisationException(CoreMessages.objectIsNull("schemaObject"), this);
    }
}

From source file:org.ojbc.util.xml.XmlUtils.java

public static Document validateInstance(String rootXsdPath, Document docXmlToValidate,
        IEPDFullPathResourceResolver fullPathResolver, List<String> additionalSchemaRelativePaths)
        throws Exception {

    List<String> schemaPaths = new ArrayList<String>();
    schemaPaths.add(rootXsdPath);//from  w  ww  . j  a va2 s .  c  o  m
    schemaPaths.addAll(additionalSchemaRelativePaths);

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(fullPathResolver);

    Source[] sources = new Source[schemaPaths.size()];
    int i = 0;
    for (String path : schemaPaths) {
        sources[i++] = new StreamSource(XmlUtils.class.getClassLoader().getResourceAsStream(path));
    }

    Schema schema = schemaFactory.newSchema(sources);

    Validator v = schema.newValidator();

    try {
        v.validate(new DOMSource(docXmlToValidate));

    } catch (Exception e) {
        try {
            e.printStackTrace();
            System.err.println("FAILED Input Doc: \n");
            XmlUtils.printNode(docXmlToValidate);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        throw e;
    }
    return docXmlToValidate;
}

From source file:org.ojbc.util.xml.XmlUtils.java

/**
  * Validate a document against an IEPD. Note that this does not require the xsi namespace location attributes to be set in the instance.
  * /* w ww.ja  v a  2 s . c om*/
  * @param schemaPathList
  *            the paths to all schemas necessary to validate the instance; this is the equivalent of specifying these schemas in an xsi:schemaLocation attribute in the instance
  *                       
  * @param Never_Used_TODO_Remove 
  * 
  *            
  * @param rootSchemaFileName
  *            the name of the document/exchange schema
  * @param d
  *            the document to validate
  * @param iepdResourceResolver
  *            the resource resolver to use
  * @return the document that was validated
  * @throws Exception
  *             if the document is not valid
  */
public static void validateInstance(Document d, LSResourceResolver iepdResourceResolver,
        List<String> schemaPathList) throws SAXException, Exception {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(iepdResourceResolver);

    List<Source> sourceList = new ArrayList<Source>();

    for (String schemaPath : schemaPathList) {

        InputStream schemaInStream = XmlUtils.class.getClassLoader().getResourceAsStream(schemaPath);

        StreamSource schemaStreamSource = new StreamSource(schemaInStream);

        sourceList.add(schemaStreamSource);
    }

    Source[] schemaSourcesArray = sourceList.toArray(new Source[] {});

    try {
        Schema schema = schemaFactory.newSchema(schemaSourcesArray);

        Validator validator = schema.newValidator();

        validator.validate(new DOMSource(d));

    } catch (Exception e) {
        try {
            e.printStackTrace();
            System.err.println("Input document:");
            XmlUtils.printNode(d);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        throw e;
    }
}

From source file:org.openehealth.ipf.commons.xml.XsdValidator.java

protected synchronized void createSchema(String schemaResource) throws SAXException, IOException {
    if (!cachedSchemas.containsKey(schemaResource)) {
        // SchemaFactory is neither thread-safe nor reentrant
        SchemaFactory factory = SchemaFactory.newInstance(getSchemaLanguage());

        // Register resource resolver to resolve external XML schemas
        factory.setResourceResolver(lrri);
        Schema schema = factory.newSchema(schemaSource(schemaResource));
        cachedSchemas.put(schemaResource, schema);
    }/*from  w w  w  . j a  v a  2s  .  c o  m*/
}

From source file:org.raml.parser.visitor.SchemaCompiler.java

public Schema compile(String schema, String path) {
    Schema compiledSchema = null;
    String trimmedSchema = StringUtils.trimToEmpty(schema);
    if (trimmedSchema.startsWith("<") && trimmedSchema.endsWith(">")) {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        ContextPath actualContextPath = contextPath;
        if (path != null) {
            actualContextPath = new ContextPath(new IncludeInfo(path));
        }//from   w  ww . ja  v  a 2s  . com
        factory.setResourceResolver(new XsdResourceResolver(actualContextPath, resourceLoader));
        try {
            compiledSchema = factory.newSchema(new StreamSource(new StringReader(trimmedSchema)));
        } catch (Exception e) {
            //ignore exception as the error is detected by the validator
            // and here we cannot tell if the schema is intended for xml or not
        }
    }
    return compiledSchema;
}

From source file:org.roda.core.SchemasCacheLoader.java

@Override
public Optional<Schema> load(Pair<String, String> pair) throws Exception {
    String metadataType = pair.getFirst();
    String metadataTypeLowerCase = metadataType.toLowerCase();
    String metadataVersion = pair.getSecond();
    String metadataVersionLowerCase = "";
    if (metadataVersion != null) {
        metadataVersionLowerCase = metadataVersion.toLowerCase();
    }//w  w w .  j av a  2 s  . c  o m

    String schemaFileName;
    if (StringUtils.isNotEmpty(metadataVersion)) {
        schemaFileName = metadataTypeLowerCase + RodaConstants.METADATA_VERSION_SEPARATOR
                + metadataVersionLowerCase + ".xsd";
    } else {
        schemaFileName = metadataTypeLowerCase + ".xsd";
    }

    String schemaPath = RodaConstants.CORE_SCHEMAS_FOLDER + "/" + schemaFileName;

    InputStream schemaStream = RodaCoreFactory.getConfigurationFileAsStream(schemaPath);

    Schema xmlSchema = null;
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(RodaConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setResourceResolver(new ResourceResolver());
        xmlSchema = schemaFactory.newSchema(new StreamSource(schemaStream));
    } finally {
        RodaUtils.closeQuietly(schemaStream);
    }

    return Optional.ofNullable(xmlSchema);
}