List of usage examples for javax.xml.validation SchemaFactory newSchema
public abstract Schema newSchema(Source[] schemas) throws SAXException;
From source file:main.java.refinement_class.Useful.java
public static Object unmashal2(String schema_file, String xml_file, Class c) { Object obj = null;/* w w w .j a v a 2s . c om*/ try { // create a JAXBContext capable of handling classes generated into // JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class ); JAXBContext jc = JAXBContext.newInstance(c); // create an Unmarshaller Unmarshaller u = jc.createUnmarshaller(); SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { javax.xml.validation.Schema schema = sf.newSchema(new File(schema_file)); u.setSchema((javax.xml.validation.Schema) schema); u.setEventHandler(new ValidationEventHandler() { // allow unmarshalling to continue even if there are errors public boolean handleEvent(ValidationEvent ve) { // ignore warnings if (ve.getSeverity() != ValidationEvent.WARNING) { ValidationEventLocator vel = ve.getLocator(); System.out.println("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:" + ve.getMessage()); } return true; } }); } catch (org.xml.sax.SAXException se) { System.out.println("Unable to validate due to following error."); se.printStackTrace(); LOG.error(se.toString()); } obj = u.unmarshal(new File(xml_file)); // even though document was determined to be invalid unmarshalling, // marshal out result. // System.out.println(""); // System.out.println("Still able to marshal invalid document"); // javax.xml.bind.Marshaller m = jc.createMarshaller(); // m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); // m.marshal(poe, System.out); } catch (UnmarshalException ue) { // The JAXB specification does not mandate how the JAXB provider // must behave when attempting to unmarshal invalid XML data. // those cases, the JAXB provider is allowed to terminate the // call to unmarshal with an UnmarshalException. System.out.println("Caught UnmarshalException"); } catch (JAXBException je) { je.printStackTrace(); LOG.error(je.toString()); } return obj; }
From source file:com.sun.tools.xjc.addon.xew.XmlElementWrapperPluginTest.java
/** * Standard test for XSD examples.//ww w . ja v a2s . c o m * * @param testName * the prototype of XSD file name / package name * @param extraXewOptions * to be passed to plugin * @param generateEpisode * generate episode file and check the list of classes included into it * @param classesToCheck * expected classes/files in target directory; these files content is checked if it is present in * resources directory; {@code ObjectFactory.java} is automatically included */ static void assertXsd(String testName, String[] extraXewOptions, boolean generateEpisode, String... classesToCheck) throws Exception { String resourceXsd = testName + ".xsd"; String packageName = testName.replace('-', '_'); // Force plugin to reinitialize the logger: System.clearProperty(XmlElementWrapperPlugin.COMMONS_LOGGING_LOG_LEVEL_PROPERTY_KEY); URL xsdUrl = XmlElementWrapperPluginTest.class.getResource(resourceXsd); File targetDir = new File(GENERATED_SOURCES_PREFIX); targetDir.mkdirs(); PrintStream loggingPrintStream = new PrintStream( new LoggingOutputStream(logger, LoggingOutputStream.LogLevel.INFO, "[XJC] ")); String[] opts = ArrayUtils.addAll(extraXewOptions, "-no-header", "-extension", "-Xxew", "-d", targetDir.getPath(), xsdUrl.getFile()); String episodeFile = new File(targetDir, "episode.xml").getPath(); // Episode plugin should be triggered after Xew, see https://github.com/dmak/jaxb-xew-plugin/issues/6 if (generateEpisode) { opts = ArrayUtils.addAll(opts, "-episode", episodeFile); } assertTrue("XJC compilation failed. Checked console for more info.", Driver.run(opts, loggingPrintStream, loggingPrintStream) == 0); if (generateEpisode) { // FIXME: Episode file actually contains only value objects Set<String> classReferences = getClassReferencesFromEpisodeFile(episodeFile); if (Arrays.asList(classesToCheck).contains("package-info")) { classReferences.add(packageName + ".package-info"); } assertEquals("Wrong number of classes in episode file", classesToCheck.length, classReferences.size()); for (String className : classesToCheck) { assertTrue(className + " class is missing in episode file;", classReferences.contains(packageName + "." + className)); } } targetDir = new File(targetDir, packageName); Collection<String> generatedJavaSources = new HashSet<String>(); // *.properties files are ignored: for (File targetFile : FileUtils.listFiles(targetDir, new String[] { "java" }, true)) { // This is effectively the path of targetFile relative to targetDir: generatedJavaSources .add(targetFile.getPath().substring(targetDir.getPath().length() + 1).replace('\\', '/')); } // This class is added and checked by default: classesToCheck = ArrayUtils.add(classesToCheck, "ObjectFactory"); assertEquals("Wrong number of generated classes " + generatedJavaSources + ";", classesToCheck.length, generatedJavaSources.size()); for (String className : classesToCheck) { className = className.replace('.', '/') + ".java"; assertTrue(className + " is missing in target directory", generatedJavaSources.contains(className)); } // Check the contents for those files which exist in resources: for (String className : classesToCheck) { className = className.replace('.', '/') + ".java"; File sourceFile = new File(PREGENERATED_SOURCES_PREFIX + packageName, className); if (sourceFile.exists()) { // To avoid CR/LF conflicts: assertEquals("For " + className, FileUtils.readFileToString(sourceFile).replace("\r", ""), FileUtils.readFileToString(new File(targetDir, className)).replace("\r", "")); } } JAXBContext jaxbContext = compileAndLoad(packageName, targetDir, generatedJavaSources); URL xmlTestFile = XmlElementWrapperPluginTest.class.getResource(testName + ".xml"); if (xmlTestFile != null) { StringWriter writer = new StringWriter(); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setSchema(schemaFactory.newSchema(xsdUrl)); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); Object bean = unmarshaller.unmarshal(xmlTestFile); marshaller.marshal(bean, writer); XMLUnit.setIgnoreComments(true); XMLUnit.setIgnoreWhitespace(true); Diff xmlDiff = new Diff(IOUtils.toString(xmlTestFile), writer.toString()); assertXMLEqual("Generated XML is wrong: " + writer.toString(), xmlDiff, true); } }
From source file:com.indivica.olis.Driver.java
public static void readResponseFromXML(HttpServletRequest request, String olisResponse) { olisResponse = olisResponse.replaceAll("<Content", "<Content xmlns=\"\" "); olisResponse = olisResponse.replaceAll("<Errors", "<Errors xmlns=\"\" "); try {//from ww w . ja v a 2s . c o m DocumentBuilderFactory.newInstance().newDocumentBuilder(); SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); Source schemaFile = new StreamSource( new File(OscarProperties.getInstance().getProperty("olis_response_schema"))); factory.newSchema(schemaFile); JAXBContext jc = JAXBContext.newInstance("ca.ssha._2005.hial"); Unmarshaller u = jc.createUnmarshaller(); @SuppressWarnings("unchecked") Response root = ((JAXBElement<Response>) u.unmarshal(new InputSource(new StringReader(olisResponse)))) .getValue(); if (root.getErrors() != null) { List<String> errorStringList = new LinkedList<String>(); // Read all the errors ArrayOfError errors = root.getErrors(); List<ca.ssha._2005.hial.Error> errorList = errors.getError(); for (ca.ssha._2005.hial.Error error : errorList) { String errorString = ""; errorString += "ERROR " + error.getNumber() + " (" + error.getSeverity() + ") : " + error.getMessage(); MiscUtils.getLogger().debug(errorString); ArrayOfString details = error.getDetails(); if (details != null) { List<String> detailList = details.getString(); for (String detail : detailList) { errorString += "\n" + detail; } } errorStringList.add(errorString); } if (request != null) request.setAttribute("errors", errorStringList); } else if (root.getContent() != null) { if (request != null) request.setAttribute("olisResponseContent", root.getContent()); } } catch (Exception e) { MiscUtils.getLogger().error("Couldn't read XML from OLIS response.", e); LoggedInInfo loggedInInfo = LoggedInInfo.getLoggedInInfoFromSession(request); notifyOlisError(loggedInInfo.getLoggedInProvider(), "Couldn't read XML from OLIS response." + "\n" + e); } }
From source file:main.java.refinement_class.Useful.java
public static Object unmashal(String schema_file, String xml_file, Class c) { Object obj = null;/*from www . j ava2 s . co m*/ try { // create a JAXBContext capable of handling classes generated into // JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class ); JAXBContext jc = JAXBContext.newInstance(c); // create an Unmarshaller Unmarshaller u = jc.createUnmarshaller(); SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { // LOG.info("\n\n XX -->> Schema file: " + schema_file); // LOG.info("\n\n XX -->> xml_file file: " + xml_file); //++ javax.xml.validation.Schema schema; if (schema_file.contains("/tmp/")) { schema = sf.newSchema(new File(schema_file)); } else { URL urlSchema = getUrl(H2mserviceImpl.class, schema_file); // LOG.info("\n\n XX -->> urlSchema: " + urlSchema.getPath()); schema = sf.newSchema(urlSchema); } //-- //javax.xml.validation.Schema schema = sf.newSchema(new File(schema_file)); // ++ u.setSchema((javax.xml.validation.Schema) schema); u.setEventHandler(new ValidationEventHandler() { // allow unmarshalling to continue even if there are errors public boolean handleEvent(ValidationEvent ve) { // ignore warnings if (ve.getSeverity() != ValidationEvent.WARNING) { ValidationEventLocator vel = ve.getLocator(); System.out.println("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:" + ve.getMessage()); } return true; } }); } catch (org.xml.sax.SAXException se) { System.out.println("Unable to validate due to following error."); se.printStackTrace(); LOG.error("===>[1]ERROR Unmashaling \n\n" + se.toString()); LOG.error(Useful.getStackTrace(se)); } catch (Exception e) { LOG.error("===>[2]ERROR Unmashaling \n\n" + e.toString()); LOG.error(Useful.getStackTrace(e)); } if (xml_file.contains("/tmp/")) { obj = u.unmarshal(new File(xml_file)); } else { URL url_xml_file = getUrl(H2mserviceImpl.class, xml_file); LOG.info("\n\n XX -->> url_xml_file: " + url_xml_file.getPath()); obj = u.unmarshal(url_xml_file); } //-- //obj = u.unmarshal( new File( xml_file)); //++ // even though document was determined to be invalid unmarshalling, // marshal out result. // System.out.println(""); // System.out.println("Still able to marshal invalid document"); // javax.xml.bind.Marshaller m = jc.createMarshaller(); // m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); // m.marshal(poe, System.out); } catch (UnmarshalException ue) { // The JAXB specification does not mandate how the JAXB provider // must behave when attempting to unmarshal invalid XML data. // those cases, the JAXB provider is allowed to terminate the // call to unmarshal with an UnmarshalException. System.out.println("Caught UnmarshalException"); LOG.error("===>[3]ERROR Unmashaling \n\n" + ue.toString()); } catch (JAXBException je) { je.printStackTrace(); LOG.error("===>[4]ERROR Unmashaling \n\n" + je.toString()); LOG.error(Useful.getStackTrace(je)); } catch (Exception e) { LOG.error("===>[5]ERROR Unmashaling \n\n" + e.toString()); LOG.error(Useful.getStackTrace(e)); } if (obj == null) { LOG.error("===>[6]ERROR Unmashaling Object NULL"); } return obj; }
From source file:edu.stanford.epad.common.util.EPADFileUtils.java
public static boolean isValidXmlUsingClassPathSchema(File f, String xsdSchema) { try {/*from ww w .j av a 2s. c o m*/ log.debug("xml:" + f.getName() + " xsd:" + xsdSchema); FileInputStream xml = new FileInputStream(f); InputStream xsd = null; try { xsd = EPADFileUtils.class.getClassLoader().getResourceAsStream(xsdSchema); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsd)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xml)); return true; } catch (SAXException ex) { log.info("Error: validating template/annotation " + ex.getMessage()); } catch (IOException e) { log.info("Error: validating template/annotation " + e.getMessage()); } } catch (IOException e) { log.info("Exception validating a file: " + f.getName()); } return false; }
From source file:edu.stanford.epad.common.util.EPADFileUtils.java
public static String validateXml(File f, String xsdSchema) throws Exception { try {/* w w w .ja va 2 s . com*/ FileInputStream xml = new FileInputStream(f); InputStream xsd = null; try { xsd = new FileInputStream(xsdSchema); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsd)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xml)); return ""; } catch (SAXException ex) { log.info("Error: validating template/annotation " + ex.getMessage()); return ex.getMessage(); } catch (IOException e) { log.info("Error: validating template/annotation " + e.getMessage()); throw e; } } catch (IOException e) { log.info("Exception validating a file: " + f.getName()); throw e; } }
From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java
/** * Validate xml./*w ww . j a v a2 s .c om*/ * * @param inSchemas the in schemas * @param inXml the in xml * @param schemaLanguage the schema language * * @return the xML error handler * * @throws MotuException the motu exception */ public static XMLErrorHandler validateXML(InputStream[] inSchemas, InputStream inXml, String schemaLanguage) throws MotuException { // parse an XML document into a DOM tree Document document; // create a Validator instance, which can be used to validate an instance document Validator validator; XMLErrorHandler errorHandler = new XMLErrorHandler(); try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); // Must enable namespace processing!!!!! try { documentBuilderFactory.setXIncludeAware(true); } catch (Exception e) { // Do Nothing } // documentBuilderFactory.setExpandEntityReferences(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); // document = documentBuilder.parse(new File(xmlUrl.toURI())); documentBuilder.setErrorHandler(errorHandler); document = documentBuilder.parse(inXml); // create a SchemaFactory capable of understanding WXS schemas SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage); schemaFactory.setErrorHandler(errorHandler); // load a WXS schema, represented by a Schema instance Source[] schemaFiles = new Source[inSchemas.length]; // InputStream inShema = null; int i = 0; for (InputStream inSchema : inSchemas) { schemaFiles[i] = new StreamSource(inSchema); i++; } Schema schema = schemaFactory.newSchema(schemaFiles); validator = schema.newValidator(); validator.setErrorHandler(errorHandler); validator.validate(new DOMSource(document)); } catch (Exception e) { throw new MotuException(e); // instance document is invalid! } return errorHandler; }
From source file:eu.europa.esig.dss.DSSXMLUtils.java
private static Schema getSchema() throws SAXException { final ResourceLoader resourceLoader = new ResourceLoader(); final InputStream xadesXsd = resourceLoader.getResource(XAD_ESV141_XSD); final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); return factory.newSchema(new StreamSource(xadesXsd)); }
From source file:com.spoledge.util.xml.XMLValidator.java
public XMLValidator(File schema) throws SAXException { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); init(sf.newSchema(schema)); }
From source file:com.spoledge.util.xml.XMLValidator.java
public XMLValidator(URL schema) throws SAXException { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); init(sf.newSchema(schema)); }