diff --git a/jenkinsfiles/build/Jenkinsfile b/jenkinsfiles/build/Jenkinsfile index e8c9dfa..21d6ba4 100644 --- a/jenkinsfiles/build/Jenkinsfile +++ b/jenkinsfiles/build/Jenkinsfile @@ -1,8 +1,8 @@ pipeline { agent any tools { - maven 'mvn' - jdk 'JDK 8' + maven 'mvn396' + jdk 'temurin-jdk17' } stages { stage('Preparation') { @@ -14,7 +14,7 @@ pipeline { stage('Build') { steps{ sh 'mvn --version' - sh 'mvn clean install site -Pdocker' + sh 'mvn clean install site -Pintegration-tests,docker -Dsoapui.test.fail.ignore=true' } } stage('Results') { diff --git a/jenkinsfiles/release/Jenkinsfile b/jenkinsfiles/release/Jenkinsfile index 2562ff9..4571ac0 100644 --- a/jenkinsfiles/release/Jenkinsfile +++ b/jenkinsfiles/release/Jenkinsfile @@ -1,34 +1,35 @@ pipeline { agent any tools { - maven 'mvn' - jdk 'JDK 8' + maven 'mvn396' + jdk 'temurin-jdk17' } stages { - stage('Preparation') { + stage('Initialize') { steps{ - deleteDir() - sh 'git clone git@github.com:opengeospatial/ets-swecommon20.git .' + sh ''' + echo "PATH = ${PATH}" + echo "M2_HOME = ${M2_HOME}" + ''' + sh 'mvn --version' } } stage('Release') { steps{ - sh 'mvn --version' sh 'mvn -Dresume=false -DdryRun=true release:prepare -Psign-artifacts-with-ogc,integration-tests,docker -DreleaseVersion=${releaseVersion} -DdevelopmentVersion=${developmentVersion}' sh 'mvn -Dresume=false release:prepare release:perform -Psign-artifacts-with-ogc,integration-tests,docker -DreleaseVersion=${releaseVersion} -DdevelopmentVersion=${developmentVersion}' } } stage('Publication of site') { steps{ - sh 'mvn --version' sh 'git checkout ${releaseVersion}' sh 'mvn clean install site site:stage scm-publish:publish-scm' } } stage('Results') { steps{ - junit '**/target/surefire-reports/TEST-*.xml' - archive 'target/*' + archiveArtifacts artifacts: 'target/*', allowEmptyArchive: true + deleteDir() } } } diff --git a/pom.xml b/pom.xml index 272f4c6..ec3651a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,360 +1,177 @@ - + - - org.opengis.cite - ets-common - 9 - - 4.0.0 - org.opengis.cite - ets-swecommon20 - 1.2-SNAPSHOT - jar + + org.opengis.cite + ets-common + 14 + - Sensor Web Enablement (SWE) Common Data Model Encoding Standard - Describe purpose of test suite. - http://opengeospatial.github.io/ets-swecommon20/ - - - Apache License, Version 2.0 - http://opensource.org/licenses/Apache-2.0 - - + 4.0.0 + ets-swecommon20 + 1.2-SNAPSHOT + jar - - Open Geospatial Consortium - http://www.opengeospatial.org/ - - - scm:git:https://github.com/opengeospatial/ets-swecommon20.git - scm:git:git@github.com:opengeospatial/ets-swecommon20.git - https://github.com/opengeospatial/ets-swecommon20 - HEAD - - - GitHub Issue Tracker - https://github.com/opengeospatial/ets-swecommon20/issues - - - - Huy Nguyen - HuyQuoc2311@gmail.com - UTC - - + Sensor Web Enablement (SWE) Common Data Model Encoding Standard + Describe purpose of test suite. + https://opengeospatial.github.io/ets-swecommon20/ + + + Apache License, Version 2.0 + https://opensource.org/licenses/Apache-2.0 + + - - swecommon20 - 2.0 - 5.4.1 - + + Open Geospatial Consortium + https://www.ogc.org/ + + + scm:git:https://github.com/opengeospatial/ets-swecommon20.git + scm:git:git@github.com:opengeospatial/ets-swecommon20.git + https://github.com/opengeospatial/ets-swecommon20 + HEAD + + + GitHub Issue Tracker + https://github.com/opengeospatial/ets-swecommon20/issues + + + + Huy Nguyen + HuyQuoc2311@gmail.com + UTC + + + Dirk Stenger + https://github.com/dstenger + + - - - org.opengis.cite.teamengine - teamengine-spi - 5.3.1 - - - org.opengis.cite - schema-utils - 1.8 - - - com.sun.jersey - jersey-client - - - junit - junit - 4.13.1 - - - org.mockito - mockito-core - 2.27.0 - - - org.testng - testng - 6.9.10 - - - org.opengis.cite.saxon - saxon9 - 9.0.0.8 - - - xml-apis - xml-apis - 1.4.01 - - - xerces - xercesImpl - 2.12.2 - - - javax.ws.rs - jsr311-api - 1.1.1 - - + + swecommon20 + 2.0 + - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.1.0 - - true - package - - http://testng.org/javadocs/ - - - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 3.0.0-M3 - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-jar-plugin - 3.1.1 - - - org.apache.maven.plugins - maven-assembly-plugin - 3.1.1 - - - - org.opengis.cite.swecommon20.TestNGController - - - - ${basedir}/src/assembly/deps.xml - ${basedir}/src/assembly/ctl-scripts.xml - ${basedir}/src/assembly/aio.xml - - - - - package - - single - - - - - - org.apache.maven.plugins - maven-release-plugin - 2.5.3 - - true - @{project.version} - release - - - - org.apache.maven.plugins - maven-site-plugin - 3.7.1 - - - - org.apache.maven.plugins - maven-scm-publish-plugin - 3.0.0 - - gh-pages - - - - + + + org.opengis.cite.teamengine + teamengine-spi + + + org.opengis.cite + schema-utils + + + junit + junit + + + org.mockito + mockito-core + + + org.testng + testng + + + org.opengis.cite.saxon + saxon9 + + + xerces + xercesImpl + + - - - docker - - - - io.fabric8 - docker-maven-plugin - 0.30.0 - - - - opengeospatial/${project.artifactId} - - ${project.basedir}/src/main/docker - - ${project.version}-teamengine-${docker.teamengine.version} - - - - - - ${project.build.directory} - . - - dependency/*teamengine-*.war - dependency/*teamengine-*.zip - *ets-*.zip - - - - - - - - - 8081:8080 - - - - http://localhost:8081/teamengine - - - - - - - - - - start - pre-integration-test - - build - start - - - - stop - post-integration-test - - stop - remove - - - - build - - build - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 3.1.1 - - - - copy-dependencies - - - - - - - - - org.opengis.cite.teamengine - teamengine-web - ${docker.teamengine.version} - war - - - org.opengis.cite.teamengine - teamengine-web - ${docker.teamengine.version} - common-libs - zip - - - org.opengis.cite.teamengine - teamengine-console - ${docker.teamengine.version} - base - zip - - - - - release - - - - maven-gpg-plugin - 1.6 - - - sign-artifacts - verify - - sign - - - - - - - - - - - - + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + org.opengis.cite.swecommon20.TestNGController + + + + + + maven-scm-publish-plugin + + - - - sonatype-nexus-staging - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - site - scm:git:git@github.com:opengeospatial/ets-swecommon20.git - - + + + + io.fabric8 + docker-maven-plugin + + + + + + 8081:8080 + + + + http://localhost:8081/teamengine + + + + + + + + + + + + + + + docker + + + + io.fabric8 + docker-maven-plugin + + + build + + build + + + + push + + push + + + + + + maven-dependency-plugin + + + + copy + + + + + + + + + + + + + site + scm:git:git@github.com:opengeospatial/ets-swecommon20.git + + diff --git a/src/assembly/deps.xml b/src/assembly/deps.xml index c082479..080a72e 100755 --- a/src/assembly/deps.xml +++ b/src/assembly/deps.xml @@ -10,23 +10,13 @@ false - - - com.sun.jersey:jersey-client - org.opengis.cite:schema-utils - - / - false - runtime - false - org.opengis.cite.teamengine:teamengine-spi - com.sun.jersey:jersey-client - org.opengis.cite:schema-utils - org.testng:testng - javax.ws.rs:jsr311-api + *:jersey-client + *:jersey-server + *:jersey-common + jakarta.ws.rs:jakarta.ws.rs-api / false diff --git a/src/docker/Dockerfile b/src/docker/Dockerfile index 38af499..e9cdfbb 100755 --- a/src/docker/Dockerfile +++ b/src/docker/Dockerfile @@ -1,4 +1,6 @@ -FROM tomcat:7.0-jre8 +FROM tomcat:10.1-jre17 + +RUN apt update && apt install -y unzip # add TEAM Engine webapp ADD maven/dependency/teamengine-web-*.war /root/ @@ -21,5 +23,7 @@ RUN cd /root/ && unzip -q ets-swecommon20-*-ctl.zip -d /root/te_base/scripts ADD maven/ets-swecommon20-*-deps.zip /root/ RUN cd /root/ && unzip -q -o ets-swecommon20-*-deps.zip -d /usr/local/tomcat/webapps/teamengine/WEB-INF/lib +RUN rm -R /root/te_base/scripts/note + # run tomcat CMD ["catalina.sh", "run"] diff --git a/src/main/java/org/opengis/cite/swecommon20/ETSAssert.java b/src/main/java/org/opengis/cite/swecommon20/ETSAssert.java index f6d9475..1584388 100755 --- a/src/main/java/org/opengis/cite/swecommon20/ETSAssert.java +++ b/src/main/java/org/opengis/cite/swecommon20/ETSAssert.java @@ -27,138 +27,108 @@ */ public class ETSAssert { - private ETSAssert() { - } + private ETSAssert() { + } - /** - * Asserts that the qualified name of a DOM Node matches the expected value. - * - * @param node - * The Node to check. - * @param qName - * A QName object containing a namespace name (URI) and a local - * part. - */ - public static void assertQualifiedName(Node node, QName qName) { - Assert.assertEquals(node.getLocalName(), qName.getLocalPart(), - ErrorMessage.get(ErrorMessageKeys.LOCAL_NAME)); - Assert.assertEquals(node.getNamespaceURI(), qName.getNamespaceURI(), - ErrorMessage.get(ErrorMessageKeys.NAMESPACE_NAME)); - } + /** + * Asserts that the qualified name of a DOM Node matches the expected value. + * @param node The Node to check. + * @param qName A QName object containing a namespace name (URI) and a local part. + */ + public static void assertQualifiedName(Node node, QName qName) { + Assert.assertEquals(node.getLocalName(), qName.getLocalPart(), ErrorMessage.get(ErrorMessageKeys.LOCAL_NAME)); + Assert.assertEquals(node.getNamespaceURI(), qName.getNamespaceURI(), + ErrorMessage.get(ErrorMessageKeys.NAMESPACE_NAME)); + } - /** - * Asserts that an XPath 1.0 expression holds true for the given evaluation - * context. The following standard namespace bindings do not need to be - * explicitly declared: - * - *
    - *
  • ows: {@value org.opengis.cite.swecommon20.Namespaces#OWS}
  • - *
  • xlink: {@value org.opengis.cite.swecommon20.Namespaces#XLINK}
  • - *
  • gml: {@value org.opengis.cite.swecommon20.Namespaces#GML}
  • - *
- * - * @param expr - * A valid XPath 1.0 expression. - * @param context - * The context node. - * @param namespaceBindings - * A collection of namespace bindings for the XPath expression, - * where each entry maps a namespace URI (key) to a prefix - * (value). It may be {@code null}. - */ - public static void assertXPath(String expr, Node context, - Map namespaceBindings) { - if (null == context) { - throw new NullPointerException("Context node is null."); - } - NamespaceBindings bindings = NamespaceBindings.withStandardBindings(); - bindings.addAllBindings(namespaceBindings); - XPath xpath = XPathFactory.newInstance().newXPath(); - xpath.setNamespaceContext(bindings); - Boolean result; - try { - result = (Boolean) xpath.evaluate(expr, context, - XPathConstants.BOOLEAN); - } catch (XPathExpressionException xpe) { - String msg = ErrorMessage - .format(ErrorMessageKeys.XPATH_ERROR, expr); - TestSuiteLogger.log(Level.WARNING, msg, xpe); - throw new AssertionError(msg); - } - Assert.assertTrue( - result, - ErrorMessage.format(ErrorMessageKeys.XPATH_RESULT, - context.getNodeName(), expr)); - } + /** + * Asserts that an XPath 1.0 expression holds true for the given evaluation context. + * The following standard namespace bindings do not need to be explicitly declared: + * + *
    + *
  • ows: {@value org.opengis.cite.swecommon20.Namespaces#OWS}
  • + *
  • xlink: {@value org.opengis.cite.swecommon20.Namespaces#XLINK}
  • + *
  • gml: {@value org.opengis.cite.swecommon20.Namespaces#GML}
  • + *
+ * @param expr A valid XPath 1.0 expression. + * @param context The context node. + * @param namespaceBindings A collection of namespace bindings for the XPath + * expression, where each entry maps a namespace URI (key) to a prefix (value). It may + * be {@code null}. + */ + public static void assertXPath(String expr, Node context, Map namespaceBindings) { + if (null == context) { + throw new NullPointerException("Context node is null."); + } + NamespaceBindings bindings = NamespaceBindings.withStandardBindings(); + bindings.addAllBindings(namespaceBindings); + XPath xpath = XPathFactory.newInstance().newXPath(); + xpath.setNamespaceContext(bindings); + Boolean result; + try { + result = (Boolean) xpath.evaluate(expr, context, XPathConstants.BOOLEAN); + } + catch (XPathExpressionException xpe) { + String msg = ErrorMessage.format(ErrorMessageKeys.XPATH_ERROR, expr); + TestSuiteLogger.log(Level.WARNING, msg, xpe); + throw new AssertionError(msg); + } + Assert.assertTrue(result, ErrorMessage.format(ErrorMessageKeys.XPATH_RESULT, context.getNodeName(), expr)); + } - /** - * Asserts that an XML resource is schema-valid. - * - * @param validator - * The Validator to use. - * @param source - * The XML Source to be validated. - */ - public static void assertSchemaValid(Validator validator, Source source) { - ValidationErrorHandler errHandler = new ValidationErrorHandler(); - validator.setErrorHandler(errHandler); - try { - validator.validate(source); - } catch (Exception e) { - throw new AssertionError(ErrorMessage.format( - ErrorMessageKeys.XML_ERROR, e.getMessage())); - } - Assert.assertFalse(errHandler.errorsDetected(), ErrorMessage.format( - ErrorMessageKeys.NOT_SCHEMA_VALID, errHandler.getErrorCount(), - errHandler.toString())); - } + /** + * Asserts that an XML resource is schema-valid. + * @param validator The Validator to use. + * @param source The XML Source to be validated. + */ + public static void assertSchemaValid(Validator validator, Source source) { + ValidationErrorHandler errHandler = new ValidationErrorHandler(); + validator.setErrorHandler(errHandler); + try { + validator.validate(source); + } + catch (Exception e) { + throw new AssertionError(ErrorMessage.format(ErrorMessageKeys.XML_ERROR, e.getMessage())); + } + Assert.assertFalse(errHandler.errorsDetected(), ErrorMessage.format(ErrorMessageKeys.NOT_SCHEMA_VALID, + errHandler.getErrorCount(), errHandler.toString())); + } - /** - * Asserts that an XML resource satisfies all applicable constraints - * specified in a Schematron (ISO 19757-3) schema. The "xslt2" query - * language binding is supported. All patterns are checked. - * - * @param schemaRef - * A URL that denotes the location of a Schematron schema. - * @param xmlSource - * The XML Source to be validated. - */ - public static void assertSchematronValid(URL schemaRef, Source xmlSource) { - SchematronValidator validator; - try { - validator = new SchematronValidator(new StreamSource( - schemaRef.toString()), "#ALL"); - } catch (Exception e) { - StringBuilder msg = new StringBuilder( - "Failed to process Schematron schema at "); - msg.append(schemaRef).append('\n'); - msg.append(e.getMessage()); - throw new AssertionError(msg); - } + /** + * Asserts that an XML resource satisfies all applicable constraints specified in a + * Schematron (ISO 19757-3) schema. The "xslt2" query language binding is supported. + * All patterns are checked. + * @param schemaRef A URL that denotes the location of a Schematron schema. + * @param xmlSource The XML Source to be validated. + */ + public static void assertSchematronValid(URL schemaRef, Source xmlSource) { + SchematronValidator validator; + try { + validator = new SchematronValidator(new StreamSource(schemaRef.toString()), "#ALL"); + } + catch (Exception e) { + StringBuilder msg = new StringBuilder("Failed to process Schematron schema at "); + msg.append(schemaRef).append('\n'); + msg.append(e.getMessage()); + throw new AssertionError(msg); + } - DOMResult result = (DOMResult) validator.validate(xmlSource); - Assert.assertFalse(validator.ruleViolationsDetected(), ErrorMessage - .format(ErrorMessageKeys.NOT_SCHEMA_VALID, - validator.getRuleViolationCount(), - XMLUtils.writeNodeToString(result.getNode()))); - } + DOMResult result = (DOMResult) validator.validate(xmlSource); + Assert.assertFalse(validator.ruleViolationsDetected(), ErrorMessage.format(ErrorMessageKeys.NOT_SCHEMA_VALID, + validator.getRuleViolationCount(), XMLUtils.writeNodeToString(result.getNode()))); + } + + /** + * Asserts that the given XML entity contains the expected number of descendant + * elements having the specified name. + * @param xmlEntity A Document representing an XML entity. + * @param elementName The qualified name of the element. + * @param expectedCount The expected number of occurrences. + */ + public static void assertDescendantElementCount(Document xmlEntity, QName elementName, int expectedCount) { + NodeList features = xmlEntity.getElementsByTagNameNS(elementName.getNamespaceURI(), elementName.getLocalPart()); + Assert.assertEquals(features.getLength(), expectedCount, + String.format("Unexpected number of %s descendant elements.", elementName)); + } - /** - * Asserts that the given XML entity contains the expected number of - * descendant elements having the specified name. - * - * @param xmlEntity - * A Document representing an XML entity. - * @param elementName - * The qualified name of the element. - * @param expectedCount - * The expected number of occurrences. - */ - public static void assertDescendantElementCount(Document xmlEntity, - QName elementName, int expectedCount) { - NodeList features = xmlEntity.getElementsByTagNameNS( - elementName.getNamespaceURI(), elementName.getLocalPart()); - Assert.assertEquals(features.getLength(), expectedCount, String.format( - "Unexpected number of %s descendant elements.", elementName)); - } } diff --git a/src/main/java/org/opengis/cite/swecommon20/ErrorMessage.java b/src/main/java/org/opengis/cite/swecommon20/ErrorMessage.java index 56d11ff..d8f5343 100755 --- a/src/main/java/org/opengis/cite/swecommon20/ErrorMessage.java +++ b/src/main/java/org/opengis/cite/swecommon20/ErrorMessage.java @@ -4,46 +4,39 @@ import java.util.ResourceBundle; /** - * Utility class for retrieving and formatting localized error messages that - * describe failed assertions. + * Utility class for retrieving and formatting localized error messages that describe + * failed assertions. */ public class ErrorMessage { - private static final String BASE_NAME = - "org.opengis.cite.swecommon20.MessageBundle"; - private static ResourceBundle msgResources = - ResourceBundle.getBundle(BASE_NAME); + private static final String BASE_NAME = "org.opengis.cite.swecommon20.MessageBundle"; - /** - * Produces a formatted error message using the supplied substitution - * arguments and the current locale. The arguments should reflect the order - * of the placeholders in the message template. - * - * @param msgKey - * The key identifying the message template; it should be a - * member of {@code ErrorMessageKeys}. - * @param args - * An array of arguments to be formatted and substituted in the - * content of the message. - * @return A String containing the message content. If no message is found - * for the given key, a {@link java.util.MissingResourceException} - * is thrown. - */ - public static String format(String msgKey, Object... args) { - return MessageFormat.format(msgResources.getString(msgKey), args); - } + private static ResourceBundle msgResources = ResourceBundle.getBundle(BASE_NAME); + + /** + * Produces a formatted error message using the supplied substitution arguments and + * the current locale. The arguments should reflect the order of the placeholders in + * the message template. + * @param msgKey The key identifying the message template; it should be a member of + * {@code ErrorMessageKeys}. + * @param args An array of arguments to be formatted and substituted in the content of + * the message. + * @return A String containing the message content. If no message is found for the + * given key, a {@link java.util.MissingResourceException} is thrown. + */ + public static String format(String msgKey, Object... args) { + return MessageFormat.format(msgResources.getString(msgKey), args); + } + + /** + * Retrieves a simple message according to the current locale. + * @param msgKey The key identifying the message; it should be a member of + * {@code ErrorMessageKeys}. + * @return A String containing the message content. If no message is found for the + * given key, a {@link java.util.MissingResourceException} is thrown. + */ + public static String get(String msgKey) { + return msgResources.getString(msgKey); + } - /** - * Retrieves a simple message according to the current locale. - * - * @param msgKey - * The key identifying the message; it should be a member of - * {@code ErrorMessageKeys}. - * @return A String containing the message content. If no message is found - * for the given key, a {@link java.util.MissingResourceException} - * is thrown. - */ - public static String get(String msgKey) { - return msgResources.getString(msgKey); - } } diff --git a/src/main/java/org/opengis/cite/swecommon20/ErrorMessageKeys.java b/src/main/java/org/opengis/cite/swecommon20/ErrorMessageKeys.java index ed84b17..fffc812 100755 --- a/src/main/java/org/opengis/cite/swecommon20/ErrorMessageKeys.java +++ b/src/main/java/org/opengis/cite/swecommon20/ErrorMessageKeys.java @@ -1,22 +1,44 @@ package org.opengis.cite.swecommon20; /** - * Defines keys used to access localized messages for assertion errors. The - * messages are stored in Properties files that are encoded in ISO-8859-1 - * (Latin-1). For some languages the {@code native2ascii} tool must be used to - * process the files and produce escaped Unicode characters. + * Defines keys used to access localized messages for assertion errors. The messages are + * stored in Properties files that are encoded in ISO-8859-1 (Latin-1). For some languages + * the {@code native2ascii} tool must be used to process the files and produce escaped + * Unicode characters. */ public class ErrorMessageKeys { - public static final String NOT_SCHEMA_VALID = "NotSchemaValid"; - public static final String EMPTY_STRING = "EmptyString"; - public static final String XPATH_RESULT = "XPathResult"; - public static final String NAMESPACE_NAME = "NamespaceName"; - public static final String LOCAL_NAME = "LocalName"; - public static final String XML_ERROR = "XMLError"; - public static final String XPATH_ERROR = "XPathError"; - public static final String MISSING_INFOSET_ITEM = "MissingInfosetItem"; - public static final String UNEXPECTED_STATUS = "UnexpectedStatus"; - public static final String UNEXPECTED_MEDIA_TYPE = "UnexpectedMediaType"; - public static final String MISSING_ENTITY = "MissingEntity"; + /** Constant NOT_SCHEMA_VALID="NotSchemaValid" */ + public static final String NOT_SCHEMA_VALID = "NotSchemaValid"; + + /** Constant EMPTY_STRING="EmptyString" */ + public static final String EMPTY_STRING = "EmptyString"; + + /** Constant XPATH_RESULT="XPathResult" */ + public static final String XPATH_RESULT = "XPathResult"; + + /** Constant NAMESPACE_NAME="NamespaceName" */ + public static final String NAMESPACE_NAME = "NamespaceName"; + + /** Constant LOCAL_NAME="LocalName" */ + public static final String LOCAL_NAME = "LocalName"; + + /** Constant XML_ERROR="XMLError" */ + public static final String XML_ERROR = "XMLError"; + + /** Constant XPATH_ERROR="XPathError" */ + public static final String XPATH_ERROR = "XPathError"; + + /** Constant MISSING_INFOSET_ITEM="MissingInfosetItem" */ + public static final String MISSING_INFOSET_ITEM = "MissingInfosetItem"; + + /** Constant UNEXPECTED_STATUS="UnexpectedStatus" */ + public static final String UNEXPECTED_STATUS = "UnexpectedStatus"; + + /** Constant UNEXPECTED_MEDIA_TYPE="UnexpectedMediaType" */ + public static final String UNEXPECTED_MEDIA_TYPE = "UnexpectedMediaType"; + + /** Constant MISSING_ENTITY="MissingEntity" */ + public static final String MISSING_ENTITY = "MissingEntity"; + } diff --git a/src/main/java/org/opengis/cite/swecommon20/Namespaces.java b/src/main/java/org/opengis/cite/swecommon20/Namespaces.java index 97e7b49..996631d 100755 --- a/src/main/java/org/opengis/cite/swecommon20/Namespaces.java +++ b/src/main/java/org/opengis/cite/swecommon20/Namespaces.java @@ -4,29 +4,33 @@ /** * XML namespace names. - * - * @see Namespaces in XML 1.0 * + * @see Namespaces in XML 1.0 */ public class Namespaces { - private Namespaces() { - } - public static final String SWE="http://www.opengis.net/swe/2.0"; - - /** SOAP 1.2 message envelopes. */ - public static final String SOAP_ENV = "http://www.w3.org/2003/05/soap-envelope"; - /** W3C XLink */ - public static final String XLINK = "http://www.w3.org/1999/xlink"; - /** OGC 06-121r3 (OWS 1.1) */ - public static final String OWS = "http://www.opengis.net/ows/1.1"; - /** ISO 19136 (GML 3.2) */ - public static final String GML = "http://www.opengis.net/gml/3.2"; - /** W3C XML Schema namespace */ - public static final URI XSD = URI - .create("http://www.w3.org/2001/XMLSchema"); - /** Schematron (ISO 19757-3) namespace */ - public static final URI SCH = URI - .create("http://purl.oclc.org/dsdl/schematron"); + private Namespaces() { + } + + /** Constant SWE="http://www.opengis.net/swe/2.0" */ + public static final String SWE = "http://www.opengis.net/swe/2.0"; + + /** SOAP 1.2 message envelopes. */ + public static final String SOAP_ENV = "http://www.w3.org/2003/05/soap-envelope"; + + /** W3C XLink */ + public static final String XLINK = "http://www.w3.org/1999/xlink"; + + /** OGC 06-121r3 (OWS 1.1) */ + public static final String OWS = "http://www.opengis.net/ows/1.1"; + + /** ISO 19136 (GML 3.2) */ + public static final String GML = "http://www.opengis.net/gml/3.2"; + + /** W3C XML Schema namespace */ + public static final URI XSD = URI.create("http://www.w3.org/2001/XMLSchema"); + + /** Schematron (ISO 19757-3) namespace */ + public static final URI SCH = URI.create("http://purl.oclc.org/dsdl/schematron"); } diff --git a/src/main/java/org/opengis/cite/swecommon20/ReusableEntityFilter.java b/src/main/java/org/opengis/cite/swecommon20/ReusableEntityFilter.java new file mode 100644 index 0000000..c43f69b --- /dev/null +++ b/src/main/java/org/opengis/cite/swecommon20/ReusableEntityFilter.java @@ -0,0 +1,28 @@ +package org.opengis.cite.swecommon20; + +import java.io.IOException; + +import org.glassfish.jersey.client.ClientResponse; + +import jakarta.ws.rs.client.ClientRequestContext; +import jakarta.ws.rs.client.ClientResponseContext; +import jakarta.ws.rs.client.ClientResponseFilter; + +/** + * Buffers the (response) entity so it can be read multiple times. + * + *

+ * WARNING: The entity InputStream must be reset after each read attempt. + *

+ */ +public class ReusableEntityFilter implements ClientResponseFilter { + + /** {@inheritDoc} */ + @Override + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { + if (responseContext instanceof ClientResponse) { + ((ClientResponse) responseContext).bufferEntity(); + } + } + +} diff --git a/src/main/java/org/opengis/cite/swecommon20/SuiteAttribute.java b/src/main/java/org/opengis/cite/swecommon20/SuiteAttribute.java index 4a5525b..9b1a924 100755 --- a/src/main/java/org/opengis/cite/swecommon20/SuiteAttribute.java +++ b/src/main/java/org/opengis/cite/swecommon20/SuiteAttribute.java @@ -8,47 +8,61 @@ import org.w3c.dom.Document; /** - * An enumerated type defining ISuite attributes that may be set to constitute a - * shared test fixture. + * An enumerated type defining ISuite attributes that may be set to constitute a shared + * test fixture. */ @SuppressWarnings("rawtypes") public enum SuiteAttribute { - SCHEMA_LOC_SET("schema-loc-set", Set.class), - XML("xml-data", File.class), - SCHEMATRON("schematron", URI.class), - /** - * Contains the XML Schema components comprising an application schema. - */ - XSMODEL("xsmodel", XSModel.class), - /** - * A DOM Document representation of the test subject or metadata about it. - */ - TEST_SUBJECT("testSubject", Document.class), + SCHEMA_LOC_SET("schema-loc-set", Set.class), XML("xml-data", File.class), SCHEMATRON("schematron", URI.class), /** - * An absolute URI referring to a DOM Document schema. - */ + * Contains the XML Schema components comprising an application schema. + */ + XSMODEL("xsmodel", XSModel.class), + /** + * A DOM Document representation of the test subject or metadata about it. + */ + TEST_SUBJECT("testSubject", Document.class), + /** + * An absolute URI referring to a DOM Document schema. + */ TEST_SUBJECT_URI("testSubjectUri", URI.class); - private final Class attrType; - private final String attrName; - - private SuiteAttribute(String attrName, Class attrType) { - this.attrName = attrName; - this.attrType = attrType; - } - - public Class getType() { - return attrType; - } - - public String getName() { - return attrName; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(attrName); - sb.append('(').append(attrType.getName()).append(')'); - return sb.toString(); - } + + private final Class attrType; + + private final String attrName; + + private SuiteAttribute(String attrName, Class attrType) { + this.attrName = attrName; + this.attrType = attrType; + } + + /** + *

+ * getType. + *

+ * @return a {@link java.lang.Class} object + */ + public Class getType() { + return attrType; + } + + /** + *

+ * getName. + *

+ * @return a {@link java.lang.String} object + */ + public String getName() { + return attrName; + } + + /** {@inheritDoc} */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(attrName); + sb.append('(').append(attrType.getName()).append(')'); + return sb.toString(); + } + } diff --git a/src/main/java/org/opengis/cite/swecommon20/SuiteFixtureListener.java b/src/main/java/org/opengis/cite/swecommon20/SuiteFixtureListener.java index 4bca8fc..8d6cd55 100755 --- a/src/main/java/org/opengis/cite/swecommon20/SuiteFixtureListener.java +++ b/src/main/java/org/opengis/cite/swecommon20/SuiteFixtureListener.java @@ -21,79 +21,74 @@ import org.w3c.dom.Document; /** - * A listener that performs various tasks before and after a test suite is run, - * usually concerned with maintaining a shared test suite fixture. Since this - * listener is loaded using the ServiceLoader mechanism, its methods will be - * called before those of other suite listeners listed in the test suite - * definition and before any annotated configuration methods. + * A listener that performs various tasks before and after a test suite is run, usually + * concerned with maintaining a shared test suite fixture. Since this listener is loaded + * using the ServiceLoader mechanism, its methods will be called before those of other + * suite listeners listed in the test suite definition and before any annotated + * configuration methods. * - * Attributes set on an ISuite instance are not inherited by constituent test - * group contexts (ITestContext). However, suite attributes are still accessible - * from lower contexts. + * Attributes set on an ISuite instance are not inherited by constituent test group + * contexts (ITestContext). However, suite attributes are still accessible from lower + * contexts. * * @see org.testng.ISuite ISuite interface */ public class SuiteFixtureListener implements ISuiteListener { - @Override - public void onStart(ISuite suite) { - processIUTParameter(suite); + /** {@inheritDoc} */ + @Override + public void onStart(ISuite suite) { + processIUTParameter(suite); processXmlReference(suite); processSchematronSchema(suite); - } + } - @Override - public void onFinish(ISuite suite) { - Reporter.clear(); // clear output from previous test runs + /** {@inheritDoc} */ + @Override + public void onFinish(ISuite suite) { + Reporter.clear(); // clear output from previous test runs Reporter.log("Test suite parameters:"); Reporter.log(suite.getXmlSuite().getAllParameters().toString()); - } + } - /** - * Processes test suite arguments and sets suite attributes accordingly. The - * entity referenced by the {@link TestRunArg#IUT iut} argument is parsed - * and the resulting Document is set as the value of the "testSubject" - * attribute. - * - * @param suite - * An ISuite object representing a TestNG test suite. - */ - void processSuiteParameters(ISuite suite) { - Map params = suite.getXmlSuite().getParameters(); - TestSuiteLogger.log(Level.CONFIG, - "Suite parameters\n" + params.toString()); - String iutParam = params.get(TestRunArg.IUT.toString()); - if ((null == iutParam) || iutParam.isEmpty()) { - throw new IllegalArgumentException( - "Required test run parameter not found: " - + TestRunArg.IUT.toString()); - } - URI iutRef = URI.create(iutParam.trim()); - File entityFile = null; - try { - entityFile = URIUtils.dereferenceURI(iutRef); - } catch (IOException iox) { - throw new RuntimeException("Failed to dereference resource located at " - + iutRef, iox); - } - Document iutDoc = null; - try { - iutDoc = URIUtils.parseURI(entityFile.toURI()); - } catch (Exception x) { - throw new RuntimeException("Failed to parse resource retrieved from " - + iutRef, x); - } - suite.setAttribute(SuiteAttribute.TEST_SUBJECT.getName(), iutDoc); - if (TestSuiteLogger.isLoggable(Level.FINE)) { - StringBuilder logMsg = new StringBuilder( - "Parsed resource retrieved from "); - logMsg.append(iutRef).append("\n"); - logMsg.append(XMLUtils.writeNodeToString(iutDoc)); - TestSuiteLogger.log(Level.FINE, logMsg.toString()); - } - } - - void processXmlReference(ISuite suite) { + /** + * Processes test suite arguments and sets suite attributes accordingly. The entity + * referenced by the {@link TestRunArg#IUT iut} argument is parsed and the resulting + * Document is set as the value of the "testSubject" attribute. + * @param suite An ISuite object representing a TestNG test suite. + */ + void processSuiteParameters(ISuite suite) { + Map params = suite.getXmlSuite().getParameters(); + TestSuiteLogger.log(Level.CONFIG, "Suite parameters\n" + params.toString()); + String iutParam = params.get(TestRunArg.IUT.toString()); + if ((null == iutParam) || iutParam.isEmpty()) { + throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.IUT.toString()); + } + URI iutRef = URI.create(iutParam.trim()); + File entityFile = null; + try { + entityFile = URIUtils.dereferenceURI(iutRef); + } + catch (IOException iox) { + throw new RuntimeException("Failed to dereference resource located at " + iutRef, iox); + } + Document iutDoc = null; + try { + iutDoc = URIUtils.parseURI(entityFile.toURI()); + } + catch (Exception x) { + throw new RuntimeException("Failed to parse resource retrieved from " + iutRef, x); + } + suite.setAttribute(SuiteAttribute.TEST_SUBJECT.getName(), iutDoc); + if (TestSuiteLogger.isLoggable(Level.FINE)) { + StringBuilder logMsg = new StringBuilder("Parsed resource retrieved from "); + logMsg.append(iutRef).append("\n"); + logMsg.append(XMLUtils.writeNodeToString(iutDoc)); + TestSuiteLogger.log(Level.FINE, logMsg.toString()); + } + } + + void processXmlReference(ISuite suite) { Map params = suite.getXmlSuite().getParameters(); TestSuiteLogger.log(Level.CONFIG, String.format("Suite parameters:\n %s", params)); Set schemaURIs = new HashSet(); @@ -118,24 +113,28 @@ void processXmlReference(ISuite suite) { if (XMLUtils.isXMLSchema(xmlFile)) { params.put(TestRunArg.XSD.toString(), xmlURI); schemaURIs.add(URI.create(xmlURI)); - } else { + } + else { schemaURIs.addAll(ValidationUtils.extractSchemaReferences(new StreamSource(xmlFile), xmlURI)); suite.setAttribute(SuiteAttribute.XML.getName(), xmlFile); Document iutDoc = null; try { - //iutDoc = URIUtils.parseURI(xmlFile.toURI()); + // iutDoc = URIUtils.parseURI(xmlFile.toURI()); iutDoc = URIUtils.parseURI(uriXml); - } catch (Exception x) { + } + catch (Exception x) { throw new RuntimeException("Failed to parse resource retrieved from " + xmlURI, x); } suite.setAttribute(SuiteAttribute.TEST_SUBJECT.getName(), iutDoc); TestSuiteLogger.log(Level.FINE, "Wrote XML document to " + xmlFile.getAbsolutePath()); suite.setAttribute(SuiteAttribute.TEST_SUBJECT_URI.getName(), URI.create(xmlURI)); } - } catch (IOException iox) { + } + catch (IOException iox) { throw new RuntimeException("Failed to read resource obtained from " + xmlURI, iox); - } catch (XMLStreamException xse) { + } + catch (XMLStreamException xse) { throw new RuntimeException("Failed to find schema reference in source: " + xmlFile.getAbsolutePath(), xse); } suite.setAttribute(SuiteAttribute.SCHEMA_LOC_SET.getName(), schemaURIs); @@ -161,15 +160,15 @@ void processIUTParameter(ISuite suite) { File iutFile = URIUtils.resolveURIAsFile(URI.create(iutRef)); if (XMLUtils.isXMLSchema(iutFile)) { params.put(TestRunArg.XSD.toString(), iutRef); - } else { + } + else { params.put(TestRunArg.XML.toString(), iutRef); } - } catch (Exception x) { + } + catch (Exception x) { throw new RuntimeException("Failed to read resource from " + iutRef, x); } params.remove(TestRunArg.IUT.toString()); } - - } diff --git a/src/main/java/org/opengis/cite/swecommon20/TestNGController.java b/src/main/java/org/opengis/cite/swecommon20/TestNGController.java index 921aebc..f00cc06 100755 --- a/src/main/java/org/opengis/cite/swecommon20/TestNGController.java +++ b/src/main/java/org/opengis/cite/swecommon20/TestNGController.java @@ -28,128 +28,116 @@ */ public class TestNGController implements TestSuiteController { - private TestRunExecutor executor; - private Properties etsProperties = new Properties(); - - /** - * A convenience method to facilitate test development. - * - * @param args - * Test run arguments (optional). The first argument must refer - * to an XML properties file containing the expected set of test - * run arguments. If no argument is supplied, the file located at - * ${user.home}/test-run-props.xml will be used. - * @throws Exception - * If the test run cannot be executed (usually due to - * unsatisfied pre-conditions). - */ - public static void main(String[] args) throws Exception { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - File xmlArgs = null; - if (args.length > 0) { - xmlArgs = (args[0].startsWith("file:")) ? new File( - URI.create(args[0])) : new File(args[0]); - } else { - String homeDir = System.getProperty("user.home"); - xmlArgs = new File(homeDir, "test-run-props.xml"); - } - if (!xmlArgs.exists()) { - throw new IllegalArgumentException( - "Test run arguments not found at " + xmlArgs); - } - Document testRunArgs = db.parse(xmlArgs); - TestNGController controller = new TestNGController(); - Source testResults = controller.doTestRun(testRunArgs); - System.out.println("Test results: " + testResults.getSystemId()); - } - - /** - * Default constructor uses the location given by the "user.home" system - * property as the root output directory. - */ - public TestNGController() { - this(new File(System.getProperty("user.home")).toURI().toString()); - } - - /** - * Construct a controller that writes results to the given output directory. - * - * @param outputDirUri - * A file URI that specifies the location of the directory in - * which test results will be written. It will be created if it - * does not exist. - */ - public TestNGController(String outputDirUri) { - InputStream is = getClass().getResourceAsStream("ets.properties"); - try { - this.etsProperties.load(is); - } catch (IOException ex) { - TestSuiteLogger.log(Level.WARNING, - "Unable to load ets.properties. " + ex.getMessage()); - } - URL tngSuite = TestNGController.class.getResource("testng.xml"); - File resultsDir = new File(URI.create(outputDirUri)); - TestSuiteLogger.log(Level.CONFIG, "Using TestNG config: " + tngSuite); - TestSuiteLogger.log(Level.CONFIG, - "Using outputDirPath: " + resultsDir.getAbsolutePath()); - // NOTE: setting third argument to 'true' enables the default listeners - this.executor = new TestNGExecutor(tngSuite.toString(), - resultsDir.getAbsolutePath(), false); - } - - @Override - public String getCode() { - return etsProperties.getProperty("ets-code"); - } - - @Override - public String getVersion() { - return etsProperties.getProperty("ets-version"); - } - - @Override - public String getTitle() { - return etsProperties.getProperty("ets-title"); - } - - @Override - public Source doTestRun(Document testRunArgs) throws Exception { - validateTestRunArgs(testRunArgs); - return executor.execute(testRunArgs); - } - - /** - * Validates the test run arguments. The test run is aborted if any of - * these checks fail. - * - * @param testRunArgs - * A DOM Document containing a set of XML properties (key-value - * pairs). - * @throws Exception - * If any arguments are missing or invalid for some reason. - */ - void validateTestRunArgs(Document testRunArgs) throws Exception { - if (null == testRunArgs - || !testRunArgs.getDocumentElement().getNodeName() - .equals("properties")) { - throw new IllegalArgumentException( - "Input is not an XML properties document."); - } - NodeList entries = testRunArgs.getDocumentElement() - .getElementsByTagName("entry"); - if (entries.getLength() == 0) { - throw new IllegalArgumentException("No test run arguments found."); - } - Map args = new HashMap(); - for (int i = 0; i < entries.getLength(); i++) { - Element entry = (Element) entries.item(i); - args.put(entry.getAttribute("key"), entry.getTextContent()); - } - if (!args.containsKey(TestRunArg.IUT.toString())) { - throw new IllegalArgumentException(String.format( - "Missing argument: '%s' must be present.", - TestRunArg.IUT)); - } - } + private TestRunExecutor executor; + + private Properties etsProperties = new Properties(); + + /** + * A convenience method to facilitate test development. + * @param args Test run arguments (optional). The first argument must refer to an XML + * properties file containing the expected set of test run arguments. If no argument + * is supplied, the file located at ${user.home}/test-run-props.xml will be used. + * @throws java.lang.Exception If the test run cannot be executed (usually due to + * unsatisfied pre-conditions). + */ + public static void main(String[] args) throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + File xmlArgs = null; + if (args.length > 0) { + xmlArgs = (args[0].startsWith("file:")) ? new File(URI.create(args[0])) : new File(args[0]); + } + else { + String homeDir = System.getProperty("user.home"); + xmlArgs = new File(homeDir, "test-run-props.xml"); + } + if (!xmlArgs.exists()) { + throw new IllegalArgumentException("Test run arguments not found at " + xmlArgs); + } + Document testRunArgs = db.parse(xmlArgs); + TestNGController controller = new TestNGController(); + Source testResults = controller.doTestRun(testRunArgs); + System.out.println("Test results: " + testResults.getSystemId()); + } + + /** + * Default constructor uses the location given by the "user.home" system property as + * the root output directory. + */ + public TestNGController() { + this(new File(System.getProperty("user.home")).toURI().toString()); + } + + /** + * Construct a controller that writes results to the given output directory. + * @param outputDirUri A file URI that specifies the location of the directory in + * which test results will be written. It will be created if it does not exist. + */ + public TestNGController(String outputDirUri) { + InputStream is = getClass().getResourceAsStream("ets.properties"); + try { + this.etsProperties.load(is); + } + catch (IOException ex) { + TestSuiteLogger.log(Level.WARNING, "Unable to load ets.properties. " + ex.getMessage()); + } + URL tngSuite = TestNGController.class.getResource("testng.xml"); + File resultsDir = new File(URI.create(outputDirUri)); + TestSuiteLogger.log(Level.CONFIG, "Using TestNG config: " + tngSuite); + TestSuiteLogger.log(Level.CONFIG, "Using outputDirPath: " + resultsDir.getAbsolutePath()); + // NOTE: setting third argument to 'true' enables the default listeners + this.executor = new TestNGExecutor(tngSuite.toString(), resultsDir.getAbsolutePath(), false); + } + + /** {@inheritDoc} */ + @Override + public String getCode() { + return etsProperties.getProperty("ets-code"); + } + + /** {@inheritDoc} */ + @Override + public String getVersion() { + return etsProperties.getProperty("ets-version"); + } + + /** {@inheritDoc} */ + @Override + public String getTitle() { + return etsProperties.getProperty("ets-title"); + } + + /** {@inheritDoc} */ + @Override + public Source doTestRun(Document testRunArgs) throws Exception { + validateTestRunArgs(testRunArgs); + return executor.execute(testRunArgs); + } + + /** + * Validates the test run arguments. The test run is aborted if any of these checks + * fail. + * @param testRunArgs A DOM Document containing a set of XML properties (key-value + * pairs). + * @throws Exception If any arguments are missing or invalid for some reason. + */ + void validateTestRunArgs(Document testRunArgs) throws Exception { + if (null == testRunArgs || !testRunArgs.getDocumentElement().getNodeName().equals("properties")) { + throw new IllegalArgumentException("Input is not an XML properties document."); + } + NodeList entries = testRunArgs.getDocumentElement().getElementsByTagName("entry"); + if (entries.getLength() == 0) { + throw new IllegalArgumentException("No test run arguments found."); + } + Map args = new HashMap(); + for (int i = 0; i < entries.getLength(); i++) { + Element entry = (Element) entries.item(i); + args.put(entry.getAttribute("key"), entry.getTextContent()); + } + if (!args.containsKey(TestRunArg.IUT.toString())) { + throw new IllegalArgumentException( + String.format("Missing argument: '%s' must be present.", TestRunArg.IUT)); + } + } + } diff --git a/src/main/java/org/opengis/cite/swecommon20/TestRunArg.java b/src/main/java/org/opengis/cite/swecommon20/TestRunArg.java index 1261eca..c3cc79d 100755 --- a/src/main/java/org/opengis/cite/swecommon20/TestRunArg.java +++ b/src/main/java/org/opengis/cite/swecommon20/TestRunArg.java @@ -5,19 +5,16 @@ */ public enum TestRunArg { - - /** - * An absolute URI that refers to a representation of the test subject or - * metadata about it. - */ - GML, - SCH, - IUT, - XML, - XSD; + /** + * An absolute URI that refers to a representation of the test subject or metadata + * about it. + */ + GML, SCH, IUT, XML, XSD; + + /** {@inheritDoc} */ + @Override + public String toString() { + return name().toLowerCase(); + } - @Override - public String toString() { - return name().toLowerCase(); - } } diff --git a/src/main/java/org/opengis/cite/swecommon20/TestRunListener.java b/src/main/java/org/opengis/cite/swecommon20/TestRunListener.java index b595247..15bbc7c 100755 --- a/src/main/java/org/opengis/cite/swecommon20/TestRunListener.java +++ b/src/main/java/org/opengis/cite/swecommon20/TestRunListener.java @@ -3,24 +3,28 @@ import org.testng.IExecutionListener; /** - * A listener that is invoked before and after a test run. It is often used to - * configure a shared fixture that endures for the duration of the entire test - * run. A FixtureManager may be used to manage such a fixture. + * A listener that is invoked before and after a test run. It is often used to configure a + * shared fixture that endures for the duration of the entire test run. A FixtureManager + * may be used to manage such a fixture. * - *

A shared fixture should be used with caution in order to avoid undesirable - * test interactions. In general, it should be populated with "read-only" - * objects that are not modified during the test run.

+ *

+ * A shared fixture should be used with caution in order to avoid undesirable test + * interactions. In general, it should be populated with "read-only" objects that are not + * modified during the test run. + *

* * @see com.occamlab.te.spi.executors.FixtureManager FixtureManager - * */ public class TestRunListener implements IExecutionListener { - @Override - public void onExecutionStart() { - } + /** {@inheritDoc} */ + @Override + public void onExecutionStart() { + } + + /** {@inheritDoc} */ + @Override + public void onExecutionFinish() { + } - @Override - public void onExecutionFinish() { - } } diff --git a/src/main/java/org/opengis/cite/swecommon20/level1/AdvancedEncodings.java b/src/main/java/org/opengis/cite/swecommon20/level1/AdvancedEncodings.java index 6c01df1..44e2d37 100755 --- a/src/main/java/org/opengis/cite/swecommon20/level1/AdvancedEncodings.java +++ b/src/main/java/org/opengis/cite/swecommon20/level1/AdvancedEncodings.java @@ -6,13 +6,24 @@ import org.opengis.cite.swecommon20.ETSAssert; import org.testng.annotations.Test; -public class AdvancedEncodings extends DataFixture{ - - @Test(groups = "AdvancedEncodings", dependsOnGroups = { "BlockComponents" }, description="A.7 defines an additional encoding method for packaging sensor data as raw or base 64 binary blocks. When this package is implemented, the binary encoding method is usable, as any other encoding method, within the “DataArray” and “DataStream” classes") +/** + *

+ * AdvancedEncodings class. + *

+ * + */ +public class AdvancedEncodings extends DataFixture { + + /** + *

+ * checkAdvancedEncodingsSchematron. + *

+ */ + @Test(groups = "AdvancedEncodings", dependsOnGroups = { "BlockComponents" }, + description = "A.7 defines an additional encoding method for packaging sensor data as raw or base 64 binary blocks. When this package is implemented, the binary encoding method is usable, as any other encoding method, within the “DataArray” and “DataStream” classes") public void checkAdvancedEncodingsSchematron() { - URL schRef = this.getClass().getResource( - "/org/opengis/cite/swecommon20/sch/A.7.AdvancedEncodings.sch"); - ETSAssert - .assertSchematronValid(schRef, new StreamSource(this.dataFile)); + URL schRef = this.getClass().getResource("/org/opengis/cite/swecommon20/sch/A.7.AdvancedEncodings.sch"); + ETSAssert.assertSchematronValid(schRef, new StreamSource(this.dataFile)); } + } diff --git a/src/main/java/org/opengis/cite/swecommon20/level1/AdvancedEncodingsSchema.java b/src/main/java/org/opengis/cite/swecommon20/level1/AdvancedEncodingsSchema.java index 62be5ce..cc6da14 100755 --- a/src/main/java/org/opengis/cite/swecommon20/level1/AdvancedEncodingsSchema.java +++ b/src/main/java/org/opengis/cite/swecommon20/level1/AdvancedEncodingsSchema.java @@ -6,13 +6,24 @@ import org.opengis.cite.swecommon20.ETSAssert; import org.testng.annotations.Test; -public class AdvancedEncodingsSchema extends DataFixture{ - - @Test(groups = "AdvancedEncodingsSchema", dependsOnGroups = { "SimpleComponents" }, description="Conformance Test Class A.13") +/** + *

+ * AdvancedEncodingsSchema class. + *

+ * + */ +public class AdvancedEncodingsSchema extends DataFixture { + + /** + *

+ * checkAdvancedEncodingsSchemaSchematron. + *

+ */ + @Test(groups = "AdvancedEncodingsSchema", dependsOnGroups = { "SimpleComponents" }, + description = "Conformance Test Class A.13") public void checkAdvancedEncodingsSchemaSchematron() { - URL schRef = this.getClass().getResource( - "/org/opengis/cite/swecommon20/sch/A.13.AdvancedEncodingsSchema.sch"); - ETSAssert - .assertSchematronValid(schRef, new StreamSource(this.dataFile)); + URL schRef = this.getClass().getResource("/org/opengis/cite/swecommon20/sch/A.13.AdvancedEncodingsSchema.sch"); + ETSAssert.assertSchematronValid(schRef, new StreamSource(this.dataFile)); } + } diff --git a/src/main/java/org/opengis/cite/swecommon20/level1/BlockComponents.java b/src/main/java/org/opengis/cite/swecommon20/level1/BlockComponents.java index b7840ad..9ed3988 100755 --- a/src/main/java/org/opengis/cite/swecommon20/level1/BlockComponents.java +++ b/src/main/java/org/opengis/cite/swecommon20/level1/BlockComponents.java @@ -7,18 +7,28 @@ import org.testng.SkipException; import org.testng.annotations.Test; -public class BlockComponents extends DataFixture{ - - @Test(groups = "BlockComponents", dependsOnGroups = { "SimpleComponents", "SimpleEncodings" }, description="A.5 defines additional aggregate components for describing arrays of values that are designed to be encoded as efficient data blocks.") +/** + *

+ * BlockComponents class. + *

+ * + */ +public class BlockComponents extends DataFixture { + + /** + *

+ * checkBlockComponentsSchematron. + *

+ */ + @Test(groups = "BlockComponents", dependsOnGroups = { "SimpleComponents", "SimpleEncodings" }, + description = "A.5 defines additional aggregate components for describing arrays of values that are designed to be encoded as efficient data blocks.") public void checkBlockComponentsSchematron() { String hasResult = this.CheckXPath2("boolean(//swe:DataArray | //swe:Matrix | //swe:DataStream)"); if (hasResult.equals("false")) - throw new SkipException("No block components found."); - - URL schRef = this.getClass().getResource( - "/org/opengis/cite/swecommon20/sch/A.5.BlockComponents.sch"); - ETSAssert - .assertSchematronValid(schRef, new StreamSource(this.dataFile)); + throw new SkipException("No block components found."); + + URL schRef = this.getClass().getResource("/org/opengis/cite/swecommon20/sch/A.5.BlockComponents.sch"); + ETSAssert.assertSchematronValid(schRef, new StreamSource(this.dataFile)); } - + } diff --git a/src/main/java/org/opengis/cite/swecommon20/level1/ChoiceComponents.java b/src/main/java/org/opengis/cite/swecommon20/level1/ChoiceComponents.java index e5393fa..d5ef4b0 100755 --- a/src/main/java/org/opengis/cite/swecommon20/level1/ChoiceComponents.java +++ b/src/main/java/org/opengis/cite/swecommon20/level1/ChoiceComponents.java @@ -7,17 +7,28 @@ import org.testng.SkipException; import org.testng.annotations.Test; -public class ChoiceComponents extends DataFixture{ - - @Test(groups = "ChoiceComponents", dependsOnGroups = { "SimpleComponents" }, description="A.4 a disjoint union component type. This aggregate type can be nested with other aggregate components to build complex structures.") +/** + *

+ * ChoiceComponents class. + *

+ * + */ +public class ChoiceComponents extends DataFixture { + + /** + *

+ * checkChoiceComponentsSchematron. + *

+ */ + @Test(groups = "ChoiceComponents", dependsOnGroups = { "SimpleComponents" }, + description = "A.4 a disjoint union component type. This aggregate type can be nested with other aggregate components to build complex structures.") public void checkChoiceComponentsSchematron() { String hasResult = this.CheckXPath2("boolean(//swe:DataChoice)"); if (hasResult.equals("false")) throw new SkipException("Not choice components data."); - - URL schRef = this.getClass().getResource( - "/org/opengis/cite/swecommon20/sch/A.4.ChoiceComponents.sch"); - ETSAssert - .assertSchematronValid(schRef, new StreamSource(this.dataFile)); + + URL schRef = this.getClass().getResource("/org/opengis/cite/swecommon20/sch/A.4.ChoiceComponents.sch"); + ETSAssert.assertSchematronValid(schRef, new StreamSource(this.dataFile)); } + } diff --git a/src/main/java/org/opengis/cite/swecommon20/level1/CoreConcept.java b/src/main/java/org/opengis/cite/swecommon20/level1/CoreConcept.java index 31c9b6d..ca4cddc 100755 --- a/src/main/java/org/opengis/cite/swecommon20/level1/CoreConcept.java +++ b/src/main/java/org/opengis/cite/swecommon20/level1/CoreConcept.java @@ -14,25 +14,46 @@ import org.testng.annotations.Test; import org.xml.sax.SAXException; +/** + *

+ * CoreConcept class. + *

+ * + */ public class CoreConcept extends DataFixture { - @Test(groups = "CoreConceptsBase", description = "A.1.1 Core concepts are the base of all derived models. Validate the XML document using the XML schema document") - public void Core() { - URL schemaUrl = this.getClass().getResource( "/org/opengis/cite/swecommon20/xsd/opengis/swe_2.0.1_flatten/swe_2.0.1.xsd" ); - Source source = new DOMSource( this.testSubject ); - Validator validator; - try { - Schema schema = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI ).newSchema( schemaUrl ); - validator = schema.newValidator(); - ETSAssert.assertSchemaValid( validator, source ); - } catch ( SAXException e ) { - e.printStackTrace(); - } - } + /** + *

+ * Core. + *

+ */ + @Test(groups = "CoreConceptsBase", + description = "A.1.1 Core concepts are the base of all derived models. Validate the XML document using the XML schema document") + public void Core() { + URL schemaUrl = this.getClass() + .getResource("/org/opengis/cite/swecommon20/xsd/opengis/swe_2.0.1_flatten/swe_2.0.1.xsd"); + Source source = new DOMSource(this.testSubject); + Validator validator; + try { + Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaUrl); + validator = schema.newValidator(); + ETSAssert.assertSchemaValid(validator, source); + } + catch (SAXException e) { + e.printStackTrace(); + } + } + + /** + *

+ * checkCoreConceptsSchematron. + *

+ */ + @Test(groups = "CoreConcepts", dependsOnGroups = { "CoreConceptsBase" }, + description = "A.1 Validate all conformance classes in core concepts by using schematron file.") + public void checkCoreConceptsSchematron() { + URL schRef = this.getClass().getResource("/org/opengis/cite/swecommon20/sch/A.1.CoreConcepts.sch"); + ETSAssert.assertSchematronValid(schRef, new StreamSource(this.dataFile)); + } - @Test(groups = "CoreConcepts", dependsOnGroups = { "CoreConceptsBase" }, description = "A.1 Validate all conformance classes in core concepts by using schematron file.") - public void checkCoreConceptsSchematron() { - URL schRef = this.getClass().getResource( "/org/opengis/cite/swecommon20/sch/A.1.CoreConcepts.sch" ); - ETSAssert.assertSchematronValid( schRef, new StreamSource( this.dataFile ) ); - } } diff --git a/src/main/java/org/opengis/cite/swecommon20/level1/DataFixture.java b/src/main/java/org/opengis/cite/swecommon20/level1/DataFixture.java index e8340ca..0069285 100755 --- a/src/main/java/org/opengis/cite/swecommon20/level1/DataFixture.java +++ b/src/main/java/org/opengis/cite/swecommon20/level1/DataFixture.java @@ -34,31 +34,50 @@ import net.sf.saxon.s9api.XdmValue; /** - * A supporting base class that provides a common fixture for validating data - * sets. The configuration methods are invoked before any that may be defined in - * a subclass. + * A supporting base class that provides a common fixture for validating data sets. The + * configuration methods are invoked before any that may be defined in a subclass. */ public class DataFixture { - /** - * Files containing tested subject. - */ - protected File dataFile; - protected Document originalSubject; - protected Document testSubject; - protected URI testSubjectUri; - - protected String Resource_GML_Path = "/org/opengis/cite/swecommon20/xsd/opengis/gml/3.2.1/gml-3.2.1.xsd"; - protected String Resource_SWE_Path = "/org/opengis/cite/swecommon20/xsd/opengis/swe_2.0.1_flatten/swe_2.0.1.xsd"; - /** - * An XSModel object representing a GML application schema. - */ - protected XSModel model; - - public DataFixture() { - } - - public Validator CreateValidator(URL xsdPath) throws XMLStreamException, SAXException, IOException { + /** + * Files containing tested subject. + */ + protected File dataFile; + + protected Document originalSubject; + + protected Document testSubject; + + protected URI testSubjectUri; + + protected String Resource_GML_Path = "/org/opengis/cite/swecommon20/xsd/opengis/gml/3.2.1/gml-3.2.1.xsd"; + + protected String Resource_SWE_Path = "/org/opengis/cite/swecommon20/xsd/opengis/swe_2.0.1_flatten/swe_2.0.1.xsd"; + + /** + * An XSModel object representing a GML application schema. + */ + protected XSModel model; + + /** + *

+ * Constructor for DataFixture. + *

+ */ + public DataFixture() { + } + + /** + *

+ * CreateValidator. + *

+ * @param xsdPath a {@link java.net.URL} object + * @return a {@link javax.xml.validation.Validator} object + * @throws javax.xml.stream.XMLStreamException if any. + * @throws org.xml.sax.SAXException if any. + * @throws java.io.IOException if any. + */ + public Validator CreateValidator(URL xsdPath) throws XMLStreamException, SAXException, IOException { Schema schema; Set schemaRefs; schemaRefs = ValidationUtils.extractSchemaReferences(new StreamSource(this.dataFile), @@ -67,12 +86,10 @@ public Validator CreateValidator(URL xsdPath) throws XMLStreamException, SAXExce schema = xsdCompiler.compileXmlSchema(schemaRefs.toArray(new URI[schemaRefs.size()])); return schema.newValidator(); } - - /** + + /** * Check XPath2.0 - * - * @param xpath - * String denoting an xpath syntax + * @param xpath String denoting an xpath syntax * @return XdmValue converted to string */ public String CheckXPath2(String xpath) { @@ -80,125 +97,114 @@ public String CheckXPath2(String xpath) { try { xdmValue = XMLUtils.evaluateXPath2(new DOMSource(this.testSubject), xpath, NamespaceBindings.getStandardBindings()); - } catch (SaxonApiException e) { + } + catch (SaxonApiException e) { e.printStackTrace(); } return xdmValue.toString(); } - - @BeforeClass(alwaysRun = true) - public void obtainTestSubject(ITestContext testContext){ - Assert.assertTrue( - testContext.getSuite().getAttributeNames() - .contains(SuiteAttribute.XML.getName()), - "No data to validate."); - this.dataFile = (File) testContext.getSuite().getAttribute( - SuiteAttribute.XML.getName()); - this.model = (XSModel) testContext.getSuite().getAttribute( - SuiteAttribute.XSMODEL.getName()); - - Object obj = testContext.getSuite().getAttribute( - SuiteAttribute.TEST_SUBJECT.getName()); - if ((null != obj) && Document.class.isAssignableFrom(obj.getClass())) { - this.testSubject = Document.class.cast(obj); - originalSubject = Document.class.cast(obj); - } - - Object uriObj = testContext.getSuite().getAttribute( - SuiteAttribute.TEST_SUBJECT_URI.getName()); - if ((null != uriObj)){ - this.testSubjectUri = URI.class.cast(uriObj); - //System.out.println(this.testSubjectUri.toString()); - } - } - /** - * A configuration method ({@code BeforeClass}) that initializes the test - * fixture as follows: - *
    - *
  1. Obtain the GML data set from the test context. The suite attribute - * {@link org.opengis.cite.iso19136.SuiteAttribute#GML} should evaluate to a - * {@code File} object containing the GML data. If no such file reference - * exists the tests are skipped.
  2. - *
  3. Obtain the schema model from the test context. The suite attribute - * {@link org.opengis.cite.iso19136.SuiteAttribute#XSMODEL model} should - * evaluate to an {@code XSModel} object representing the GML application - * schema.
  4. - *
- * - * @param testContext - * The test (group) context. - */ -// @BeforeClass(alwaysRun = true) -// public void initDataFixture(ITestContext testContext) { -// Assert.assertTrue( -// testContext.getSuite().getAttributeNames() -// .contains(SuiteAttribute.XML.getName()), -// "No data to validate."); -// this.dataFile = (File) testContext.getSuite().getAttribute( -// SuiteAttribute.XML.getName()); -// this.model = (XSModel) testContext.getSuite().getAttribute( -// SuiteAttribute.XSMODEL.getName()); -// -// Object obj = testContext.getSuite().getAttribute( -// SuiteAttribute.TEST_SUBJECT.getName()); -// if ((null != obj) && Document.class.isAssignableFrom(obj.getClass())) { -// this.testSubject = Document.class.cast(obj); -// } -// } - - /** - * Sets the data file. This is a convenience method intended to facilitate - * unit testing. - * - * @param dataFile - * A File containing the data to be validated. - */ - public void setDataFile(File dataFile) { - this.dataFile = dataFile; - } - - /** - * Sets the schema model (for unit testing purposes). - * - * @param xsModel - * An XSModel object representing a GML application schema. - */ - public void setSchemaModel(XSModel xsModel) { - this.model = xsModel; - } - - /** - * Generates an XPath expression to find all instances of the given elements - * in the data being validated. The supplied namespace bindings will be - * supplemented if necessary. - * - * @param elemNames - * A list of qualified names corresponding to element - * declarations. - * @param namespaceBindings - * A collection of namespace bindings required to evaluate the - * XPath expression, where each entry maps a namespace URI (key) - * to a prefix (value). - * @return An XPath (1.0) expression. - */ - public String generateXPathExpression(List elemNames, - Map namespaceBindings) { - StringBuilder xpath = new StringBuilder(); - ListIterator itr = elemNames.listIterator(); - while (itr.hasNext()) { - QName qName = itr.next(); - String namespace = qName.getNamespaceURI(); - String prefix = namespaceBindings.get(namespace); - if (null == prefix) { - prefix = (namespace.equals(Namespaces.SWE)) ? "swe" : "ns" - + itr.previousIndex(); - namespaceBindings.put(namespace, prefix); - } - xpath.append("//").append(prefix).append(":"); - xpath.append(qName.getLocalPart()); - if (itr.hasNext()) - xpath.append(" | "); // union operator - } - return xpath.toString(); - } + + /** + *

+ * obtainTestSubject. + *

+ * @param testContext a {@link org.testng.ITestContext} object + */ + @BeforeClass(alwaysRun = true) + public void obtainTestSubject(ITestContext testContext) { + Assert.assertTrue(testContext.getSuite().getAttributeNames().contains(SuiteAttribute.XML.getName()), + "No data to validate."); + this.dataFile = (File) testContext.getSuite().getAttribute(SuiteAttribute.XML.getName()); + this.model = (XSModel) testContext.getSuite().getAttribute(SuiteAttribute.XSMODEL.getName()); + + Object obj = testContext.getSuite().getAttribute(SuiteAttribute.TEST_SUBJECT.getName()); + if ((null != obj) && Document.class.isAssignableFrom(obj.getClass())) { + this.testSubject = Document.class.cast(obj); + originalSubject = Document.class.cast(obj); + } + + Object uriObj = testContext.getSuite().getAttribute(SuiteAttribute.TEST_SUBJECT_URI.getName()); + if ((null != uriObj)) { + this.testSubjectUri = URI.class.cast(uriObj); + // System.out.println(this.testSubjectUri.toString()); + } + } + /** + * A configuration method ({@code BeforeClass}) that initializes the test fixture as + * follows: + *
    + *
  1. Obtain the GML data set from the test context. The suite attribute + * {@link org.opengis.cite.iso19136.SuiteAttribute#GML} should evaluate to a + * {@code File} object containing the GML data. If no such file reference exists the + * tests are skipped.
  2. + *
  3. Obtain the schema model from the test context. The suite attribute + * {@link org.opengis.cite.iso19136.SuiteAttribute#XSMODEL model} should evaluate to + * an {@code XSModel} object representing the GML application schema.
  4. + *
+ * @param testContext The test (group) context. + */ + // @BeforeClass(alwaysRun = true) + // public void initDataFixture(ITestContext testContext) { + // Assert.assertTrue( + // testContext.getSuite().getAttributeNames() + // .contains(SuiteAttribute.XML.getName()), + // "No data to validate."); + // this.dataFile = (File) testContext.getSuite().getAttribute( + // SuiteAttribute.XML.getName()); + // this.model = (XSModel) testContext.getSuite().getAttribute( + // SuiteAttribute.XSMODEL.getName()); + // + // Object obj = testContext.getSuite().getAttribute( + // SuiteAttribute.TEST_SUBJECT.getName()); + // if ((null != obj) && Document.class.isAssignableFrom(obj.getClass())) { + // this.testSubject = Document.class.cast(obj); + // } + // } + + /** + * Sets the data file. This is a convenience method intended to facilitate unit + * testing. + * @param dataFile A File containing the data to be validated. + */ + public void setDataFile(File dataFile) { + this.dataFile = dataFile; + } + + /** + * Sets the schema model (for unit testing purposes). + * @param xsModel An XSModel object representing a GML application schema. + */ + public void setSchemaModel(XSModel xsModel) { + this.model = xsModel; + } + + /** + * Generates an XPath expression to find all instances of the given elements in the + * data being validated. The supplied namespace bindings will be supplemented if + * necessary. + * @param elemNames A list of qualified names corresponding to element declarations. + * @param namespaceBindings A collection of namespace bindings required to evaluate + * the XPath expression, where each entry maps a namespace URI (key) to a prefix + * (value). + * @return An XPath (1.0) expression. + */ + public String generateXPathExpression(List elemNames, Map namespaceBindings) { + StringBuilder xpath = new StringBuilder(); + ListIterator itr = elemNames.listIterator(); + while (itr.hasNext()) { + QName qName = itr.next(); + String namespace = qName.getNamespaceURI(); + String prefix = namespaceBindings.get(namespace); + if (null == prefix) { + prefix = (namespace.equals(Namespaces.SWE)) ? "swe" : "ns" + itr.previousIndex(); + namespaceBindings.put(namespace, prefix); + } + xpath.append("//").append(prefix).append(":"); + xpath.append(qName.getLocalPart()); + if (itr.hasNext()) + xpath.append(" | "); // union operator + } + return xpath.toString(); + } + } diff --git a/src/main/java/org/opengis/cite/swecommon20/level1/GeneralEncodingRules.java b/src/main/java/org/opengis/cite/swecommon20/level1/GeneralEncodingRules.java index be85aa7..6c1dfd6 100755 --- a/src/main/java/org/opengis/cite/swecommon20/level1/GeneralEncodingRules.java +++ b/src/main/java/org/opengis/cite/swecommon20/level1/GeneralEncodingRules.java @@ -6,13 +6,24 @@ import org.opengis.cite.swecommon20.ETSAssert; import org.testng.annotations.Test; -public class GeneralEncodingRules extends DataFixture{ - - @Test(groups = "GeneralEncodingRules", dependsOnGroups = { "SimpleComponents" }, description="Conformance Test Class A.14") +/** + *

+ * GeneralEncodingRules class. + *

+ * + */ +public class GeneralEncodingRules extends DataFixture { + + /** + *

+ * checkGeneralEncodingRulesSchematron. + *

+ */ + @Test(groups = "GeneralEncodingRules", dependsOnGroups = { "SimpleComponents" }, + description = "Conformance Test Class A.14") public void checkGeneralEncodingRulesSchematron() { - URL schRef = this.getClass().getResource( - "/org/opengis/cite/swecommon20/sch/A.14.GeneralEncodingRules.sch"); - ETSAssert - .assertSchematronValid(schRef, new StreamSource(this.dataFile)); + URL schRef = this.getClass().getResource("/org/opengis/cite/swecommon20/sch/A.14.GeneralEncodingRules.sch"); + ETSAssert.assertSchematronValid(schRef, new StreamSource(this.dataFile)); } + } diff --git a/src/main/java/org/opengis/cite/swecommon20/level1/RecordComponents.java b/src/main/java/org/opengis/cite/swecommon20/level1/RecordComponents.java index 6080059..1d80afc 100755 --- a/src/main/java/org/opengis/cite/swecommon20/level1/RecordComponents.java +++ b/src/main/java/org/opengis/cite/swecommon20/level1/RecordComponents.java @@ -7,16 +7,27 @@ import org.testng.SkipException; import org.testng.annotations.Test; -public class RecordComponents extends DataFixture{ - - @Test(groups = "RecordComponents", dependsOnGroups = { "SimpleComponents" }, description="A.3 classes modeling record style component types that can be nested to build complex structures from the simple component types") +/** + *

+ * RecordComponents class. + *

+ * + */ +public class RecordComponents extends DataFixture { + + /** + *

+ * checkRecordComponentsSchematron. + *

+ */ + @Test(groups = "RecordComponents", dependsOnGroups = { "SimpleComponents" }, + description = "A.3 classes modeling record style component types that can be nested to build complex structures from the simple component types") public void checkRecordComponentsSchematron() { String hasResult = this.CheckXPath2("boolean(//swe:DataRecord or //swe:Vector)"); if (hasResult.equals("false")) throw new SkipException("No record components found."); - URL schRef = this.getClass().getResource( - "/org/opengis/cite/swecommon20/sch/A.3.RecordComponents.sch"); - ETSAssert - .assertSchematronValid(schRef, new StreamSource(this.dataFile)); - } + URL schRef = this.getClass().getResource("/org/opengis/cite/swecommon20/sch/A.3.RecordComponents.sch"); + ETSAssert.assertSchematronValid(schRef, new StreamSource(this.dataFile)); + } + } diff --git a/src/main/java/org/opengis/cite/swecommon20/level1/SimpleComponents.java b/src/main/java/org/opengis/cite/swecommon20/level1/SimpleComponents.java index 4439351..1e811fd 100755 --- a/src/main/java/org/opengis/cite/swecommon20/level1/SimpleComponents.java +++ b/src/main/java/org/opengis/cite/swecommon20/level1/SimpleComponents.java @@ -5,14 +5,24 @@ import org.opengis.cite.swecommon20.ETSAssert; import org.testng.annotations.Test; -public class SimpleComponents extends DataFixture{ - - @Test(groups = "SimpleComponents", dependsOnGroups = { "CoreConcepts" }, description="A.2 test conformance of software and encoding models implementing the conceptual models defined in Requirements Class: Basic Types and Simple Components Packages..") +/** + *

+ * SimpleComponents class. + *

+ * + */ +public class SimpleComponents extends DataFixture { + + /** + *

+ * checkSimpleComponentsSchematron. + *

+ */ + @Test(groups = "SimpleComponents", dependsOnGroups = { "CoreConcepts" }, + description = "A.2 test conformance of software and encoding models implementing the conceptual models defined in Requirements Class: Basic Types and Simple Components Packages..") public void checkSimpleComponentsSchematron() { - URL schRef = this.getClass().getResource( - "/org/opengis/cite/swecommon20/sch/A.2.BasicType_SimpleComponent.sch"); - ETSAssert - .assertSchematronValid(schRef, new StreamSource(this.dataFile)); + URL schRef = this.getClass().getResource("/org/opengis/cite/swecommon20/sch/A.2.BasicType_SimpleComponent.sch"); + ETSAssert.assertSchematronValid(schRef, new StreamSource(this.dataFile)); } - + } diff --git a/src/main/java/org/opengis/cite/swecommon20/level1/SimpleComponentsSchemas.java b/src/main/java/org/opengis/cite/swecommon20/level1/SimpleComponentsSchemas.java index 99c8fa6..4fc644d 100755 --- a/src/main/java/org/opengis/cite/swecommon20/level1/SimpleComponentsSchemas.java +++ b/src/main/java/org/opengis/cite/swecommon20/level1/SimpleComponentsSchemas.java @@ -5,14 +5,25 @@ import org.opengis.cite.swecommon20.ETSAssert; import org.testng.annotations.Test; -public class SimpleComponentsSchemas extends DataFixture{ - - @Test(groups = "SimpleComponentsSchemas", dependsOnGroups = { "SimpleComponents" }, description="A.8 his conformance test class and in the following shall be used to check conformance of XML instances created according to the schemas defined in this standard. They shall also be used to check conformance of software implementations that output XML instances") +/** + *

+ * SimpleComponentsSchemas class. + *

+ * + */ +public class SimpleComponentsSchemas extends DataFixture { + + /** + *

+ * checkSimpleComponentsSchemasSchematron. + *

+ */ + @Test(groups = "SimpleComponentsSchemas", dependsOnGroups = { "SimpleComponents" }, + description = "A.8 his conformance test class and in the following shall be used to check conformance of XML instances created according to the schemas defined in this standard. They shall also be used to check conformance of software implementations that output XML instances") public void checkSimpleComponentsSchemasSchematron() { - URL schRef = this.getClass().getResource( - "/org/opengis/cite/swecommon20/sch/A.8.BasicTypesAndSimpleComponents.sch"); - ETSAssert - .assertSchematronValid(schRef, new StreamSource(this.dataFile)); + URL schRef = this.getClass() + .getResource("/org/opengis/cite/swecommon20/sch/A.8.BasicTypesAndSimpleComponents.sch"); + ETSAssert.assertSchematronValid(schRef, new StreamSource(this.dataFile)); } - + } diff --git a/src/main/java/org/opengis/cite/swecommon20/level1/SimpleEncodings.java b/src/main/java/org/opengis/cite/swecommon20/level1/SimpleEncodings.java index 9ee97c8..09dd6dc 100755 --- a/src/main/java/org/opengis/cite/swecommon20/level1/SimpleEncodings.java +++ b/src/main/java/org/opengis/cite/swecommon20/level1/SimpleEncodings.java @@ -6,13 +6,24 @@ import org.opengis.cite.swecommon20.ETSAssert; import org.testng.annotations.Test; -public class SimpleEncodings extends DataFixture{ - - @Test(groups = "SimpleEncodings", dependsOnGroups = { "SimpleComponents" }, description="A.6 provide definitions of simple encoding methods. They are used as descriptors of the method used to encode data component values wrapped by aggregate classes defined in the 'Block Components' package.") +/** + *

+ * SimpleEncodings class. + *

+ * + */ +public class SimpleEncodings extends DataFixture { + + /** + *

+ * checkSimpleEncodingsSchematron. + *

+ */ + @Test(groups = "SimpleEncodings", dependsOnGroups = { "SimpleComponents" }, + description = "A.6 provide definitions of simple encoding methods. They are used as descriptors of the method used to encode data component values wrapped by aggregate classes defined in the 'Block Components' package.") public void checkSimpleEncodingsSchematron() { - URL schRef = this.getClass().getResource( - "/org/opengis/cite/swecommon20/sch/A.6.SimpleEncodings.sch"); - ETSAssert - .assertSchematronValid(schRef, new StreamSource(this.dataFile)); + URL schRef = this.getClass().getResource("/org/opengis/cite/swecommon20/sch/A.6.SimpleEncodings.sch"); + ETSAssert.assertSchematronValid(schRef, new StreamSource(this.dataFile)); } + } diff --git a/src/main/java/org/opengis/cite/swecommon20/level1/package-info.java b/src/main/java/org/opengis/cite/swecommon20/level1/package-info.java index cd34493..93ef39d 100755 --- a/src/main/java/org/opengis/cite/swecommon20/level1/package-info.java +++ b/src/main/java/org/opengis/cite/swecommon20/level1/package-info.java @@ -1,14 +1,13 @@ /** - * Conformance Level 1 includes basic facilities. The following capabilities - * must be supported: + * Conformance Level 1 includes basic facilities. The following capabilities must be + * supported: *
    *
  • Capability 1.1
  • *
  • Capability 1.2
  • - *
  • Capability 1.3
  • + *
  • Capability 1.3
  • *
* - * @see HTML5 + * @see HTML5 * - Conformance classes */ package org.opengis.cite.swecommon20.level1; diff --git a/src/main/java/org/opengis/cite/swecommon20/level2/package-info.java b/src/main/java/org/opengis/cite/swecommon20/level2/package-info.java index c7cd028..720fc56 100755 --- a/src/main/java/org/opengis/cite/swecommon20/level2/package-info.java +++ b/src/main/java/org/opengis/cite/swecommon20/level2/package-info.java @@ -1,13 +1,12 @@ /** - * Conformance Level 2 extends Level 1. The following additional capabilities - * are required: - *
    + * Conformance Level 2 extends Level 1. The following additional capabilities are + * required: + *
      *
    • Capability 2.1
    • *
    • Capability 2.2
    • *
    * - * @see HTML5 + * @see HTML5 * - Conformance classes */ package org.opengis.cite.swecommon20.level2; diff --git a/src/main/java/org/opengis/cite/swecommon20/package-info.java b/src/main/java/org/opengis/cite/swecommon20/package-info.java index 5caf9ca..5e0407f 100755 --- a/src/main/java/org/opengis/cite/swecommon20/package-info.java +++ b/src/main/java/org/opengis/cite/swecommon20/package-info.java @@ -1,8 +1,9 @@ /** - * The root package includes supporting classes of general utility such as the - * main controller, listeners, and reporters. + * The root package includes supporting classes of general utility such as the main + * controller, listeners, and reporters. * - *

    Subsidiary packages correspond to distinct test groups such as conformance - * classes.

    + *

    + * Subsidiary packages correspond to distinct test groups such as conformance classes. + *

    */ -package org.opengis.cite.swecommon20; \ No newline at end of file +package org.opengis.cite.swecommon20; \ No newline at end of file diff --git a/src/main/java/org/opengis/cite/swecommon20/util/ClientUtils.java b/src/main/java/org/opengis/cite/swecommon20/util/ClientUtils.java new file mode 100644 index 0000000..abf4dec --- /dev/null +++ b/src/main/java/org/opengis/cite/swecommon20/util/ClientUtils.java @@ -0,0 +1,131 @@ +package org.opengis.cite.swecommon20.util; + +import java.io.IOException; +import java.io.InputStream; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.client.JerseyClientBuilder; +import org.glassfish.jersey.logging.LoggingFeature; +import org.opengis.cite.swecommon20.ReusableEntityFilter; +import org.w3c.dom.Document; + +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.core.Response; + +/** + * Provides various utility methods for creating and configuring HTTP client components. + */ +public class ClientUtils { + + /** + * Builds a client component for interacting with HTTP endpoints. The client will + * automatically redirect to the URI declared in 3xx responses. The connection timeout + * is 10 s. Request and response messages may be logged to a JDK logger (in the + * namespace "com.sun.jersey.api.client"). + * @return A Client component. + */ + public static Client buildClient() { + ClientConfig config = new ClientConfig(); + config.property(ClientProperties.FOLLOW_REDIRECTS, true); + config.property(ClientProperties.CONNECT_TIMEOUT, 10000); + config.register(new LoggingFeature()); // TODO: verify if this works + Client client = JerseyClientBuilder.newClient(config); + client.register(new ReusableEntityFilter()); + return client; + } + + /** + * Obtains the (XML) response entity as a JAXP Source object and resets the entity + * input stream for subsequent reads. + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @param response A representation of an HTTP response message. + * @param targetURI The target URI from which the entity was retrieved (may be null). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + */ + public static Source getResponseEntityAsSource(Response response, String targetURI) { + Source source = response.readEntity(DOMSource.class); + if (null != targetURI && !targetURI.isEmpty()) { + source.setSystemId(targetURI); + } + if (response.readEntity(InputStream.class).markSupported()) { + try { + // NOTE: entity was buffered by client filter + response.readEntity(InputStream.class).reset(); + } + catch (IOException ex) { + Logger.getLogger(ClientUtils.class.getName()) + .log(Level.WARNING, "Failed to reset response entity.", ex); + } + } + return source; + } + + /** + * Obtains the (XML) response entity as a DOM Document and resets the entity input + * stream for subsequent reads. + * @param response A representation of an HTTP response message. + * @param targetURI The target URI from which the entity was retrieved (may be null). + * @return A Document representing the entity; its base URI is set using the given + * targetURI value (this may be used to resolve any relative URIs found in the + * document). + */ + public static Document getResponseEntityAsDocument(Response response, String targetURI) { + DOMSource domSource = (DOMSource) getResponseEntityAsSource(response, targetURI); + Document entityDoc = (Document) domSource.getNode(); + entityDoc.setDocumentURI(domSource.getSystemId()); + return entityDoc; + } + +} diff --git a/src/main/java/org/opengis/cite/swecommon20/util/NamespaceBindings.java b/src/main/java/org/opengis/cite/swecommon20/util/NamespaceBindings.java index 8367e0e..a069ee9 100755 --- a/src/main/java/org/opengis/cite/swecommon20/util/NamespaceBindings.java +++ b/src/main/java/org/opengis/cite/swecommon20/util/NamespaceBindings.java @@ -9,107 +9,108 @@ import org.opengis.cite.swecommon20.Namespaces; /** - * Provides namespace bindings for evaluating XPath 1.0 expressions using the - * JAXP XPath API. A namespace name (URI) may be bound to only one prefix. + * Provides namespace bindings for evaluating XPath 1.0 expressions using the JAXP XPath + * API. A namespace name (URI) may be bound to only one prefix. */ public class NamespaceBindings implements NamespaceContext { - private Map bindings = new HashMap(); + private Map bindings = new HashMap(); - @Override - public String getNamespaceURI(String prefix) { - String nsName = null; - for (Map.Entry binding : bindings.entrySet()) { - if (binding.getValue().equals(prefix)) { - nsName = binding.getKey(); - break; - } - } - return nsName; - } + /** {@inheritDoc} */ + @Override + public String getNamespaceURI(String prefix) { + String nsName = null; + for (Map.Entry binding : bindings.entrySet()) { + if (binding.getValue().equals(prefix)) { + nsName = binding.getKey(); + break; + } + } + return nsName; + } - @Override - public String getPrefix(String namespaceURI) { - return bindings.get(namespaceURI); - } + /** {@inheritDoc} */ + @Override + public String getPrefix(String namespaceURI) { + return bindings.get(namespaceURI); + } - @Override - public Iterator getPrefixes(String namespaceURI) { - return Arrays.asList(getPrefix(namespaceURI)).iterator(); - } + /** {@inheritDoc} */ + @Override + public Iterator getPrefixes(String namespaceURI) { + return Arrays.asList(getPrefix(namespaceURI)).iterator(); + } - /** - * Adds a namespace binding that associates a namespace name with a prefix. - * If a binding for a given namespace name already exists it will be - * replaced. - * - * @param namespaceURI - * A String denoting a namespace name (an absolute URI value). - * @param prefix - * A prefix associated with the namespace name. - */ - public void addNamespaceBinding(String namespaceURI, String prefix) { - bindings.put(namespaceURI, prefix); - } + /** + * Adds a namespace binding that associates a namespace name with a prefix. If a + * binding for a given namespace name already exists it will be replaced. + * @param namespaceURI A String denoting a namespace name (an absolute URI value). + * @param prefix A prefix associated with the namespace name. + */ + public void addNamespaceBinding(String namespaceURI, String prefix) { + bindings.put(namespaceURI, prefix); + } - /** - * Adds all of the supplied namespace bindings to the existing set of - * entries. - * - * @param nsBindings - * A Map containing a collection of namespace bindings where the - * key is an absolute URI specifying the namespace name and the - * value denotes the associated prefix. - */ - public void addAllBindings(Map nsBindings) { - if (null != nsBindings) - bindings.putAll(nsBindings); - } + /** + * Adds all of the supplied namespace bindings to the existing set of entries. + * @param nsBindings A Map containing a collection of namespace bindings where the key + * is an absolute URI specifying the namespace name and the value denotes the + * associated prefix. + */ + public void addAllBindings(Map nsBindings) { + if (null != nsBindings) + bindings.putAll(nsBindings); + } - /** - * Returns an unmodifiable view of the declared namespace bindings. - * - * @return An immutable Map containing zero or more namespace bindings where - * the key is an absolute URI specifying the namespace name and the - * value is the associated prefix. - */ - public Map getAllBindings() { - return Collections.unmodifiableMap(this.bindings); - } + /** + * Returns an unmodifiable view of the declared namespace bindings. + * @return An immutable Map containing zero or more namespace bindings where the key + * is an absolute URI specifying the namespace name and the value is the associated + * prefix. + */ + public Map getAllBindings() { + return Collections.unmodifiableMap(this.bindings); + } - /** - * Creates a NamespaceBindings object that declares the following namespace - * bindings: - * - *
      - *
    • ows: {@value org.opengis.cite.swecommon20.Namespaces#OWS}
    • - *
    • xlink: {@value org.opengis.cite.swecommon20.Namespaces#XLINK}
    • - *
    • gml: {@value org.opengis.cite.swecommon20.Namespaces#GML}
    • - *
    - * - * @return A NamespaceBindings object. - */ - public static NamespaceBindings withStandardBindings() { - NamespaceBindings nsBindings = new NamespaceBindings(); - nsBindings.addAllBindings(getStandardBindings()); - return nsBindings; - } - - public static Map getStandardBindings() { - Map nsBindings = new HashMap(); - nsBindings.put(Namespaces.OWS, "ows"); - nsBindings.put(Namespaces.XLINK, "xlink"); - nsBindings.put(Namespaces.GML, "gml"); - //nsBindings.put(Namespaces.OM, "om"); - nsBindings.put(Namespaces.SWE, "swe"); -// nsBindings.put(Namespaces.SAMS, "sams"); -// nsBindings.put(Namespaces.SAM, "sam"); -// nsBindings.put(Namespaces.SPEC, "spec"); - return nsBindings; - } + /** + * Creates a NamespaceBindings object that declares the following namespace bindings: + * + *
      + *
    • ows: {@value org.opengis.cite.swecommon20.Namespaces#OWS}
    • + *
    • xlink: {@value org.opengis.cite.swecommon20.Namespaces#XLINK}
    • + *
    • gml: {@value org.opengis.cite.swecommon20.Namespaces#GML}
    • + *
    + * @return A NamespaceBindings object. + */ + public static NamespaceBindings withStandardBindings() { + NamespaceBindings nsBindings = new NamespaceBindings(); + nsBindings.addAllBindings(getStandardBindings()); + return nsBindings; + } + + /** + *

    + * getStandardBindings. + *

    + * @return a {@link java.util.Map} object + */ + public static Map getStandardBindings() { + Map nsBindings = new HashMap(); + nsBindings.put(Namespaces.OWS, "ows"); + nsBindings.put(Namespaces.XLINK, "xlink"); + nsBindings.put(Namespaces.GML, "gml"); + // nsBindings.put(Namespaces.OM, "om"); + nsBindings.put(Namespaces.SWE, "swe"); + // nsBindings.put(Namespaces.SAMS, "sams"); + // nsBindings.put(Namespaces.SAM, "sam"); + // nsBindings.put(Namespaces.SPEC, "spec"); + return nsBindings; + } + + /** {@inheritDoc} */ + @Override + public String toString() { + return "NamespaceBindings:\n" + bindings; + } - @Override - public String toString() { - return "NamespaceBindings:\n" + bindings; - } } diff --git a/src/main/java/org/opengis/cite/swecommon20/util/TestSuiteLogger.java b/src/main/java/org/opengis/cite/swecommon20/util/TestSuiteLogger.java index 5d3232b..213753b 100755 --- a/src/main/java/org/opengis/cite/swecommon20/util/TestSuiteLogger.java +++ b/src/main/java/org/opengis/cite/swecommon20/util/TestSuiteLogger.java @@ -4,70 +4,65 @@ import java.util.logging.Logger; /** - * Logging utility class that provides simple access to the JDK Logging API. Set - * the "java.util.logging.config.file" system property to specify the location - * of the desired logging configuration file. A sample configuration file is - * available at {@code src/main/config/logging.properties}. + * Logging utility class that provides simple access to the JDK Logging API. Set the + * "java.util.logging.config.file" system property to specify the location of the desired + * logging configuration file. A sample configuration file is available at + * {@code src/main/config/logging.properties}. * * @see java.util.logging.LogManager LogManager */ public class TestSuiteLogger { - private static final Logger LOGR = - Logger.getLogger(TestSuiteLogger.class.getPackage().getName()); + private static final Logger LOGR = Logger.getLogger(TestSuiteLogger.class.getPackage().getName()); - /** - * Logs a message at the specified logging level with the given message - * parameters. - * - * @param level The logging {@link Level level}. - * @param message A String representing the content of the log message. - * @param params An array of message parameters. - */ - public static void log(Level level, String message, Object[] params) { - if (LOGR.isLoggable(level)) { - LOGR.log(level, message, params); - } - } + /** + * Logs a message at the specified logging level with the given message parameters. + * @param level The logging {@link Level level}. + * @param message A String representing the content of the log message. + * @param params An array of message parameters. + */ + public static void log(Level level, String message, Object[] params) { + if (LOGR.isLoggable(level)) { + LOGR.log(level, message, params); + } + } - /** - * Logs a message at the specified logging level with the given Exception - * object that represents a noteworthy error condition. - * - * @param level The logging {@link Level level}. - * @param message A String representing the content of the log message. - * @param except An object that indicates an exceptional situation. - */ - public static void log(Level level, String message, Exception except) { - if (LOGR.isLoggable(level)) { - LOGR.log(level, message, except); - } - } + /** + * Logs a message at the specified logging level with the given Exception object that + * represents a noteworthy error condition. + * @param level The logging {@link Level level}. + * @param message A String representing the content of the log message. + * @param except An object that indicates an exceptional situation. + */ + public static void log(Level level, String message, Exception except) { + if (LOGR.isLoggable(level)) { + LOGR.log(level, message, except); + } + } - /** - * Logs a simple message at the specified logging level. - * - * @param level The logging {@link Level level}. - * @param message A String representing the content of the log message. - */ - public static void log(Level level, String message) { - if (LOGR.isLoggable(level)) { - LOGR.log(level, message); - } - } + /** + * Logs a simple message at the specified logging level. + * @param level The logging {@link Level level}. + * @param message A String representing the content of the log message. + */ + public static void log(Level level, String message) { + if (LOGR.isLoggable(level)) { + LOGR.log(level, message); + } + } - /** - * Indicates if the logger is enabled at a given logging level. Message - * levels lower than this value will be discarded. - * - * @param level The logging {@link Level level}. - * @return true if the logger is currently enabled for this logging level; - * false otherwise. - */ - public static boolean isLoggable(Level level) { - return LOGR.isLoggable(level); - } + /** + * Indicates if the logger is enabled at a given logging level. Message levels lower + * than this value will be discarded. + * @param level The logging {@link Level level}. + * @return true if the logger is currently enabled for this logging level; false + * otherwise. + */ + public static boolean isLoggable(Level level) { + return LOGR.isLoggable(level); + } + + private TestSuiteLogger() { + } - private TestSuiteLogger() { - } } diff --git a/src/main/java/org/opengis/cite/swecommon20/util/URIUtils.java b/src/main/java/org/opengis/cite/swecommon20/util/URIUtils.java index 5858f07..cb904f8 100755 --- a/src/main/java/org/opengis/cite/swecommon20/util/URIUtils.java +++ b/src/main/java/org/opengis/cite/swecommon20/util/URIUtils.java @@ -8,7 +8,6 @@ import java.net.URI; import java.util.logging.Level; -import javax.ws.rs.core.HttpHeaders; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -16,155 +15,151 @@ import org.w3c.dom.Document; import org.xml.sax.SAXException; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.Invocation.Builder; +import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.Response; /** - * Provides a collection of utility methods for manipulating or resolving URI - * references. + * Provides a collection of utility methods for manipulating or resolving URI references. */ public class URIUtils { - private static final String FIXUP_BASE_URI = "http://apache.org/xml/features/xinclude/fixup-base-uris"; + private static final String FIXUP_BASE_URI = "http://apache.org/xml/features/xinclude/fixup-base-uris"; - /** - * Parses the content of the given URI as an XML document and returns a new - * DOM Document object. Entity reference nodes will not be expanded. XML - * inclusions (xi:include elements) will be processed if present. - * - * @param uriRef - * An absolute URI specifying the location of an XML resource. - * @return A DOM Document node representing an XML resource. - * @throws SAXException - * If the resource cannot be parsed. - * @throws IOException - * If the resource is not accessible. - */ - public static Document parseURI(URI uriRef) throws SAXException, - IOException { - if ((null == uriRef) || !uriRef.isAbsolute()) { - throw new IllegalArgumentException( - "Absolute URI is required, but received " + uriRef); - } - DocumentBuilderFactory docFactory = DocumentBuilderFactory - .newInstance(); - docFactory.setNamespaceAware(true); - docFactory.setExpandEntityReferences(false); - docFactory.setXIncludeAware(true); - Document doc = null; - try { - // XInclude processor will not add xml:base attributes - docFactory.setFeature(FIXUP_BASE_URI, false); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - doc = docBuilder.parse(uriRef.toString()); - } catch (ParserConfigurationException x) { - TestSuiteLogger.log(Level.WARNING, - "Failed to create DocumentBuilder." + x); - } - if (null != doc) { - doc.setDocumentURI(uriRef.toString()); - } - return doc; - } + /** + * Parses the content of the given URI as an XML document and returns a new DOM + * Document object. Entity reference nodes will not be expanded. XML inclusions + * (xi:include elements) will be processed if present. + * @param uriRef An absolute URI specifying the location of an XML resource. + * @return A DOM Document node representing an XML resource. + * @throws org.xml.sax.SAXException If the resource cannot be parsed. + * @throws java.io.IOException If the resource is not accessible. + */ + public static Document parseURI(URI uriRef) throws SAXException, IOException { + if ((null == uriRef) || !uriRef.isAbsolute()) { + throw new IllegalArgumentException("Absolute URI is required, but received " + uriRef); + } + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setNamespaceAware(true); + docFactory.setExpandEntityReferences(false); + docFactory.setXIncludeAware(true); + Document doc = null; + try { + // XInclude processor will not add xml:base attributes + docFactory.setFeature(FIXUP_BASE_URI, false); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + doc = docBuilder.parse(uriRef.toString()); + } + catch (ParserConfigurationException x) { + TestSuiteLogger.log(Level.WARNING, "Failed to create DocumentBuilder." + x); + } + if (null != doc) { + doc.setDocumentURI(uriRef.toString()); + } + return doc; + } - /** - * Dereferences the given URI and stores the resulting resource - * representation in a local file. The file will be located in the default - * temporary file directory. - * - * @param uriRef - * An absolute URI specifying the location of some resource. - * @return A File containing the content of the resource; it may be empty if - * resolution failed for any reason. - * @throws IOException - * If an IO error occurred. - */ - public static File dereferenceURI(URI uriRef) throws IOException { - if ((null == uriRef) || !uriRef.isAbsolute()) { - throw new IllegalArgumentException( - "Absolute URI is required, but received " + uriRef); - } - if (uriRef.getScheme().equalsIgnoreCase("file")) { - return new File(uriRef); - } + /** + * Dereferences the given URI and stores the resulting resource representation in a + * local file. The file will be located in the default temporary file directory. + * @param uriRef An absolute URI specifying the location of some resource. + * @return A File containing the content of the resource; it may be empty if + * resolution failed for any reason. + * @throws java.io.IOException If an IO error occurred. + */ + public static File dereferenceURI(URI uriRef) throws IOException { + if ((null == uriRef) || !uriRef.isAbsolute()) { + throw new IllegalArgumentException("Absolute URI is required, but received " + uriRef); + } + if (uriRef.getScheme().equalsIgnoreCase("file")) { + return new File(uriRef); + } + Client client = ClientUtils.buildClient(); + WebTarget target = client.target(uriRef); + Builder builder = target.request(); + Response rsp = builder.buildGet().invoke(); + String suffix = null; + if (rsp.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE).toString().endsWith("xml")) { + suffix = ".xml"; + } + File destFile = File.createTempFile("entity-", suffix); + if (rsp.hasEntity()) { + Object entity = rsp.getEntity(); + if (!(entity instanceof InputStream)) { + return null; + } + InputStream is = (InputStream) entity; + OutputStream os = new FileOutputStream(destFile); + byte[] buffer = new byte[8 * 1024]; + int bytesRead; + while ((bytesRead = is.read(buffer)) != -1) { + os.write(buffer, 0, bytesRead); + } + is.close(); + os.flush(); + os.close(); + } + TestSuiteLogger.log(Level.FINE, + "Wrote " + destFile.length() + " bytes to file at " + destFile.getAbsolutePath()); + return destFile; + } - Client client = Client.create(); - WebResource webRes = client.resource(uriRef); - ClientResponse rsp = webRes.get(ClientResponse.class); + /** + * Constructs an absolute URI from the given URI reference and a base URI. + * + * @see RFC 3986, 5.2 + * @param baseURI The base URI; if present, it must be an absolute URI. + * @param uriRef A URI reference that may be relative to the given base URI. + * @return The resulting URI. + */ + public static URI resolveRelativeURI(String baseURI, String uriRef) { + URI uri = (null != baseURI) ? URI.create(baseURI) : URI.create(""); + if (null != baseURI && null == uri.getScheme()) { + throw new IllegalArgumentException("Base URI has no scheme component: " + baseURI); + } + return uri.resolve(uriRef); + } - String suffix = null; - if (rsp.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE).endsWith("xml")) { - suffix = ".xml"; - } - File destFile = File.createTempFile("entity-", suffix); - if (rsp.hasEntity()) { - InputStream is = rsp.getEntityInputStream(); - OutputStream os = new FileOutputStream(destFile); - byte[] buffer = new byte[8 * 1024]; - int bytesRead; - while ((bytesRead = is.read(buffer)) != -1) { - os.write(buffer, 0, bytesRead); - } - is.close(); - os.flush(); - os.close(); - } - TestSuiteLogger.log(Level.FINE, "Wrote " + destFile.length() - + " bytes to file at " + destFile.getAbsolutePath()); - return destFile; - } + /** + * Resolves the given URI and stores the resulting resource representation in a local + * file. The file will be located in the default temporary file directory. + * @param uriRef An absolute URI specifying the location of some resource. + * @return A File containing the content of the resource; it may be empty if + * resolution failed for any reason. + * @throws java.io.IOException If an IO error occurs. + */ + public static File resolveURIAsFile(URI uriRef) throws IOException { + if ((null == uriRef) || !uriRef.isAbsolute()) { + throw new IllegalArgumentException("Absolute URI is required, but received " + uriRef); + } + if (uriRef.getScheme().equalsIgnoreCase("file")) { + return new File(uriRef); + } + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(uriRef); + Response rsp = target.request().get(); + File destFile = File.createTempFile("entity-", ".xml"); + if (rsp.hasEntity()) { + Object entity = rsp.getEntity(); + if (entity instanceof InputStream) { + InputStream is = (InputStream) entity; + OutputStream os = new FileOutputStream(destFile); + byte[] buffer = new byte[8 * 1024]; + int bytesRead; + while ((bytesRead = is.read(buffer)) != -1) { + os.write(buffer, 0, bytesRead); + } + is.close(); + os.flush(); + os.close(); + } + } + TestSuiteLogger.log(Level.FINE, + "Wrote " + destFile.length() + " bytes to file at " + destFile.getAbsolutePath()); + return destFile; + } - /** - * Constructs an absolute URI from the given URI reference and a base URI. - * - * @see RFC 3986, - * 5.2 - * - * @param baseURI - * The base URI; if present, it must be an absolute URI. - * @param uriRef - * A URI reference that may be relative to the given base URI. - * @return The resulting URI. - * - */ - public static URI resolveRelativeURI(String baseURI, String uriRef) { - URI uri = (null != baseURI) ? URI.create(baseURI) : URI.create(""); - if (null != baseURI && null == uri.getScheme()) { - throw new IllegalArgumentException( - "Base URI has no scheme component: " + baseURI); - } - return uri.resolve(uriRef); - } - - public static File resolveURIAsFile(URI uriRef) throws IOException { - if ((null == uriRef) || !uriRef.isAbsolute()) { - throw new IllegalArgumentException( - "Absolute URI is required, but received " + uriRef); - } - if (uriRef.getScheme().equalsIgnoreCase("file")) { - return new File(uriRef); - } - - Client client = Client.create(); - WebResource webRes = client.resource(uriRef); - ClientResponse rsp = webRes.get(ClientResponse.class); - - File destFile = File.createTempFile("entity-", ".xml"); - if (rsp.hasEntity()) { - InputStream is = rsp.getEntityInputStream(); - OutputStream os = new FileOutputStream(destFile); - byte[] buffer = new byte[8 * 1024]; - int bytesRead; - while ((bytesRead = is.read(buffer)) != -1) { - os.write(buffer, 0, bytesRead); - } - is.close(); - os.flush(); - os.close(); - } - TestSuiteLogger.log(Level.FINE, "Wrote " + destFile.length() - + " bytes to file at " + destFile.getAbsolutePath()); - return destFile; - } } diff --git a/src/main/java/org/opengis/cite/swecommon20/util/ValidationUtils.java b/src/main/java/org/opengis/cite/swecommon20/util/ValidationUtils.java index 0b2a1de..6348042 100755 --- a/src/main/java/org/opengis/cite/swecommon20/util/ValidationUtils.java +++ b/src/main/java/org/opengis/cite/swecommon20/util/ValidationUtils.java @@ -25,138 +25,120 @@ import org.w3c.dom.ls.LSResourceResolver; /** - * A utility class that provides convenience methods to support schema - * validation. + * A utility class that provides convenience methods to support schema validation. */ public class ValidationUtils { - static final String ROOT_PKG = "/org/opengis/cite/swecommon20/"; - private static final XMLCatalogResolver SCH_RESOLVER = initCatalogResolver(); + static final String ROOT_PKG = "/org/opengis/cite/swecommon20/"; - private static XMLCatalogResolver initCatalogResolver() { - return (XMLCatalogResolver) createSchemaResolver(Namespaces.SCH); - } + private static final XMLCatalogResolver SCH_RESOLVER = initCatalogResolver(); - /** - * Creates a resource resolver suitable for locating schemas using an entity - * catalog. In effect, local copies of standard schemas are returned instead - * of retrieving them from external repositories. - * - * @param schemaLanguage - * A URI that identifies a schema language by namespace name. - * @return A {@code LSResourceResolver} object that is configured to use an - * OASIS entity catalog. - */ - public static LSResourceResolver createSchemaResolver(URI schemaLanguage) { - String catalogFileName; - if (schemaLanguage.equals(Namespaces.XSD)) { - catalogFileName = "schema-catalog.xml"; - } else { - catalogFileName = "schematron-catalog.xml"; - } - URL catalogURL = ValidationUtils.class.getResource(ROOT_PKG - + catalogFileName); - XMLCatalogResolver resolver = new XMLCatalogResolver(); - resolver.setCatalogList(new String[] { catalogURL.toString() }); - return resolver; - } + private static XMLCatalogResolver initCatalogResolver() { + return (XMLCatalogResolver) createSchemaResolver(Namespaces.SCH); + } - /** - * Constructs a SchematronValidator that will check an XML resource against - * the rules defined in a Schematron schema. An attempt is made to resolve - * the schema reference using an entity catalog; if this fails the reference - * is used as given. - * - * @param schemaRef - * A reference to a Schematron schema; this is expected to be a - * relative or absolute URI value, possibly matching the system - * identifier for some entry in an entity catalog. - * @param phase - * The name of the phase to invoke. - * @return A SchematronValidator instance, or {@code null} if the validator - * cannot be constructed (e.g. invalid schema reference or phase - * name). - */ - public static SchematronValidator buildSchematronValidator( - String schemaRef, String phase) { - Source source = null; - try { - String catalogRef = SCH_RESOLVER - .resolveSystem(schemaRef.toString()); - if (null != catalogRef) { - source = new StreamSource(URI.create(catalogRef).toString()); - } else { - source = new StreamSource(schemaRef); - } - } catch (IOException x) { - TestSuiteLogger.log(Level.WARNING, - "Error reading Schematron schema catalog.", x); - } - SchematronValidator validator = null; - try { - validator = new SchematronValidator(source, phase); - } catch (Exception e) { - TestSuiteLogger.log(Level.WARNING, - "Error creating Schematron validator.", e); - } - return validator; - } + /** + * Creates a resource resolver suitable for locating schemas using an entity catalog. + * In effect, local copies of standard schemas are returned instead of retrieving them + * from external repositories. + * @param schemaLanguage A URI that identifies a schema language by namespace name. + * @return A {@code LSResourceResolver} object that is configured to use an OASIS + * entity catalog. + */ + public static LSResourceResolver createSchemaResolver(URI schemaLanguage) { + String catalogFileName; + if (schemaLanguage.equals(Namespaces.XSD)) { + catalogFileName = "schema-catalog.xml"; + } + else { + catalogFileName = "schematron-catalog.xml"; + } + URL catalogURL = ValidationUtils.class.getResource(ROOT_PKG + catalogFileName); + XMLCatalogResolver resolver = new XMLCatalogResolver(); + resolver.setCatalogList(new String[] { catalogURL.toString() }); + return resolver; + } + + /** + * Constructs a SchematronValidator that will check an XML resource against the rules + * defined in a Schematron schema. An attempt is made to resolve the schema reference + * using an entity catalog; if this fails the reference is used as given. + * @param schemaRef A reference to a Schematron schema; this is expected to be a + * relative or absolute URI value, possibly matching the system identifier for some + * entry in an entity catalog. + * @param phase The name of the phase to invoke. + * @return A SchematronValidator instance, or {@code null} if the validator cannot be + * constructed (e.g. invalid schema reference or phase name). + */ + public static SchematronValidator buildSchematronValidator(String schemaRef, String phase) { + Source source = null; + try { + String catalogRef = SCH_RESOLVER.resolveSystem(schemaRef.toString()); + if (null != catalogRef) { + source = new StreamSource(URI.create(catalogRef).toString()); + } + else { + source = new StreamSource(schemaRef); + } + } + catch (IOException x) { + TestSuiteLogger.log(Level.WARNING, "Error reading Schematron schema catalog.", x); + } + SchematronValidator validator = null; + try { + validator = new SchematronValidator(source, phase); + } + catch (Exception e) { + TestSuiteLogger.log(Level.WARNING, "Error creating Schematron validator.", e); + } + return validator; + } + + /** + * Extracts a set of XML Schema references from a source XML document. The document + * element is expected to include the standard xsi:schemaLocation attribute. + * @param source The source instance to read from; its base URI (systemId) should be + * set. + * @param baseURI An alternative base URI to use if the source does not have a system + * identifier set or if its system id is a {@code file} URI. This will usually be the + * URI used to retrieve the resource; it may be null. + * @return A Set containing absolute URI references that specify the locations of XML + * Schema resources. + * @throws javax.xml.stream.XMLStreamException If an error occurs while reading the + * source instance. + */ + public static Set extractSchemaReferences(Source source, String baseURI) throws XMLStreamException { + XMLInputFactory factory = XMLInputFactory.newInstance(); + XMLEventReader reader = factory.createXMLEventReader(source); + // advance to document element + StartElement docElem = reader.nextTag().asStartElement(); + Attribute schemaLoc = docElem + .getAttributeByName(new QName(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "schemaLocation")); + if (null == schemaLoc) { + throw new RuntimeException("No xsi:schemaLocation attribute found. See ISO 19136, A.3.1."); + } + String[] uriValues = schemaLoc.getValue().split("\\s+"); + if (uriValues.length % 2 != 0) { + throw new RuntimeException("xsi:schemaLocation attribute contains an odd number of URI values:\n" + + Arrays.toString(uriValues)); + } + Set schemaURIs = new HashSet(); + // one or more pairs of [namespace name] [schema location] + for (int i = 0; i < uriValues.length; i += 2) { + URI schemaURI = null; + if (!URI.create(uriValues[i + 1]).isAbsolute() && (null != source.getSystemId())) { + String schemaRef = URIUtils.resolveRelativeURI(source.getSystemId(), uriValues[i + 1]).toString(); + if (schemaRef.startsWith("file") && !new File(schemaRef).exists() && (null != baseURI)) { + schemaRef = URIUtils.resolveRelativeURI(baseURI, uriValues[i + 1]).toString(); + } + schemaURI = URI.create(schemaRef); + } + else { + schemaURI = URI.create(uriValues[i + 1]); + } + schemaURIs.add(schemaURI); + } + return schemaURIs; + } - /** - * Extracts a set of XML Schema references from a source XML document. The - * document element is expected to include the standard xsi:schemaLocation - * attribute. - * - * @param source - * The source instance to read from; its base URI (systemId) - * should be set. - * @param baseURI - * An alternative base URI to use if the source does not have a - * system identifier set or if its system id is a {@code file} - * URI. This will usually be the URI used to retrieve the - * resource; it may be null. - * @return A Set containing absolute URI references that specify the - * locations of XML Schema resources. - * @throws XMLStreamException - * If an error occurs while reading the source instance. - */ - public static Set extractSchemaReferences(Source source, String baseURI) - throws XMLStreamException { - XMLInputFactory factory = XMLInputFactory.newInstance(); - XMLEventReader reader = factory.createXMLEventReader(source); - // advance to document element - StartElement docElem = reader.nextTag().asStartElement(); - Attribute schemaLoc = docElem.getAttributeByName(new QName( - XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "schemaLocation")); - if (null == schemaLoc) { - throw new RuntimeException( - "No xsi:schemaLocation attribute found. See ISO 19136, A.3.1."); - } - String[] uriValues = schemaLoc.getValue().split("\\s+"); - if (uriValues.length % 2 != 0) { - throw new RuntimeException( - "xsi:schemaLocation attribute contains an odd number of URI values:\n" - + Arrays.toString(uriValues)); - } - Set schemaURIs = new HashSet(); - // one or more pairs of [namespace name] [schema location] - for (int i = 0; i < uriValues.length; i += 2) { - URI schemaURI = null; - if (!URI.create(uriValues[i + 1]).isAbsolute() - && (null != source.getSystemId())) { - String schemaRef = URIUtils.resolveRelativeURI( - source.getSystemId(), uriValues[i + 1]).toString(); - if (schemaRef.startsWith("file") - && !new File(schemaRef).exists() && (null != baseURI)) { - schemaRef = URIUtils.resolveRelativeURI(baseURI, - uriValues[i + 1]).toString(); - } - schemaURI = URI.create(schemaRef); - } else { - schemaURI = URI.create(uriValues[i + 1]); - } - schemaURIs.add(schemaURI); - } - return schemaURIs; - } } diff --git a/src/main/java/org/opengis/cite/swecommon20/util/XMLUtils.java b/src/main/java/org/opengis/cite/swecommon20/util/XMLUtils.java index 514cdc1..3e02414 100755 --- a/src/main/java/org/opengis/cite/swecommon20/util/XMLUtils.java +++ b/src/main/java/org/opengis/cite/swecommon20/util/XMLUtils.java @@ -54,330 +54,300 @@ import org.w3c.dom.NodeList; /** - * Provides various utility methods for accessing or manipulating XML - * representations. + * Provides various utility methods for accessing or manipulating XML representations. */ public class XMLUtils { - private static final Logger LOGR = Logger.getLogger(XMLUtils.class - .getPackage().getName()); - private static final XMLInputFactory STAX_FACTORY = initXMLInputFactory(); - private static final XPathFactory XPATH_FACTORY = initXPathFactory(); + private static final Logger LOGR = Logger.getLogger(XMLUtils.class.getPackage().getName()); - private static XPathFactory initXPathFactory() { - XPathFactory factory = XPathFactory.newInstance(); - return factory; - } + private static final XMLInputFactory STAX_FACTORY = initXMLInputFactory(); - private static XMLInputFactory initXMLInputFactory() { - XMLInputFactory factory = XMLInputFactory.newInstance(); - factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); - return factory; - } + private static final XPathFactory XPATH_FACTORY = initXPathFactory(); - /** - * Writes the content of a DOM Node to a String. The XML declaration is - * always omitted. - * - * @param node - * The DOM Node to be serialized. - * @return A String representing the content of the given node. - */ - public static String writeNodeToString(Node node) { - StringWriter writer = null; - try { - Transformer idTransformer = TransformerFactory.newInstance() - .newTransformer(); - Properties outProps = new Properties(); - outProps.setProperty("encoding", "UTF-16"); - outProps.setProperty("omit-xml-declaration", "yes"); - outProps.setProperty("indent", "yes"); - idTransformer.setOutputProperties(outProps); - writer = new StringWriter(); - idTransformer.transform(new DOMSource(node), new StreamResult( - writer)); - } catch (TransformerException ex) { - TestSuiteLogger.log(Level.WARNING, "Failed to serialize DOM node: " - + node.getNodeName(), ex); - } - return writer.toString(); - } + private static XPathFactory initXPathFactory() { + XPathFactory factory = XPathFactory.newInstance(); + return factory; + } - /** - * Writes the content of a DOM Node to a byte stream. An XML declaration is - * always omitted. - * - * @param node - * The DOM Node to be serialized. - * @param outputStream - * The destination OutputStream reference. - */ - public static void writeNode(Node node, OutputStream outputStream) { - try { - Transformer idTransformer = TransformerFactory.newInstance() - .newTransformer(); - Properties outProps = new Properties(); - outProps.setProperty(OutputKeys.METHOD, "xml"); - outProps.setProperty(OutputKeys.ENCODING, "UTF-8"); - outProps.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - outProps.setProperty(OutputKeys.INDENT, "yes"); - idTransformer.setOutputProperties(outProps); - idTransformer.transform(new DOMSource(node), new StreamResult( - outputStream)); - } catch (TransformerException ex) { - String nodeName = (node.getNodeType() == Node.DOCUMENT_NODE) ? Document.class - .cast(node).getDocumentElement().getNodeName() - : node.getNodeName(); - TestSuiteLogger.log(Level.WARNING, "Failed to serialize DOM node: " - + nodeName, ex); - } - } + private static XMLInputFactory initXMLInputFactory() { + XMLInputFactory factory = XMLInputFactory.newInstance(); + factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); + return factory; + } - /** - * Evaluates an XPath 1.0 expression using the given context and returns the - * result as a node set. - * - * @param context - * The context node. - * @param expr - * An XPath expression. - * @param namespaceBindings - * A collection of namespace bindings for the XPath expression, - * where each entry maps a namespace URI (key) to a prefix - * (value). Standard bindings do not need to be declared (see - * {@link NamespaceBindings#withStandardBindings()}. - * @return A NodeList containing nodes that satisfy the expression (it may - * be empty). - * @throws XPathExpressionException - * If the expression cannot be evaluated for any reason. - */ - public static NodeList evaluateXPath(Node context, String expr, - Map namespaceBindings) - throws XPathExpressionException { - Object result = evaluateXPath(context, expr, namespaceBindings, - XPathConstants.NODESET); - if (!NodeList.class.isInstance(result)) { - throw new XPathExpressionException( - "Expression does not evaluate to a NodeList: " + expr); - } - return (NodeList) result; - } + /** + * Writes the content of a DOM Node to a String. The XML declaration is always + * omitted. + * @param node The DOM Node to be serialized. + * @return A String representing the content of the given node. + */ + public static String writeNodeToString(Node node) { + StringWriter writer = null; + try { + Transformer idTransformer = TransformerFactory.newInstance().newTransformer(); + Properties outProps = new Properties(); + outProps.setProperty("encoding", "UTF-16"); + outProps.setProperty("omit-xml-declaration", "yes"); + outProps.setProperty("indent", "yes"); + idTransformer.setOutputProperties(outProps); + writer = new StringWriter(); + idTransformer.transform(new DOMSource(node), new StreamResult(writer)); + } + catch (TransformerException ex) { + TestSuiteLogger.log(Level.WARNING, "Failed to serialize DOM node: " + node.getNodeName(), ex); + } + return writer.toString(); + } - /** - * Evaluates an XPath expression using the given context and returns the - * result as the specified type. - * - *

    - * Note: The Saxon implementation supports XPath 2.0 - * expressions when using the JAXP XPath APIs (the default implementation - * will throw an exception). - *

    - * - * @param context - * The context node. - * @param expr - * An XPath expression. - * @param namespaceBindings - * A collection of namespace bindings for the XPath expression, - * where each entry maps a namespace URI (key) to a prefix - * (value). Standard bindings do not need to be declared (see - * {@link NamespaceBindings#withStandardBindings()}. - * @param returnType - * The desired return type (as declared in {@link XPathConstants} - * ). - * @return The result converted to the desired returnType. - * @throws XPathExpressionException - * If the expression cannot be evaluated for any reason. - */ - public static Object evaluateXPath(Node context, String expr, - Map namespaceBindings, QName returnType) - throws XPathExpressionException { - NamespaceBindings bindings = NamespaceBindings.withStandardBindings(); - bindings.addAllBindings(namespaceBindings); - XPathFactory factory = XPATH_FACTORY; - // WARNING: If context node is Saxon NodeOverNodeInfo, the factory must - // use the same Configuration object to avoid IllegalArgumentException - XPath xpath = factory.newXPath(); - xpath.setNamespaceContext(bindings); - Object result = xpath.evaluate(expr, context, returnType); - return result; - } + /** + * Writes the content of a DOM Node to a byte stream. An XML declaration is always + * omitted. + * @param node The DOM Node to be serialized. + * @param outputStream The destination OutputStream reference. + */ + public static void writeNode(Node node, OutputStream outputStream) { + try { + Transformer idTransformer = TransformerFactory.newInstance().newTransformer(); + Properties outProps = new Properties(); + outProps.setProperty(OutputKeys.METHOD, "xml"); + outProps.setProperty(OutputKeys.ENCODING, "UTF-8"); + outProps.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + outProps.setProperty(OutputKeys.INDENT, "yes"); + idTransformer.setOutputProperties(outProps); + idTransformer.transform(new DOMSource(node), new StreamResult(outputStream)); + } + catch (TransformerException ex) { + String nodeName = (node.getNodeType() == Node.DOCUMENT_NODE) + ? Document.class.cast(node).getDocumentElement().getNodeName() : node.getNodeName(); + TestSuiteLogger.log(Level.WARNING, "Failed to serialize DOM node: " + nodeName, ex); + } + } - /** - * Evaluates an XPath 2.0 expression using the Saxon s9api interfaces. - * - * @param xmlSource - * The XML Source. - * @param expr - * The XPath expression to be evaluated. - * @param nsBindings - * A collection of namespace bindings required to evaluate the - * XPath expression, where each entry maps a namespace URI (key) - * to a prefix (value); this may be {@code null} if not needed. - * @return An XdmValue object representing a value in the XDM data model; - * this is a sequence of zero or more items, where each item is - * either an atomic value or a node. - * @throws SaxonApiException - * If an error occurs while evaluating the expression; this - * always wraps some other underlying exception. - */ - public static XdmValue evaluateXPath2(Source xmlSource, String expr, - Map nsBindings) throws SaxonApiException { - Processor proc = new Processor(false); - XPathCompiler compiler = proc.newXPathCompiler(); - if (null != nsBindings) { - for (String nsURI : nsBindings.keySet()) { - compiler.declareNamespace(nsBindings.get(nsURI), nsURI); - } - } - XPathSelector xpath = compiler.compile(expr).load(); - DocumentBuilder builder = proc.newDocumentBuilder(); - XdmNode node = null; - if (DOMSource.class.isInstance(xmlSource)) { - DOMSource domSource = (DOMSource) xmlSource; - node = builder.wrap(domSource.getNode()); - } else { - node = builder.build(xmlSource); - } - xpath.setContextItem(node); - return xpath.evaluate(); - } + /** + * Evaluates an XPath 1.0 expression using the given context and returns the result as + * a node set. + * @param context The context node. + * @param expr An XPath expression. + * @param namespaceBindings A collection of namespace bindings for the XPath + * expression, where each entry maps a namespace URI (key) to a prefix (value). + * Standard bindings do not need to be declared (see + * {@link org.opengis.cite.swecommon20.util.NamespaceBindings#withStandardBindings()}. + * @return A NodeList containing nodes that satisfy the expression (it may be empty). + * @throws javax.xml.xpath.XPathExpressionException If the expression cannot be + * evaluated for any reason. + */ + public static NodeList evaluateXPath(Node context, String expr, Map namespaceBindings) + throws XPathExpressionException { + Object result = evaluateXPath(context, expr, namespaceBindings, XPathConstants.NODESET); + if (!NodeList.class.isInstance(result)) { + throw new XPathExpressionException("Expression does not evaluate to a NodeList: " + expr); + } + return (NodeList) result; + } - /** - * Creates a new Element having the specified qualified name. The element - * must be {@link Document#adoptNode(Node) adopted} when inserted into - * another Document. - * - * @param qName - * A QName object. - * @return An Element node (with a Document owner but no parent). - */ - public static Element createElement(QName qName) { - Document doc = null; - try { - doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() - .newDocument(); - } catch (ParserConfigurationException e) { - throw new RuntimeException(e); - } - Element elem = doc.createElementNS(qName.getNamespaceURI(), - qName.getLocalPart()); - return elem; - } + /** + * Evaluates an XPath expression using the given context and returns the result as the + * specified type. + * + *

    + * Note: The Saxon implementation supports XPath 2.0 expressions when + * using the JAXP XPath APIs (the default implementation will throw an exception). + *

    + * @param context The context node. + * @param expr An XPath expression. + * @param namespaceBindings A collection of namespace bindings for the XPath + * expression, where each entry maps a namespace URI (key) to a prefix (value). + * Standard bindings do not need to be declared (see + * {@link org.opengis.cite.swecommon20.util.NamespaceBindings#withStandardBindings()}. + * @param returnType The desired return type (as declared in + * {@link javax.xml.xpath.XPathConstants} ). + * @return The result converted to the desired returnType. + * @throws javax.xml.xpath.XPathExpressionException If the expression cannot be + * evaluated for any reason. + */ + public static Object evaluateXPath(Node context, String expr, Map namespaceBindings, + QName returnType) throws XPathExpressionException { + NamespaceBindings bindings = NamespaceBindings.withStandardBindings(); + bindings.addAllBindings(namespaceBindings); + XPathFactory factory = XPATH_FACTORY; + // WARNING: If context node is Saxon NodeOverNodeInfo, the factory must + // use the same Configuration object to avoid IllegalArgumentException + XPath xpath = factory.newXPath(); + xpath.setNamespaceContext(bindings); + Object result = xpath.evaluate(expr, context, returnType); + return result; + } - /** - * Returns a List of all descendant Element nodes having the specified - * [namespace name] property. The elements are listed in document order. - * - * @param node - * The node to search from. - * @param namespaceURI - * An absolute URI denoting a namespace name. - * @return A List containing elements in the specified namespace; the list - * is empty if there are no elements in the namespace. - */ - public static List getElementsByNamespaceURI(Node node, - String namespaceURI) { - List list = new ArrayList(); - NodeList children = node.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - if (child.getNodeType() != Node.ELEMENT_NODE) - continue; - if (child.getNamespaceURI().equals(namespaceURI)) - list.add((Element) child); - } - return list; - } + /** + * Evaluates an XPath 2.0 expression using the Saxon s9api interfaces. + * @param xmlSource The XML Source. + * @param expr The XPath expression to be evaluated. + * @param nsBindings A collection of namespace bindings required to evaluate the XPath + * expression, where each entry maps a namespace URI (key) to a prefix (value); this + * may be {@code null} if not needed. + * @return An XdmValue object representing a value in the XDM data model; this is a + * sequence of zero or more items, where each item is either an atomic value or a + * node. + * @throws net.sf.saxon.s9api.SaxonApiException If an error occurs while evaluating + * the expression; this always wraps some other underlying exception. + */ + public static XdmValue evaluateXPath2(Source xmlSource, String expr, Map nsBindings) + throws SaxonApiException { + Processor proc = new Processor(false); + XPathCompiler compiler = proc.newXPathCompiler(); + if (null != nsBindings) { + for (String nsURI : nsBindings.keySet()) { + compiler.declareNamespace(nsBindings.get(nsURI), nsURI); + } + } + XPathSelector xpath = compiler.compile(expr).load(); + DocumentBuilder builder = proc.newDocumentBuilder(); + XdmNode node = null; + if (DOMSource.class.isInstance(xmlSource)) { + DOMSource domSource = (DOMSource) xmlSource; + node = builder.wrap(domSource.getNode()); + } + else { + node = builder.build(xmlSource); + } + xpath.setContextItem(node); + return xpath.evaluate(); + } - /** - * Transforms the content of a DOM Node using a specified XSLT stylesheet. - * - * @param xslt - * A Source object representing a stylesheet (XSLT 1.0 or 2.0). - * @param source - * A Node representing the XML source. If it is an Element node - * it will be imported into a new DOM Document. - * @return A DOM Document containing the result of the transformation. - */ - public static Document transform(Source xslt, Node source) { - Document sourceDoc = null; - Document resultDoc = null; - try { - resultDoc = DocumentBuilderFactory.newInstance() - .newDocumentBuilder().newDocument(); - if (source.getNodeType() == Node.DOCUMENT_NODE) { - sourceDoc = (Document) source; - } else { - sourceDoc = DocumentBuilderFactory.newInstance() - .newDocumentBuilder().newDocument(); - sourceDoc.appendChild(sourceDoc.importNode(source, true)); - } - } catch (ParserConfigurationException pce) { - throw new RuntimeException(pce); - } - Processor processor = new Processor(false); - XsltCompiler compiler = processor.newXsltCompiler(); - try { - XsltExecutable exec = compiler.compile(xslt); - XsltTransformer transformer = exec.load(); - transformer.setSource(new DOMSource(sourceDoc)); - transformer.setDestination(new DOMDestination(resultDoc)); - transformer.transform(); - } catch (SaxonApiException e) { - throw new RuntimeException(e); - } - return resultDoc; - } + /** + * Creates a new Element having the specified qualified name. The element must be + * {@link org.w3c.dom.Document#adoptNode(Node) adopted} when inserted into another + * Document. + * @param qName A QName object. + * @return An Element node (with a Document owner but no parent). + */ + public static Element createElement(QName qName) { + Document doc = null; + try { + doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + } + catch (ParserConfigurationException e) { + throw new RuntimeException(e); + } + Element elem = doc.createElementNS(qName.getNamespaceURI(), qName.getLocalPart()); + return elem; + } + + /** + * Returns a List of all descendant Element nodes having the specified [namespace + * name] property. The elements are listed in document order. + * @param node The node to search from. + * @param namespaceURI An absolute URI denoting a namespace name. + * @return A List containing elements in the specified namespace; the list is empty if + * there are no elements in the namespace. + */ + public static List getElementsByNamespaceURI(Node node, String namespaceURI) { + List list = new ArrayList(); + NodeList children = node.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + Node child = children.item(i); + if (child.getNodeType() != Node.ELEMENT_NODE) + continue; + if (child.getNamespaceURI().equals(namespaceURI)) + list.add((Element) child); + } + return list; + } + + /** + * Transforms the content of a DOM Node using a specified XSLT stylesheet. + * @param xslt A Source object representing a stylesheet (XSLT 1.0 or 2.0). + * @param source A Node representing the XML source. If it is an Element node it will + * be imported into a new DOM Document. + * @return A DOM Document containing the result of the transformation. + */ + public static Document transform(Source xslt, Node source) { + Document sourceDoc = null; + Document resultDoc = null; + try { + resultDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + if (source.getNodeType() == Node.DOCUMENT_NODE) { + sourceDoc = (Document) source; + } + else { + sourceDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + sourceDoc.appendChild(sourceDoc.importNode(source, true)); + } + } + catch (ParserConfigurationException pce) { + throw new RuntimeException(pce); + } + Processor processor = new Processor(false); + XsltCompiler compiler = processor.newXsltCompiler(); + try { + XsltExecutable exec = compiler.compile(xslt); + XsltTransformer transformer = exec.load(); + transformer.setSource(new DOMSource(sourceDoc)); + transformer.setDestination(new DOMDestination(resultDoc)); + transformer.transform(); + } + catch (SaxonApiException e) { + throw new RuntimeException(e); + } + return resultDoc; + } + + /** + * Expands character entity and numeric references that occur within a given string + * value. It may be necessary to do this before processing an XPath expression. + * @param value A string representing text content. + * @return A string with all included references expanded. + */ + public static String expandReferencesInText(String value) { + StringBuilder wrapper = new StringBuilder(""); + wrapper.append(value).append(""); + Reader reader = new StringReader(wrapper.toString()); + String str = null; + try { + XMLStreamReader xsr = STAX_FACTORY.createXMLStreamReader(reader); + xsr.nextTag(); // document element + str = xsr.getElementText(); + } + catch (XMLStreamException xse) { + LOGR.log(Level.WARNING, xse.getMessage(), xse); + } + return str; + } + + /** + *

    + * isXMLSchema. + *

    + * @param file a {@link java.io.File} object + * @return a boolean + */ + public static boolean isXMLSchema(File file) { + if (!file.exists() || (file.length() == 0)) { + return false; + } + QName docElemName = QName.valueOf(""); + InputStream inStream = null; + XMLEventReader reader = null; + try { + inStream = new FileInputStream(file); + XMLInputFactory factory = XMLInputFactory.newInstance(); + reader = factory.createXMLEventReader(inStream); + StartElement docElem = reader.nextTag().asStartElement(); + docElemName = docElem.getName(); + } + catch (Exception e1) { + return false; + } + finally { + try { + reader.close(); + inStream.close(); + } + catch (Exception e2) { + TestSuiteLogger.log(Level.INFO, "Error closing resource.", e2); + } + } + return docElemName.getNamespaceURI().equals(XMLConstants.W3C_XML_SCHEMA_NS_URI); + } - /** - * Expands character entity and numeric references - * that occur within a given string value. It may be necessary to do - * this before processing an XPath expression. - * - * @param value - * A string representing text content. - * @return A string with all included references expanded. - */ - public static String expandReferencesInText(String value) { - StringBuilder wrapper = new StringBuilder(""); - wrapper.append(value).append(""); - Reader reader = new StringReader(wrapper.toString()); - String str = null; - try { - XMLStreamReader xsr = STAX_FACTORY.createXMLStreamReader(reader); - xsr.nextTag(); // document element - str = xsr.getElementText(); - } catch (XMLStreamException xse) { - LOGR.log(Level.WARNING, xse.getMessage(), xse); - } - return str; - } - - public static boolean isXMLSchema(File file) { - if (!file.exists() || (file.length() == 0)) { - return false; - } - QName docElemName = QName.valueOf(""); - InputStream inStream = null; - XMLEventReader reader = null; - try { - inStream = new FileInputStream(file); - XMLInputFactory factory = XMLInputFactory.newInstance(); - reader = factory.createXMLEventReader(inStream); - StartElement docElem = reader.nextTag().asStartElement(); - docElemName = docElem.getName(); - } catch (Exception e1) { - return false; - } finally { - try { - reader.close(); - inStream.close(); - } catch (Exception e2) { - TestSuiteLogger.log(Level.INFO, "Error closing resource.", e2); - } - } - return docElemName.getNamespaceURI().equals( - XMLConstants.W3C_XML_SCHEMA_NS_URI); - } } diff --git a/src/site/site.xml b/src/site/site.xml index 7310df9..4e69efb 100755 --- a/src/site/site.xml +++ b/src/site/site.xml @@ -7,7 +7,7 @@ org.apache.maven.skins maven-fluido-skin - 1.7 + 2.0.1 diff --git a/src/test/java/org/opengis/cite/swecommon20/VerifyETSAssert.java b/src/test/java/org/opengis/cite/swecommon20/VerifyETSAssert.java index 3a9cfbb..1e68921 100755 --- a/src/test/java/org/opengis/cite/swecommon20/VerifyETSAssert.java +++ b/src/test/java/org/opengis/cite/swecommon20/VerifyETSAssert.java @@ -21,53 +21,53 @@ public class VerifyETSAssert { - private static final String WADL_NS = "http://wadl.dev.java.net/2009/02"; - private static DocumentBuilder docBuilder; - private static SchemaFactory factory; - @Rule - public ExpectedException thrown = ExpectedException.none(); + private static final String WADL_NS = "http://wadl.dev.java.net/2009/02"; - public VerifyETSAssert() { - } + private static DocumentBuilder docBuilder; - @BeforeClass - public static void setUpClass() throws ParserConfigurationException { - factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - docBuilder = dbf.newDocumentBuilder(); - } + private static SchemaFactory factory; - @Test - public void validateUsingSchemaHints_expect2Errors() throws SAXException { - thrown.expect(AssertionError.class); - thrown.expectMessage("2 schema validation error(s) detected"); - URL url = this.getClass().getResource("/Gamma.xml"); - Schema schema = factory.newSchema(); - Validator validator = schema.newValidator(); - ETSAssert - .assertSchemaValid(validator, new StreamSource(url.toString())); - } + @Rule + public ExpectedException thrown = ExpectedException.none(); - @Test - public void assertXPathWithNamespaceBindings() throws SAXException, - IOException { - Document doc = docBuilder.parse(this.getClass().getResourceAsStream( - "/capabilities-simple.xml")); - Map nsBindings = new HashMap(); - nsBindings.put(WADL_NS, "ns1"); - String xpath = "//ns1:resources"; - ETSAssert.assertXPath(xpath, doc, nsBindings); - } + public VerifyETSAssert() { + } + + @BeforeClass + public static void setUpClass() throws ParserConfigurationException { + factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + docBuilder = dbf.newDocumentBuilder(); + } + + @Test + public void validateUsingSchemaHints_expect2Errors() throws SAXException { + thrown.expect(AssertionError.class); + thrown.expectMessage("2 schema validation error(s) detected"); + URL url = this.getClass().getResource("/Gamma.xml"); + Schema schema = factory.newSchema(); + Validator validator = schema.newValidator(); + ETSAssert.assertSchemaValid(validator, new StreamSource(url.toString())); + } + + @Test + public void assertXPathWithNamespaceBindings() throws SAXException, IOException { + Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/capabilities-simple.xml")); + Map nsBindings = new HashMap(); + nsBindings.put(WADL_NS, "ns1"); + String xpath = "//ns1:resources"; + ETSAssert.assertXPath(xpath, doc, nsBindings); + } + + @Test + public void assertXPath_expectFalse() throws SAXException, IOException { + thrown.expect(AssertionError.class); + thrown.expectMessage("Unexpected result evaluating XPath expression"); + Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/capabilities-simple.xml")); + // using built-in namespace binding + String xpath = "//ows:OperationsMetadata/ows:Constraint[@name='XMLEncoding']/ows:DefaultValue = 'TRUE'"; + ETSAssert.assertXPath(xpath, doc, null); + } - @Test - public void assertXPath_expectFalse() throws SAXException, IOException { - thrown.expect(AssertionError.class); - thrown.expectMessage("Unexpected result evaluating XPath expression"); - Document doc = docBuilder.parse(this.getClass().getResourceAsStream( - "/capabilities-simple.xml")); - // using built-in namespace binding - String xpath = "//ows:OperationsMetadata/ows:Constraint[@name='XMLEncoding']/ows:DefaultValue = 'TRUE'"; - ETSAssert.assertXPath(xpath, doc, null); - } } diff --git a/src/test/java/org/opengis/cite/swecommon20/VerifySuiteFixtureListener.java b/src/test/java/org/opengis/cite/swecommon20/VerifySuiteFixtureListener.java index 31ce351..ccd78b4 100755 --- a/src/test/java/org/opengis/cite/swecommon20/VerifySuiteFixtureListener.java +++ b/src/test/java/org/opengis/cite/swecommon20/VerifySuiteFixtureListener.java @@ -13,57 +13,57 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.mockito.Matchers; +import org.mockito.ArgumentMatchers; import org.testng.ISuite; import org.testng.xml.XmlSuite; import org.w3c.dom.Document; public class VerifySuiteFixtureListener { - private static XmlSuite xmlSuite; - private static ISuite suite; + private static XmlSuite xmlSuite; - public VerifySuiteFixtureListener() { - } + private static ISuite suite; - @BeforeClass - public static void setUpClass() { - xmlSuite = mock(XmlSuite.class); - suite = mock(ISuite.class); - when(suite.getXmlSuite()).thenReturn(xmlSuite); - } + public VerifySuiteFixtureListener() { + } - @AfterClass - public static void tearDownClass() { - } + @BeforeClass + public static void setUpClass() { + xmlSuite = mock(XmlSuite.class); + suite = mock(ISuite.class); + when(suite.getXmlSuite()).thenReturn(xmlSuite); + } - @Before - public void setUp() { - } + @AfterClass + public static void tearDownClass() { + } - @After - public void tearDown() { - } + @Before + public void setUp() { + } - @Test(expected = IllegalArgumentException.class) - public void noSuiteParameters() { - Map params = new HashMap(); - when(xmlSuite.getParameters()).thenReturn(params); - SuiteFixtureListener iut = new SuiteFixtureListener(); - iut.onStart(suite); - } + @After + public void tearDown() { + } -// @Test -// public void processIUTParameter() throws URISyntaxException { -// URL url = this.getClass().getResource("/atom-feed.xml"); -// Map params = new HashMap(); -// params.put(TestRunArg.IUT.toString(), url.toURI().toString()); -// when(xmlSuite.getParameters()).thenReturn(params); -// SuiteFixtureListener iut = new SuiteFixtureListener(); -// iut.onStart(suite); -// verify(suite).setAttribute( -// Matchers.eq(SuiteAttribute.TEST_SUBJECT.getName()), -// Matchers.isA(Document.class)); -// } + @Test(expected = IllegalArgumentException.class) + public void noSuiteParameters() { + Map params = new HashMap(); + when(xmlSuite.getParameters()).thenReturn(params); + SuiteFixtureListener iut = new SuiteFixtureListener(); + iut.onStart(suite); + } + + @Test + public void processIUTParameter() throws URISyntaxException { + URL url = this.getClass().getResource("/examples/image_data.xml"); + Map params = new HashMap(); + params.put(TestRunArg.IUT.toString(), url.toURI().toString()); + when(xmlSuite.getParameters()).thenReturn(params); + SuiteFixtureListener iut = new SuiteFixtureListener(); + iut.onStart(suite); + verify(suite).setAttribute(ArgumentMatchers.eq(SuiteAttribute.TEST_SUBJECT.getName()), + ArgumentMatchers.isA(Document.class)); + } } diff --git a/src/test/java/org/opengis/cite/swecommon20/VerifyTestNGController.java b/src/test/java/org/opengis/cite/swecommon20/VerifyTestNGController.java index 6ae491a..cdccdda 100755 --- a/src/test/java/org/opengis/cite/swecommon20/VerifyTestNGController.java +++ b/src/test/java/org/opengis/cite/swecommon20/VerifyTestNGController.java @@ -25,47 +25,42 @@ /** * Verifies the results of executing a test run using the main controller * (TestNGController). - * + * */ public class VerifyTestNGController { - private static DocumentBuilder docBuilder; - private Properties testRunProps; + private static DocumentBuilder docBuilder; - @BeforeClass - public static void initParser() throws ParserConfigurationException { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setValidating(false); - dbf.setFeature( - "http://apache.org/xml/features/nonvalidating/load-external-dtd", - false); - docBuilder = dbf.newDocumentBuilder(); - } + private Properties testRunProps; - @Before - public void loadDefaultTestRunProperties() - throws InvalidPropertiesFormatException, IOException { - this.testRunProps = new Properties(); - this.testRunProps.loadFromXML(getClass().getResourceAsStream( - "/test-run-props.xml")); - } + @BeforeClass + public static void initParser() throws ParserConfigurationException { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setValidating(false); + dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); + docBuilder = dbf.newDocumentBuilder(); + } + + @Before + public void loadDefaultTestRunProperties() throws InvalidPropertiesFormatException, IOException { + this.testRunProps = new Properties(); + this.testRunProps.loadFromXML(getClass().getResourceAsStream("/test-run-props.xml")); + } + + @Test + public void doTestRun() throws Exception { + URL testSubject = getClass().getResource("/examples/52NorthSWECom.xml"); + this.testRunProps.setProperty(TestRunArg.IUT.toString(), testSubject.toURI().toString()); + ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024); + this.testRunProps.storeToXML(outStream, "Integration test"); + Document testRunArgs = docBuilder.parse(new ByteArrayInputStream(outStream.toByteArray())); + TestNGController controller = new TestNGController(); + Source results = controller.doTestRun(testRunArgs); + String xpath = "/testng-results/@failed"; + XdmValue failed = XMLUtils.evaluateXPath2(results, xpath, null); + int numFailed = Integer.parseInt(failed.getUnderlyingValue().getStringValue()); + assertEquals("Unexpected number of fail verdicts.", 1, numFailed); + } - @Test - public void doTestRun() throws Exception { - URL testSubject = getClass().getResource("/examples/52NorthSWECom.xml"); - this.testRunProps.setProperty(TestRunArg.IUT.toString(), testSubject - .toURI().toString()); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024); - this.testRunProps.storeToXML(outStream, "Integration test"); - Document testRunArgs = docBuilder.parse(new ByteArrayInputStream( - outStream.toByteArray())); - TestNGController controller = new TestNGController(); - Source results = controller.doTestRun(testRunArgs); - String xpath = "/testng-results/@failed"; - XdmValue failed = XMLUtils.evaluateXPath2(results, xpath, null); - int numFailed = Integer.parseInt(failed.getUnderlyingValue() - .getStringValue()); - assertEquals("Unexpected number of fail verdicts.", 1, numFailed); - } } diff --git a/src/test/java/org/opengis/cite/swecommon20/util/VerifyURIUtils.java b/src/test/java/org/opengis/cite/swecommon20/util/VerifyURIUtils.java index 2147ee9..4912e83 100755 --- a/src/test/java/org/opengis/cite/swecommon20/util/VerifyURIUtils.java +++ b/src/test/java/org/opengis/cite/swecommon20/util/VerifyURIUtils.java @@ -19,65 +19,60 @@ */ public class VerifyURIUtils { - public VerifyURIUtils() { - } + public VerifyURIUtils() { + } - @BeforeClass - public static void setUpClass() { - } + @BeforeClass + public static void setUpClass() { + } - @Ignore - @Test - // comment out @Ignore to run test (requires network connection) - public void resolveHttpUriAsDocument() throws SAXException, IOException { - URI uriRef = URI.create("http://www.w3schools.com/xml/note.xml"); - Document doc = URIUtils.parseURI(uriRef); - Assert.assertNotNull(doc); - Assert.assertEquals("Document element has unexpected [local name].", - "note", doc.getDocumentElement().getLocalName()); - } + @Ignore + @Test + // comment out @Ignore to run test (requires network connection) + public void resolveHttpUriAsDocument() throws SAXException, IOException { + URI uriRef = URI.create("http://www.w3schools.com/xml/note.xml"); + Document doc = URIUtils.parseURI(uriRef); + Assert.assertNotNull(doc); + Assert.assertEquals("Document element has unexpected [local name].", "note", + doc.getDocumentElement().getLocalName()); + } - @Ignore - @Test - // comment out @Ignore to run test (requires network connection) - public void resolveHttpUriAsFile() throws SAXException, IOException { - URI uriRef = URI.create("http://www.w3schools.com/xml/note.xml"); - File file = URIUtils.dereferenceURI(uriRef); - Assert.assertNotNull(file); - Assert.assertTrue("File should not be empty", file.length() > 0); - } + @Ignore + @Test + // comment out @Ignore to run test (requires network connection) + public void resolveHttpUriAsFile() throws SAXException, IOException { + URI uriRef = URI.create("http://www.w3schools.com/xml/note.xml"); + File file = URIUtils.dereferenceURI(uriRef); + Assert.assertNotNull(file); + Assert.assertTrue("File should not be empty", file.length() > 0); + } - @Test - public void resolveClasspathResource() throws SAXException, IOException, - URISyntaxException { - URL url = this.getClass().getResource("/atom-feed.xml"); - Document doc = URIUtils.parseURI(url.toURI()); - Assert.assertNotNull(doc); - Assert.assertEquals("Document element has unexpected [local name].", - "feed", doc.getDocumentElement().getLocalName()); - } + @Test + public void resolveClasspathResource() throws SAXException, IOException, URISyntaxException { + URL url = this.getClass().getResource("/atom-feed.xml"); + Document doc = URIUtils.parseURI(url.toURI()); + Assert.assertNotNull(doc); + Assert.assertEquals("Document element has unexpected [local name].", "feed", + doc.getDocumentElement().getLocalName()); + } - @Test - public void resolveFileRefWithXInclude() throws SAXException, IOException, - URISyntaxException { - File file = new File("src/test/resources/Alpha-xinclude.xml"); - Document doc = URIUtils.parseURI(file.toURI()); - Assert.assertNotNull(doc); - Assert.assertEquals("Document element has unexpected [local name].", - "Alpha", doc.getDocumentElement().getLocalName()); - NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS( - "http://www.example.net/gamma", "Gamma"); - Assert.assertEquals( - "Expected element {http://www.example.net/gamma}Gamma", 1, - nodes.getLength()); - } + @Test + public void resolveFileRefWithXInclude() throws SAXException, IOException, URISyntaxException { + File file = new File("src/test/resources/Alpha-xinclude.xml"); + Document doc = URIUtils.parseURI(file.toURI()); + Assert.assertNotNull(doc); + Assert.assertEquals("Document element has unexpected [local name].", "Alpha", + doc.getDocumentElement().getLocalName()); + NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS("http://www.example.net/gamma", "Gamma"); + Assert.assertEquals("Expected element {http://www.example.net/gamma}Gamma", 1, nodes.getLength()); + } + + @Test(expected = IllegalArgumentException.class) + public void resolveMissingClasspathResource() throws SAXException, URISyntaxException, IOException { + URL url = this.getClass().getResource("/alpha.xml"); + URI uri = (null != url) ? url.toURI() : null; + Document doc = URIUtils.parseURI(uri); + Assert.assertNull(doc); + } - @Test(expected = IllegalArgumentException.class) - public void resolveMissingClasspathResource() throws SAXException, - URISyntaxException, IOException { - URL url = this.getClass().getResource("/alpha.xml"); - URI uri = (null != url) ? url.toURI() : null; - Document doc = URIUtils.parseURI(uri); - Assert.assertNull(doc); - } } diff --git a/src/test/java/org/opengis/cite/swecommon20/util/VerifyValidationUtils.java b/src/test/java/org/opengis/cite/swecommon20/util/VerifyValidationUtils.java index 1938e7e..1d5ce91 100755 --- a/src/test/java/org/opengis/cite/swecommon20/util/VerifyValidationUtils.java +++ b/src/test/java/org/opengis/cite/swecommon20/util/VerifyValidationUtils.java @@ -18,26 +18,23 @@ */ public class VerifyValidationUtils { - public VerifyValidationUtils() { - } - - @Test - public void testBuildSchematronValidator() { - String schemaRef = "http://schemas.opengis.net/gml/3.2.1/SchematronConstraints.xml"; - String phase = ""; - SchematronValidator result = ValidationUtils.buildSchematronValidator( - schemaRef, phase); - assertNotNull(result); - } - - @Test - public void extractRelativeSchemaReference() throws FileNotFoundException, - XMLStreamException { - File xmlFile = new File("src/test/resources/Alpha-1.xml"); - Set xsdSet = ValidationUtils.extractSchemaReferences( - new StreamSource(xmlFile), null); - URI schemaURI = xsdSet.iterator().next(); - assertTrue("Expected schema reference */xsd/alpha.xsd", schemaURI - .toString().endsWith("/xsd/alpha.xsd")); - } + public VerifyValidationUtils() { + } + + @Test + public void testBuildSchematronValidator() { + String schemaRef = "http://schemas.opengis.net/gml/3.2.1/SchematronConstraints.xml"; + String phase = ""; + SchematronValidator result = ValidationUtils.buildSchematronValidator(schemaRef, phase); + assertNotNull(result); + } + + @Test + public void extractRelativeSchemaReference() throws FileNotFoundException, XMLStreamException { + File xmlFile = new File("src/test/resources/Alpha-1.xml"); + Set xsdSet = ValidationUtils.extractSchemaReferences(new StreamSource(xmlFile), null); + URI schemaURI = xsdSet.iterator().next(); + assertTrue("Expected schema reference */xsd/alpha.xsd", schemaURI.toString().endsWith("/xsd/alpha.xsd")); + } + } diff --git a/src/test/java/org/opengis/cite/swecommon20/util/VerifyXMLUtils.java b/src/test/java/org/opengis/cite/swecommon20/util/VerifyXMLUtils.java index f4a7e4e..871b1d9 100755 --- a/src/test/java/org/opengis/cite/swecommon20/util/VerifyXMLUtils.java +++ b/src/test/java/org/opengis/cite/swecommon20/util/VerifyXMLUtils.java @@ -26,122 +26,110 @@ */ public class VerifyXMLUtils { - private static final String ATOM_NS = "http://www.w3.org/2005/Atom"; - private static final String EX_NS = "http://example.org/ns1"; - private static DocumentBuilder docBuilder; - - public VerifyXMLUtils() { - } - - @BeforeClass - public static void setUpClass() throws Exception { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - docBuilder = dbf.newDocumentBuilder(); - } - - @Test - public void writeDocToString() throws SAXException, IOException { - Document doc = docBuilder.parse(this.getClass().getResourceAsStream( - "/atom-feed.xml")); - String content = XMLUtils.writeNodeToString(doc); - Assert.assertTrue("String should start with ' nsBindings = new HashMap(); - nsBindings.put(ATOM_NS, "tns"); - nsBindings.put(EX_NS, "ns1"); - NodeList results = XMLUtils.evaluateXPath(doc, expr, nsBindings); - Assert.assertTrue("Expected 1 node in results.", - results.getLength() == 1); - Assert.assertEquals("author", results.item(0).getLocalName()); - } - - @Test - public void evaluateXPathExpression_noMatch() - throws XPathExpressionException, SAXException, IOException { - Document doc = docBuilder.parse(this.getClass().getResourceAsStream( - "/atom-feed.xml")); - String expr = "/tns:feed/tns:author[ns1:blog]"; - Map nsBindings = new HashMap(); - nsBindings.put(ATOM_NS, "tns"); - nsBindings.put(EX_NS, "ns1"); - NodeList results = XMLUtils.evaluateXPath(doc, expr, nsBindings); - Assert.assertTrue("Expected empty results.", results.getLength() == 0); - } - - @Test(expected = XPathExpressionException.class) - public void evaluateXPathExpression_booleanResult() - throws XPathExpressionException, SAXException, IOException { - Document doc = docBuilder.parse(this.getClass().getResourceAsStream( - "/atom-feed.xml")); - String expr = "count(//tns:entry) > 0"; - Map nsBindings = new HashMap(); - nsBindings.put(ATOM_NS, "tns"); - NodeList results = XMLUtils.evaluateXPath(doc, expr, nsBindings); - Assert.assertNull(results); - } - - @Test - public void createElement_Alpha() { - QName qName = new QName("http://example.org", "Alpha"); - Element elem = XMLUtils.createElement(qName); - Assert.assertEquals("Alpha", elem.getLocalName()); - Assert.assertNull(elem.getParentNode()); - Assert.assertNotNull(elem.getOwnerDocument()); - } - - @Test - public void evaluateXPath2ExpressionAgainstDocument() throws SAXException, - IOException, SaxonApiException, XPathException { - Document doc = docBuilder.parse(this.getClass().getResourceAsStream( - "/atom-feed.xml")); - String expr = "matches(//tns:entry/tns:title, '.*Robots')"; - Map nsBindings = new HashMap(); - nsBindings.put(ATOM_NS, "tns"); - XdmValue result = XMLUtils.evaluateXPath2(new DOMSource(doc), expr, - nsBindings); - Assert.assertTrue("Expected non-empty result.", result.size() > 0); - Assert.assertEquals("Result has unexpected string value.", "true", - result.getUnderlyingValue().getStringValue()); - } - - @Test - public void evaluateXPath2ExpressionAgainstElement() throws SAXException, - IOException, SaxonApiException, XPathException { - Document doc = docBuilder.parse(this.getClass().getResourceAsStream( - "/atom-feed.xml")); - Node entry = doc.getElementsByTagNameNS(ATOM_NS, "entry").item(0); - String expr = "matches(tns:title, '.*Robots')"; - Map nsBindings = new HashMap(); - nsBindings.put(ATOM_NS, "tns"); - XdmValue result = XMLUtils.evaluateXPath2(new DOMSource(entry), expr, - nsBindings); - Assert.assertTrue("Expected non-empty result.", result.size() > 0); - Assert.assertEquals("Result has unexpected string value.", "true", - result.getUnderlyingValue().getStringValue()); - } - - @Test - public void expandCharacterEntity() { - String text = "Ce n'est pas"; - String result = XMLUtils.expandReferencesInText(text); - Assert.assertTrue("Expected result to contain an apostrophe (')", - result.contains("'")); - } - - @Test - public void expandNumericCharacterReference() { - String text = "Montréal"; - String result = XMLUtils.expandReferencesInText(text); - Assert.assertEquals("Expected result to contain character é (U+00E9)", - "Montréal", result); - } + private static final String ATOM_NS = "http://www.w3.org/2005/Atom"; + + private static final String EX_NS = "http://example.org/ns1"; + + private static DocumentBuilder docBuilder; + + public VerifyXMLUtils() { + } + + @BeforeClass + public static void setUpClass() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + docBuilder = dbf.newDocumentBuilder(); + } + + @Test + public void writeDocToString() throws SAXException, IOException { + Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/atom-feed.xml")); + String content = XMLUtils.writeNodeToString(doc); + Assert.assertTrue("String should start with ' nsBindings = new HashMap(); + nsBindings.put(ATOM_NS, "tns"); + nsBindings.put(EX_NS, "ns1"); + NodeList results = XMLUtils.evaluateXPath(doc, expr, nsBindings); + Assert.assertTrue("Expected 1 node in results.", results.getLength() == 1); + Assert.assertEquals("author", results.item(0).getLocalName()); + } + + @Test + public void evaluateXPathExpression_noMatch() throws XPathExpressionException, SAXException, IOException { + Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/atom-feed.xml")); + String expr = "/tns:feed/tns:author[ns1:blog]"; + Map nsBindings = new HashMap(); + nsBindings.put(ATOM_NS, "tns"); + nsBindings.put(EX_NS, "ns1"); + NodeList results = XMLUtils.evaluateXPath(doc, expr, nsBindings); + Assert.assertTrue("Expected empty results.", results.getLength() == 0); + } + + @Test(expected = XPathExpressionException.class) + public void evaluateXPathExpression_booleanResult() throws XPathExpressionException, SAXException, IOException { + Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/atom-feed.xml")); + String expr = "count(//tns:entry) > 0"; + Map nsBindings = new HashMap(); + nsBindings.put(ATOM_NS, "tns"); + NodeList results = XMLUtils.evaluateXPath(doc, expr, nsBindings); + Assert.assertNull(results); + } + + @Test + public void createElement_Alpha() { + QName qName = new QName("http://example.org", "Alpha"); + Element elem = XMLUtils.createElement(qName); + Assert.assertEquals("Alpha", elem.getLocalName()); + Assert.assertNull(elem.getParentNode()); + Assert.assertNotNull(elem.getOwnerDocument()); + } + + @Test + public void evaluateXPath2ExpressionAgainstDocument() + throws SAXException, IOException, SaxonApiException, XPathException { + Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/atom-feed.xml")); + String expr = "matches(//tns:entry/tns:title, '.*Robots')"; + Map nsBindings = new HashMap(); + nsBindings.put(ATOM_NS, "tns"); + XdmValue result = XMLUtils.evaluateXPath2(new DOMSource(doc), expr, nsBindings); + Assert.assertTrue("Expected non-empty result.", result.size() > 0); + Assert.assertEquals("Result has unexpected string value.", "true", + result.getUnderlyingValue().getStringValue()); + } + + @Test + public void evaluateXPath2ExpressionAgainstElement() + throws SAXException, IOException, SaxonApiException, XPathException { + Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/atom-feed.xml")); + Node entry = doc.getElementsByTagNameNS(ATOM_NS, "entry").item(0); + String expr = "matches(tns:title, '.*Robots')"; + Map nsBindings = new HashMap(); + nsBindings.put(ATOM_NS, "tns"); + XdmValue result = XMLUtils.evaluateXPath2(new DOMSource(entry), expr, nsBindings); + Assert.assertTrue("Expected non-empty result.", result.size() > 0); + Assert.assertEquals("Result has unexpected string value.", "true", + result.getUnderlyingValue().getStringValue()); + } + + @Test + public void expandCharacterEntity() { + String text = "Ce n'est pas"; + String result = XMLUtils.expandReferencesInText(text); + Assert.assertTrue("Expected result to contain an apostrophe (')", result.contains("'")); + } + + @Test + public void expandNumericCharacterReference() { + String text = "Montréal"; + String result = XMLUtils.expandReferencesInText(text); + Assert.assertEquals("Expected result to contain character é (U+00E9)", "Montréal", result); + } + }