List of usage examples for javax.xml.validation SchemaFactory newInstance
public static SchemaFactory newInstance(String schemaLanguage)
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.data.QueryResultContainer.java
/** * Validates input XML file using 'queryResult.xsd' schema. * * @param xml xml/*www. j a va 2s .c om*/ * @throws IOException if file is not valid */ public static void validateXML(String xml) throws IOException { String xsdName = "queryResult.xsd"; URL resource = QueryResultContainer.class.getClass().getResource(xsdName); if (resource == null) { throw new IllegalStateException("Cannot locate resource " + xsdName + " on classpath"); } URL xsdFile; try { xsdFile = resource.toURI().toURL(); } catch (MalformedURLException | URISyntaxException e) { throw new IOException(e); } SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { Schema schema = factory.newSchema(xsdFile); Validator validator = schema.newValidator(); validator.validate(new StreamSource(new StringReader(xml))); } catch (SAXException e) { throw new IOException(e); } }
From source file:at.gv.egiz.slbinding.SLUnmarshaller.java
private static Schema createSchema(Collection<String> schemaUrls) throws SAXException, IOException { Logger log = LoggerFactory.getLogger(SLUnmarshaller.class); Source[] sources = new Source[schemaUrls.size()]; Iterator<String> urls = schemaUrls.iterator(); StringBuilder sb = null;/*from ww w . j a va2s. c om*/ if (log.isDebugEnabled()) { sb = new StringBuilder(); sb.append("Created schema using URLs: "); } for (int i = 0; i < sources.length && urls.hasNext(); i++) { String url = urls.next(); if (url != null && url.startsWith("classpath:")) { URL schemaUrl = new URL(null, url, new ClasspathURLStreamHandler()); sources[i] = new StreamSource(schemaUrl.openStream()); } else { sources[i] = new StreamSource(url); } if (sb != null) { sb.append(url); if (urls.hasNext()) { sb.append(", "); } } } SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(sources); if (sb != null) { log.debug(sb.toString()); } return schema; }
From source file:io.inkstand.scribble.jcr.rules.util.XMLContentLoaderTest.java
@Test public void testLoadContent_validating_validResource() throws Exception { // prepare/*from w w w .j av a2s .c o m*/ final URL resource = getClass().getResource("XMLContentLoaderTest_inkstandJcrImport_v1-0.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); Node rootNode = subject.loadContent(actSession, resource); // assert assertNotNull(rootNode); final Session verifySession = repository.getRepository().login(); verifySession.refresh(true); assertNodeExistByPath(verifySession, "/root"); final Node root = verifySession.getNode("/root"); assertNodeExistByPath(verifySession, "/root"); assertPrimaryNodeType(root, "nt:unstructured"); assertMixinNodeType(root, "mix:title"); assertStringPropertyEquals(root, "jcr:title", "TestTitle"); }
From source file:eu.europa.ejusticeportal.dss.controller.config.Config.java
/** * /*from w ww . j a v a 2s .c om*/ * The default constructor for SigningContextRepositoryXmlImpl. */ private Config() { InputStream is = null; try { is = Config.class.getClassLoader().getResourceAsStream("signingcontext-v1.xsd"); StreamSource source = new StreamSource(is, CardProfileNamespace.NS); schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(source); } catch (SAXException e) { LOGGER.error("Unable to load XML validation schema - validation of configuration xml will not be done.", e); } finally { IOUtils.closeQuietly(is); } }
From source file:io.tourniquet.junit.jcr.rules.util.XMLContentLoaderTest.java
@Test public void testLoadContent_validating_validResource() throws Exception { // prepare//from w w w.j a v a 2 s . com final URL resource = getClass().getResource("XMLContentLoaderTest_tourniquetJcrImport_v1-0.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); Node rootNode = subject.loadContent(actSession, resource); // assert assertNotNull(rootNode); final Session verifySession = repository.getRepository().login(); verifySession.refresh(true); assertNodeExistByPath(verifySession, "/root"); final Node root = verifySession.getNode("/root"); assertNodeExistByPath(verifySession, "/root"); assertPrimaryNodeType(root, "nt:unstructured"); assertMixinNodeType(root, "mix:title"); assertStringPropertyEquals(root, "jcr:title", "TestTitle"); }
From source file:com.jkoolcloud.tnt4j.streams.configure.sax.StreamsConfigSAXParser.java
/** * Validates configuration XML against XML defined XSD schema. * * @param config//from ww w. java2s . 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:io.inkstand.jcr.util.JCRContentLoaderTest.java
@Test(expected = InkstandRuntimeException.class) @Ignore//from w w w .j a v a 2s.c om public void testLoadContent_validating_invalidResource() throws Exception { // prepare final URL resource = getClass().getResource("test01_inkstandJcrImport_v1-0_invalid.xml"); final Session actSession = repository.login("admin", "admin"); 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:com.betfair.cougar.marshalling.impl.databinding.xml.XMLUtils.java
public static Schema getSchema(JAXBContext context) { Result result = new ResultImplementation(); SchemaOutputResolver outputResolver = new SchemaOutputResolverImpl(result); File tempFile = null;/*from ww w .j av a 2s . c o m*/ try { context.generateSchema(outputResolver); String schemaFile = result.getSystemId(); if (schemaFile != null) { tempFile = new File(URI.create(schemaFile)); String content = FileUtils.readFileToString(tempFile); // JAXB nicely generates a schema with element refs, unfortunately it also adds the nillable attribute to the // referencing element, which is invalid, it has to go on the target. this string manipulation is to move the // nillable attribute to the correct place, preserving it's value. Map<String, Boolean> referenceElementsWithNillable = new HashMap<>(); BufferedReader br = new BufferedReader(new StringReader(content)); String line; while ((line = br.readLine()) != null) { if (line.contains("<xs:element") && line.contains(" ref=\"") && line.contains(" nillable=\"")) { // we've got a reference element with nillable set int refStartIndex = line.indexOf(" ref=\"") + 6; int refEndIndex = line.indexOf("\"", refStartIndex); int nillableStartIndex = line.indexOf(" nillable=\"") + 11; int nillableEndIndex = line.indexOf("\"", nillableStartIndex); String ref = line.substring(refStartIndex, refEndIndex); if (ref.startsWith("tns:")) { ref = ref.substring(4); } String nillable = line.substring(nillableStartIndex, nillableEndIndex); referenceElementsWithNillable.put(ref, Boolean.valueOf(nillable)); } } // if we got some hits, then we need to rewrite this schema if (!referenceElementsWithNillable.isEmpty()) { StringBuilder sb = new StringBuilder(); br = new BufferedReader(new StringReader(content)); while ((line = br.readLine()) != null) { // these we need to remove the nillable section from if (line.contains("<xs:element") && line.contains(" ref=\"") && line.contains(" nillable=\"")) { int nillableStartIndex = line.indexOf(" nillable=\""); int nillableEndIndex = line.indexOf("\"", nillableStartIndex + 11); line = line.substring(0, nillableStartIndex) + line.substring(nillableEndIndex + 1); } else if (line.contains("<xs:element name=\"")) { for (String key : referenceElementsWithNillable.keySet()) { // this we need to add the nillable back to String elementTagWithName = "<xs:element name=\"" + key + "\""; if (line.contains(elementTagWithName)) { int endOfElementName = line.indexOf(elementTagWithName) + elementTagWithName.length(); line = line.substring(0, endOfElementName) + " nillable=\"" + referenceElementsWithNillable.get(key) + "\"" + line.substring(endOfElementName); break; } } } sb.append(line).append("\n"); } content = sb.toString(); } SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); return sf.newSchema(new StreamSource(new StringReader(content))); } } catch (IOException e) { throw new PanicInTheCougar(e); } catch (SAXException e) { throw new PanicInTheCougar(e); } finally { if (tempFile != null) tempFile.delete(); } return null; }
From source file:org.raml.parser.rule.SchemaRule.java
@Override public List<ValidationResult> doValidateValue(ScalarNode node) { String value = node.getValue(); List<ValidationResult> validationResults = super.doValidateValue(node); IncludeInfo globaSchemaIncludeInfo = null; ScalarNode schemaNode = getGlobalSchemaNode(value); if (schemaNode == null) { schemaNode = node;/*from ww w .j a v a 2 s. c om*/ } else { value = schemaNode.getValue(); if (schemaNode.getTag().startsWith(INCLUDE_APPLIED_TAG)) { globaSchemaIncludeInfo = new IncludeInfo(schemaNode.getTag()); } } if (value == null || isCustomTag(schemaNode.getTag())) { return validationResults; } String mimeType = ((ScalarNode) getParentTupleRule().getKey()).getValue(); if (mimeType.contains("json")) { try { JsonNode jsonNode = JsonLoader.fromString(value); ProcessingReport report = VALIDATOR.validateSchema(jsonNode); if (!report.isSuccess()) { StringBuilder msg = new StringBuilder("invalid JSON schema"); msg.append(getSourceErrorDetail(node)); for (ProcessingMessage processingMessage : report) { msg.append("\n").append(processingMessage.toString()); } validationResults .add(getErrorResult(msg.toString(), getLineOffset(schemaNode), globaSchemaIncludeInfo)); } } catch (JsonParseException jpe) { String msg = "invalid JSON schema" + getSourceErrorDetail(node) + jpe.getOriginalMessage(); JsonLocation loc = jpe.getLocation(); validationResults.add( getErrorResult(msg, getLineOffset(schemaNode) + loc.getLineNr(), globaSchemaIncludeInfo)); } catch (IOException e) { String prefix = "invalid JSON schema" + getSourceErrorDetail(node); validationResults.add(getErrorResult(prefix + e.getMessage(), UNKNOWN, globaSchemaIncludeInfo)); } } else if (mimeType.contains("xml")) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { factory.newSchema(new StreamSource(new StringReader(value))); } catch (SAXParseException e) { String msg = "invalid XML schema" + getSourceErrorDetail(node) + e.getMessage(); validationResults.add( getErrorResult(msg, getLineOffset(schemaNode) + e.getLineNumber(), globaSchemaIncludeInfo)); } catch (SAXException e) { String msg = "invalid XML schema" + getSourceErrorDetail(node); validationResults.add(getErrorResult(msg, getLineOffset(schemaNode), globaSchemaIncludeInfo)); } } return validationResults; }
From source file:org.openwms.core.configuration.file.ApplicationPreferenceTest.java
/** * Just test to validate the given XML file against the schema declaration. If the XML file is not compliant with the schema, the test * will fail./*from w ww . jav a 2s .co m*/ * * @throws Exception any error */ @Test public void testReadPreferences() throws Exception { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(ResourceUtils.getFile("classpath:preferences.xsd")); // Schema schema = schemaFactory.newSchema(new // URL("http://www.openwms.org/schema/preferences.xsd")); JAXBContext ctx = JAXBContext.newInstance("org.openwms.core.configuration.file"); Unmarshaller unmarshaller = ctx.createUnmarshaller(); unmarshaller.setSchema(schema); unmarshaller.setEventHandler(new ValidationEventHandler() { @Override public boolean handleEvent(ValidationEvent event) { RuntimeException ex = new RuntimeException(event.getMessage(), event.getLinkedException()); LOGGER.error(ex.getMessage()); throw ex; } }); Preferences prefs = Preferences.class.cast(unmarshaller .unmarshal(ResourceUtils.getFile("classpath:org/openwms/core/configuration/file/preferences.xml"))); for (AbstractPreference pref : prefs.getApplications()) { LOGGER.info(pref.toString()); } for (AbstractPreference pref : prefs.getModules()) { LOGGER.info(pref.toString()); } for (AbstractPreference pref : prefs.getUsers()) { LOGGER.info(pref.toString()); } }