Example usage for javax.xml.validation SchemaFactory newInstance

List of usage examples for javax.xml.validation SchemaFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.validation SchemaFactory newInstance.

Prototype

public static SchemaFactory newInstance(String schemaLanguage) 

Source Link

Document

Lookup an implementation of the SchemaFactory that supports the specified schema language and return it.

Usage

From source file:oscar.oscarLab.ca.all.parsers.HRMXMLHandler.java

public void init(String hl7Body) throws HL7Exception {

    // this.version = p.getVersion(hl7Body);
    logger.info("A NEW HRM XML PARSER OBJECT INSTANTIATED TO PARSE HL7 FILE " + hl7Body);

    try {//from www  .ja v  a2s  .c o m
        ByteArrayInputStream byeArrayInputStream = new ByteArrayInputStream(hl7Body.getBytes());

        // 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 schemaFile = new StreamSource(new File(SFTPConnector.OMD_directory + "report_manager_cds.xsd"));
        Schema schema = factory.newSchema(schemaFile); //new File(SFTPConnector.OMD_directory + "report_manager_cds.xsd"));

        JAXBContext jc = JAXBContext.newInstance("oscar.hospitalReportManager.xsd");
        Unmarshaller u = jc.createUnmarshaller();
        root = (OmdCds) u.unmarshal(byeArrayInputStream);
        pr = root.getPatientRecord();

    } catch (Exception e) {
        logger.error("error", e);
    }

    headers = new ArrayList<String>();

}

From source file:pl.nask.hsn2.workflow.parser.HWLParser.java

private void createSchema() throws IOException, SAXException {
    final DOMResult result = new DOMResult();

    SchemaOutputResolver outputResolver = new HwlSchemaOutputResolver(result);

    ctx.generateSchema(outputResolver);/*from  w ww. java 2 s. c om*/
    this.schemaNode = result.getNode();
    this.schemaSystemId = result.getSystemId();

    Source source = new DOMSource(schemaNode, schemaSystemId);

    this.schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(source);
}

From source file:pl.psnc.synat.wrdz.zmkd.plan.MigrationPlansBean.java

/**
 * /*from   w ww .  j a v a  2 s.c  om*/
 * Bean initialization instructions.
 * 
 * @throws JAXBException
 *             if creating an instance of JAXBContext fails
 * @throws SAXException
 *             if creating a schema object fails
 */
@PostConstruct
protected void init() throws JAXBException, SAXException {

    deleteErrorMessage = "notSet";

    jaxbContext = JAXBContext.newInstance(pl.psnc.darceo.migration.MigrationPlan.class);

    InputStream schemaInput = null;
    try {
        schemaInput = getClass().getResourceAsStream(XML_SCHEMA_FILE);
        schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new StreamSource(schemaInput));
    } finally {
        IOUtils.closeQuietly(schemaInput);
    }
}

From source file:se.mithlond.services.shared.test.entity.PlainJaxbContextRule.java

/**
 * Acquires a JAXB Schema from the provided JAXBContext.
 *
 * @param ctx The context for which am XSD should be constructed.
 * @return A tuple holding the constructed XSD from the provided JAXBContext, and
 * the LSResourceResolver synthesized during the way.
 * @throws NullPointerException     if ctx was {@code null}.
 * @throws IllegalArgumentException if a JAXB-related exception occurred while extracting the schema.
 *///from  w  w  w.  j  a  va2 s .  c  o  m
