Java Code Examples for javax.xml.validation.SchemaFactory#setResourceResolver()

The following examples show how to use javax.xml.validation.SchemaFactory#setResourceResolver() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Jaxb2Marshaller.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")  // on JDK 9
private Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException {
	if (logger.isDebugEnabled()) {
		logger.debug("Setting validation schema to " +
				StringUtils.arrayToCommaDelimitedString(this.schemaResources));
	}
	Assert.notEmpty(resources, "No resources given");
	Assert.hasLength(schemaLanguage, "No schema language provided");
	Source[] schemaSources = new Source[resources.length];
	XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
	xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
	for (int i = 0; i < resources.length; i++) {
		Resource resource = resources[i];
		Assert.isTrue(resource != null && resource.exists(), () -> "Resource does not exist: " + resource);
		InputSource inputSource = SaxResourceUtils.createInputSource(resource);
		schemaSources[i] = new SAXSource(xmlReader, inputSource);
	}
	SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
	if (this.schemaResourceResolver != null) {
		schemaFactory.setResourceResolver(this.schemaResourceResolver);
	}
	return schemaFactory.newSchema(schemaSources);
}
 
Example 2
Source File: WSDLInlineSchemaValidator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void validate(WSDLModel model, 
                      Source saxSource, 
                      XsdBasedValidator.Handler handler,
                      LSResourceResolver resolver) {
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        if (resolver != null) {
            sf.setResourceResolver(resolver);
        }
        sf.setErrorHandler(handler);

        if (saxSource == null) {
            return;
        }
        sf.newSchema(saxSource);
    } catch(SAXException sax) {
        //already processed by handler
    } catch(Exception ex) {
        handler.logValidationErrors(Validator.ResultType.ERROR, ex.getMessage());
    }
}
 
Example 3
Source File: XsdBasedValidator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Subclasses can use this to get a compiled schema object.
 * @param schemas Input stream of schemas.
 * @param lsResourceResolver  resolver can be supplied optionally. Otherwise pass null.
 * @return  Compiled Schema object.
 */
protected Schema getCompiledSchema(InputStream[] schemas,
        LSResourceResolver lsResourceResolver) {
    
    Schema schema = null;
    // Convert InputStream[] to StreamSource[]
    StreamSource[] schemaStreamSources = new StreamSource[schemas.length];
    for(int index1=0 ; index1<schemas.length ; index1++)
        schemaStreamSources[index1] = new StreamSource(schemas[index1]);
    
    // Create a compiled Schema object.
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(lsResourceResolver);
    try {
        schema = schemaFactory.newSchema(schemaStreamSources);            
    } catch(SAXException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "getCompiledSchema", ex);
    } 
    
    return schema;
}
 
Example 4
Source File: SchemaXsdBasedValidator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
  protected void validate(Model model, Schema schema, XsdBasedValidator.Handler handler) {
      try {
          SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
          CatalogModel cm = (CatalogModel) model.getModelSource().getLookup()
.lookup(CatalogModel.class);
   if (cm != null) {
              sf.setResourceResolver(cm);
          }
          sf.setErrorHandler(handler);
          Source saxSource = getSource(model, handler);
          if (saxSource == null) {
              return;
          }
          sf.newSchema(saxSource);
      } catch(SAXException sax) {
          //already processed by handler
      } catch(Exception ex) {
          handler.logValidationErrors(Validator.ResultType.ERROR, ex.getMessage());
      }
  }
 
Example 5
Source File: MetsUtils.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
/**
 *
 * Validates given document agains an XSD schema
 *
 * @param document
 * @param xsd
 * @return
 */
public static List<String> validateAgainstXSD(Document document, InputStream xsd) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setResourceResolver(MetsLSResolver.getInstance());
    Schema schema = factory.newSchema(new StreamSource(xsd));
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    DOMSource domSource = new DOMSource(document);
    StreamResult sResult = new StreamResult();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    sResult.setOutputStream(bos);
    transformer.transform(domSource, sResult);
    InputStream is = new ByteArrayInputStream(bos.toByteArray());
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setValidating(false);
    dbfactory.setNamespaceAware(true);
    dbfactory.setSchema(schema);
    DocumentBuilder documentBuilder = dbfactory.newDocumentBuilder();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler();
    documentBuilder.setErrorHandler(errorHandler);
    documentBuilder.parse(is);
    return errorHandler.getValidationErrors();
}
 
Example 6
Source File: JavaxXmlValidator.java    From iaf with Apache License 2.0 6 votes vote down vote up
/**
 * 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)}
 */
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() {
			@Override
			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;
}
 
