List of usage examples for javax.xml.validation Validator setErrorHandler
public abstract void setErrorHandler(ErrorHandler errorHandler);
From source file:nl.armatiek.xslweb.web.servlet.XSLWebServlet.java
private void executeRequest(WebApp webApp, HttpServletRequest req, HttpServletResponse resp, OutputStream respOs) throws Exception { boolean developmentMode = webApp.getDevelopmentMode(); String requestXML = (String) req.getAttribute(Definitions.ATTRNAME_REQUESTXML); PipelineHandler pipelineHandler = (PipelineHandler) req.getAttribute(Definitions.ATTRNAME_PIPELINEHANDLER); ErrorListener errorListener = new TransformationErrorListener(resp, developmentMode); MessageWarner messageWarner = new MessageWarner(); List<PipelineStep> steps = pipelineHandler.getPipelineSteps(); if (steps == null || steps.isEmpty()) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource not found"); return;/* w w w . java 2 s. com*/ } OutputStream os = (developmentMode) ? new ByteArrayOutputStream() : respOs; Properties outputProperties = getOutputProperties(webApp, errorListener, steps); Map<QName, XdmValue> baseStylesheetParameters = XSLWebUtils.getStylesheetParameters(webApp, req, resp, homeDir); addResponseTransformationStep(steps); Map<QName, XdmValue> extraStylesheetParameters = null; Source source = new StreamSource(new StringReader(requestXML)); Destination destination = null; for (int i = 0; i < steps.size(); i++) { PipelineStep step = steps.get(i); if (step instanceof SerializerStep) { break; } PipelineStep nextStep = (i < steps.size() - 1) ? steps.get(i + 1) : null; if (step instanceof TransformerStep) { String xslPath = null; if (step instanceof SystemTransformerStep) { xslPath = new File(homeDir, "common/xsl/" + ((TransformerStep) step).getXslPath()) .getAbsolutePath(); } else { xslPath = ((TransformerStep) step).getXslPath(); } XsltExecutable templates = webApp.getTemplates(xslPath, errorListener); Xslt30Transformer transformer = templates.load30(); transformer.getUnderlyingController().setMessageEmitter(messageWarner); transformer.setErrorListener(errorListener); Map<QName, XdmValue> stylesheetParameters = new HashMap<QName, XdmValue>(); stylesheetParameters.putAll(baseStylesheetParameters); XSLWebUtils.addStylesheetParameters(stylesheetParameters, ((TransformerStep) step).getParameters()); if (extraStylesheetParameters != null) { stylesheetParameters.putAll(extraStylesheetParameters); extraStylesheetParameters.clear(); } transformer.setStylesheetParameters(stylesheetParameters); destination = getDestination(webApp, req, resp, os, outputProperties, step, nextStep); transformer.applyTemplates(source, destination); } else if (step instanceof SchemaValidatorStep) { SchemaValidatorStep svStep = (SchemaValidatorStep) step; List<String> schemaPaths = svStep.getSchemaPaths(); Schema schema = webApp.getSchema(schemaPaths, errorListener); source = makeNodeInfoSource(source, webApp, errorListener); destination = null; Serializer serializer = webApp.getProcessor().newSerializer(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); serializer.setOutputStream(outputStream); serializer.setOutputProperty(Property.INDENT, "yes"); serializer.serializeNode(new XdmNode((NodeInfo) source)); Source validationSource = new StreamSource(new ByteArrayInputStream(outputStream.toByteArray())); Validator validator = schema.newValidator(); ValidatorErrorHandler errorHandler = new ValidatorErrorHandler( "Step: " + ((step.getName() != null) ? step.getName() : "noname")); validator.setErrorHandler(errorHandler); Properties properties = svStep.getProperties(); if (properties != null) { @SuppressWarnings("rawtypes") Enumeration names = properties.propertyNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); validator.setProperty(name, properties.getProperty(name)); } } Properties features = svStep.getProperties(); if (features != null) { @SuppressWarnings("rawtypes") Enumeration names = features.propertyNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); validator.setProperty(name, features.getProperty(name)); } } validator.validate(validationSource); Source resultsSource = errorHandler.getValidationResults(); if (resultsSource != null) { NodeInfo resultsNodeInfo = webApp.getConfiguration().buildDocumentTree(resultsSource) .getRootNode(); String xslParamName = svStep.getXslParamName(); if (xslParamName != null) { if (extraStylesheetParameters == null) { extraStylesheetParameters = new HashMap<QName, XdmValue>(); } extraStylesheetParameters.put(new QName(svStep.getXslParamNamespace(), xslParamName), new XdmNode(resultsNodeInfo)); } } } else if (step instanceof SchematronValidatorStep) { SchematronValidatorStep svStep = (SchematronValidatorStep) step; source = makeNodeInfoSource(source, webApp, errorListener); destination = null; /* Execute schematron validation */ XsltExecutable templates = webApp.getSchematron(svStep.getSchematronPath(), svStep.getPhase(), errorListener); Xslt30Transformer transformer = templates.load30(); transformer.getUnderlyingController().setMessageEmitter(messageWarner); transformer.setErrorListener(errorListener); XdmDestination svrlDest = new XdmDestination(); transformer.applyTemplates(source, svrlDest); String xslParamName = svStep.getXslParamName(); if (xslParamName != null) { if (extraStylesheetParameters == null) { extraStylesheetParameters = new HashMap<QName, XdmValue>(); } extraStylesheetParameters.put(new QName(svStep.getXslParamNamespace(), xslParamName), svrlDest.getXdmNode()); } } else if (step instanceof ResponseStep) { source = new StreamSource(new StringReader(((ResponseStep) step).getResponse())); continue; } if (destination instanceof SourceDestination) { /* Set source for next pipeline step: */ source = ((SourceDestination) destination).asSource(); } } if (developmentMode) { byte[] body = ((ByteArrayOutputStream) os).toByteArray(); IOUtils.copy(new ByteArrayInputStream(body), respOs); } }
From source file:org.apache.maven.plugin.changes.schema.DefaultChangesSchemaValidator.java
public XmlValidationHandler validateXmlWithSchema(File file, String schemaVersion, boolean failOnValidationError) throws SchemaValidatorException { Reader reader = null;//from ww w . j a va 2 s . com try { String schemaPath = CHANGES_SCHEMA_PATH + "changes-" + schemaVersion + ".xsd"; Schema schema = getSchema(schemaPath); Validator validator = schema.newValidator(); XmlValidationHandler baseHandler = new XmlValidationHandler(failOnValidationError); validator.setErrorHandler(baseHandler); reader = new XmlStreamReader(file); validator.validate(new StreamSource(reader)); return baseHandler; } catch (IOException e) { throw new SchemaValidatorException("IOException : " + e.getMessage(), e); } catch (SAXException e) { throw new SchemaValidatorException("SAXException : " + e.getMessage(), e); } catch (Exception e) { throw new SchemaValidatorException("Exception : " + e.getMessage(), e); } finally { IOUtil.close(reader); } }
From source file:org.apache.servicemix.jbi.deployer.descriptor.DescriptorFactory.java
/** * Build a jbi descriptor from the specified binary data. * The descriptor is validated against the schema, but no * semantic validation is performed./*ww w .j a v a2s . c o m*/ * * @param bytes hold the content of the JBI descriptor xml document * @return the Descriptor object */ public static Descriptor buildDescriptor(final byte[] bytes) { try { // Validate descriptor SchemaFactory schemaFactory = SchemaFactory.newInstance(XSD_SCHEMA_LANGUAGE); Schema schema = schemaFactory.newSchema(DescriptorFactory.class.getResource(JBI_DESCRIPTOR_XSD)); Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { //log.debug("Validation warning on " + url + ": " + exception); } public void error(SAXParseException exception) throws SAXException { //log.info("Validation error on " + url + ": " + exception); } public void fatalError(SAXParseException exception) throws SAXException { throw exception; } }); validator.validate(new StreamSource(new ByteArrayInputStream(bytes))); // Parse descriptor DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.parse(new ByteArrayInputStream(bytes)); Element jbi = doc.getDocumentElement(); Descriptor desc = new Descriptor(); desc.setVersion(Double.parseDouble(getAttribute(jbi, VERSION))); Element child = getFirstChildElement(jbi); if (COMPONENT.equals(child.getLocalName())) { ComponentDesc component = new ComponentDesc(); component.setType(child.getAttribute(TYPE)); component.setComponentClassLoaderDelegation(getAttribute(child, COMPONENT_CLASS_LOADER_DELEGATION)); component.setBootstrapClassLoaderDelegation(getAttribute(child, BOOTSTRAP_CLASS_LOADER_DELEGATION)); List<SharedLibraryList> sls = new ArrayList<SharedLibraryList>(); DocumentFragment ext = null; for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (IDENTIFICATION.equals(e.getLocalName())) { component.setIdentification(readIdentification(e)); } else if (COMPONENT_CLASS_NAME.equals(e.getLocalName())) { component.setComponentClassName(getText(e)); component.setDescription(getAttribute(e, DESCRIPTION)); } else if (COMPONENT_CLASS_PATH.equals(e.getLocalName())) { ClassPath componentClassPath = new ClassPath(); ArrayList<String> l = new ArrayList<String>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (PATH_ELEMENT.equals(e2.getLocalName())) { l.add(getText(e2)); } } componentClassPath.setPathList(l); component.setComponentClassPath(componentClassPath); } else if (BOOTSTRAP_CLASS_NAME.equals(e.getLocalName())) { component.setBootstrapClassName(getText(e)); } else if (BOOTSTRAP_CLASS_PATH.equals(e.getLocalName())) { ClassPath bootstrapClassPath = new ClassPath(); ArrayList<String> l = new ArrayList<String>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (PATH_ELEMENT.equals(e2.getLocalName())) { l.add(getText(e2)); } } bootstrapClassPath.setPathList(l); component.setBootstrapClassPath(bootstrapClassPath); } else if (SHARED_LIBRARY.equals(e.getLocalName())) { SharedLibraryList sl = new SharedLibraryList(); sl.setName(getText(e)); sl.setVersion(getAttribute(e, VERSION)); sls.add(sl); } else { if (ext == null) { ext = doc.createDocumentFragment(); } ext.appendChild(e); } } component.setSharedLibraries(sls.toArray(new SharedLibraryList[sls.size()])); if (ext != null) { InstallationDescriptorExtension descriptorExtension = new InstallationDescriptorExtension(); descriptorExtension.setDescriptorExtension(ext); component.setDescriptorExtension(descriptorExtension); } desc.setComponent(component); } else if (SHARED_LIBRARY.equals(child.getLocalName())) { SharedLibraryDesc sharedLibrary = new SharedLibraryDesc(); sharedLibrary.setClassLoaderDelegation(getAttribute(child, CLASS_LOADER_DELEGATION)); sharedLibrary.setVersion(getAttribute(child, VERSION)); for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (IDENTIFICATION.equals(e.getLocalName())) { sharedLibrary.setIdentification(readIdentification(e)); } else if (SHARED_LIBRARY_CLASS_PATH.equals(e.getLocalName())) { ClassPath sharedLibraryClassPath = new ClassPath(); ArrayList<String> l = new ArrayList<String>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (PATH_ELEMENT.equals(e2.getLocalName())) { l.add(getText(e2)); } } sharedLibraryClassPath.setPathList(l); sharedLibrary.setSharedLibraryClassPath(sharedLibraryClassPath); } } desc.setSharedLibrary(sharedLibrary); } else if (SERVICE_ASSEMBLY.equals(child.getLocalName())) { ServiceAssemblyDesc serviceAssembly = new ServiceAssemblyDesc(); ArrayList<ServiceUnitDesc> sus = new ArrayList<ServiceUnitDesc>(); for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (IDENTIFICATION.equals(e.getLocalName())) { serviceAssembly.setIdentification(readIdentification(e)); } else if (SERVICE_UNIT.equals(e.getLocalName())) { ServiceUnitDesc su = new ServiceUnitDesc(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (IDENTIFICATION.equals(e2.getLocalName())) { su.setIdentification(readIdentification(e2)); } else if (TARGET.equals(e2.getLocalName())) { Target target = new Target(); for (Element e3 = getFirstChildElement(e2); e3 != null; e3 = getNextSiblingElement( e3)) { if (ARTIFACTS_ZIP.equals(e3.getLocalName())) { target.setArtifactsZip(getText(e3)); } else if (COMPONENT_NAME.equals(e3.getLocalName())) { target.setComponentName(getText(e3)); } } su.setTarget(target); } } sus.add(su); } else if (CONNECTIONS.equals(e.getLocalName())) { Connections connections = new Connections(); ArrayList<Connection> cns = new ArrayList<Connection>(); for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) { if (CONNECTION.equals(e2.getLocalName())) { Connection cn = new Connection(); for (Element e3 = getFirstChildElement(e2); e3 != null; e3 = getNextSiblingElement( e3)) { if (CONSUMER.equals(e3.getLocalName())) { Consumer consumer = new Consumer(); consumer.setInterfaceName(readAttributeQName(e3, INTERFACE_NAME)); consumer.setServiceName(readAttributeQName(e3, SERVICE_NAME)); consumer.setEndpointName(getAttribute(e3, ENDPOINT_NAME)); cn.setConsumer(consumer); } else if (PROVIDER.equals(e3.getLocalName())) { Provider provider = new Provider(); provider.setServiceName(readAttributeQName(e3, SERVICE_NAME)); provider.setEndpointName(getAttribute(e3, ENDPOINT_NAME)); cn.setProvider(provider); } } cns.add(cn); } } connections.setConnections(cns.toArray(new Connection[cns.size()])); serviceAssembly.setConnections(connections); } } serviceAssembly.setServiceUnits(sus.toArray(new ServiceUnitDesc[sus.size()])); desc.setServiceAssembly(serviceAssembly); } else if (SERVICES.equals(child.getLocalName())) { Services services = new Services(); services.setBindingComponent( Boolean.valueOf(getAttribute(child, BINDING_COMPONENT)).booleanValue()); ArrayList<Provides> provides = new ArrayList<Provides>(); ArrayList<Consumes> consumes = new ArrayList<Consumes>(); for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) { if (PROVIDES.equals(e.getLocalName())) { Provides p = new Provides(); p.setInterfaceName(readAttributeQName(e, INTERFACE_NAME)); p.setServiceName(readAttributeQName(e, SERVICE_NAME)); p.setEndpointName(getAttribute(e, ENDPOINT_NAME)); provides.add(p); } else if (CONSUMES.equals(e.getLocalName())) { Consumes c = new Consumes(); c.setInterfaceName(readAttributeQName(e, INTERFACE_NAME)); c.setServiceName(readAttributeQName(e, SERVICE_NAME)); c.setEndpointName(getAttribute(e, ENDPOINT_NAME)); c.setLinkType(getAttribute(e, LINK_TYPE)); consumes.add(c); } } services.setProvides(provides.toArray(new Provides[provides.size()])); services.setConsumes(consumes.toArray(new Consumes[consumes.size()])); desc.setServices(services); } checkDescriptor(desc); return desc; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.synapse.format.syslog.SyslogMessageBuilderTest.java
private SyslogMessage test(String message) throws Exception { MessageContext msgContext = new MessageContext(); ByteArrayInputStream in = new ByteArrayInputStream(message.getBytes("us-ascii")); OMElement element = new SyslogMessageBuilder().processDocument(in, null, msgContext); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema( new StreamSource(SyslogMessageBuilderTest.class.getResource("schema.xsd").toExternalForm())); Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandler() { public void error(SAXParseException exception) throws SAXException { throw exception; }/*from w w w .ja va 2 s .c o m*/ public void fatalError(SAXParseException exception) throws SAXException { throw exception; } public void warning(SAXParseException exception) throws SAXException { throw exception; } }); validator.validate(new OMSource(element)); String pidString = element.getAttributeValue(new QName(SyslogConstants.PID)); return new SyslogMessage(element.getAttributeValue(new QName(SyslogConstants.FACILITY)), element.getAttributeValue(new QName(SyslogConstants.SEVERITY)), element.getAttributeValue(new QName(SyslogConstants.TAG)), pidString == null ? -1 : Integer.parseInt(pidString), element.getText()); }
From source file:org.bungeni.editor.system.ValidateConfiguration.java
public List<SAXParseException> validate(File xmlFile, ConfigInfo config) { final List<SAXParseException> exceptions = new LinkedList<SAXParseException>(); try {/*from w w w . ja va 2 s . c o m*/ String pathToXSD = config.getXsdPath(); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver(new ResourceResolver()); Schema schema = factory.newSchema(new StreamSource(config.getXsdInputStream())); Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { exceptions.add(exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { exceptions.add(exception); } @Override public void error(SAXParseException exception) throws SAXException { exceptions.add(exception); } }); StreamSource streamXML = new StreamSource(xmlFile); validator.validate(streamXML); } catch (SAXException ex) { log.error("Error during validation", ex); } catch (IOException ex) { log.error("Error during validation", ex); } finally { } return exceptions; }
From source file:org.dataconservancy.model.builder.DcsModelBuilderTest.java
private ErrorHandlerCollector isValid(TestCase tc, String xml) throws IOException, SAXException { assertNotNull(tc);/*from w w w . j a v a 2s . c o m*/ assertNotNull(xml); assertFalse(xml.trim().length() == 0); final TestResult result; final Schema s = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(new StreamSource(dcpSchema.getInputStream())); final ErrorHandlerCollector errors = new ErrorHandlerCollector(); final Validator v = s.newValidator(); v.setErrorHandler(errors); try { v.validate(new StreamSource(IOUtils.toInputStream(xml))); } catch (SAXException e) { // ignore } catch (IOException e) { // ignore } return errors; }
From source file:org.geoserver.test.GeoServerAbstractTestSupport.java
/** * Given a dom and a schema, checks that the dom validates against the schema * of the validation errors instead/*w ww .j ava2 s. c om*/ * @param validationErrors * @throws IOException * @throws SAXException */ protected void checkValidationErrors(Document dom, Schema schema) throws SAXException, IOException { final Validator validator = schema.newValidator(); final List<Exception> validationErrors = new ArrayList<Exception>(); validator.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { System.out.println(exception.getMessage()); } public void fatalError(SAXParseException exception) throws SAXException { validationErrors.add(exception); } public void error(SAXParseException exception) throws SAXException { validationErrors.add(exception); } }); validator.validate(new DOMSource(dom)); if (validationErrors != null && validationErrors.size() > 0) { StringBuilder sb = new StringBuilder(); for (Exception ve : validationErrors) { sb.append(ve.getMessage()).append("\n"); } fail(sb.toString()); } }
From source file:org.gluu.oxtrust.ldap.service.Shibboleth2ConfService.java
/** * @param stream// w ww. j a v a 2 s . c o m * @throws IOException * @throws SAXException * @throws ParserConfigurationException */ public synchronized GluuErrorHandler validateMetadata(InputStream stream) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory newFactory = DocumentBuilderFactory.newInstance(); newFactory.setCoalescing(false); newFactory.setExpandEntityReferences(true); newFactory.setIgnoringComments(false); newFactory.setIgnoringElementContentWhitespace(false); newFactory.setNamespaceAware(true); newFactory.setValidating(false); DocumentBuilder xmlParser = newFactory.newDocumentBuilder(); Document xmlDoc = xmlParser.parse(stream); String schemaDir = System.getProperty("catalina.home") + File.separator + "conf" + File.separator + "shibboleth2" + File.separator + "idp" + File.separator + "schema" + File.separator; Schema schema = SchemaBuilder.buildSchema(SchemaLanguage.XML, schemaDir); Validator validator = schema.newValidator(); GluuErrorHandler handler = new GluuErrorHandler(); validator.setErrorHandler(handler); validator.validate(new DOMSource(xmlDoc)); return handler; }
From source file:org.kuali.kfs.module.ar.batch.CustomerLoadXMLSchemaTest.java
/** * Validates the xml contents against the batch input type schema using the java 1.5 validation package. * //from ww w .j a v a2 s . c o m * @param schemaLocation - location of the schema file * @param fileContents - xml contents to validate against the schema */ private void validateContentsAgainstSchema(InputStream schemaLocation, InputStream fileContents) throws ParseException, MalformedURLException, IOException, SAXException { // create a SchemaFactory capable of understanding WXS schemas SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // load a WXS schema, represented by a Schema instance Source schemaSource = null; schemaSource = new StreamSource(schemaLocation); Schema schema = null; schema = factory.newSchema(schemaSource); // create a Validator instance, which can be used to validate an instance document Validator validator = schema.newValidator(); validator.setErrorHandler(new XmlErrorHandler()); // validate validator.validate(new StreamSource(fileContents)); }
From source file:org.kuali.kfs.module.tem.batch.PerDiemXmlInputFileType.java
/** * @see org.kuali.kfs.sys.batch.XmlBatchInputFileTypeBase#validateContentsAgainstSchema(java.lang.String, java.io.InputStream) *//* w ww.java 2 s. c o m*/ @Override protected void validateContentsAgainstSchema(String schemaLocation, InputStream fileContents) throws ParseException { try { // get schemaFile UrlResource schemaResource = new UrlResource(schemaLocation); // load a WXS schema, represented by a Schema instance Source schemaSource = new StreamSource(schemaResource.getInputStream()); // create a SchemaFactory capable of understanding WXS schemas SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(schemaSource); // create a validator instance, which can be used to validate an instance document Validator validator = schema.newValidator(); validator.setErrorHandler(new XmlErrorHandler()); Source source = this.transform(fileContents); validator.validate(source); } catch (MalformedURLException e2) { LOG.error("error getting schema url: " + e2.getMessage()); throw new RuntimeException("error getting schema url: " + e2.getMessage(), e2); } catch (SAXException e) { LOG.error("error encountered while parsing xml " + e.getMessage()); throw new ParseException("Schema validation error occured while processing file: " + e.getMessage(), e); } catch (IOException e1) { LOG.error("error occured while validating file contents: " + e1.getMessage()); throw new RuntimeException("error occurred while validating file contents: " + e1.getMessage(), e1); } }