/** @return BPMN 2.0 XML schema */ private static Schema getBpmnSchema() { try { final ClassLoader loader = BpmnDefinitions.class.getClassLoader(); SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); schemaFactory.setResourceResolver(new JarLSResourceResolver()); return schemaFactory.newSchema(new StreamSource(loader.getResourceAsStream(BPMN_XSD))); } catch (SAXException e) { throw new RuntimeException("Couldn't parse BPMN XML schema", e); } }
private void loadSchema() { SchemaFactory schemaFactory = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); try { schemaFactory.setResourceResolver(new ClasspathResourceResolver()); Resource schemaResource = resourceLoader.getResource(schemaPath); messageSchema = schemaFactory.newSchema(schemaResource.getFile()); } catch (Exception e) { throw new RuntimeException(e); } }
/** * @param schemas Schema files to be checked. * @param errorHandler detected errors will be reported to this handler. * @return true if there was no error, false if there were errors. */ public static boolean check( InputSource[] schemas, ErrorReceiver errorHandler, final EntityResolver entityResolver, boolean disableXmlSecurity) { ErrorReceiverFilter errorFilter = new ErrorReceiverFilter(errorHandler); boolean hadErrors = false; SchemaFactory sf = XmlFactory.createSchemaFactory(W3C_XML_SCHEMA_NS_URI, disableXmlSecurity); XmlFactory.allowExternalAccess(sf, "all", disableXmlSecurity); sf.setErrorHandler(errorFilter); if (entityResolver != null) { sf.setResourceResolver( new LSResourceResolver() { public LSInput resolveResource( String type, String namespaceURI, String publicId, String systemId, String baseURI) { try { // XSOM passes the namespace URI to the publicID parameter. // we do the same here . InputSource is = entityResolver.resolveEntity(namespaceURI, systemId); if (is == null) return null; return new LSInputSAXWrapper(is); } catch (SAXException e) { // TODO: is this sufficient? return null; } catch (IOException e) { // TODO: is this sufficient? return null; } } }); } try { XmlFactory.allowExternalDTDAccess(sf, "all", disableXmlSecurity); sf.newSchema(getSchemaSource(schemas, entityResolver)); } catch (SAXException e) { // TODO: we haven't thrown exceptions from here before. should we just trap them and return // false? hadErrors = true; } catch (OutOfMemoryError e) { errorHandler.warning(null, Messages.format(Messages.WARN_UNABLE_TO_CHECK_CORRECTNESS)); } return !(hadErrors || errorFilter.hadError()); }
static { sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); sf.setResourceResolver(SchemaResolver.getInstance()); dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db_ = null; try { db_ = dbf.newDocumentBuilder(); } catch (ParserConfigurationException pce) { /* do nothing */ } db = db_; }
public Schema compile(String schema) { Schema compiledSchema = null; String trimmedSchema = StringUtils.trimToEmpty(schema); if (trimmedSchema.startsWith("<") && trimmedSchema.endsWith(">")) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver(new XsdResourceResolver(contextPath, resourceLoader)); try { compiledSchema = factory.newSchema(new StreamSource(new StringReader(trimmedSchema))); } catch (Exception e) { // ignore exception as the error is detected by the validator // and here we cannot tell if the schema is intended for xml or not } } return compiledSchema; }
/** * Parse given W3C XML Schema 'File' (probably an .xsd) and store so it can later be used for * validation. * * @param key * @param schemaFile * @throws SAXException */ private Schema put(String key, File schemaFile) throws SAXException { // create a SchemaFactory capable of understanding W3C XML Schemas (WXS) SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // Set the error handler to receive any error during Schema Compilation factory.setErrorHandler(new MyErrorHandler()); // set the resource resolver to customize resource resolution factory.setResourceResolver(new MyLSResourceResolver()); // load a WXS schema, represented by a Schema instance Schema schema = factory.newSchema(new StreamSource(schemaFile)); /** * This boolean provides the two sides of a performance comparison. If ynUseCache==false, the * .xsd is compiled for every request. If ynUseCache==true, the .xsd is compiled once and * subsequently retrieved from the cahce. */ if (this.ynUseCache) this.schemas.put(key, schema); return schema; }
protected String validateAgainstSchema( InputStream src, Source schemaSource, MyMapStreamSchemaOutputResolver outputResolver) { SchemaFactory sFact = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); sFact.setResourceResolver(new ResourceResolver(outputResolver)); Schema theSchema; try { theSchema = sFact.newSchema(schemaSource); Validator validator = theSchema.newValidator(); StreamSource ss = new StreamSource(src); validator.validate(ss); } catch (Exception e) { if (e.getMessage() == null) { return "An unknown exception occurred."; } return e.getMessage(); } return null; }
/** * Validates specified XML file with specified XML schema file * * @param xmlFile name of xml file * @param schemaFile name of schema file * @return true if the xml is valid under specified schema. */ public static boolean validateXmlFile(String xmlFile, String schemaFile) { boolean result = false; // 1. Lookup a factory for the W3C XML Schema language SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); // Register custom LSResourceResolver factory.setResourceResolver(new XmlUtils.CustomSchemaResourceResolver()); // 2. Compile the schema. // Here the schema is loaded from a java.io.File, but you could use // a java.net.URL or a javax.xml.transform.Source instead. // File schemaLocation = new File(schemaFile); InputStream is = ClassLoader.getSystemResourceAsStream(schemaFile); Schema schema; try { // schema = factory.newSchema(schemaLocation); schema = factory.newSchema(new StreamSource(is)); } catch (SAXException ex) { logger.log(Level.WARNING, "The Schema file is not valid. {0}", ex.getMessage()); ex.printStackTrace(); return false; } // 3. Get a validator from the schema. Validator validator = schema.newValidator(); // 4. Parse the document you want to check. Source source = new StreamSource(xmlFile); // 5. Check the document try { validator.validate(source); logger.log(Level.INFO, xmlFile + " is valid."); result = true; } catch (SAXException ex) { logger.log(Level.WARNING, xmlFile + " is not valid because\n >>>" + ex.getMessage()); } catch (IOException ex) { logger.log(Level.WARNING, xmlFile + " is not a valid file." + ex.getMessage()); } return result; }
public int Validate( File inFile, File entitiesResolverConfigFile, File schemaFile, File schemataResolverConfigFile) { try { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); // Disable validating by DTD. parserFactory.setValidating(false); parserFactory.setNamespaceAware(true); SchemaEntityResolverLocal localResolver = new SchemaEntityResolverLocal(entitiesResolverConfigFile, schemataResolverConfigFile); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setResourceResolver(localResolver); Source schemaSource = new StreamSource(schemaFile); parserFactory.setSchema(schemaFactory.newSchema(new Source[] {schemaSource})); SAXParser parser = parserFactory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(this); reader.setEntityResolver(localResolver); // Do XML Schema validation. reader.parse(new InputSource(new FileReader(inFile))); } catch (SAXException ex) { ex.printStackTrace(); System.exit(-1); } catch (ParserConfigurationException ex) { ex.printStackTrace(); System.exit(-1); } catch (FileNotFoundException ex) { ex.printStackTrace(); System.exit(-1); } catch (IOException ex) { ex.printStackTrace(); System.exit(-1); } return 0; }
/** * Returns the {@link Schema} associated with this validator. This ia an XSD schema containing * knowledge about the schema source as returned by {@link #getSchemaSources()} * * @throws ConfigurationException */ protected synchronized Schema getSchemaObject( String schemasId, List<nl.nn.adapterframework.validation.Schema> schemas) throws ConfigurationException { Schema schema = javaxSchemas.get(schemasId); if (schema == null) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver( new LSResourceResolver() { public LSInput resolveResource(String s, String s1, String s2, String s3, String s4) { return null; } }); try { Collection<Source> sources = getSchemaSources(schemas); schema = factory.newSchema(sources.toArray(new Source[sources.size()])); javaxSchemas.put(schemasId, schema); } catch (Exception e) { throw new ConfigurationException("cannot read schema's [" + schemasId + "]", e); } } return schema; }
/** Init our cache objects. */ private static void initStatics() { // First, cache the various files // PENDING_RELEASE (rlubke) clean this up try { URL url = DbfFactory.class.getResource(FACES_1_2_XSD); if (url == null) { // try to load from the file File f = new File(FACES_1_2_XSD_FILE); if (!f.exists()) { throw new IllegalStateException("Unable to find web-facesconfig_1_2.xsd"); } url = f.toURI().toURL(); } URLConnection conn = url.openConnection(); conn.setUseCaches(false); InputStream in = conn.getInputStream(); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver((LSResourceResolver) DbfFactory.FACES_ENTITY_RESOLVER); FACES_12_SCHEMA = factory.newSchema(new StreamSource(in)); url = DbfFactory.class.getResource(FACES_1_1_XSD); conn = url.openConnection(); conn.setUseCaches(false); in = conn.getInputStream(); factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver((LSResourceResolver) DbfFactory.FACES_ENTITY_RESOLVER); FACES_11_SCHEMA = factory.newSchema(new StreamSource(in)); url = DbfFactory.class.getResource(FACES_2_1_XSD); if (url == null) { // try to load from the file File f = new File(FACES_2_1_XSD_FILE); if (!f.exists()) { throw new IllegalStateException("Unable to find web-facesconfig_2_1.xsd"); } url = f.toURI().toURL(); } conn = url.openConnection(); conn.setUseCaches(false); in = conn.getInputStream(); factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver((LSResourceResolver) DbfFactory.FACES_ENTITY_RESOLVER); FACES_21_SCHEMA = factory.newSchema(new StreamSource(in)); url = DbfFactory.class.getResource(FACES_2_0_XSD); if (url == null) { // try to load from the file File f = new File(FACES_2_0_XSD_FILE); if (!f.exists()) { throw new IllegalStateException("Unable to find web-facesconfig_2_0.xsd"); } url = f.toURI().toURL(); } conn = url.openConnection(); conn.setUseCaches(false); in = conn.getInputStream(); factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver((LSResourceResolver) DbfFactory.FACES_ENTITY_RESOLVER); FACES_20_SCHEMA = factory.newSchema(new StreamSource(in)); url = DbfFactory.class.getResource(FACELET_TAGLIB_2_0_XSD); if (url == null) { // try to load from the file File f = new File(FACELET_TAGLIB_2_0_XSD_FILE); if (!f.exists()) { throw new IllegalStateException("Unable to find web-facelettaglibrary_2_0.xsd"); } url = f.toURI().toURL(); } conn = url.openConnection(); conn.setUseCaches(false); in = conn.getInputStream(); factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver((LSResourceResolver) DbfFactory.FACES_ENTITY_RESOLVER); FACELET_TAGLIB_20_SCHEMA = factory.newSchema(new StreamSource(in)); } catch (Exception e) { throw new ConfigurationException(e); } }
public Document parseBPELFile(InputStream bpelStream) { // System.setProperty("javax.xml.parsers.DocumentBuilderFactory", // "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); // Get Document Builder Factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // turn off validation, we use the new validation package factory.setValidating(false); // ignore comments factory.setIgnoringComments(true); // turn on namespaces factory.setNamespaceAware(true); Document doc = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(bpelStream); if (doc != null) { // System.setProperty("javax.xml.validation.SchemaFactory:http://www.w3.org/2001/XMLSchema","org.apache.xerces.jaxp.validation.XMLSchemaFactory"); // Validate SchemaFactory constraintFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS domImplementationLS = (DOMImplementationLS) registry.getDOMImplementation("LS"); if (domImplementationLS != null) { // set our own resolver implementation constraintFactory.setResourceResolver(new BPELResolver(domImplementationLS)); } // should we validate against "executable" or "abstract" BPEL ? // default is "executable" Source bpelConstraints = new StreamSource(new File(FILENAME_BPEL_EXECUTABLE_SCHEMA)); if (doc.getDocumentElement().getNamespaceURI() != null) { if (doc.getDocumentElement().getNamespaceURI().equals(BPEL_ABSTRACT_NS)) { bpelConstraints = new StreamSource(new File(FILENAME_BPEL_ABSTRACT_SCHEMA)); } } Schema schema = constraintFactory.newSchema(bpelConstraints); Validator validator = schema.newValidator(); try { validator.validate(new DOMSource(doc)); this.successfulValidation = true; } catch (SAXException e) { // schema validation failed! // we continue with the transformation, however, the user is notified this.successfulValidation = false; this.validationException = e.getMessage(); } } } catch (Exception e) { // a lot can go wrong, no chance to recover e.printStackTrace(); } return doc; }
@Test public void testSignEnvelopingDocumentOffice2010() throws Exception { // setup EnvelopedSignatureFacet envelopedSignatureFacet = new EnvelopedSignatureFacet(); KeyInfoSignatureFacet keyInfoSignatureFacet = new KeyInfoSignatureFacet(true, false, false); SignaturePolicyService signaturePolicyService = new ExplicitSignaturePolicyService( "urn:test", "hello world".getBytes(), "description", "http://here.com"); XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(signaturePolicyService); TimeStampService mockTimeStampService = EasyMock.createMock(TimeStampService.class); RevocationDataService mockRevocationDataService = EasyMock.createMock(RevocationDataService.class); XAdESXLSignatureFacet xadesXLSignatureFacet = new XAdESXLSignatureFacet(mockTimeStampService, mockRevocationDataService); XmlSignatureTestService testedInstance = new XmlSignatureTestService( envelopedSignatureFacet, keyInfoSignatureFacet, xadesSignatureFacet, new Office2010SignatureFacet(), xadesXLSignatureFacet); KeyPair keyPair = PkiTestUtils.generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); X509Certificate certificate = PkiTestUtils.generateCertificate( keyPair.getPublic(), "CN=Test", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null, new KeyUsage(KeyUsage.nonRepudiation)); List<X509Certificate> certificateChain = new LinkedList<X509Certificate>(); /* * We need at least 2 certificates for the XAdES-C complete certificate * refs construction. */ certificateChain.add(certificate); certificateChain.add(certificate); RevocationData revocationData = new RevocationData(); final X509CRL crl = PkiTestUtils.generateCrl(certificate, keyPair.getPrivate()); revocationData.addCRL(crl); OCSPResp ocspResp = PkiTestUtils.createOcspResp( certificate, false, certificate, certificate, keyPair.getPrivate(), "SHA1withRSA"); revocationData.addOCSP(ocspResp.getEncoded()); // expectations EasyMock.expect( mockTimeStampService.timeStamp( EasyMock.anyObject(byte[].class), EasyMock.anyObject(RevocationData.class))) .andStubAnswer( new IAnswer<byte[]>() { public byte[] answer() throws Throwable { Object[] arguments = EasyMock.getCurrentArguments(); RevocationData revocationData = (RevocationData) arguments[1]; revocationData.addCRL(crl); return "time-stamp-token".getBytes(); } }); EasyMock.expect(mockRevocationDataService.getRevocationData(EasyMock.eq(certificateChain))) .andStubReturn(revocationData); // prepare EasyMock.replay(mockTimeStampService, mockRevocationDataService); // operate DigestInfo digestInfo = testedInstance.preSign(null, certificateChain, null, null, null); // verify assertNotNull(digestInfo); assertEquals("SHA-1", digestInfo.digestAlgo); assertNotNull(digestInfo.digestValue); TemporaryTestDataStorage temporaryDataStorage = (TemporaryTestDataStorage) testedInstance.getTemporaryDataStorage(); assertNotNull(temporaryDataStorage); InputStream tempInputStream = temporaryDataStorage.getTempInputStream(); assertNotNull(tempInputStream); Document tmpDocument = PkiTestUtils.loadDocument(tempInputStream); LOG.debug("tmp document: " + PkiTestUtils.toString(tmpDocument)); Element nsElement = tmpDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS); nsElement.setAttributeNS( Constants.NamespaceSpecNS, "xmlns:xades", "http://uri.etsi.org/01903/v1.3.2#"); Node digestValueNode = XPathAPI.selectSingleNode(tmpDocument, "//ds:DigestValue", nsElement); assertNotNull(digestValueNode); String digestValueTextContent = digestValueNode.getTextContent(); LOG.debug("digest value text content: " + digestValueTextContent); assertFalse(digestValueTextContent.isEmpty()); /* * Sign the received XML signature digest value. */ Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate()); byte[] digestInfoValue = ArrayUtils.addAll(PkiTestUtils.SHA1_DIGEST_INFO_PREFIX, digestInfo.digestValue); byte[] signatureValue = cipher.doFinal(digestInfoValue); /* * Operate: postSign */ testedInstance.postSign(signatureValue, certificateChain); // verify EasyMock.verify(mockTimeStampService, mockRevocationDataService); byte[] signedDocumentData = testedInstance.getSignedDocumentData(); assertNotNull(signedDocumentData); Document signedDocument = PkiTestUtils.loadDocument(new ByteArrayInputStream(signedDocumentData)); LOG.debug("signed document: " + PkiTestUtils.toString(signedDocument)); NodeList signatureNodeList = signedDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); assertEquals(1, signatureNodeList.getLength()); Element signatureNode = (Element) signatureNodeList.item(0); // work-around for Java 7 Element signedPropertiesElement = (Element) signatureNode .getElementsByTagNameNS(XAdESXLSignatureFacet.XADES_NAMESPACE, "SignedProperties") .item(0); signedPropertiesElement.setIdAttribute("Id", true); DOMValidateContext domValidateContext = new DOMValidateContext( KeySelector.singletonKeySelector(keyPair.getPublic()), signatureNode); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); assertTrue(validity); File tmpFile = File.createTempFile("xades-bes-", ".xml"); FileUtils.writeStringToFile(tmpFile, PkiTestUtils.toString(signedDocument)); LOG.debug("tmp file: " + tmpFile.getAbsolutePath()); Node resultNode = XPathAPI.selectSingleNode( signedDocument, "ds:Signature/ds:Object/xades:QualifyingProperties/xades:SignedProperties/xades:SignedSignatureProperties/xades:SigningCertificate/xades:Cert/xades:CertDigest/ds:DigestValue", nsElement); assertNotNull(resultNode); // also test whether the XAdES extension is in line with the XAdES XML // Schema. // stax-api 1.0.1 prevents us from using // "XMLConstants.W3C_XML_SCHEMA_NS_URI" Node qualifyingPropertiesNode = XPathAPI.selectSingleNode( signedDocument, "ds:Signature/ds:Object/xades:QualifyingProperties", nsElement); SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); LSResourceResolver xadesResourceResolver = new XAdESLSResourceResolver(); factory.setResourceResolver(xadesResourceResolver); InputStream schemaInputStream = XAdESSignatureFacetTest.class.getResourceAsStream("/XAdESv141.xsd"); Source schemaSource = new StreamSource(schemaInputStream); Schema schema = factory.newSchema(schemaSource); Validator validator = schema.newValidator(); // DOMResult gives some DOMException... validator.validate(new DOMSource(qualifyingPropertiesNode)); StreamSource streamSource = new StreamSource(tmpFile.toURI().toString()); ByteArrayOutputStream resultOutputStream = new ByteArrayOutputStream(); StreamResult streamResult = new StreamResult(resultOutputStream); // validator.validate(streamSource, streamResult); LOG.debug("result: " + resultOutputStream); }