List of usage examples for javax.xml.validation Validator validate
public void validate(Source source) throws SAXException, IOException
From source file:org.eclipse.wb.internal.core.model.description.helpers.DescriptionHelper.java
/** * Validates <code>*.wbp-component.xml</code> against its schema. *//*w ww.jav a 2 s.c om*/ public static synchronized void validateComponentDescription(ResourceInfo resource) throws Exception { // validate on developers computers if (EnvironmentUtils.isTestingTime()) { // prepare Schema if (m_wbpComponentSchema == null) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); InputStream schemaStream = DesignerPlugin.getFile("schema/wbp-component.xsd"); m_wbpComponentSchema = factory.newSchema(new StreamSource(schemaStream)); } // validate InputStream contents = resource.getURL().openStream(); try { Validator validator = m_wbpComponentSchema.newValidator(); validator.validate(new StreamSource(contents)); } catch (Throwable e) { throw new Exception("Exception during validation " + resource.getURL(), e); } finally { contents.close(); } } }
From source file:org.eurekastreams.server.action.validation.gallery.UrlXmlValidator.java
/** * Validates xml from given Url returning true if it passes validation, false otherwise. * * @param inActionContext//from w w w . j a va 2 s .co m * the action context * @throws ValidationException * on error */ @Override @SuppressWarnings("unchecked") public void validate(final ServiceActionContext inActionContext) throws ValidationException { InputStream schemaStream = null; Map<String, Serializable> fields = (Map<String, Serializable>) inActionContext.getParams(); String galleryItemUrl = (String) fields.get(URL_KEY); try { schemaStream = this.getClass().getResourceAsStream(xsdPath); log.debug("Attempt to validate xml at: " + galleryItemUrl + "with xsd at: " + xsdPath); SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaString); Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream)); Validator validator = schema.newValidator(); // TODO: stuff the input stream into the context for execute() InputStream galleryItemInputStream = xmlFetcher.getInputStream(galleryItemUrl); validator.validate(new StreamSource(galleryItemInputStream)); log.debug("Success validating xml at: " + galleryItemUrl); } catch (Exception e) { log.error("Validation for gadget definition failed.", e); ValidationException ve = new ValidationException(); ve.addError(URL_KEY, "Valid url is required"); throw ve; } finally { try { if (schemaStream != null) { schemaStream.close(); } } catch (IOException ex) { log.error("Error closing stream, already closed.", ex); } } }
From source file:org.fcrepo.server.security.PolicyParser.java
/** * Parses the given policy and optionally schema validates it. * * @param policyStream/*from w w w.j a v a2s . com*/ * the serialized XACML policy * @param validate * whether to schema validate * @return the parsed policy. * @throws ValidationException * if the given xml is not a valid policy. This will occur if it * is not well-formed XML, its root element is not named * <code>Policy</code> or <code>PolicySet</code>, it triggers * a parse exception in the Sun libraries when constructing an * <code>AbstractPolicy</code> from the DOM, or (if validation * is true) it is not schema-valid. */ public AbstractPolicy parse(InputStream policyStream, boolean schemaValidate) throws ValidationException { // Parse; die if not well-formed Document doc = null; DocumentBuilder domParser = null; try { domParser = XmlTransformUtility.borrowDocumentBuilder(); domParser.setErrorHandler(THROW_ALL); doc = domParser.parse(policyStream); } catch (Exception e) { throw new ValidationException("Policy invalid; malformed XML", e); } finally { if (domParser != null) { XmlTransformUtility.returnDocumentBuilder(domParser); } } if (schemaValidate) { // XSD-validate; die if not schema-valid Validator validator = null; try { validator = m_validators.borrowObject(); validator.validate(new DOMSource(doc)); } catch (Exception e) { throw new ValidationException("Policy invalid; schema" + " validation failed", e); } finally { if (validator != null) try { m_validators.returnObject(validator); } catch (Exception e) { logger.warn(e.getMessage(), e); } } } // Construct AbstractPolicy from doc; die if root isn't "Policy[Set]" Element root = doc.getDocumentElement(); String rootName = root.getTagName(); try { if (rootName.equals("Policy")) { return Policy.getInstance(root); } else if (rootName.equals("PolicySet")) { return PolicySet.getInstance(root); } else { throw new ValidationException( "Policy invalid; root element is " + rootName + ", but should be " + "Policy or PolicySet"); } } catch (ParsingException e) { throw new ValidationException("Policy invalid; failed parsing by " + "Sun XACML implementation", e); } }
From source file:org.fosstrak.epcis.repository.capture.CaptureOperationsModule.java
/** * Validates the given document against the given schema. *//*from ww w . j a va 2s . c o m*/ private void validateDocument(Document document, Schema schema) throws SAXException, IOException { if (schema != null) { Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); LOG.info("Incoming capture request was successfully validated against the EPCISDocument schema"); } else { LOG.warn("Schema validator unavailable. Unable to validate EPCIS capture event against schema!"); } }
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//from www . ja v a2s .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 va2 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.impalaframework.util.XMLDomUtils.java
/** * Validates document of given description using w3c.org schema validation * @param document the DOM document instance * @param description a description of the document, typically name or path * @param xsdResource the schema resource used for validation *//*from w w w . j a v a2 s . c o m*/ public static void validateDocument(Document document, String description, Resource xsdResource) { Assert.notNull(xsdResource, "xsdResource cannot be null"); if (!xsdResource.exists()) { throw new ExecutionException( "Cannot validate document as xsdResource '" + xsdResource + "' does not exist"); } else { if (logger.isDebugEnabled()) { logger.debug("Validating using schema resource " + xsdResource.getDescription()); } } SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { InputStream inputStream = xsdResource.getInputStream(); Source source = new StreamSource(inputStream); Schema schema = factory.newSchema(source); Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); } catch (SAXParseException e) { throw new ExecutionException("Error on " + e.getLineNumber() + ", column " + e.getColumnNumber() + " in " + description + ": " + e.getMessage(), e); } catch (SAXException e) { throw new ExecutionException("Error parsing " + description + ": " + e.getMessage(), e); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.infoscoop.api.rest.v1.controller.admin.TabLayoutsController.java
/** * validatation and parse XMLString for tabLayouts. * @param xml/*w ww .ja v a2 s. c o m*/ * @return */ private Document parseTabLayoutsXML(String xml) { try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL path = Thread.currentThread().getContextClassLoader().getResource("tabLayouts.xsd"); File f = new File(path.toURI()); Schema schema = factory.newSchema(f); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setSchema(schema); dbf.setNamespaceAware(true); DocumentBuilder parser = dbf.newDocumentBuilder(); Document doc = parser.parse(new InputSource(new StringReader(xml))); Validator validator = schema.newValidator(); validator.validate(new DOMSource(doc)); return doc; } catch (SAXException e) { // instance document is invalid throw new RuntimeException(e); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.jboss.cdi.tck.test.shrinkwrap.descriptors.ejb.EjbJarDescriptorBuilderTest.java
@Test public void testDescriptorIsValid() throws ParserConfigurationException, SAXException, DescriptorExportException, IOException { EjbJarDescriptor ejbJarDescriptor = new EjbJarDescriptorBuilder().messageDrivenBeans( newMessageDriven("TestQueue", QueueMessageDrivenBean.class.getName()) .addActivationConfigProperty("acknowledgeMode", "Auto-acknowledge") .addActivationConfigProperty("destinationType", "javax.jms.Queue") .addActivationConfigProperty("destinationLookup", "test_queue"), newMessageDriven("TestTopic", TopicMessageDrivenBean.class.getName()) .addActivationConfigProperty("acknowledgeMode", "Auto-acknowledge") .addActivationConfigProperty("destinationType", "javax.jms.Topic") .addActivationConfigProperty("destinationLookup", "test_topic")) .build();/* w w w . j a v a 2s .co m*/ SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setResourceResolver(new LSResourceResolver() { @Override public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { try { if (systemId.startsWith("http")) { // Ugly workaround for xml.xsd systemId = StringUtils.substringAfterLast(systemId, "/"); } return new Input(publicId, systemId, new FileInputStream(new File("src/test/resources/xsd", systemId))); } catch (FileNotFoundException e) { throw new IllegalStateException(); } } }); schemaFactory.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { } @Override public void fatalError(SAXParseException exception) throws SAXException { throw exception; } @Override public void error(SAXParseException exception) throws SAXException { throw exception; } }); Source schemaFile = new StreamSource( new FileInputStream(new File("src/test/resources/xsd", "ejb-jar_3_1.xsd"))); Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); validator .validate(new StreamSource(new ByteArrayInputStream(ejbJarDescriptor.exportAsString().getBytes()))); }
From source file:org.kepler.kar.karxml.KarXml.java
/** * Validate the document against the schema. Currently we only validate against * kar xml 2.0.0 and 2.1.0. If it is not a kar xml 2.0.0 or 2.1.0 xml, this method will return true. * @param document the document need to be validate * @return true if it is a valid document *//*w ww . ja va 2s . c om*/ public static boolean validateDocument(Document document) { if (document == null) { return false; } try { Node docElement = document.getDocumentElement(); String nameSpace = docElement.getNamespaceURI(); log.debug("The name space is ===== " + nameSpace); if (nameSpace == null || !nameSpace.equals(KARFile.KAR_VERSION_200_NAMESPACE_DEFAULT) || !nameSpace.equals(KARFile.KAR_VERSION_210_NAMESPACE_DEFAULT)) { return true; } SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); String resourceDir = KARFile.getResourceDir(nameSpace); String resourceFileName = KARFile.getResourceFileName(nameSpace); // ClassLoader.getResource javadoc says: // The name of a resource is a '/'-separated path name that identifies the resource. // so I am using a hardcode / in this path: Source schemaFile = new StreamSource( KarXml.class.getClassLoader().getResourceAsStream(resourceDir + "/" + resourceFileName)); Schema schema = factory.newSchema(schemaFile); Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); } catch (SAXException ex) { ex.printStackTrace(); return false; } catch (IOException ex) { ex.printStackTrace(); return false; } log.debug("return true"); return true; }