Example usage for javax.xml.validation Schema newValidator

List of usage examples for javax.xml.validation Schema newValidator

Introduction

In this page you can find the example usage for javax.xml.validation Schema newValidator.

Prototype

public abstract Validator newValidator();

Source Link

Document

Creates a new Validator for this Schema .

Usage

From source file:org.wso2.carbon.identity.entitlement.EntitlementUtil.java

/**
 * Validates the given policy XML files against the standard XACML policies.
 *
 * @param policy Policy to validate/*from   w w  w  .  j  a v a2  s  .  c om*/
 * @return return false, If validation failed or XML parsing failed or any IOException occurs
 */
public static boolean validatePolicy(PolicyDTO policy) {
    try {

        if (!"true".equalsIgnoreCase((String) EntitlementServiceComponent.getEntitlementConfig()
                .getEngineProperties().get(EntitlementExtensionBuilder.PDP_SCHEMA_VALIDATION))) {
            return true;
        }

        // there may be cases where you only updated the policy meta data in PolicyDTO not the
        // actual XACML policy String
        if (policy.getPolicy() == null || policy.getPolicy().trim().length() < 1) {
            return true;
        }

        //get policy version
        String policyXMLNS = getPolicyVersion(policy.getPolicy());

        Map<String, Schema> schemaMap = EntitlementServiceComponent.getEntitlementConfig().getPolicySchemaMap();
        //load correct schema by version
        Schema schema = schemaMap.get(policyXMLNS);

        if (schema != null) {
            //build XML document
            DocumentBuilder documentBuilder = getSecuredDocumentBuilder(false);
            InputStream stream = new ByteArrayInputStream(policy.getPolicy().getBytes());
            Document doc = documentBuilder.parse(stream);
            //Do the DOM validation
            DOMSource domSource = new DOMSource(doc);
            DOMResult domResult = new DOMResult();
            Validator validator = schema.newValidator();
            validator.validate(domSource, domResult);
            if (log.isDebugEnabled()) {
                log.debug("XACML Policy validation succeeded with the Schema");
            }
            return true;
        } else {
            log.error("Invalid Namespace in policy");
        }
    } catch (SAXException e) {
        log.error("XACML policy is not valid according to the schema :" + e.getMessage());
    } catch (IOException e) {
        //ignore
    } catch (ParserConfigurationException e) {
        //ignore
    }
    return false;
}

From source file:org.wso2.carbon.integration.common.tests.utils.DistributionValidationTestUtils.java

public static void validateXml(HashMap<String, Exception> xsdValidateMap, String distributionXml,
        String xsdFile) throws IOException {
    Source schemaFile = new StreamSource(new File(xsdFile));
    Source xmlFile = new StreamSource(new File(distributionXml));
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;
    try {/*from   w  w  w  .  ja  v  a 2s  .  c om*/
        schema = schemaFactory.newSchema(schemaFile);
    } catch (SAXException e) {
        log.error(distributionXml, e);
        xsdValidateMap.put(distributionXml, e);
    }
    if (schema != null) {
        Validator validator = schema.newValidator();
        try {
            validator.validate(xmlFile);
        } catch (SAXException e) {
            log.error(distributionXml, e);
            xsdValidateMap.put(distributionXml, e);
        }
    }
}

From source file:org.wso2.carbon.lcm.core.util.LifecycleUtils.java

/**
 * Method used to get schema validator object for lifecycle configurations.
 * @param schemaPath Schema path in the server extracted directory.
 * @return schema validator object/* w w w.  ja  va2  s .  co  m*/
 */
public static synchronized Validator getLifecycleSchemaValidator(String schemaPath) {
    if (lifecycleSchemaValidator != null) {
        return lifecycleSchemaValidator;
    }
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File(schemaPath));
        lifecycleSchemaValidator = schema.newValidator();
    } catch (SAXException e) {
        log.error("Unable to get a schema validator from the given file path : " + schemaPath);
    }
    return lifecycleSchemaValidator;
}

