From 369e00425541baca7f7069383960af3ff4379cbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Pro=C3=9F?= Date: Tue, 17 Dec 2024 14:34:49 +0100 Subject: [PATCH 1/8] Adjust pom.xml --- pom.xml | 214 +++++++------------------------------------------------- 1 file changed, 27 insertions(+), 187 deletions(-) diff --git a/pom.xml b/pom.xml index b77e0bd..50200db 100644 --- a/pom.xml +++ b/pom.xml @@ -3,11 +3,10 @@ org.opengis.cite ets-common - 9 + 14-SNAPSHOT 4.0.0 - org.opengis.cite ets-geopose10 1.1-SNAPSHOT jar @@ -47,58 +46,41 @@ geopose10 1.0 - 5.5.2 - - - - com.fasterxml.jackson.core - jackson-databind - 2.12.1 - - - com.fasterxml.jackson.core - jackson-annotations - 2.12.1 - - - com.fasterxml.jackson.core - jackson-core - 2.12.1 - - - org.slf4j - slf4j-api - 1.7.30 - - - org.apache.commons - commons-lang3 - 3.11 - - - - - + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.core + jackson-annotations + + + com.fasterxml.jackson.core + jackson-core + + + org.slf4j + slf4j-api + + + org.apache.commons + commons-lang3 + com.networknt json-schema-validator - 1.0.76 org.opengis.cite.teamengine teamengine-spi - 5.5.2 org.opengis.cite schema-utils - - com.sun.jersey - jersey-client - junit junit @@ -107,29 +89,14 @@ org.mockito mockito-core + + org.glassfish.jersey.connectors + jersey-apache-connector + - - maven-javadoc-plugin - 2.10.4 - - true - package - - http://testng.org/javadocs/ - - - - - attach-javadocs - - jar - - - - maven-assembly-plugin @@ -153,66 +120,12 @@ - - maven-surefire-plugin - - - maven-compiler-plugin - - - maven-jar-plugin - - - maven-release-plugin - 2.5.3 - - true - @{project.version} - release - - - - org.apache.maven.plugins - maven-site-plugin - 3.7.1 - - - site-package - prepare-package - - jar - - - - - - org.asciidoctor - asciidoctor-maven-plugin - 1.5.7.1 - - - - false - - - - org.codehaus.mojo - buildnumber-maven-plugin - - - maven-scm-publish-plugin - 1.1 - - gh-pages - - io.fabric8 docker-maven-plugin - 0.28.0 @@ -220,7 +133,7 @@ ${project.basedir}/src/docker - ${project.version}-teamengine-${docker.teamengine.version} + ${project.version}-teamengine-${teamengine.version} @@ -253,58 +166,11 @@ - - maven-dependency-plugin - 3.0.0 - - - - 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 - - - - - - integration-tests - - - - maven-failsafe-plugin - 2.22.0 - - - - integration-test - verify - - - - - - - docker @@ -340,32 +206,6 @@ - - release - - - - maven-gpg-plugin - 1.6 - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - - - - From 070d77b10d7ea590fc390d6361cf72a3ef7533dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Pro=C3=9F?= Date: Tue, 17 Dec 2024 14:34:58 +0100 Subject: [PATCH 2/8] Adjust code --- .../opengis/cite/geopose10/CommonFixture.java | 20 +- .../org/opengis/cite/geopose10/ETSAssert.java | 7 +- .../cite/geopose10/ReusableEntityFilter.java | 26 +-- .../cite/geopose10/SuiteAttribute.java | 4 +- .../cite/geopose10/SuiteFixtureListener.java | 4 +- .../cite/geopose10/SuitePreconditions.java | 21 +- .../cite/geopose10/TestFailureListener.java | 16 +- .../cite/geopose10/util/ClientUtils.java | 197 ++++++++---------- .../opengis/cite/geopose10/util/URIUtils.java | 55 ++--- 9 files changed, 172 insertions(+), 178 deletions(-) diff --git a/src/main/java/org/opengis/cite/geopose10/CommonFixture.java b/src/main/java/org/opengis/cite/geopose10/CommonFixture.java index 9aca649..6864747 100644 --- a/src/main/java/org/opengis/cite/geopose10/CommonFixture.java +++ b/src/main/java/org/opengis/cite/geopose10/CommonFixture.java @@ -1,18 +1,20 @@ package org.opengis.cite.geopose10; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; import java.net.URI; import java.util.Map; -import javax.ws.rs.core.MediaType; + +import org.glassfish.jersey.client.ClientRequest; +import org.glassfish.jersey.client.ClientResponse; import org.opengis.cite.geopose10.util.ClientUtils; import org.testng.ITestContext; -import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.w3c.dom.Document; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + /** * A supporting base class that sets up a common test fixture. These * configuration methods are invoked before those defined in a subclass. @@ -34,7 +36,7 @@ public class CommonFixture { /** * An HTTP response message. */ - protected ClientResponse response; + protected Response response; /** * Initializes the common test fixture with a client component for @@ -70,7 +72,7 @@ public void clearMessages() { * * @see ClientUtils#getResponseEntityAsDocument */ - public Document getResponseEntityAsDocument(ClientResponse response, + public Document getResponseEntityAsDocument(Response response, String targetURI) { return ClientUtils.getResponseEntityAsDocument(response, targetURI); } @@ -84,11 +86,11 @@ public Document getResponseEntityAsDocument(ClientResponse response, * @param qryParams A Map containing query parameters (may be null); * @param mediaTypes A list of acceptable media types; if not specified, * generic XML ("application/xml") is preferred. - * @return A ClientRequest object. + * @return A Response object. * * @see ClientUtils#buildGetRequest */ - public ClientRequest buildGetRequest(URI endpoint, + public Response buildGetRequest(URI endpoint, Map qryParams, MediaType... mediaTypes) { return ClientUtils.buildGetRequest(endpoint, qryParams, mediaTypes); } diff --git a/src/main/java/org/opengis/cite/geopose10/ETSAssert.java b/src/main/java/org/opengis/cite/geopose10/ETSAssert.java index 117c4e9..652e35e 100644 --- a/src/main/java/org/opengis/cite/geopose10/ETSAssert.java +++ b/src/main/java/org/opengis/cite/geopose10/ETSAssert.java @@ -15,6 +15,7 @@ import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; +import org.glassfish.jersey.client.ClientResponse; import org.opengis.cite.geopose10.util.NamespaceBindings; import org.opengis.cite.geopose10.util.XMLUtils; import org.opengis.cite.validation.SchematronValidator; @@ -25,7 +26,7 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import com.sun.jersey.api.client.ClientResponse; +import jakarta.ws.rs.core.Response.Status; /** * Provides a set of custom assertion methods. @@ -189,9 +190,9 @@ public static void assertDescendantElementCount(Document xmlEntity, QName elemen * will be ignored if the argument is null or empty. */ public static void assertExceptionReport(ClientResponse rsp, String exceptionCode, String locator) { - Assert.assertEquals(rsp.getStatus(), ClientResponse.Status.BAD_REQUEST.getStatusCode(), + Assert.assertEquals(rsp.getStatus(), Status.BAD_REQUEST.getStatusCode(), ErrorMessage.get(ErrorMessageKeys.UNEXPECTED_STATUS)); - Document doc = rsp.getEntity(Document.class); + Document doc = rsp.readEntity(Document.class); String expr = String.format("//ows:Exception[@exceptionCode = '%s']", exceptionCode); NodeList nodeList = null; try { diff --git a/src/main/java/org/opengis/cite/geopose10/ReusableEntityFilter.java b/src/main/java/org/opengis/cite/geopose10/ReusableEntityFilter.java index d6934de..6c88e9b 100644 --- a/src/main/java/org/opengis/cite/geopose10/ReusableEntityFilter.java +++ b/src/main/java/org/opengis/cite/geopose10/ReusableEntityFilter.java @@ -1,9 +1,12 @@ package org.opengis.cite.geopose10; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.filter.ClientFilter; +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. @@ -11,16 +14,15 @@ *

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

*/ -public class ReusableEntityFilter extends ClientFilter { +public class ReusableEntityFilter implements ClientResponseFilter { + /** {@inheritDoc} */ @Override - public ClientResponse handle(ClientRequest req) throws ClientHandlerException { - // leave request entity--it can usually be read multiple times - ClientResponse rsp = getNext().handle(req); - if (rsp.hasEntity()) { - rsp.bufferEntity(); - } - return rsp; + 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/geopose10/SuiteAttribute.java b/src/main/java/org/opengis/cite/geopose10/SuiteAttribute.java index 9439421..4b4f536 100644 --- a/src/main/java/org/opengis/cite/geopose10/SuiteAttribute.java +++ b/src/main/java/org/opengis/cite/geopose10/SuiteAttribute.java @@ -1,11 +1,11 @@ package org.opengis.cite.geopose10; -import com.sun.jersey.api.client.Client; - import java.io.File; import org.w3c.dom.Document; +import jakarta.ws.rs.client.Client; + /** * An enumerated type defining ISuite attributes that may be set to constitute a * shared test fixture. diff --git a/src/main/java/org/opengis/cite/geopose10/SuiteFixtureListener.java b/src/main/java/org/opengis/cite/geopose10/SuiteFixtureListener.java index 6a30a68..8cfa5fb 100644 --- a/src/main/java/org/opengis/cite/geopose10/SuiteFixtureListener.java +++ b/src/main/java/org/opengis/cite/geopose10/SuiteFixtureListener.java @@ -9,12 +9,10 @@ import org.opengis.cite.geopose10.util.ClientUtils; import org.opengis.cite.geopose10.util.TestSuiteLogger; import org.opengis.cite.geopose10.util.URIUtils; -import org.opengis.cite.geopose10.util.XMLUtils; import org.testng.ISuite; import org.testng.ISuiteListener; -import org.w3c.dom.Document; -import com.sun.jersey.api.client.Client; +import jakarta.ws.rs.client.Client; /** * A listener that performs various tasks before and after a test suite is run, diff --git a/src/main/java/org/opengis/cite/geopose10/SuitePreconditions.java b/src/main/java/org/opengis/cite/geopose10/SuitePreconditions.java index 6f87e5c..f30161d 100644 --- a/src/main/java/org/opengis/cite/geopose10/SuitePreconditions.java +++ b/src/main/java/org/opengis/cite/geopose10/SuitePreconditions.java @@ -3,7 +3,7 @@ import java.util.logging.Level; import java.util.logging.Logger; -import org.testng.ITestContext; +import org.testng.Reporter; import org.testng.annotations.BeforeSuite; /** @@ -18,12 +18,25 @@ public class SuitePreconditions { * Verifies that the referenced test subject exists and has the expected * type. * - * @param testContext - * Information about the (pending) test run. */ @BeforeSuite @SuppressWarnings("rawtypes") - public void verifyTestSubject(ITestContext testContext) { + public void verifyTestSubject() { + SuiteAttribute testFileAttr = SuiteAttribute.TEST_SUBJ_FILE; + Object sutObj = Reporter.getCurrentTestResult() + .getTestContext() + .getSuite() + .getAttribute(testFileAttr.getName()); + Class expectedType = testFileAttr.getType(); + if (null != sutObj && expectedType.isInstance(sutObj)) { + // TODO: Verify test subject + } + else { + String msg = String.format("Value of test suite attribute '%s' is missing or is not an instance of %s", + testFileAttr.getName(), expectedType.getName()); + LOGR.log(Level.SEVERE, msg); + throw new AssertionError(msg); + } } } diff --git a/src/main/java/org/opengis/cite/geopose10/TestFailureListener.java b/src/main/java/org/opengis/cite/geopose10/TestFailureListener.java index 2e66ddc..6f4c6db 100644 --- a/src/main/java/org/opengis/cite/geopose10/TestFailureListener.java +++ b/src/main/java/org/opengis/cite/geopose10/TestFailureListener.java @@ -1,15 +1,17 @@ package org.opengis.cite.geopose10; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; import java.nio.charset.StandardCharsets; -import javax.ws.rs.core.MediaType; + +import org.glassfish.jersey.client.ClientRequest; import org.opengis.cite.geopose10.util.ClientUtils; import org.opengis.cite.geopose10.util.XMLUtils; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.w3c.dom.Document; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + /** * A listener that augments a test result with diagnostic information in the * event that a test method failed. This information will appear in the XML @@ -51,7 +53,7 @@ String getRequestMessageInfo(ClientRequest req) { } StringBuilder msgInfo = new StringBuilder(); msgInfo.append("Method: ").append(req.getMethod()).append('\n'); - msgInfo.append("Target URI: ").append(req.getURI()).append('\n'); + msgInfo.append("Target URI: ").append(req.getUri()).append('\n'); msgInfo.append("Headers: ").append(req.getHeaders()).append('\n'); if (null != req.getEntity()) { Object entity = req.getEntity(); @@ -74,7 +76,7 @@ String getRequestMessageInfo(ClientRequest req) { * @return A string containing information gleaned from the response * message. */ - String getResponseMessageInfo(ClientResponse rsp) { + String getResponseMessageInfo(Response rsp) { if (null == rsp) { return "No response message."; } @@ -82,11 +84,11 @@ String getResponseMessageInfo(ClientResponse rsp) { msgInfo.append("Status: ").append(rsp.getStatus()).append('\n'); msgInfo.append("Headers: ").append(rsp.getHeaders()).append('\n'); if (rsp.hasEntity()) { - if (rsp.getType().isCompatible(MediaType.APPLICATION_XML_TYPE)) { + if (rsp.getMediaType().isCompatible(MediaType.APPLICATION_XML_TYPE)) { Document doc = ClientUtils.getResponseEntityAsDocument(rsp, null); msgInfo.append(XMLUtils.writeNodeToString(doc)); } else { - byte[] body = rsp.getEntity(byte[].class); + byte[] body = rsp.readEntity(byte[].class); msgInfo.append(new String(body, StandardCharsets.UTF_8)); } msgInfo.append('\n'); diff --git a/src/main/java/org/opengis/cite/geopose10/util/ClientUtils.java b/src/main/java/org/opengis/cite/geopose10/util/ClientUtils.java index c4baf84..4289a46 100644 --- a/src/main/java/org/opengis/cite/geopose10/util/ClientUtils.java +++ b/src/main/java/org/opengis/cite/geopose10/util/ClientUtils.java @@ -1,173 +1,144 @@ package org.opengis.cite.geopose10.util; -import java.io.IOException; -import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.SocketAddress; -import java.net.URL; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.client.filter.LoggingFilter; -import com.sun.jersey.client.urlconnection.HttpURLConnectionFactory; -import com.sun.jersey.client.urlconnection.URLConnectionClientHandler; import java.net.URI; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; -import javax.ws.rs.HttpMethod; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.UriBuilder; + import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; + +import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.logging.LoggingFeature; import org.opengis.cite.geopose10.ReusableEntityFilter; import org.w3c.dom.Document; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.client.Invocation.Builder; +import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriBuilder; + /** * Provides various utility methods for creating and configuring HTTP client * components. */ public class ClientUtils { + private static final Logger LOGGER = Logger.getLogger(ClientUtils.class.getName()); + /** - * 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"). - * + * 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 DefaultClientConfig(); - config.getProperties().put( - ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); - config.getProperties().put( - ClientConfig.PROPERTY_CONNECT_TIMEOUT, 10000); - Client client = Client.create(config); - client.addFilter(new ReusableEntityFilter()); - client.addFilter(new LoggingFilter()); - return client; + ClientConfig config = new ClientConfig(); + config.property(ClientProperties.FOLLOW_REDIRECTS, true); + config.property(ClientProperties.CONNECT_TIMEOUT, 10000); + config.register(new LoggingFeature(LOGGER, Level.ALL, LoggingFeature.Verbosity.PAYLOAD_ANY, 5000)); + Client client = ClientBuilder.newClient(config); + client.register(new ReusableEntityFilter()); + return client; } /** - * Constructs a client component that uses a specified web proxy. Proxy - * authentication is not supported. Configuring the client to use an - * intercepting proxy can be useful when debugging a test. - * + * Constructs a client component that uses a specified web proxy. Proxy authentication + * is not supported. Configuring the client to use an intercepting proxy can be useful + * when debugging a test. * @param proxyHost The host name or IP address of the proxy server. * @param proxyPort The port number of the proxy listener. - * * @return A Client component that submits requests through a web proxy. */ - public static Client buildClientWithProxy(final String proxyHost, - final int proxyPort) { - ClientConfig config = new DefaultClientConfig(); - config.getProperties().put( - ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); - Client client = new Client(new URLConnectionClientHandler( - new HttpURLConnectionFactory() { - SocketAddress addr = new InetSocketAddress(proxyHost, proxyPort); - Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); - - @Override - public HttpURLConnection getHttpURLConnection(URL url) throws IOException { - return (HttpURLConnection) url.openConnection(proxy); - } - }), config); - client.addFilter(new LoggingFilter()); - return client; + public static Client buildClientWithProxy(final String proxyHost, final int proxyPort) { + ClientConfig config = new ClientConfig(); + config.connectorProvider(new ApacheConnectorProvider()); + config.register(new LoggingFeature(LOGGER, Level.ALL, LoggingFeature.Verbosity.PAYLOAD_ANY, 5000)); + SocketAddress addr = new InetSocketAddress(proxyHost, proxyPort); + Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); + config.property(ClientProperties.PROXY_URI, proxy); + config.property(ClientProperties.FOLLOW_REDIRECTS, true); + config.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY_CLIENT, LoggingFeature.Verbosity.PAYLOAD_ANY); + config.property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_CLIENT, Level.ALL); + Client client = ClientBuilder.newClient(config); + client.register(new ReusableEntityFilter()); + return client; } /** * Builds an HTTP request message that uses the GET method. - * * @param endpoint A URI indicating the target resource. * @param qryParams A Map containing query parameters (may be null); - * @param mediaTypes A list of acceptable media types; if not specified, - * generic XML ("application/xml") is preferred. - * + * @param mediaTypes A list of acceptable media types; if not specified, the Accept + * header is omitted. * @return A ClientRequest object. */ - public static ClientRequest buildGetRequest(URI endpoint, - Map qryParams, MediaType... mediaTypes) { - UriBuilder uriBuilder = UriBuilder.fromUri(endpoint); - if (null != qryParams) { - for (Map.Entry param : qryParams.entrySet()) { - uriBuilder.queryParam(param.getKey(), param.getValue()); + public static Response buildGetRequest(URI endpoint, Map qryParams, MediaType... mediaTypes) { + UriBuilder uriBuilder = UriBuilder.fromUri(endpoint); + if (null != qryParams) { + for (Map.Entry param : qryParams.entrySet()) { + uriBuilder.queryParam(param.getKey(), param.getValue()); + } + } + URI uri = uriBuilder.build(); + WebTarget target = buildClient().target(uri); + Builder reqBuilder = target.request(); + if (null != mediaTypes && mediaTypes.length > 0) { + reqBuilder = reqBuilder.accept(mediaTypes); } - } - URI uri = uriBuilder.build(); - ClientRequest.Builder reqBuilder = ClientRequest.create(); - if (null == mediaTypes || mediaTypes.length == 0) { - reqBuilder = reqBuilder.accept(MediaType.APPLICATION_XML_TYPE); - } else { - reqBuilder = reqBuilder.accept(mediaTypes); - } - ClientRequest req = reqBuilder.build(uri, HttpMethod.GET); - return req; + Invocation req = reqBuilder.buildGet(); + return req.invoke(); } /** * Creates a copy of the given MediaType object but without any parameters. - * * @param mediaType A MediaType descriptor. - * @return A new (immutable) MediaType object having the same type and - * subtype. + * @return A new (immutable) MediaType object having the same type and subtype. */ public static MediaType removeParameters(MediaType mediaType) { - return new MediaType(mediaType.getType(), mediaType.getSubtype()); + return new MediaType(mediaType.getType(), mediaType.getSubtype()); } /** - * Obtains the (XML) response entity as a JAXP Source object and resets the - * entity input stream for subsequent reads. - * + * Obtains the (XML) response entity as a JAXP Source object 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 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 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). */ - public static Source getResponseEntityAsSource(ClientResponse response, - String targetURI) { - Source source = response.getEntity(DOMSource.class); - if (null != targetURI && !targetURI.isEmpty()) { - source.setSystemId(targetURI); - } - if (response.getEntityInputStream().markSupported()) { - try { - // NOTE: entity was buffered by client filter - response.getEntityInputStream().reset(); - } catch (IOException ex) { - Logger.getLogger(ClientUtils.class.getName()).log(Level.WARNING, - "Failed to reset response entity.", ex); + public static Source getResponseEntityAsSource(Response response, String targetURI) { + Source source = response.readEntity(DOMSource.class); + if (null != targetURI && !targetURI.isEmpty()) { + source.setSystemId(targetURI); } - } - return source; + return source; } /** - * Obtains the (XML) response entity as a DOM Document and resets the entity - * input stream for subsequent reads. - * + * 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). + * @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(ClientResponse response, - String targetURI) { - DOMSource domSource = (DOMSource) getResponseEntityAsSource(response, - targetURI); - Document entityDoc = (Document) domSource.getNode(); - entityDoc.setDocumentURI(domSource.getSystemId()); - return entityDoc; + 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/geopose10/util/URIUtils.java b/src/main/java/org/opengis/cite/geopose10/util/URIUtils.java index 83ecdd6..f2745b4 100644 --- a/src/main/java/org/opengis/cite/geopose10/util/URIUtils.java +++ b/src/main/java/org/opengis/cite/geopose10/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,9 +15,11 @@ 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.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 @@ -82,36 +83,40 @@ public static Document parseURI(URI uriRef) throws SAXException, */ public static File dereferenceURI(URI uriRef) throws IOException { if ((null == uriRef) || !uriRef.isAbsolute()) { - throw new IllegalArgumentException( - "Absolute URI is required, but received " + uriRef); + throw new IllegalArgumentException("Absolute URI is required, but received " + uriRef); } if (uriRef.getScheme().equalsIgnoreCase("file")) { - return new File(uriRef); + return new File(uriRef); } - Client client = Client.create(); - WebResource webRes = client.resource(uriRef); - ClientResponse rsp = webRes.get(ClientResponse.class); + 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).endsWith("xml")) { - suffix = ".xml"; + if (rsp.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE).toString().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(); + 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()); + 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. From 43b28eae771edb5205b9d09e72049e9a7c69e8ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Pro=C3=9F?= Date: Tue, 17 Dec 2024 15:03:43 +0100 Subject: [PATCH 3/8] Formatting, javadoc --- .../BaseJsonSchemaValidatorTest.java | 199 ++++-- .../cite/geopose10/CommandLineArguments.java | 93 ++- .../opengis/cite/geopose10/CommonFixture.java | 140 ++-- .../org/opengis/cite/geopose10/ETSAssert.java | 317 ++++----- .../opengis/cite/geopose10/ErrorMessage.java | 67 +- .../cite/geopose10/ErrorMessageKeys.java | 52 +- .../opengis/cite/geopose10/Namespaces.java | 40 +- .../cite/geopose10/ReusableEntityFilter.java | 20 +- .../cite/geopose10/SuiteAttribute.java | 131 ++-- .../cite/geopose10/SuiteFixtureListener.java | 463 +++++++------ .../cite/geopose10/SuitePreconditions.java | 55 +- .../cite/geopose10/TestFailureListener.java | 152 ++-- .../cite/geopose10/TestNGController.java | 274 ++++---- .../opengis/cite/geopose10/TestRunArg.java | 72 +- .../cite/geopose10/TestRunListener.java | 30 +- .../geopose10/encodings/json/Advanced.java | 147 ++-- .../encodings/json/BasicQuaternion.java | 154 ++--- .../geopose10/encodings/json/BasicYPR.java | 147 ++-- .../cite/geopose10/encodings/json/Chain.java | 147 ++-- .../cite/geopose10/encodings/json/Graph.java | 147 ++-- .../encodings/json/SeriesRegular.java | 147 ++-- .../encodings/json/StreamElement.java | 148 ++-- .../encodings/json/StreamHeader.java | 147 ++-- .../encodings/json/StreamRecord.java | 148 ++-- .../opengis/cite/geopose10/package-info.java | 11 +- .../cite/geopose10/util/ClientUtils.java | 208 +++--- .../geopose10/util/NamespaceBindings.java | 157 ++--- .../opengis/cite/geopose10/util/Samples.java | 98 ++- .../cite/geopose10/util/TestSuiteLogger.java | 107 ++- .../opengis/cite/geopose10/util/URIUtils.java | 205 +++--- .../cite/geopose10/util/ValidationUtils.java | 236 +++---- .../opengis/cite/geopose10/util/XMLUtils.java | 647 +++++++++--------- .../cite/geopose10/VerifyETSAssert.java | 88 +-- .../cite/geopose10/util/VerifyURIUtils.java | 105 ++- .../geopose10/util/VerifyValidationUtils.java | 41 +- .../cite/geopose10/util/VerifyXMLUtils.java | 224 +++--- 36 files changed, 2825 insertions(+), 2739 deletions(-) diff --git a/src/main/java/org/opengis/cite/geopose10/BaseJsonSchemaValidatorTest.java b/src/main/java/org/opengis/cite/geopose10/BaseJsonSchemaValidatorTest.java index 670794e..c603d40 100644 --- a/src/main/java/org/opengis/cite/geopose10/BaseJsonSchemaValidatorTest.java +++ b/src/main/java/org/opengis/cite/geopose10/BaseJsonSchemaValidatorTest.java @@ -14,67 +14,144 @@ import com.networknt.schema.SpecVersion; import com.networknt.schema.SpecVersionDetector; +/** + *

+ * BaseJsonSchemaValidatorTest class. + *

+ * + */ public class BaseJsonSchemaValidatorTest { + + /** + * int DEFAULT_BUFFER_SIZE = 8192 + */ public final int DEFAULT_BUFFER_SIZE = 8192; - private ObjectMapper mapper = new ObjectMapper(); - - //from https://github.com/networknt/json-schema-validator/blob/master/doc/quickstart.md - - public JsonNode getJsonNodeFromClasspath(String name) throws IOException { - InputStream is1 = Thread.currentThread().getContextClassLoader() - .getResourceAsStream(name); - return mapper.readTree(is1); - } - - public JsonNode getJsonNodeFromStringContent(String content) throws IOException { - return mapper.readTree(content); - } - - public JsonNode getJsonNodeFromUrl(String url) throws IOException { - return mapper.readTree(new URL(url)); - } - - public JsonSchema getJsonSchemaFromClasspath(String name) { - JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4); - InputStream is = Thread.currentThread().getContextClassLoader() - .getResourceAsStream(name); - return factory.getSchema(is); - } - - public JsonSchema getJsonSchemaFromStringContent(String schemaContent) { - JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4); - return factory.getSchema(schemaContent); - } - - public JsonSchema getJsonSchemaFromUrl(String uri) throws URISyntaxException { - JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4); - return factory.getSchema(new URI(uri)); - } - - public JsonSchema getJsonSchemaFromJsonNode(JsonNode jsonNode) { - JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4); - return factory.getSchema(jsonNode); - } - - // Automatically detect version for given JsonNode - public JsonSchema getJsonSchemaFromJsonNodeAutomaticVersion(JsonNode jsonNode) { - JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersionDetector.detect(jsonNode)); - return factory.getSchema(jsonNode); - } - // from https://mkyong.com/java/how-to-convert-inputstream-to-string-in-java/ - public String otherConvertInputStreamToString(InputStream is) throws IOException { - - ByteArrayOutputStream result = new ByteArrayOutputStream(); - byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; - int length; - while ((length = is.read(buffer)) != -1) { - result.write(buffer, 0, length); - } - - - - return result.toString("UTF-8"); - - - } + + private ObjectMapper mapper = new ObjectMapper(); + + // from + // https://github.com/networknt/json-schema-validator/blob/master/doc/quickstart.md + + /** + *

+ * getJsonNodeFromClasspath. + *

+ * @param name a {@link java.lang.String} object + * @return a {@link com.fasterxml.jackson.databind.JsonNode} object + * @throws java.io.IOException if any. + */ + public JsonNode getJsonNodeFromClasspath(String name) throws IOException { + InputStream is1 = Thread.currentThread().getContextClassLoader().getResourceAsStream(name); + return mapper.readTree(is1); + } + + /** + *

+ * getJsonNodeFromStringContent. + *

+ * @param content a {@link java.lang.String} object + * @return a {@link com.fasterxml.jackson.databind.JsonNode} object + * @throws java.io.IOException if any. + */ + public JsonNode getJsonNodeFromStringContent(String content) throws IOException { + return mapper.readTree(content); + } + + /** + *

+ * getJsonNodeFromUrl. + *

+ * @param url a {@link java.lang.String} object + * @return a {@link com.fasterxml.jackson.databind.JsonNode} object + * @throws java.io.IOException if any. + */ + public JsonNode getJsonNodeFromUrl(String url) throws IOException { + return mapper.readTree(new URL(url)); + } + + /** + *

+ * getJsonSchemaFromClasspath. + *

+ * @param name a {@link java.lang.String} object + * @return a {@link com.networknt.schema.JsonSchema} object + */ + public JsonSchema getJsonSchemaFromClasspath(String name) { + JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4); + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(name); + return factory.getSchema(is); + } + + /** + *

+ * getJsonSchemaFromStringContent. + *

+ * @param schemaContent a {@link java.lang.String} object + * @return a {@link com.networknt.schema.JsonSchema} object + */ + public JsonSchema getJsonSchemaFromStringContent(String schemaContent) { + JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4); + return factory.getSchema(schemaContent); + } + + /** + *

+ * getJsonSchemaFromUrl. + *

+ * @param uri a {@link java.lang.String} object + * @return a {@link com.networknt.schema.JsonSchema} object + * @throws java.net.URISyntaxException if any. + */ + public JsonSchema getJsonSchemaFromUrl(String uri) throws URISyntaxException { + JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4); + return factory.getSchema(new URI(uri)); + } + + /** + *

+ * getJsonSchemaFromJsonNode. + *

+ * @param jsonNode a {@link com.fasterxml.jackson.databind.JsonNode} object + * @return a {@link com.networknt.schema.JsonSchema} object + */ + public JsonSchema getJsonSchemaFromJsonNode(JsonNode jsonNode) { + JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4); + return factory.getSchema(jsonNode); + } + + // Automatically detect version for given JsonNode + /** + *

