List of usage examples for javax.xml.validation Schema newValidator
public abstract Validator newValidator();
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);/*ww w. j ava 2 s . c o m*/ 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:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizer.java
/** * Validate the configuration against XML Schema. * * @throws ConfigException if not valid/*from ww w . j a v a 2 s . c o m*/ */ private void validateXMLConfiguration(InputStream xmlConfigurationStream) throws IOException, ConfigException { assert xmlConfigurationStream != null; final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { final Schema schema = sf .newSchema(MathMLCanonicalizer.class.getResource(Settings.getProperty("configSchema"))); final Validator validator = schema.newValidator(); validator.validate(new StreamSource(xmlConfigurationStream)); } catch (SAXException ex) { throw new ConfigException("configuration not valid\n" + ex.getMessage(), ex); } }
From source file:gov.nih.nci.ncicb.tcga.dcc.common.util.BCRXMLFileReader.java
private void processXML(final InputStream in) throws SAXException, ParserConfigurationException, IOException { // Some of the following code is nabbed from http://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi.html final SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); final File schemaLocation = bcrXSD; final Schema schema; schema = factory.newSchema(schemaLocation); final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); // never forget this final DocumentBuilder builder = domFactory.newDocumentBuilder(); document = builder.parse(in);//from ww w. jav a 2 s . com final DOMSource source = new DOMSource(document); final Validator validator = schema.newValidator(); //Check to see if we actually want to validate docs or just skip. if (isValidate()) { validator.validate(source); } }
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 {//w w w.j a v a 2s .co 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.rapid.server.RapidServletContextListener.java
public static int loadThemes(ServletContext servletContext) throws Exception { // assume no themes int themeCount = 0; // create a list for our themes List<Theme> themes = new ArrayList<Theme>(); // get the directory in which the control xml files are stored File dir = new File(servletContext.getRealPath("/WEB-INF/themes/")); // create a filter for finding .control.xml files FilenameFilter xmlFilenameFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".theme.xml"); }/*from w w w. j a v a 2s . co m*/ }; // create a schema object for the xsd Schema schema = _schemaFactory .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/theme.xsd")); // create a validator Validator validator = schema.newValidator(); // loop the xml files in the folder for (File xmlFile : dir.listFiles(xmlFilenameFilter)) { // get a scanner to read the file Scanner fileScanner = new Scanner(xmlFile).useDelimiter("\\A"); // read the xml into a string String xml = fileScanner.next(); // close the scanner (and file) fileScanner.close(); // validate the control xml file against the schema validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8")))); // create a theme object from the xml Theme theme = new Theme(xml); // add it to our collection themes.add(theme); // inc the template count themeCount++; } // sort the list of templates by name Collections.sort(themes, new Comparator<Theme>() { @Override public int compare(Theme t1, Theme t2) { return Comparators.AsciiCompare(t1.getName(), t2.getName(), false); } }); // put the jsonControls in a context attribute (this is available via the getJsonControls method in RapidHttpServlet) servletContext.setAttribute("themes", themes); _logger.info(themeCount + " templates loaded in .template.xml files"); return themeCount; }
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 ww. ja v a 2s. 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; }
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 www . j a va2 s .co 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 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//from w ww. j a v a 2 s . c o 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:eu.artist.postmigration.eubt.executiontrace.abstractor.SOAPTraceAbstractor.java
/** * Validates soap trace (i.e., list of soap responses) against schema and * stores the result//from w ww. j a va 2 s. c o m * * @param soapResponseTrace trace that contains soap responses * @return map of soap responses and their respective validation result * @throws EUBTException in case the schema location could not be found */ private LinkedMap<SOAPResponse, String> validateSoapTrace(final SOAPTrace soapResponseTrace) throws EUBTException { final LinkedMap<SOAPResponse, String> validationResults = new LinkedMap<SOAPResponse, String>(); final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Validator validator; try { final Schema schema = schemaFactory.newSchema(new URL(schemaLocation)); validator = schema.newValidator(); } catch (SAXException | IOException e) { throw new EUBTException("Failed to create Schema from Schema location " + schemaLocation + ". Detailed Exception: " + e.getMessage()); } // for each soap response for (final Response response : soapResponseTrace.getResponses()) { String validationResult = VALIDATION_INVALID; final SOAPResponse soapResponse = (SOAPResponse) response; final SOAPEnvelope soapEnvelope = (SOAPEnvelope) soapResponse.getData(); final OMElement bodyContent = soapEnvelope.getBody().getFirstElement(); // create some invalid content // SOAP12Factory factory = new SOAP12Factory(); // OMElement invalidElement = factory.createOMElement(new QName("blah")); // OMNamespace invalidNamespace = factory.createOMNamespace("http://notMyNamespace.com", "invNS"); // OMAttribute invalidAttribute = factory.createOMAttribute("someAttribute", invalidNamespace, "attributeValue"); // bodyContent.addChild(invalidElement); // bodyContent.addAttribute(invalidAttribute); // validate soap body content -> will cause an exception if not valid try { validator.validate(bodyContent.getSAXSource(true)); // validation succeeded validationResult = VALIDATION_VALID; Debug.debug(this, "Successfully validated SOAP body content " + bodyContent); } catch (final IOException e) { throw new EUBTException("Failed to validate SOAP body content " + bodyContent + ". Detailed Exception: " + e.getMessage()); } catch (final SAXException e) { // validation failed Debug.debug(this, "Failed to validate soap SOAP content " + bodyContent + ". Detailed Exception: " + e.getMessage()); } // finished validating, store result validationResults.put(soapResponse, validationResult); validator.reset(); } // for each soap response return validationResults; }
From source file:com.rapid.server.RapidServletContextListener.java
public static int loadConnectionAdapters(ServletContext servletContext) throws Exception { int adapterCount = 0; // retain our class constructors in a hashtable - this speeds up initialisation HashMap<String, Constructor> connectionConstructors = new HashMap<String, Constructor>(); // create an array list of json objects which we will sort later according to the order ArrayList<JSONObject> connectionAdapters = new ArrayList<JSONObject>(); // get the directory in which the control xml files are stored File dir = new File(servletContext.getRealPath("/WEB-INF/database/")); // create a filter for finding .control.xml files FilenameFilter xmlFilenameFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".connectionadapter.xml"); }/*from w ww .j a v a2 s. c o m*/ }; // create a schema object for the xsd Schema schema = _schemaFactory .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/connectionAdapter.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 jsonConnectionAdapter = org.json.XML.toJSONObject(xml).getJSONObject("connectionAdapter"); // get the class name from the json String className = jsonConnectionAdapter.getString("class"); // get the class Class classClass = Class.forName(className); // check the class extends com.rapid.data.ConnectionAdapter if (!Classes.extendsClass(classClass, com.rapid.data.ConnectionAdapter.class)) throw new Exception( classClass.getCanonicalName() + " must extend com.rapid.data.ConnectionAdapter"); // check this class is unique if (connectionConstructors.get(className) != null) throw new Exception(className + " connection adapter already loaded."); // add to constructors hashmap referenced by type connectionConstructors.put(className, classClass.getConstructor(ServletContext.class, String.class, String.class, String.class, String.class)); // add to to our array list connectionAdapters.add(jsonConnectionAdapter); // increment the count adapterCount++; } // sort the connection adapters according to their order property Collections.sort(connectionAdapters, new Comparator<JSONObject>() { @Override public int compare(JSONObject o1, JSONObject o2) { try { return o1.getInt("order") - o2.getInt("order"); } catch (JSONException e) { return 999; } } }); // create a JSON Array object which will hold json for all of the available security adapters JSONArray jsonConnectionAdapters = new JSONArray(); // loop the sorted connection adapters and add to the json array for (JSONObject jsonConnectionAdapter : connectionAdapters) jsonConnectionAdapters.put(jsonConnectionAdapter); // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet) servletContext.setAttribute("jsonConnectionAdapters", jsonConnectionAdapters); // put the constructors hashmapin a context attribute (this is available via the getContructor method in RapidHttpServlet) servletContext.setAttribute("securityConstructors", connectionConstructors); _logger.info(adapterCount + " connection adapters loaded in .connectionAdapter.xml files"); return adapterCount; }