Example 7
Source File: CatalogSupportBase.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void testValidation(boolean setUseCatalog, boolean useCatalog, String catalog,
        String xsd, LSResourceResolver resolver)
        throws Exception {

    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // use resolver or catalog if resolver = null
    if (resolver != null) {
        factory.setResourceResolver(resolver);
    }
    if (setUseCatalog) {
        factory.setFeature(XMLConstants.USE_CATALOG, useCatalog);
    }
    factory.setProperty(CatalogFeatures.Feature.FILES.getPropertyName(), catalog);

    Schema schema = factory.newSchema(new StreamSource(new StringReader(xsd)));
    success("XMLSchema.dtd and datatypes.dtd are resolved.");
}
 
Example 8
Source File: MCRXMLHelper.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * validates <code>doc</code> using XML Schema defined <code>schemaURI</code>
 * @param doc document to be validated
 * @param schemaURI URI of XML Schema document
 * @throws SAXException if validation fails
 * @throws IOException if resolving resources fails
 */
public static void validate(Document doc, String schemaURI) throws SAXException, IOException {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    sf.setResourceResolver(MCREntityResolver.instance());
    Schema schema;
    try {
        schema = sf.newSchema(MCRURIResolver.instance().resolve(schemaURI, null));
    } catch (TransformerException e) {
        Throwable cause = e.getCause();
        if (cause == null) {
            throw new IOException(e);
        }
        if (cause instanceof SAXException) {
            throw (SAXException) cause;
        }
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        throw new IOException(e);
    }
    Validator validator = schema.newValidator();
    validator.setResourceResolver(MCREntityResolver.instance());
    validator.validate(new JDOMSource(doc));
}
 
Example 9
Source File: SchemaLoader.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
public SchemaLoader(String schemaName) {
  try {

    Resource schemaResource = getSchema(schemaName);

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

    schema = schemaFactory.newSchema(new StreamSource(schemaResource.getInputStream()));
  } catch (SAXException | IOException e) {
    throw new RuntimeException("Could not load schemas", e);
  }
}
 
Example 10
Source File: ModsUtils.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
public static Schema getSchema() throws SAXException {
    if (MODS_SCHEMA == null) {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setResourceResolver(MetsLSResolver.getInstance());
        MODS_SCHEMA = schemaFactory.newSchema(ModsDefinition.class.getResource(MODS_SCHEMA_PATH));
    }
    return MODS_SCHEMA;
}
 
Example 11
Source File: AltoDatastream.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
public static List<Schema> getSchemasList() throws SAXException {
    List <Schema> schemas = new ArrayList<>();
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(MetsLSResolver.getInstance());
    schemas.add(schemaFactory.newSchema(AltoDatastream.class.getResource(ALTO_SCHEMA_PATH_20)));
    schemas.add(schemaFactory.newSchema(AltoDatastream.class.getResource(ALTO_SCHEMA_PATH_21)));
    schemas.add(schemaFactory.newSchema(AltoDatastream.class.getResource(ALTO_SCHEMA_PATH_30)));
    return schemas;
}
 
Example 12
Source File: XMLUtils.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static Validator getValidator() throws IOException, SAXException {
	if (validator == null) {
		SchemaFactory xmlSchemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		File schemafile = new File(schemaFilePathName);
		int idx = schemaFilePathName.lastIndexOf(schemafile.getName());
		String path = schemaFilePathName.substring(0, idx);
		xmlSchemaFactory.setResourceResolver(new XMLUtils().new ResourceResolver(path));
		Reader reader = new StringReader(convertSchemaToString(schemaFilePathName));
		Schema schema = xmlSchemaFactory.newSchema(new StreamSource(reader));
		validator = schema.newValidator();
	}
	return validator;
}
 
Example 13
Source File: RepositoryValidator.java    From fix-orchestra with Apache License 2.0 5 votes vote down vote up
private Document validateSchema(ErrorListener errorHandler)
    throws ParserConfigurationException, SAXException, IOException {
  // parse an XML document into a DOM tree
  final DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();
  parserFactory.setNamespaceAware(true);
  parserFactory.setXIncludeAware(true);
  final DocumentBuilder parser = parserFactory.newDocumentBuilder();
  final Document document = parser.parse(inputStream);

  // create a SchemaFactory capable of understanding WXS schemas
  final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  final ResourceResolver resourceResolver = new ResourceResolver();
  factory.setResourceResolver(resourceResolver);

  // load a WXS schema, represented by a Schema instance
  final URL resourceUrl = this.getClass().getClassLoader().getResource("xsd/repository.xsd");
  final String path = resourceUrl.getPath();
  final String parentPath = path.substring(0, path.lastIndexOf('/'));
  final URL baseUrl = new URL(resourceUrl.getProtocol(), null, parentPath);
  resourceResolver.setBaseUrl(baseUrl);

  final Source schemaFile = new StreamSource(resourceUrl.openStream());
  final Schema schema = factory.newSchema(schemaFile);

  // create a Validator instance, which can be used to validate an instance document
  final Validator validator = schema.newValidator();

  validator.setErrorHandler(errorHandler);

  // validate the DOM tree
  validator.validate(new DOMSource(document));
  return document;
}
 
