List of usage examples for javax.xml.validation Validator validate
public void validate(Source source) throws SAXException, IOException
From source file:org.openremote.beehive.configuration.www.UsersAPI.java
private File createControllerXmlFile(java.nio.file.Path temporaryFolder, Account account) { File controllerXmlFile = new File(temporaryFolder.toFile(), "controller.xml"); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); try {//from w ww . jav a2s.c o m documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); DOMImplementation domImplementation = documentBuilder.getDOMImplementation(); Document document = domImplementation.createDocument(OPENREMOTE_NAMESPACE, "openremote", null); document.getDocumentElement().setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation", "http://www.openremote.org http://www.openremote.org/schemas/controller.xsd"); Element componentsElement = document.createElementNS(OPENREMOTE_NAMESPACE, "components"); document.getDocumentElement().appendChild(componentsElement); writeSensors(document, document.getDocumentElement(), account, findHighestCommandId(account)); writeCommands(document, document.getDocumentElement(), account); writeConfig(document, document.getDocumentElement(), account); // Document is fully built, validate against schema before writing to file URL xsdResource = UsersAPI.class.getResource(CONTROLLER_XSD_PATH); if (xsdResource == null) { log.error("Cannot find XSD schema ''{0}''. Disabling validation...", CONTROLLER_XSD_PATH); } else { String language = XMLConstants.W3C_XML_SCHEMA_NS_URI; SchemaFactory factory = SchemaFactory.newInstance(language); Schema schema = factory.newSchema(xsdResource); Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); } Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Result output = new StreamResult(controllerXmlFile); Source input = new DOMSource(document); transformer.transform(input, output); } catch (ParserConfigurationException e) { log.error("Error generating controller.xml file", e); throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR); } catch (TransformerConfigurationException e) { log.error("Error generating controller.xml file", e); throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR); } catch (TransformerException e) { log.error("Error generating controller.xml file", e); throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR); } catch (SAXException e) { log.error("Error generating controller.xml file", e); throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR); } catch (IOException e) { log.error("Error generating controller.xml file", e); throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR); } return controllerXmlFile; }
From source file:com.graphhopper.util.InstructionListTest.java
public void verifyGPX(String gpx) { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = null;/* ww w . ja v a 2 s.co m*/ try { Source schemaFile = new StreamSource(getClass().getResourceAsStream("gpx-schema.xsd")); schema = schemaFactory.newSchema(schemaFile); // using more schemas: http://stackoverflow.com/q/1094893/194609 } catch (SAXException e1) { throw new IllegalStateException( "There was a problem with the schema supplied for validation. Message:" + e1.getMessage()); } Validator validator = schema.newValidator(); try { validator.validate(new StreamSource(new StringReader(gpx))); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.panet.imeta.trans.steps.xsdvalidator.XsdValidator.java
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (XsdValidatorMeta) smi;/*www. j a v a 2 s .com*/ data = (XsdValidatorData) sdi; Object[] row = getRow(); if (row == null) // no more input to be expected... { setOutputDone(); return false; } if (first) { first = false; data.outputRowMeta = getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); // Check if XML stream is given if (meta.getXMLStream() != null) { // Try to get XML Field index data.xmlindex = getInputRowMeta().indexOfValue(meta.getXMLStream()); // Let's check the Field if (data.xmlindex < 0) { // The field is unreachable ! logError(Messages.getString("XsdValidator.Log.ErrorFindingField") + "[" + meta.getXMLStream() //$NON-NLS-1$//$NON-NLS-2$ + "]"); throw new KettleStepException( Messages.getString("XsdValidator.Exception.CouldnotFindField", meta.getXMLStream())); //$NON-NLS-1$ //$NON-NLS-2$ } // Let's check that Result Field is given if (meta.getResultfieldname() == null) { // Result field is missing ! logError(Messages.getString("XsdValidator.Log.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException( Messages.getString("XsdValidator.Exception.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$ } // Is XSD file is provided? if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) { if (meta.getXSDFilename() == null) { logError(Messages.getString("XsdValidator.Log.ErrorXSDFileMissing")); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException( Messages.getString("XsdValidator.Exception.ErrorXSDFileMissing")); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Is XSD file exists ? FileObject xsdfile = null; try { xsdfile = KettleVFS.getFileObject(environmentSubstitute(meta.getXSDFilename())); if (!xsdfile.exists()) { logError(Messages.getString("XsdValidator.Log.Error.XSDFileNotExists")); throw new KettleStepException( Messages.getString("XsdValidator.Exception.XSDFileNotExists")); } } catch (Exception e) { logError(Messages.getString("XsdValidator.Log.Error.GettingXSDFile")); throw new KettleStepException( Messages.getString("XsdValidator.Exception.GettingXSDFile")); } finally { try { if (xsdfile != null) xsdfile.close(); } catch (IOException e) { } } } } // Is XSD field is provided? if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) { if (meta.getXSDDefinedField() == null) { logError(Messages.getString("XsdValidator.Log.Error.XSDFieldMissing")); throw new KettleStepException(Messages.getString("XsdValidator.Exception.XSDFieldMissing")); } else { // Let's check if the XSD field exist // Try to get XML Field index data.xsdindex = getInputRowMeta().indexOfValue(meta.getXSDDefinedField()); if (data.xsdindex < 0) { // The field is unreachable ! logError(Messages.getString("XsdValidator.Log.ErrorFindingXSDField", //$NON-NLS-1$ meta.getXSDDefinedField())); //$NON-NLS-2$ throw new KettleStepException(Messages.getString( "XsdValidator.Exception.ErrorFindingXSDField", meta.getXSDDefinedField())); //$NON-NLS-1$ //$NON-NLS-2$ } } } } else { // XML stream field is missing ! logError(Messages.getString("XsdValidator.Log.Error.XmlStreamFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException(Messages.getString("XsdValidator.Exception.XmlStreamFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$ } } boolean sendToErrorRow = false; String errorMessage = null; try { // Get the XML field value String XMLFieldvalue = getInputRowMeta().getString(row, data.xmlindex); boolean isvalid = false; // XSD filename String xsdfilename = null; if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) { xsdfilename = environmentSubstitute(meta.getXSDFilename()); } else if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) { // Get the XSD field value xsdfilename = getInputRowMeta().getString(row, data.xsdindex); } // Get XSD filename FileObject xsdfile = null; String validationmsg = null; try { SchemaFactory factoryXSDValidator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); xsdfile = KettleVFS.getFileObject(xsdfilename); File XSDFile = new File(KettleVFS.getFilename(xsdfile)); // Get XML stream Source sourceXML = new StreamSource(new StringReader(XMLFieldvalue)); if (meta.getXMLSourceFile()) { // We deal with XML file // Get XML File File xmlfileValidator = new File(XMLFieldvalue); if (!xmlfileValidator.exists()) { logError(Messages.getString("XsdValidator.Log.Error.XMLfileMissing", XMLFieldvalue)); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException( Messages.getString("XsdValidator.Exception.XMLfileMissing", XMLFieldvalue)); //$NON-NLS-1$ //$NON-NLS-2$ } sourceXML = new StreamSource(xmlfileValidator); } // Create XSD schema Schema SchematXSD = factoryXSDValidator.newSchema(XSDFile); if (meta.getXSDSource().equals(meta.NO_NEED)) { // ---Some documents specify the schema they expect to be validated against, // ---typically using xsi:noNamespaceSchemaLocation and/or xsi:schemaLocation attributes //---Schema SchematXSD = factoryXSDValidator.newSchema(); SchematXSD = factoryXSDValidator.newSchema(); } // Create XSDValidator Validator XSDValidator = SchematXSD.newValidator(); // Validate XML / XSD XSDValidator.validate(sourceXML); isvalid = true; } catch (SAXException ex) { validationmsg = ex.getMessage(); logError("SAX Exception : " + ex); } catch (IOException ex) { validationmsg = ex.getMessage(); logError("SAX Exception : " + ex); } finally { try { if (xsdfile != null) xsdfile.close(); } catch (IOException e) { } } Object[] outputRowData = null; Object[] outputRowData2 = null; if (meta.getOutputStringField()) { // Output type=String if (isvalid) outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(), environmentSubstitute(meta.getIfXmlValid())); else outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(), environmentSubstitute(meta.getIfXmlInvalid())); } else { outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(), isvalid); } if (meta.useAddValidationMessage()) outputRowData2 = RowDataUtil.addValueData(outputRowData, getInputRowMeta().size() + 1, validationmsg); else outputRowData2 = outputRowData; if (log.isRowLevel()) logRowlevel( Messages.getString("XsdValidator.Log.ReadRow") + " " + getInputRowMeta().getString(row)); // add new values to the row. putRow(data.outputRowMeta, outputRowData2); // copy row to output rowset(s); } catch (KettleException e) { if (getStepMeta().isDoingErrorHandling()) { sendToErrorRow = true; errorMessage = e.toString(); } if (sendToErrorRow) { // Simply add this row to the error row putError(getInputRowMeta(), row, 1, errorMessage, null, "XSD001"); } else { logError(Messages.getString("XsdValidator.ErrorProcesing" + " : " + e.getMessage())); throw new KettleStepException(Messages.getString("XsdValidator.ErrorProcesing"), e); } } return true; }
From source file:de.fzi.ALERT.actor.MessageObserver.ComplexEventObserver.JMSMessageParser.java
public void validateXml(Schema schema, org.w3c.dom.Document doc) { try {/* w w w .j av a 2 s .c om*/ // creating a Validator instance Validator validator = schema.newValidator(); System.out.println(); System.out.println("Validator Class: " + validator.getClass().getName()); // setting my own error handler validator.setErrorHandler(new MyErrorHandler()); // validating the document against the schema validator.validate(new DOMSource(doc)); System.out.println(); if (errorCount > 0) { System.out.println("Failed with errors: " + errorCount); } else { System.out.println("Passed."); } } catch (Exception e) { // catching all validation exceptions System.out.println(); System.out.println(e.toString()); } }
From source file:com.panet.imeta.job.entries.xsdvalidator.JobEntryXSDValidator.java
public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = previousResult; result.setResult(false);/*from w w w. j av a 2 s. c om*/ String realxmlfilename = getRealxmlfilename(); String realxsdfilename = getRealxsdfilename(); FileObject xmlfile = null; FileObject xsdfile = null; try { if (xmlfilename != null && xsdfilename != null) { xmlfile = KettleVFS.getFileObject(realxmlfilename); xsdfile = KettleVFS.getFileObject(realxsdfilename); if (xmlfile.exists() && xsdfile.exists()) { SchemaFactory factorytXSDValidator_1 = SchemaFactory .newInstance("http://www.w3.org/2001/XMLSchema"); // Get XSD File File XSDFile = new File(KettleVFS.getFilename(xsdfile)); Schema SchematXSD = factorytXSDValidator_1.newSchema(XSDFile); Validator XSDValidator = SchematXSD.newValidator(); // Get XML File File xmlfiletXSDValidator_1 = new File(KettleVFS.getFilename(xmlfile)); Source sourcetXSDValidator_1 = new StreamSource(xmlfiletXSDValidator_1); XSDValidator.validate(sourcetXSDValidator_1); // Everything is OK result.setResult(true); } else { if (!xmlfile.exists()) { log.logError(toString(), Messages.getString("JobEntryXSDValidator.FileDoesNotExist1.Label") + realxmlfilename + Messages.getString("JobEntryXSDValidator.FileDoesNotExist2.Label")); } if (!xsdfile.exists()) { log.logError(toString(), Messages.getString("JobEntryXSDValidator.FileDoesNotExist1.Label") + realxsdfilename + Messages.getString("JobEntryXSDValidator.FileDoesNotExist2.Label")); } result.setResult(false); result.setNrErrors(1); } } else { log.logError(toString(), Messages.getString("JobEntryXSDValidator.AllFilesNotNull.Label")); result.setResult(false); result.setNrErrors(1); } } catch (SAXException ex) { log.logError(toString(), "Error :" + ex.getMessage()); } catch (Exception e) { log.logError(toString(), Messages.getString("JobEntryXSDValidator.ErrorXSDValidator.Label") + Messages.getString("JobEntryXSDValidator.ErrorXML1.Label") + realxmlfilename + Messages.getString("JobEntryXSDValidator.ErrorXML2.Label") + Messages.getString("JobEntryXSDValidator.ErrorXSD1.Label") + realxsdfilename + Messages.getString("JobEntryXSDValidator.ErrorXSD2.Label") + e.getMessage()); result.setResult(false); result.setNrErrors(1); } finally { try { if (xmlfile != null) xmlfile.close(); if (xsdfile != null) xsdfile.close(); } catch (IOException e) { } } return result; }
From source file:eu.esdihumboldt.hale.io.appschema.writer.AppSchemaFileWriterTest.java
private boolean isMappingValid(File mappingFile) throws IOException { URL mappingSchema = getClass().getResource(MAPPING_SCHEMA); Source xmlFile = new StreamSource(mappingFile); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); javax.xml.validation.Schema schema = null; try {/*w ww .ja v a2 s . c o m*/ schema = schemaFactory.newSchema(mappingSchema); } catch (SAXException e) { fail("Exception parsing mapping schema: " + e.getMessage()); } @SuppressWarnings("null") Validator validator = schema.newValidator(); try { validator.validate(xmlFile); return true; } catch (SAXException e) { log.error("Mapping file validation failed", e); return false; } }
From source file:com.rapid.server.RapidServletContextListener.java
public static int loadDatabaseDrivers(ServletContext servletContext) throws Exception { // create a schema object for the xsd Schema schema = _schemaFactory .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/databaseDrivers.xsd")); // create a validator Validator validator = schema.newValidator(); // read the xml into a string String xml = Strings// w w w.j a v a 2 s .co m .getString(new File(servletContext.getRealPath("/WEB-INF/database/") + "/databaseDrivers.xml")); // validate the control xml file against the schema validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8")))); // convert the xml string into JSON JSONObject jsonDatabaseDriverCollection = org.json.XML.toJSONObject(xml).getJSONObject("databaseDrivers"); // prepare the array we are going to popoulate JSONArray jsonDatabaseDrivers = new JSONArray(); JSONObject jsonDatabaseDriver; int index = 0; int count = 0; if (jsonDatabaseDriverCollection.optJSONArray("databaseDriver") == null) { jsonDatabaseDriver = jsonDatabaseDriverCollection.getJSONObject("databaseDriver"); } else { jsonDatabaseDriver = jsonDatabaseDriverCollection.getJSONArray("databaseDriver").getJSONObject(index); count = jsonDatabaseDriverCollection.getJSONArray("databaseDriver").length(); } do { _logger.info("Registering database driver " + jsonDatabaseDriver.getString("name") + " using " + jsonDatabaseDriver.getString("class")); try { // check this type does not already exist for (int i = 0; i < jsonDatabaseDrivers.length(); i++) { if (jsonDatabaseDriver.getString("name") .equals(jsonDatabaseDrivers.getJSONObject(i).getString("name"))) throw new Exception(" database driver type is loaded already. Type names must be unique"); } // get the class name String className = jsonDatabaseDriver.getString("class"); // get the current thread class loader (this should log better if there are any issues) ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // check we got a class loader if (classLoader == null) { // register the class the old fashioned way so the DriverManager can find it Class.forName(className); } else { // register the class on this thread so we can catch any errors Class.forName(className, true, classLoader); } // add the jsonControl to our array jsonDatabaseDrivers.put(jsonDatabaseDriver); } catch (Exception ex) { _logger.error("Error registering database driver : " + ex.getMessage(), ex); } // inc the count of controls in this file index++; // get the next one if (index < count) jsonDatabaseDriver = jsonDatabaseDriverCollection.getJSONArray("databaseDriver") .getJSONObject(index); } while (index < count); // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet) servletContext.setAttribute("jsonDatabaseDrivers", jsonDatabaseDrivers); _logger.info(index + " database drivers loaded from databaseDrivers.xml file"); return index; }
From source file:com.rapid.server.RapidServletContextListener.java
public static int loadSecurityAdapters(ServletContext servletContext) throws Exception { int adapterCount = 0; // retain our class constructors in a hashtable - this speeds up initialisation HashMap<String, Constructor> securityConstructors = new HashMap<String, Constructor>(); // create a JSON Array object which will hold json for all of the available security adapters JSONArray jsonSecurityAdapters = new JSONArray(); // get the directory in which the control xml files are stored File dir = new File(servletContext.getRealPath("/WEB-INF/security/")); // create a filter for finding .securityadapter.xml files FilenameFilter xmlFilenameFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".securityadapter.xml"); }/*from w w w.ja v a 2 s. c o m*/ }; // create a schema object for the xsd Schema schema = _schemaFactory .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/securityAdapter.xsd")); // create a validator Validator validator = schema.newValidator(); // loop the xml files in the folder for (File xmlFile : dir.listFiles(xmlFilenameFilter)) { // read the xml into a string String xml = Strings.getString(xmlFile); // validate the control xml file against the schema validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8")))); // convert the string into JSON JSONObject jsonSecurityAdapter = org.json.XML.toJSONObject(xml).getJSONObject("securityAdapter"); // get the type from the json String type = jsonSecurityAdapter.getString("type"); // get the class name from the json String className = jsonSecurityAdapter.getString("class"); // get the class Class classClass = Class.forName(className); // check the class extends com.rapid.security.SecurityAdapter if (!Classes.extendsClass(classClass, com.rapid.security.SecurityAdapter.class)) throw new Exception(type + " security adapter class " + classClass.getCanonicalName() + " must extend com.rapid.security.SecurityAdapter"); // check this type is unique if (securityConstructors.get(type) != null) throw new Exception(type + " security adapter already loaded. Type names must be unique."); // add to constructors hashmap referenced by type securityConstructors.put(type, classClass.getConstructor(ServletContext.class, Application.class)); // add to our collection jsonSecurityAdapters.put(jsonSecurityAdapter); // increment the count adapterCount++; } // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet) servletContext.setAttribute("jsonSecurityAdapters", jsonSecurityAdapters); // put the constructors hashmapin a context attribute (this is available via the getContructor method in RapidHttpServlet) servletContext.setAttribute("securityConstructors", securityConstructors); _logger.info(adapterCount + " security adapters loaded in .securityAdapter.xml files"); return adapterCount; }
From source file:com.rapid.server.RapidServletContextListener.java
public static int loadFormAdapters(ServletContext servletContext) throws Exception { int adapterCount = 0; // retain our class constructors in a hashtable - this speeds up initialisation HashMap<String, Constructor> formConstructors = new HashMap<String, Constructor>(); // create a JSON Array object which will hold json for all of the available security adapters JSONArray jsonAdapters = new JSONArray(); // get the directory in which the control xml files are stored File dir = new File(servletContext.getRealPath("/WEB-INF/forms/")); // create a filter for finding .formadapter.xml files FilenameFilter xmlFilenameFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".formadapter.xml"); }//from w w w. j ava2s. c o m }; // create a schema object for the xsd Schema schema = _schemaFactory .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/formAdapter.xsd")); // create a validator Validator validator = schema.newValidator(); // loop the xml files in the folder for (File xmlFile : dir.listFiles(xmlFilenameFilter)) { // read the xml into a string String xml = Strings.getString(xmlFile); // validate the control xml file against the schema validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8")))); // convert the string into JSON JSONObject jsonFormAdapter = org.json.XML.toJSONObject(xml).getJSONObject("formAdapter"); // get the type from the json String type = jsonFormAdapter.getString("type"); // get the class name from the json String className = jsonFormAdapter.getString("class"); // get the class Class classClass = Class.forName(className); // check the class extends com.rapid.security.SecurityAdapter if (!Classes.extendsClass(classClass, com.rapid.forms.FormAdapter.class)) throw new Exception(type + " form adapter class " + classClass.getCanonicalName() + " must extend com.rapid.forms.FormsAdapter"); // check this type is unique if (formConstructors.get(type) != null) throw new Exception(type + " form adapter already loaded. Type names must be unique."); // add to constructors hashmap referenced by type formConstructors.put(type, classClass.getConstructor(ServletContext.class, Application.class)); // add to our collection jsonAdapters.put(jsonFormAdapter); // increment the count adapterCount++; } // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet) servletContext.setAttribute("jsonFormAdapters", jsonAdapters); // put the constructors hashmapin a context attribute (this is available via the getContructor method in RapidHttpServlet) servletContext.setAttribute("formConstructors", formConstructors); _logger.info(adapterCount + " form adapters loaded in .formAdapter.xml files"); return adapterCount; }