From source file:org.xsystem.bpmn2.formats.xml.XMLParser3.java

Document validate(InputStream input) throws ParserConfigurationException, SAXException, IOException {
    Schema schema = buildSxema();
    Validator validator = schema.newValidator();

    validator.setErrorHandler(new ErrorHandler() {

        @Override/* w  ww  . j a  va 2  s  . c  o  m*/
        public void warning(SAXParseException ex) throws SAXException {
            System.err.println(ex.getMessage());
        }

        @Override
        public void error(SAXParseException ex) throws SAXException {
            System.err.println(ex.getMessage());
        }

        @Override
        public void fatalError(SAXParseException ex) throws SAXException {
            throw ex;
        }

    });

    Document doc = XMLUtil.getDocument(input);

    DOMSource source = new DOMSource(doc);

    validator.validate(source);//, result);

    return doc;
}

From source file:test.common.TestBase.java

/**
 * Assert that the XML is valid to the schema.
 * /*from   w ww .j a v  a  2  s. c  om*/
 * @param xmlData
 * @param schemaFileName
 * @throws Exception Any exception
 */
public static void assertXMLValid(final String xmlData) throws Exception {
    logger.info("### assertXMLValid ###");
    if (xmlData == null) {
        throw new IllegalArgumentException(TestBase.class.getSimpleName() + ":assertXMLValid:xmlData is null");
    }
    if (schemas == null) {
        initializeSchemas();
    }
    String nameSpace = getNameSpaceFromXml(xmlData);
    logger.info("Looking up namespace '" + nameSpace + "'");
    Schema schema = schemas.get(nameSpace);

    try {
        Validator validator = schema.newValidator();
        InputStream in = new ByteArrayInputStream(xmlData.getBytes("UTF-8"));
        validator.validate(new SAXSource(new InputSource(in)));
    } catch (SAXParseException e) {
        e.printStackTrace();
        StringBuffer sb = new StringBuffer();
        sb.append("XML invalid at line:" + e.getLineNumber() + ", column:" + e.getColumnNumber() + "\n");
        sb.append("SAXParseException message: " + e.getMessage() + "\n");
        sb.append("Affected XML: \n" + xmlData);
        fail(sb.toString());
    }
}

From source file:test.common.TestBase.java

/**
 * @throws IOException/* ww  w  .  ja v  a2 s  .  c om*/
 * @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

/**
 * Assert that the XML is valid to the schema.
 * /*from   ww  w . j  a  va2 s  .c  o  m*/
 * @param xmlData The XML as a String.
 * @param schemaFileName The filename of the schema.
 * @throws Exception
 */
protected static void assertXMLValid(final String xmlData, final String schemaFileName) throws Exception {
    Schema schema = getSchema(schemaFileName);
    try {
        Validator validator = schema.newValidator();
        InputStream in = new ByteArrayInputStream(xmlData.getBytes("UTF-8"));
        validator.validate(new SAXSource(new InputSource(in)));
    } catch (SAXParseException e) {
        StringBuffer sb = new StringBuffer();
        sb.append("XML invalid at line:" + e.getLineNumber() + ", column:" + e.getColumnNumber() + "\n");
        sb.append("SAXParseException message: " + e.getMessage() + "\n");
        sb.append("Affected XML: \n" + xmlData);
        fail(sb.toString());
    }
}

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

@Test
public void testSignEnvelopingDocument() throws Exception {
    // setup//  w w w  .  j  a  v  a 2 s  .c  om
    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 w w .j  a v  a  2s .c om*/
    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);
}

From source file:test.unit.be.fedict.eid.tsl.BelgianTrustServiceListFactoryTest.java