Example 14
Source File: QuikitServlet.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private EntityResolver createEntityResolver( DocumentBuilder builder )
    throws SAXException
{
    QuikitResolver quickitResolver = new QuikitResolver( builder );
    SchemaFactory schemaFactory = SchemaFactory.newInstance( "http://www.w3.org/2001/XMLSchema" );
    schemaFactory.setResourceResolver( quickitResolver );
    return quickitResolver;
}
 
Example 15
Source File: SchemaLoader.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
public SchemaLoader(InputStream is) {
  try {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(this);

    schema = schemaFactory.newSchema(new StreamSource(is));
  } catch (SAXException e) {
    throw new RuntimeException("Could not load schemas", e);
  }
}
 
Example 16
Source File: SchemaCache.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public ValidatorHandler newValidator() {
    if (schema==null) {
        synchronized (this) {
            if (schema == null) {

                ResourceResolver resourceResolver = null;
                try (InputStream is = clazz.getResourceAsStream(resourceName)) {

                    StreamSource source = new StreamSource(is);
                    source.setSystemId(resourceName);
                    // do not disable secure processing - these are well-known schemas

                    SchemaFactory sf = XmlFactory.createSchemaFactory(XMLConstants.W3C_XML_SCHEMA_NS_URI, false);
                    SchemaFactory schemaFactory = allowExternalAccess(sf, "file", false);

                    if (createResolver) {
                        resourceResolver = new ResourceResolver(clazz);
                        schemaFactory.setResourceResolver(resourceResolver);
                    }
                    schema = schemaFactory.newSchema(source);

                } catch (IOException | SAXException e) {
                    InternalError ie = new InternalError(e.getMessage());
                    ie.initCause(e);
                    throw ie;
                } finally {
                    if (resourceResolver != null) resourceResolver.closeStreams();
                }
            }
        }
    }
    return schema.newValidatorHandler();
}
 
Example 17
Source File: CrossrefBuilder.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
static Schema getCrossrefSchema() throws SAXException {
    if (SCHEMA_CROSSREF == null) {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        factory.setResourceResolver(new SimpleLSResourceResolver()
                .base(CrossrefBuilder.class)
        );
        SCHEMA_CROSSREF = factory.newSchema(CrossrefBuilder.class.getResource(XSD_FILENAME));
    }
    return SCHEMA_CROSSREF;
}
 
Example 18
Source File: ParserUtils.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
private static Schema getSchema(String schemaPublicId)
        throws SAXException {

    Schema schema = schemaCache.get(schemaPublicId);
    if (schema == null) {
        synchronized (schemaCache) {
            schema = schemaCache.get(schemaPublicId);
            if (schema == null) {
                SchemaFactory schemaFactory = SchemaFactory.newInstance(
                    XMLConstants.W3C_XML_SCHEMA_NS_URI);
                schemaFactory.setResourceResolver(
                    new MyLSResourceResolver());
                schemaFactory.setErrorHandler(new MyErrorHandler());

                String path = schemaPublicId;
                if (schemaResourcePrefix != null) {
                    int index = schemaPublicId.lastIndexOf('/');
                    if (index != -1) {
                        path = schemaPublicId.substring(index+1);
                    }
                    path = schemaResourcePrefix + path;
                }

                InputStream input = null;
                if (isSchemaResourcePrefixFileUrl) {
                    try {
                        File f = new File(new URI(path));
                        if (f.exists()) { 
                            input = new FileInputStream(f);
                        }
                    } catch (Exception e) {
                        throw new SAXException(e);
                    }
                } else {
                    input = ParserUtils.class.getResourceAsStream(path);
                }

                if (input == null) {
      throw new SAXException(
                        Localizer.getMessage(
                            "jsp.error.internal.filenotfound",
                            schemaPublicId));
                }

                schema = schemaFactory.newSchema(new StreamSource(input));
                schemaCache.put(schemaPublicId, schema);
            }
        }
    }

    return schema;
}
 
Example 19
Source File: SchemaValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
private Schema createSchema(String[] schemas) throws SAXException, IOException {

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        sf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);

        SchemaResourceResolver resourceResolver = new SchemaResourceResolver();

        sf.setResourceResolver(resourceResolver);

        Source[] sources = new Source[schemas.length];

        for (int i = 0; i < schemas.length; i++) {
            // need to validate the schema file
            Document doc = docBuilder.parse(schemas[i]);

            DOMSource stream = new DOMSource(doc, schemas[i]);

            sources[i] = stream;
        }
        return sf.newSchema(sources);

    }
 
Example 20
Source File: CatalogTest.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
@Test(dataProvider = "supportLSResourceResolver")
public void supportLSResourceResolver(URI catalogFile, Source schemaSource) throws SAXException {

    CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogFile);

    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setResourceResolver(cr);
    Schema schema = factory.newSchema(schemaSource);

}