List of usage examples for javax.xml.validation Schema newValidator
public abstract Validator newValidator();
From source file:com.rapid.server.RapidServletContextListener.java
public static int loadControls(ServletContext servletContext) throws Exception { // assume no controls int controlCount = 0; // create a list for our controls List<JSONObject> jsonControls = new ArrayList<JSONObject>(); // get the directory in which the control xml files are stored File dir = new File(servletContext.getRealPath("/WEB-INF/controls/")); // create a filter for finding .control.xml files FilenameFilter xmlFilenameFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".control.xml"); }//from ww w .j a v a 2s. c om }; // create a schema object for the xsd Schema schema = _schemaFactory .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/control.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")))); // convert the string into JSON JSONObject jsonControlCollection = org.json.XML.toJSONObject(xml).getJSONObject("controls"); JSONObject jsonControl; int index = 0; int count = 0; if (jsonControlCollection.optJSONArray("control") == null) { jsonControl = jsonControlCollection.getJSONObject("control"); } else { jsonControl = jsonControlCollection.getJSONArray("control").getJSONObject(index); count = jsonControlCollection.getJSONArray("control").length(); } do { // check this type does not already exist for (int i = 0; i < jsonControls.size(); i++) { if (jsonControl.getString("type").equals(jsonControls.get(i).getString("type"))) throw new Exception(" control type is loaded already. Type names must be unique"); } // add the jsonControl to our array jsonControls.add(jsonControl); // inc the control count controlCount++; // inc the count of controls in this file index++; // get the next one if (index < count) jsonControl = jsonControlCollection.getJSONArray("control").getJSONObject(index); } while (index < count); } // sort the list of controls by name Collections.sort(jsonControls, new Comparator<JSONObject>() { @Override public int compare(JSONObject c1, JSONObject c2) { try { return Comparators.AsciiCompare(c1.getString("name"), c2.getString("name"), false); } catch (JSONException e) { return 0; } } }); // create a JSON Array object which will hold json for all of the available controls JSONArray jsonArrayControls = new JSONArray(jsonControls); // put the jsonControls in a context attribute (this is available via the getJsonControls method in RapidHttpServlet) servletContext.setAttribute("jsonControls", jsonArrayControls); _logger.info(controlCount + " controls loaded in .control.xml files"); return controlCount; }
From source file:com.rapid.server.RapidServletContextListener.java
public static int loadActions(ServletContext servletContext) throws Exception { // assume no actions int actionCount = 0; // create a list of json actions which we will sort later List<JSONObject> jsonActions = new ArrayList<JSONObject>(); // retain our class constructors in a hashtable - this speeds up initialisation HashMap<String, Constructor> actionConstructors = new HashMap<String, Constructor>(); // build a collection of classes so we can re-initilise the JAXB context to recognise our injectable classes ArrayList<Action> actions = new ArrayList<Action>(); // get the directory in which the control xml files are stored File dir = new File(servletContext.getRealPath("/WEB-INF/actions/")); // create a filter for finding .control.xml files FilenameFilter xmlFilenameFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".action.xml"); }// w w w . j a v a 2 s . co m }; // create a schema object for the xsd Schema schema = _schemaFactory .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/action.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")))); // convert the string into JSON JSONObject jsonActionCollection = org.json.XML.toJSONObject(xml).getJSONObject("actions"); JSONObject jsonAction; int index = 0; int count = 0; // the JSON library will add a single key of there is a single class, otherwise an array if (jsonActionCollection.optJSONArray("action") == null) { jsonAction = jsonActionCollection.getJSONObject("action"); } else { jsonAction = jsonActionCollection.getJSONArray("action").getJSONObject(index); count = jsonActionCollection.getJSONArray("action").length(); } do { // check this type does not already exist for (int i = 0; i < jsonActions.size(); i++) { if (jsonAction.getString("type").equals(jsonActions.get(i).getString("type"))) throw new Exception(" action type is loaded already. Type names must be unique"); } // add the jsonControl to our array jsonActions.add(jsonAction); // get the named type from the json String type = jsonAction.getString("type"); // get the class name from the json String className = jsonAction.getString("class"); // get the class Class classClass = Class.forName(className); // check the class extends com.rapid.Action if (!Classes.extendsClass(classClass, com.rapid.core.Action.class)) throw new Exception(type + " action class " + classClass.getCanonicalName() + " must extend com.rapid.core.Action."); // check this type is unique if (actionConstructors.get(type) != null) throw new Exception(type + " action already loaded. Type names must be unique."); // add to constructors hashmap referenced by type actionConstructors.put(type, classClass.getConstructor(RapidHttpServlet.class, JSONObject.class)); // add to our jaxb classes collection _jaxbClasses.add(classClass); // inc the control count actionCount++; // inc the count of controls in this file index++; // get the next one if (index < count) jsonAction = jsonActionCollection.getJSONArray("control").getJSONObject(index); } while (index < count); } // sort the list of actions by name Collections.sort(jsonActions, new Comparator<JSONObject>() { @Override public int compare(JSONObject c1, JSONObject c2) { try { return Comparators.AsciiCompare(c1.getString("name"), c2.getString("name"), false); } catch (JSONException e) { return 0; } } }); // create a JSON Array object which will hold json for all of the available controls JSONArray jsonArrayActions = new JSONArray(jsonActions); // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet) servletContext.setAttribute("jsonActions", jsonArrayActions); // put the constructors hashmapin a context attribute (this is available via the getContructor method in RapidHttpServlet) servletContext.setAttribute("actionConstructors", actionConstructors); _logger.info(actionCount + " actions loaded in .action.xml files"); return actionCount; }
From source file:edu.wustl.bulkoperator.templateImport.AbstractImportBulkOperation.java
/** * * @param operationName/*ww w.ja va 2 s .c o m*/ * @param dropdownName * @param csvFile * @param xmlFile * @param mappingXml * @return * @throws BulkOperationException * @throws SQLException * @throws IOException * @throws DAOException */ protected Set<String> validate(String operationName, String dropdownName, String csvFile, String xmlFile, String mappingXml, String xsdLocation) throws BulkOperationException, SQLException, IOException, DAOException { Set<String> errorList = null; CsvReader csvReader = null; try { csvReader = CsvFileReader.createCsvFileReader(csvFile, true); } catch (Exception exp) { ErrorKey errorkey = ErrorKey.getErrorKey("bulk.error.incorrect.csv.file"); throw new BulkOperationException(errorkey, exp, ""); } BulkOperationMetaData bulkOperationMetaData = null; try { SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); File schemaLocation = new File(xsdLocation); Schema schema = factory.newSchema(schemaLocation); DigesterLoader digesterLoader = DigesterLoader.newLoader(new XmlRulesModule(mappingXml)); Digester digester = digesterLoader.newDigester(); digester.setValidating(true); digester.setXMLSchema(schema); Validator validator = schema.newValidator(); Source xmlFileForValidation = new StreamSource(new File(xmlFile)); validator.validate(xmlFileForValidation); InputStream inputStream = new FileInputStream(xmlFile); bulkOperationMetaData = digester.parse(inputStream); } catch (SAXException e) { logger.debug(e.getMessage()); ErrorKey errorkey = ErrorKey.getErrorKey("bulk.error.xml.template"); throw new BulkOperationException(errorkey, e, e.getMessage()); } Collection<BulkOperationClass> classList = bulkOperationMetaData.getBulkOperationClass(); if (classList == null) { ErrorKey errorkey = ErrorKey.getErrorKey("bulk.no.templates.loaded.message"); throw new BulkOperationException(errorkey, null, ""); } else { Iterator<BulkOperationClass> iterator = classList.iterator(); if (iterator.hasNext()) { BulkOperationClass bulkOperationClass = iterator.next(); TemplateValidator templateValidator = new TemplateValidator(); errorList = templateValidator.validateXmlAndCsv(bulkOperationClass, operationName, csvReader); } } return errorList; }
From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.util.QCliveXMLSchemaValidator.java
protected Boolean validateSchema(final List<Source> schemaSourceList, final Document document, final File xmlFile, final QcContext context) throws SAXException, IOException { final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // instantiate the schema Schema schema = factory.newSchema(schemaSourceList.toArray(new Source[] {})); // now validate the file against the schema // note: supposedly there is a way to just let the XML document figure // out its own schema based on what is referred to, but // I could not get that to work, which is why I am looking for the // schema in the attribute final DOMSource source = new DOMSource(document); final Validator validator = schema.newValidator(); // wow this looks dumb, but isValid has to be final to be accessed from // within an inner class // and this was IDEA's solution to the problem: make it an array and set // the first element of the array final boolean[] isValid = new boolean[] { true }; // add error handler that will add validation errors and warnings // directly to the QcContext object validator.setErrorHandler(new ErrorHandler() { public void warning(final SAXParseException exception) { context.addWarning(new StringBuilder().append(xmlFile.getName()).append(": ") .append(exception.getMessage()).toString()); }//www . jav a 2 s. co m public void error(final SAXParseException exception) { context.addError(MessageFormat.format(MessagePropertyType.XML_FILE_PROCESSING_ERROR, xmlFile.getName(), new StringBuilder().append(xmlFile.getName()).append(": ") .append(exception.getMessage()).toString())); isValid[0] = false; } public void fatalError(final SAXParseException exception) throws SAXException { context.getArchive().setDeployStatus(Archive.STATUS_INVALID); throw exception; } }); validator.validate(source); return isValid[0]; }
From source file:edu.unc.lib.dl.ingest.sip.METSPackageSIPProcessor.java
private void xsdValidate(File metsFile2) throws IngestException { // TODO can reuse schema object, it is thread safe javax.xml.validation.SchemaFactory schemaFactory = javax.xml.validation.SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); StreamSource xml = new StreamSource(getClass().getResourceAsStream(schemaPackage + "xml.xsd")); StreamSource xlink = new StreamSource(getClass().getResourceAsStream(schemaPackage + "xlink.xsd")); StreamSource mets = new StreamSource(getClass().getResourceAsStream(schemaPackage + "mets.xsd")); StreamSource premis = new StreamSource(getClass().getResourceAsStream(schemaPackage + "premis-v2-0.xsd")); StreamSource mods = new StreamSource(getClass().getResourceAsStream(schemaPackage + "mods-3-4.xsd")); StreamSource acl = new StreamSource(getClass().getResourceAsStream(schemaPackage + "acl.xsd")); Schema schema; try {/*from w ww . ja v a 2 s .c o m*/ Source[] sources = { xml, xlink, mets, premis, mods, acl }; schema = schemaFactory.newSchema(sources); } catch (SAXException e) { throw new Error("Cannot locate METS schema in classpath.", e); } Validator metsValidator = schema.newValidator(); METSParseException handler = new METSParseException("There was a problem parsing METS XML."); metsValidator.setErrorHandler(handler); // TODO get a Result document for reporting error try { metsValidator.validate(new StreamSource(metsFile2)); } catch (SAXException e) { if (log.isDebugEnabled()) { log.debug(e.getMessage()); } throw handler; } catch (IOException e) { throw new IngestException("The supplied METS file is not readable.", e); } }
From source file:org.kite9.diagram.server.AbstractKite9Controller.java
protected void validateXML(String xml) throws SAXException, IOException { // validate the xml against the schema InputSource is = new InputSource(new StringReader(xml)); SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); // load a WXS schema, represented by a Schema instance Source schemaFile = new StreamSource(Diagram.class.getResourceAsStream("/adl_1.0.xsd")); Schema schema = factory.newSchema(schemaFile); Validator validator = schema.newValidator(); SAXSource source = new SAXSource(is); validator.validate(source);//from w ww.j a v a2 s . c o m }
From source file:org.rivetlogic.export.components.AbstractXMLProcessor.java
public void setXsdPath(String xsdPath) throws SAXException { this.xsdPath = xsdPath; if (xsdPath != null) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = null; try {//www .j a v a 2 s. co m schema = factory.newSchema(this.getClass().getClassLoader().getResource(xsdPath)); } catch (SAXException e) { logger.error(e); throw e; } validator = schema.newValidator(); } }
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; try {//from w ww .j a v a 2 s.c o m 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;/* ww w. j a v a2 s . c o m*/ 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:fll.scheduler.TournamentSchedule.java
/** * Validate the schedule XML document./* ww w . j a va 2 s . co m*/ * * @throws SAXException on an error */ public static void validateXML(final org.w3c.dom.Document document) throws SAXException { try { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Source schemaFile = new StreamSource( classLoader.getResourceAsStream("fll/resources/schedule.xsd")); final Schema schema = factory.newSchema(schemaFile); final Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); } catch (final IOException e) { throw new RuntimeException("Internal error, should never get IOException here", e); } }