List of usage examples for javax.xml.validation Validator setErrorHandler
public abstract void setErrorHandler(ErrorHandler errorHandler);
From source file:Main.java
public static void main(String[] args) throws Exception { Customer customer = new Customer(); customer.setName("abcabcabcabcabcabcabc"); customer.getPhoneNumbers().add(new PhoneNumber()); customer.getPhoneNumbers().add(new PhoneNumber()); customer.getPhoneNumbers().add(new PhoneNumber()); customer.getPhoneNumbers().add(new PhoneNumber()); customer.getPhoneNumbers().add(new PhoneNumber()); customer.getPhoneNumbers().add(new PhoneNumber()); customer.getPhoneNumbers().add(new PhoneNumber()); customer.getPhoneNumbers().add(new PhoneNumber()); customer.getPhoneNumbers().add(new PhoneNumber()); customer.getPhoneNumbers().add(new PhoneNumber()); JAXBContext jc = JAXBContext.newInstance(Customer.class); JAXBSource source = new JAXBSource(jc, customer); SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new File("customer.xsd")); Validator validator = schema.newValidator(); validator.setErrorHandler(new MyErrorHandler()); validator.validate(source);/*from w w w .ja va2 s .c o m*/ }
From source file:InlineSchemaValidator.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 a v a 2s . com*/ System.exit(1); } // variables Vector schemas = null; Vector instances = null; HashMap prefixMappings = null; HashMap uriMappings = null; String docURI = argv[argv.length - 1]; String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE; int repetition = DEFAULT_REPETITION; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; boolean memoryUsage = DEFAULT_MEMORY_USAGE; // process arguments for (int i = 0; i < argv.length - 1; ++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("x")) { if (++i == argv.length) { System.err.println("error: Missing argument to -x option."); continue; } String number = argv[i]; try { int value = Integer.parseInt(number); if (value < 1) { System.err.println("error: Repetition must be at least 1."); continue; } repetition = value; } catch (NumberFormatException e) { System.err.println("error: invalid number (" + number + ")."); } continue; } if (arg.equals("-a")) { // process -a: xpath expressions for schemas if (schemas == null) { schemas = new Vector(); } while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) { schemas.add(arg); ++i; } continue; } if (arg.equals("-i")) { // process -i: xpath expressions for instance documents if (instances == null) { instances = new Vector(); } while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) { instances.add(arg); ++i; } continue; } if (arg.equals("-nm")) { String prefix; String uri; while (i + 2 < argv.length - 1 && !(prefix = argv[i + 1]).startsWith("-") && !(uri = argv[i + 2]).startsWith("-")) { if (prefixMappings == null) { prefixMappings = new HashMap(); uriMappings = new HashMap(); } prefixMappings.put(prefix, uri); HashSet prefixes = (HashSet) uriMappings.get(uri); if (prefixes == null) { prefixes = new HashSet(); uriMappings.put(uri, prefixes); } prefixes.add(prefix); i += 2; } 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.equalsIgnoreCase("m")) { memoryUsage = option.equals("m"); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option (" + option + ")."); continue; } } try { // Create new instance of inline schema validator. InlineSchemaValidator inlineSchemaValidator = new InlineSchemaValidator(prefixMappings, uriMappings); // Parse document containing schemas and validation roots DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(inlineSchemaValidator); Document doc = db.parse(docURI); // Create XPath factory for selecting schema and validation roots XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); xpath.setNamespaceContext(inlineSchemaValidator); // Select schema roots from the DOM NodeList[] schemaNodes = new NodeList[schemas != null ? schemas.size() : 0]; for (int i = 0; i < schemaNodes.length; ++i) { XPathExpression xpathSchema = xpath.compile((String) schemas.elementAt(i)); schemaNodes[i] = (NodeList) xpathSchema.evaluate(doc, XPathConstants.NODESET); } // Select validation roots from the DOM NodeList[] instanceNodes = new NodeList[instances != null ? instances.size() : 0]; for (int i = 0; i < instanceNodes.length; ++i) { XPathExpression xpathInstance = xpath.compile((String) instances.elementAt(i)); instanceNodes[i] = (NodeList) xpathInstance.evaluate(doc, XPathConstants.NODESET); } // Create SchemaFactory and configure SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage); factory.setErrorHandler(inlineSchemaValidator); 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; { DOMSource[] sources; int size = 0; for (int i = 0; i < schemaNodes.length; ++i) { size += schemaNodes[i].getLength(); } sources = new DOMSource[size]; if (size == 0) { schema = factory.newSchema(); } else { int count = 0; for (int i = 0; i < schemaNodes.length; ++i) { NodeList nodeList = schemaNodes[i]; int nodeListLength = nodeList.getLength(); for (int j = 0; j < nodeListLength; ++j) { sources[count++] = new DOMSource(nodeList.item(j)); } } schema = factory.newSchema(sources); } } // Setup validator and input source. Validator validator = schema.newValidator(); validator.setErrorHandler(inlineSchemaValidator); 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 for (int i = 0; i < instanceNodes.length; ++i) { NodeList nodeList = instanceNodes[i]; int nodeListLength = nodeList.getLength(); for (int j = 0; j < nodeListLength; ++j) { DOMSource source = new DOMSource(nodeList.item(j)); source.setSystemId(docURI); inlineSchemaValidator.validate(validator, source, docURI, repetition, memoryUsage); } } } 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.jkoolcloud.tnt4j.streams.configure.sax.StreamsConfigSAXParser.java
/** * Validates configuration XML against XML defined XSD schema. * * @param config/*from ww w . j ava2 s . co m*/ * {@link InputStream} to get configuration data from * @return map of found validation errors * @throws SAXException * if there was an error parsing the configuration * @throws IOException * if there is an error reading the configuration data */ public static Map<OpLevel, List<SAXParseException>> validate(InputStream config) throws SAXException, IOException { final Map<OpLevel, List<SAXParseException>> validationErrors = new HashMap<>(); try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(); Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { handleValidationError(OpLevel.WARNING, exception); } @Override public void error(SAXParseException exception) throws SAXException { handleValidationError(OpLevel.ERROR, exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { handleValidationError(OpLevel.FATAL, exception); } private void handleValidationError(OpLevel level, SAXParseException exception) { List<SAXParseException> lErrorsList = validationErrors.get(level); if (lErrorsList == null) { lErrorsList = new ArrayList<>(); validationErrors.put(level, lErrorsList); } lErrorsList.add(exception); } }); validator.validate(new StreamSource(config)); } finally { if (config.markSupported()) { config.reset(); } } return validationErrors; }
From source file:Main.java
/** * Check whether a DOM tree is valid according to a schema. Example of * usage:// w w w.j av a 2 s. co m * <pre> * Element fragment = ...; * SchemaFactory f = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); * Schema s = f.newSchema(This.class.getResource("something.xsd")); * try { * XMLUtil.validate(fragment, s); * // valid * } catch (SAXException x) { * // invalid * } * </pre> * * @param data a DOM tree * @param schema a parsed schema * @throws SAXException if validation failed * @since org.openide.util 7.17 */ public static void validate(Element data, Schema schema) throws SAXException { Validator v = schema.newValidator(); final SAXException[] error = { null }; v.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException x) throws SAXException { } @Override public void error(SAXParseException x) throws SAXException { // Just rethrowing it is bad because it will also print it to stderr. error[0] = x; } @Override public void fatalError(SAXParseException x) throws SAXException { error[0] = x; } }); try { v.validate(new DOMSource(fixupAttrs(data))); } catch (IOException x) { assert false : x; } if (error[0] != null) { throw error[0]; } }
From source file:com.maxl.java.aips2sqlite.Aips2Sqlite.java
static List<MedicalInformations.MedicalInformation> readAipsFile() { List<MedicalInformations.MedicalInformation> med_list = null; try {/* ww w. j a v a 2 s . c o m*/ JAXBContext context = JAXBContext.newInstance(MedicalInformations.class); // Validation SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new File(Constants.FILE_MEDICAL_INFOS_XSD)); Validator validator = schema.newValidator(); validator.setErrorHandler(new MyErrorHandler()); // Marshaller /* * Marshaller ma = context.createMarshaller(); * ma.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); * MedicalInformations medi_infos = new MedicalInformations(); * ma.marshal(medi_infos, System.out); */ // Unmarshaller long startTime = System.currentTimeMillis(); if (CmlOptions.SHOW_LOGS) System.out.print("- Unmarshalling Swissmedic xml... "); FileInputStream fis = new FileInputStream(new File(Constants.FILE_MEDICAL_INFOS_XML)); Unmarshaller um = context.createUnmarshaller(); MedicalInformations med_infos = (MedicalInformations) um.unmarshal(fis); med_list = med_infos.getMedicalInformation(); long stopTime = System.currentTimeMillis(); if (CmlOptions.SHOW_LOGS) System.out.println(med_list.size() + " medis in " + (stopTime - startTime) / 1000.0f + " sec"); } catch (IOException e) { e.printStackTrace(); } catch (JAXBException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return med_list; }
From source file:eu.delving.x3ml.X3MLEngine.java
public static List<String> validateStream(InputStream inputStream) throws SAXException, IOException { Schema schema = schemaFactory().newSchema(new StreamSource(inputStream("x3ml_v1.0.xsd"))); Validator validator = schema.newValidator(); final List<String> errors = new ArrayList<String>(); validator.setErrorHandler(new ErrorHandler() { @Override/* ww w. j a va 2s . c om*/ public void warning(SAXParseException exception) throws SAXException { errors.add(errorMessage(exception)); } @Override public void error(SAXParseException exception) throws SAXException { errors.add(errorMessage(exception)); } @Override public void fatalError(SAXParseException exception) throws SAXException { errors.add(errorMessage(exception)); } }); StreamSource source = new StreamSource(inputStream); validator.validate(source); return errors; }
From source file:com.impetus.kundera.loader.PersistenceXMLLoader.java
/** * Validates an xml object graph against its schema. Therefore it reads the * version from the root tag and tries to load the related xsd file from the * classpath./* w w w . j av a 2 s. c om*/ * * @param xmlRootNode * root xml node of the document to validate * @throws InvalidConfigurationException * if the validation could not be performed or the xml graph is * invalid against the schema */ private static void validateDocumentAgainstSchema(final Document xmlRootNode) throws InvalidConfigurationException { final Element rootElement = xmlRootNode.getDocumentElement(); final String version = rootElement.getAttribute("version"); String schemaFileName = "persistence_" + version.replace(".", "_") + ".xsd"; try { final List validationErrors = new ArrayList(); final String schemaLanguage = XMLConstants.W3C_XML_SCHEMA_NS_URI; final StreamSource streamSource = new StreamSource(getStreamFromClasspath(schemaFileName)); final Schema schemaDefinition = SchemaFactory.newInstance(schemaLanguage).newSchema(streamSource); final Validator schemaValidator = schemaDefinition.newValidator(); schemaValidator.setErrorHandler(new ErrorLogger("XML InputStream", validationErrors)); schemaValidator.validate(new DOMSource(xmlRootNode)); if (!validationErrors.isEmpty()) { final String exceptionText = "persistence.xml is not conform against the supported schema definitions."; throw new InvalidConfigurationException(exceptionText); } } catch (SAXException e) { final String exceptionText = "Error validating persistence.xml against schema defintion, caused by: "; throw new InvalidConfigurationException(exceptionText, e); } catch (IOException e) { final String exceptionText = "Error opening xsd schema file. The given persistence.xml descriptor version " + version + " might not be supported yet."; throw new InvalidConfigurationException(exceptionText, e); } }
From source file:com.maxl.java.aips2xml.Aips2Xml.java
static List<MedicalInformations.MedicalInformation> readAipsFile() { List<MedicalInformations.MedicalInformation> med_list = null; try {//from ww w . j av a 2s . co m JAXBContext context = JAXBContext.newInstance(MedicalInformations.class); // Validation SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new File(FILE_MEDICAL_INFOS_XSD)); Validator validator = schema.newValidator(); validator.setErrorHandler(new MyErrorHandler()); // Marshaller /* Marshaller ma = context.createMarshaller(); ma.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); MedicalInformations medi_infos = new MedicalInformations(); ma.marshal(medi_infos, System.out); */ // Unmarshaller long startTime = System.currentTimeMillis(); if (SHOW_LOGS) System.out.print("- Unmarshalling Swissmedic xml ... "); FileInputStream fis = new FileInputStream(new File(FILE_MEDICAL_INFOS_XML)); Unmarshaller um = context.createUnmarshaller(); MedicalInformations med_infos = (MedicalInformations) um.unmarshal(fis); med_list = med_infos.getMedicalInformation(); long stopTime = System.currentTimeMillis(); if (SHOW_LOGS) System.out.println(med_list.size() + " medis in " + (stopTime - startTime) / 1000.0f + " sec"); } catch (IOException e) { e.printStackTrace(); } catch (JAXBException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return med_list; }
From source file:com.predic8.membrane.core.interceptor.schemavalidation.XMLSchemaValidator.java
@Override protected List<Validator> createValidators() throws Exception { SchemaFactory sf = SchemaFactory.newInstance(Constants.XSD_NS); sf.setResourceResolver(resourceResolver.toLSResourceResolver()); List<Validator> validators = new ArrayList<Validator>(); log.debug("Creating validator for schema: " + location); StreamSource ss = new StreamSource(resourceResolver.resolve(location)); ss.setSystemId(location);/*from w ww .ja v a 2s . c o m*/ Validator validator = sf.newSchema(ss).newValidator(); validator.setResourceResolver(resourceResolver.toLSResourceResolver()); validator.setErrorHandler(new SchemaValidatorErrorHandler()); validators.add(validator); return validators; }
From source file:com.amalto.core.schema.validation.XmlSchemaValidator.java
public void validate(Element element) throws ValidateException { javax.xml.validation.Validator validator = getValidator(); SAXErrorHandler errorHandler = new SAXErrorHandler(); try {//from w ww . j a va 2 s. com validator.setErrorHandler(errorHandler); validator.validate(new DOMSource(element)); } catch (Exception e) { // All errors are expected to be handled by the error handler. throw new RuntimeException("Unexpected validation issue.", e); } String errors = errorHandler.getErrors(); if (!errors.isEmpty()) { throw new ValidateException(errors); } next.validate(element); }