public static Tuple<Schema, LSResourceResolver> generateTransientXSD(final JAXBContext ctx)
        throws NullPointerException, IllegalArgumentException {

    // Check sanity
    org.apache.commons.lang3.Validate.notNull(ctx, "Cannot handle null ctx argument.");

    final SortedMap<String, ByteArrayOutputStream> namespace2SchemaMap = new TreeMap<>();

    try {
        ctx.generateSchema(new SchemaOutputResolver() {

            /**
             * {@inheritDoc}
             */
            @Override
            public Result createOutput(final String namespaceUri, final String suggestedFileName)
                    throws IOException {

                // The types should really be annotated with @XmlType(namespace = "... something ...")
                // to avoid using the default ("") namespace.
                if (namespaceUri.isEmpty()) {
                    log.warn("Received empty namespaceUri while resolving a generated schema. "
                            + "Did you forget to add a @XmlType(namespace = \"... something ...\") annotation "
                            + "to your class?");
                }

                // Create the result ByteArrayOutputStream
                final ByteArrayOutputStream out = new ByteArrayOutputStream();
                final StreamResult toReturn = new StreamResult(out);
                toReturn.setSystemId("");

                // Map the namespaceUri to the schemaResult.
                namespace2SchemaMap.put(namespaceUri, out);

                // All done.
                return toReturn;
            }
        });
    } catch (IOException e) {
        throw new IllegalArgumentException("Could not acquire Schema snippets.", e);
    }

    // Convert to an array of StreamSource.
    final MappedSchemaResourceResolver resourceResolver = new MappedSchemaResourceResolver();
    final StreamSource[] schemaSources = new StreamSource[namespace2SchemaMap.size()];
    int counter = 0;
    for (Map.Entry<String, ByteArrayOutputStream> current : namespace2SchemaMap.entrySet()) {

        final byte[] schemaSnippetAsBytes = current.getValue().toByteArray();
        resourceResolver.addNamespace2SchemaEntry(current.getKey(), new String(schemaSnippetAsBytes));

        if (log.isDebugEnabled()) {
            log.info("Generated schema [" + (counter + 1) + "/" + schemaSources.length + "]:\n "
                    + new String(schemaSnippetAsBytes));
        }

        // Copy the schema source to the schemaSources array.
        schemaSources[counter] = new StreamSource(new ByteArrayInputStream(schemaSnippetAsBytes), "");

        // Increase the counter
        counter++;
    }

    try {

        // All done.
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setResourceResolver(resourceResolver);
        final Schema transientSchema = schemaFactory.newSchema(schemaSources);

        // All done.
        return new Tuple<>(transientSchema, resourceResolver);

    } catch (final SAXException e) {
        throw new IllegalArgumentException("Could not create Schema from snippets.", e);
    }
}

From source file:se.skl.skltpservices.npoadapter.mapper.AbstractMapper.java

protected void initialiseValidator(String... xsds) {
    List<Source> schemaFiles = new ArrayList<Source>();
    for (String xsd : xsds) {
        schemaFiles.add(new StreamSource(getClass().getResourceAsStream(xsd)));
    }/*from  w  w w.j av  a  2 s. c o m*/

    // Note - SchemaFactory is not threadsafe
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        // Note - Schema is threadsafe
        schema = factory.newSchema(schemaFiles.toArray(new StreamSource[schemaFiles.size()]));
    } catch (SAXException s) {
        throw new RuntimeException(
                new InstantiationException("Failed to instantiate schema: " + s.getMessage()));
    }

}

From source file:sernet.verinice.service.XmlRightsService.java

private Schema getSchema() {
    if (schema == null) {
        SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {/*  w w w  .j  a v  a2s  . co m*/
            schema = sf.newSchema(getAuthConfigurationSchema().getURL());
        } catch (Exception e) {
            log.error("Error while creating schema.", e);
        }
    }
    return schema;
}

From source file:test.common.TestBase.java