+ * getJsonSchemaFromJsonNodeAutomaticVersion. + *

+ * @param jsonNode a {@link com.fasterxml.jackson.databind.JsonNode} object + * @return a {@link com.networknt.schema.JsonSchema} object + */ + public JsonSchema getJsonSchemaFromJsonNodeAutomaticVersion(JsonNode jsonNode) { + JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersionDetector.detect(jsonNode)); + return factory.getSchema(jsonNode); + } + + // from https://mkyong.com/java/how-to-convert-inputstream-to-string-in-java/ + /** + *

+ * otherConvertInputStreamToString. + *

+ * @param is a {@link java.io.InputStream} object + * @return a {@link java.lang.String} object + * @throws java.io.IOException if any. + */ + public String otherConvertInputStreamToString(InputStream is) throws IOException { + + ByteArrayOutputStream result = new ByteArrayOutputStream(); + byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; + int length; + while ((length = is.read(buffer)) != -1) { + result.write(buffer, 0, length); + } + + return result.toString("UTF-8"); + + } + } diff --git a/src/main/java/org/opengis/cite/geopose10/CommandLineArguments.java b/src/main/java/org/opengis/cite/geopose10/CommandLineArguments.java index a8e0cad..93f8327 100644 --- a/src/main/java/org/opengis/cite/geopose10/CommandLineArguments.java +++ b/src/main/java/org/opengis/cite/geopose10/CommandLineArguments.java @@ -7,9 +7,8 @@ import java.util.List; /** - * Declares supported command line arguments that are parsed using the - * JCommander library. All arguments are optional. The default values are as - * follows: + * Declares supported command line arguments that are parsed using the JCommander library. + * All arguments are optional. The default values are as follows: *
    *
  • XML properties file: ${user.home}/test-run-props.xml
  • *
  • outputDir: ${user.home}
  • @@ -26,35 +25,61 @@ */ public class CommandLineArguments { - @Parameter(description = "Properties file") - private final List xmlProps; - - @Parameter(names = {"-o", "--outputDir"}, description = "Output directory") - private String outputDir; - - @Parameter(names = {"-d", "--deleteSubjectOnFinish"}, description = "Delete file containing representation of test subject when finished") - private boolean deleteSubjectOnFinish = false; - - public CommandLineArguments() { - this.xmlProps = new ArrayList<>(); - } - - public File getPropertiesFile() { - File fileRef; - if (xmlProps.isEmpty()) { - fileRef = new File(System.getProperty("user.home"), "test-run-props.xml"); - } else { - String propsFile = xmlProps.get(0); - fileRef = (propsFile.startsWith("file:")) ? new File(URI.create(propsFile)) : new File(propsFile); - } - return fileRef; - } - - public String getOutputDir() { - return (null != outputDir) ? outputDir : System.getProperty("user.home"); - } - - public boolean doDeleteSubjectOnFinish() { - return deleteSubjectOnFinish; - } + @Parameter(description = "Properties file") + private final List xmlProps; + + @Parameter(names = { "-o", "--outputDir" }, description = "Output directory") + private String outputDir; + + @Parameter(names = { "-d", "--deleteSubjectOnFinish" }, + description = "Delete file containing representation of test subject when finished") + private boolean deleteSubjectOnFinish = false; + + /** + *

    + * Constructor for CommandLineArguments. + *

    + */ + public CommandLineArguments() { + this.xmlProps = new ArrayList<>(); + } + + /** + *

    + * getPropertiesFile. + *

    + * @return a {@link java.io.File} object + */ + public File getPropertiesFile() { + File fileRef; + if (xmlProps.isEmpty()) { + fileRef = new File(System.getProperty("user.home"), "test-run-props.xml"); + } + else { + String propsFile = xmlProps.get(0); + fileRef = (propsFile.startsWith("file:")) ? new File(URI.create(propsFile)) : new File(propsFile); + } + return fileRef; + } + + /** + *

    + * Getter for the field outputDir. + *

    + * @return a {@link java.lang.String} object + */ + public String getOutputDir() { + return (null != outputDir) ? outputDir : System.getProperty("user.home"); + } + + /** + *

    + * doDeleteSubjectOnFinish. + *

    + * @return a boolean + */ + public boolean doDeleteSubjectOnFinish() { + return deleteSubjectOnFinish; + } + } diff --git a/src/main/java/org/opengis/cite/geopose10/CommonFixture.java b/src/main/java/org/opengis/cite/geopose10/CommonFixture.java index 6864747..80c59ed 100644 --- a/src/main/java/org/opengis/cite/geopose10/CommonFixture.java +++ b/src/main/java/org/opengis/cite/geopose10/CommonFixture.java @@ -16,83 +16,81 @@ import jakarta.ws.rs.core.Response; /** - * A supporting base class that sets up a common test fixture. These - * configuration methods are invoked before those defined in a subclass. + * A supporting base class that sets up a common test fixture. These configuration methods + * are invoked before those defined in a subclass. */ public class CommonFixture { - /** - * Root test suite package (absolute path). - */ - public static final String ROOT_PKG_PATH = "/org/opengis/cite/geopose10/"; - /** - * HTTP client component (JAX-RS Client API). - */ - protected Client client; - /** - * An HTTP request message. - */ - protected ClientRequest request; - /** - * An HTTP response message. - */ - protected Response response; + /** + * Root test suite package (absolute path). + */ + public static final String ROOT_PKG_PATH = "/org/opengis/cite/geopose10/"; - /** - * Initializes the common test fixture with a client component for - * interacting with HTTP endpoints. - * - * @param testContext The test context that contains all the information for - * a test run, including suite attributes. - */ - @BeforeClass - public void initCommonFixture(ITestContext testContext) { - Object obj = testContext.getSuite().getAttribute(SuiteAttribute.CLIENT.getName()); - if (null != obj) { - this.client = Client.class.cast(obj); - } - - } + /** + * HTTP client component (JAX-RS Client API). + */ + protected Client client; - @BeforeMethod - public void clearMessages() { - this.request = null; - this.response = null; - } + /** + * An HTTP request message. + */ + protected ClientRequest request; - /** - * Obtains the (XML) response entity as a DOM Document. This convenience - * method wraps a static method call to facilitate unit testing (Mockito - * workaround). - * - * @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. - * - * @see ClientUtils#getResponseEntityAsDocument - */ - public Document getResponseEntityAsDocument(Response response, - String targetURI) { - return ClientUtils.getResponseEntityAsDocument(response, targetURI); - } + /** + * An HTTP response message. + */ + protected Response response; - /** - * Builds an HTTP request message that uses the GET method. This convenience - * method wraps a static method call to facilitate unit testing (Mockito - * workaround). - * - * @param endpoint A URI indicating the target resource. - * @param qryParams A Map containing query parameters (may be null); - * @param mediaTypes A list of acceptable media types; if not specified, - * generic XML ("application/xml") is preferred. - * @return A Response object. - * - * @see ClientUtils#buildGetRequest - */ - public Response buildGetRequest(URI endpoint, - Map qryParams, MediaType... mediaTypes) { - return ClientUtils.buildGetRequest(endpoint, qryParams, mediaTypes); - } + /** + * Initializes the common test fixture with a client component for interacting with + * HTTP endpoints. + * @param testContext The test context that contains all the information for a test + * run, including suite attributes. + */ + @BeforeClass + public void initCommonFixture(ITestContext testContext) { + Object obj = testContext.getSuite().getAttribute(SuiteAttribute.CLIENT.getName()); + if (null != obj) { + this.client = Client.class.cast(obj); + } + + } + + /** + *

    + * clearMessages. + *

    + */ + @BeforeMethod + public void clearMessages() { + this.request = null; + this.response = null; + } + + /** + * Obtains the (XML) response entity as a DOM Document. This convenience method wraps + * a static method call to facilitate unit testing (Mockito workaround). + * @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. + * @see ClientUtils#getResponseEntityAsDocument + */ + public Document getResponseEntityAsDocument(Response response, String targetURI) { + return ClientUtils.getResponseEntityAsDocument(response, targetURI); + } + + /** + * Builds an HTTP request message that uses the GET method. This convenience method + * wraps a static method call to facilitate unit testing (Mockito workaround). + * @param endpoint A URI indicating the target resource. + * @param qryParams A Map containing query parameters (may be null); + * @param mediaTypes A list of acceptable media types; if not specified, generic XML + * ("application/xml") is preferred. + * @return A Response object. + * @see ClientUtils#buildGetRequest + */ + public Response buildGetRequest(URI endpoint, Map qryParams, MediaType... mediaTypes) { + return ClientUtils.buildGetRequest(endpoint, qryParams, mediaTypes); + } } diff --git a/src/main/java/org/opengis/cite/geopose10/ETSAssert.java b/src/main/java/org/opengis/cite/geopose10/ETSAssert.java index 652e35e..253f5cb 100644 --- a/src/main/java/org/opengis/cite/geopose10/ETSAssert.java +++ b/src/main/java/org/opengis/cite/geopose10/ETSAssert.java @@ -33,179 +33,160 @@ */ public class ETSAssert { - private static final Logger LOGR = Logger.getLogger(ETSAssert.class.getPackage().getName()); + private static final Logger LOGR = Logger.getLogger(ETSAssert.class.getPackage().getName()); - 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.geopose10.Namespaces#OWS}
    • - *
    • xlink: {@value org.opengis.cite.geopose10.Namespaces#XLINK}
    • - *
    • gml: {@value org.opengis.cite.geopose10.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); - LOGR.log(Level.WARNING, msg, xpe); - throw new AssertionError(msg); - } - Element elemNode; - if (Document.class.isInstance(context)) { - elemNode = Document.class.cast(context).getDocumentElement(); - } else { - elemNode = (Element) context; - } - Assert.assertTrue(result, ErrorMessage.format(ErrorMessageKeys.XPATH_RESULT, elemNode.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.geopose10.Namespaces#OWS}
    • + *
    • xlink: {@value org.opengis.cite.geopose10.Namespaces#XLINK}
    • + *
    • gml: {@value org.opengis.cite.geopose10.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); + LOGR.log(Level.WARNING, msg, xpe); + throw new AssertionError(msg); + } + Element elemNode; + if (Document.class.isInstance(context)) { + elemNode = Document.class.cast(context).getDocumentElement(); + } + else { + elemNode = (Element) context; + } + Assert.assertTrue(result, ErrorMessage.format(ErrorMessageKeys.XPATH_RESULT, elemNode.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 defined - * for the specified phase in a Schematron (ISO 19757-3) schema. The "xslt2" - * query language binding is supported. Two phase names have special - * meanings: - *
      - *
    • "#ALL": All patterns are active
    • - *
    • "#DEFAULT": The phase identified by the defaultPhase attribute on the - * schema element should be used.
    • - *
    - * - * @param schemaRef - * A URL that denotes the location of a Schematron schema. - * @param xmlSource - * The XML Source to be validated. - * @param activePhase - * The active phase (pattern set) whose patterns are used for - * validation; this is set to "#ALL" if not specified. - */ - public static void assertSchematronValid(URL schemaRef, Source xmlSource, String activePhase) { - String phase = (null == activePhase || activePhase.isEmpty()) ? "#ALL" : activePhase; - SchematronValidator validator; - try { - validator = new SchematronValidator(new StreamSource(schemaRef.toString()), phase); - } 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()))); - } + /** + * Asserts that an XML resource satisfies all applicable constraints defined for the + * specified phase in a Schematron (ISO 19757-3) schema. The "xslt2" query language + * binding is supported. Two phase names have special meanings: + *
      + *
    • "#ALL": All patterns are active
    • + *
    • "#DEFAULT": The phase identified by the defaultPhase attribute on the schema + * element should be used.
    • + *
    + * @param schemaRef A URL that denotes the location of a Schematron schema. + * @param xmlSource The XML Source to be validated. + * @param activePhase The active phase (pattern set) whose patterns are used for + * validation; this is set to "#ALL" if not specified. + */ + public static void assertSchematronValid(URL schemaRef, Source xmlSource, String activePhase) { + String phase = (null == activePhase || activePhase.isEmpty()) ? "#ALL" : activePhase; + SchematronValidator validator; + try { + validator = new SchematronValidator(new StreamSource(schemaRef.toString()), phase); + } + 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()))); + } - /** - * 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)); + } + + /** + * Asserts that the given response message contains an OGC exception report. The + * message body must contain an XML document that has a document element with the + * following properties: + * + *
      + *
    • [local name] = "ExceptionReport"
    • + *
    • [namespace name] = "http://www.opengis.net/ows/2.0"
    • + *
    + * @param rsp A ClientResponse object representing an HTTP response message. + * @param exceptionCode The expected OGC exception code. + * @param locator A case-insensitive string value expected to occur in the locator + * attribute (e.g. a parameter name); the attribute value will be ignored if the + * argument is null or empty. + */ + public static void assertExceptionReport(ClientResponse rsp, String exceptionCode, String locator) { + Assert.assertEquals(rsp.getStatus(), Status.BAD_REQUEST.getStatusCode(), + ErrorMessage.get(ErrorMessageKeys.UNEXPECTED_STATUS)); + Document doc = rsp.readEntity(Document.class); + String expr = String.format("//ows:Exception[@exceptionCode = '%s']", exceptionCode); + NodeList nodeList = null; + try { + nodeList = XMLUtils.evaluateXPath(doc, expr, null); + } + catch (XPathExpressionException xpe) { + // won't happen + } + Assert.assertTrue(nodeList.getLength() > 0, "Exception not found in response: " + expr); + if (null != locator && !locator.isEmpty()) { + Element exception = (Element) nodeList.item(0); + String locatorValue = exception.getAttribute("locator").toLowerCase(); + Assert.assertTrue(locatorValue.contains(locator.toLowerCase()), + String.format("Expected locator attribute to contain '%s']", locator)); + } + } - /** - * Asserts that the given response message contains an OGC exception report. - * The message body must contain an XML document that has a document element - * with the following properties: - * - *
      - *
    • [local name] = "ExceptionReport"
    • - *
    • [namespace name] = "http://www.opengis.net/ows/2.0"
    • - *
    - * - * @param rsp - * A ClientResponse object representing an HTTP response message. - * @param exceptionCode - * The expected OGC exception code. - * @param locator - * A case-insensitive string value expected to occur in the - * locator attribute (e.g. a parameter name); the attribute value - * will be ignored if the argument is null or empty. - */ - public static void assertExceptionReport(ClientResponse rsp, String exceptionCode, String locator) { - Assert.assertEquals(rsp.getStatus(), Status.BAD_REQUEST.getStatusCode(), - ErrorMessage.get(ErrorMessageKeys.UNEXPECTED_STATUS)); - Document doc = rsp.readEntity(Document.class); - String expr = String.format("//ows:Exception[@exceptionCode = '%s']", exceptionCode); - NodeList nodeList = null; - try { - nodeList = XMLUtils.evaluateXPath(doc, expr, null); - } catch (XPathExpressionException xpe) { - // won't happen - } - Assert.assertTrue(nodeList.getLength() > 0, "Exception not found in response: " + expr); - if (null != locator && !locator.isEmpty()) { - Element exception = (Element) nodeList.item(0); - String locatorValue = exception.getAttribute("locator").toLowerCase(); - Assert.assertTrue(locatorValue.contains(locator.toLowerCase()), - String.format("Expected locator attribute to contain '%s']", locator)); - } - } } diff --git a/src/main/java/org/opengis/cite/geopose10/ErrorMessage.java b/src/main/java/org/opengis/cite/geopose10/ErrorMessage.java index c3b9c8a..aaf6fcd 100644 --- a/src/main/java/org/opengis/cite/geopose10/ErrorMessage.java +++ b/src/main/java/org/opengis/cite/geopose10/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.geopose10.MessageBundle"; - private static ResourceBundle msgResources = - ResourceBundle.getBundle(BASE_NAME); + private static final String BASE_NAME = "org.opengis.cite.geopose10.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/geopose10/ErrorMessageKeys.java b/src/main/java/org/opengis/cite/geopose10/ErrorMessageKeys.java index e555104..0dbd41a 100644 --- a/src/main/java/org/opengis/cite/geopose10/ErrorMessageKeys.java +++ b/src/main/java/org/opengis/cite/geopose10/ErrorMessageKeys.java @@ -1,22 +1,44 @@ package org.opengis.cite.geopose10; /** - * 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/geopose10/Namespaces.java b/src/main/java/org/opengis/cite/geopose10/Namespaces.java index 47147c2..8eb8a4e 100644 --- a/src/main/java/org/opengis/cite/geopose10/Namespaces.java +++ b/src/main/java/org/opengis/cite/geopose10/Namespaces.java @@ -4,28 +4,30 @@ /** * XML namespace names. - * - * @see Namespaces in XML 1.0 * + * @see Namespaces in XML 1.0 */ public class Namespaces { - private Namespaces() { - } - - /** 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() { + } + + /** 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/geopose10/ReusableEntityFilter.java b/src/main/java/org/opengis/cite/geopose10/ReusableEntityFilter.java index 6c88e9b..005e67e 100644 --- a/src/main/java/org/opengis/cite/geopose10/ReusableEntityFilter.java +++ b/src/main/java/org/opengis/cite/geopose10/ReusableEntityFilter.java @@ -11,18 +11,18 @@ /** * Buffers the (response) entity so it can be read multiple times. * - *

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

    + *

    + * 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(); - } - } + /** {@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/geopose10/SuiteAttribute.java b/src/main/java/org/opengis/cite/geopose10/SuiteAttribute.java index 4b4f536..e6a84f2 100644 --- a/src/main/java/org/opengis/cite/geopose10/SuiteAttribute.java +++ b/src/main/java/org/opengis/cite/geopose10/SuiteAttribute.java @@ -7,54 +7,93 @@ import jakarta.ws.rs.client.Client; /** - * 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 { - /** - * A client component for interacting with HTTP endpoints. - */ - CLIENT("httpClient", Client.class), - /** - * A DOM Document that represents the test subject or metadata about it. - */ - TEST_SUBJECT("testSubject", Document.class), - /** - * A File containing the test subject or a description of it. - */ - TEST_SUBJ_FILE("testSubjectFile", File.class), - STREAMRECORD_TEST_SUBJ_FILE("streamRecordTestSubjectFile", File.class), - STREAMHEADER_TEST_SUBJ_FILE("streamHeaderTestSubjectFile", File.class), - STREAMELEMENT_TEST_SUBJ_FILE("streamElementTestSubjectFile", File.class), - SERIESREGULAR_TEST_SUBJ_FILE("seriesRegularTestSubjectFile", File.class), - GRAPH_TEST_SUBJ_FILE("graphTestSubjectFile", File.class), - CHAIN_TEST_SUBJ_FILE("chainTestSubjectFile", File.class), - ADVANCED_TEST_SUBJ_FILE("advancedTestSubjectFile", File.class), - BASICQUATERNION_TEST_SUBJ_FILE("basicQuaternionTestSubjectFile", File.class), - BASICYPR_TEST_SUBJ_FILE("basicYPRTestSubjectFile", File.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(); - } + /** + * A client component for interacting with HTTP endpoints. + */ + CLIENT("httpClient", Client.class), + /** + * A DOM Document that represents the test subject or metadata about it. + */ + TEST_SUBJECT("testSubject", Document.class), + /** + * A File containing the test subject or a description of it. + */ + TEST_SUBJ_FILE("testSubjectFile", File.class), + /** + * A File containing the test subject for streamRecord tests or a description of it. + */ + STREAMRECORD_TEST_SUBJ_FILE("streamRecordTestSubjectFile", File.class), + /** + * A File containing the test subject for streamHeader tests or a description of it. + */ + STREAMHEADER_TEST_SUBJ_FILE("streamHeaderTestSubjectFile", File.class), + /** + * A File containing the test subject for streamElement tests or a description of it. + */ + STREAMELEMENT_TEST_SUBJ_FILE("streamElementTestSubjectFile", File.class), + /** + * A File containing the test subject for seriesRegular tests or a description of it. + */ + SERIESREGULAR_TEST_SUBJ_FILE("seriesRegularTestSubjectFile", File.class), + /** + * A File containing the test subject for graph tests or a description of it. + */ + GRAPH_TEST_SUBJ_FILE("graphTestSubjectFile", File.class), CHAIN_TEST_SUBJ_FILE("chainTestSubjectFile", File.class), + /** + * A File containing the test subject for advanced tests or a description of it. + */ + ADVANCED_TEST_SUBJ_FILE("advancedTestSubjectFile", File.class), + /** + * A File containing the test subject for basicQuaternion tests or a description of + * it. + */ + BASICQUATERNION_TEST_SUBJ_FILE("basicQuaternionTestSubjectFile", File.class), + /** + * A File containing the test subject for basicYPR tests or a description of it. + */ + BASICYPR_TEST_SUBJ_FILE("basicYPRTestSubjectFile", File.class); + + 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/geopose10/SuiteFixtureListener.java b/src/main/java/org/opengis/cite/geopose10/SuiteFixtureListener.java index 8cfa5fb..19eafae 100644 --- a/src/main/java/org/opengis/cite/geopose10/SuiteFixtureListener.java +++ b/src/main/java/org/opengis/cite/geopose10/SuiteFixtureListener.java @@ -15,236 +15,247 @@ import jakarta.ws.rs.client.Client; /** - * 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) { - processSuiteParameters(suite); - registerClientComponent(suite); - } - - @Override - public void onFinish(ISuite suite) { - if (null != System.getProperty("deleteSubjectOnFinish")) { - deleteTempFiles(suite); - System.getProperties().remove("deleteSubjectOnFinish"); - } - } - - /** - * Processes test suite arguments and sets suite attributes accordingly. The - * entity referenced by the {@link TestRunArg#IUT iut} argument is retrieved - * and written to a File that is set as the value of the suite attribute - * {@link SuiteAttribute#TEST_SUBJ_FILE testSubjectFile}. - * - * @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()); - - - //------Basic YPR - - String basicYPRParam = params.get(TestRunArg.BASICYPR.toString()); - if ((null == basicYPRParam) || basicYPRParam.isEmpty()) { - throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.BASICYPR.toString()); - } - URI basicYPRRef = URI.create(basicYPRParam.trim()); - File basicYPREntityFile = null; - try { - basicYPREntityFile = URIUtils.dereferenceURI( basicYPRRef ); - } catch ( IOException ioxc ) { - throw new RuntimeException( "Failed to dereference resource located at " + basicYPRRef, ioxc ); - } - TestSuiteLogger.log( Level.FINE, String.format( "Wrote test subject to file: %s (%d bytes)", - basicYPREntityFile.getAbsolutePath(), basicYPREntityFile.length() ) ); - suite.setAttribute(SuiteAttribute.BASICYPR_TEST_SUBJ_FILE.getName(), basicYPREntityFile); - - //------Basic Quaternion - - String basicQuaternionParam = params.get(TestRunArg.BASICQuaternion.toString()); - if ((null == basicQuaternionParam) || basicQuaternionParam.isEmpty()) { - throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.BASICQuaternion.toString()); - } - URI basicQuaternionRef = URI.create(basicQuaternionParam.trim()); - File basicQuaternionEntityFile = null; - try { - basicQuaternionEntityFile = URIUtils.dereferenceURI( basicQuaternionRef ); - } catch ( IOException ioxc ) { - throw new RuntimeException( "Failed to dereference resource located at " + basicQuaternionRef, ioxc ); - } - TestSuiteLogger.log( Level.FINE, String.format( "Wrote test subject to file: %s (%d bytes)", - basicQuaternionEntityFile.getAbsolutePath(), basicQuaternionEntityFile.length() ) ); - suite.setAttribute(SuiteAttribute.BASICQUATERNION_TEST_SUBJ_FILE.getName(), basicQuaternionEntityFile); - - //------Advanced - - String advancedParam = params.get(TestRunArg.ADVANCED.toString()); - if ((null == advancedParam) || advancedParam.isEmpty()) { - throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.ADVANCED.toString()); - } - URI advancedRef = URI.create(advancedParam.trim()); - File advancedEntityFile = null; - try { - advancedEntityFile = URIUtils.dereferenceURI( advancedRef ); - } catch ( IOException ioxc ) { - throw new RuntimeException( "Failed to dereference resource located at " + advancedRef, ioxc ); - } - TestSuiteLogger.log( Level.FINE, String.format( "Wrote test subject to file: %s (%d bytes)", - advancedEntityFile.getAbsolutePath(), advancedEntityFile.length() ) ); - suite.setAttribute(SuiteAttribute.ADVANCED_TEST_SUBJ_FILE.getName(), advancedEntityFile); - - //------Chain - - String chainParam = params.get(TestRunArg.CHAIN.toString()); - if ((null == chainParam) || chainParam.isEmpty()) { - throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.CHAIN.toString()); - } - URI chainRef = URI.create(chainParam.trim()); - File chainEntityFile = null; - try { - chainEntityFile = URIUtils.dereferenceURI( chainRef ); - } catch ( IOException ioxc ) { - throw new RuntimeException( "Failed to dereference resource located at " + chainRef, ioxc ); - } - TestSuiteLogger.log( Level.FINE, String.format( "Wrote test subject to file: %s (%d bytes)", - chainEntityFile.getAbsolutePath(), chainEntityFile.length() ) ); - suite.setAttribute(SuiteAttribute.CHAIN_TEST_SUBJ_FILE.getName(), chainEntityFile); - - //------Graph - - String graphParam = params.get(TestRunArg.GRAPH.toString()); - if ((null == graphParam) || graphParam.isEmpty()) { - throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.GRAPH.toString()); - } - URI graphRef = URI.create(graphParam.trim()); - File graphEntityFile = null; - try { - graphEntityFile = URIUtils.dereferenceURI( graphRef ); - } catch ( IOException ioxc ) { - throw new RuntimeException( "Failed to dereference resource located at " + graphRef, ioxc ); - } - TestSuiteLogger.log( Level.FINE, String.format( "Wrote test subject to file: %s (%d bytes)", - graphEntityFile.getAbsolutePath(), graphEntityFile.length() ) ); - suite.setAttribute(SuiteAttribute.GRAPH_TEST_SUBJ_FILE.getName(), graphEntityFile); - - //------SeriesRegular - - String seriesregularParam = params.get(TestRunArg.SERIESREGULAR.toString()); - if ((null == seriesregularParam) || seriesregularParam.isEmpty()) { - throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.SERIESREGULAR.toString()); - } - URI seriesregularRef = URI.create(seriesregularParam.trim()); - File seriesregularEntityFile = null; - try { - seriesregularEntityFile = URIUtils.dereferenceURI( seriesregularRef ); - } catch ( IOException ioxc ) { - throw new RuntimeException( "Failed to dereference resource located at " + seriesregularRef, ioxc ); - } - - System.out.println(String.format( "Wrote test subject to file: %s (%d bytes)", - seriesregularEntityFile.getAbsolutePath(), seriesregularEntityFile.length() )); - - TestSuiteLogger.log( Level.FINE, String.format( "Wrote test subject to file: %s (%d bytes)", - seriesregularEntityFile.getAbsolutePath(), seriesregularEntityFile.length() ) ); - suite.setAttribute(SuiteAttribute.SERIESREGULAR_TEST_SUBJ_FILE.getName(), seriesregularEntityFile); - - //------StreamElement - - String streamelementParam = params.get(TestRunArg.STREAMELEMENT.toString()); - if ((null == streamelementParam) || streamelementParam.isEmpty()) { - throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.STREAMELEMENT.toString()); - } - URI streamelementRef = URI.create(streamelementParam.trim()); - File streamelementEntityFile = null; - try { - streamelementEntityFile = URIUtils.dereferenceURI( streamelementRef ); - } catch ( IOException ioxc ) { - throw new RuntimeException( "Failed to dereference resource located at " + streamelementRef, ioxc ); - } - TestSuiteLogger.log( Level.FINE, String.format( "Wrote test subject to file: %s (%d bytes)", - streamelementEntityFile.getAbsolutePath(), streamelementEntityFile.length() ) ); - suite.setAttribute(SuiteAttribute.STREAMELEMENT_TEST_SUBJ_FILE.getName(), streamelementEntityFile); - - //------StreamHeader - - String streamheaderParam = params.get(TestRunArg.STREAMHEADER.toString()); - if ((null == streamheaderParam) || streamheaderParam.isEmpty()) { - throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.STREAMHEADER.toString()); - } - URI streamheaderRef = URI.create(streamheaderParam.trim()); - File streamheaderEntityFile = null; - try { - streamheaderEntityFile = URIUtils.dereferenceURI( streamheaderRef ); - } catch ( IOException ioxc ) { - throw new RuntimeException( "Failed to dereference resource located at " + streamheaderRef, ioxc ); - } - TestSuiteLogger.log( Level.FINE, String.format( "Wrote test subject to file: %s (%d bytes)", - streamheaderEntityFile.getAbsolutePath(), streamheaderEntityFile.length() ) ); - suite.setAttribute(SuiteAttribute.STREAMHEADER_TEST_SUBJ_FILE.getName(), streamheaderEntityFile); - - //------StreamRecord - - String streamrecordParam = params.get(TestRunArg.STREAMRECORD.toString()); - if ((null == streamrecordParam) || streamrecordParam.isEmpty()) { - throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.STREAMRECORD.toString()); - } - URI streamrecordRef = URI.create(streamrecordParam.trim()); - File streamrecordEntityFile = null; - try { - streamrecordEntityFile = URIUtils.dereferenceURI( streamrecordRef ); - } catch ( IOException ioxc ) { - throw new RuntimeException( "Failed to dereference resource located at " + streamrecordRef, ioxc ); - } - TestSuiteLogger.log( Level.FINE, String.format( "Wrote test subject to file: %s (%d bytes)", - streamrecordEntityFile.getAbsolutePath(), streamrecordEntityFile.length() ) ); - suite.setAttribute(SuiteAttribute.STREAMRECORD_TEST_SUBJ_FILE.getName(), streamrecordEntityFile); - } - - /** - * A client component is added to the suite fixture as the value of the - * {@link SuiteAttribute#CLIENT} attribute; it may be subsequently accessed - * via the {@link org.testng.ITestContext#getSuite()} method. - * - * @param suite - * The test suite instance. - */ - void registerClientComponent(ISuite suite) { - Client client = ClientUtils.buildClient(); - if (null != client) { - suite.setAttribute(SuiteAttribute.CLIENT.getName(), client); - } - } - - /** - * Deletes temporary files created during the test run if TestSuiteLogger is - * enabled at the INFO level or higher (they are left intact at the CONFIG - * level or lower). - * - * @param suite - * The test suite. - */ - void deleteTempFiles(ISuite suite) { - if (TestSuiteLogger.isLoggable(Level.CONFIG)) { - return; - } - File testSubjFile = (File) suite.getAttribute(SuiteAttribute.TEST_SUBJ_FILE.getName()); - if (testSubjFile.exists()) { - testSubjFile.delete(); - } - } + /** {@inheritDoc} */ + @Override + public void onStart(ISuite suite) { + processSuiteParameters(suite); + registerClientComponent(suite); + } + + /** {@inheritDoc} */ + @Override + public void onFinish(ISuite suite) { + if (null != System.getProperty("deleteSubjectOnFinish")) { + deleteTempFiles(suite); + System.getProperties().remove("deleteSubjectOnFinish"); + } + } + + /** + * Processes test suite arguments and sets suite attributes accordingly. The entity + * referenced by the {@link TestRunArg#IUT iut} argument is retrieved and written to a + * File that is set as the value of the suite attribute + * {@link SuiteAttribute#TEST_SUBJ_FILE testSubjectFile}. + * @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()); + + // ------Basic YPR + + String basicYPRParam = params.get(TestRunArg.BASICYPR.toString()); + if ((null == basicYPRParam) || basicYPRParam.isEmpty()) { + throw new IllegalArgumentException( + "Required test run parameter not found: " + TestRunArg.BASICYPR.toString()); + } + URI basicYPRRef = URI.create(basicYPRParam.trim()); + File basicYPREntityFile = null; + try { + basicYPREntityFile = URIUtils.dereferenceURI(basicYPRRef); + } + catch (IOException ioxc) { + throw new RuntimeException("Failed to dereference resource located at " + basicYPRRef, ioxc); + } + TestSuiteLogger.log(Level.FINE, String.format("Wrote test subject to file: %s (%d bytes)", + basicYPREntityFile.getAbsolutePath(), basicYPREntityFile.length())); + suite.setAttribute(SuiteAttribute.BASICYPR_TEST_SUBJ_FILE.getName(), basicYPREntityFile); + + // ------Basic Quaternion + + String basicQuaternionParam = params.get(TestRunArg.BASICQuaternion.toString()); + if ((null == basicQuaternionParam) || basicQuaternionParam.isEmpty()) { + throw new IllegalArgumentException( + "Required test run parameter not found: " + TestRunArg.BASICQuaternion.toString()); + } + URI basicQuaternionRef = URI.create(basicQuaternionParam.trim()); + File basicQuaternionEntityFile = null; + try { + basicQuaternionEntityFile = URIUtils.dereferenceURI(basicQuaternionRef); + } + catch (IOException ioxc) { + throw new RuntimeException("Failed to dereference resource located at " + basicQuaternionRef, ioxc); + } + TestSuiteLogger.log(Level.FINE, String.format("Wrote test subject to file: %s (%d bytes)", + basicQuaternionEntityFile.getAbsolutePath(), basicQuaternionEntityFile.length())); + suite.setAttribute(SuiteAttribute.BASICQUATERNION_TEST_SUBJ_FILE.getName(), basicQuaternionEntityFile); + + // ------Advanced + + String advancedParam = params.get(TestRunArg.ADVANCED.toString()); + if ((null == advancedParam) || advancedParam.isEmpty()) { + throw new IllegalArgumentException( + "Required test run parameter not found: " + TestRunArg.ADVANCED.toString()); + } + URI advancedRef = URI.create(advancedParam.trim()); + File advancedEntityFile = null; + try { + advancedEntityFile = URIUtils.dereferenceURI(advancedRef); + } + catch (IOException ioxc) { + throw new RuntimeException("Failed to dereference resource located at " + advancedRef, ioxc); + } + TestSuiteLogger.log(Level.FINE, String.format("Wrote test subject to file: %s (%d bytes)", + advancedEntityFile.getAbsolutePath(), advancedEntityFile.length())); + suite.setAttribute(SuiteAttribute.ADVANCED_TEST_SUBJ_FILE.getName(), advancedEntityFile); + + // ------Chain + + String chainParam = params.get(TestRunArg.CHAIN.toString()); + if ((null == chainParam) || chainParam.isEmpty()) { + throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.CHAIN.toString()); + } + URI chainRef = URI.create(chainParam.trim()); + File chainEntityFile = null; + try { + chainEntityFile = URIUtils.dereferenceURI(chainRef); + } + catch (IOException ioxc) { + throw new RuntimeException("Failed to dereference resource located at " + chainRef, ioxc); + } + TestSuiteLogger.log(Level.FINE, String.format("Wrote test subject to file: %s (%d bytes)", + chainEntityFile.getAbsolutePath(), chainEntityFile.length())); + suite.setAttribute(SuiteAttribute.CHAIN_TEST_SUBJ_FILE.getName(), chainEntityFile); + + // ------Graph + + String graphParam = params.get(TestRunArg.GRAPH.toString()); + if ((null == graphParam) || graphParam.isEmpty()) { + throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.GRAPH.toString()); + } + URI graphRef = URI.create(graphParam.trim()); + File graphEntityFile = null; + try { + graphEntityFile = URIUtils.dereferenceURI(graphRef); + } + catch (IOException ioxc) { + throw new RuntimeException("Failed to dereference resource located at " + graphRef, ioxc); + } + TestSuiteLogger.log(Level.FINE, String.format("Wrote test subject to file: %s (%d bytes)", + graphEntityFile.getAbsolutePath(), graphEntityFile.length())); + suite.setAttribute(SuiteAttribute.GRAPH_TEST_SUBJ_FILE.getName(), graphEntityFile); + + // ------SeriesRegular + + String seriesregularParam = params.get(TestRunArg.SERIESREGULAR.toString()); + if ((null == seriesregularParam) || seriesregularParam.isEmpty()) { + throw new IllegalArgumentException( + "Required test run parameter not found: " + TestRunArg.SERIESREGULAR.toString()); + } + URI seriesregularRef = URI.create(seriesregularParam.trim()); + File seriesregularEntityFile = null; + try { + seriesregularEntityFile = URIUtils.dereferenceURI(seriesregularRef); + } + catch (IOException ioxc) { + throw new RuntimeException("Failed to dereference resource located at " + seriesregularRef, ioxc); + } + + System.out.println(String.format("Wrote test subject to file: %s (%d bytes)", + seriesregularEntityFile.getAbsolutePath(), seriesregularEntityFile.length())); + + TestSuiteLogger.log(Level.FINE, String.format("Wrote test subject to file: %s (%d bytes)", + seriesregularEntityFile.getAbsolutePath(), seriesregularEntityFile.length())); + suite.setAttribute(SuiteAttribute.SERIESREGULAR_TEST_SUBJ_FILE.getName(), seriesregularEntityFile); + + // ------StreamElement + + String streamelementParam = params.get(TestRunArg.STREAMELEMENT.toString()); + if ((null == streamelementParam) || streamelementParam.isEmpty()) { + throw new IllegalArgumentException( + "Required test run parameter not found: " + TestRunArg.STREAMELEMENT.toString()); + } + URI streamelementRef = URI.create(streamelementParam.trim()); + File streamelementEntityFile = null; + try { + streamelementEntityFile = URIUtils.dereferenceURI(streamelementRef); + } + catch (IOException ioxc) { + throw new RuntimeException("Failed to dereference resource located at " + streamelementRef, ioxc); + } + TestSuiteLogger.log(Level.FINE, String.format("Wrote test subject to file: %s (%d bytes)", + streamelementEntityFile.getAbsolutePath(), streamelementEntityFile.length())); + suite.setAttribute(SuiteAttribute.STREAMELEMENT_TEST_SUBJ_FILE.getName(), streamelementEntityFile); + + // ------StreamHeader + + String streamheaderParam = params.get(TestRunArg.STREAMHEADER.toString()); + if ((null == streamheaderParam) || streamheaderParam.isEmpty()) { + throw new IllegalArgumentException( + "Required test run parameter not found: " + TestRunArg.STREAMHEADER.toString()); + } + URI streamheaderRef = URI.create(streamheaderParam.trim()); + File streamheaderEntityFile = null; + try { + streamheaderEntityFile = URIUtils.dereferenceURI(streamheaderRef); + } + catch (IOException ioxc) { + throw new RuntimeException("Failed to dereference resource located at " + streamheaderRef, ioxc); + } + TestSuiteLogger.log(Level.FINE, String.format("Wrote test subject to file: %s (%d bytes)", + streamheaderEntityFile.getAbsolutePath(), streamheaderEntityFile.length())); + suite.setAttribute(SuiteAttribute.STREAMHEADER_TEST_SUBJ_FILE.getName(), streamheaderEntityFile); + + // ------StreamRecord + + String streamrecordParam = params.get(TestRunArg.STREAMRECORD.toString()); + if ((null == streamrecordParam) || streamrecordParam.isEmpty()) { + throw new IllegalArgumentException( + "Required test run parameter not found: " + TestRunArg.STREAMRECORD.toString()); + } + URI streamrecordRef = URI.create(streamrecordParam.trim()); + File streamrecordEntityFile = null; + try { + streamrecordEntityFile = URIUtils.dereferenceURI(streamrecordRef); + } + catch (IOException ioxc) { + throw new RuntimeException("Failed to dereference resource located at " + streamrecordRef, ioxc); + } + TestSuiteLogger.log(Level.FINE, String.format("Wrote test subject to file: %s (%d bytes)", + streamrecordEntityFile.getAbsolutePath(), streamrecordEntityFile.length())); + suite.setAttribute(SuiteAttribute.STREAMRECORD_TEST_SUBJ_FILE.getName(), streamrecordEntityFile); + } + + /** + * A client component is added to the suite fixture as the value of the + * {@link SuiteAttribute#CLIENT} attribute; it may be subsequently accessed via the + * {@link org.testng.ITestContext#getSuite()} method. + * @param suite The test suite instance. + */ + void registerClientComponent(ISuite suite) { + Client client = ClientUtils.buildClient(); + if (null != client) { + suite.setAttribute(SuiteAttribute.CLIENT.getName(), client); + } + } + + /** + * Deletes temporary files created during the test run if TestSuiteLogger is enabled + * at the INFO level or higher (they are left intact at the CONFIG level or lower). + * @param suite The test suite. + */ + void deleteTempFiles(ISuite suite) { + if (TestSuiteLogger.isLoggable(Level.CONFIG)) { + return; + } + File testSubjFile = (File) suite.getAttribute(SuiteAttribute.TEST_SUBJ_FILE.getName()); + if (testSubjFile.exists()) { + testSubjFile.delete(); + } + } + } diff --git a/src/main/java/org/opengis/cite/geopose10/SuitePreconditions.java b/src/main/java/org/opengis/cite/geopose10/SuitePreconditions.java index f30161d..f53f3af 100644 --- a/src/main/java/org/opengis/cite/geopose10/SuitePreconditions.java +++ b/src/main/java/org/opengis/cite/geopose10/SuitePreconditions.java @@ -7,36 +7,35 @@ import org.testng.annotations.BeforeSuite; /** - * Checks that various preconditions are satisfied before the test suite is run. - * If any of these (BeforeSuite) methods fail, all tests will be skipped. + * Checks that various preconditions are satisfied before the test suite is run. If any of + * these (BeforeSuite) methods fail, all tests will be skipped. */ public class SuitePreconditions { - private static final Logger LOGR = Logger.getLogger(SuitePreconditions.class.getName()); + private static final Logger LOGR = Logger.getLogger(SuitePreconditions.class.getName()); + + /** + * Verifies that the referenced test subject exists and has the expected type. + */ + @BeforeSuite + @SuppressWarnings("rawtypes") + public void verifyTestSubject() { + SuiteAttribute testFileAttr = SuiteAttribute.TEST_SUBJ_FILE; + Object sutObj = Reporter.getCurrentTestResult() + .getTestContext() + .getSuite() + .getAttribute(testFileAttr.getName()); + Class expectedType = testFileAttr.getType(); + if (null != sutObj && expectedType.isInstance(sutObj)) { + // TODO: Verify test subject + } + else { + String msg = String.format("Value of test suite attribute '%s' is missing or is not an instance of %s", + testFileAttr.getName(), expectedType.getName()); + LOGR.log(Level.SEVERE, msg); + throw new AssertionError(msg); + } + + } - /** - * Verifies that the referenced test subject exists and has the expected - * type. - * - */ - @BeforeSuite - @SuppressWarnings("rawtypes") - public void verifyTestSubject() { - SuiteAttribute testFileAttr = SuiteAttribute.TEST_SUBJ_FILE; - Object sutObj = Reporter.getCurrentTestResult() - .getTestContext() - .getSuite() - .getAttribute(testFileAttr.getName()); - Class expectedType = testFileAttr.getType(); - if (null != sutObj && expectedType.isInstance(sutObj)) { - // TODO: Verify test subject - } - else { - String msg = String.format("Value of test suite attribute '%s' is missing or is not an instance of %s", - testFileAttr.getName(), expectedType.getName()); - LOGR.log(Level.SEVERE, msg); - throw new AssertionError(msg); - } - - } } diff --git a/src/main/java/org/opengis/cite/geopose10/TestFailureListener.java b/src/main/java/org/opengis/cite/geopose10/TestFailureListener.java index 6f4c6db..a8b8cfd 100644 --- a/src/main/java/org/opengis/cite/geopose10/TestFailureListener.java +++ b/src/main/java/org/opengis/cite/geopose10/TestFailureListener.java @@ -13,87 +13,85 @@ import jakarta.ws.rs.core.Response; /** - * A listener that augments a test result with diagnostic information in the - * event that a test method failed. This information will appear in the XML - * report when the test run is completed. + * A listener that augments a test result with diagnostic information in the event that a + * test method failed. This information will appear in the XML report when the test run is + * completed. */ public class TestFailureListener extends TestListenerAdapter { - /** - * Sets the "request" and "response" attributes of a test result. The value - * of these attributes is a string that contains information about the - * content of an outgoing or incoming message: target resource, status code, - * headers, entity (if present). The entity is represented as a String with - * UTF-8 character encoding. - * - * @param result A description of a test result (with a fail verdict). - */ - @Override - public void onTestFailure(ITestResult result) { - super.onTestFailure(result); - Object instance = result.getInstance(); - if (CommonFixture.class.isInstance(instance)) { - CommonFixture fixture = CommonFixture.class.cast(instance); - result.setAttribute("request", getRequestMessageInfo(fixture.request)); - result.setAttribute("response", getResponseMessageInfo(fixture.response)); - } - } + /** + * {@inheritDoc} + * + * Sets the "request" and "response" attributes of a test result. The value of these + * attributes is a string that contains information about the content of an outgoing + * or incoming message: target resource, status code, headers, entity (if present). + * The entity is represented as a String with UTF-8 character encoding. + */ + @Override + public void onTestFailure(ITestResult result) { + super.onTestFailure(result); + Object instance = result.getInstance(); + if (CommonFixture.class.isInstance(instance)) { + CommonFixture fixture = CommonFixture.class.cast(instance); + result.setAttribute("request", getRequestMessageInfo(fixture.request)); + result.setAttribute("response", getResponseMessageInfo(fixture.response)); + } + } - /** - * Gets diagnostic information about a request message. If the request - * contains a message body, it should be represented as a DOM Document node - * or as an object having a meaningful toString() implementation. - * - * @param req An object representing an HTTP request message. - * @return A string containing information gleaned from the request message. - */ - String getRequestMessageInfo(ClientRequest req) { - if (null == req) { - return "No request message."; - } - StringBuilder msgInfo = new StringBuilder(); - msgInfo.append("Method: ").append(req.getMethod()).append('\n'); - msgInfo.append("Target URI: ").append(req.getUri()).append('\n'); - msgInfo.append("Headers: ").append(req.getHeaders()).append('\n'); - if (null != req.getEntity()) { - Object entity = req.getEntity(); - String body; - if (Document.class.isInstance(entity)) { - Document doc = Document.class.cast(entity); - body = XMLUtils.writeNodeToString(doc); - } else { - body = entity.toString(); - } - msgInfo.append(body).append('\n'); - } - return msgInfo.toString(); - } + /** + * Gets diagnostic information about a request message. If the request contains a + * message body, it should be represented as a DOM Document node or as an object + * having a meaningful toString() implementation. + * @param req An object representing an HTTP request message. + * @return A string containing information gleaned from the request message. + */ + String getRequestMessageInfo(ClientRequest req) { + if (null == req) { + return "No request message."; + } + StringBuilder msgInfo = new StringBuilder(); + msgInfo.append("Method: ").append(req.getMethod()).append('\n'); + msgInfo.append("Target URI: ").append(req.getUri()).append('\n'); + msgInfo.append("Headers: ").append(req.getHeaders()).append('\n'); + if (null != req.getEntity()) { + Object entity = req.getEntity(); + String body; + if (Document.class.isInstance(entity)) { + Document doc = Document.class.cast(entity); + body = XMLUtils.writeNodeToString(doc); + } + else { + body = entity.toString(); + } + msgInfo.append(body).append('\n'); + } + return msgInfo.toString(); + } - /** - * Gets diagnostic information about a response message. - * - * @param rsp An object representing an HTTP response message. - * @return A string containing information gleaned from the response - * message. - */ - String getResponseMessageInfo(Response rsp) { - if (null == rsp) { - return "No response message."; - } - StringBuilder msgInfo = new StringBuilder(); - msgInfo.append("Status: ").append(rsp.getStatus()).append('\n'); - msgInfo.append("Headers: ").append(rsp.getHeaders()).append('\n'); - if (rsp.hasEntity()) { - if (rsp.getMediaType().isCompatible(MediaType.APPLICATION_XML_TYPE)) { - Document doc = ClientUtils.getResponseEntityAsDocument(rsp, null); - msgInfo.append(XMLUtils.writeNodeToString(doc)); - } else { - byte[] body = rsp.readEntity(byte[].class); - msgInfo.append(new String(body, StandardCharsets.UTF_8)); - } - msgInfo.append('\n'); - } - return msgInfo.toString(); - } + /** + * Gets diagnostic information about a response message. + * @param rsp An object representing an HTTP response message. + * @return A string containing information gleaned from the response message. + */ + String getResponseMessageInfo(Response rsp) { + if (null == rsp) { + return "No response message."; + } + StringBuilder msgInfo = new StringBuilder(); + msgInfo.append("Status: ").append(rsp.getStatus()).append('\n'); + msgInfo.append("Headers: ").append(rsp.getHeaders()).append('\n'); + if (rsp.hasEntity()) { + if (rsp.getMediaType().isCompatible(MediaType.APPLICATION_XML_TYPE)) { + Document doc = ClientUtils.getResponseEntityAsDocument(rsp, null); + msgInfo.append(XMLUtils.writeNodeToString(doc)); + } + else { + byte[] body = rsp.readEntity(byte[].class); + msgInfo.append(new String(body, StandardCharsets.UTF_8)); + } + msgInfo.append('\n'); + } + return msgInfo.toString(); + } } diff --git a/src/main/java/org/opengis/cite/geopose10/TestNGController.java b/src/main/java/org/opengis/cite/geopose10/TestNGController.java index 2b65a07..f25b569 100644 --- a/src/main/java/org/opengis/cite/geopose10/TestNGController.java +++ b/src/main/java/org/opengis/cite/geopose10/TestNGController.java @@ -30,140 +30,142 @@ */ public class TestNGController implements TestSuiteController { - private TestRunExecutor executor; - private Properties etsProperties = new Properties(); - - /** - * A convenience method for running the test suite using a command-line - * interface. The default values of the test run arguments are as follows: - *
      - *
    • XML properties file: ${user.home}/test-run-props.xml
    • - *
    • outputDir: ${user.home}
    • - *
    • deleteSubjectOnFinish: false
    • - *
    - *

    - * Synopsis - *

    - * - *
    -     * ets-*-aio.jar [-o|--outputDir $TMPDIR] [-d|--deleteSubjectOnFinish] [test-run-props.xml]
    -     * 
    - * - * @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 { - CommandLineArguments testRunArgs = new CommandLineArguments(); - JCommander cmd = new JCommander(testRunArgs); - try { - cmd.parse(args); - } catch (ParameterException px) { - System.out.println(px.getMessage()); - cmd.usage(); - } - if (testRunArgs.doDeleteSubjectOnFinish()) { - System.setProperty("deleteSubjectOnFinish", "true"); - } - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - File xmlArgs = testRunArgs.getPropertiesFile(); - Document testRunProps = db.parse(xmlArgs); - TestNGController controller = new TestNGController(testRunArgs.getOutputDir()); - Source testResults = controller.doTestRun(testRunProps); - System.out.println("Test results: " + testResults.getSystemId()); - } - - /** - * Default constructor uses the location given by the "java.io.tmpdir" - * system property as the root output directory. - */ - public TestNGController() { - this(System.getProperty("java.io.tmpdir")); - } - - /** - * Construct a controller that writes results to the given output directory. - * - * @param outputDir - * The location of the directory in which test results will be - * written (a file system path or a 'file' URI). It will be - * created if it does not exist. - */ - public TestNGController(String outputDir) { - 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; - if (null == outputDir || outputDir.isEmpty()) { - resultsDir = new File(System.getProperty("user.home")); - } else if (outputDir.startsWith("file:")) { - resultsDir = new File(URI.create(outputDir)); - } else { - resultsDir = new File(outputDir); - } - 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 IllegalArgumentException - * If any arguments are missing or invalid for some reason. - */ - void validateTestRunArgs(Document testRunArgs) { - 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.BASICYPR.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 for running the test suite using a command-line interface. The + * default values of the test run arguments are as follows: + *
      + *
    • XML properties file: ${user.home}/test-run-props.xml
    • + *
    • outputDir: ${user.home}
    • + *
    • deleteSubjectOnFinish: false
    • + *
    + *

    + * Synopsis + *

    + * + *
    +	 * ets-*-aio.jar [-o|--outputDir $TMPDIR] [-d|--deleteSubjectOnFinish] [test-run-props.xml]
    +	 * 
    + * @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 { + CommandLineArguments testRunArgs = new CommandLineArguments(); + JCommander cmd = new JCommander(testRunArgs); + try { + cmd.parse(args); + } + catch (ParameterException px) { + System.out.println(px.getMessage()); + cmd.usage(); + } + if (testRunArgs.doDeleteSubjectOnFinish()) { + System.setProperty("deleteSubjectOnFinish", "true"); + } + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + File xmlArgs = testRunArgs.getPropertiesFile(); + Document testRunProps = db.parse(xmlArgs); + TestNGController controller = new TestNGController(testRunArgs.getOutputDir()); + Source testResults = controller.doTestRun(testRunProps); + System.out.println("Test results: " + testResults.getSystemId()); + } + + /** + * Default constructor uses the location given by the "java.io.tmpdir" system property + * as the root output directory. + */ + public TestNGController() { + this(System.getProperty("java.io.tmpdir")); + } + + /** + * Construct a controller that writes results to the given output directory. + * @param outputDir The location of the directory in which test results will be + * written (a file system path or a 'file' URI). It will be created if it does not + * exist. + */ + public TestNGController(String outputDir) { + 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; + if (null == outputDir || outputDir.isEmpty()) { + resultsDir = new File(System.getProperty("user.home")); + } + else if (outputDir.startsWith("file:")) { + resultsDir = new File(URI.create(outputDir)); + } + else { + resultsDir = new File(outputDir); + } + 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 IllegalArgumentException If any arguments are missing or invalid for some + * reason. + */ + void validateTestRunArgs(Document testRunArgs) { + 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.BASICYPR.toString())) { + throw new IllegalArgumentException( + String.format("Missing argument: '%s' must be present.", TestRunArg.IUT)); + } + } + } diff --git a/src/main/java/org/opengis/cite/geopose10/TestRunArg.java b/src/main/java/org/opengis/cite/geopose10/TestRunArg.java index d3b63af..b8ded24 100644 --- a/src/main/java/org/opengis/cite/geopose10/TestRunArg.java +++ b/src/main/java/org/opengis/cite/geopose10/TestRunArg.java @@ -5,23 +5,61 @@ */ public enum TestRunArg { - /** - * An absolute URI that refers to a representation of the test subject or - * metadata about it. - */ - IUT, - STREAMRECORD, - STREAMHEADER, - STREAMELEMENT, - SERIESREGULAR, - GRAPH, - CHAIN, - ADVANCED, - BASICQuaternion, + /** + * An absolute URI that refers to a representation of the test subject or metadata + * about it. + */ + IUT, + /** + * An absolute URI that refers to a representation of the test subject for + * streamRecord tests or metadata about it. + */ + STREAMRECORD, + /** + * An absolute URI that refers to a representation of the test subject for + * streamHeader tests or metadata about it. + */ + STREAMHEADER, + /** + * An absolute URI that refers to a representation of the test subject for + * streamElement tests or metadata about it. + */ + STREAMELEMENT, + /** + * An absolute URI that refers to a representation of the test subject for + * seriesRegular tests or metadata about it. + */ + SERIESREGULAR, + /** + * An absolute URI that refers to a representation of the test subject for graph tests + * or metadata about it. + */ + GRAPH, + /** + * An absolute URI that refers to a representation of the test subject for chain tests + * or metadata about it. + */ + CHAIN, + /** + * An absolute URI that refers to a representation of the test subject for advanced + * tests or metadata about it. + */ + ADVANCED, + /** + * An absolute URI that refers to a representation of the test subject for + * basicQuaternion tests or metadata about it. + */ + BASICQuaternion, + /** + * An absolute URI that refers to a representation of the test subject for basicYPR + * tests or metadata about it. + */ BASICYPR; - @Override - public String toString() { - return name().toLowerCase(); - } + /** {@inheritDoc} */ + @Override + public String toString() { + return name().toLowerCase(); + } + } diff --git a/src/main/java/org/opengis/cite/geopose10/TestRunListener.java b/src/main/java/org/opengis/cite/geopose10/TestRunListener.java index 6dfad61..d5d53b1 100644 --- a/src/main/java/org/opengis/cite/geopose10/TestRunListener.java +++ b/src/main/java/org/opengis/cite/geopose10/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/geopose10/encodings/json/Advanced.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/Advanced.java index d52996e..8893707 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/Advanced.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/Advanced.java @@ -32,82 +32,83 @@ import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; +/** + *

    + * Advanced class. + *

    + * + */ public class Advanced extends CommonFixture { - private File testSubject; - - /** - * Obtains the test subject from the ISuite context. The suite attribute - * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should - * evaluate to a DOM Document node. - * - * @param testContext - * The test (group) context. - */ - @BeforeClass - public void obtainTestSubject(ITestContext testContext) { - - Object obj = testContext.getSuite().getAttribute( - SuiteAttribute.ADVANCED_TEST_SUBJ_FILE.getName()); - - this.testSubject = (File) obj; - - } - - /** - * Sets the test subject. This method is intended to facilitate unit - * testing. - * - * @param testSubject A Document node representing the test subject or - * metadata about it. - */ - public void setTestSubject(File testSubject) { - this.testSubject = testSubject; - } - - /** - * Implements Conformance test A.40: Verify conformance via JSON schema - * Validate the JSON data against the Advanced JSON-Schema 2019-9 definition - */ - @Test(description = "Implements Conformance test A.40: Verify conformance via JSON schema (/conf/advanced-encoding-json/definition)") - public void validateByAdvancedSchema() { - - - if(!testSubject.isFile()) { - Assert.assertTrue(testSubject.isFile(),"No file selected. "); - } - - BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); - String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Advanced.Schema.json"; - - boolean valid = false; - StringBuffer sb = new StringBuffer(); - - InputStream inputStream = tester.getClass() - .getResourceAsStream(schemaToApply); - - try { - JsonNode schemaNode = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); - JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); - - schema.initializeValidators(); - - JsonNode node = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); - Set errors = schema.validate(node); - - - - Iterator it = errors.iterator(); - while(it.hasNext()) - { - sb.append(" "+it.next()+".\n"); - - } - - } catch (IOException e) { + + private File testSubject; + + /** + * Obtains the test subject from the ISuite context. The suite attribute + * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should evaluate to a + * DOM Document node. + * @param testContext The test (group) context. + */ + @BeforeClass + public void obtainTestSubject(ITestContext testContext) { + + Object obj = testContext.getSuite().getAttribute(SuiteAttribute.ADVANCED_TEST_SUBJ_FILE.getName()); + + this.testSubject = (File) obj; + + } + + /** + * Sets the test subject. This method is intended to facilitate unit testing. + * @param testSubject A Document node representing the test subject or metadata about + * it. + */ + public void setTestSubject(File testSubject) { + this.testSubject = testSubject; + } + + /** + * Implements Conformance test A.40: Verify conformance via JSON schema Validate the + * JSON data against the Advanced JSON-Schema 2019-9 definition + */ + @Test(description = "Implements Conformance test A.40: Verify conformance via JSON schema (/conf/advanced-encoding-json/definition)") + public void validateByAdvancedSchema() { + + if (!testSubject.isFile()) { + Assert.assertTrue(testSubject.isFile(), "No file selected. "); + } + + BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); + String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Advanced.Schema.json"; + + boolean valid = false; + StringBuffer sb = new StringBuffer(); + + InputStream inputStream = tester.getClass().getResourceAsStream(schemaToApply); + + try { + JsonNode schemaNode = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); + JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); + + schema.initializeValidators(); + + JsonNode node = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); + Set errors = schema.validate(node); + + Iterator it = errors.iterator(); + while (it.hasNext()) { + sb.append(" " + it.next() + ".\n"); + + } + + } + catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - Assert.assertTrue(sb.toString().length()==0,sb.toString()); - } + Assert.assertTrue(sb.toString().length() == 0, sb.toString()); + } + } diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicQuaternion.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicQuaternion.java index bb96388..11aedf4 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicQuaternion.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicQuaternion.java @@ -32,87 +32,85 @@ import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; +/** + *

    + * BasicQuaternion class. + *

    + * + */ public class BasicQuaternion extends CommonFixture { - private File testSubject; - - /** - * Obtains the test subject from the ISuite context. The suite attribute - * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should - * evaluate to a DOM Document node. - * - * @param testContext - * The test (group) context. - */ - @BeforeClass - public void obtainTestSubject(ITestContext testContext) { - - Object obj = testContext.getSuite().getAttribute( - SuiteAttribute.BASICQUATERNION_TEST_SUBJ_FILE.getName()); - - this.testSubject = (File) obj; - - } - - /** - * Sets the test subject. This method is intended to facilitate unit - * testing. - * - * @param testSubject A Document node representing the test subject or - * metadata about it. - */ - public void setTestSubject(File testSubject) { - this.testSubject = testSubject; - } - - /** - * Implements Conformance test A.39: Verify conformance via JSON schema - * Validate the JSON data against the Basic-Quaternion JSON Schema 2019-9 definition - * - */ - @Test(description = "Implements Conformance test A.39: Verify conformance via JSON schema (/conf/basic-quaternion-encoding-json/definition)") - public void validateByBasicQuaternionSchema() { - - - - if(!testSubject.isFile()) { - Assert.assertTrue(testSubject.isFile(),"No file selected. "); - } - - StringBuffer errorMessages = new StringBuffer(); - - BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); - String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Basic.Quaternion.Schema.json"; - - boolean valid = false; - StringBuffer sb = new StringBuffer(); - - InputStream inputStream = tester.getClass() - .getResourceAsStream(schemaToApply); - - try { - JsonNode schemaNode = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); - JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); - - schema.initializeValidators(); - - - JsonNode node = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); - Set errors = schema.validate(node); - - - - Iterator it = errors.iterator(); - while(it.hasNext()) - { - sb.append(" "+it.next()+".\n"); - - } - - } catch (IOException e) { + + private File testSubject; + + /** + * Obtains the test subject from the ISuite context. The suite attribute + * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should evaluate to a + * DOM Document node. + * @param testContext The test (group) context. + */ + @BeforeClass + public void obtainTestSubject(ITestContext testContext) { + + Object obj = testContext.getSuite().getAttribute(SuiteAttribute.BASICQUATERNION_TEST_SUBJ_FILE.getName()); + + this.testSubject = (File) obj; + + } + + /** + * Sets the test subject. This method is intended to facilitate unit testing. + * @param testSubject A Document node representing the test subject or metadata about + * it. + */ + public void setTestSubject(File testSubject) { + this.testSubject = testSubject; + } + + /** + * Implements Conformance test A.39: Verify conformance via JSON schema Validate the + * JSON data against the Basic-Quaternion JSON Schema 2019-9 definition + */ + @Test(description = "Implements Conformance test A.39: Verify conformance via JSON schema (/conf/basic-quaternion-encoding-json/definition)") + public void validateByBasicQuaternionSchema() { + + if (!testSubject.isFile()) { + Assert.assertTrue(testSubject.isFile(), "No file selected. "); + } + + StringBuffer errorMessages = new StringBuffer(); + + BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); + String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Basic.Quaternion.Schema.json"; + + boolean valid = false; + StringBuffer sb = new StringBuffer(); + + InputStream inputStream = tester.getClass().getResourceAsStream(schemaToApply); + + try { + JsonNode schemaNode = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); + JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); + + schema.initializeValidators(); + + JsonNode node = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); + Set errors = schema.validate(node); + + Iterator it = errors.iterator(); + while (it.hasNext()) { + sb.append(" " + it.next() + ".\n"); + + } + + } + catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - Assert.assertTrue(sb.toString().length()==0,sb.toString()); - } + Assert.assertTrue(sb.toString().length() == 0, sb.toString()); + } + } diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicYPR.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicYPR.java index 4934212..22e66e5 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicYPR.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicYPR.java @@ -32,82 +32,83 @@ import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; +/** + *

    + * BasicYPR class. + *

    + * + */ public class BasicYPR extends CommonFixture { - private File testSubject; - - /** - * Obtains the test subject from the ISuite context. The suite attribute - * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should - * evaluate to a DOM Document node. - * - * @param testContext - * The test (group) context. - */ - @BeforeClass - public void obtainTestSubject(ITestContext testContext) { - - Object obj = testContext.getSuite().getAttribute( - SuiteAttribute.BASICYPR_TEST_SUBJ_FILE.getName()); - - this.testSubject = (File) obj; - - } - - /** - * Sets the test subject. This method is intended to facilitate unit - * testing. - * - * @param testSubject A Document node representing the test subject or - * metadata about it. - */ - public void setTestSubject(File testSubject) { - this.testSubject = testSubject; - } - - /** - * Implements Conformance test A.37: Verify conformance via JSON schema - * Test Method: Validate the JSON data against the Basic-YPR JSON Schema 2019-9 definition - */ - @Test(description = "Implements Conformance test A.37: Verify conformance via JSON schema (/conf/basic-ypr-encoding-json/definition)") - public void validateByBasicYprSchema() { - - - if(!testSubject.isFile()) { - Assert.assertTrue(testSubject.isFile(),"No file selected. "); - } - - BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); - String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Basic.YPR.Schema.json"; - - boolean valid = false; - StringBuffer sb = new StringBuffer(); - - InputStream inputStream = tester.getClass() - .getResourceAsStream(schemaToApply); - - try { - JsonNode schemaNode = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); - JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); - - schema.initializeValidators(); - - JsonNode node = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); - Set errors = schema.validate(node); - - - - Iterator it = errors.iterator(); - while(it.hasNext()) - { - sb.append(" "+it.next()+".\n"); - - } - - } catch (IOException e) { + + private File testSubject; + + /** + * Obtains the test subject from the ISuite context. The suite attribute + * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should evaluate to a + * DOM Document node. + * @param testContext The test (group) context. + */ + @BeforeClass + public void obtainTestSubject(ITestContext testContext) { + + Object obj = testContext.getSuite().getAttribute(SuiteAttribute.BASICYPR_TEST_SUBJ_FILE.getName()); + + this.testSubject = (File) obj; + + } + + /** + * Sets the test subject. This method is intended to facilitate unit testing. + * @param testSubject A Document node representing the test subject or metadata about + * it. + */ + public void setTestSubject(File testSubject) { + this.testSubject = testSubject; + } + + /** + * Implements Conformance test A.37: Verify conformance via JSON schema Test Method: + * Validate the JSON data against the Basic-YPR JSON Schema 2019-9 definition + */ + @Test(description = "Implements Conformance test A.37: Verify conformance via JSON schema (/conf/basic-ypr-encoding-json/definition)") + public void validateByBasicYprSchema() { + + if (!testSubject.isFile()) { + Assert.assertTrue(testSubject.isFile(), "No file selected. "); + } + + BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); + String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Basic.YPR.Schema.json"; + + boolean valid = false; + StringBuffer sb = new StringBuffer(); + + InputStream inputStream = tester.getClass().getResourceAsStream(schemaToApply); + + try { + JsonNode schemaNode = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); + JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); + + schema.initializeValidators(); + + JsonNode node = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); + Set errors = schema.validate(node); + + Iterator it = errors.iterator(); + while (it.hasNext()) { + sb.append(" " + it.next() + ".\n"); + + } + + } + catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - Assert.assertTrue(sb.toString().length()==0,sb.toString()); - } + Assert.assertTrue(sb.toString().length() == 0, sb.toString()); + } + } diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/Chain.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/Chain.java index 27baa0a..b97b39c 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/Chain.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/Chain.java @@ -32,82 +32,83 @@ import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; +/** + *

    + * Chain class. + *

    + * + */ public class Chain extends CommonFixture { - private File testSubject; - - /** - * Obtains the test subject from the ISuite context. The suite attribute - * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should - * evaluate to a DOM Document node. - * - * @param testContext - * The test (group) context. - */ - @BeforeClass - public void obtainTestSubject(ITestContext testContext) { - - Object obj = testContext.getSuite().getAttribute( - SuiteAttribute.CHAIN_TEST_SUBJ_FILE.getName()); - - this.testSubject = (File) obj; - - } - - /** - * Sets the test subject. This method is intended to facilitate unit - * testing. - * - * @param testSubject A Document node representing the test subject or - * metadata about it. - */ - public void setTestSubject(File testSubject) { - this.testSubject = testSubject; - } - - /** - * Implements Conformance test A.42: Verify conformance via JSON schema - * Validate the JSON data against the GeoPose Chain JSON-Schema 2019-9 definition - */ - @Test(description = "Implements Conformance test A.42: Verify conformance via JSON schema (/conf/chain-encoding-json/definition)") - public void validateByChainSchema() { - - - if(!testSubject.isFile()) { - Assert.assertTrue(testSubject.isFile(),"No file selected. "); - } - - BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); - String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Composite.Chain.Schema.json"; - - boolean valid = false; - StringBuffer sb = new StringBuffer(); - - InputStream inputStream = tester.getClass() - .getResourceAsStream(schemaToApply); - - try { - JsonNode schemaNode = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); - JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); - - schema.initializeValidators(); - - JsonNode node = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); - Set errors = schema.validate(node); - - - - Iterator it = errors.iterator(); - while(it.hasNext()) - { - sb.append(" "+it.next()+".\n"); - - } - - } catch (IOException e) { + + private File testSubject; + + /** + * Obtains the test subject from the ISuite context. The suite attribute + * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should evaluate to a + * DOM Document node. + * @param testContext The test (group) context. + */ + @BeforeClass + public void obtainTestSubject(ITestContext testContext) { + + Object obj = testContext.getSuite().getAttribute(SuiteAttribute.CHAIN_TEST_SUBJ_FILE.getName()); + + this.testSubject = (File) obj; + + } + + /** + * Sets the test subject. This method is intended to facilitate unit testing. + * @param testSubject A Document node representing the test subject or metadata about + * it. + */ + public void setTestSubject(File testSubject) { + this.testSubject = testSubject; + } + + /** + * Implements Conformance test A.42: Verify conformance via JSON schema Validate the + * JSON data against the GeoPose Chain JSON-Schema 2019-9 definition + */ + @Test(description = "Implements Conformance test A.42: Verify conformance via JSON schema (/conf/chain-encoding-json/definition)") + public void validateByChainSchema() { + + if (!testSubject.isFile()) { + Assert.assertTrue(testSubject.isFile(), "No file selected. "); + } + + BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); + String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Composite.Chain.Schema.json"; + + boolean valid = false; + StringBuffer sb = new StringBuffer(); + + InputStream inputStream = tester.getClass().getResourceAsStream(schemaToApply); + + try { + JsonNode schemaNode = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); + JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); + + schema.initializeValidators(); + + JsonNode node = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); + Set errors = schema.validate(node); + + Iterator it = errors.iterator(); + while (it.hasNext()) { + sb.append(" " + it.next() + ".\n"); + + } + + } + catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - Assert.assertTrue(sb.toString().length()==0,sb.toString()); - } + Assert.assertTrue(sb.toString().length() == 0, sb.toString()); + } + } diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/Graph.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/Graph.java index 9aa70fc..44b0260 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/Graph.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/Graph.java @@ -32,82 +32,83 @@ import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; +/** + *

    + * Graph class. + *

    + * + */ public class Graph extends CommonFixture { - private File testSubject; - - /** - * Obtains the test subject from the ISuite context. The suite attribute - * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should - * evaluate to a DOM Document node. - * - * @param testContext - * The test (group) context. - */ - @BeforeClass - public void obtainTestSubject(ITestContext testContext) { - - Object obj = testContext.getSuite().getAttribute( - SuiteAttribute.GRAPH_TEST_SUBJ_FILE.getName()); - - this.testSubject = (File) obj; - - } - - /** - * Sets the test subject. This method is intended to facilitate unit - * testing. - * - * @param testSubject A Document node representing the test subject or - * metadata about it. - */ - public void setTestSubject(File testSubject) { - this.testSubject = testSubject; - } - - /** - * Implements Conformance test A.41: Verify conformance via JSON schema - * Validate the JSON data against the GeoPose Graph JSON-Schema 2019-9 definition - */ - @Test(description = "Implements Conformance test A.41: Verify conformance via JSON schema (/conf/graph-encoding-json/definition)") - public void validateByGraphSchema() { - - - if(!testSubject.isFile()) { - Assert.assertTrue(testSubject.isFile(),"No file selected. "); - } - - BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); - String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Composite.Graph.Schema.json"; - - boolean valid = false; - StringBuffer sb = new StringBuffer(); - - InputStream inputStream = tester.getClass() - .getResourceAsStream(schemaToApply); - - try { - JsonNode schemaNode = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); - JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); - - schema.initializeValidators(); - - JsonNode node = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); - Set errors = schema.validate(node); - - - - Iterator it = errors.iterator(); - while(it.hasNext()) - { - sb.append(" "+it.next()+".\n"); - - } - - } catch (IOException e) { + + private File testSubject; + + /** + * Obtains the test subject from the ISuite context. The suite attribute + * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should evaluate to a + * DOM Document node. + * @param testContext The test (group) context. + */ + @BeforeClass + public void obtainTestSubject(ITestContext testContext) { + + Object obj = testContext.getSuite().getAttribute(SuiteAttribute.GRAPH_TEST_SUBJ_FILE.getName()); + + this.testSubject = (File) obj; + + } + + /** + * Sets the test subject. This method is intended to facilitate unit testing. + * @param testSubject A Document node representing the test subject or metadata about + * it. + */ + public void setTestSubject(File testSubject) { + this.testSubject = testSubject; + } + + /** + * Implements Conformance test A.41: Verify conformance via JSON schema Validate the + * JSON data against the GeoPose Graph JSON-Schema 2019-9 definition + */ + @Test(description = "Implements Conformance test A.41: Verify conformance via JSON schema (/conf/graph-encoding-json/definition)") + public void validateByGraphSchema() { + + if (!testSubject.isFile()) { + Assert.assertTrue(testSubject.isFile(), "No file selected. "); + } + + BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); + String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Composite.Graph.Schema.json"; + + boolean valid = false; + StringBuffer sb = new StringBuffer(); + + InputStream inputStream = tester.getClass().getResourceAsStream(schemaToApply); + + try { + JsonNode schemaNode = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); + JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); + + schema.initializeValidators(); + + JsonNode node = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); + Set errors = schema.validate(node); + + Iterator it = errors.iterator(); + while (it.hasNext()) { + sb.append(" " + it.next() + ".\n"); + + } + + } + catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - Assert.assertTrue(sb.toString().length()==0,sb.toString()); - } + Assert.assertTrue(sb.toString().length() == 0, sb.toString()); + } + } diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/SeriesRegular.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/SeriesRegular.java index 6cb73b0..8898cb4 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/SeriesRegular.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/SeriesRegular.java @@ -32,82 +32,83 @@ import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; +/** + *

    + * SeriesRegular class. + *

    + * + */ public class SeriesRegular extends CommonFixture { - private File testSubject; - - /** - * Obtains the test subject from the ISuite context. The suite attribute - * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should - * evaluate to a DOM Document node. - * - * @param testContext - * The test (group) context. - */ - @BeforeClass - public void obtainTestSubject(ITestContext testContext) { - - Object obj = testContext.getSuite().getAttribute( - SuiteAttribute.SERIESREGULAR_TEST_SUBJ_FILE.getName()); - - this.testSubject = (File) obj; - - } - - /** - * Sets the test subject. This method is intended to facilitate unit - * testing. - * - * @param testSubject A Document node representing the test subject or - * metadata about it. - */ - public void setTestSubject(File testSubject) { - this.testSubject = testSubject; - } - - /** - * Implements Conformance test A.43: Verify conformance via JSON schema - * Validate the JSON data against the GeoPose Regular Series JSON-Schema 2019-9 definition - */ - @Test(description = "Implements Conformance test A.43: Verify conformance via JSON schema ( /conf/series-regular-encoding-json/definition)") - public void validateBySeriesRegularSchema() { - - - if(!testSubject.isFile()) { - Assert.assertTrue(testSubject.isFile(),"No file selected. "); - } - - BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); - String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Composite.Sequence.Series.Regular.Schema.json"; - - boolean valid = false; - StringBuffer sb = new StringBuffer(); - - InputStream inputStream = tester.getClass() - .getResourceAsStream(schemaToApply); - - try { - JsonNode schemaNode = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); - JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); - - schema.initializeValidators(); - - JsonNode node = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); - Set errors = schema.validate(node); - - - - Iterator it = errors.iterator(); - while(it.hasNext()) - { - sb.append(" "+it.next()+".\n"); - - } - - } catch (IOException e) { + + private File testSubject; + + /** + * Obtains the test subject from the ISuite context. The suite attribute + * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should evaluate to a + * DOM Document node. + * @param testContext The test (group) context. + */ + @BeforeClass + public void obtainTestSubject(ITestContext testContext) { + + Object obj = testContext.getSuite().getAttribute(SuiteAttribute.SERIESREGULAR_TEST_SUBJ_FILE.getName()); + + this.testSubject = (File) obj; + + } + + /** + * Sets the test subject. This method is intended to facilitate unit testing. + * @param testSubject A Document node representing the test subject or metadata about + * it. + */ + public void setTestSubject(File testSubject) { + this.testSubject = testSubject; + } + + /** + * Implements Conformance test A.43: Verify conformance via JSON schema Validate the + * JSON data against the GeoPose Regular Series JSON-Schema 2019-9 definition + */ + @Test(description = "Implements Conformance test A.43: Verify conformance via JSON schema ( /conf/series-regular-encoding-json/definition)") + public void validateBySeriesRegularSchema() { + + if (!testSubject.isFile()) { + Assert.assertTrue(testSubject.isFile(), "No file selected. "); + } + + BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); + String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Composite.Sequence.Series.Regular.Schema.json"; + + boolean valid = false; + StringBuffer sb = new StringBuffer(); + + InputStream inputStream = tester.getClass().getResourceAsStream(schemaToApply); + + try { + JsonNode schemaNode = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); + JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); + + schema.initializeValidators(); + + JsonNode node = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); + Set errors = schema.validate(node); + + Iterator it = errors.iterator(); + while (it.hasNext()) { + sb.append(" " + it.next() + ".\n"); + + } + + } + catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - Assert.assertTrue(sb.toString().length()==0,sb.toString()); - } + Assert.assertTrue(sb.toString().length() == 0, sb.toString()); + } + } diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamElement.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamElement.java index 99ce35e..401279b 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamElement.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamElement.java @@ -32,82 +32,84 @@ import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; +/** + *

    + * StreamElement class. + *

    + * + */ public class StreamElement extends CommonFixture { - private File testSubject; - - /** - * Obtains the test subject from the ISuite context. The suite attribute - * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should - * evaluate to a DOM Document node. - * - * @param testContext - * The test (group) context. - */ - @BeforeClass - public void obtainTestSubject(ITestContext testContext) { - - Object obj = testContext.getSuite().getAttribute( - SuiteAttribute.STREAMELEMENT_TEST_SUBJ_FILE.getName()); - - this.testSubject = (File) obj; - - } - - /** - * Sets the test subject. This method is intended to facilitate unit - * testing. - * - * @param testSubject A Document node representing the test subject or - * metadata about it. - */ - public void setTestSubject(File testSubject) { - this.testSubject = testSubject; - } - - /** - * Implements Conformance test A.45: Verify Stream Element conformance to JSON schema - * Validate the JSON data against the GeoPose Stream Element JSON-Schema 2019-9 definition - */ - @Test(description = "Implements Conformance test A.45: Verify Stream Element conformance to JSON schema (/conf/stream-encoding-json/element)") - public void validateByStreamElementSchema() { - - - if(!testSubject.isFile()) { - Assert.assertTrue(testSubject.isFile(),"No file selected. "); - } - - BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); - String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Composite.Sequence.StreamElement.Schema.json"; - - boolean valid = false; - StringBuffer sb = new StringBuffer(); - - InputStream inputStream = tester.getClass() - .getResourceAsStream(schemaToApply); - - try { - JsonNode schemaNode = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); - JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); - - schema.initializeValidators(); - - JsonNode node = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); - Set errors = schema.validate(node); - - - - Iterator it = errors.iterator(); - while(it.hasNext()) - { - sb.append(" "+it.next()+".\n"); - - } - - } catch (IOException e) { + + private File testSubject; + + /** + * Obtains the test subject from the ISuite context. The suite attribute + * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should evaluate to a + * DOM Document node. + * @param testContext The test (group) context. + */ + @BeforeClass + public void obtainTestSubject(ITestContext testContext) { + + Object obj = testContext.getSuite().getAttribute(SuiteAttribute.STREAMELEMENT_TEST_SUBJ_FILE.getName()); + + this.testSubject = (File) obj; + + } + + /** + * Sets the test subject. This method is intended to facilitate unit testing. + * @param testSubject A Document node representing the test subject or metadata about + * it. + */ + public void setTestSubject(File testSubject) { + this.testSubject = testSubject; + } + + /** + * Implements Conformance test A.45: Verify Stream Element conformance to JSON schema + * Validate the JSON data against the GeoPose Stream Element JSON-Schema 2019-9 + * definition + */ + @Test(description = "Implements Conformance test A.45: Verify Stream Element conformance to JSON schema (/conf/stream-encoding-json/element)") + public void validateByStreamElementSchema() { + + if (!testSubject.isFile()) { + Assert.assertTrue(testSubject.isFile(), "No file selected. "); + } + + BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); + String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Composite.Sequence.StreamElement.Schema.json"; + + boolean valid = false; + StringBuffer sb = new StringBuffer(); + + InputStream inputStream = tester.getClass().getResourceAsStream(schemaToApply); + + try { + JsonNode schemaNode = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); + JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); + + schema.initializeValidators(); + + JsonNode node = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); + Set errors = schema.validate(node); + + Iterator it = errors.iterator(); + while (it.hasNext()) { + sb.append(" " + it.next() + ".\n"); + + } + + } + catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - Assert.assertTrue(sb.toString().length()==0,sb.toString()); - } + Assert.assertTrue(sb.toString().length() == 0, sb.toString()); + } + } diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamHeader.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamHeader.java index 01bd2e1..763adfb 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamHeader.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamHeader.java @@ -32,82 +32,83 @@ import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; +/** + *

    + * StreamHeader class. + *

    + * + */ public class StreamHeader extends CommonFixture { - private File testSubject; - - /** - * Obtains the test subject from the ISuite context. The suite attribute - * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should - * evaluate to a DOM Document node. - * - * @param testContext - * The test (group) context. - */ - @BeforeClass - public void obtainTestSubject(ITestContext testContext) { - - Object obj = testContext.getSuite().getAttribute( - SuiteAttribute.STREAMHEADER_TEST_SUBJ_FILE.getName()); - - this.testSubject = (File) obj; - - } - - /** - * Sets the test subject. This method is intended to facilitate unit - * testing. - * - * @param testSubject A Document node representing the test subject or - * metadata about it. - */ - public void setTestSubject(File testSubject) { - this.testSubject = testSubject; - } - - /** - * Implements Conformance test A.42: Verify conformance via JSON schema - * Validate the JSON data against the GeoPose StreamHeader JSON-Schema 2019-9 definition - */ - @Test(description = "Implements Conformance test A.42: Verify conformance via JSON schema (/conf/stream-encoding-json/header)") - public void validateByStreamHeaderSchema() { - - - if(!testSubject.isFile()) { - Assert.assertTrue(testSubject.isFile(),"No file selected. "); - } - - BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); - String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Composite.Sequence.StreamHeader.Schema.json"; - - boolean valid = false; - StringBuffer sb = new StringBuffer(); - - InputStream inputStream = tester.getClass() - .getResourceAsStream(schemaToApply); - - try { - JsonNode schemaNode = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); - JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); - - schema.initializeValidators(); - - JsonNode node = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); - Set errors = schema.validate(node); - - - - Iterator it = errors.iterator(); - while(it.hasNext()) - { - sb.append(" "+it.next()+".\n"); - - } - - } catch (IOException e) { + + private File testSubject; + + /** + * Obtains the test subject from the ISuite context. The suite attribute + * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should evaluate to a + * DOM Document node. + * @param testContext The test (group) context. + */ + @BeforeClass + public void obtainTestSubject(ITestContext testContext) { + + Object obj = testContext.getSuite().getAttribute(SuiteAttribute.STREAMHEADER_TEST_SUBJ_FILE.getName()); + + this.testSubject = (File) obj; + + } + + /** + * Sets the test subject. This method is intended to facilitate unit testing. + * @param testSubject A Document node representing the test subject or metadata about + * it. + */ + public void setTestSubject(File testSubject) { + this.testSubject = testSubject; + } + + /** + * Implements Conformance test A.42: Verify conformance via JSON schema Validate the + * JSON data against the GeoPose StreamHeader JSON-Schema 2019-9 definition + */ + @Test(description = "Implements Conformance test A.42: Verify conformance via JSON schema (/conf/stream-encoding-json/header)") + public void validateByStreamHeaderSchema() { + + if (!testSubject.isFile()) { + Assert.assertTrue(testSubject.isFile(), "No file selected. "); + } + + BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); + String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Composite.Sequence.StreamHeader.Schema.json"; + + boolean valid = false; + StringBuffer sb = new StringBuffer(); + + InputStream inputStream = tester.getClass().getResourceAsStream(schemaToApply); + + try { + JsonNode schemaNode = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); + JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); + + schema.initializeValidators(); + + JsonNode node = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); + Set errors = schema.validate(node); + + Iterator it = errors.iterator(); + while (it.hasNext()) { + sb.append(" " + it.next() + ".\n"); + + } + + } + catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - Assert.assertTrue(sb.toString().length()==0,sb.toString()); - } + Assert.assertTrue(sb.toString().length() == 0, sb.toString()); + } + } diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamRecord.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamRecord.java index 3308788..365b9e7 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamRecord.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamRecord.java @@ -32,82 +32,84 @@ import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; +/** + *

    + * StreamRecord class. + *

    + * + */ public class StreamRecord extends CommonFixture { - private File testSubject; - - /** - * Obtains the test subject from the ISuite context. The suite attribute - * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should - * evaluate to a DOM Document node. - * - * @param testContext - * The test (group) context. - */ - @BeforeClass - public void obtainTestSubject(ITestContext testContext) { - - Object obj = testContext.getSuite().getAttribute( - SuiteAttribute.STREAMRECORD_TEST_SUBJ_FILE.getName()); - - this.testSubject = (File) obj; - - } - - /** - * Sets the test subject. This method is intended to facilitate unit - * testing. - * - * @param testSubject A Document node representing the test subject or - * metadata about it. - */ - public void setTestSubject(File testSubject) { - this.testSubject = testSubject; - } - - /** - * Implements Conformance test A.47: Verify Stream Record conformance to JSON schema - * Validate the JSON data against the GeoPose Stream Record JSON-Schema 2019-9 definition - */ - @Test(description = "Implements Conformance test A.47: Verify Stream Record conformance to JSON schema (/conf/stream-encoding-json/record)") - public void validateByStreamRecordSchema() { - - - if(!testSubject.isFile()) { - Assert.assertTrue(testSubject.isFile(),"No file selected. "); - } - - BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); - String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Composite.Sequence.Stream.Schema.json"; - - boolean valid = false; - StringBuffer sb = new StringBuffer(); - - InputStream inputStream = tester.getClass() - .getResourceAsStream(schemaToApply); - - try { - JsonNode schemaNode = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); - JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); - - schema.initializeValidators(); - - JsonNode node = tester.getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); - Set errors = schema.validate(node); - - - - Iterator it = errors.iterator(); - while(it.hasNext()) - { - sb.append(" "+it.next()+".\n"); - - } - - } catch (IOException e) { + + private File testSubject; + + /** + * Obtains the test subject from the ISuite context. The suite attribute + * {@link org.opengis.cite.geopose10.SuiteAttribute#TEST_SUBJECT} should evaluate to a + * DOM Document node. + * @param testContext The test (group) context. + */ + @BeforeClass + public void obtainTestSubject(ITestContext testContext) { + + Object obj = testContext.getSuite().getAttribute(SuiteAttribute.STREAMRECORD_TEST_SUBJ_FILE.getName()); + + this.testSubject = (File) obj; + + } + + /** + * Sets the test subject. This method is intended to facilitate unit testing. + * @param testSubject A Document node representing the test subject or metadata about + * it. + */ + public void setTestSubject(File testSubject) { + this.testSubject = testSubject; + } + + /** + * Implements Conformance test A.47: Verify Stream Record conformance to JSON schema + * Validate the JSON data against the GeoPose Stream Record JSON-Schema 2019-9 + * definition + */ + @Test(description = "Implements Conformance test A.47: Verify Stream Record conformance to JSON schema (/conf/stream-encoding-json/record)") + public void validateByStreamRecordSchema() { + + if (!testSubject.isFile()) { + Assert.assertTrue(testSubject.isFile(), "No file selected. "); + } + + BaseJsonSchemaValidatorTest tester = new BaseJsonSchemaValidatorTest(); + String schemaToApply = "/org/opengis/cite/geopose10/jsonschema/GeoPose.Composite.Sequence.Stream.Schema.json"; + + boolean valid = false; + StringBuffer sb = new StringBuffer(); + + InputStream inputStream = tester.getClass().getResourceAsStream(schemaToApply); + + try { + JsonNode schemaNode = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(inputStream)); + JsonSchema schema = tester.getJsonSchemaFromJsonNodeAutomaticVersion(schemaNode); + + schema.initializeValidators(); + + JsonNode node = tester + .getJsonNodeFromStringContent(tester.otherConvertInputStreamToString(new FileInputStream(testSubject))); + Set errors = schema.validate(node); + + Iterator it = errors.iterator(); + while (it.hasNext()) { + sb.append(" " + it.next() + ".\n"); + + } + + } + catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - Assert.assertTrue(sb.toString().length()==0,sb.toString()); - } + Assert.assertTrue(sb.toString().length() == 0, sb.toString()); + } + } diff --git a/src/main/java/org/opengis/cite/geopose10/package-info.java b/src/main/java/org/opengis/cite/geopose10/package-info.java index 66bb51a..ee48788 100644 --- a/src/main/java/org/opengis/cite/geopose10/package-info.java +++ b/src/main/java/org/opengis/cite/geopose10/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.geopose10; \ No newline at end of file +package org.opengis.cite.geopose10; \ No newline at end of file diff --git a/src/main/java/org/opengis/cite/geopose10/util/ClientUtils.java b/src/main/java/org/opengis/cite/geopose10/util/ClientUtils.java index 4289a46..3c127c3 100644 --- a/src/main/java/org/opengis/cite/geopose10/util/ClientUtils.java +++ b/src/main/java/org/opengis/cite/geopose10/util/ClientUtils.java @@ -28,117 +28,117 @@ import jakarta.ws.rs.core.UriBuilder; /** - * Provides various utility methods for creating and configuring HTTP client - * components. + * Provides various utility methods for creating and configuring HTTP client components. */ public class ClientUtils { - private static final Logger LOGGER = Logger.getLogger(ClientUtils.class.getName()); + private static final Logger LOGGER = Logger.getLogger(ClientUtils.class.getName()); - /** - * 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(LOGGER, Level.ALL, LoggingFeature.Verbosity.PAYLOAD_ANY, 5000)); - Client client = ClientBuilder.newClient(config); - client.register(new ReusableEntityFilter()); - return client; - } + /** + * 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(LOGGER, Level.ALL, LoggingFeature.Verbosity.PAYLOAD_ANY, 5000)); + Client client = ClientBuilder.newClient(config); + client.register(new ReusableEntityFilter()); + return client; + } - /** - * Constructs a client component that uses a specified web proxy. Proxy authentication - * is not supported. Configuring the client to use an intercepting proxy can be useful - * when debugging a test. - * @param proxyHost The host name or IP address of the proxy server. - * @param proxyPort The port number of the proxy listener. - * @return A Client component that submits requests through a web proxy. - */ - public static Client buildClientWithProxy(final String proxyHost, final int proxyPort) { - ClientConfig config = new ClientConfig(); - config.connectorProvider(new ApacheConnectorProvider()); - config.register(new LoggingFeature(LOGGER, Level.ALL, LoggingFeature.Verbosity.PAYLOAD_ANY, 5000)); - SocketAddress addr = new InetSocketAddress(proxyHost, proxyPort); - Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); - config.property(ClientProperties.PROXY_URI, proxy); - config.property(ClientProperties.FOLLOW_REDIRECTS, true); - config.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY_CLIENT, LoggingFeature.Verbosity.PAYLOAD_ANY); - config.property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_CLIENT, Level.ALL); - Client client = ClientBuilder.newClient(config); - client.register(new ReusableEntityFilter()); - return client; - } + /** + * Constructs a client component that uses a specified web proxy. Proxy authentication + * is not supported. Configuring the client to use an intercepting proxy can be useful + * when debugging a test. + * @param proxyHost The host name or IP address of the proxy server. + * @param proxyPort The port number of the proxy listener. + * @return A Client component that submits requests through a web proxy. + */ + public static Client buildClientWithProxy(final String proxyHost, final int proxyPort) { + ClientConfig config = new ClientConfig(); + config.connectorProvider(new ApacheConnectorProvider()); + config.register(new LoggingFeature(LOGGER, Level.ALL, LoggingFeature.Verbosity.PAYLOAD_ANY, 5000)); + SocketAddress addr = new InetSocketAddress(proxyHost, proxyPort); + Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); + config.property(ClientProperties.PROXY_URI, proxy); + config.property(ClientProperties.FOLLOW_REDIRECTS, true); + config.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY_CLIENT, LoggingFeature.Verbosity.PAYLOAD_ANY); + config.property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_CLIENT, Level.ALL); + Client client = ClientBuilder.newClient(config); + client.register(new ReusableEntityFilter()); + return client; + } - /** - * Builds an HTTP request message that uses the GET method. - * @param endpoint A URI indicating the target resource. - * @param qryParams A Map containing query parameters (may be null); - * @param mediaTypes A list of acceptable media types; if not specified, the Accept - * header is omitted. - * @return A ClientRequest object. - */ - public static Response buildGetRequest(URI endpoint, Map qryParams, MediaType... mediaTypes) { - UriBuilder uriBuilder = UriBuilder.fromUri(endpoint); - if (null != qryParams) { - for (Map.Entry param : qryParams.entrySet()) { - uriBuilder.queryParam(param.getKey(), param.getValue()); - } - } - URI uri = uriBuilder.build(); - WebTarget target = buildClient().target(uri); - Builder reqBuilder = target.request(); - if (null != mediaTypes && mediaTypes.length > 0) { - reqBuilder = reqBuilder.accept(mediaTypes); - } - Invocation req = reqBuilder.buildGet(); - return req.invoke(); - } + /** + * Builds an HTTP request message that uses the GET method. + * @param endpoint A URI indicating the target resource. + * @param qryParams A Map containing query parameters (may be null); + * @param mediaTypes A list of acceptable media types; if not specified, the Accept + * header is omitted. + * @return A ClientRequest object. + */ + public static Response buildGetRequest(URI endpoint, Map qryParams, MediaType... mediaTypes) { + UriBuilder uriBuilder = UriBuilder.fromUri(endpoint); + if (null != qryParams) { + for (Map.Entry param : qryParams.entrySet()) { + uriBuilder.queryParam(param.getKey(), param.getValue()); + } + } + URI uri = uriBuilder.build(); + WebTarget target = buildClient().target(uri); + Builder reqBuilder = target.request(); + if (null != mediaTypes && mediaTypes.length > 0) { + reqBuilder = reqBuilder.accept(mediaTypes); + } + Invocation req = reqBuilder.buildGet(); + return req.invoke(); + } - /** - * Creates a copy of the given MediaType object but without any parameters. - * @param mediaType A MediaType descriptor. - * @return A new (immutable) MediaType object having the same type and subtype. - */ - public static MediaType removeParameters(MediaType mediaType) { - return new MediaType(mediaType.getType(), mediaType.getSubtype()); - } + /** + * Creates a copy of the given MediaType object but without any parameters. + * @param mediaType A MediaType descriptor. + * @return A new (immutable) MediaType object having the same type and subtype. + */ + public static MediaType removeParameters(MediaType mediaType) { + return new MediaType(mediaType.getType(), mediaType.getSubtype()); + } - /** - * Obtains the (XML) response entity as a JAXP Source object 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 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); - } - return source; - } + /** + * Obtains the (XML) response entity as a JAXP Source object 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 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); + } + 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; + } - /** - * 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/geopose10/util/NamespaceBindings.java b/src/main/java/org/opengis/cite/geopose10/util/NamespaceBindings.java index ba228d8..e44bb26 100644 --- a/src/main/java/org/opengis/cite/geopose10/util/NamespaceBindings.java +++ b/src/main/java/org/opengis/cite/geopose10/util/NamespaceBindings.java @@ -9,96 +9,91 @@ import org.opengis.cite.geopose10.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.geopose10.Namespaces#OWS}
    • - *
    • xlink: {@value org.opengis.cite.geopose10.Namespaces#XLINK}
    • - *
    • gml: {@value org.opengis.cite.geopose10.Namespaces#GML}
    • - *
    - * - * @return A NamespaceBindings object. - */ - public static NamespaceBindings withStandardBindings() { - NamespaceBindings nsBindings = new NamespaceBindings(); - nsBindings.addNamespaceBinding(Namespaces.OWS, "ows"); - nsBindings.addNamespaceBinding(Namespaces.XLINK, "xlink"); - nsBindings.addNamespaceBinding(Namespaces.GML, "gml"); - return nsBindings; - } + /** + * Creates a NamespaceBindings object that declares the following namespace bindings: + * + *
      + *
    • ows: {@value org.opengis.cite.geopose10.Namespaces#OWS}
    • + *
    • xlink: {@value org.opengis.cite.geopose10.Namespaces#XLINK}
    • + *
    • gml: {@value org.opengis.cite.geopose10.Namespaces#GML}
    • + *
    + * @return A NamespaceBindings object. + */ + public static NamespaceBindings withStandardBindings() { + NamespaceBindings nsBindings = new NamespaceBindings(); + nsBindings.addNamespaceBinding(Namespaces.OWS, "ows"); + nsBindings.addNamespaceBinding(Namespaces.XLINK, "xlink"); + nsBindings.addNamespaceBinding(Namespaces.GML, "gml"); + 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/geopose10/util/Samples.java b/src/main/java/org/opengis/cite/geopose10/util/Samples.java index 813f925..00e25d6 100644 --- a/src/main/java/org/opengis/cite/geopose10/util/Samples.java +++ b/src/main/java/org/opengis/cite/geopose10/util/Samples.java @@ -1,62 +1,46 @@ package org.opengis.cite.geopose10.util; +/** + *

    + * Samples class. + *

    + * + */ public class Samples { - - public final static String BASIC_EULER_1 = "{\n" + - " \"position\": {\n" + - " \"lon\": -1.8,\n" + - " \"lat\": 50.7,\n" + - " \"h\": 77.26\n" + - " },\n" + - " \"angles\": {\n" + - " \"yaw\": 181.325,\n" + - " \"pitch\": 16.9227,\n" + - " \"roll\": -1.7858\n" + - " }\n" + - "}\n" + - ""; - public final static String BASIC_EULER_2 = "{\n" + - " \"position\": {\n" + - " \"lon\": -1.8,\n" + - " \"lat\": 50.73,\n" + - " \"h\": 73.19\n" + - " },\n" + - " \"angles\": {\n" + - " \"yaw\": 126.5898,\n" + - " \"pitch\": 13.8023,\n" + - " \"roll\": 0.3978\n" + - " }\n" + - "}\n" + - ""; - public final static String BASIC_QUATERNION_1 = "{\n" + - " \"position\": {\n" + - " \"lon\": -1.8,\n" + - " \"lat\": 50.73,\n" + - " \"h\": 73.19\n" + - " },\n" + - " \"quaternion\": {\n" + - " \"x\": -0.129036,\n" + - " \"y\": 0.06133,\n" + - " \"z\": 0.880018,\n" + - " \"w\": 0.452942\n" + - " }\n" + - "}\n" + - ""; - public final static String ADVANCED_1 = "{\n" + - " \"frameSpecification\": {\n" + - " \"authority\": \"/geopose/1.0\",\n" + - " \"id\": \"LTP-ENU\",\n" + - " \"parameters\": \"longitude=-1.8000000&latitude=50.7300000&height=73.19\"\n" + - " },\n" + - " \"quaternion\": {\n" + - " \"x\": -0.149617,\n" + - " \"y\": 0.049202,\n" + - " \"z\": 0.884979,\n" + - " \"w\": 0.438185\n" + - " },\n" + - " \"validTime\": 1673471266374\n" + - "}\n" + - ""; - + + /** + * Constant + * BASIC_EULER_1="{\n \"position\": {\n \""{trunked} + */ + public final static String BASIC_EULER_1 = "{\n" + " \"position\": {\n" + " \"lon\": -1.8,\n" + + " \"lat\": 50.7,\n" + " \"h\": 77.26\n" + " },\n" + " \"angles\": {\n" + " \"yaw\": 181.325,\n" + + " \"pitch\": 16.9227,\n" + " \"roll\": -1.7858\n" + " }\n" + "}\n" + ""; + + /** + * Constant + * BASIC_EULER_2="{\n \"position\": {\n \""{trunked} + */ + public final static String BASIC_EULER_2 = "{\n" + " \"position\": {\n" + " \"lon\": -1.8,\n" + + " \"lat\": 50.73,\n" + " \"h\": 73.19\n" + " },\n" + " \"angles\": {\n" + + " \"yaw\": 126.5898,\n" + " \"pitch\": 13.8023,\n" + " \"roll\": 0.3978\n" + " }\n" + "}\n" + + ""; + + /** + * Constant + * BASIC_QUATERNION_1="{\n \"position\": {\n \""{trunked} + */ + public final static String BASIC_QUATERNION_1 = "{\n" + " \"position\": {\n" + " \"lon\": -1.8,\n" + + " \"lat\": 50.73,\n" + " \"h\": 73.19\n" + " },\n" + " \"quaternion\": {\n" + + " \"x\": -0.129036,\n" + " \"y\": 0.06133,\n" + " \"z\": 0.880018,\n" + " \"w\": 0.452942\n" + + " }\n" + "}\n" + ""; + + /** + * Constant ADVANCED_1="{\n \"frameSpecification\": "{trunked} + */ + public final static String ADVANCED_1 = "{\n" + " \"frameSpecification\": {\n" + + " \"authority\": \"/geopose/1.0\",\n" + " \"id\": \"LTP-ENU\",\n" + + " \"parameters\": \"longitude=-1.8000000&latitude=50.7300000&height=73.19\"\n" + " },\n" + + " \"quaternion\": {\n" + " \"x\": -0.149617,\n" + " \"y\": 0.049202,\n" + " \"z\": 0.884979,\n" + + " \"w\": 0.438185\n" + " },\n" + " \"validTime\": 1673471266374\n" + "}\n" + ""; } diff --git a/src/main/java/org/opengis/cite/geopose10/util/TestSuiteLogger.java b/src/main/java/org/opengis/cite/geopose10/util/TestSuiteLogger.java index 0d60e7d..e2f126e 100644 --- a/src/main/java/org/opengis/cite/geopose10/util/TestSuiteLogger.java +++ b/src/main/java/org/opengis/cite/geopose10/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/geopose10/util/URIUtils.java b/src/main/java/org/opengis/cite/geopose10/util/URIUtils.java index f2745b4..60ff26b 100644 --- a/src/main/java/org/opengis/cite/geopose10/util/URIUtils.java +++ b/src/main/java/org/opengis/cite/geopose10/util/URIUtils.java @@ -22,121 +22,104 @@ 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); - } - 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; -} + /** + * 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; + } + + /** + * 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); + } - /** - * 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); - } } diff --git a/src/main/java/org/opengis/cite/geopose10/util/ValidationUtils.java b/src/main/java/org/opengis/cite/geopose10/util/ValidationUtils.java index 064c02d..5f0b6f7 100644 --- a/src/main/java/org/opengis/cite/geopose10/util/ValidationUtils.java +++ b/src/main/java/org/opengis/cite/geopose10/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/geopose10/"; - private static final XMLCatalogResolver SCH_RESOLVER = initCatalogResolver(); + static final String ROOT_PKG = "/org/opengis/cite/geopose10/"; - 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/geopose10/util/XMLUtils.java b/src/main/java/org/opengis/cite/geopose10/util/XMLUtils.java index 3a63fde..d4af409 100644 --- a/src/main/java/org/opengis/cite/geopose10/util/XMLUtils.java +++ b/src/main/java/org/opengis/cite/geopose10/util/XMLUtils.java @@ -51,360 +51,329 @@ 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 - * omitted and the character encoding is set to "US-ASCII" (any character - * outside of this set is serialized as a numeric character reference). - * - * @param node - * The DOM Node to be serialized. - * @return A String representing the content of the given node. - */ - public static String writeNodeToString(Node node) { - if (null == node) { - return ""; - } - Writer writer = null; - try { - Transformer idTransformer = TransformerFactory.newInstance().newTransformer(); - Properties outProps = new Properties(); - outProps.setProperty(OutputKeys.ENCODING, "US-ASCII"); - outProps.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - outProps.setProperty(OutputKeys.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 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 omitted and + * the character encoding is set to "US-ASCII" (any character outside of this set is + * serialized as a numeric character reference). + * @param node The DOM Node to be serialized. + * @return A String representing the content of the given node. + */ + public static String writeNodeToString(Node node) { + if (null == node) { + return ""; + } + Writer writer = null; + try { + Transformer idTransformer = TransformerFactory.newInstance().newTransformer(); + Properties outProps = new Properties(); + outProps.setProperty(OutputKeys.ENCODING, "US-ASCII"); + outProps.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + outProps.setProperty(OutputKeys.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 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.geopose10.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; + } - /** - * Evaluates an XQuery 1.0 expression using the Saxon s9api interfaces. - * - * @param source - * The XML Source. - * @param query - * The query expression. - * @param nsBindings - * A collection of namespace bindings required to evaluate the - * query, where each entry maps a namespace URI (key) to a prefix - * (value). - * @return An XdmValue object representing a value in the XDM data model. - * @throws SaxonApiException - * If an error occurs while evaluating the query (this always - * wraps some other underlying exception). - */ - public static XdmValue evaluateXQuery(Source source, String query, Map nsBindings) - throws SaxonApiException { - Processor proc = new Processor(false); - XQueryCompiler xqCompiler = proc.newXQueryCompiler(); - if (null != nsBindings) { - for (String nsURI : nsBindings.keySet()) { - xqCompiler.declareNamespace(nsBindings.get(nsURI), nsURI); - } - } - XQueryExecutable xqExec = xqCompiler.compile(query); - XQueryEvaluator xqEval = xqExec.load(); - xqEval.setSource(source); - return xqEval.evaluate(); - } + /** + * 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.geopose10.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; + } - /** - * 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 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(); + } - /** - * 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 XQuery 1.0 expression using the Saxon s9api interfaces. + * @param source The XML Source. + * @param query The query expression. + * @param nsBindings A collection of namespace bindings required to evaluate the + * query, where each entry maps a namespace URI (key) to a prefix (value). + * @return An XdmValue object representing a value in the XDM data model. + * @throws net.sf.saxon.s9api.SaxonApiException If an error occurs while evaluating + * the query (this always wraps some other underlying exception). + */ + public static XdmValue evaluateXQuery(Source source, String query, Map nsBindings) + throws SaxonApiException { + Processor proc = new Processor(false); + XQueryCompiler xqCompiler = proc.newXQueryCompiler(); + if (null != nsBindings) { + for (String nsURI : nsBindings.keySet()) { + xqCompiler.declareNamespace(nsBindings.get(nsURI), nsURI); + } + } + XQueryExecutable xqExec = xqCompiler.compile(query); + XQueryEvaluator xqEval = xqExec.load(); + xqEval.setSource(source); + return xqEval.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; + } - /** - * Expands character entity ({@literal &name;}) and numeric references ( - * {@literal &#xhhhh;} or {@literal &dddd;}) 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; - } + /** + * 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; + } - /** - * Creates a DOM Document with the given Element as the document element. A - * deep copy of the element is imported; the source element is not altered. - * - * @param elem - * An Element node. - * @return A Document node. - */ - public static Document importElement(Element elem) { - javax.xml.parsers.DocumentBuilder docBuilder = null; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - docBuilder = factory.newDocumentBuilder(); - } catch (ParserConfigurationException ex) { - LOGR.log(Level.WARNING, null, ex); - } - Document newDoc = docBuilder.newDocument(); - Node newNode = newDoc.importNode(elem, true); - newDoc.appendChild(newNode); - return newDoc; - } + /** + * 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 ({@literal &name;}) and numeric references ( + * {@literal &#xhhhh;} or {@literal &dddd;}) 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; + } + + /** + * Creates a DOM Document with the given Element as the document element. A deep copy + * of the element is imported; the source element is not altered. + * @param elem An Element node. + * @return A Document node. + */ + public static Document importElement(Element elem) { + javax.xml.parsers.DocumentBuilder docBuilder = null; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + docBuilder = factory.newDocumentBuilder(); + } + catch (ParserConfigurationException ex) { + LOGR.log(Level.WARNING, null, ex); + } + Document newDoc = docBuilder.newDocument(); + Node newNode = newDoc.importNode(elem, true); + newDoc.appendChild(newNode); + return newDoc; + } + + /** + * Returns a List view of the nodes in the given NodeList collection. + * @param nodeList An ordered collection of DOM nodes. + * @return A List containing the original sequence of Node objects. + */ + public static List asList(NodeList nodeList) { + List nodes = new ArrayList<>(); + for (int i = 0; i < nodeList.getLength(); i++) { + nodes.add(nodeList.item(i)); + } + return nodes; + } - /** - * Returns a List view of the nodes in the given NodeList collection. - * - * @param nodeList - * An ordered collection of DOM nodes. - * @return A List containing the original sequence of Node objects. - */ - public static List asList(NodeList nodeList) { - List nodes = new ArrayList<>(); - for (int i = 0; i < nodeList.getLength(); i++) { - nodes.add(nodeList.item(i)); - } - return nodes; - } } diff --git a/src/test/java/org/opengis/cite/geopose10/VerifyETSAssert.java b/src/test/java/org/opengis/cite/geopose10/VerifyETSAssert.java index 0bee9ea..6a4f2cb 100644 --- a/src/test/java/org/opengis/cite/geopose10/VerifyETSAssert.java +++ b/src/test/java/org/opengis/cite/geopose10/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/geopose10/util/VerifyURIUtils.java b/src/test/java/org/opengis/cite/geopose10/util/VerifyURIUtils.java index d03327f..e946d97 100644 --- a/src/test/java/org/opengis/cite/geopose10/util/VerifyURIUtils.java +++ b/src/test/java/org/opengis/cite/geopose10/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/geopose10/util/VerifyValidationUtils.java b/src/test/java/org/opengis/cite/geopose10/util/VerifyValidationUtils.java index fe8ccce..c893349 100644 --- a/src/test/java/org/opengis/cite/geopose10/util/VerifyValidationUtils.java +++ b/src/test/java/org/opengis/cite/geopose10/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/geopose10/util/VerifyXMLUtils.java b/src/test/java/org/opengis/cite/geopose10/util/VerifyXMLUtils.java index ab7e464..1208eab 100644 --- a/src/test/java/org/opengis/cite/geopose10/util/VerifyXMLUtils.java +++ b/src/test/java/org/opengis/cite/geopose10/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); + } + } From cb3756495eda0c2ca2dac0d3adfe53e3373894af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Pro=C3=9F?= Date: Tue, 17 Dec 2024 15:04:07 +0100 Subject: [PATCH 4/8] Organize imports --- .../geopose10/BaseJsonSchemaValidatorTest.java | 2 +- .../cite/geopose10/CommandLineArguments.java | 3 ++- .../org/opengis/cite/geopose10/CommonFixture.java | 1 - .../cite/geopose10/encodings/json/Advanced.java | 15 +-------------- .../geopose10/encodings/json/BasicQuaternion.java | 15 +-------------- .../cite/geopose10/encodings/json/BasicYPR.java | 15 +-------------- .../cite/geopose10/encodings/json/Chain.java | 15 +-------------- .../cite/geopose10/encodings/json/Graph.java | 15 +-------------- .../geopose10/encodings/json/SeriesRegular.java | 15 +-------------- .../geopose10/encodings/json/StreamElement.java | 15 +-------------- .../geopose10/encodings/json/StreamHeader.java | 15 +-------------- .../geopose10/encodings/json/StreamRecord.java | 15 +-------------- .../cite/geopose10/util/NamespaceBindings.java | 2 ++ .../org/opengis/cite/geopose10/util/XMLUtils.java | 10 +++++----- .../opengis/cite/geopose10/VerifyETSAssert.java | 2 ++ .../geopose10/util/VerifyValidationUtils.java | 3 ++- .../cite/geopose10/util/VerifyXMLUtils.java | 8 +++++--- 17 files changed, 28 insertions(+), 138 deletions(-) diff --git a/src/main/java/org/opengis/cite/geopose10/BaseJsonSchemaValidatorTest.java b/src/main/java/org/opengis/cite/geopose10/BaseJsonSchemaValidatorTest.java index c603d40..8d4b5cb 100644 --- a/src/main/java/org/opengis/cite/geopose10/BaseJsonSchemaValidatorTest.java +++ b/src/main/java/org/opengis/cite/geopose10/BaseJsonSchemaValidatorTest.java @@ -9,8 +9,8 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.networknt.schema.JsonSchemaFactory; import com.networknt.schema.JsonSchema; +import com.networknt.schema.JsonSchemaFactory; import com.networknt.schema.SpecVersion; import com.networknt.schema.SpecVersionDetector; diff --git a/src/main/java/org/opengis/cite/geopose10/CommandLineArguments.java b/src/main/java/org/opengis/cite/geopose10/CommandLineArguments.java index 93f8327..1b7a928 100644 --- a/src/main/java/org/opengis/cite/geopose10/CommandLineArguments.java +++ b/src/main/java/org/opengis/cite/geopose10/CommandLineArguments.java @@ -1,11 +1,12 @@ package org.opengis.cite.geopose10; -import com.beust.jcommander.Parameter; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.List; +import com.beust.jcommander.Parameter; + /** * Declares supported command line arguments that are parsed using the JCommander library. * All arguments are optional. The default values are as follows: diff --git a/src/main/java/org/opengis/cite/geopose10/CommonFixture.java b/src/main/java/org/opengis/cite/geopose10/CommonFixture.java index 80c59ed..0548c20 100644 --- a/src/main/java/org/opengis/cite/geopose10/CommonFixture.java +++ b/src/main/java/org/opengis/cite/geopose10/CommonFixture.java @@ -4,7 +4,6 @@ import java.util.Map; import org.glassfish.jersey.client.ClientRequest; -import org.glassfish.jersey.client.ClientResponse; import org.opengis.cite.geopose10.util.ClientUtils; import org.testng.ITestContext; import org.testng.annotations.BeforeClass; diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/Advanced.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/Advanced.java index 8893707..82cca17 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/Advanced.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/Advanced.java @@ -1,35 +1,22 @@ package org.opengis.cite.geopose10.encodings.json; -import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; -import org.opengis.cite.geopose10.CommonFixture; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.net.URL; import java.util.Iterator; import java.util.Set; +import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; import org.opengis.cite.geopose10.CommonFixture; -import org.opengis.cite.geopose10.ErrorMessage; -import org.opengis.cite.geopose10.ErrorMessageKeys; import org.opengis.cite.geopose10.SuiteAttribute; -import org.opengis.cite.geopose10.util.Samples; -import org.opengis.cite.validation.RelaxNGValidator; -import org.opengis.cite.validation.ValidationErrorHandler; import org.testng.Assert; import org.testng.ITestContext; -import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.networknt.schema.JsonSchemaFactory; import com.networknt.schema.JsonSchema; -import com.networknt.schema.SpecVersion; -import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; /** diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicQuaternion.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicQuaternion.java index 11aedf4..fec857d 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicQuaternion.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicQuaternion.java @@ -1,35 +1,22 @@ package org.opengis.cite.geopose10.encodings.json; -import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; -import org.opengis.cite.geopose10.CommonFixture; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.net.URL; import java.util.Iterator; import java.util.Set; +import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; import org.opengis.cite.geopose10.CommonFixture; -import org.opengis.cite.geopose10.ErrorMessage; -import org.opengis.cite.geopose10.ErrorMessageKeys; import org.opengis.cite.geopose10.SuiteAttribute; -import org.opengis.cite.geopose10.util.Samples; -import org.opengis.cite.validation.RelaxNGValidator; -import org.opengis.cite.validation.ValidationErrorHandler; import org.testng.Assert; import org.testng.ITestContext; -import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.networknt.schema.JsonSchemaFactory; import com.networknt.schema.JsonSchema; -import com.networknt.schema.SpecVersion; -import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; /** diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicYPR.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicYPR.java index 22e66e5..1abc2ee 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicYPR.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/BasicYPR.java @@ -1,35 +1,22 @@ package org.opengis.cite.geopose10.encodings.json; -import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; -import org.opengis.cite.geopose10.CommonFixture; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.net.URL; import java.util.Iterator; import java.util.Set; +import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; import org.opengis.cite.geopose10.CommonFixture; -import org.opengis.cite.geopose10.ErrorMessage; -import org.opengis.cite.geopose10.ErrorMessageKeys; import org.opengis.cite.geopose10.SuiteAttribute; -import org.opengis.cite.geopose10.util.Samples; -import org.opengis.cite.validation.RelaxNGValidator; -import org.opengis.cite.validation.ValidationErrorHandler; import org.testng.Assert; import org.testng.ITestContext; -import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.networknt.schema.JsonSchemaFactory; import com.networknt.schema.JsonSchema; -import com.networknt.schema.SpecVersion; -import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; /** diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/Chain.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/Chain.java index b97b39c..32a6c0d 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/Chain.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/Chain.java @@ -1,35 +1,22 @@ package org.opengis.cite.geopose10.encodings.json; -import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; -import org.opengis.cite.geopose10.CommonFixture; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.net.URL; import java.util.Iterator; import java.util.Set; +import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; import org.opengis.cite.geopose10.CommonFixture; -import org.opengis.cite.geopose10.ErrorMessage; -import org.opengis.cite.geopose10.ErrorMessageKeys; import org.opengis.cite.geopose10.SuiteAttribute; -import org.opengis.cite.geopose10.util.Samples; -import org.opengis.cite.validation.RelaxNGValidator; -import org.opengis.cite.validation.ValidationErrorHandler; import org.testng.Assert; import org.testng.ITestContext; -import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.networknt.schema.JsonSchemaFactory; import com.networknt.schema.JsonSchema; -import com.networknt.schema.SpecVersion; -import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; /** diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/Graph.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/Graph.java index 44b0260..fd29b5f 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/Graph.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/Graph.java @@ -1,35 +1,22 @@ package org.opengis.cite.geopose10.encodings.json; -import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; -import org.opengis.cite.geopose10.CommonFixture; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.net.URL; import java.util.Iterator; import java.util.Set; +import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; import org.opengis.cite.geopose10.CommonFixture; -import org.opengis.cite.geopose10.ErrorMessage; -import org.opengis.cite.geopose10.ErrorMessageKeys; import org.opengis.cite.geopose10.SuiteAttribute; -import org.opengis.cite.geopose10.util.Samples; -import org.opengis.cite.validation.RelaxNGValidator; -import org.opengis.cite.validation.ValidationErrorHandler; import org.testng.Assert; import org.testng.ITestContext; -import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.networknt.schema.JsonSchemaFactory; import com.networknt.schema.JsonSchema; -import com.networknt.schema.SpecVersion; -import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; /** diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/SeriesRegular.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/SeriesRegular.java index 8898cb4..d9d2928 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/SeriesRegular.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/SeriesRegular.java @@ -1,35 +1,22 @@ package org.opengis.cite.geopose10.encodings.json; -import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; -import org.opengis.cite.geopose10.CommonFixture; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.net.URL; import java.util.Iterator; import java.util.Set; +import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; import org.opengis.cite.geopose10.CommonFixture; -import org.opengis.cite.geopose10.ErrorMessage; -import org.opengis.cite.geopose10.ErrorMessageKeys; import org.opengis.cite.geopose10.SuiteAttribute; -import org.opengis.cite.geopose10.util.Samples; -import org.opengis.cite.validation.RelaxNGValidator; -import org.opengis.cite.validation.ValidationErrorHandler; import org.testng.Assert; import org.testng.ITestContext; -import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.networknt.schema.JsonSchemaFactory; import com.networknt.schema.JsonSchema; -import com.networknt.schema.SpecVersion; -import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; /** diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamElement.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamElement.java index 401279b..911e951 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamElement.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamElement.java @@ -1,35 +1,22 @@ package org.opengis.cite.geopose10.encodings.json; -import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; -import org.opengis.cite.geopose10.CommonFixture; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.net.URL; import java.util.Iterator; import java.util.Set; +import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; import org.opengis.cite.geopose10.CommonFixture; -import org.opengis.cite.geopose10.ErrorMessage; -import org.opengis.cite.geopose10.ErrorMessageKeys; import org.opengis.cite.geopose10.SuiteAttribute; -import org.opengis.cite.geopose10.util.Samples; -import org.opengis.cite.validation.RelaxNGValidator; -import org.opengis.cite.validation.ValidationErrorHandler; import org.testng.Assert; import org.testng.ITestContext; -import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.networknt.schema.JsonSchemaFactory; import com.networknt.schema.JsonSchema; -import com.networknt.schema.SpecVersion; -import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; /** diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamHeader.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamHeader.java index 763adfb..3bba2b6 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamHeader.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamHeader.java @@ -1,35 +1,22 @@ package org.opengis.cite.geopose10.encodings.json; -import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; -import org.opengis.cite.geopose10.CommonFixture; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.net.URL; import java.util.Iterator; import java.util.Set; +import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; import org.opengis.cite.geopose10.CommonFixture; -import org.opengis.cite.geopose10.ErrorMessage; -import org.opengis.cite.geopose10.ErrorMessageKeys; import org.opengis.cite.geopose10.SuiteAttribute; -import org.opengis.cite.geopose10.util.Samples; -import org.opengis.cite.validation.RelaxNGValidator; -import org.opengis.cite.validation.ValidationErrorHandler; import org.testng.Assert; import org.testng.ITestContext; -import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.networknt.schema.JsonSchemaFactory; import com.networknt.schema.JsonSchema; -import com.networknt.schema.SpecVersion; -import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; /** diff --git a/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamRecord.java b/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamRecord.java index 365b9e7..619f3ec 100644 --- a/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamRecord.java +++ b/src/main/java/org/opengis/cite/geopose10/encodings/json/StreamRecord.java @@ -1,35 +1,22 @@ package org.opengis.cite.geopose10.encodings.json; -import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; -import org.opengis.cite.geopose10.CommonFixture; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.net.URL; import java.util.Iterator; import java.util.Set; +import org.opengis.cite.geopose10.BaseJsonSchemaValidatorTest; import org.opengis.cite.geopose10.CommonFixture; -import org.opengis.cite.geopose10.ErrorMessage; -import org.opengis.cite.geopose10.ErrorMessageKeys; import org.opengis.cite.geopose10.SuiteAttribute; -import org.opengis.cite.geopose10.util.Samples; -import org.opengis.cite.validation.RelaxNGValidator; -import org.opengis.cite.validation.ValidationErrorHandler; import org.testng.Assert; import org.testng.ITestContext; -import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.networknt.schema.JsonSchemaFactory; import com.networknt.schema.JsonSchema; -import com.networknt.schema.SpecVersion; -import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.ValidationMessage; /** diff --git a/src/main/java/org/opengis/cite/geopose10/util/NamespaceBindings.java b/src/main/java/org/opengis/cite/geopose10/util/NamespaceBindings.java index e44bb26..c0910ca 100644 --- a/src/main/java/org/opengis/cite/geopose10/util/NamespaceBindings.java +++ b/src/main/java/org/opengis/cite/geopose10/util/NamespaceBindings.java @@ -5,7 +5,9 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; + import javax.xml.namespace.NamespaceContext; + import org.opengis.cite.geopose10.Namespaces; /** diff --git a/src/main/java/org/opengis/cite/geopose10/util/XMLUtils.java b/src/main/java/org/opengis/cite/geopose10/util/XMLUtils.java index d4af409..3c0113c 100644 --- a/src/main/java/org/opengis/cite/geopose10/util/XMLUtils.java +++ b/src/main/java/org/opengis/cite/geopose10/util/XMLUtils.java @@ -30,6 +30,11 @@ import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + import net.sf.saxon.s9api.DOMDestination; import net.sf.saxon.s9api.DocumentBuilder; import net.sf.saxon.s9api.Processor; @@ -45,11 +50,6 @@ import net.sf.saxon.s9api.XsltExecutable; import net.sf.saxon.s9api.XsltTransformer; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - /** * Provides various utility methods for accessing or manipulating XML representations. */ diff --git a/src/test/java/org/opengis/cite/geopose10/VerifyETSAssert.java b/src/test/java/org/opengis/cite/geopose10/VerifyETSAssert.java index 6a4f2cb..79483fc 100644 --- a/src/test/java/org/opengis/cite/geopose10/VerifyETSAssert.java +++ b/src/test/java/org/opengis/cite/geopose10/VerifyETSAssert.java @@ -4,6 +4,7 @@ import java.net.URL; import java.util.HashMap; import java.util.Map; + import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -12,6 +13,7 @@ import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; + import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; diff --git a/src/test/java/org/opengis/cite/geopose10/util/VerifyValidationUtils.java b/src/test/java/org/opengis/cite/geopose10/util/VerifyValidationUtils.java index c893349..4aed40e 100644 --- a/src/test/java/org/opengis/cite/geopose10/util/VerifyValidationUtils.java +++ b/src/test/java/org/opengis/cite/geopose10/util/VerifyValidationUtils.java @@ -1,6 +1,7 @@ package org.opengis.cite.geopose10.util; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; diff --git a/src/test/java/org/opengis/cite/geopose10/util/VerifyXMLUtils.java b/src/test/java/org/opengis/cite/geopose10/util/VerifyXMLUtils.java index 1208eab..585f8d1 100644 --- a/src/test/java/org/opengis/cite/geopose10/util/VerifyXMLUtils.java +++ b/src/test/java/org/opengis/cite/geopose10/util/VerifyXMLUtils.java @@ -3,14 +3,12 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; + import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.xpath.XPathExpressionException; -import net.sf.saxon.s9api.SaxonApiException; -import net.sf.saxon.s9api.XdmValue; -import net.sf.saxon.trans.XPathException; import org.junit.Assert; import org.junit.BeforeClass; @@ -21,6 +19,10 @@ import org.w3c.dom.NodeList; import org.xml.sax.SAXException; +import net.sf.saxon.s9api.SaxonApiException; +import net.sf.saxon.s9api.XdmValue; +import net.sf.saxon.trans.XPathException; + /** * Verifies the behavior of the XMLUtils class. */ From 0badb06a034a72a6ca823a2349846816688ff2f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Pro=C3=9F?= Date: Tue, 17 Dec 2024 15:15:18 +0100 Subject: [PATCH 5/8] Adjust assembly files --- src/assembly/aio.xml | 3 --- src/assembly/deps.xml | 16 ++++------------ 2 files changed, 4 insertions(+), 15 deletions(-) diff --git a/src/assembly/aio.xml b/src/assembly/aio.xml index 637399b..34c320c 100644 --- a/src/assembly/aio.xml +++ b/src/assembly/aio.xml @@ -12,9 +12,6 @@ true true runtime - - com.sun.jersey:jersey-server - diff --git a/src/assembly/deps.xml b/src/assembly/deps.xml index e878346..080a72e 100644 --- a/src/assembly/deps.xml +++ b/src/assembly/deps.xml @@ -10,21 +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 + *:jersey-client + *:jersey-server + *:jersey-common + jakarta.ws.rs:jakarta.ws.rs-api / false From d724923e0259f26a9f5fcef332556d62da39993f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Pro=C3=9F?= Date: Tue, 17 Dec 2024 15:15:31 +0100 Subject: [PATCH 6/8] Fix console execution --- .../java/org/opengis/cite/geopose10/CommandLineArguments.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/opengis/cite/geopose10/CommandLineArguments.java b/src/main/java/org/opengis/cite/geopose10/CommandLineArguments.java index 1b7a928..671ed2e 100644 --- a/src/main/java/org/opengis/cite/geopose10/CommandLineArguments.java +++ b/src/main/java/org/opengis/cite/geopose10/CommandLineArguments.java @@ -27,7 +27,7 @@ public class CommandLineArguments { @Parameter(description = "Properties file") - private final List xmlProps; + private List xmlProps; @Parameter(names = { "-o", "--outputDir" }, description = "Output directory") private String outputDir; From 4c00dae974abee86445ca5fe18ab92135002310a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Pro=C3=9F?= Date: Tue, 17 Dec 2024 15:15:41 +0100 Subject: [PATCH 7/8] Adjust Dockerfile --- src/docker/Dockerfile | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/docker/Dockerfile b/src/docker/Dockerfile index 6acec14..4ad327f 100644 --- 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-geopose10-*-ctl.zip -d /root/te_base/scripts ADD maven/ets-geopose10-*-deps.zip /root/ RUN cd /root/ && unzip -q -o ets-geopose10-*-deps.zip -d /usr/local/tomcat/webapps/teamengine/WEB-INF/lib +RUN rm -R /root/te_base/scripts/note + # run tomcat CMD ["catalina.sh", "jpda", "run"] \ No newline at end of file From c4d13008defcbdb32e0afa29c6c9d3bb2c5a15a0 Mon Sep 17 00:00:00 2001 From: Dirk Stenger Date: Fri, 3 Jan 2025 16:21:01 +0100 Subject: [PATCH 8/8] #20 - Add plugin and adjust outdated and delete obsolete content in pom.xml and update jenkinsfiles --- jenkinsfiles/build/Jenkinsfile | 6 ++-- jenkinsfiles/release/Jenkinsfile | 4 +-- pom.xml | 61 +++++++------------------------- 3 files changed, 18 insertions(+), 53 deletions(-) diff --git a/jenkinsfiles/build/Jenkinsfile b/jenkinsfiles/build/Jenkinsfile index c9c35af..2688484 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 -Pintegration-tests,docker' + 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 9808bcc..4571ac0 100644 --- a/jenkinsfiles/release/Jenkinsfile +++ b/jenkinsfiles/release/Jenkinsfile @@ -1,8 +1,8 @@ pipeline { agent any tools { - maven 'mvn' - jdk 'JDK 8' + maven 'mvn396' + jdk 'temurin-jdk17' } stages { stage('Initialize') { diff --git a/pom.xml b/pom.xml index 50200db..783a3b2 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,5 @@ - + org.opengis.cite @@ -13,17 +14,17 @@ GeoPose 1.0 Conformance Test Suite Describe purpose of test suite. - http://opengeospatial.github.io/ets-geopose10/ + https://opengeospatial.github.io/ets-geopose10/ Apache License, Version 2.0 - http://opensource.org/licenses/Apache-2.0 + https://opensource.org/licenses/Apache-2.0 Open Geospatial Consortium - http://www.opengeospatial.org/ + https://www.ogc.org/ scm:git:https://github.com/opengeospatial/ets-geopose10.git @@ -37,9 +38,8 @@ - Alpha Beta - https://github.com/ - UTC + Dirk Stenger + https://github.com/dstenger @@ -48,7 +48,7 @@ 1.0 - + com.fasterxml.jackson.core jackson-databind @@ -72,7 +72,7 @@ com.networknt json-schema-validator - + org.opengis.cite.teamengine teamengine-spi @@ -105,22 +105,13 @@ org.opengis.cite.geopose10.TestNGController - - ${basedir}/src/assembly/deps.xml - ${basedir}/src/assembly/ctl-scripts.xml - ${basedir}/src/assembly/aio.xml - - - - package - - single - - - + + + maven-scm-publish-plugin + @@ -129,28 +120,6 @@ - ogccite/${project.artifactId} - - ${project.basedir}/src/docker - - ${project.version}-teamengine-${teamengine.version} - - - - - - ${project.build.directory} - . - - dependency/*teamengine-*.war - dependency/*teamengine-*.zip - *ets-*.zip - - - - - - 8081:8080 @@ -209,10 +178,6 @@ - - sonatype-nexus-staging - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - site scm:git:git@github.com:opengeospatial/ets-geopose10.git