@Test
public void testBelgianTrustList() throws Exception {
    // setup/*from   www  .  j av  a  2  s. c o  m*/
    TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2014, Trimester.FIRST);

    assertNotNull(trustServiceList.getType());

    File unsignedTslFile = File.createTempFile("tsl-be-2014-T1-candidatetest", ".xml");
    trustServiceList.saveAs(unsignedTslFile);

    // sign trust list
    KeyPair keyPair = TrustTestUtils.generateKeyPair(2048);
    PrivateKey privateKey = keyPair.getPrivate();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(5);
    X509Certificate certificate = TrustTestUtils.generateSelfSignedCertificate(keyPair,
            "C=BE, CN=Belgium Trust List Scheme Operator", notBefore, notAfter);
    trustServiceList.sign(privateKey, certificate);

    // operate
    File tmpTslFile = File.createTempFile("tsl-be-", ".xml");
    // tmpTslFile.deleteOnExit();
    trustServiceList.saveAs(tmpTslFile);

    // --------------- VERIFY TRUST LIST --------------------
    LOG.debug("TSL: " + FileUtils.readFileToString(tmpTslFile));
    Document document = TrustTestUtils.loadDocument(tmpTslFile);

    // XML schema validation
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    LSResourceResolver resourceResolver = new TSLLSResourceResolver();
    factory.setResourceResolver(resourceResolver);
    InputStream tslSchemaInputStream = BelgianTrustServiceListFactoryTest.class
            .getResourceAsStream("/ts_119612v010101_xsd.xsd");
    Source tslSchemaSource = new StreamSource(tslSchemaInputStream);
    Schema tslSchema = factory.newSchema(tslSchemaSource);
    Validator tslValidator = tslSchema.newValidator();
    LOG.debug("Starting validate");
    tslValidator.validate(new DOMSource(document));

    Validator eccValidator = factory
            .newSchema(BelgianTrustServiceListFactoryTest.class.getResource("/ts_119612v010101_sie_xsd.xsd"))
            .newValidator();
    NodeList eccQualificationsNodeList = document.getElementsByTagNameNS(
            "http://uri.etsi.org/TrstSvc/SvcInfoExt/eSigDir-1999-93-EC-TrustedList/#", "Qualifications");
    for (int idx = 0; idx < eccQualificationsNodeList.getLength(); idx++) {
        Node eccQualificationsNode = eccQualificationsNodeList.item(idx);
        eccValidator.validate(new DOMSource(eccQualificationsNode));
    }

    Validator xadesValidator = factory
            .newSchema(BelgianTrustServiceListFactoryTest.class.getResource("/XAdES.xsd")).newValidator();
    NodeList xadesQualifyingPropertiesNodeList = document
            .getElementsByTagNameNS("http://uri.etsi.org/01903/v1.3.2#", "QualifyingProperties");
    for (int idx = 0; idx < xadesQualifyingPropertiesNodeList.getLength(); idx++) {
        Node xadesQualifyingPropertiesNode = xadesQualifyingPropertiesNodeList.item(idx);
        xadesValidator.validate(new DOMSource(xadesQualifyingPropertiesNode));
    }

    // signature
    trustServiceList = TrustServiceListFactory.newInstance(tmpTslFile);
    X509Certificate resultCertificate = trustServiceList.verifySignature();
    assertEquals(certificate, resultCertificate);

    File pdfExportFile = File.createTempFile("tsl-be-", ".pdf");
    trustServiceList.humanReadableExport(pdfExportFile);

    // scheme operator name
    String schemeOperatorNameEn = trustServiceList.getSchemeOperatorName(Locale.ENGLISH);
    assertEquals("FPS Economy, SMEs, Self-employed and Energy - Quality and Safety", schemeOperatorNameEn);
    LOG.debug("Locale.ENGLISH: " + Locale.ENGLISH.getLanguage());
    assertEquals("SPF Economie, PME, Classes moyennes et Energie - Qualit et Scurit",
            trustServiceList.getSchemeOperatorName(Locale.FRENCH));

    Node schemeOperatorNameEnNode = XPathAPI.selectSingleNode(document,
            "tsl:TrustServiceStatusList/tsl:SchemeInformation/tsl:SchemeOperatorName/tsl:Name[@xml:lang='en']");
    assertNotNull(schemeOperatorNameEnNode);
    assertEquals("FPS Economy, SMEs, Self-employed and Energy - Quality and Safety",
            schemeOperatorNameEnNode.getTextContent());

    // scheme operator postal address
    PostalAddressType resultPostalAddress = trustServiceList.getSchemeOperatorPostalAddress(Locale.ENGLISH);
    assertNotNull(resultPostalAddress);
    assertEquals("NG III - Koning Albert II-laan 16", resultPostalAddress.getStreetAddress());
    assertEquals("Brussels", resultPostalAddress.getLocality());
    assertEquals("Brussel", trustServiceList.getSchemeOperatorPostalAddress(new Locale("nl")).getLocality());

    // scheme operator electronic address
    assertEquals(2, trustServiceList.getSchemeOperatorElectronicAddresses().size());
    LOG.debug("electronic addresses: " + trustServiceList.getSchemeOperatorElectronicAddresses());

    // scheme name
    assertTrue(trustServiceList.getSchemeName(Locale.ENGLISH).startsWith("BE:"));

    // scheme information uri
    List<String> schemeInformationUris = trustServiceList.getSchemeInformationUris();
    assertNotNull(schemeInformationUris);
    // assertEquals(3, schemeInformationUris.size());
    assertEquals("http://tsl.belgium.be/", schemeInformationUris.get(0));

    // status determination approach
    assertEquals("http://uri.etsi.org/TrstSvc/TrustedList/TSLType/StatusDetn/EUappropriate",
            trustServiceList.getStatusDeterminationApproach());

    // scheme types

    /*List<String> schemeTypes = trustServiceList.getSchemeTypes();
    assertNotNull(schemeTypes);
    assertEquals(2, schemeTypes.size());
     */
    // scheme territory
    assertEquals("BE", trustServiceList.getSchemeTerritory());

    // legal notice
    String resultLegalNotice = trustServiceList.getLegalNotice(Locale.ENGLISH);
    assertNotNull(resultLegalNotice);
    assertTrue(resultLegalNotice.indexOf("1999/93/EC") != -1);
    assertTrue(resultLegalNotice.indexOf("Belgium") != -1);

    // historical information period
    assertEquals(new Integer(21845 * 3), trustServiceList.getHistoricalInformationPeriod());

    // list issue date time
    DateTime resultListIssueDateTime = trustServiceList.getListIssueDateTime();
    assertNotNull(resultListIssueDateTime);

    // next update
    DateTime resultNextUpdateDateTime = trustServiceList.getNextUpdate();
    assertNotNull(resultNextUpdateDateTime);

    // trust service provider list
    List<TrustServiceProvider> trustServiceProviders = trustServiceList.getTrustServiceProviders();
    assertEquals(2, trustServiceProviders.size());
    TrustServiceProvider certipostTrustServiceProvider = trustServiceProviders.get(0);
    assertEquals("Certipost n.v./s.a.", certipostTrustServiceProvider.getName(Locale.ENGLISH));

    // postal address
    PostalAddressType certipostPostalAddress = certipostTrustServiceProvider.getPostalAddress(Locale.ENGLISH);
    assertNotNull(certipostPostalAddress);
    assertEquals("Muntcentrum", certipostPostalAddress.getStreetAddress());
    assertEquals("BE", certipostPostalAddress.getCountryName());

    // electronic address
    /*
    List<String> resultElectronicAddress = certipostTrustServiceProvider
    .getElectronicAddress();
    assertEquals(2, resultElectronicAddress.size());
     */
    // information uri
    /*
    List<String> resultInformationUris = certipostTrustServiceProvider
    .getInformationUris(Locale.ENGLISH);
    assertEquals(2, resultInformationUris.size());
    assertEquals("http://repository.eid.belgium.be/EN/Index.htm",
    resultInformationUris.get(0));
    */

    LOG.debug("unsigned TSL: " + unsignedTslFile.getAbsolutePath());
    LOG.debug("TSL: " + tmpTslFile.getAbsolutePath());
    LOG.debug("PDF: " + pdfExportFile.getAbsolutePath());
}