/** * 利用xsd验证xml * @param xsdFile xsdFile * @param xmlInput xmlInput * @throws SAXException SAXException * @throws IOException IOException */ public static void validation(String xsdFile, InputStream xmlInput) throws SAXException, IOException { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL xsdURL = Validation.class.getClassLoader().getResource(xsdFile); if(xsdURL != null) { Schema schema = factory.newSchema(xsdURL); Validator validator = schema.newValidator(); // validator.setErrorHandler(new AutoErrorHandler()); Source source = new StreamSource(xmlInput); try(OutputStream resultOut = new FileOutputStream(new File(PathUtil.getRootDir(), xsdFile + ".xml"))) { Result result = new StreamResult(resultOut); validator.validate(source, result); } } else { throw new FileNotFoundException(String.format("can not found xsd file [%s] from classpath.", xsdFile)); } }
/** * Validates XML against XSD schema * * @param xml XML in which the element is being searched * @param schemas XSD schemas against which the XML is validated * @throws SAXException if the XSD schema is invalid * @throws IOException if the XML at the specified path is missing */ public static void validateWithXMLSchema(InputStream xml, InputStream[] schemas) throws IOException, SAXException { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source[] sources = new Source[schemas.length]; for (int i = 0; i < schemas.length; i++) { sources[i] = new StreamSource(schemas[i]); } Schema schema = factory.newSchema(sources); Validator validator = schema.newValidator(); try { validator.validate(new StreamSource(xml)); } catch (SAXException e) { throw new GeneralException(e); } }
@Override public void define(Context context) { try ( Reader xmlStreamValidationReader = xmlFactory.newRulesXmlReader(); Reader xmlStreamRulesDefinitionReader = xmlFactory.newRulesXmlReader(); Reader xsdStreamReader = xmlFactory.newRulesXsdReader() ) { StreamSource xsdStreamSource = new StreamSource(xsdStreamReader); StreamSource xmlStreamSource = new StreamSource(xmlStreamValidationReader); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(xsdStreamSource); Validator validator = schema.newValidator(); validator.validate(xmlStreamSource); NewRepository repo = context.createRepository(repositoryKey(), "php").setName(repositoryName()); RulesDefinitionXmlLoader xmlLoader = new RulesDefinitionXmlLoader(); xmlLoader.load(repo, xmlStreamRulesDefinitionReader); repo.done(); } catch (Exception e) { throw new IllegalStateException("rules.xml not found or invalid", e); } }
@Test public void rulesXmlIsValid() { RulesXmlReaderFactory xmlFactory = new RulesXmlReaderFactory(); try (Reader xmlReader = xmlFactory.newRulesXmlReader(); Reader xsdReader = xmlFactory.newRulesXsdReader()) { StreamSource xsdStreamSource = new StreamSource(xsdReader); StreamSource xmlStreamSource = new StreamSource(xmlReader); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(xsdStreamSource); Validator validator = schema.newValidator(); validator.validate(xmlStreamSource); } catch (Exception e) { fail("rules.xml does not conform to schema!"); } }
/** * Helper method that returns a validator for our XSD, or null if the current Java * implementation can't process XSD schemas. * * @param version The version of the XML Schema. * See {@link SdkStatsConstants#getXsdStream(int)} */ private Validator getValidator(int version) throws SAXException { InputStream xsdStream = SdkStatsConstants.getXsdStream(version); try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); if (factory == null) { return null; } // This may throw a SAX Exception if the schema itself is not a valid XSD Schema schema = factory.newSchema(new StreamSource(xsdStream)); Validator validator = schema == null ? null : schema.newValidator(); return validator; } finally { if (xsdStream != null) { try { xsdStream.close(); } catch (IOException ignore) {} } } }
/** * Helper method that returns a validator for our XSD, or null if the current Java * implementation can't process XSD schemas. * * @param version The version of the XML Schema. * See {@link SdkAddonsListConstants#getXsdStream(int)} */ private Validator getValidator(int version) throws SAXException { InputStream xsdStream = SdkAddonsListConstants.getXsdStream(version); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); if (factory == null) { return null; } // This may throw a SAX Exception if the schema itself is not a valid XSD Schema schema = factory.newSchema(new StreamSource(xsdStream)); Validator validator = schema == null ? null : schema.newValidator(); return validator; }
protected void validateXSD(Document signedDoc) throws SAXException, IOException { NodeList nodeList = signedDoc.getElementsByTagNameNS(RedactableXMLSignature.XML_NAMESPACE, "Signature"); assertEquals(1, nodeList.getLength()); Node signature = nodeList.item(0); NodeList childNodes = signature.getChildNodes(); int actualNodes = 0; for (int i = 0; i < childNodes.getLength(); i++) { if (childNodes.item(i).getNodeType() == Node.ELEMENT_NODE) { ++actualNodes; } } assertEquals(3, actualNodes); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new File("xmlrss_schema.xsd")); Validator validator = schema.newValidator(); validator.validate(new DOMSource(signature)); }
public void testStringTemplate() throws Exception { StringTemplate t1 = StringTemplate.template("model.goods.goodsAmount") .add("%goods%", "model.goods.food.name") .addName("%amount%", "100"); StringTemplate t2 = StringTemplate.template("model.goods.goodsAmount") .addAmount("%amount%", 50) .addStringTemplate("%goods%", t1); Game game = getGame(); Player player = game.getPlayerByNationId("model.nation.dutch"); try { Validator validator = buildValidator("schema/data/data-stringTemplate.xsd"); validator.validate(buildSource(t2)); } catch (SAXParseException e){ String errMsg = e.getMessage() + " at line=" + e.getLineNumber() + " column=" + e.getColumnNumber(); fail(errMsg); } }
public void testSpecification() throws Exception { try { String filename = "test/data/specification.xml"; Validator validator = buildValidator("schema/specification-schema.xsd"); FileOutputStream fos = new FileOutputStream(filename); try (FreeColXMLWriter xw = new FreeColXMLWriter(fos, null, false)) { spec().toXML(xw); } catch (IOException ioe) { fail(ioe.getMessage()); } validator.validate(new StreamSource(new FileReader(filename))); } catch (SAXParseException e) { String errMsg = e.getMessage() + " at line=" + e.getLineNumber() + " column=" + e.getColumnNumber(); fail(errMsg); } }
@SneakyThrows public void validateXml(String xsdPath, boolean namespaceAware, String schemaLanguage, String pageBody) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(namespaceAware); DocumentBuilder builder = factory.newDocumentBuilder(); org.w3c.dom.Document document = builder.parse(new InputSource(new StringReader(pageBody))); SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage); Source schemaSource = new StreamSource(getClass().getResourceAsStream(xsdPath)); Schema schema = schemaFactory.newSchema(schemaSource); Validator validator = schema.newValidator(); Source source = new DOMSource(document); validator.setErrorHandler(new XmlErrorHandler()); validator.validate(source); }
private boolean validateXML(InputStream xml, InputStream xsd){ try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); javax.xml.validation.Schema schema = factory.newSchema(new StreamSource(xsd)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xml)); return true; } catch( SAXException| IOException ex) { //MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error", Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage()); MessageBox dialog = new MessageBox(Display.getCurrent().getActiveShell(), SWT.ICON_ERROR | SWT.OK); dialog.setText(Messages.ERROR); dialog.setMessage(Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage()); logger.error(Messages.IMPORT_XML_FORMAT_ERROR); return false; } }
private boolean validateXML(InputStream xml, InputStream xsd){ try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); javax.xml.validation.Schema schema = factory.newSchema(new StreamSource(xsd)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xml)); return true; } catch( SAXException| IOException ex) { MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error", Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage()); logger.error(Messages.IMPORT_XML_FORMAT_ERROR); return false; } }
public static boolean validateDAT(File xmlFile) { try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new File(DATschemaURL.getPath())); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xmlFile)); } catch (IOException | SAXException e) { System.out.println("Exception: " + e.getMessage()); return false; } return true; }
@Test public void testSecureProcessingFeaturePropagationAndReset() throws Exception { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); boolean value; value = factory.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING); //default is true for JDK //assertFalse("Default value of feature on SchemaFactory should have been false.", value); assertTrue("Default value of feature on SchemaFactory should have been false.", value); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Schema schema = makeSchema(factory, null); Validator validator = schema.newValidator(); value = validator.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING); assertTrue("Value of feature on Validator should have been true.", value); validator.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false); value = validator.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING); assertFalse("Value of feature on Validator should have been false.", value); validator.reset(); value = validator.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING); assertTrue("After reset, value of feature on Validator should be true.", value); }
@Test public final void testStream() { try { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schemaGrammar = schemaFactory.newSchema(new File(getClass().getResource("gMonths.xsd").getFile())); Validator schemaValidator = schemaGrammar.newValidator(); Source xmlSource = new javax.xml.transform.stream.StreamSource(new File(CR6708840Test.class.getResource("gMonths.xml").toURI())); schemaValidator.validate(xmlSource); } catch (NullPointerException ne) { Assert.fail("NullPointerException when result is not specified."); } catch (Exception e) { Assert.fail(e.getMessage()); e.printStackTrace(); } }
@Test public void test1() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder parser = dbf.newDocumentBuilder(); Document dom = parser.parse(Bug5072946.class.getResourceAsStream("Bug5072946.xml")); SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema s = sf.newSchema(Bug5072946.class.getResource("Bug5072946.xsd")); Validator v = s.newValidator(); DOMResult r = new DOMResult(); // r.setNode(dbf.newDocumentBuilder().newDocument()); v.validate(new DOMSource(dom), r); Node node = r.getNode(); Assert.assertNotNull(node); Node fc = node.getFirstChild(); Assert.assertTrue(fc instanceof Element); Element e = (Element) fc; Assert.assertEquals("value", e.getAttribute("foo")); }
private void validate(final String xsdFile, final Source src, final Result result) throws Exception { try { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new File(ValidatorTest.class.getResource(xsdFile).toURI())); // Get a Validator which can be used to validate instance document // against this grammar. Validator validator = schema.newValidator(); ErrorHandler eh = new ErrorHandlerImpl(); validator.setErrorHandler(eh); // Validate this instance document against the // Instance document supplied validator.validate(src, result); } catch (Exception ex) { throw ex; } }
@Test public void testValidation_SAX_withServiceMech() { System.out.println("Validation using SAX Source. Using service mechnism (by default) to find SAX Impl:"); InputSource is = new InputSource(Bug6941169Test.class.getResourceAsStream("Bug6941169.xml")); SAXSource ss = new SAXSource(is); setSystemProperty(SAX_FACTORY_ID, "MySAXFactoryImpl"); long start = System.currentTimeMillis(); try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(_xsd)); Validator validator = schema.newValidator(); validator.validate(ss, null); Assert.fail("User impl MySAXFactoryImpl should be used."); } catch (Exception e) { String error = e.getMessage(); if (error.indexOf("javax.xml.parsers.FactoryConfigurationError: Provider MySAXFactoryImpl not found") > 0) { // expected } // System.out.println(e.getMessage()); } long end = System.currentTimeMillis(); double elapsedTime = ((end - start)); System.out.println("Time elapsed: " + elapsedTime); clearSystemProperty(SAX_FACTORY_ID); }
/** * Check grammar caching with imported schemas. * * @throws Exception If any errors occur. * @see <a href="content/coins.xsd">coins.xsd</a> * @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a> */ @Test public void testGetOwnerItemList() throws Exception { String xsdFile = XML_DIR + "coins.xsd"; String xmlFile = XML_DIR + "coins.xml"; try(FileInputStream fis = new FileInputStream(xmlFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); dbf.setValidating(false); SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new File(((xsdFile)))); MyErrorHandler eh = new MyErrorHandler(); Validator validator = schema.newValidator(); validator.setErrorHandler(eh); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); Document document = docBuilder.parse(fis); validator.validate(new DOMSource(document), new DOMResult()); assertFalse(eh.isAnyError()); } }
/** * Tests if the access-control-schema.xml is valid. * * @throws ParserConfigurationException If a DocumentBuilder cannot be created which satisfies the configuration * requested. * @throws IOException If any IO errors occur. * @throws SAXException If an error occurs during the validation. */ @Test public void validateAccessControllSchema() throws ParserConfigurationException, SAXException, IOException { // parse an XML document into a DOM tree DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); String xmlPath = getClass().getResource("/config/app/security/access-control-schema.xml").getPath(); Document document = parser.parse(new File(xmlPath)); // 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 URL schemaPath = getClass().getResource("/io/oasp/module/security/access-control-schema.xsd"); Schema schema = factory.newSchema(schemaPath); // create a Validator instance, which can be used to validate an instance document Validator validator = schema.newValidator(); // validate the DOM tree validator.validate(new DOMSource(document)); }
@Test public void testValidation_SAX_withServiceMech() { System.out.println("Validation using SAX Source. Using service mechnism (by default) to find SAX Impl:"); InputSource is = new InputSource(Bug6941169Test.class.getResourceAsStream("Bug6941169.xml")); SAXSource ss = new SAXSource(is); System.setProperty(SAX_FACTORY_ID, "MySAXFactoryImpl"); long start = System.currentTimeMillis(); try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(_xsd)); Validator validator = schema.newValidator(); validator.validate(ss, null); Assert.fail("User impl MySAXFactoryImpl should be used."); } catch (Exception e) { String error = e.getMessage(); if (error.indexOf("javax.xml.parsers.FactoryConfigurationError: Provider MySAXFactoryImpl not found") > 0) { // expected } // System.out.println(e.getMessage()); } long end = System.currentTimeMillis(); double elapsedTime = ((end - start)); System.out.println("Time elapsed: " + elapsedTime); System.clearProperty(SAX_FACTORY_ID); }
private Validator createValidator() { URL schemaUrl = Thread.currentThread().getContextClassLoader().getResource("XMLSchema.xsd"); if (schemaUrl == null) { throw new IllegalStateException("Classpath resource 'XMLSchema.xsd' not found"); } URL xmlUrl = Thread.currentThread().getContextClassLoader().getResource("xml.xsd"); if (xmlUrl == null) { throw new IllegalStateException("Classpath resource 'xml.xsd' not found"); } SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { Source[] sources = new Source[]{new StreamSource(new ByteArrayInputStream(readFromUrl(xmlUrl))) , new StreamSource(new ByteArrayInputStream(readFromUrl(schemaUrl)))}; Schema schema = schemaFactory.newSchema(sources); return schema.newValidator(); } catch (SAXException | IOException e) { throw new IllegalStateException("Cannot create schema", e); } }
/** * Parse the XML configuration document that is used for testing. * * @throws Exception * */ @Test public void parseXML() throws Exception { // NOSONAR final String xml = "/mocktcpserver.xml"; final String schemaName = "/mocktcpserver.xsd"; DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder parser; try { parser = builderFactory.newDocumentBuilder(); Document document = parser.parse(ClassLoader.class.getResourceAsStream(xml)); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source schemaFile = new StreamSource(ClassLoader.class.getResourceAsStream(schemaName)); Schema schema = factory.newSchema(schemaFile); Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); } catch (ParserConfigurationException | SAXException | IOException e) { throw e; // NOSONAR } }
/** * Helper method that returns a validator for our Addon XSD * * @param version The version number, in range {@code 1..NS_LATEST_VERSION} * @param handler A {@link CaptureErrorHandler}. If null the default will be used, * which will most likely print errors to stderr. */ private Validator getAddonValidator(int version, @Nullable CaptureErrorHandler handler) throws SAXException { Validator validator = null; InputStream xsdStream = SdkAddonConstants.getXsdStream(version); if (xsdStream != null) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsdStream)); validator = schema.newValidator(); if (handler != null) { validator.setErrorHandler(handler); } } return validator; }
/** * Helper method that returns a validator for our Addons-List XSD * * @param version The version number, in range {@code 1..NS_LATEST_VERSION} * @param handler A {@link CaptureErrorHandler}. If null the default will be used, * which will most likely print errors to stderr. */ private Validator getValidator(int version, @Nullable CaptureErrorHandler handler) throws SAXException { Validator validator = null; InputStream xsdStream = SdkAddonsListConstants.getXsdStream(version); if (xsdStream != null) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsdStream)); validator = schema.newValidator(); if (handler != null) { validator.setErrorHandler(handler); } } return validator; }
private boolean isValidGuidelineXml(String guidelineXml) { StreamSource xsd = new StreamSource(this.getClass().getResourceAsStream("/k2a/dsGuideline.xsd")); StreamSource xml = new StreamSource(new StringReader(guidelineXml)); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { Schema schema = schemaFactory.newSchema(xsd); Validator validator = schema.newValidator(); validator.validate(xml); } catch (Exception e) { DecisionSupportException newException = new DecisionSupportException("Error parsing guideline: "+guidelineXml, e); logger.error(newException.getMessage()); return false; } return true; }
Document readFile(Path p) { Document document = null; try { // parse an XML document into a DOM tree DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder parser = factory.newDocumentBuilder(); document = parser.parse(p.toFile()); // create a Validator instance, which can be used to validate an instance document Validator validator = schema.newValidator(); // validate the DOM tree validator.validate(new DOMSource(document)); } catch (SAXException | IOException | ParserConfigurationException e) { throw new ParseException(e); } return document; }
/** * Read and validate the given file to a configuration for stereotype check. * * @param file * The file to read. * @param additionalCheckCfg * a previously read configuration which may override parts of * the configuration read by the file. * @param readingAdditionalCfg * Are we reading the additionalCfg. * @return the configuration. * @throws XMLStreamException * @throws IllegalArgumentException * @throws SAXException * @throws IOException */ private static StereotypeCheckConfiguration read(File file, String checkstyleStereotypeXsd, StereotypeCheckConfiguration additionalCheckCfg, boolean readingAdditionalCfg) throws XMLStreamException, IllegalArgumentException, SAXException, IOException { // Validate with StreamSource because Stax Validation is not provided // with every implementation of JAXP SchemaFactory schemafactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemafactory .newSchema(StereotypeCheckReader.class.getClassLoader().getResource(checkstyleStereotypeXsd)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(file)); // Parse with Stax XMLStreamReader reader = XMLInputFactory.newInstance() .createXMLStreamReader(new BufferedInputStream(new FileInputStream(file))); StereotypeCheckConfigurationReader delegate = new StereotypeCheckConfigurationReader(reader, additionalCheckCfg, readingAdditionalCfg); while (delegate.hasNext()) { delegate.next(); } return delegate.getConfig(); }
/** * Test is extra schema can be loaded to the schema registry and whether the file compliant to that * schema can be validated. */ @Test public void testExtraSchema() throws SAXException, IOException, SchemaException { System.out.println("===[ testExtraSchema ]==="); Document dataDoc = DOMUtil.parseFile(new File(COMMON_DIR_PATH, "root-foo.xml")); PrismContext context = constructPrismContext(); SchemaRegistryImpl reg = (SchemaRegistryImpl) context.getSchemaRegistry(); Document extraSchemaDoc = DOMUtil.parseFile(new File(EXTRA_SCHEMA_DIR, "root.xsd")); reg.registerSchema(extraSchemaDoc, "file root.xsd"); reg.initialize(); Schema javaxSchema = reg.getJavaxSchema(); assertNotNull(javaxSchema); Validator validator = javaxSchema.newValidator(); DOMResult validationResult = new DOMResult(); validator.validate(new DOMSource(dataDoc),validationResult); // System.out.println("Validation result:"); // System.out.println(DOMUtil.serializeDOMToString(validationResult.getNode())); }
/** * Test whether the midpoint prism context was constructed OK and if it can validate * ordinary user object. */ @Test public void testBasic() throws SAXException, IOException, SchemaException { MidPointPrismContextFactory factory = getContextFactory(); PrismContext context = factory.createInitializedPrismContext(); SchemaRegistry reg = context.getSchemaRegistry(); Schema javaxSchema = reg.getJavaxSchema(); assertNotNull(javaxSchema); // Try to use the schema to validate Jack // PrismObject<UserType> user = context.parseObject(new File("src/test/resources/common/user-jack.xml")); // Element document = context.serializeToDom(user); Document document = DOMUtil.parseFile("src/test/resources/common/user-jack.xml"); Validator validator = javaxSchema.newValidator(); DOMResult validationResult = new DOMResult(); validator.validate(new DOMSource(document), validationResult); // System.out.println("Validation result:"); // System.out.println(DOMUtil.serializeDOMToString(validationResult.getNode())); }
protected void validateGood(File file) throws IOException, SAXException, AdeException { System.out.println("Starting"); String fileName_Flowlayout_xsd = Ade.getAde().getConfigProperties() .getXsltDir() + FLOW_LAYOUT_XSD_File_Name; Source schemaFile = new StreamSource(fileName_Flowlayout_xsd); SchemaFactory sf = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema mSchema = sf.newSchema(schemaFile); System.out.println("Validating " + file.getPath()); Validator val = mSchema.newValidator(); FileInputStream fis = new FileInputStream(file); StreamSource streamSource = new StreamSource(fis); try { val.validate(streamSource); } catch (SAXParseException e) { System.out.println(e); throw e; } System.out.println("SUCCESS!"); }
private static Element testSchema(Document document, Element tableA, Validator validator) { //Add schema element. Element schema = document.createElement("schema"); tableA.appendChild(schema); try { validator.validate(new DOMSource(document)); fail("Validation with incomplete schema element should not be successful!"); } catch(Exception e) { assertTrue(e.getMessage().contains("The content of element 'schema' is not complete.")); } //Add and test attribute elements. testAttributes(document, schema, validator); return schema; }
private static Element testTableB(Document document, Element root, Validator validator) { Element tableB = document.createElement("table"); tableB.setAttribute("name", "tableB"); root.appendChild(tableB); Element schema = document.createElement("schema"); tableB.appendChild(schema); Element attribute = document.createElement("attribute"); attribute.setAttribute("name", "id"); attribute.setAttribute("type", "java.lang.Integer"); attribute.setAttribute("isPrimaryKey", "true"); schema.appendChild(attribute); Element record = document.createElement("record"); record.setAttribute("id", "1"); tableB.appendChild(record); try { validator.validate(new DOMSource(document)); } catch(Exception e) { fail("Document should now be valid!"); } return tableB; }