List of usage examples for javax.xml.validation SchemaFactory newInstance
public static SchemaFactory newInstance(String schemaLanguage)
From source file:TypeInfoWriter.java
/** Main program entry point. */ public static void main(String[] argv) { // is there anything to do? if (argv.length == 0) { printUsage();/*from w w w . j ava 2s . c o m*/ System.exit(1); } // variables XMLReader parser = null; Vector schemas = null; Vector instances = null; String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; // process arguments for (int i = 0; i < argv.length; ++i) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("l")) { // get schema language name if (++i == argv.length) { System.err.println("error: Missing argument to -l option."); } else { schemaLanguage = argv[i]; } continue; } if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); continue; } String parserName = argv[i]; // create parser try { parser = XMLReaderFactory.createXMLReader(parserName); } catch (Exception e) { try { Parser sax1Parser = ParserFactory.makeParser(parserName); parser = new ParserAdapter(sax1Parser); System.err.println("warning: Features and properties not supported on SAX1 parsers."); } catch (Exception ex) { parser = null; System.err.println("error: Unable to instantiate parser (" + parserName + ")"); e.printStackTrace(System.err); System.exit(1); } } continue; } if (arg.equals("-a")) { // process -a: schema documents if (schemas == null) { schemas = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { schemas.add(arg); ++i; } continue; } if (arg.equals("-i")) { // process -i: instance documents if (instances == null) { instances = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { instances.add(arg); ++i; } continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("ga")) { generateSyntheticAnnotations = option.equals("ga"); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option (" + option + ")."); continue; } } // use default parser? if (parser == null) { // create parser try { parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME); } catch (Exception e) { System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")"); e.printStackTrace(System.err); System.exit(1); } } try { // Create writer TypeInfoWriter writer = new TypeInfoWriter(); writer.setOutput(System.out, "UTF8"); // Create SchemaFactory and configure SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage); factory.setErrorHandler(writer); try { factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } // Build Schema from sources Schema schema; if (schemas != null && schemas.size() > 0) { final int length = schemas.size(); StreamSource[] sources = new StreamSource[length]; for (int j = 0; j < length; ++j) { sources[j] = new StreamSource((String) schemas.elementAt(j)); } schema = factory.newSchema(sources); } else { schema = factory.newSchema(); } // Setup validator and parser ValidatorHandler validator = schema.newValidatorHandler(); parser.setContentHandler(validator); if (validator instanceof DTDHandler) { parser.setDTDHandler((DTDHandler) validator); } parser.setErrorHandler(writer); validator.setContentHandler(writer); validator.setErrorHandler(writer); writer.setTypeInfoProvider(validator.getTypeInfoProvider()); try { validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } // Validate instance documents and print type information if (instances != null && instances.size() > 0) { final int length = instances.size(); for (int j = 0; j < length; ++j) { parser.parse((String) instances.elementAt(j)); } } } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException) e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } }
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);/*from w ww .j av a2 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:com.adaptris.core.transform.XmlSchemaValidator.java
@Override public void init() throws CoreException { try {/*from www. jav a2 s .co m*/ if (StringUtils.isBlank(getSchema()) && StringUtils.isBlank(getSchemaMetadataKey())) { throw new CoreException("metadata-key & schema are blank"); } LifecycleHelper.init(getSchemaCache()); schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); } catch (Exception e) { throw ExceptionHelper.wrapCoreException(e); } }
From source file:io.inkstand.scribble.jcr.rules.util.XMLContentLoaderTest.java
@Test(expected = AssertionError.class) public void testLoadContent_validating_invalidResource() throws Exception { // prepare/* www.jav a2s .c om*/ final URL resource = getClass().getResource("XMLContentLoaderTest_inkstandJcrImport_v1-0_invalid.xml"); final Session actSession = repository.getAdminSession(); final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema = schemaFactory.newSchema(getClass().getResource("inkstandJcrImport_v1-0.xsd")); // act subject.setSchema(schema); subject.loadContent(actSession, resource); }
From source file:alter.vitro.vgw.service.query.SimpleQueryHandler.java
/** * * Constructor method (for handling responses to queries) * TODO: resolve this obscurity with the two constructors (for the user and gw sides) *///from w ww . j av a2 s . c o m // TODO: maybe make this into singleton private SimpleQueryHandler() { myPeerId = null; // not needed myPeerName = null; // not needed myPipeDataProducer = null; // not needed myPipeDataSession = null; // not needed this.myDCon = null; if (schema == null) { try { schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new File( "src/main/java/alter/vitro/vgw/service/query/xmlmessages/aggrquery/PublicQueryAggrMsg.xsd")); } catch (SAXException saxEx) { logger.error("Exception while initializing schema from PublicQueryAggrMsg.xsd", saxEx); } } if (enDisFromVSPschema == null) { try { enDisFromVSPschema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(new File( "src/main/java/alter/vitro/vgw/service/query/xmlmessages/enablednodessynch/fromvsp/fromvsp.xsd")); } catch (SAXException saxEx) { logger.error("Exception while initializing schema (enable synch) from fromvsp.xsd", saxEx); } } if (equivSynchFromVSPschema == null) { try { equivSynchFromVSPschema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(new File( "src/main/java/alter/vitro/vgw/service/query/xmlmessages/equivlistsynch/fromvsp/fromvsp.xsd")); } catch (SAXException saxEx) { logger.error("Exception while initializing schema (equiv list synch) from fromvsp.xsd", saxEx); } } }
From source file:io.tourniquet.junit.jcr.rules.util.XMLContentLoaderTest.java
@Test(expected = AssertionError.class) public void testLoadContent_validating_invalidResource() throws Exception { // prepare// w ww.ja v a 2 s. com final URL resource = getClass().getResource("XMLContentLoaderTest_tourniquetJcrImport_v1-0_invalid.xml"); final Session actSession = repository.getAdminSession(); final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema = schemaFactory.newSchema(resolver.resolve("/tourniquetJcrImport_v1-0.xsd")); // act subject.setSchema(schema); subject.loadContent(actSession, resource); }
From source file:ca.uhn.fhir.validation.SchemaBaseValidator.java
private Schema loadSchema(String theVersion, String theSchemaName) { String key = theVersion + "-" + theSchemaName; synchronized (myKeyToSchema) { Schema schema = myKeyToSchema.get(key); if (schema != null) { return schema; }//from www.j a va 2 s. co m Source baseSource = loadXml(null, theSchemaName); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setResourceResolver(new MyResourceResolver()); try { try { /* * See https://github.com/jamesagnew/hapi-fhir/issues/339 * https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing */ schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); } catch (SAXNotRecognizedException snex) { ourLog.warn("Jaxp 1.5 Support not found.", snex); } schema = schemaFactory.newSchema(new Source[] { baseSource }); } catch (SAXException e) { throw new ConfigurationException("Could not load/parse schema file: " + theSchemaName, e); } myKeyToSchema.put(key, schema); return schema; } }
From source file:edu.lternet.pasta.common.XmlUtility.java
/** * Returns the provided XML string as a schema. * * @param xmlString an XML schema.//ww w. j ava2s. co m * * @return a schema object that corresponds to the provided string. */ public static Schema xmlStringToSchema(String xmlString) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setErrorHandler(new XmlParsingErrorHandler(xmlString)); StreamSource source = new StreamSource(new StringReader(xmlString)); try { return factory.newSchema(source); } catch (SAXException e) { throw new IllegalStateException(e); // shouldn't be reached } }
From source file:dk.netarkivet.common.utils.XmlUtils.java
/** * Validate that the settings xml files conforms to the XSD. * * @param xsdFile Schema to check settings against. * @throws ArgumentNotValid if unable to validate the settings files * @throws IOFailure If unable to read the settings files and/or * the xsd file./*from w w w .jav a2s . co m*/ */ public static void validateWithXSD(File xsdFile) { ArgumentNotValid.checkNotNull(xsdFile, "File xsdFile"); List<File> settingsFiles = Settings.getSettingsFiles(); for (File settingsFile : settingsFiles) { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder parser = builderFactory.newDocumentBuilder(); org.w3c.dom.Document document = parser.parse(settingsFile); // create a SchemaFactory capable of understanding WXS schemas SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // load a WXS schema, represented by a Schema instance Source schemaFile = new StreamSource(xsdFile); Schema schema = factory.newSchema(schemaFile); // create a Validator instance, which can be used to validate an // instance document Validator validator = schema.newValidator(); // validate the DOM tree try { validator.validate(new DOMSource(document)); } catch (SAXException e) { // instance document is invalid! final String msg = "Settings file '" + settingsFile + "' does not validate using '" + xsdFile + "'"; log.warn(msg, e); throw new ArgumentNotValid(msg, e); } } catch (IOException e) { throw new IOFailure("Error while validating: ", e); } catch (ParserConfigurationException e) { final String msg = "Error validating settings file '" + settingsFile + "'"; log.warn(msg, e); throw new ArgumentNotValid(msg, e); } catch (SAXException e) { final String msg = "Error validating settings file '" + settingsFile + "'"; log.warn(msg, e); throw new ArgumentNotValid(msg, e); } } }
From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.util.QCliveXMLSchemaValidator.java
protected Boolean validateSchema(final List<Source> schemaSourceList, final Document document, final File xmlFile, final QcContext context) throws SAXException, IOException { final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // instantiate the schema Schema schema = factory.newSchema(schemaSourceList.toArray(new Source[] {})); // now validate the file against the schema // note: supposedly there is a way to just let the XML document figure // out its own schema based on what is referred to, but // I could not get that to work, which is why I am looking for the // schema in the attribute final DOMSource source = new DOMSource(document); final Validator validator = schema.newValidator(); // wow this looks dumb, but isValid has to be final to be accessed from // within an inner class // and this was IDEA's solution to the problem: make it an array and set // the first element of the array final boolean[] isValid = new boolean[] { true }; // add error handler that will add validation errors and warnings // directly to the QcContext object validator.setErrorHandler(new ErrorHandler() { public void warning(final SAXParseException exception) { context.addWarning(new StringBuilder().append(xmlFile.getName()).append(": ") .append(exception.getMessage()).toString()); }/*from w w w. j av a2 s . c om*/ public void error(final SAXParseException exception) { context.addError(MessageFormat.format(MessagePropertyType.XML_FILE_PROCESSING_ERROR, xmlFile.getName(), new StringBuilder().append(xmlFile.getName()).append(": ") .append(exception.getMessage()).toString())); isValid[0] = false; } public void fatalError(final SAXParseException exception) throws SAXException { context.getArchive().setDeployStatus(Archive.STATUS_INVALID); throw exception; } }); validator.validate(source); return isValid[0]; }