/**
 * @throws IOException/*  ww w.  j av a 2  s .c  o m*/
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private static void initializeSchemas() throws IOException, SAXException, ParserConfigurationException {
    File[] schemaFiles = ResourceUtil.getFilenamesInDirectory("xsd/", TestBase.class.getClassLoader());
    PrintWriter pwriter = new PrintWriter("target/schemas.txt");
    logger.debug("Number of schema files: " + schemaFiles.length);
    pwriter.println("Number of schema files: " + schemaFiles.length);

    schemas = new HashMap<String, Schema>();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    //        sf.setResourceResolver(new ImportResolver());
    for (File file : schemaFiles) {
        logger.debug("Schema file: " + file.getCanonicalPath());
        pwriter.println("Schema file: " + file.getCanonicalPath());

        try {

            //TODO remove this hack when xsd files are cleared
            if (file.getCanonicalPath().contains("rest")) {
                logger.debug("Skipping schema file: " + file.getCanonicalPath());
                continue;
            }
            if (file.getCanonicalPath().endsWith("srw-types.xsd") && !file.getCanonicalPath().contains("0.8")) {
                logger.debug("Skipping schema file: " + file.getCanonicalPath());
                continue;
            }
            // end TODO                

            Schema schema = sf.newSchema(file);

            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            DefaultHandler handler = new DefaultHandler() {
                private String nameSpace = null;
                private boolean found = false;

                public void startElement(String uri, String localName, String qName, Attributes attributes) {
                    if (!found) {
                        String tagName = null;
                        int ix = qName.indexOf(":");
                        if (ix >= 0) {
                            tagName = qName.substring(ix + 1);
                        } else {
                            tagName = qName;
                        }
                        if ("schema".equals(tagName)) {
                            nameSpace = attributes.getValue("targetNamespace");
                            found = true;
                        }
                    }
                }

                public String toString() {
                    return nameSpace;
                }
            };
            parser.parse(file, handler);
            if (handler.toString() != null) {
                Schema s = schemas.get(handler.toString());
                if (s != null) {
                    logger.debug("overwriting key '" + handler.toString() + "'");
                }
                schemas.put(handler.toString(), schema);
                logger.debug("Successfully added: " + file.getCanonicalPath() + " key: '" + handler.toString()
                        + "' value: " + schema.toString() + " " + schema.newValidator());
            } else {
                logger.warn("Error reading xml schema: " + file);
            }
        } catch (Exception e) {
            logger.warn("Invalid xml schema " + file + " , cause " + e.getLocalizedMessage());
            logger.debug("Stacktrace: ", e);
        }
    }
    logger.info("XSD Schemas found: " + schemas);
    pwriter.close();
}

From source file:test.framework.TestBase.java

/**
 * Gets the <code>Schema</code> object for the provided <code>File</code>.
 * /*  w  ww . j  a  v  a  2  s .  c  o  m*/
 * @param schemaStream The file containing the schema.
 * @return The <code>Schema</code> object.
 * @throws Exception If anything fails.
 */
private static Schema getSchema(final String schemaFileName) throws Exception {
    if (schemaFileName == null) {
        throw new Exception("No schema input file name provided");
    }
    File schemaFile = new File(schemaFileName);
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema theSchema = sf.newSchema(schemaFile);
    return theSchema;
}

From source file:test.unit.be.fedict.eid.applet.service.signer.XAdESSignatureFacetTest.java

@Test
public void testSignEnvelopingDocument() throws Exception {
    // setup/*  www.j  a  v a 2  s  .  co  m*/
    EnvelopedSignatureFacet envelopedSignatureFacet = new EnvelopedSignatureFacet();
    KeyInfoSignatureFacet keyInfoSignatureFacet = new KeyInfoSignatureFacet(true, false, false);
    SignaturePolicyService signaturePolicyService = null;
    //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, 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);

    // 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());
    Node signatureNode = signatureNodeList.item(0);

    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-x-l-", ".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);
}

From source file:test.unit.be.fedict.eid.applet.service.signer.XAdESSignatureFacetTest.java

@Test
public void testSignEnvelopingDocumentOffice2010() throws Exception {
    // setup/*from w  ww  . j av  a2s  . com*/
    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);

    // 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());
    Node signatureNode = signatureNodeList.item(0);

    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);
}