From e6b33fc83f5b833e34227bb5a8d86d39847a61a0 Mon Sep 17 00:00:00 2001 From: Dirk Stenger Date: Thu, 17 Oct 2024 17:49:53 +0200 Subject: [PATCH] #122 - Include updated ets-common and refactorings --- pom.xml | 151 +--- .../ogcapiedr10/CommandLineArguments.java | 70 +- .../cite/ogcapiedr10/CommonDataFixture.java | 35 +- .../cite/ogcapiedr10/CommonFixture.java | 220 +++-- .../cite/ogcapiedr10/ErrorMessage.java | 67 +- .../cite/ogcapiedr10/ErrorMessageKeys.java | 41 +- .../opengis/cite/ogcapiedr10/EtsAssert.java | 40 +- .../opengis/cite/ogcapiedr10/Namespaces.java | 37 +- .../opengis/cite/ogcapiedr10/OgcApiEdr10.java | 8 +- .../cite/ogcapiedr10/SuiteAttribute.java | 151 ++-- .../ogcapiedr10/SuiteFixtureListener.java | 274 +++--- .../cite/ogcapiedr10/SuitePreconditions.java | 55 +- .../cite/ogcapiedr10/TestFailureListener.java | 151 ++-- .../cite/ogcapiedr10/TestNGController.java | 270 +++--- .../opengis/cite/ogcapiedr10/TestRunArg.java | 29 +- .../cite/ogcapiedr10/TestRunListener.java | 27 +- .../collections/AbstractFeatures.java | 17 +- .../collections/AreaCollections.java | 93 +- .../collections/CollectionsTime.java | 844 ++++++++---------- .../collections/CorridorCollections.java | 177 ++-- .../collections/CubeCollections.java | 83 +- .../collections/FeaturesAssertions.java | 143 ++- .../collections/LocationsCollections.java | 59 +- .../collections/PositionCollections.java | 83 +- .../collections/TrajectoryCollections.java | 81 +- .../conformance/ApiDefinition.java | 144 +-- .../ogcapiedr10/conformance/Conformance.java | 210 +++-- .../conformance/RequirementClass.java | 111 ++- .../corecollections/Collections.java | 232 ++--- .../corecollections/CollectionsResponse.java | 815 ++++++++--------- .../edrgeojson/EDRGeoJSONEncoding.java | 402 ++++----- .../encodings/geojson/GeoJSONEncoding.java | 172 ++-- .../encodings/geojson/GeoJSONValidator.java | 78 +- .../encodings/json/JSONEncoding.java | 40 +- .../ogcapiedr10/landingpage/LandingPage.java | 71 +- .../ogcapiedr10/openapi3/OpenApiUtils.java | 251 +++--- .../cite/ogcapiedr10/openapi3/TestPoint.java | 181 ++-- .../cite/ogcapiedr10/openapi3/UriBuilder.java | 126 ++- .../cite/ogcapiedr10/package-info.java | 11 +- .../queries/AbstractProcessor.java | 30 +- .../queries/AreaQueryProcessor.java | 496 +++++----- .../queries/CorridorQueryProcessor.java | 492 +++++----- .../queries/PositionQueryProcessor.java | 449 +++++----- .../ogcapiedr10/queries/QueryCollections.java | 254 +++--- .../queries/TrajectoryQueryProcessor.java | 486 +++++----- .../opengis/cite/ogcapiedr10/util/BBox.java | 110 ++- .../cite/ogcapiedr10/util/ClientUtils.java | 300 +++---- .../cite/ogcapiedr10/util/JsonUtils.java | 730 ++++++++------- .../opengis/cite/ogcapiedr10/util/Link.java | 31 +- .../ogcapiedr10/util/NamespaceBindings.java | 153 ++-- .../cite/ogcapiedr10/util/TemporalExtent.java | 24 +- .../ogcapiedr10/util/TestSuiteLogger.java | 107 ++- .../cite/ogcapiedr10/util/URIUtils.java | 91 +- .../cite/ogcapiedr10/util/XMLUtils.java | 54 +- .../VerifySuiteFixtureListener.java | 67 +- .../ogcapiedr10/VerifyTestNGController.java | 27 +- 56 files changed, 4755 insertions(+), 5196 deletions(-) diff --git a/pom.xml b/pom.xml index 2c15d4e..64c847c 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,5 @@ - + org.opengis.cite @@ -13,17 +14,17 @@ OGC API - Environmental Data Retrieval 1.0 Conformance Test Suite Describe purpose of test suite. - http://opengeospatial.github.io/ets-ogcapi-edr10/ + https://opengeospatial.github.io/ets-ogcapi-edr10/ 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-ogcapi-edr10.git @@ -37,9 +38,9 @@ - Alpha Beta - https://github.com/ - UTC + D. Stenger + https://github.com/dstenger + Europe/Berlin @@ -86,7 +87,7 @@ openapi-parser - io.rest-assured + io.rest-assured rest-assured @@ -132,17 +133,17 @@ json - org.glassfish.jersey.core + org.glassfish.jersey.core jersey-server - org.glassfish.jersey.core + org.glassfish.jersey.core jersey-client - org.glassfish.jersey.inject + org.glassfish.jersey.inject jersey-hk2 - + org.glassfish.jersey.connectors jersey-apache-connector @@ -158,7 +159,7 @@ org.apache.sis.non-free sis-embedded-data - + org.mockito mockito-core @@ -176,111 +177,29 @@ org.opengis.cite.ogcapiedr10.TestNGController - - ${basedir}/src/assembly/deps.xml - ${basedir}/src/assembly/ctl-scripts.xml - ${basedir}/src/assembly/aio.xml - - - - - package - - single - - - - - - maven-surefire-plugin - - - maven-compiler-plugin - - - maven-jar-plugin - - - maven-release-plugin - 3.0.1 - - true - @{project.version} - release - - - - org.apache.maven.plugins - maven-site-plugin - 3.12.1 - - - site-package - prepare-package - - jar - - - - - - org.asciidoctor - asciidoctor-maven-plugin - 3.0.0 - - - - 17 - false - - org.codehaus.mojo - buildnumber-maven-plugin - maven-scm-publish-plugin - 3.2.1 - - gh-pages - + io.fabric8 docker-maven-plugin - 0.43.4 - ogccite/${project.artifactId} - ${project.basedir}/src/docker ${project.version}-teamengine-${docker.teamengine.version} - - - - - ${project.build.directory} - . - - dependency/*teamengine-*.war - dependency/*teamengine-*.zip - *ets-*.zip - - - - - 8081:8080 - 8000:8000 @@ -295,7 +214,6 @@ maven-dependency-plugin - 3.6.1 @@ -332,15 +250,6 @@ maven-failsafe-plugin - 3.2.5 - - - - integration-test - verify - - - @@ -380,32 +289,6 @@ - - release - - - - maven-gpg-plugin - 3.1.0 - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - - - - @@ -419,10 +302,6 @@ - - sonatype-nexus-staging - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - site scm:git:git@github.com:opengeospatial/ets-ogcapi-edr10.git diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/CommandLineArguments.java b/src/main/java/org/opengis/cite/ogcapiedr10/CommandLineArguments.java index fedbda9..c17d481 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/CommandLineArguments.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/CommandLineArguments.java @@ -8,9 +8,8 @@ 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: + * 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}
  • @@ -27,35 +26,38 @@ */ public class CommandLineArguments { - @Parameter(description = "Properties file") - private 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 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; + } + } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/CommonDataFixture.java b/src/main/java/org/opengis/cite/ogcapiedr10/CommonDataFixture.java index 9be6221..6c2b2a3 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/CommonDataFixture.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/CommonDataFixture.java @@ -23,29 +23,26 @@ public class CommonDataFixture extends CommonFixture { private static final int DEFAULT_NUMBER_OF_COLLECTIONS = 3; private OpenApi3 apiModel = null; - + public URI modelUri = null; private List requirementClasses; protected int noOfCollections = DEFAULT_NUMBER_OF_COLLECTIONS; - - - - public OpenApi3 getModel() - { - if(this.apiModel==null) { + + public OpenApi3 getModel() { + if (this.apiModel == null) { String msg = "apiModel is null in CommonDataFixture"; System.out.println(msg); throw new NullPointerException(msg); } return this.apiModel; - } + } @BeforeClass public void requirementClasses(ITestContext testContext) { this.requirementClasses = (List) testContext.getSuite() - .getAttribute(REQUIREMENTCLASSES.getName()); + .getAttribute(REQUIREMENTCLASSES.getName()); } @BeforeClass @@ -55,21 +52,22 @@ public void noOfCollections(ITestContext testContext) { this.noOfCollections = (Integer) noOfCollections; } } - - private URI appendFormatToURI(URI input) - { + + private URI appendFormatToURI(URI input) { URI modelUri = null; try { if (input.toString().contains("?")) { modelUri = new URI(input.toString() + "f=application/json"); - } else { + } + else { modelUri = new URI(input.toString() + "?f=application/json"); } - } catch (Exception e) { + } + catch (Exception e) { e.printStackTrace(); } - + return modelUri; } @@ -77,11 +75,9 @@ private URI appendFormatToURI(URI input) public void retrieveApiModel(ITestContext testContext) { modelUri = (URI) testContext.getSuite().getAttribute(SuiteAttribute.API_DEFINITION.getName()); - - this.apiModel = (OpenApi3) testContext.getSuite().getAttribute( SuiteAttribute.API_MODEL.getName() ); - } - + this.apiModel = (OpenApi3) testContext.getSuite().getAttribute(SuiteAttribute.API_MODEL.getName()); + } protected List createListOfMediaTypesToSupportForOtherResources(Map linkToSelf) { if (this.requirementClasses == null) @@ -112,4 +108,5 @@ protected List createListOfMediaTypesToSupportForFeatureCollectionsAndFe mediaTypesToSupport.remove(linkToSelf.get("type")); return mediaTypesToSupport; } + } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/CommonFixture.java b/src/main/java/org/opengis/cite/ogcapiedr10/CommonFixture.java index 2f682ce..570c52a 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/CommonFixture.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/CommonFixture.java @@ -23,123 +23,111 @@ import io.restassured.specification.RequestSpecification; /** - * 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 { - - - private ByteArrayOutputStream requestOutputStream = new ByteArrayOutputStream(); + private ByteArrayOutputStream requestOutputStream = new ByteArrayOutputStream(); - private ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream(); + private ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream(); - protected RequestLoggingFilter requestLoggingFilter; + protected RequestLoggingFilter requestLoggingFilter; - protected ResponseLoggingFilter responseLoggingFilter; + protected ResponseLoggingFilter responseLoggingFilter; - protected URI rootUri; - - protected URI apiDefUri; - - protected String testingWktPOINT = "POINT(-1.054687%2052.498649)"; //TODO change to user inputs - protected String geoJSONTestingCollection = "gfs-surface-precip"; //TODO change to user inputs + protected URI rootUri; + + protected URI apiDefUri; + + protected String testingWktPOINT = "POINT(-1.054687%2052.498649)"; // TODO change to + // user inputs + + protected String geoJSONTestingCollection = "gfs-surface-precip"; // TODO change to + // user inputs - protected final int DEFAULT_BUFFER_SIZE = 8192; - - /** - * 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 ) { - initLogging(); - rootUri = (URI) testContext.getSuite().getAttribute( SuiteAttribute.IUT.getName() ); - - - apiDefUri = (URI) testContext.getSuite().getAttribute(SuiteAttribute.API_DEFINITION.getName()); - - - } - - /*@BeforeMethod - public void trackProgress(Method method) { - java.io.FileWriter fw = null; - try { - fw = new java.io.FileWriter("/ets/mylog.txt",true); - fw.write(this.getClass().getName()+"-"+method.getName()+"\n"); - fw.close(); - } - catch(Exception er) - { - er.printStackTrace(); - } - }*/ - - @BeforeMethod - public void clearMessages() { - initLogging(); - } - - public String getRequest() { - return requestOutputStream.toString(); - } - - public String getResponse() { - return responseOutputStream.toString(); - } - - protected RequestSpecification init() { - return given().filters( requestLoggingFilter, responseLoggingFilter ).log().all(); - } - - /** - * 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( ClientResponse - * 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). - * - * @return A ClientRequest object. - * - * @see ClientUtils#buildGetRequest public ClientRequest buildGetRequest( URI endpoint, Map - * qryParams, MediaType... mediaTypes ) { return ClientUtils.buildGetRequest( endpoint, qryParams, mediaTypes - * ); } - */ - - private void initLogging() { - this.requestOutputStream = new ByteArrayOutputStream(); - this.responseOutputStream = new ByteArrayOutputStream(); - PrintStream requestPrintStream = new PrintStream( requestOutputStream, true ); - PrintStream responsePrintStream = new PrintStream( responseOutputStream, true ); - requestLoggingFilter = new RequestLoggingFilter( requestPrintStream ); - responseLoggingFilter = new ResponseLoggingFilter( responsePrintStream ); - } - + + /** + * 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) { + initLogging(); + rootUri = (URI) testContext.getSuite().getAttribute(SuiteAttribute.IUT.getName()); + + apiDefUri = (URI) testContext.getSuite().getAttribute(SuiteAttribute.API_DEFINITION.getName()); + + } + + /* + * @BeforeMethod public void trackProgress(Method method) { java.io.FileWriter fw = + * null; try { fw = new java.io.FileWriter("/ets/mylog.txt",true); + * fw.write(this.getClass().getName()+"-"+method.getName()+"\n"); fw.close(); } + * catch(Exception er) { er.printStackTrace(); } } + */ + + @BeforeMethod + public void clearMessages() { + initLogging(); + } + + public String getRequest() { + return requestOutputStream.toString(); + } + + public String getResponse() { + return responseOutputStream.toString(); + } + + protected RequestSpecification init() { + return given().filters(requestLoggingFilter, responseLoggingFilter).log().all(); + } + + /** + * 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( ClientResponse 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). + * @return A ClientRequest object. + * + * @see ClientUtils#buildGetRequest public ClientRequest buildGetRequest( URI + * endpoint, Map qryParams, MediaType... mediaTypes ) { return + * ClientUtils.buildGetRequest( endpoint, qryParams, mediaTypes ); } + */ + + private void initLogging() { + this.requestOutputStream = new ByteArrayOutputStream(); + this.responseOutputStream = new ByteArrayOutputStream(); + PrintStream requestPrintStream = new PrintStream(requestOutputStream, true); + PrintStream responsePrintStream = new PrintStream(responseOutputStream, true); + requestLoggingFilter = new RequestLoggingFilter(requestPrintStream); + responseLoggingFilter = new ResponseLoggingFilter(responsePrintStream); + } + protected String constructDateTimeValue(String input) throws Exception { - + // Example input is R36/2021-10-05T03:00:00Z/PT3H - + String startDateOfInterval = null; String endDateOfInterval = null; - if (!input.contains("00:00Z")) - input = input.replace(":00Z", ":00:00Z"); // TODO For testing. REMOVE when done. + input = input.replace(":00Z", ":00:00Z"); // TODO For testing. REMOVE when + // done. String[] token = input.split("/"); @@ -161,25 +149,23 @@ protected String constructDateTimeValue(String input) throws Exception { return startDateOfInterval + "/" + endDateOfInterval; } - - // from https://mkyong.com/java/how-to-convert-inputstream-to-string-in-java/ - public String convertInputStreamToString(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); - } + // from https://mkyong.com/java/how-to-convert-inputstream-to-string-in-java/ + public String convertInputStreamToString(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"); - return result.toString("UTF-8"); + } + protected Response getCollectionResponse(String collectionId) { + return JsonUtils.getCollectionResponse(rootUri.toString(), collectionId, init()); + } - } - - protected Response getCollectionResponse(String collectionId) { - return JsonUtils.getCollectionResponse(rootUri.toString(), collectionId, init()); - } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/ErrorMessage.java b/src/main/java/org/opengis/cite/ogcapiedr10/ErrorMessage.java index 7cc6059..9b842f1 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/ErrorMessage.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/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.ogcapifeatures10.MessageBundle"; - private static ResourceBundle msgResources = - ResourceBundle.getBundle(BASE_NAME); + private static final String BASE_NAME = "org.opengis.cite.ogcapifeatures10.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/ogcapiedr10/ErrorMessageKeys.java b/src/main/java/org/opengis/cite/ogcapiedr10/ErrorMessageKeys.java index 2dfc00d..ab45d5a 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/ErrorMessageKeys.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/ErrorMessageKeys.java @@ -1,22 +1,33 @@ package org.opengis.cite.ogcapiedr10; /** - * 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"; + 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"; + } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/EtsAssert.java b/src/main/java/org/opengis/cite/ogcapiedr10/EtsAssert.java index 5f5c045..c4a7c4c 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/EtsAssert.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/EtsAssert.java @@ -5,29 +5,27 @@ * * @author Lyn Goltz */ - + public class EtsAssert { - /** - * @param valueToAssert - * the boolean to assert to be true - * @param failureMsg - * the message to throw in case of a failure, should not be null - */ - public static void assertTrue( boolean valueToAssert, String failureMsg ) { - if ( !valueToAssert ) - throw new AssertionError( failureMsg ); - } + /** + * @param valueToAssert the boolean to assert to be true + * @param failureMsg the message to throw in case of a failure, should not be + * null + */ + public static void assertTrue(boolean valueToAssert, String failureMsg) { + if (!valueToAssert) + throw new AssertionError(failureMsg); + } - /** - * @param valueToAssert - * the boolean to assert to be false - * @param failureMsg - * the message to throw in case of a failure, should not be null - */ - public static void assertFalse( boolean valueToAssert, String failureMsg ) { - if ( valueToAssert ) - throw new AssertionError( failureMsg ); - } + /** + * @param valueToAssert the boolean to assert to be false + * @param failureMsg the message to throw in case of a failure, should not be + * null + */ + public static void assertFalse(boolean valueToAssert, String failureMsg) { + if (valueToAssert) + throw new AssertionError(failureMsg); + } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/Namespaces.java b/src/main/java/org/opengis/cite/ogcapiedr10/Namespaces.java index 86ccce8..db2138c 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/Namespaces.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/Namespaces.java @@ -10,22 +10,25 @@ */ 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/ogcapiedr10/OgcApiEdr10.java b/src/main/java/org/opengis/cite/ogcapiedr10/OgcApiEdr10.java index d5a809b..cf4fca1 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/OgcApiEdr10.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/OgcApiEdr10.java @@ -7,11 +7,11 @@ */ public class OgcApiEdr10 { - private OgcApiEdr10() { - } + private OgcApiEdr10() { + } - public static final String OPEN_API_MIME_TYPE = "application/vnd.oai.openapi+json;version=3.0"; + public static final String OPEN_API_MIME_TYPE = "application/vnd.oai.openapi+json;version=3.0"; - public static final String GEOJSON_MIME_TYPE = "application/geo+json"; + public static final String GEOJSON_MIME_TYPE = "application/geo+json"; } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/SuiteAttribute.java b/src/main/java/org/opengis/cite/ogcapiedr10/SuiteAttribute.java index b3713a3..0a0b4ba 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/SuiteAttribute.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/SuiteAttribute.java @@ -11,82 +11,85 @@ 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 ), - - /** - * The root URL. - */ - IUT( "instanceUnderTest", URI.class ), - - /** - * A File containing the test subject or a description of it. - */ - TEST_SUBJ_FILE( "testSubjectFile", File.class ), - - /** - * The number of collections to test. - */ - NO_OF_COLLECTIONS( "noOfCollections", Integer.class ), - - /** - * Location of API Definition - */ - API_DEFINITION( "apiDefinition", URI.class ), - - /** - * Parsed OpenApi3 document resource /api; Added during execution. - */ - API_MODEL( "apiModel", OpenApi3.class ), - - /** - * Requirement classes parsed from /conformance; Added during execution. - */ - REQUIREMENTCLASSES( "requirementclasses", List.class ), - - /** - * Parsed collections from resource /collections; Added during execution. - */ - COLLECTIONS( "collections", List.class ), - - /** - * LandingPage as JSONPath object - */ - LANDINGPAGEJSONPATH( "landingpagejsonpath", JsonPath.class ), - - /** - * Collection names assigned to a feature id parsed from resource /collections/{name}/items; Added during execution. - */ - FEATUREIDS( "featureIds", Map.class ); - - private final Class attrType; - - private final String attrName; - - 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), + + /** + * The root URL. + */ + IUT("instanceUnderTest", URI.class), + + /** + * A File containing the test subject or a description of it. + */ + TEST_SUBJ_FILE("testSubjectFile", File.class), + + /** + * The number of collections to test. + */ + NO_OF_COLLECTIONS("noOfCollections", Integer.class), + + /** + * Location of API Definition + */ + API_DEFINITION("apiDefinition", URI.class), + + /** + * Parsed OpenApi3 document resource /api; Added during execution. + */ + API_MODEL("apiModel", OpenApi3.class), + + /** + * Requirement classes parsed from /conformance; Added during execution. + */ + REQUIREMENTCLASSES("requirementclasses", List.class), + + /** + * Parsed collections from resource /collections; Added during execution. + */ + COLLECTIONS("collections", List.class), + + /** + * LandingPage as JSONPath object + */ + LANDINGPAGEJSONPATH("landingpagejsonpath", JsonPath.class), + + /** + * Collection names assigned to a feature id parsed from resource + * /collections/{name}/items; Added during execution. + */ + FEATUREIDS("featureIds", Map.class); + + private final Class attrType; + + private final String attrName; + + 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(); + } + } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/SuiteFixtureListener.java b/src/main/java/org/opengis/cite/ogcapiedr10/SuiteFixtureListener.java index 19d01d3..eb5d470 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/SuiteFixtureListener.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/SuiteFixtureListener.java @@ -26,148 +26,150 @@ import io.restassured.response.Response; 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 + * 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() ); - String iutParam = params.get( TestRunArg.IUT.toString() ); - if ( ( null == iutParam ) || iutParam.isEmpty() ) { - throw new IllegalArgumentException( "Required test run parameter not found: " + TestRunArg.IUT.toString() ); - } - URI iutRef = URI.create( iutParam.trim() ); - suite.setAttribute( SuiteAttribute.IUT.getName(), iutRef ); - File entityFile = null; - try { - entityFile = URIUtils.dereferenceURI( iutRef ); - } catch ( IOException iox ) { - throw new RuntimeException( "Failed to dereference resource located at " + iutRef, iox ); - } - TestSuiteLogger.log( Level.FINE, String.format( "Wrote test subject to file: %s (%d bytes)", - entityFile.getAbsolutePath(), entityFile.length() ) ); - suite.setAttribute( SuiteAttribute.TEST_SUBJ_FILE.getName(), entityFile ); - - String noOfCollections = params.get( TestRunArg.NOOFCOLLECTIONS.toString() ); - try { - if ( noOfCollections != null ) { - int noOfCollectionsInt = Integer.parseInt( noOfCollections ); - suite.setAttribute( SuiteAttribute.NO_OF_COLLECTIONS.getName(), noOfCollectionsInt ); - } - } catch ( NumberFormatException e ) { - TestSuiteLogger.log( Level.WARNING, - String.format( "Could not parse parameter %s: %s. Expected is a valid integer", - TestRunArg.NOOFCOLLECTIONS.toString(), noOfCollections ) ); - } - - - - URI apiDefinitionLocation = URI.create( params.get( "apiDefinition" )); - suite.setAttribute( SuiteAttribute.API_DEFINITION.getName(), apiDefinitionLocation ); - File apiDefinitionFile = null; - try { - apiDefinitionFile = URIUtils.dereferenceURI( apiDefinitionLocation ); - } catch ( IOException iox ) { - throw new RuntimeException( "Failed to dereference resource located at " + apiDefinitionLocation, iox ); - } - - String f = ""; - - if(iutRef.toString().contains("f=json") || iutRef.toString().contains("f=application/json")) {} - else { f = "f=application/json"; } - - Response response = null; - - if(ClientUtils.is200Response(URI.create(iutRef.toString()+"?f=application/json"))) - { - response = given().baseUri( iutRef.toString() ).accept( JSON ).when().request( GET, "?f=application/json"); - response.then().statusCode( 200 ); - } - else if(ClientUtils.is200Response(URI.create(iutRef.toString()+"?f=json"))) - { - response = given().baseUri( iutRef.toString() ).accept( JSON ).when().request( GET, "?f=json"); - response.then().statusCode( 200 ); - } - JsonPath jsonPath = response.jsonPath(); - suite.setAttribute( SuiteAttribute.LANDINGPAGEJSONPATH.getName(), jsonPath ); - - OpenApiParser parser = new OpenApiParser(); - OpenApi3 apiModel = null; - - try { - Link apiUrl = OpenApiUtils.parseApiUrl(jsonPath); - URL resolutionBase = new URL(apiUrl.getHref()); // https://github.com/RepreZen/KaiZen-OpenApi-Parser/blob/83c47220d21fe7569f46eeacd3f5bdecb58da69a/API-Overview.md#parsing-options - Response apiModelResponse = given().accept(apiUrl.getType()).get(apiUrl.getHref()); - apiModel = (OpenApi3) parser.parse(apiModelResponse.asString(), resolutionBase); - } catch (Exception e) { - TestSuiteLogger.log(Level.SEVERE, "The API definition linked from the Landing Page resulted in an exception.", e); - } - - suite.setAttribute(SuiteAttribute.API_MODEL.getName(), apiModel); - - } - - /** - * 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(); - } - } + @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()); + String iutParam = params.get(TestRunArg.IUT.toString()); + if ((null == iutParam) || iutParam.isEmpty()) { + throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.IUT.toString()); + } + URI iutRef = URI.create(iutParam.trim()); + suite.setAttribute(SuiteAttribute.IUT.getName(), iutRef); + File entityFile = null; + try { + entityFile = URIUtils.dereferenceURI(iutRef); + } + catch (IOException iox) { + throw new RuntimeException("Failed to dereference resource located at " + iutRef, iox); + } + TestSuiteLogger.log(Level.FINE, String.format("Wrote test subject to file: %s (%d bytes)", + entityFile.getAbsolutePath(), entityFile.length())); + suite.setAttribute(SuiteAttribute.TEST_SUBJ_FILE.getName(), entityFile); + + String noOfCollections = params.get(TestRunArg.NOOFCOLLECTIONS.toString()); + try { + if (noOfCollections != null) { + int noOfCollectionsInt = Integer.parseInt(noOfCollections); + suite.setAttribute(SuiteAttribute.NO_OF_COLLECTIONS.getName(), noOfCollectionsInt); + } + } + catch (NumberFormatException e) { + TestSuiteLogger.log(Level.WARNING, + String.format("Could not parse parameter %s: %s. Expected is a valid integer", + TestRunArg.NOOFCOLLECTIONS.toString(), noOfCollections)); + } + + URI apiDefinitionLocation = URI.create(params.get("apiDefinition")); + suite.setAttribute(SuiteAttribute.API_DEFINITION.getName(), apiDefinitionLocation); + File apiDefinitionFile = null; + try { + apiDefinitionFile = URIUtils.dereferenceURI(apiDefinitionLocation); + } + catch (IOException iox) { + throw new RuntimeException("Failed to dereference resource located at " + apiDefinitionLocation, iox); + } + + String f = ""; + + if (iutRef.toString().contains("f=json") || iutRef.toString().contains("f=application/json")) { + } + else { + f = "f=application/json"; + } + + Response response = null; + + if (ClientUtils.is200Response(URI.create(iutRef.toString() + "?f=application/json"))) { + response = given().baseUri(iutRef.toString()).accept(JSON).when().request(GET, "?f=application/json"); + response.then().statusCode(200); + } + else if (ClientUtils.is200Response(URI.create(iutRef.toString() + "?f=json"))) { + response = given().baseUri(iutRef.toString()).accept(JSON).when().request(GET, "?f=json"); + response.then().statusCode(200); + } + JsonPath jsonPath = response.jsonPath(); + suite.setAttribute(SuiteAttribute.LANDINGPAGEJSONPATH.getName(), jsonPath); + + OpenApiParser parser = new OpenApiParser(); + OpenApi3 apiModel = null; + + try { + Link apiUrl = OpenApiUtils.parseApiUrl(jsonPath); + URL resolutionBase = new URL(apiUrl.getHref()); // https://github.com/RepreZen/KaiZen-OpenApi-Parser/blob/83c47220d21fe7569f46eeacd3f5bdecb58da69a/API-Overview.md#parsing-options + Response apiModelResponse = given().accept(apiUrl.getType()).get(apiUrl.getHref()); + apiModel = (OpenApi3) parser.parse(apiModelResponse.asString(), resolutionBase); + } + catch (Exception e) { + TestSuiteLogger.log(Level.SEVERE, + "The API definition linked from the Landing Page resulted in an exception.", e); + } + + suite.setAttribute(SuiteAttribute.API_MODEL.getName(), apiModel); + + } + + /** + * 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/ogcapiedr10/SuitePreconditions.java b/src/main/java/org/opengis/cite/ogcapiedr10/SuitePreconditions.java index 26f0f55..cfa9506 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/SuitePreconditions.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/SuitePreconditions.java @@ -8,35 +8,36 @@ 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() { + // ITestcontext was removed from the BeforeSuite annotation, see here: + // https://github.com/testng-team/testng/issues/3032 + ITestContext testContext = Reporter.getCurrentTestResult().getTestContext(); + SuiteAttribute testFileAttr = SuiteAttribute.TEST_SUBJ_FILE; + Object sutObj = testContext.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() { - // ITestcontext was removed from the BeforeSuite annotation, see here: - // https://github.com/testng-team/testng/issues/3032 - ITestContext testContext = Reporter.getCurrentTestResult().getTestContext(); - SuiteAttribute testFileAttr = SuiteAttribute.TEST_SUBJ_FILE; - Object sutObj = testContext.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/ogcapiedr10/TestFailureListener.java b/src/main/java/org/opengis/cite/ogcapiedr10/TestFailureListener.java index a4df5d7..e480314 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/TestFailureListener.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/TestFailureListener.java @@ -13,87 +13,84 @@ import jakarta.ws.rs.core.MediaType; /** - * 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", fixture.getRequest()); - result.setAttribute("response", fixture.getResponse()); - } - } + /** + * 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", fixture.getRequest()); + result.setAttribute("response", fixture.getResponse()); + } + } - /** - * 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(ClientResponse 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(ClientResponse 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/ogcapiedr10/TestNGController.java b/src/main/java/org/opengis/cite/ogcapiedr10/TestNGController.java index 9acfddf..55f884f 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/TestNGController.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/TestNGController.java @@ -30,140 +30,138 @@ */ 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.IUT.toString())) { - throw new IllegalArgumentException( - String.format("Missing argument: '%s' must be present.", TestRunArg.IUT)); - } - } + private TestRunExecutor executor; + + private Properties etsProperties = new Properties(); + + /** + * A convenience method 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.IUT.toString())) { + throw new IllegalArgumentException( + String.format("Missing argument: '%s' must be present.", TestRunArg.IUT)); + } + } + } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/TestRunArg.java b/src/main/java/org/opengis/cite/ogcapiedr10/TestRunArg.java index 8500f95..e74ff00 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/TestRunArg.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/TestRunArg.java @@ -5,20 +5,23 @@ */ public enum TestRunArg { - /** - * 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 or metadata + * about it. + */ + IUT, + + /** + * The number of collections to test (a value less or equal to 0 means all + * collections). + */ + NOOFCOLLECTIONS, - /** - * The number of collections to test (a value less or equal to 0 means all collections). - */ - NOOFCOLLECTIONS, - APIDEFINITION; - @Override - public String toString() { - return name().toLowerCase(); - } + @Override + public String toString() { + return name().toLowerCase(); + } + } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/TestRunListener.java b/src/main/java/org/opengis/cite/ogcapiedr10/TestRunListener.java index 71b9445..2f465a2 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/TestRunListener.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/TestRunListener.java @@ -3,24 +3,27 @@ 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() { - } + @Override + public void onExecutionStart() { + } + + @Override + public void onExecutionFinish() { + } - @Override - public void onExecutionFinish() { - } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/collections/AbstractFeatures.java b/src/main/java/org/opengis/cite/ogcapiedr10/collections/AbstractFeatures.java index fab1234..f498a3e 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/collections/AbstractFeatures.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/collections/AbstractFeatures.java @@ -178,11 +178,11 @@ public Iterator corridorCollectionPaths(ITestContext testContext) { return collectionsData.iterator(); } - @BeforeClass - public void retrieveRequiredInformationFromTestContext(ITestContext testContext) { - OpenApi3 openApiDef = (OpenApi3) testContext.getSuite().getAttribute(SuiteAttribute.API_MODEL.getName()); - apiDef = openApiDef.toString(); - } + @BeforeClass + public void retrieveRequiredInformationFromTestContext(ITestContext testContext) { + OpenApi3 openApiDef = (OpenApi3) testContext.getSuite().getAttribute(SuiteAttribute.API_MODEL.getName()); + apiDef = openApiDef.toString(); + } /** * Abstract Test 22, Test Method 1 @@ -195,7 +195,6 @@ public void retrieveRequiredInformationFromTestContext(ITestContext testContext) * Test Method * 1. Validate that the type property is present and has a value of FeatureCollection * - * * @param collection the collection under test, never null */ public void validateTypeProperty(CollectionResponseKey collection) { @@ -220,7 +219,6 @@ public void validateTypeProperty(CollectionResponseKey collection) { * Test Method * 2. Validate the features property is present and that it is populated with an array of feature items. * - * * @param collection the collection under test, never null */ void validateFeaturesProperty(CollectionResponseKey collection) { @@ -257,7 +255,6 @@ void validateFeaturesProperty(CollectionResponseKey collection) { * * Verify that all links include the rel and type link parameters. * - * * @param collection the collection under test, never null */ void validateLinks(CollectionResponseKey collection) { @@ -313,7 +310,6 @@ void validateLinks(CollectionResponseKey collection) { * * Test Method: Validate that the timeStamp value is set to the time when the response was generated. * - * * @param collection the collection under test, never null */ public void validateTimeStamp(CollectionResponseKey collection) { @@ -346,7 +342,6 @@ public void validateTimeStamp(CollectionResponseKey collection) { * * Test Method: Validate that the numberReturned value is identical to the number of features in the response. * - * * @param collection the collection under test, never null */ void validateNumberReturned(CollectionResponseKey collection) { @@ -397,6 +392,7 @@ public ResponseData(Response response, ZonedDateTime timeStampBeforeResponse, public JsonPath jsonPath() { return response.jsonPath(); } + } protected class CollectionResponseKey { @@ -421,6 +417,7 @@ public boolean equals(Object o) { public int hashCode() { return Objects.hash(id); } + } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/collections/AreaCollections.java b/src/main/java/org/opengis/cite/ogcapiedr10/collections/AreaCollections.java index 6494ad3..d309f7c 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/collections/AreaCollections.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/collections/AreaCollections.java @@ -9,109 +9,90 @@ */ public class AreaCollections extends AbstractFeatures { - CollectionsTime ct= new CollectionsTime(); + CollectionsTime ct = new CollectionsTime(); + /** *
     	 * Abstract Test 54: Validate that the coords query parameters are constructed correctly. (area)
     	 * 
    - * * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 54 (/conf/edr/rc-coords-definition)", dataProvider = "areaCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 54 (/conf/edr/rc-coords-definition)", + dataProvider = "areaCollectionPaths", alwaysRun = true) public void areaCoordsParameterDefinition(TestPoint testPoint) { - - - ct.coordsParameterDefinition(testPoint,this.getModel()); System.gc(); - - + ct.coordsParameterDefinition(testPoint, this.getModel()); + System.gc(); + } /** *
     	 * Abstract Test 58: Validate that the dateTime query parameters are constructed correctly. (area)
     	 * 
    - * * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 58 (/conf/core/datetime-definition)", dataProvider = "areaCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 58 (/conf/core/datetime-definition)", + dataProvider = "areaCollectionPaths", alwaysRun = true) public void areaDateTimeParameterDefinition(TestPoint testPoint) { - - - ct.dateTimeParameterDefinition(testPoint,this.getModel()); System.gc(); - + ct.dateTimeParameterDefinition(testPoint, this.getModel()); + System.gc(); } /** - * Abstract Test 60: Validate that the parameter-name query parameters are processed correctly. (area) - * + * Abstract Test 60: Validate that the parameter-name query parameters are processed + * correctly. (area) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 60 (/conf/collections/REQ_rc-parameter-name-definition)", dataProvider = "areaCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 60 (/conf/collections/REQ_rc-parameter-name-definition)", + dataProvider = "areaCollectionPaths", alwaysRun = true) public void areaParameternameParameterDefinition(TestPoint testPoint) { - - - ct.parameternameParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.parameternameParameterDefinition(testPoint, this.getModel()); + System.gc(); } /** - * Abstract Test 62: Validate that the crs query parameters are constructed correctly. (area) - * + * Abstract Test 62: Validate that the crs query parameters are constructed correctly. + * (area) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 62 (/conf/edr/REQ_rc-crs-definition)", dataProvider = "areaCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 62 (/conf/edr/REQ_rc-crs-definition)", + dataProvider = "areaCollectionPaths", alwaysRun = true) public void areaCrsParameterDefinition(TestPoint testPoint) { - - - ct.crsParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.crsParameterDefinition(testPoint, this.getModel()); + System.gc(); } - - /** - * Abstract Test 64: Validate that the f query parameter is constructed correctly. (area) - * + * Abstract Test 64: Validate that the f query parameter is constructed correctly. + * (area) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 64 (/conf/edr/rc-f-definition)", dataProvider = "areaCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 64 (/conf/edr/rc-f-definition)", dataProvider = "areaCollectionPaths", + alwaysRun = true) public void areaFParameterDefinition(TestPoint testPoint) { - - - - ct.fParameterDefinition(testPoint,this.getModel()); System.gc(); - } + ct.fParameterDefinition(testPoint, this.getModel()); + System.gc(); + } /** - * Abstract Test 56: Validate that the vertical level query parameters are constructed correctly. (area) - * - * + * Abstract Test 56: Validate that the vertical level query parameters are constructed + * correctly. (area) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 56 (/conf/edr/rc-z-definition)", dataProvider = "areaCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 56 (/conf/edr/rc-z-definition)", dataProvider = "areaCollectionPaths", + alwaysRun = true) public void areaZParameterDefinition(TestPoint testPoint) { - - - ct.zParameterDefinition(testPoint,this.getModel()); System.gc(); - - } - - - - - - - - - + ct.zParameterDefinition(testPoint, this.getModel()); + System.gc(); + } - - } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/collections/CollectionsTime.java b/src/main/java/org/opengis/cite/ogcapiedr10/collections/CollectionsTime.java index b3502ed..bffd393 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/collections/CollectionsTime.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/collections/CollectionsTime.java @@ -17,18 +17,16 @@ * /collections/{collectionId}/ * */ -public class CollectionsTime{ - - - - protected boolean isRequired( Parameter param ) { - return param.getRequired() != null && param.getRequired(); - } - - protected Boolean isExplode( Parameter param ) { - return param.getExplode() != null && param.getExplode(); - } - +public class CollectionsTime { + + protected boolean isRequired(Parameter param) { + return param.getRequired() != null && param.getRequired(); + } + + protected Boolean isExplode(Parameter param) { + return param.getExplode() != null && param.getExplode(); + } + /** *
     	 * Abstract Test 38: Validate that the coords query parameters are constructed correctly. (position)
    @@ -36,18 +34,15 @@ protected Boolean isExplode( Parameter param ) {
     	 * Abstract Test 92: Validate that the coords query parameters are constructed correctly. (trajectory)
     	 * Abstract Test 116: Validate that the coords query parameters are constructed correctly. (corridor)
     	 * 
    - * * @param testPoint the testPoint under test, never null * @param model api definition, never null */ - public void coordsParameterDefinition(TestPoint testPoint,OpenApi3 model) { - - + public void coordsParameterDefinition(TestPoint testPoint, OpenApi3 model) { + Parameter coords = null; String paramName = "coords"; - boolean hasCoordsParameter = false; for (Path path : model.getPaths().values()) { @@ -56,12 +51,12 @@ public void coordsParameterDefinition(TestPoint testPoint,OpenApi3 model) { for (Operation op : path.getOperations().values()) { for (Parameter param : op.getParameters()) { - - if(hasName(param)) { + + if (hasName(param)) { if (param.getName().equals(paramName)) { coords = param; } - } + } } } } @@ -78,7 +73,8 @@ public void coordsParameterDefinition(TestPoint testPoint,OpenApi3 model) { assertEquals(coords.getName(), paramName, String.format(msg, "name", paramName, coords.getName())); assertEquals(coords.getIn(), "query", String.format(msg, "in", "query", coords.getIn())); assertTrue(isRequired(coords), String.format(msg, "required", "true", coords.getRequired())); - // assertEquals( coords.getStyle(), "form", String.format( msg, "style","form", + // assertEquals( coords.getStyle(), "form", String.format( msg, + // "style","form", // coords.getStyle() ) ); //TODO SHOULD BE Enabled assertFalse(isExplode(coords), String.format(msg, "explode", "false", coords.getExplode())); Schema schema = coords.getSchema(); @@ -86,64 +82,60 @@ public void coordsParameterDefinition(TestPoint testPoint,OpenApi3 model) { String.format(msg, "schema -> type", "string", schema.getType())); } - } - - } - - /** - *
    -         * Abstract Test 70: Validate that the coords query parameters are constructed correctly. (cube)
    -         * 
    - * - * @param testPoint - * the testPoint under test, never null - * @param model - * api definition, never null - */ - - public void bboxParameterDefinition(TestPoint testPoint, - OpenApi3 model) { - - Parameter bbox = null; - String paramName = "bbox"; - - for (Path path : model.getPaths().values()) { - - if (path.getPathString().endsWith(testPoint.getPath())) { - - for (Operation op : path.getOperations().values()) { - for (Parameter param : op.getParameters()) { - - if (hasName(param)) { - if (param.getName().equals(paramName)) { - bbox = param; - } - } - } - } - } - } - - // ---------------- - - if (!testPoint.getPath().endsWith("/locations")) { - assertNotNull(bbox, "Required " + paramName + " parameter for collections with path '" - + testPoint.getPath() + "' in OpenAPI document is missing"); - - if (bbox != null) { - String msg = "Expected property '%s' with value '%s' but was '%s'"; - assertEquals(bbox.getName(), paramName, String.format(msg, "name", paramName, bbox.getName())); - assertEquals(bbox.getIn(), "query", String.format(msg, "in", "query", bbox.getIn())); - assertTrue(isRequired(bbox), String.format(msg, "required", "true", bbox.getRequired())); - assertFalse(isExplode(bbox), String.format(msg, "explode", "false", bbox.getExplode())); - Schema schema = bbox.getSchema(); - assertEquals(schema.getType(), "string", - String.format(msg, "schema -> type", "string", schema.getType())); - } - - } - - } + } + + } + + /** + *
    +	 * Abstract Test 70: Validate that the coords query parameters are constructed correctly. (cube)
    +	 * 
    + * @param testPoint the testPoint under test, never null + * @param model api definition, never null + */ + + public void bboxParameterDefinition(TestPoint testPoint, OpenApi3 model) { + + Parameter bbox = null; + String paramName = "bbox"; + + for (Path path : model.getPaths().values()) { + + if (path.getPathString().endsWith(testPoint.getPath())) { + + for (Operation op : path.getOperations().values()) { + for (Parameter param : op.getParameters()) { + + if (hasName(param)) { + if (param.getName().equals(paramName)) { + bbox = param; + } + } + } + } + } + } + + // ---------------- + + if (!testPoint.getPath().endsWith("/locations")) { + assertNotNull(bbox, "Required " + paramName + " parameter for collections with path '" + testPoint.getPath() + + "' in OpenAPI document is missing"); + + if (bbox != null) { + String msg = "Expected property '%s' with value '%s' but was '%s'"; + assertEquals(bbox.getName(), paramName, String.format(msg, "name", paramName, bbox.getName())); + assertEquals(bbox.getIn(), "query", String.format(msg, "in", "query", bbox.getIn())); + assertTrue(isRequired(bbox), String.format(msg, "required", "true", bbox.getRequired())); + assertFalse(isExplode(bbox), String.format(msg, "explode", "false", bbox.getExplode())); + Schema schema = bbox.getSchema(); + assertEquals(schema.getType(), "string", + String.format(msg, "schema -> type", "string", schema.getType())); + } + + } + + } /** *
    @@ -152,34 +144,29 @@ public void bboxParameterDefinition(TestPoint testPoint,
     	 * Abstract Test 74: Validate that the dateTime query parameters are constructed correctly. (cube)
     	 * Abstract Test 139: Validate that the dateTime query parameters are constructed correctly. (instances)
     	 * 
    - * * @param testPoint the testPoint under test, never null * @param model api definition, never null */ - public void dateTimeParameterDefinition(TestPoint testPoint,OpenApi3 model) { - + public void dateTimeParameterDefinition(TestPoint testPoint, OpenApi3 model) { Parameter datetime = null; String paramName = "datetime"; - - for (Path path : model.getPaths().values()) { if (path.getPathString().endsWith(testPoint.getPath())) { for (Operation op : path.getOperations().values()) { - + for (Parameter param : op.getParameters()) { - - if(hasName(param)) { - if (param.getName().equals(paramName)) - { - datetime = param; + + if (hasName(param)) { + if (param.getName().equals(paramName)) { + datetime = param; } } } - + } } } @@ -197,42 +184,39 @@ public void dateTimeParameterDefinition(TestPoint testPoint,OpenApi3 model) { } } - - - public boolean hasName(Parameter parameter) - { + + public boolean hasName(Parameter parameter) { boolean result = true; - - try { - parameter.getName(); //we do this to check whether there is a name - } - catch(Exception ee) { - result = false; - } - + + try { + parameter.getName(); // we do this to check whether there is a name + } + catch (Exception ee) { + result = false; + } + return result; - + } /** - * Abstract Test 44: Validate that the parameter-name query parameters are processed correctly. (position) - * Abstract Test 60: Validate that the parameter-name query parameters are processed correctly. (area) - * Abstract Test 76: Validate that the parameter-name query parameters are processed correctly. (cube) - * Abstract Test 94: Validate that the parameter-name query parameters are processed correctly. (trajectory) - * Abstract Test 126: Validate that the parameter-name query parameters are processed correctly. (corridor) - * Abstract Test 141: Validate that the parameter-name query parameters are processed correctly. (locations) - * + * Abstract Test 44: Validate that the parameter-name query parameters are processed + * correctly. (position) Abstract Test 60: Validate that the parameter-name query + * parameters are processed correctly. (area) Abstract Test 76: Validate that the + * parameter-name query parameters are processed correctly. (cube) Abstract Test 94: + * Validate that the parameter-name query parameters are processed correctly. + * (trajectory) Abstract Test 126: Validate that the parameter-name query parameters + * are processed correctly. (corridor) Abstract Test 141: Validate that the + * parameter-name query parameters are processed correctly. (locations) * @param testPoint the testPoint under test, never null * @param model api definition, never null */ public void parameternameParameterDefinition(TestPoint testPoint, OpenApi3 model) { - Parameter parametername = null; String paramName = "parameter-name"; - for (Path path : model.getPaths().values()) { if (testPoint.getPath().equals(path.getPathString())) { @@ -240,14 +224,13 @@ public void parameternameParameterDefinition(TestPoint testPoint, OpenApi3 model for (Operation op : path.getOperations().values()) { for (Parameter param : op.getParameters()) { - - if(hasName(param)) { - if (param.getName().equals(paramName)) - { - parametername = param; + + if (hasName(param)) { + if (param.getName().equals(paramName)) { + parametername = param; } } - + } } } @@ -269,24 +252,22 @@ public void parameternameParameterDefinition(TestPoint testPoint, OpenApi3 model } /** - * Abstract Test 46: Validate that the crs query parameters are constructed correctly. (position) - * Abstract Test 62: Validate that the crs query parameters are constructed correctly. (area) - * Abstract Test 78: Validate that the crs query parameters are constructed correctly. (cube) - * Abstract Test 96: Validate that the crs query parameters are constructed correctly. (trajectory) - * Abstract Test 128: Validate that the crs query parameters are constructed correctly. (corridor) - * Abstract Test 143: Validate that the crs query parameters are constructed correctly. (locations) - * + * Abstract Test 46: Validate that the crs query parameters are constructed correctly. + * (position) Abstract Test 62: Validate that the crs query parameters are constructed + * correctly. (area) Abstract Test 78: Validate that the crs query parameters are + * constructed correctly. (cube) Abstract Test 96: Validate that the crs query + * parameters are constructed correctly. (trajectory) Abstract Test 128: Validate that + * the crs query parameters are constructed correctly. (corridor) Abstract Test 143: + * Validate that the crs query parameters are constructed correctly. (locations) * @param testPoint the testPoint under test, never null * @param model api definition, never null */ public void crsParameterDefinition(TestPoint testPoint, OpenApi3 model) { - Parameter crs = null; String paramName = "crs"; - for (Path path : model.getPaths().values()) { if (testPoint.getPath().equals(path.getPathString())) { @@ -294,11 +275,10 @@ public void crsParameterDefinition(TestPoint testPoint, OpenApi3 model) { for (Operation op : path.getOperations().values()) { for (Parameter param : op.getParameters()) { - - if(hasName(param)) { - - if (param.getName().equals(paramName)) - { + + if (hasName(param)) { + + if (param.getName().equals(paramName)) { crs = param; } } @@ -318,505 +298,411 @@ public void crsParameterDefinition(TestPoint testPoint, OpenApi3 model) { } } - - /** - * Abstract Test 48: Validate that the f query parameter is constructed correctly. (position) - * Abstract Test 64: Validate that the f query parameter is constructed correctly. (area) - * Abstract Test 80: Validate that the f query parameter is constructed correctly. (cube) - * Abstract Test 98: Validate that the f query parameter is constructed correctly. (trajectory) - * Abstract Test 130: Validate that the f query parameter is constructed correctly. (corridor) - * Abstract Test 145: Validate that the f query parameter is constructed correctly. (locations) - * + * Abstract Test 48: Validate that the f query parameter is constructed correctly. + * (position) Abstract Test 64: Validate that the f query parameter is constructed + * correctly. (area) Abstract Test 80: Validate that the f query parameter is + * constructed correctly. (cube) Abstract Test 98: Validate that the f query parameter + * is constructed correctly. (trajectory) Abstract Test 130: Validate that the f query + * parameter is constructed correctly. (corridor) Abstract Test 145: Validate that the + * f query parameter is constructed correctly. (locations) * @param testPoint the testPoint under test, never null * @param model api definition, never null */ public void fParameterDefinition(TestPoint testPoint, OpenApi3 model) { + Parameter f = null; + String paramName = "f"; + for (Path path : model.getPaths().values()) { - Parameter f = null; - String paramName = "f"; - - - for (Path path : model.getPaths().values()) { - - - - if (testPoint.getPath().equals(path.getPathString())) { + if (testPoint.getPath().equals(path.getPathString())) { - for (Operation op : path.getOperations().values()) { + for (Operation op : path.getOperations().values()) { - for (Parameter param : op.getParameters()) { - - if(hasName(param)) { - if (param.getName().equals(paramName)) - { - f = param; - } - } - } - } - } - } + for (Parameter param : op.getParameters()) { - // ---------------- + if (hasName(param)) { + if (param.getName().equals(paramName)) { + f = param; + } + } + } + } + } + } + // ---------------- - if (f != null) { + if (f != null) { - String msg = "Expected property '%s' with value '%s' but was '%s'"; - assertEquals(f.getName(), paramName, String.format(msg, "name", paramName, f.getName())); - assertEquals(f.getIn(), "query", String.format(msg, "in", "query", f.getIn())); - assertFalse(isRequired(f), String.format(msg, "required", "false", f.getRequired())); - assertEquals( f.getStyle(), "form", String.format( msg, "style","form", f.getStyle() ) ); - assertFalse(isExplode(f), String.format(msg, "explode", "false", f.getExplode())); - } - } + String msg = "Expected property '%s' with value '%s' but was '%s'"; + assertEquals(f.getName(), paramName, String.format(msg, "name", paramName, f.getName())); + assertEquals(f.getIn(), "query", String.format(msg, "in", "query", f.getIn())); + assertFalse(isRequired(f), String.format(msg, "required", "false", f.getRequired())); + assertEquals(f.getStyle(), "form", String.format(msg, "style", "form", f.getStyle())); + assertFalse(isExplode(f), String.format(msg, "explode", "false", f.getExplode())); + } + } /** - * Abstract Test 40 (/conf/edr/rc-z-definition): Validate that the vertical level query parameters are constructed correctly. (position) - * Abstract Test 56 (/conf/edr/rc-z-definition): Validate that the vertical level query parameters are constructed correctly. (area) - * - * + * Abstract Test 40 (/conf/edr/rc-z-definition): Validate that the vertical level + * query parameters are constructed correctly. (position) Abstract Test 56 + * (/conf/edr/rc-z-definition): Validate that the vertical level query parameters are + * constructed correctly. (area) * @param testPoint the testPoint under test, never null * @param model api definition, never null */ public void zParameterDefinition(TestPoint testPoint, OpenApi3 model) { - - Parameter z = null; - String paramName = "z"; + Parameter z = null; + String paramName = "z"; + for (Path path : model.getPaths().values()) { - for (Path path : model.getPaths().values()) { - - - - if (testPoint.getPath().equals(path.getPathString())) { - - for (Operation op : path.getOperations().values()) { + if (testPoint.getPath().equals(path.getPathString())) { - for (Parameter param : op.getParameters()) { - - if(hasName(param)) { - if (param.getName().equals(paramName)) - { - z = param; - } - } - } - } - } - } + for (Operation op : path.getOperations().values()) { - // ---------------- + for (Parameter param : op.getParameters()) { + if (hasName(param)) { + if (param.getName().equals(paramName)) { + z = param; + } + } + } + } + } + } - if (z != null) { - String msg = "Expected property '%s' with value '%s' but was '%s'"; - assertEquals(z.getName(), paramName, String.format(msg, "name", paramName, z.getName())); - assertEquals(z.getIn(), "query", String.format(msg, "in", "query", z.getIn())); - assertTrue(isRequired(z), String.format(msg, "required", "true", z.getRequired())); - assertEquals( z.getStyle(), "form", String.format( msg, "style","form", z.getStyle() ) ); - assertFalse(isExplode(z), String.format(msg, "explode", "false", z.getExplode())); - } + // ---------------- - } + if (z != null) { + String msg = "Expected property '%s' with value '%s' but was '%s'"; + assertEquals(z.getName(), paramName, String.format(msg, "name", paramName, z.getName())); + assertEquals(z.getIn(), "query", String.format(msg, "in", "query", z.getIn())); + assertTrue(isRequired(z), String.format(msg, "required", "true", z.getRequired())); + assertEquals(z.getStyle(), "form", String.format(msg, "style", "form", z.getStyle())); + assertFalse(isExplode(z), String.format(msg, "explode", "false", z.getExplode())); + } + } /** *
     	 * Requirement A.21: /req/edr/within-definition Parameter within definition
    -	 * 
    - * NOTE: Not referenced by ATS - * + * NOTE: Not referenced by ATS * @param testPoint the testPoint under test, never null * @param model api definition, never null */ public void withinParameterDefinition(TestPoint testPoint, OpenApi3 model) { - - - // Based on - // https://github.com/RepreZen/KaiZen-OpenApi-Parser/blob/master/GettingStarted.md - - Parameter within = null; - String paramName = "within"; - - for (Path path : model.getPaths().values()) { + // Based on + // https://github.com/RepreZen/KaiZen-OpenApi-Parser/blob/master/GettingStarted.md + Parameter within = null; + String paramName = "within"; + for (Path path : model.getPaths().values()) { - if (testPoint.getPath().equals(path.getPathString())) { + if (testPoint.getPath().equals(path.getPathString())) { - for (Operation op : path.getOperations().values()) { + for (Operation op : path.getOperations().values()) { - for (Parameter param : op.getParameters()) { - - if(hasName(param)) { - if (param.getName().equals(paramName)) - { - within = param; - } - } - } - } - } - } + for (Parameter param : op.getParameters()) { - // ---------------- + if (hasName(param)) { + if (param.getName().equals(paramName)) { + within = param; + } + } + } + } + } + } + // ---------------- - if (within != null) { - String msg = "Expected property '%s' with value '%s' but was '%s'"; - assertEquals(within.getName(), paramName, String.format(msg, "name", paramName, within.getName())); - assertEquals(within.getIn(), "query", String.format(msg, "in", "query", within.getIn())); - assertFalse(isRequired(within), String.format(msg, "required", "false", within.getRequired())); - assertEquals( within.getStyle(), "form", String.format( msg, "style","form", within.getStyle() ) ); - assertFalse(isExplode(within), String.format(msg, "explode", "false", within.getExplode())); - } - - + if (within != null) { + String msg = "Expected property '%s' with value '%s' but was '%s'"; + assertEquals(within.getName(), paramName, String.format(msg, "name", paramName, within.getName())); + assertEquals(within.getIn(), "query", String.format(msg, "in", "query", within.getIn())); + assertFalse(isRequired(within), String.format(msg, "required", "false", within.getRequired())); + assertEquals(within.getStyle(), "form", String.format(msg, "style", "form", within.getStyle())); + assertFalse(isExplode(within), String.format(msg, "explode", "false", within.getExplode())); + } - } - - + } /** *
     	 * Requirement A.23: /req/edr/within-units-definition Parameter withinUnits
    - definition
    -	 * 
    - * NOTE: Not referenced by ATS - * + definition + * NOTE: Not referenced by ATS * @param testPoint the testPoint under test, never null - * @param model api definition, never null + * @param model api definition, never null */ public void withinUnitsParameterDefinition(TestPoint testPoint, OpenApi3 model) { - - - - - Parameter withinUnits = null; - String paramName = "within-units"; - - - - for (Path path : model.getPaths().values()) { - + Parameter withinUnits = null; + String paramName = "within-units"; - if (testPoint.getPath().equals(path.getPathString())) { + for (Path path : model.getPaths().values()) { - for (Operation op : path.getOperations().values()) { + if (testPoint.getPath().equals(path.getPathString())) { - for (Parameter param : op.getParameters()) { - if(hasName(param)) { - if (param.getName().equals(paramName)) - { - withinUnits = param; - } - } - } - } - } - } + for (Operation op : path.getOperations().values()) { - // ---------------- + for (Parameter param : op.getParameters()) { + if (hasName(param)) { + if (param.getName().equals(paramName)) { + withinUnits = param; + } + } + } + } + } + } + // ---------------- - if (withinUnits != null) { - String msg = "Expected property '%s' with value '%s' but was '%s'"; - assertEquals(withinUnits.getName(), paramName, String.format(msg, "name", paramName, withinUnits.getName())); - assertEquals(withinUnits.getIn(), "query", String.format(msg, "in", "query", withinUnits.getIn())); - assertFalse(isRequired(withinUnits), String.format(msg, "required", "false", withinUnits.getRequired())); - assertEquals( withinUnits.getStyle(), "form", String.format( msg, "style","form", withinUnits.getStyle() ) ); - assertFalse(isExplode(withinUnits), String.format(msg, "explode", "false", withinUnits.getExplode())); - } - - + if (withinUnits != null) { + String msg = "Expected property '%s' with value '%s' but was '%s'"; + assertEquals(withinUnits.getName(), paramName, + String.format(msg, "name", paramName, withinUnits.getName())); + assertEquals(withinUnits.getIn(), "query", String.format(msg, "in", "query", withinUnits.getIn())); + assertFalse(isRequired(withinUnits), String.format(msg, "required", "false", withinUnits.getRequired())); + assertEquals(withinUnits.getStyle(), "form", String.format(msg, "style", "form", withinUnits.getStyle())); + assertFalse(isExplode(withinUnits), String.format(msg, "explode", "false", withinUnits.getExplode())); + } } - - - /** *
     	 * Requirement A.25: /req/edr/resolution-x-definition Parameter resolution-x
    - definition
    -	 * 
    - * NOTE: Not referenced by ATS - * + definition + * NOTE: Not referenced by ATS * @param testPoint the testPoint under test, never null * @param model api definition, never null */ public void resolutionxParameterDefinition(TestPoint testPoint, OpenApi3 model) { - - - - - Parameter resolutionx = null; - String paramName = "resolution-x"; - - - - for (Path path : model.getPaths().values()) { + Parameter resolutionx = null; + String paramName = "resolution-x"; + for (Path path : model.getPaths().values()) { - if (testPoint.getPath().equals(path.getPathString())) { + if (testPoint.getPath().equals(path.getPathString())) { - for (Operation op : path.getOperations().values()) { + for (Operation op : path.getOperations().values()) { - for (Parameter param : op.getParameters()) { - - if(hasName(param)) { - if (param.getName().equals(paramName)) - { - resolutionx = param; - } - } - } - } - } - } + for (Parameter param : op.getParameters()) { - // ---------------- + if (hasName(param)) { + if (param.getName().equals(paramName)) { + resolutionx = param; + } + } + } + } + } + } + // ---------------- - if (resolutionx != null) { - String msg = "Expected property '%s' with value '%s' but was '%s'"; - assertEquals(resolutionx.getName(), paramName, String.format(msg, "name", paramName, resolutionx.getName())); - assertEquals(resolutionx.getIn(), "query", String.format(msg, "in", "query", resolutionx.getIn())); - assertFalse(isRequired(resolutionx), String.format(msg, "required", "false", resolutionx.getRequired())); - assertEquals( resolutionx.getStyle(), "form", String.format( msg, "style","form", resolutionx.getStyle() ) ); - assertFalse(isExplode(resolutionx), String.format(msg, "explode", "false", resolutionx.getExplode())); - } - - + if (resolutionx != null) { + String msg = "Expected property '%s' with value '%s' but was '%s'"; + assertEquals(resolutionx.getName(), paramName, + String.format(msg, "name", paramName, resolutionx.getName())); + assertEquals(resolutionx.getIn(), "query", String.format(msg, "in", "query", resolutionx.getIn())); + assertFalse(isRequired(resolutionx), String.format(msg, "required", "false", resolutionx.getRequired())); + assertEquals(resolutionx.getStyle(), "form", String.format(msg, "style", "form", resolutionx.getStyle())); + assertFalse(isExplode(resolutionx), String.format(msg, "explode", "false", resolutionx.getExplode())); + } } /** *
     	 * Requirement A.28: /req/edr/resolution-y-definition Parameter resolution-y
    - definition
    -	 * 
    - * NOTE: Not referenced by ATS - * + definition + * NOTE: Not referenced by ATS * @param testPoint the testPoint under test, never null * @param model api definition, never null */ public void resolutionyParameterDefinition(TestPoint testPoint, OpenApi3 model) { - - - - - Parameter resolutiony = null; - String paramName = "resolution-y"; - - - - for (Path path : model.getPaths().values()) { + Parameter resolutiony = null; + String paramName = "resolution-y"; + for (Path path : model.getPaths().values()) { - if (testPoint.getPath().equals(path.getPathString())) { + if (testPoint.getPath().equals(path.getPathString())) { - for (Operation op : path.getOperations().values()) { + for (Operation op : path.getOperations().values()) { - for (Parameter param : op.getParameters()) { - - if(hasName(param)) { - if (param.getName().equals(paramName)) - { - resolutiony = param; - } - } - } - } - } - } + for (Parameter param : op.getParameters()) { - // ---------------- + if (hasName(param)) { + if (param.getName().equals(paramName)) { + resolutiony = param; + } + } + } + } + } + } + // ---------------- - if (resolutiony != null) { - String msg = "Expected property '%s' with value '%s' but was '%s'"; - assertEquals(resolutiony.getName(), paramName, String.format(msg, "name", paramName, resolutiony.getName())); - assertEquals(resolutiony.getIn(), "query", String.format(msg, "in", "query", resolutiony.getIn())); - assertFalse(isRequired(resolutiony), String.format(msg, "required", "false", resolutiony.getRequired())); - assertEquals( resolutiony.getStyle(), "form", String.format( msg, "style","form", resolutiony.getStyle() ) ); - assertFalse(isExplode(resolutiony), String.format(msg, "explode", "false", resolutiony.getExplode())); - } + if (resolutiony != null) { + String msg = "Expected property '%s' with value '%s' but was '%s'"; + assertEquals(resolutiony.getName(), paramName, + String.format(msg, "name", paramName, resolutiony.getName())); + assertEquals(resolutiony.getIn(), "query", String.format(msg, "in", "query", resolutiony.getIn())); + assertFalse(isRequired(resolutiony), String.format(msg, "required", "false", resolutiony.getRequired())); + assertEquals(resolutiony.getStyle(), "form", String.format(msg, "style", "form", resolutiony.getStyle())); + assertFalse(isExplode(resolutiony), String.format(msg, "explode", "false", resolutiony.getExplode())); + } - } /** *
     	 * Requirement A.30: /req/edr/resolution-z-definition Parameter resolution-z definition
    -	 * 
    - * NOTE: Not referenced by ATS - * + * NOTE: Not referenced by ATS * @param testPoint the testPoint under test, never null * @param model api definition, never null */ public void resolutionzParameterDefinition(TestPoint testPoint, OpenApi3 model) { - - - - - Parameter resolutionz = null; - String paramName = "resolution-z"; - - - - for (Path path : model.getPaths().values()) { + Parameter resolutionz = null; + String paramName = "resolution-z"; + for (Path path : model.getPaths().values()) { - if (testPoint.getPath().equals(path.getPathString())) { + if (testPoint.getPath().equals(path.getPathString())) { - for (Operation op : path.getOperations().values()) { + for (Operation op : path.getOperations().values()) { - for (Parameter param : op.getParameters()) { - if(hasName(param)) { - if (param.getName().equals(paramName)) - { - resolutionz = param; - } - } - } - } - } - } + for (Parameter param : op.getParameters()) { + if (hasName(param)) { + if (param.getName().equals(paramName)) { + resolutionz = param; + } + } + } + } + } + } - // ---------------- + // ---------------- + if (resolutionz != null) { - if (resolutionz != null) { + String msg = "Expected property '%s' with value '%s' but was '%s'"; + assertEquals(resolutionz.getName(), paramName, + String.format(msg, "name", paramName, resolutionz.getName())); + assertEquals(resolutionz.getIn(), "query", String.format(msg, "in", "query", resolutionz.getIn())); + assertFalse(isRequired(resolutionz), String.format(msg, "required", "false", resolutionz.getRequired())); + assertEquals(resolutionz.getStyle(), "form", String.format(msg, "style", "form", resolutionz.getStyle())); + assertFalse(isExplode(resolutionz), String.format(msg, "explode", "false", resolutionz.getExplode())); + } - String msg = "Expected property '%s' with value '%s' but was '%s'"; - assertEquals(resolutionz.getName(), paramName, String.format(msg, "name", paramName, resolutionz.getName())); - assertEquals(resolutionz.getIn(), "query", String.format(msg, "in", "query", resolutionz.getIn())); - assertFalse(isRequired(resolutionz), String.format(msg, "required", "false", resolutionz.getRequired())); - assertEquals( resolutionz.getStyle(), "form", String.format( msg, "style","form", resolutionz.getStyle() ) ); - assertFalse(isExplode(resolutionz), String.format(msg, "explode", "false", resolutionz.getExplode())); - } - - } /** *
     	 * Abstract Test 120: Validate that the corridor-height query parameter is constructed correctly.
     	 * 
    - * * @param testPoint the testPoint under test, never null * @param model api definition, never null */ public void corridorHeightParameterDefinition(TestPoint testPoint, OpenApi3 model) { + Parameter corridorHeight = null; + String paramName = "corridor-height"; + for (Path path : model.getPaths().values()) { + if (testPoint.getPath().equals(path.getPathString())) { - Parameter corridorHeight = null; - String paramName = "corridor-height"; - - - - for (Path path : model.getPaths().values()) { - - - - if (testPoint.getPath().equals(path.getPathString())) { - - for (Operation op : path.getOperations().values()) { + for (Operation op : path.getOperations().values()) { - for (Parameter param : op.getParameters()) { - if(hasName(param)) { - if (param.getName().equals(paramName)) - { - corridorHeight = param; - } - } - } - } - } - } + for (Parameter param : op.getParameters()) { + if (hasName(param)) { + if (param.getName().equals(paramName)) { + corridorHeight = param; + } + } + } + } + } + } - // ---------------- + // ---------------- + if (corridorHeight != null) { - if (corridorHeight != null) { + String msg = "Expected property '%s' with value '%s' but was '%s'"; + assertEquals(corridorHeight.getName(), paramName, + String.format(msg, "name", paramName, corridorHeight.getName())); + assertEquals(corridorHeight.getIn(), "query", String.format(msg, "in", "query", corridorHeight.getIn())); + assertTrue(isRequired(corridorHeight), + String.format(msg, "required", "true", corridorHeight.getRequired())); + assertEquals(corridorHeight.getStyle(), "form", + String.format(msg, "style", "form", corridorHeight.getStyle())); + assertFalse(isExplode(corridorHeight), String.format(msg, "explode", "false", corridorHeight.getExplode())); + } - String msg = "Expected property '%s' with value '%s' but was '%s'"; - assertEquals(corridorHeight.getName(), paramName, String.format(msg, "name", paramName, corridorHeight.getName())); - assertEquals(corridorHeight.getIn(), "query", String.format(msg, "in", "query", corridorHeight.getIn())); - assertTrue(isRequired(corridorHeight), String.format(msg, "required", "true", corridorHeight.getRequired())); - assertEquals( corridorHeight.getStyle(), "form", String.format( msg, "style","form", corridorHeight.getStyle() ) ); - assertFalse(isExplode(corridorHeight), String.format(msg, "explode", "false", corridorHeight.getExplode())); - } - - } /** *
     	 * Abstract Test 118: Validate that the corridor-width query parameter is constructed correctly. (corridor)
    -	 * 
    - * NOTE: Not referenced by ATS - * + * NOTE: Not referenced by ATS * @param testPoint the testPoint under test, never null * @param model api definition, never null */ public void corridorWidthParameterDefinition(TestPoint testPoint, OpenApi3 model) { + Parameter corridorWidth = null; + String paramName = "corridor-width"; - Parameter corridorWidth = null; - String paramName = "corridor-width"; - - - - for (Path path : model.getPaths().values()) { - - + for (Path path : model.getPaths().values()) { - if (testPoint.getPath().equals(path.getPathString())) { + if (testPoint.getPath().equals(path.getPathString())) { - for (Operation op : path.getOperations().values()) { + for (Operation op : path.getOperations().values()) { - for (Parameter param : op.getParameters()) { - if(hasName(param)) { - if (param.getName().equals(paramName)) - { - corridorWidth = param; - } - } - } - } - } - } + for (Parameter param : op.getParameters()) { + if (hasName(param)) { + if (param.getName().equals(paramName)) { + corridorWidth = param; + } + } + } + } + } + } - // ---------------- + // ---------------- + if (corridorWidth != null) { - if (corridorWidth != null) { + String msg = "Expected property '%s' with value '%s' but was '%s'"; + assertEquals(corridorWidth.getName(), paramName, + String.format(msg, "name", paramName, corridorWidth.getName())); + assertEquals(corridorWidth.getIn(), "query", String.format(msg, "in", "query", corridorWidth.getIn())); + assertTrue(isRequired(corridorWidth), String.format(msg, "required", "true", corridorWidth.getRequired())); + assertEquals(corridorWidth.getStyle(), "form", + String.format(msg, "style", "form", corridorWidth.getStyle())); + assertFalse(isExplode(corridorWidth), String.format(msg, "explode", "false", corridorWidth.getExplode())); + } - String msg = "Expected property '%s' with value '%s' but was '%s'"; - assertEquals(corridorWidth.getName(), paramName, String.format(msg, "name", paramName, corridorWidth.getName())); - assertEquals(corridorWidth.getIn(), "query", String.format(msg, "in", "query", corridorWidth.getIn())); - assertTrue(isRequired(corridorWidth), String.format(msg, "required", "true", corridorWidth.getRequired())); - assertEquals( corridorWidth.getStyle(), "form", String.format( msg, "style","form", corridorWidth.getStyle() ) ); - assertFalse(isExplode(corridorWidth), String.format(msg, "explode", "false", corridorWidth.getExplode())); - } - - } - - + } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/collections/CorridorCollections.java b/src/main/java/org/opengis/cite/ogcapiedr10/collections/CorridorCollections.java index 07ddc14..6eb2ed0 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/collections/CorridorCollections.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/collections/CorridorCollections.java @@ -9,7 +9,8 @@ */ public class CorridorCollections extends AbstractFeatures { - CollectionsTime ct= new CollectionsTime(); + CollectionsTime ct = new CollectionsTime(); + /** *
     	 * Abstract Test 38: Validate that the coords query parameters are constructed correctly. (position)
    @@ -18,17 +19,14 @@ public class CorridorCollections extends AbstractFeatures {
     	 * Abstract Test 92: Validate that the coords query parameters are constructed correctly. (trajectory)
     	 * Abstract Test 116: Validate that the coords query parameters are constructed correctly. (corridor)
     	 * 
    - * * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 38 (/conf/edr/rc-coords-definition), Abstract Test 54, Abstract Test 70, Abstract Test 92, Abstract Test 116", dataProvider = "corridorCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 38 (/conf/edr/rc-coords-definition), Abstract Test 54, Abstract Test 70, Abstract Test 92, Abstract Test 116", + dataProvider = "corridorCollectionPaths", alwaysRun = true) public void corridorCoordsParameterDefinition(TestPoint testPoint) { - - - - ct.coordsParameterDefinition(testPoint,this.getModel()); System.gc(); - + ct.coordsParameterDefinition(testPoint, this.getModel()); + System.gc(); } @@ -41,175 +39,144 @@ public void corridorCoordsParameterDefinition(TestPoint testPoint) { * Abstract Test 115: Validate that resources can be identified and extracted from a Collection with a corridor query using query parameters. (corridor) * Abstract Test 139: Validate that the dateTime query parameters are constructed correctly. (locations) * - * * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 42 (/conf/core/datetime-definition), Abstract Test 58 (/conf/core/datetime-definition), and Abstract Test 74 (/conf/core/datetime-definition), Abstract Test 115 (/conf/corridor), and Abstract Test 139 (/conf/core/datetime-definition)", dataProvider = "corridorCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 42 (/conf/core/datetime-definition), Abstract Test 58 (/conf/core/datetime-definition), and Abstract Test 74 (/conf/core/datetime-definition), Abstract Test 115 (/conf/corridor), and Abstract Test 139 (/conf/core/datetime-definition)", + dataProvider = "corridorCollectionPaths", alwaysRun = true) public void corridorDateTimeParameterDefinition(TestPoint testPoint) { - - - - ct.dateTimeParameterDefinition(testPoint,this.getModel()); System.gc(); - + ct.dateTimeParameterDefinition(testPoint, this.getModel()); + System.gc(); } /** - * Abstract Test 44: Validate that the parameter-name query parameters are processed correctly. (position) - * Abstract Test 60: Validate that the parameter-name query parameters are processed correctly. (area) - * Abstract Test 76: Validate that the parameter-name query parameters are processed correctly. (cube) - * Abstract Test 94: Validate that the parameter-name query parameters are processed correctly. (trajectory) - * Abstract Test 126: Validate that the parameter-name query parameters are processed correctly. (corridor) - * Abstract Test 141: Validate that the parameter-name query parameters are processed correctly. (locations) - * + * Abstract Test 44: Validate that the parameter-name query parameters are processed + * correctly. (position) Abstract Test 60: Validate that the parameter-name query + * parameters are processed correctly. (area) Abstract Test 76: Validate that the + * parameter-name query parameters are processed correctly. (cube) Abstract Test 94: + * Validate that the parameter-name query parameters are processed correctly. + * (trajectory) Abstract Test 126: Validate that the parameter-name query parameters + * are processed correctly. (corridor) Abstract Test 141: Validate that the + * parameter-name query parameters are processed correctly. (locations) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 44 (/conf/collections/REQ_rc-parameter-name-definition), Abstract Test 60 (/conf/collections/REQ_rc-parameter-name-definition), Abstract Test 76 (/conf/collections/REQ_rc-parameter-name-definition), Abstract Test 94 (/conf/collections/REQ_rc-parameter-name-definition), Abstract Test 126 (/conf/collections/REQ_rc-parameter-name-definition), Abstract Test 141 (/conf/collections/REQ_rc-parameter-name-definition)", dataProvider = "corridorCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 44 (/conf/collections/REQ_rc-parameter-name-definition), Abstract Test 60 (/conf/collections/REQ_rc-parameter-name-definition), Abstract Test 76 (/conf/collections/REQ_rc-parameter-name-definition), Abstract Test 94 (/conf/collections/REQ_rc-parameter-name-definition), Abstract Test 126 (/conf/collections/REQ_rc-parameter-name-definition), Abstract Test 141 (/conf/collections/REQ_rc-parameter-name-definition)", + dataProvider = "corridorCollectionPaths", alwaysRun = true) public void corridorParameternameParameterDefinition(TestPoint testPoint) { - - - - ct.parameternameParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.parameternameParameterDefinition(testPoint, this.getModel()); + System.gc(); } /** - * Abstract Test 46: Validate that the crs query parameters are constructed correctly. (position) - * Abstract Test 62: Validate that the crs query parameters are constructed correctly. (area) - * Abstract Test 78: Validate that the crs query parameters are constructed correctly. (cube) - * Abstract Test 96: Validate that the crs query parameters are constructed correctly. (trajectory) - * Abstract Test 128: Validate that the crs query parameters are constructed correctly. (corridor) - * Abstract Test 143: Validate that the crs query parameters are constructed correctly. (locations) - * + * Abstract Test 46: Validate that the crs query parameters are constructed correctly. + * (position) Abstract Test 62: Validate that the crs query parameters are constructed + * correctly. (area) Abstract Test 78: Validate that the crs query parameters are + * constructed correctly. (cube) Abstract Test 96: Validate that the crs query + * parameters are constructed correctly. (trajectory) Abstract Test 128: Validate that + * the crs query parameters are constructed correctly. (corridor) Abstract Test 143: + * Validate that the crs query parameters are constructed correctly. (locations) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 46 (/conf/edr/REQ_rc-crs-definition), Abstract Test 62 (/conf/edr/REQ_rc-crs-definition), Abstract Test 78 (/conf/edr/REQ_rc-crs-definition), Abstract Test 96 (/conf/edr/REQ_rc-crs-definition), Abstract Test 128 (/conf/edr/REQ_rc-crs-definition), Abstract Test 143 (/conf/edr/REQ_rc-crs-definition)", dataProvider = "corridorCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 46 (/conf/edr/REQ_rc-crs-definition), Abstract Test 62 (/conf/edr/REQ_rc-crs-definition), Abstract Test 78 (/conf/edr/REQ_rc-crs-definition), Abstract Test 96 (/conf/edr/REQ_rc-crs-definition), Abstract Test 128 (/conf/edr/REQ_rc-crs-definition), Abstract Test 143 (/conf/edr/REQ_rc-crs-definition)", + dataProvider = "corridorCollectionPaths", alwaysRun = true) public void corridorCrsParameterDefinition(TestPoint testPoint) { - - - - ct.crsParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.crsParameterDefinition(testPoint, this.getModel()); + System.gc(); } - - /** - * Abstract Test 48: Validate that the f query parameter is constructed correctly. (position) - * Abstract Test 64: Validate that the f query parameter is constructed correctly. (area) - * Abstract Test 80: Validate that the f query parameter is constructed correctly. (cube) - * Abstract Test 98: Validate that the f query parameter is constructed correctly. (trajectory) - * Abstract Test 130: Validate that the f query parameter is constructed correctly. (corridor) - * Abstract Test 145: Validate that the f query parameter is constructed correctly. (locations) - * + * Abstract Test 48: Validate that the f query parameter is constructed correctly. + * (position) Abstract Test 64: Validate that the f query parameter is constructed + * correctly. (area) Abstract Test 80: Validate that the f query parameter is + * constructed correctly. (cube) Abstract Test 98: Validate that the f query parameter + * is constructed correctly. (trajectory) Abstract Test 130: Validate that the f query + * parameter is constructed correctly. (corridor) Abstract Test 145: Validate that the + * f query parameter is constructed correctly. (locations) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 48 (/conf/edr/rc-f-definition),Abstract Test 64 (/conf/edr/rc-f-definition), Abstract Test 80 (/conf/edr/rc-f-definition), Abstract Test 98 (/conf/edr/rc-f-definition), Abstract Test 130 (/conf/edr/rc-f-definition), Abstract Test 145 (/conf/edr/rc-f-definition)", dataProvider = "corridorCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 48 (/conf/edr/rc-f-definition),Abstract Test 64 (/conf/edr/rc-f-definition), Abstract Test 80 (/conf/edr/rc-f-definition), Abstract Test 98 (/conf/edr/rc-f-definition), Abstract Test 130 (/conf/edr/rc-f-definition), Abstract Test 145 (/conf/edr/rc-f-definition)", + dataProvider = "corridorCollectionPaths", alwaysRun = true) public void corridorFParameterDefinition(TestPoint testPoint) { - - - - - ct.fParameterDefinition(testPoint,this.getModel()); System.gc(); - } + ct.fParameterDefinition(testPoint, this.getModel()); + System.gc(); + } /** - * Abstract Test 40: Validate that the vertical level query parameters are constructed correctly. (position) - * Abstract Test 56: Validate that the vertical level query parameters are constructed correctly. (area) - * - * + * Abstract Test 40: Validate that the vertical level query parameters are constructed + * correctly. (position) Abstract Test 56: Validate that the vertical level query + * parameters are constructed correctly. (area) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 40 (/conf/edr/rc-z-definition), Abstract Test 56 (/conf/edr/rc-z-definition)", dataProvider = "corridorCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 40 (/conf/edr/rc-z-definition), Abstract Test 56 (/conf/edr/rc-z-definition)", + dataProvider = "corridorCollectionPaths", alwaysRun = true) public void corridorZParameterDefinition(TestPoint testPoint) { - - - - ct.zParameterDefinition(testPoint,this.getModel()); System.gc(); - - } + ct.zParameterDefinition(testPoint, this.getModel()); + System.gc(); + } /** *
     	 * Requirement A.21: /req/edr/within-definition Parameter within definition
    -	 * 
    - * NOTE: Not referenced by ATS - * + * NOTE: Not referenced by ATS * @param testPoint the testPoint under test, never null */ - @Test(description = "Requirement A.21: /req/edr/within-definition Parameter within definition", dataProvider = "corridorCollectionPaths", alwaysRun = true) + @Test(description = "Requirement A.21: /req/edr/within-definition Parameter within definition", + dataProvider = "corridorCollectionPaths", alwaysRun = true) public void corridorWithinParameterDefinition(TestPoint testPoint) { - - - - ct.withinParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.withinParameterDefinition(testPoint, this.getModel()); + System.gc(); - } - - + } /** *
     	 * Abstract Test 124: Validate that the vertical level query parameters are constructed correctly. (corridor)
     	 * 
    - * * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 124: (/conf/edr/REQ_rc-height-units-definition)", dataProvider = "corridorCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 124: (/conf/edr/REQ_rc-height-units-definition)", + dataProvider = "corridorCollectionPaths", alwaysRun = true) public void corridorWithinUnitsParameterDefinition(TestPoint testPoint) { - - - - ct.withinUnitsParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.withinUnitsParameterDefinition(testPoint, this.getModel()); + System.gc(); } - - - - - - /** *
     	 * Abstract Test 120: Validate that the corridor-height query parameter is constructed correctly.
     	 * 
    - * * @param testPoint the testPoint under test, never null */ - @Test(description = "Abstract Test 120: (/conf/edr/REQ_rc-corridor-height-definition)", dataProvider = "corridorCollectionPaths", alwaysRun = true) + @Test(description = "Abstract Test 120: (/conf/edr/REQ_rc-corridor-height-definition)", + dataProvider = "corridorCollectionPaths", alwaysRun = true) public void corridorCorridorHeightParameterDefinition(TestPoint testPoint) { - - - - ct.corridorHeightParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.corridorHeightParameterDefinition(testPoint, this.getModel()); + System.gc(); } /** *
     	 * Abstract Test 118: Validate that the corridor-width query parameter is constructed correctly. (corridor)
     	 * 
    - * * @param testPoint the testPoint under test, never null */ - @Test(description = "Abstract Test 118 (/conf/edr/REQ_rc-corridor-width-definition)", dataProvider = "corridorCollectionPaths", alwaysRun = true) + @Test(description = "Abstract Test 118 (/conf/edr/REQ_rc-corridor-width-definition)", + dataProvider = "corridorCollectionPaths", alwaysRun = true) public void corridorCorridorWidthParameterDefinition(TestPoint testPoint) { - - - - - ct.corridorWidthParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.corridorWidthParameterDefinition(testPoint, this.getModel()); + System.gc(); } - - -} +} diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/collections/CubeCollections.java b/src/main/java/org/opengis/cite/ogcapiedr10/collections/CubeCollections.java index 6ff494e..220007b 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/collections/CubeCollections.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/collections/CubeCollections.java @@ -9,22 +9,21 @@ */ public class CubeCollections extends AbstractFeatures { - CollectionsTime ct= new CollectionsTime(); + CollectionsTime ct = new CollectionsTime(); + /** *
     	 * Abstract Test 70: Validate that the coords query parameters are constructed correctly. (cube)
     	 * Note that the test actually tests for the bbox parameter (see https://github.com/opengeospatial/ogcapi-environmental-data-retrieval/issues/423)
     	 * 
    - * * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 70 (/conf/edr/rc-coords-definition)", dataProvider = "cubeCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 70 (/conf/edr/rc-coords-definition)", + dataProvider = "cubeCollectionPaths", alwaysRun = true) public void cubeBboxParameterDefinition(TestPoint testPoint) { - - - ct.bboxParameterDefinition(testPoint,this.getModel()); System.gc(); - + ct.bboxParameterDefinition(testPoint, this.getModel()); + System.gc(); } @@ -32,79 +31,69 @@ public void cubeBboxParameterDefinition(TestPoint testPoint) { *
     	 * Abstract Test 74: Validate that the dateTime query parameters are constructed correctly. (cube)
     	 * 
    - * * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 74 (/conf/core/datetime-definition)", dataProvider = "cubeCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 74 (/conf/core/datetime-definition)", + dataProvider = "cubeCollectionPaths", alwaysRun = true) public void cubeDateTimeParameterDefinition(TestPoint testPoint) { - - - ct.dateTimeParameterDefinition(testPoint,this.getModel()); System.gc(); - + ct.dateTimeParameterDefinition(testPoint, this.getModel()); + System.gc(); } /** - * Abstract Test 76: Validate that the parameter-name query parameters are processed correctly. (cube) - * + * Abstract Test 76: Validate that the parameter-name query parameters are processed + * correctly. (cube) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements 76 (/conf/collections/REQ_rc-parameter-name-definition)", dataProvider = "cubeCollectionPaths", alwaysRun = true) + @Test(description = "Implements 76 (/conf/collections/REQ_rc-parameter-name-definition)", + dataProvider = "cubeCollectionPaths", alwaysRun = true) public void cubeParameternameParameterDefinition(TestPoint testPoint) { - - - ct.parameternameParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.parameternameParameterDefinition(testPoint, this.getModel()); + System.gc(); } /** - * Abstract Test 78: Validate that the crs query parameters are constructed correctly. (cube) - * + * Abstract Test 78: Validate that the crs query parameters are constructed correctly. + * (cube) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 78 (/conf/edr/REQ_rc-crs-definition)", dataProvider = "cubeCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 78 (/conf/edr/REQ_rc-crs-definition)", + dataProvider = "cubeCollectionPaths", alwaysRun = true) public void cubeCrsParameterDefinition(TestPoint testPoint) { - - - ct.crsParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.crsParameterDefinition(testPoint, this.getModel()); + System.gc(); } - - /** - * Abstract Test 80: Validate that the f query parameter is constructed correctly. (cube) - * + * Abstract Test 80: Validate that the f query parameter is constructed correctly. + * (cube) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 80 (/conf/edr/rc-f-definition)", dataProvider = "cubeCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 80 (/conf/edr/rc-f-definition)", dataProvider = "cubeCollectionPaths", + alwaysRun = true) public void cubeFParameterDefinition(TestPoint testPoint) { - - - - ct.fParameterDefinition(testPoint,this.getModel()); System.gc(); - } + ct.fParameterDefinition(testPoint, this.getModel()); + System.gc(); + } /** - * Abstract Test 69: Validate that resources can be identified and extracted from a Collection with a Cube query using query parameters. - * - * + * Abstract Test 69: Validate that resources can be identified and extracted from a + * Collection with a Cube query using query parameters. * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements VerticalLevel check of Abstract Test 69 (/conf/cube)", dataProvider = "cubeCollectionPaths", alwaysRun = true) + @Test(description = "Implements VerticalLevel check of Abstract Test 69 (/conf/cube)", + dataProvider = "cubeCollectionPaths", alwaysRun = true) public void cubeZParameterDefinition(TestPoint testPoint) { - - - ct.zParameterDefinition(testPoint,this.getModel()); System.gc(); - - } + ct.zParameterDefinition(testPoint, this.getModel()); + System.gc(); + } - - } - diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/collections/FeaturesAssertions.java b/src/main/java/org/opengis/cite/ogcapiedr10/collections/FeaturesAssertions.java index 67f29e5..c26a184 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/collections/FeaturesAssertions.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/collections/FeaturesAssertions.java @@ -27,78 +27,75 @@ */ public class FeaturesAssertions { - static void assertIntegerGreaterZero( Object value, String propertyName ) { - if ( value instanceof Number ) - assertIntegerGreaterZero( ( (Number) value ).intValue(), propertyName ); - else if ( value instanceof String ) - try { - int valueAsInt = Integer.parseInt( (String) value ); - assertIntegerGreaterZero( valueAsInt, propertyName ); - } catch ( NumberFormatException e ) { - String msg = "Expected property '%s' to be an integer, but was '%s'"; - throw new AssertionError( String.format( msg, propertyName, value ) ); - } - } - - static void assertIntegerGreaterZero( int value, String propertyName ) { - String msg = "Expected property '%s' to be an integer greater than 0, but was '%s'"; - assertTrue( value > 0, String.format( msg, propertyName, value ) ); - } - - static void assertTimeStamp( String collectionName, JsonPath jsonPath, ZonedDateTime timeStampBeforeResponse, - ZonedDateTime timeStampAfterResponse, boolean skipIfNoTimeStamp ) { - String timeStamp = jsonPath.getString( "timeStamp" ); - if ( timeStamp == null ) - if ( skipIfNoTimeStamp ) - throw new SkipException( "Property timeStamp is not set in collection items '" + collectionName + "'" ); - else - return; - - ZonedDateTime date = parseAsDate( timeStamp ); - assertNotNull(date, "Not valid timestamp."); - } - - static void assertNumberReturned( String collectionName, JsonPath jsonPath, boolean skipIfNoNumberReturned ) { - if ( !hasProperty( "numberReturned", jsonPath ) ) - if ( skipIfNoNumberReturned ) - throw new SkipException( "Property numberReturned is not set in collection items '" + collectionName - + "'" ); - else - return; - - int numberReturned = jsonPath.getInt( "numberReturned" ); - int numberOfFeatures = jsonPath.getList( "features" ).size(); - assertEquals( numberReturned, numberOfFeatures, - "Value of numberReturned (" + numberReturned - + ") does not match the number of features in the response (" - + numberOfFeatures + ")" ); - } - - static void assertNumberMatched( OpenApi3 apiModel, URI iut, String collectionName, JsonPath jsonPath, - boolean skipIfNoNumberMatched ) - throws URISyntaxException { - if ( !hasProperty( "numberMatched", jsonPath ) ) - if ( skipIfNoNumberMatched ) - throw new SkipException( "Property numberMatched is not set in collection items '" + collectionName - + "'" ); - else - return; - - int maximumLimit = -1; - - List testPoints = retrieveTestPointsForCollection( apiModel, iut, collectionName ); - if ( !testPoints.isEmpty() ) { - TestPoint testPoint = testPoints.get( 0 ); - Parameter limitParameter = OpenApiUtils.retrieveParameterByName( testPoint.getPath(), apiModel, "limit" ); - if ( limitParameter != null && limitParameter.getSchema() != null ) { - maximumLimit = limitParameter.getSchema().getMaximum().intValue(); - } - } - int numberMatched = jsonPath.getInt( "numberMatched" ); - int numberOfAllReturnedFeatures = collectNumberOfAllReturnedFeatures( jsonPath, maximumLimit ); - assertEquals( numberMatched, numberOfAllReturnedFeatures, - "Value of numberReturned (" + numberMatched + ") does not match the number of features in all responses (" - + numberOfAllReturnedFeatures + ")" ); - } + static void assertIntegerGreaterZero(Object value, String propertyName) { + if (value instanceof Number) + assertIntegerGreaterZero(((Number) value).intValue(), propertyName); + else if (value instanceof String) + try { + int valueAsInt = Integer.parseInt((String) value); + assertIntegerGreaterZero(valueAsInt, propertyName); + } + catch (NumberFormatException e) { + String msg = "Expected property '%s' to be an integer, but was '%s'"; + throw new AssertionError(String.format(msg, propertyName, value)); + } + } + + static void assertIntegerGreaterZero(int value, String propertyName) { + String msg = "Expected property '%s' to be an integer greater than 0, but was '%s'"; + assertTrue(value > 0, String.format(msg, propertyName, value)); + } + + static void assertTimeStamp(String collectionName, JsonPath jsonPath, ZonedDateTime timeStampBeforeResponse, + ZonedDateTime timeStampAfterResponse, boolean skipIfNoTimeStamp) { + String timeStamp = jsonPath.getString("timeStamp"); + if (timeStamp == null) + if (skipIfNoTimeStamp) + throw new SkipException("Property timeStamp is not set in collection items '" + collectionName + "'"); + else + return; + + ZonedDateTime date = parseAsDate(timeStamp); + assertNotNull(date, "Not valid timestamp."); + } + + static void assertNumberReturned(String collectionName, JsonPath jsonPath, boolean skipIfNoNumberReturned) { + if (!hasProperty("numberReturned", jsonPath)) + if (skipIfNoNumberReturned) + throw new SkipException( + "Property numberReturned is not set in collection items '" + collectionName + "'"); + else + return; + + int numberReturned = jsonPath.getInt("numberReturned"); + int numberOfFeatures = jsonPath.getList("features").size(); + assertEquals(numberReturned, numberOfFeatures, "Value of numberReturned (" + numberReturned + + ") does not match the number of features in the response (" + numberOfFeatures + ")"); + } + + static void assertNumberMatched(OpenApi3 apiModel, URI iut, String collectionName, JsonPath jsonPath, + boolean skipIfNoNumberMatched) throws URISyntaxException { + if (!hasProperty("numberMatched", jsonPath)) + if (skipIfNoNumberMatched) + throw new SkipException( + "Property numberMatched is not set in collection items '" + collectionName + "'"); + else + return; + + int maximumLimit = -1; + + List testPoints = retrieveTestPointsForCollection(apiModel, iut, collectionName); + if (!testPoints.isEmpty()) { + TestPoint testPoint = testPoints.get(0); + Parameter limitParameter = OpenApiUtils.retrieveParameterByName(testPoint.getPath(), apiModel, "limit"); + if (limitParameter != null && limitParameter.getSchema() != null) { + maximumLimit = limitParameter.getSchema().getMaximum().intValue(); + } + } + int numberMatched = jsonPath.getInt("numberMatched"); + int numberOfAllReturnedFeatures = collectNumberOfAllReturnedFeatures(jsonPath, maximumLimit); + assertEquals(numberMatched, numberOfAllReturnedFeatures, "Value of numberReturned (" + numberMatched + + ") does not match the number of features in all responses (" + numberOfAllReturnedFeatures + ")"); + } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/collections/LocationsCollections.java b/src/main/java/org/opengis/cite/ogcapiedr10/collections/LocationsCollections.java index b0aefb4..7ef6433 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/collections/LocationsCollections.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/collections/LocationsCollections.java @@ -9,72 +9,61 @@ */ public class LocationsCollections extends AbstractFeatures { - CollectionsTime ct= new CollectionsTime(); + CollectionsTime ct = new CollectionsTime(); /** *
     	 * Abstract Test 139: Validate that the datetime query parameters are constructed correctly.
     	 * 
    - * * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 139 (/conf/core/datetime-definition)", dataProvider = "locationsCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 139 (/conf/core/datetime-definition)", + dataProvider = "locationsCollectionPaths", alwaysRun = true) public void locationsDateTimeParameterDefinition(TestPoint testPoint) { - - - ct.dateTimeParameterDefinition(testPoint,this.getModel()); System.gc(); - + ct.dateTimeParameterDefinition(testPoint, this.getModel()); + System.gc(); } /** - * Abstract Test 141: Validate that the parameter-name query parameters are processed correctly. (locations) - * + * Abstract Test 141: Validate that the parameter-name query parameters are processed + * correctly. (locations) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 141 (/conf/collections/REQ_rc-parameter-name-definition)", dataProvider = "locationsCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 141 (/conf/collections/REQ_rc-parameter-name-definition)", + dataProvider = "locationsCollectionPaths", alwaysRun = true) public void locationsParameternameParameterDefinition(TestPoint testPoint) { - - - ct.parameternameParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.parameternameParameterDefinition(testPoint, this.getModel()); + System.gc(); } /** - * Abstract Test 143: Validate that the crs query parameters are constructed correctly. (locations) - * + * Abstract Test 143: Validate that the crs query parameters are constructed + * correctly. (locations) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 143 (/conf/edr/REQ_rc-crs-definition)", dataProvider = "locationsCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 143 (/conf/edr/REQ_rc-crs-definition)", + dataProvider = "locationsCollectionPaths", alwaysRun = true) public void locationsCrsParameterDefinition(TestPoint testPoint) { - - - ct.crsParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.crsParameterDefinition(testPoint, this.getModel()); + System.gc(); } - - /** - * Abstract Test 145: Validate that the f query parameter is constructed correctly. (locations) - * + * Abstract Test 145: Validate that the f query parameter is constructed correctly. + * (locations) * @param testPoint the testPoint under test, never null */ - @Test(description = "Abstract Test 145 (/conf/edr/rc-f-definition)", dataProvider = "locationsCollectionPaths", alwaysRun = true) + @Test(description = "Abstract Test 145 (/conf/edr/rc-f-definition)", dataProvider = "locationsCollectionPaths", + alwaysRun = true) public void locationsFParameterDefinition(TestPoint testPoint) { + ct.fParameterDefinition(testPoint, this.getModel()); + System.gc(); + } - - - ct.fParameterDefinition(testPoint,this.getModel()); System.gc(); - } - - - - - - } - diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/collections/PositionCollections.java b/src/main/java/org/opengis/cite/ogcapiedr10/collections/PositionCollections.java index e5445f7..0f63cec 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/collections/PositionCollections.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/collections/PositionCollections.java @@ -9,21 +9,20 @@ */ public class PositionCollections extends AbstractFeatures { - CollectionsTime ct= new CollectionsTime(); + CollectionsTime ct = new CollectionsTime(); + /** *
     	 * Abstract Test 38: Validate that the coords query parameters are constructed correctly. (position)
     	 * 
    - * * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 36 (/conf/edr/rc-coords-definition)", dataProvider = "positionCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 36 (/conf/edr/rc-coords-definition)", + dataProvider = "positionCollectionPaths", alwaysRun = true) public void positionCoordsParameterDefinition(TestPoint testPoint) { - - - ct.coordsParameterDefinition(testPoint,this.getModel()); System.gc(); - + ct.coordsParameterDefinition(testPoint, this.getModel()); + System.gc(); } @@ -31,79 +30,69 @@ public void positionCoordsParameterDefinition(TestPoint testPoint) { *
     	 * Abstract Test 42: Validate that the dateTime query parameters are constructed correctly. (position)
     	 * 
    - * * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 42 (/conf/core/datetime-definition)", dataProvider = "positionCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 42 (/conf/core/datetime-definition)", + dataProvider = "positionCollectionPaths", alwaysRun = true) public void positionDateTimeParameterDefinition(TestPoint testPoint) { - - - ct.dateTimeParameterDefinition(testPoint,this.getModel()); System.gc(); - + ct.dateTimeParameterDefinition(testPoint, this.getModel()); + System.gc(); } /** - * Abstract Test 44: Validate that the parameter-name query parameters are processed correctly. (position) - * + * Abstract Test 44: Validate that the parameter-name query parameters are processed + * correctly. (position) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 44 (/conf/collections/REQ_rc-parameter-name-definition)", dataProvider = "positionCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 44 (/conf/collections/REQ_rc-parameter-name-definition)", + dataProvider = "positionCollectionPaths", alwaysRun = true) public void positionParameternameParameterDefinition(TestPoint testPoint) { - - - ct.parameternameParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.parameternameParameterDefinition(testPoint, this.getModel()); + System.gc(); } /** - * Abstract Test 46: Validate that the crs query parameters are constructed correctly. (position) - * + * Abstract Test 46: Validate that the crs query parameters are constructed correctly. + * (position) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 46 (/conf/edr/REQ_rc-crs-definition)", dataProvider = "positionCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 46 (/conf/edr/REQ_rc-crs-definition)", + dataProvider = "positionCollectionPaths", alwaysRun = true) public void positionCrsParameterDefinition(TestPoint testPoint) { - - - ct.crsParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.crsParameterDefinition(testPoint, this.getModel()); + System.gc(); } - - /** - * Abstract Test 48: Validate that the f query parameter is constructed correctly. (position) - * + * Abstract Test 48: Validate that the f query parameter is constructed correctly. + * (position) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 48 (/conf/edr/rc-f-definition)", dataProvider = "positionCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 48 (/conf/edr/rc-f-definition)", + dataProvider = "positionCollectionPaths", alwaysRun = true) public void positionFParameterDefinition(TestPoint testPoint) { - - - - ct.fParameterDefinition(testPoint,this.getModel()); System.gc(); - } + ct.fParameterDefinition(testPoint, this.getModel()); + System.gc(); + } /** - * Abstract Test 40: Validate that the vertical level query parameters are constructed correctly. (position) - * - * + * Abstract Test 40: Validate that the vertical level query parameters are constructed + * correctly. (position) * @param testPoint the testPoint under test, never null */ - @Test(description = "Abstract Test 40 (/conf/edr/rc-z-definition)", dataProvider = "positionCollectionPaths", alwaysRun = true) + @Test(description = "Abstract Test 40 (/conf/edr/rc-z-definition)", dataProvider = "positionCollectionPaths", + alwaysRun = true) public void positionZParameterDefinition(TestPoint testPoint) { - - - ct.zParameterDefinition(testPoint,this.getModel()); System.gc(); - - } - + ct.zParameterDefinition(testPoint, this.getModel()); + System.gc(); + } - } - diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/collections/TrajectoryCollections.java b/src/main/java/org/opengis/cite/ogcapiedr10/collections/TrajectoryCollections.java index 75320ee..2b25d3e 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/collections/TrajectoryCollections.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/collections/TrajectoryCollections.java @@ -9,21 +9,20 @@ */ public class TrajectoryCollections extends AbstractFeatures { - CollectionsTime ct= new CollectionsTime(); + CollectionsTime ct = new CollectionsTime(); + /** *
     	 * Abstract Test 92: Validate that the coords query parameters are constructed correctly. (trajectory)
     	 * 
    - * * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 92 (/conf/edr/rc-coords-definition)", dataProvider = "trajectoryCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 92 (/conf/edr/rc-coords-definition)", + dataProvider = "trajectoryCollectionPaths", alwaysRun = true) public void trajectoryCoordsParameterDefinition(TestPoint testPoint) { - - - ct.coordsParameterDefinition(testPoint,this.getModel()); System.gc(); - + ct.coordsParameterDefinition(testPoint, this.getModel()); + System.gc(); } @@ -31,77 +30,69 @@ public void trajectoryCoordsParameterDefinition(TestPoint testPoint) { *
     	 * Abstract Test 91: Validate that resources can be identified and extracted from a Collection with a Trajectory query using query parameters. (trajectory)
     	 * 
    - * * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements datetime parameter part of Abstract Test 91 (/conf/trajectory)", dataProvider = "trajectoryCollectionPaths", alwaysRun = true) + @Test(description = "Implements datetime parameter part of Abstract Test 91 (/conf/trajectory)", + dataProvider = "trajectoryCollectionPaths", alwaysRun = true) public void trajectoryDateTimeParameterDefinition(TestPoint testPoint) { - - - ct.dateTimeParameterDefinition(testPoint,this.getModel()); System.gc(); - + ct.dateTimeParameterDefinition(testPoint, this.getModel()); + System.gc(); } /** - * Abstract Test 94: Validate that the parameter-name query parameters are processed correctly. (trajectory) - * + * Abstract Test 94: Validate that the parameter-name query parameters are processed + * correctly. (trajectory) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 94 (/conf/collections/REQ_rc-parameter-name-definition)", dataProvider = "trajectoryCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 94 (/conf/collections/REQ_rc-parameter-name-definition)", + dataProvider = "trajectoryCollectionPaths", alwaysRun = true) public void trajectoryParameternameParameterDefinition(TestPoint testPoint) { - - - ct.parameternameParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.parameternameParameterDefinition(testPoint, this.getModel()); + System.gc(); } /** - * Abstract Test 96: Validate that the crs query parameters are constructed correctly. (trajectory) - * + * Abstract Test 96: Validate that the crs query parameters are constructed correctly. + * (trajectory) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 96 (/conf/edr/REQ_rc-crs-definition)", dataProvider = "trajectoryCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 96 (/conf/edr/REQ_rc-crs-definition)", + dataProvider = "trajectoryCollectionPaths", alwaysRun = true) public void trajectoryCrsParameterDefinition(TestPoint testPoint) { - - - ct.crsParameterDefinition(testPoint,this.getModel()); System.gc(); + ct.crsParameterDefinition(testPoint, this.getModel()); + System.gc(); } - - /** - * Abstract Test 98: Validate that the f query parameter is constructed correctly. (trajectory) - * + * Abstract Test 98: Validate that the f query parameter is constructed correctly. + * (trajectory) * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements Abstract Test 98 (/conf/edr/rc-f-definition)", dataProvider = "trajectoryCollectionPaths", alwaysRun = true) + @Test(description = "Implements Abstract Test 98 (/conf/edr/rc-f-definition)", + dataProvider = "trajectoryCollectionPaths", alwaysRun = true) public void trajectoryFParameterDefinition(TestPoint testPoint) { - - - - ct.fParameterDefinition(testPoint,this.getModel()); System.gc(); - } + ct.fParameterDefinition(testPoint, this.getModel()); + System.gc(); + } /** - * Abstract Test 91: Validate that resources can be identified and extracted from a Collection with a Trajectory query using query parameters. - * - * + * Abstract Test 91: Validate that resources can be identified and extracted from a + * Collection with a Trajectory query using query parameters. * @param testPoint the testPoint under test, never null */ - @Test(description = "Implements VerticalLevel part of Abstract Test 91 (/conf/trajectory)", dataProvider = "trajectoryCollectionPaths", alwaysRun = true) + @Test(description = "Implements VerticalLevel part of Abstract Test 91 (/conf/trajectory)", + dataProvider = "trajectoryCollectionPaths", alwaysRun = true) public void trajectoryZParameterDefinition(TestPoint testPoint) { - - ct.zParameterDefinition(testPoint,this.getModel()); System.gc(); - - } + ct.zParameterDefinition(testPoint, this.getModel()); + System.gc(); + } - } - diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/conformance/ApiDefinition.java b/src/main/java/org/opengis/cite/ogcapiedr10/conformance/ApiDefinition.java index 5c945e6..6420787 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/conformance/ApiDefinition.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/conformance/ApiDefinition.java @@ -31,76 +31,78 @@ */ public class ApiDefinition extends CommonFixture { - private String response; - - private Link apiUrl = null; - - @BeforeClass(dependsOnMethods = "initCommonFixture") - public void retrieveApiUrl() { - Response request = init().baseUri( rootUri.toString() ).accept( JSON ).when().request( GET ); - JsonPath jsonPath = request.jsonPath(); - - this.apiUrl = OpenApiUtils.parseApiUrl( jsonPath ); - } - - - - - /** - *
    -     * Abstract Test 4: Test Purpose: Validate that the API Definition document can be retrieved from the expected location.
    -     * 
    - */ - @Test(description = "Implements Abstract Test 4 (/conf/core/api-definition)", groups = "apidefinition", dependsOnGroups = "landingpage") - public void openapiDocumentRetrieval() { - - if ( apiUrl == null || apiUrl.getHref().isEmpty() ) - throw new AssertionError( "Path to the API Definition could not be constructed from the landing page" ); - Response request = init().baseUri( apiUrl.getHref() ).accept( apiUrl.getType() ).when().request( GET ); - request.then().statusCode( 200 ); - response = request.asString(); - } - - /** - *
    -     * Abstract Test 5: Validate that the API Definition complies with the required structure and contents.
    -     * 
    - * - * @param testContext - * never null - * @throws MalformedURLException - * if the apiUrl is malformed - */ - @Test(description = "Implements Abstract Test 5 (/conf/core/api-definition-success)", groups = "apidefinition", dependsOnMethods = "openapiDocumentRetrieval") - public void apiDefinitionValidation( ITestContext testContext ) - throws MalformedURLException { - - OpenApi3 apiModel = (OpenApi3) testContext.getSuite().getAttribute( API_MODEL.getName()); - - if(apiModel == null) { - URI apiDefinitionLocation = (URI) testContext.getSuite().getAttribute( SuiteAttribute.API_DEFINITION.getName()); - throw new AssertionError("Could not create API model from URI: " + apiDefinitionLocation); - } - - if(apiModel.isValid() && (!apiUrl.getType().equals(OPEN_API_MIME_TYPE))) - { - throw new SkipException("The API Definition was found to be valid. However, the Media Type identified by the Link to the API Definition document was not "+OPEN_API_MIME_TYPE); - } - - assertTrue( apiModel.isValid(), createValidationMsg( apiModel ) ); - - } - - private String createValidationMsg( OpenApi3 model ) { - StringBuilder sb = new StringBuilder(); - sb.append( "API definition is not valid. Found following validation items:" ); - if ( !model.isValid() ) { - for ( ValidationResults.ValidationItem item : model.getValidationItems() ) { - sb.append( " @ " ).append( item.getPositionInfo() ).append( " - " ).append( item.getSeverity() ).append( ": " ).append( item.getMsg() ); - - } - } - return sb.toString(); - } + private String response; + + private Link apiUrl = null; + + @BeforeClass(dependsOnMethods = "initCommonFixture") + public void retrieveApiUrl() { + Response request = init().baseUri(rootUri.toString()).accept(JSON).when().request(GET); + JsonPath jsonPath = request.jsonPath(); + + this.apiUrl = OpenApiUtils.parseApiUrl(jsonPath); + } + + /** + *
    +	 * Abstract Test 4: Test Purpose: Validate that the API Definition document can be retrieved from the expected location.
    +	 * 
    + */ + @Test(description = "Implements Abstract Test 4 (/conf/core/api-definition)", groups = "apidefinition", + dependsOnGroups = "landingpage") + public void openapiDocumentRetrieval() { + + if (apiUrl == null || apiUrl.getHref().isEmpty()) + throw new AssertionError("Path to the API Definition could not be constructed from the landing page"); + Response request = init().baseUri(apiUrl.getHref()).accept(apiUrl.getType()).when().request(GET); + request.then().statusCode(200); + response = request.asString(); + } + + /** + *
    +	 * Abstract Test 5: Validate that the API Definition complies with the required structure and contents.
    +	 * 
    + * @param testContext never null + * @throws MalformedURLException if the apiUrl is malformed + */ + @Test(description = "Implements Abstract Test 5 (/conf/core/api-definition-success)", groups = "apidefinition", + dependsOnMethods = "openapiDocumentRetrieval") + public void apiDefinitionValidation(ITestContext testContext) throws MalformedURLException { + + OpenApi3 apiModel = (OpenApi3) testContext.getSuite().getAttribute(API_MODEL.getName()); + + if (apiModel == null) { + URI apiDefinitionLocation = (URI) testContext.getSuite() + .getAttribute(SuiteAttribute.API_DEFINITION.getName()); + throw new AssertionError("Could not create API model from URI: " + apiDefinitionLocation); + } + + if (apiModel.isValid() && (!apiUrl.getType().equals(OPEN_API_MIME_TYPE))) { + throw new SkipException( + "The API Definition was found to be valid. However, the Media Type identified by the Link to the API Definition document was not " + + OPEN_API_MIME_TYPE); + } + + assertTrue(apiModel.isValid(), createValidationMsg(apiModel)); + + } + + private String createValidationMsg(OpenApi3 model) { + StringBuilder sb = new StringBuilder(); + sb.append("API definition is not valid. Found following validation items:"); + if (!model.isValid()) { + for (ValidationResults.ValidationItem item : model.getValidationItems()) { + sb.append(" @ ") + .append(item.getPositionInfo()) + .append(" - ") + .append(item.getSeverity()) + .append(": ") + .append(item.getMsg()); + + } + } + return sb.toString(); + } } \ No newline at end of file diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/conformance/Conformance.java b/src/main/java/org/opengis/cite/ogcapiedr10/conformance/Conformance.java index 197e0c6..2c9a274 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/conformance/Conformance.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/conformance/Conformance.java @@ -34,111 +34,107 @@ */ public class Conformance extends CommonFixture { - private List requirementClasses; - - @DataProvider(name = "conformanceUris") - public Object[][] conformanceUris( ITestContext testContext ) { - OpenApi3 apiModel = (OpenApi3) testContext.getSuite().getAttribute( API_MODEL.getName() ); - URI iut = (URI) testContext.getSuite().getAttribute( IUT.getName() ); - - //https://github.com/opengeospatial/ets-ogcapi-edr10/issues/110 - //check for trailing forward slash - String serverUrl = rootUri.toString(); - serverUrl = serverUrl.endsWith("/") ? serverUrl.substring(0, serverUrl.length() - 1) : serverUrl; - - TestPoint tp = new TestPoint(serverUrl, "/conformance" ,null); - - - List testPoints = new ArrayList(); - testPoints.add(tp); - Object[][] testPointsData = new Object[1][]; - int i = 0; - for ( TestPoint testPoint : testPoints ) { - testPointsData[i++] = new Object[] { testPoint }; - } - return testPointsData; - } - - @AfterClass - public void storeRequirementClassesInTestContext( ITestContext testContext ) { - testContext.getSuite().setAttribute( REQUIREMENTCLASSES.getName(), this.requirementClasses ); - } - - /** - *
    -     * Abstract Test 1: Validate that the resource paths advertised through the API conform with HTTP 1.1 and, where approprate, TLS.
    -     * 
    - */ - @Test(description = "Implements Abstract Test 1 and Requirement /req/core/http") - public void http() { - Response response = init().baseUri( rootUri.toString() ).when().request( GET, "/" ); - response.then().statusLine( containsString( "HTTP/1.1" ) ); - } - - /** - * Abstract Test 6: Validate that a Conformance Declaration can be retrieved from the expected location. - * Abstract Test 7: Validate that the Conformance Declaration response complies with the required structure and contents. - * - * @param testPoint - * the test point to test, never null - */ - @Test(description = "Implements Abstract Test 6 (/conf/core/conformance) and Abstract Test 7 (/conf/core/conformance-success)", groups = "conformance", dataProvider = "conformanceUris") - public void validateConformanceOperationAndResponse( TestPoint testPoint ) { - - String f = ""; - if(rootUri.toString().contains("f=json") || rootUri.toString().contains("f=application/json")) {} - else { - //f = "f=application/json&f=json"; - f = "f=json"; - } - - String testPointUri = new UriBuilder( testPoint ).buildUrl(); - - Response response = init().baseUri( testPointUri ).accept( JSON ).when().request( GET ,"?"+f); - validateConformanceOperationResponse( testPointUri, response ); - } - - /** - * private method to support Abstract Test 6 and Abstract Test 7 - * - */ - private void validateConformanceOperationResponse( String testPointUri, Response response ) { - response.then().statusCode( 200 ); - - JsonPath jsonPath = response.jsonPath(); - this.requirementClasses = parseAndValidateRequirementClasses( jsonPath ); - assertTrue( this.requirementClasses.contains( CORE ), - "Requirement class \"http://www.opengis.net/spec/ogcapi-edr-1/1.0/conf/core\" is not available from path " - + testPointUri ); - } - - /** - * @param jsonPath - * never null - * @return the parsed requirement classes, never null - * @throws AssertionError - * if the json does not follow the expected structure - */ - List parseAndValidateRequirementClasses( JsonPath jsonPath ) { - List conformsTo = jsonPath.getList( "conformsTo" ); - assertNotNull( conformsTo, "Missing member 'conformsTo'." ); - - List requirementClasses = new ArrayList<>(); - for ( Object conformTo : conformsTo ) { - - if ( conformTo instanceof String ) { - String conformanceClass = (String) conformTo; - RequirementClass requirementClass = RequirementClass.byConformanceClass( conformanceClass ); - if ( requirementClass != null ) - requirementClasses.add( requirementClass ); - } else - throw new AssertionError( "At least one element array 'conformsTo' is not a string value (" + conformTo - + ")" ); - } - return requirementClasses; - } - - - - + private List requirementClasses; + + @DataProvider(name = "conformanceUris") + public Object[][] conformanceUris(ITestContext testContext) { + OpenApi3 apiModel = (OpenApi3) testContext.getSuite().getAttribute(API_MODEL.getName()); + URI iut = (URI) testContext.getSuite().getAttribute(IUT.getName()); + + // https://github.com/opengeospatial/ets-ogcapi-edr10/issues/110 + // check for trailing forward slash + String serverUrl = rootUri.toString(); + serverUrl = serverUrl.endsWith("/") ? serverUrl.substring(0, serverUrl.length() - 1) : serverUrl; + + TestPoint tp = new TestPoint(serverUrl, "/conformance", null); + + List testPoints = new ArrayList(); + testPoints.add(tp); + Object[][] testPointsData = new Object[1][]; + int i = 0; + for (TestPoint testPoint : testPoints) { + testPointsData[i++] = new Object[] { testPoint }; + } + return testPointsData; + } + + @AfterClass + public void storeRequirementClassesInTestContext(ITestContext testContext) { + testContext.getSuite().setAttribute(REQUIREMENTCLASSES.getName(), this.requirementClasses); + } + + /** + *
    +	 * Abstract Test 1: Validate that the resource paths advertised through the API conform with HTTP 1.1 and, where approprate, TLS.
    +	 * 
    + */ + @Test(description = "Implements Abstract Test 1 and Requirement /req/core/http") + public void http() { + Response response = init().baseUri(rootUri.toString()).when().request(GET, "/"); + response.then().statusLine(containsString("HTTP/1.1")); + } + + /** + * Abstract Test 6: Validate that a Conformance Declaration can be retrieved from the + * expected location. Abstract Test 7: Validate that the Conformance Declaration + * response complies with the required structure and contents. + * @param testPoint the test point to test, never null + */ + @Test(description = "Implements Abstract Test 6 (/conf/core/conformance) and Abstract Test 7 (/conf/core/conformance-success)", + groups = "conformance", dataProvider = "conformanceUris") + public void validateConformanceOperationAndResponse(TestPoint testPoint) { + + String f = ""; + if (rootUri.toString().contains("f=json") || rootUri.toString().contains("f=application/json")) { + } + else { + // f = "f=application/json&f=json"; + f = "f=json"; + } + + String testPointUri = new UriBuilder(testPoint).buildUrl(); + + Response response = init().baseUri(testPointUri).accept(JSON).when().request(GET, "?" + f); + validateConformanceOperationResponse(testPointUri, response); + } + + /** + * private method to support Abstract Test 6 and Abstract Test 7 + * + */ + private void validateConformanceOperationResponse(String testPointUri, Response response) { + response.then().statusCode(200); + + JsonPath jsonPath = response.jsonPath(); + this.requirementClasses = parseAndValidateRequirementClasses(jsonPath); + assertTrue(this.requirementClasses.contains(CORE), + "Requirement class \"http://www.opengis.net/spec/ogcapi-edr-1/1.0/conf/core\" is not available from path " + + testPointUri); + } + + /** + * @param jsonPath never null + * @return the parsed requirement classes, never null + * @throws AssertionError if the json does not follow the expected structure + */ + List parseAndValidateRequirementClasses(JsonPath jsonPath) { + List conformsTo = jsonPath.getList("conformsTo"); + assertNotNull(conformsTo, "Missing member 'conformsTo'."); + + List requirementClasses = new ArrayList<>(); + for (Object conformTo : conformsTo) { + + if (conformTo instanceof String) { + String conformanceClass = (String) conformTo; + RequirementClass requirementClass = RequirementClass.byConformanceClass(conformanceClass); + if (requirementClass != null) + requirementClasses.add(requirementClass); + } + else + throw new AssertionError( + "At least one element array 'conformsTo' is not a string value (" + conformTo + ")"); + } + return requirementClasses; + } + } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/conformance/RequirementClass.java b/src/main/java/org/opengis/cite/ogcapiedr10/conformance/RequirementClass.java index 9db2166..eb7a138 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/conformance/RequirementClass.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/conformance/RequirementClass.java @@ -9,72 +9,71 @@ */ public enum RequirementClass { - CORE( "http://www.opengis.net/spec/ogcapi-edr-1/1.0/conf/core" ), - GEOJSON("http://www.opengis.net/spec/ogcapi-edr-1/1.0/conf/geojson"), - EDRGEOJSON("http://www.opengis.net/spec/ogcapi-edr-1/1.0/req/edr-geojson"); + CORE("http://www.opengis.net/spec/ogcapi-edr-1/1.0/conf/core"), + GEOJSON("http://www.opengis.net/spec/ogcapi-edr-1/1.0/conf/geojson"), + EDRGEOJSON("http://www.opengis.net/spec/ogcapi-edr-1/1.0/req/edr-geojson"); + private final String conformanceClass; - private final String conformanceClass; + private final String mediaTypeFeaturesAndCollections; - private final String mediaTypeFeaturesAndCollections; + private final String mediaTypeOtherResources; - private final String mediaTypeOtherResources; + RequirementClass(String conformanceClass) { + this(conformanceClass, null, null); + } - RequirementClass( String conformanceClass ) { - this( conformanceClass, null, null ); - } + RequirementClass(String conformanceClass, String mediaTypeFeaturesAndCollections, String mediaTypeOtherResources) { + this.conformanceClass = conformanceClass; + this.mediaTypeFeaturesAndCollections = mediaTypeFeaturesAndCollections; + this.mediaTypeOtherResources = mediaTypeOtherResources; + } - RequirementClass( String conformanceClass, String mediaTypeFeaturesAndCollections, String mediaTypeOtherResources ) { - this.conformanceClass = conformanceClass; - this.mediaTypeFeaturesAndCollections = mediaTypeFeaturesAndCollections; - this.mediaTypeOtherResources = mediaTypeOtherResources; - } + /** + * @return true if the RequirementClass has a media type for features and + * collections, true otherwise + */ + public boolean hasMediaTypeForFeaturesAndCollections() { + return mediaTypeFeaturesAndCollections != null; + } - /** - * @return true if the RequirementClass has a media type for features and collections, - * true otherwise - */ - public boolean hasMediaTypeForFeaturesAndCollections() { - return mediaTypeFeaturesAndCollections != null; - } + /** + * @return media type for features and collections, null if not available + */ + public String getMediaTypeFeaturesAndCollections() { + return mediaTypeFeaturesAndCollections; + } - /** - * @return media type for features and collections, null if not available - */ - public String getMediaTypeFeaturesAndCollections() { - return mediaTypeFeaturesAndCollections; - } + /** + * @return true if the RequirementClass has a media type for other + * resources, true otherwise + */ + public boolean hasMediaTypeForOtherResources() { + return mediaTypeOtherResources != null; + } - /** - * @return true if the RequirementClass has a media type for other resources, - * true otherwise - */ - public boolean hasMediaTypeForOtherResources() { - return mediaTypeOtherResources != null; - } + /** + * @return media type of other resources, null if not available + */ + public String getMediaTypeOtherResources() { + return mediaTypeOtherResources; + } - /** - * @return media type of other resources, null if not available - */ - public String getMediaTypeOtherResources() { - return mediaTypeOtherResources; - } + public String getConformanceClass() { + return conformanceClass; + } - public String getConformanceClass() { - return conformanceClass; - } - - /** - * @param conformanceClass - * the conformance class of the RequirementClass to return. - * @return the RequirementClass with the passed conformance class, null if RequirementClass exists - */ - public static RequirementClass byConformanceClass( String conformanceClass ) { - for ( RequirementClass requirementClass : values() ) { - if ( requirementClass.conformanceClass.equals( conformanceClass ) ) - return requirementClass; - } - return null; - } + /** + * @param conformanceClass the conformance class of the RequirementClass to return. + * @return the RequirementClass with the passed conformance class, null + * if RequirementClass exists + */ + public static RequirementClass byConformanceClass(String conformanceClass) { + for (RequirementClass requirementClass : values()) { + if (requirementClass.conformanceClass.equals(conformanceClass)) + return requirementClass; + } + return null; + } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/corecollections/Collections.java b/src/main/java/org/opengis/cite/ogcapiedr10/corecollections/Collections.java index c62b4ac..0919b58 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/corecollections/Collections.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/corecollections/Collections.java @@ -34,117 +34,123 @@ * */ public class Collections extends CommonDataFixture { - private final Map testPointAndResponses = new HashMap<>(); - - private Object[][] testPointsData; - - @DataProvider(name = "collectionsUris") - public Object[][] collectionsUris(ITestContext testContext) { - if (this.testPointsData == null) { - URI iut = (URI) testContext.getSuite().getAttribute(IUT.getName()); - List testPoints = retrieveTestPointsForCollectionsMetadata(this.getModel(), iut); - this.testPointsData = new Object[testPoints.size()][]; - int i = 0; - for (TestPoint testPoint : testPoints) { - this.testPointsData[i++] = new Object[] { testPoint }; - System.out.println("CHKDA1 "+testPoint.getServerUrl()+ " | "+testPoint.getPath()); - } - } - return testPointsData; - } - - /** - *
    -     * Abstract Test 82: Validate that information about the Collections can be retrieved from the expected location.
    -     * 
    - * - * @param testPoint the test point to test, never null - */ - @Test(description = "Implements Abstract Test 82, meets Requirement /req/collections/rc-md-op", dataProvider = "collectionsUris", dependsOnGroups = "conformance") - public void validateCollectionsMetadataOperation(TestPoint testPoint) { - - System.out.println("CHKDA2 "+testPoint.getServerUrl()+ " | "+testPoint.getPath()); - - String testPointUri = new UriBuilder(testPoint).buildUrl(); - Response response = init().baseUri(testPointUri).accept(JSON).when().request(GET); - response.then().statusCode(200); - this.testPointAndResponses.put(testPoint, response); - } - - /** - *
    -     * Abstract Test 15: Validate that each Collection metadata entry in the Collections Metadata document includes all required links.
    -     * 
    - * - * @param testPoint - * the test point to test, never null - */ - @Test(description = "Implements Abstract Test 15, meets Requirement /req/edr/rc-md-query-links", dataProvider = "collectionsUris", dependsOnMethods = "validateCollectionsMetadataOperation") - public void validateCollectionMetadata_Links(TestPoint testPoint) { - Response response = testPointAndResponses.get(testPoint); - if (response == null) - throw new SkipException("Could not find a response for test point " + testPoint); - - JsonPath jsonPath = response.jsonPath(); - List> collections = jsonPath.getList("collections"); - - for (Map collection : collections) { - Map map = (Map) collection; - Object links = map.get("links"); - - List> collectionLinks = (List>) links; - Boolean relationIsDataOrCollection = false; - Boolean isValidCollection = false; - - for (Map link : collectionLinks) { - Object rel = link.get("rel"); - if (rel.equals("data") || rel.equals("collection")) { - relationIsDataOrCollection = true; - if (linkIncludesRelAndType(link)) { - isValidCollection = true; - break; - } - } - } - assertTrue(relationIsDataOrCollection, - "Collection must include links for data or collection encodings. Missing links for collection " + map.get("id")); - assertTrue(isValidCollection, - "Links for data or collection encodings must include a rel and type parameter. Missing for collection " + map.get("id")); - } - } - - /** - *
    -     * Abstract Test 16: Validate that the required links are included in the Collections Metadata document.
    -     * 
    - * - * @param testPoint the test point to test, never null - */ - @Test(description = "Implements Abstract Test 16, meets Requirement /req/core/rc-collection-info-links", dataProvider = "collectionsUris", dependsOnMethods = "validateCollectionsMetadataOperation") - public void validateCollectionsMetadata_Links(TestPoint testPoint) { - Response response = testPointAndResponses.get(testPoint); - if (response == null) - throw new SkipException("Could not find a response for test point " + testPoint); - - JsonPath jsonPath = response.jsonPath(); - List> links = jsonPath.getList("links"); - - Map linkToSelf = findLinkByRel(links, "self"); - assertNotNull(linkToSelf, "Collections Metadata document must include a link for itself"); - assertTrue(linkIncludesRelAndType(linkToSelf), "Link to itself must include a rel and type parameter"); - - List mediaTypesToSupport = createListOfMediaTypesToSupportForOtherResources(linkToSelf); - List> alternateLinks = findLinksWithSupportedMediaTypeByRel(links, mediaTypesToSupport, "alternate"); - List typesWithoutLink = findUnsupportedTypes(alternateLinks, mediaTypesToSupport); - - assertTrue(typesWithoutLink.isEmpty(), - "Collections Metadata document must include links for alternate encodings. Missing links for types " + typesWithoutLink); - - Set rels = new HashSet<>(); - rels.add("self"); - rels.add("alternate"); - List linksWithoutRelOrType = findLinksWithoutRelOrType(alternateLinks, rels); - assertTrue(linksWithoutRelOrType.isEmpty(), - "Links for alternate encodings must include a rel and type parameter. Missing for links " + linksWithoutRelOrType); - } + + private final Map testPointAndResponses = new HashMap<>(); + + private Object[][] testPointsData; + + @DataProvider(name = "collectionsUris") + public Object[][] collectionsUris(ITestContext testContext) { + if (this.testPointsData == null) { + URI iut = (URI) testContext.getSuite().getAttribute(IUT.getName()); + List testPoints = retrieveTestPointsForCollectionsMetadata(this.getModel(), iut); + this.testPointsData = new Object[testPoints.size()][]; + int i = 0; + for (TestPoint testPoint : testPoints) { + this.testPointsData[i++] = new Object[] { testPoint }; + System.out.println("CHKDA1 " + testPoint.getServerUrl() + " | " + testPoint.getPath()); + } + } + return testPointsData; + } + + /** + *
    +	 * Abstract Test 82: Validate that information about the Collections can be retrieved from the expected location.
    +	 * 
    + * @param testPoint the test point to test, never null + */ + @Test(description = "Implements Abstract Test 82, meets Requirement /req/collections/rc-md-op", + dataProvider = "collectionsUris", dependsOnGroups = "conformance") + public void validateCollectionsMetadataOperation(TestPoint testPoint) { + + System.out.println("CHKDA2 " + testPoint.getServerUrl() + " | " + testPoint.getPath()); + + String testPointUri = new UriBuilder(testPoint).buildUrl(); + Response response = init().baseUri(testPointUri).accept(JSON).when().request(GET); + response.then().statusCode(200); + this.testPointAndResponses.put(testPoint, response); + } + + /** + *
    +	 * Abstract Test 15: Validate that each Collection metadata entry in the Collections Metadata document includes all required links.
    +	 * 
    + * @param testPoint the test point to test, never null + */ + @Test(description = "Implements Abstract Test 15, meets Requirement /req/edr/rc-md-query-links", + dataProvider = "collectionsUris", dependsOnMethods = "validateCollectionsMetadataOperation") + public void validateCollectionMetadata_Links(TestPoint testPoint) { + Response response = testPointAndResponses.get(testPoint); + if (response == null) + throw new SkipException("Could not find a response for test point " + testPoint); + + JsonPath jsonPath = response.jsonPath(); + List> collections = jsonPath.getList("collections"); + + for (Map collection : collections) { + Map map = (Map) collection; + Object links = map.get("links"); + + List> collectionLinks = (List>) links; + Boolean relationIsDataOrCollection = false; + Boolean isValidCollection = false; + + for (Map link : collectionLinks) { + Object rel = link.get("rel"); + if (rel.equals("data") || rel.equals("collection")) { + relationIsDataOrCollection = true; + if (linkIncludesRelAndType(link)) { + isValidCollection = true; + break; + } + } + } + assertTrue(relationIsDataOrCollection, + "Collection must include links for data or collection encodings. Missing links for collection " + + map.get("id")); + assertTrue(isValidCollection, + "Links for data or collection encodings must include a rel and type parameter. Missing for collection " + + map.get("id")); + } + } + + /** + *
    +	 * Abstract Test 16: Validate that the required links are included in the Collections Metadata document.
    +	 * 
    + * @param testPoint the test point to test, never null + */ + @Test(description = "Implements Abstract Test 16, meets Requirement /req/core/rc-collection-info-links", + dataProvider = "collectionsUris", dependsOnMethods = "validateCollectionsMetadataOperation") + public void validateCollectionsMetadata_Links(TestPoint testPoint) { + Response response = testPointAndResponses.get(testPoint); + if (response == null) + throw new SkipException("Could not find a response for test point " + testPoint); + + JsonPath jsonPath = response.jsonPath(); + List> links = jsonPath.getList("links"); + + Map linkToSelf = findLinkByRel(links, "self"); + assertNotNull(linkToSelf, "Collections Metadata document must include a link for itself"); + assertTrue(linkIncludesRelAndType(linkToSelf), "Link to itself must include a rel and type parameter"); + + List mediaTypesToSupport = createListOfMediaTypesToSupportForOtherResources(linkToSelf); + List> alternateLinks = findLinksWithSupportedMediaTypeByRel(links, mediaTypesToSupport, + "alternate"); + List typesWithoutLink = findUnsupportedTypes(alternateLinks, mediaTypesToSupport); + + assertTrue(typesWithoutLink.isEmpty(), + "Collections Metadata document must include links for alternate encodings. Missing links for types " + + typesWithoutLink); + + Set rels = new HashSet<>(); + rels.add("self"); + rels.add("alternate"); + List linksWithoutRelOrType = findLinksWithoutRelOrType(alternateLinks, rels); + assertTrue(linksWithoutRelOrType.isEmpty(), + "Links for alternate encodings must include a rel and type parameter. Missing for links " + + linksWithoutRelOrType); + } + } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/corecollections/CollectionsResponse.java b/src/main/java/org/opengis/cite/ogcapiedr10/corecollections/CollectionsResponse.java index 862ddbc..2416fd0 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/corecollections/CollectionsResponse.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/corecollections/CollectionsResponse.java @@ -30,429 +30,440 @@ public class CollectionsResponse extends CommonFixture { protected URI iut; - - @DataProvider(name = "collectionIDs") - public Iterator collectionIDs( ITestContext testContext ) { - - - this.iut = (URI) testContext.getSuite().getAttribute( IUT.getName() ); - - - Set collectionTypes = extractCollectionIDs(this.iut); - List collectionsData = new ArrayList<>(); - - collectionsData.add(new Object[] {collectionTypes}); - - return collectionsData.iterator(); - - } - - private Set extractCollectionIDs(URI rootUri) - { - JsonPath response; - Response request = getCollectionResponse(null); - - request.then().statusCode( 200 ); - response = request.jsonPath(); - List collections = response.getList( "collections" ); - Set collectionTypes = new HashSet<>(); - for ( Object collection : collections ) { - Map collectionMap = (Map) collection; - Object collectionType = collectionMap.get( "id" ); - collectionTypes.add( (String) collectionType ); - } - - return collectionTypes; - - } - - - /* - * Abstract Test 9 /conf/collections/rc-md-op - * Abstract Test 10 /conf/rc-md-success - * Validate that information about the Collections can be retrieved from the expected location. - * Validate that the Collections content complies with the required structure and contents. - */ - - @Test(description = "Implements Abstract Test 9 (/conf/collections/rc-md-op) and Abstract Test 10 (/conf/rc-md-success)", dataProvider = "collectionIDs", alwaysRun = true) + + @DataProvider(name = "collectionIDs") + public Iterator collectionIDs(ITestContext testContext) { + + this.iut = (URI) testContext.getSuite().getAttribute(IUT.getName()); + + Set collectionTypes = extractCollectionIDs(this.iut); + List collectionsData = new ArrayList<>(); + + collectionsData.add(new Object[] { collectionTypes }); + + return collectionsData.iterator(); + + } + + private Set extractCollectionIDs(URI rootUri) { + JsonPath response; + Response request = getCollectionResponse(null); + + request.then().statusCode(200); + response = request.jsonPath(); + List collections = response.getList("collections"); + Set collectionTypes = new HashSet<>(); + for (Object collection : collections) { + Map collectionMap = (Map) collection; + Object collectionType = collectionMap.get("id"); + collectionTypes.add((String) collectionType); + } + + return collectionTypes; + + } + + /* + * Abstract Test 9 /conf/collections/rc-md-op Abstract Test 10 /conf/rc-md-success + * Validate that information about the Collections can be retrieved from the expected + * location. Validate that the Collections content complies with the required + * structure and contents. + */ + + @Test(description = "Implements Abstract Test 9 (/conf/collections/rc-md-op) and Abstract Test 10 (/conf/rc-md-success)", + dataProvider = "collectionIDs", alwaysRun = true) public void validateRetrievalOfCollections(Object collectionIdentifiers) { Set collectionTypes = (Set) collectionIdentifiers; - - //The dataProvider validated the response code was 200 - //Therefore if the size of the collection is greater than zero, we know the iut passed the test - - assertTrue(collectionTypes.size()>0, "Was not able to validate that information about the Collections was retrieved correctly"); - - } - - /* - * Abstract Test 11 /conf/collections/src-md-op - * Abstract Test 12 /conf/collections/src-md-success - * Validate that the Collection content can be retrieved from the expected location. - * Validate that the Collections content complies with the required structure and contents. - */ - - @Test(description = "Implements Abstract Test 11 (/conf/collections/src-md-op) and Abstract Test 12 (/conf/collections/src-md-success)", dataProvider = "collectionIDs", alwaysRun = true) + + // The dataProvider validated the response code was 200 + // Therefore if the size of the collection is greater than zero, we know the iut + // passed the test + + assertTrue(collectionTypes.size() > 0, + "Was not able to validate that information about the Collections was retrieved correctly"); + + } + + /* + * Abstract Test 11 /conf/collections/src-md-op Abstract Test 12 + * /conf/collections/src-md-success Validate that the Collection content can be + * retrieved from the expected location. Validate that the Collections content + * complies with the required structure and contents. + */ + + @Test(description = "Implements Abstract Test 11 (/conf/collections/src-md-op) and Abstract Test 12 (/conf/collections/src-md-success)", + dataProvider = "collectionIDs", alwaysRun = true) public void validateRetrievalOfEnvironmentalDataCollections(Object collectionIdentifiers) { Set collectionTypes = (Set) collectionIdentifiers; - + boolean identicalID = false; - int i=0; - for(String collection:collectionTypes) - { - - if(i==0) //We choose to test one + int i = 0; + for (String collection : collectionTypes) { + + if (i == 0) // We choose to test one { System.out.println(collection); - JsonPath response; - Response request = getCollectionResponse(collection); - - request.then().statusCode( 200 ); - response = request.jsonPath(); - - if(response.getString("id").equals(collection)) identicalID = true; - - + JsonPath response; + Response request = getCollectionResponse(collection); + + request.then().statusCode(200); + response = request.jsonPath(); + + if (response.getString("id").equals(collection)) + identicalID = true; + } i++; } - - assertTrue(identicalID, "The id of the collection returned by the response did not match the collectionID in the URL"); - - } - - - - - /** - *
    -    	 * Abstract Test 8: Validate that all spatial geometries provided through the API are in the CRS84 spatial reference system unless otherwise requested by the client.
    -    	 * 
    -    	 * Requirement A.46 G, which is in the Collections Requirements Class, states that "Every Collection within a collections array MUST have a 'crs' parameter which must comply with the requirement '/req/edr/rc-crs'."
    -    	 * Therefore we can expect that there be a declaration of support for CRS84
    -    	 * 
    - * - */ - - @Test(description = "Implements Abstract Test 8 (/conf/core/crs84)") - public void collectionsCRS84() { - - boolean compliesWithCRS84Requirement = true; - StringBuffer resultMessage = new StringBuffer(); - - Response response = getCollectionResponse(null); - JsonPath jsonPath = response.jsonPath(); - - List collectionsList = jsonPath.getList("collections"); - - - for (int t = 0; t < collectionsList.size(); t++) { - boolean supportsCRS84 = false; - - HashMap collectionMap = (HashMap) collectionsList.get(t); - - String crsText = null; - - if(collectionMap.containsKey("crs")) { - crsText = collectionMap.get("crs").toString(); - } - else { - - if(collectionMap.containsKey("extent")) { - - HashMap extentMap = (HashMap) collectionMap.get("extent"); - - HashMap spatialMap = (HashMap) extentMap.get("spatial"); - - crsText = spatialMap.get("crs").toString(); - - - } - - } - - - if (crsText.contains("CRS:84") || crsText.contains("CRS84") || crsText.contains("EPSG:4326") || crsText.contains("WGS84") || crsText.contains("www.opengis.net/def/crs/OGC/1.3/CRS84")){ - compliesWithCRS84Requirement = true; - } - else{ - compliesWithCRS84Requirement = false; - resultMessage.append("Collection " + collectionMap.get("id").toString() + " fails. "); - } - - } - - - - org.testng.Assert.assertTrue(compliesWithCRS84Requirement, - "Fails Abstract Test 8 because " + resultMessage.toString()); - - } - - /* - * We keep code here for future use - * - */ - - private void crsChecking_NotUsed(ArrayList crsList) - { - boolean compliesWithCRS84Requirement = true; - StringBuffer resultMessage = new StringBuffer(); - boolean supportsCRS84 = false; - HashMap collectionMap = null; //(HashMap) collectionsList.get(t); - - //ArrayList crsList = (ArrayList) collectionMap.get("crs"); - - HashMap crsMap = (HashMap) crsList.get(0); - - CoordinateReferenceSystem source = null; - - try { - - source = CRS.fromWKT(crsMap.get("wkt").toString()); - } catch (Exception e) { - - e.printStackTrace(); + + assertTrue(identicalID, + "The id of the collection returned by the response did not match the collectionID in the URL"); + + } + + /** + *
    +	 * Abstract Test 8: Validate that all spatial geometries provided through the API are in the CRS84 spatial reference system unless otherwise requested by the client.
    +	 *
    +	 * Requirement A.46 G, which is in the Collections Requirements Class, states that "Every Collection within a collections array MUST have a 'crs' parameter which must comply with the requirement '/req/edr/rc-crs'."
    +	 * Therefore we can expect that there be a declaration of support for CRS84
    +	 * 
    + * + */ + + @Test(description = "Implements Abstract Test 8 (/conf/core/crs84)") + public void collectionsCRS84() { + + boolean compliesWithCRS84Requirement = true; + StringBuffer resultMessage = new StringBuffer(); + + Response response = getCollectionResponse(null); + JsonPath jsonPath = response.jsonPath(); + + List collectionsList = jsonPath.getList("collections"); + + for (int t = 0; t < collectionsList.size(); t++) { + boolean supportsCRS84 = false; + + HashMap collectionMap = (HashMap) collectionsList.get(t); + + String crsText = null; + + if (collectionMap.containsKey("crs")) { + crsText = collectionMap.get("crs").toString(); } + else { - GeographicCRS crs = (GeographicCRS) source; + if (collectionMap.containsKey("extent")) { - if (crs.getDatum().getEllipsoid().getName().toString().equals("WGS 84") - || crs.getDatum().getEllipsoid().getName().toString().equals("WGS_1984") - || crs.getDatum().getEllipsoid().getName().toString().equals("WGS84")) { + HashMap extentMap = (HashMap) collectionMap.get("extent"); - if (source.getCoordinateSystem().getAxis(0).toString().toLowerCase().contains("longitude") - && source.getCoordinateSystem().getAxis(1).toString().toLowerCase().contains("latitude")) { + HashMap spatialMap = (HashMap) extentMap.get("spatial"); - supportsCRS84 = true; + crsText = spatialMap.get("crs").toString(); } + } - if (supportsCRS84 == false) { + + if (crsText.contains("CRS:84") || crsText.contains("CRS84") || crsText.contains("EPSG:4326") + || crsText.contains("WGS84") || crsText.contains("www.opengis.net/def/crs/OGC/1.3/CRS84")) { + compliesWithCRS84Requirement = true; + } + else { compliesWithCRS84Requirement = false; resultMessage.append("Collection " + collectionMap.get("id").toString() + " fails. "); } - } - - /** - *
    -    	 * Abstract Test 17: Validate that each parameter in a collection is correctly defined.
    -    	 * 
    - * - */ - @Test(description = "Implements Abstract Test 17 (/conf/edr/rc-parameters)") - public void collectionsParameters() { - boolean compliesWithCollectionParametersRequirement = true; - StringBuffer resultMessage = new StringBuffer(); - - Response response = getCollectionResponse(null); - JsonPath jsonPath = response.jsonPath(); - - - List collectionsList = jsonPath.getList("collections"); - - boolean atLeastOneCollectionIsEDR = false; - - for (int t = 0; t < collectionsList.size(); t++) { - - HashMap collectionMap = (HashMap) collectionsList.get(t); - - if(collectionMap.containsKey("itemType")) continue; //skip if this is an OGC API Features or OGC API Records collection - - if(!collectionMap.containsKey("parameter_names")) continue; //skip if this is not an EDR collection - else atLeastOneCollectionIsEDR = true; - - String parameterNameText = collectionMap.get("parameter_names").toString(); - HashMap parameterNameMap = (HashMap) collectionMap.get("parameter_names"); - - - ArrayList parameterNameList = new ArrayList(); - - //Implements Test Method 2: Verify that each parameter property has a unique name (in the collection). - for (Object k: parameterNameMap.keySet()) - { - if(parameterNameList.contains(k.toString())) { - org.testng.Assert.fail( "Fails Abstract Test 17 because the parameter " + k.toString()+" is duplicated in collection "+collectionMap.get("id")); - } - else { - parameterNameList.add(k.toString()); - } - } - - //Implements Test Method 1: Verify that all parameters listed in a collection have the required properties. - //Implements Test Method 3: Verify that each parameter property has a type property. - //Implements Test Method 4: Verify that each parameter property has a observedProperty property. - for(int i=0; i < parameterNameList.size(); i++) - { - String parameterName = parameterNameList.get(i); - - HashMap parameterValueMap = (HashMap) parameterNameMap.get(parameterName); - boolean hasType = parameterValueMap.containsKey("type"); - boolean hasObservedProperty = parameterValueMap.containsKey("observedProperty"); - - org.testng.Assert.assertTrue(hasType, "Fails Abstract Test 17 because parameter " + parameterName+" in collection "+collectionMap.get("id") + " is missing a 'type' property"); - org.testng.Assert.assertTrue(hasObservedProperty, "Fails Abstract Test 17 because parameter " + parameterName+" in collection "+collectionMap.get("id") + " is missing a 'observedProperty' property"); - } - - - org.testng.Assert.assertTrue(compliesWithCollectionParametersRequirement, "Fails Abstract Test 17 because " + resultMessage.toString()); - } - } - - /** - *
    -    	 * Abstract Test 13: Validate the extent property if it is present
    -    	 * Abstract Test 14: Validate that each collection provided by the server is described in the Collections Metadata.
    -    	 * Abstract Test 15: Validate that each Collection metadata entry in the Collections Metadata document includes all required links (data or collection).
    -    	 * Abstract Test 16: Validate that the required links are included in the Collections Metadata document (self and alternate).
    -    	 * 
    - * - */ - @Test(description = "Implements Abstract Test 13 (/conf/core/rc-extent), Abstract Test 14 (/conf/edr/rc-collection-info), Abstract Test 15 (/conf/edr/rc-md-query-links), Abstract Test 16 (/conf/core/rc-collection-info-links)") - public void verifyCollectionsMetadata() { - - StringBuffer resultMessageForSelfAndAlternateLinks = new StringBuffer(); - StringBuffer resultMessageForDataOrCollectionLinks = new StringBuffer(); - StringBuffer resultMessageForCollectionId = new StringBuffer(); - StringBuffer resultMessageForCollectionExtent = new StringBuffer(); - - Response response = getCollectionResponse(null); - JsonPath jsonPath = response.jsonPath(); - - List collectionsList = jsonPath.getList("collections"); - - - - for (int t = 0; t < collectionsList.size(); t++) { - boolean collectionHasSelfAndAlternateLinks = false; - boolean collectionHasDataOrCollectionLinks = false; - boolean collectionHasID = false; - boolean collectionHasValidExtent = false; - - HashMap collectionMap = (HashMap) collectionsList.get(t); - - if(collectionMap.containsKey("itemType")) continue; - - //Test Method 2 of Abstract Test 14: Verify that each collection entry includes an identifier. - if(collectionMap.containsKey("id")==false) resultMessageForCollectionId.append(collectionMap.get("id").toString()+" , "); - - //Test Method 1 of Abstract Test 14: Verify that all collections listed in the collections array of the Collections Metadata exist. - - JsonPath jsonPathCol = getCollectionMetadata(collectionMap.get("id").toString()); - - //Abstract Test 13 - if(checkExtentInCollection(jsonPathCol)==false) resultMessageForCollectionExtent.append(collectionMap.get("id").toString()+" , "); - - - //Abstract Test 15 - List linksList1 = jsonPathCol.getList("links"); - linksList1.addAll((ArrayList) collectionMap.get("links")); //in some cases, the links shown for the collection at /collections are a subset of those shown in /collections/collectionid - - collectionHasDataOrCollectionLinks = checkDataOrCollectionLinksArePresentInCollectionMetadata(linksList1); - - - - - //Abstract Test 16 - collectionHasSelfAndAlternateLinks = checkSelfAndAlternateLinksArePresentInCollectionMetadata(linksList1); - - - if(collectionHasSelfAndAlternateLinks==false) resultMessageForSelfAndAlternateLinks.append(collectionMap.get("id").toString()+" , "); - if(collectionHasDataOrCollectionLinks==false) resultMessageForDataOrCollectionLinks.append(collectionMap.get("id").toString()+" , "); - - } - - StringBuffer resultMessage = new StringBuffer(); - - if(!resultMessageForCollectionExtent.toString().isEmpty()) - resultMessage.append("Fails Abstract Test 13 because these collections have invalid or missing extent elements: " + resultMessageForCollectionExtent.toString()+". "); - - if(!resultMessageForCollectionId.toString().isEmpty()) - resultMessage.append("Fails Abstract Test 14 because these collections are missing 'id' properties: " + resultMessageForCollectionId.toString()+". "); - - if(!resultMessageForDataOrCollectionLinks.toString().isEmpty()) - resultMessage.append("Fails Abstract Test 15 because these collections are missing 'data' or 'collection' rel links: " + resultMessageForDataOrCollectionLinks.toString()+". "); - - if(!resultMessageForSelfAndAlternateLinks.toString().isEmpty()) - resultMessage.append("Fails Abstract Test 16 because these collections are missing 'self' or 'alternate' rel links: " + resultMessageForSelfAndAlternateLinks.toString()+". "); - - - org.testng.Assert.assertTrue(resultMessage.toString().isEmpty(), resultMessage.toString()); - } - /* - * check that the collection extent contains bbox - */ - private boolean checkExtentInCollection(JsonPath jsonPathCol) - { - - HashMap extentMap = (HashMap) jsonPathCol.get("extent"); - - return extentMap.containsKey("spatial"); - - // Deactivated because of changes between v1.0.0 and v1.0.1 - //HashMap spatialMap = (HashMap) extentMap.get("spatial"); - //return spatialMap.containsKey("bbox"); - - } - /* - * check that the collection exists and get links from it - */ - private JsonPath getCollectionMetadata(String collectionId) - { - Response response = getCollectionResponse(collectionId); - JsonPath jsonPath = response.jsonPath(); - - return jsonPath; - } - private boolean checkSelfAndAlternateLinksArePresentInCollectionMetadata(List linksList) - { - - - - - boolean hasSelfRel = false; - boolean hasAlternateRel = false; - - for(int w = 0; w < linksList.size(); w++) - { - HashMap linksMap = (HashMap) linksList.get(w); - - if (linksMap.get("rel").toString().equals("self")) hasSelfRel = true; - if (linksMap.get("rel").toString().equals("alternate")) hasAlternateRel = true; - } - - if (hasSelfRel || hasAlternateRel) return true; - return false; - - } - private boolean checkDataOrCollectionLinksArePresentInCollectionMetadata(List linksList) - { - - //check for data link deactivated because of https://github.com/opengeospatial/ogcapi-environmental-data-retrieval/issues/371 - - boolean hasDataRel = false; - boolean hasCollectionRel = false; - - - - for(int w = 0; w < linksList.size(); w++) - { - HashMap linksMap = (HashMap) linksList.get(w); - - - if (linksMap.get("rel").toString().equals("data")) hasDataRel = true; - if (linksMap.get("rel").toString().equals("collection")) hasCollectionRel = true; - } - - - - - if (hasDataRel || hasCollectionRel) return true; - return false; - - } - - //http://localhost/edr/collections/metar_demo/position?coords=POINT(-1.054687%2052.498649)¶meter-name=Metar%20observation&datetime=2021-09-19T01:00Z/2021-09-19T02:00Z&crs=CRS84&f=GeoJSON + + } + + org.testng.Assert.assertTrue(compliesWithCRS84Requirement, + "Fails Abstract Test 8 because " + resultMessage.toString()); + + } + + /* + * We keep code here for future use + * + */ + + private void crsChecking_NotUsed(ArrayList crsList) { + boolean compliesWithCRS84Requirement = true; + StringBuffer resultMessage = new StringBuffer(); + boolean supportsCRS84 = false; + HashMap collectionMap = null; // (HashMap) collectionsList.get(t); + + // ArrayList crsList = (ArrayList) collectionMap.get("crs"); + + HashMap crsMap = (HashMap) crsList.get(0); + + CoordinateReferenceSystem source = null; + + try { + + source = CRS.fromWKT(crsMap.get("wkt").toString()); + } + catch (Exception e) { + + e.printStackTrace(); + } + + GeographicCRS crs = (GeographicCRS) source; + + if (crs.getDatum().getEllipsoid().getName().toString().equals("WGS 84") + || crs.getDatum().getEllipsoid().getName().toString().equals("WGS_1984") + || crs.getDatum().getEllipsoid().getName().toString().equals("WGS84")) { + + if (source.getCoordinateSystem().getAxis(0).toString().toLowerCase().contains("longitude") + && source.getCoordinateSystem().getAxis(1).toString().toLowerCase().contains("latitude")) { + + supportsCRS84 = true; + + } + } + if (supportsCRS84 == false) { + compliesWithCRS84Requirement = false; + resultMessage.append("Collection " + collectionMap.get("id").toString() + " fails. "); + } + } + + /** + *
    +	 * Abstract Test 17: Validate that each parameter in a collection is correctly defined.
    +	 * 
    + * + */ + @Test(description = "Implements Abstract Test 17 (/conf/edr/rc-parameters)") + public void collectionsParameters() { + boolean compliesWithCollectionParametersRequirement = true; + StringBuffer resultMessage = new StringBuffer(); + + Response response = getCollectionResponse(null); + JsonPath jsonPath = response.jsonPath(); + + List collectionsList = jsonPath.getList("collections"); + + boolean atLeastOneCollectionIsEDR = false; + + for (int t = 0; t < collectionsList.size(); t++) { + + HashMap collectionMap = (HashMap) collectionsList.get(t); + + if (collectionMap.containsKey("itemType")) + continue; // skip if this is an OGC API Features or OGC API Records + // collection + + if (!collectionMap.containsKey("parameter_names")) + continue; // skip if this is not an EDR collection + else + atLeastOneCollectionIsEDR = true; + + String parameterNameText = collectionMap.get("parameter_names").toString(); + HashMap parameterNameMap = (HashMap) collectionMap.get("parameter_names"); + + ArrayList parameterNameList = new ArrayList(); + + // Implements Test Method 2: Verify that each parameter property has a unique + // name (in the collection). + for (Object k : parameterNameMap.keySet()) { + if (parameterNameList.contains(k.toString())) { + org.testng.Assert.fail("Fails Abstract Test 17 because the parameter " + k.toString() + + " is duplicated in collection " + collectionMap.get("id")); + } + else { + parameterNameList.add(k.toString()); + } + } + + // Implements Test Method 1: Verify that all parameters listed in a collection + // have the required properties. + // Implements Test Method 3: Verify that each parameter property has a type + // property. + // Implements Test Method 4: Verify that each parameter property has a + // observedProperty property. + for (int i = 0; i < parameterNameList.size(); i++) { + String parameterName = parameterNameList.get(i); + + HashMap parameterValueMap = (HashMap) parameterNameMap.get(parameterName); + boolean hasType = parameterValueMap.containsKey("type"); + boolean hasObservedProperty = parameterValueMap.containsKey("observedProperty"); + + org.testng.Assert.assertTrue(hasType, "Fails Abstract Test 17 because parameter " + parameterName + + " in collection " + collectionMap.get("id") + " is missing a 'type' property"); + org.testng.Assert.assertTrue(hasObservedProperty, + "Fails Abstract Test 17 because parameter " + parameterName + " in collection " + + collectionMap.get("id") + " is missing a 'observedProperty' property"); + } + + org.testng.Assert.assertTrue(compliesWithCollectionParametersRequirement, + "Fails Abstract Test 17 because " + resultMessage.toString()); + } + } + + /** + *
    +	 * Abstract Test 13: Validate the extent property if it is present
    +	 * Abstract Test 14: Validate that each collection provided by the server is described in the Collections Metadata.
    +	 * Abstract Test 15: Validate that each Collection metadata entry in the Collections Metadata document includes all required links (data or collection).
    +	 * Abstract Test 16: Validate that the required links are included in the Collections Metadata document (self and alternate).
    +	 * 
    + * + */ + @Test(description = "Implements Abstract Test 13 (/conf/core/rc-extent), Abstract Test 14 (/conf/edr/rc-collection-info), Abstract Test 15 (/conf/edr/rc-md-query-links), Abstract Test 16 (/conf/core/rc-collection-info-links)") + public void verifyCollectionsMetadata() { + + StringBuffer resultMessageForSelfAndAlternateLinks = new StringBuffer(); + StringBuffer resultMessageForDataOrCollectionLinks = new StringBuffer(); + StringBuffer resultMessageForCollectionId = new StringBuffer(); + StringBuffer resultMessageForCollectionExtent = new StringBuffer(); + + Response response = getCollectionResponse(null); + JsonPath jsonPath = response.jsonPath(); + + List collectionsList = jsonPath.getList("collections"); + + for (int t = 0; t < collectionsList.size(); t++) { + boolean collectionHasSelfAndAlternateLinks = false; + boolean collectionHasDataOrCollectionLinks = false; + boolean collectionHasID = false; + boolean collectionHasValidExtent = false; + + HashMap collectionMap = (HashMap) collectionsList.get(t); + + if (collectionMap.containsKey("itemType")) + continue; + + // Test Method 2 of Abstract Test 14: Verify that each collection entry + // includes an identifier. + if (collectionMap.containsKey("id") == false) + resultMessageForCollectionId.append(collectionMap.get("id").toString() + " , "); + + // Test Method 1 of Abstract Test 14: Verify that all collections listed in + // the collections array of the Collections Metadata exist. + + JsonPath jsonPathCol = getCollectionMetadata(collectionMap.get("id").toString()); + + // Abstract Test 13 + if (checkExtentInCollection(jsonPathCol) == false) + resultMessageForCollectionExtent.append(collectionMap.get("id").toString() + " , "); + + // Abstract Test 15 + List linksList1 = jsonPathCol.getList("links"); + linksList1.addAll((ArrayList) collectionMap.get("links")); // in some cases, + // the links shown + // for the + // collection at + // /collections + // are a subset of + // those shown in + // /collections/collectionid + + collectionHasDataOrCollectionLinks = checkDataOrCollectionLinksArePresentInCollectionMetadata(linksList1); + + // Abstract Test 16 + collectionHasSelfAndAlternateLinks = checkSelfAndAlternateLinksArePresentInCollectionMetadata(linksList1); + + if (collectionHasSelfAndAlternateLinks == false) + resultMessageForSelfAndAlternateLinks.append(collectionMap.get("id").toString() + " , "); + if (collectionHasDataOrCollectionLinks == false) + resultMessageForDataOrCollectionLinks.append(collectionMap.get("id").toString() + " , "); + + } + + StringBuffer resultMessage = new StringBuffer(); + + if (!resultMessageForCollectionExtent.toString().isEmpty()) + resultMessage + .append("Fails Abstract Test 13 because these collections have invalid or missing extent elements: " + + resultMessageForCollectionExtent.toString() + ". "); + + if (!resultMessageForCollectionId.toString().isEmpty()) + resultMessage.append("Fails Abstract Test 14 because these collections are missing 'id' properties: " + + resultMessageForCollectionId.toString() + ". "); + + if (!resultMessageForDataOrCollectionLinks.toString().isEmpty()) + resultMessage.append( + "Fails Abstract Test 15 because these collections are missing 'data' or 'collection' rel links: " + + resultMessageForDataOrCollectionLinks.toString() + ". "); + + if (!resultMessageForSelfAndAlternateLinks.toString().isEmpty()) + resultMessage + .append("Fails Abstract Test 16 because these collections are missing 'self' or 'alternate' rel links: " + + resultMessageForSelfAndAlternateLinks.toString() + ". "); + + org.testng.Assert.assertTrue(resultMessage.toString().isEmpty(), resultMessage.toString()); + } + + /* + * check that the collection extent contains bbox + */ + private boolean checkExtentInCollection(JsonPath jsonPathCol) { + + HashMap extentMap = (HashMap) jsonPathCol.get("extent"); + + return extentMap.containsKey("spatial"); + + // Deactivated because of changes between v1.0.0 and v1.0.1 + // HashMap spatialMap = (HashMap) extentMap.get("spatial"); + // return spatialMap.containsKey("bbox"); + + } + + /* + * check that the collection exists and get links from it + */ + private JsonPath getCollectionMetadata(String collectionId) { + Response response = getCollectionResponse(collectionId); + JsonPath jsonPath = response.jsonPath(); + + return jsonPath; + } + + private boolean checkSelfAndAlternateLinksArePresentInCollectionMetadata(List linksList) { + + boolean hasSelfRel = false; + boolean hasAlternateRel = false; + + for (int w = 0; w < linksList.size(); w++) { + HashMap linksMap = (HashMap) linksList.get(w); + + if (linksMap.get("rel").toString().equals("self")) + hasSelfRel = true; + if (linksMap.get("rel").toString().equals("alternate")) + hasAlternateRel = true; + } + + if (hasSelfRel || hasAlternateRel) + return true; + return false; + + } + + private boolean checkDataOrCollectionLinksArePresentInCollectionMetadata(List linksList) { + + // check for data link deactivated because of + // https://github.com/opengeospatial/ogcapi-environmental-data-retrieval/issues/371 + + boolean hasDataRel = false; + boolean hasCollectionRel = false; + + for (int w = 0; w < linksList.size(); w++) { + HashMap linksMap = (HashMap) linksList.get(w); + + if (linksMap.get("rel").toString().equals("data")) + hasDataRel = true; + if (linksMap.get("rel").toString().equals("collection")) + hasCollectionRel = true; + } + + if (hasDataRel || hasCollectionRel) + return true; + return false; + + } + + // http://localhost/edr/collections/metar_demo/position?coords=POINT(-1.054687%2052.498649)¶meter-name=Metar%20observation&datetime=2021-09-19T01:00Z/2021-09-19T02:00Z&crs=CRS84&f=GeoJSON + } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/encodings/edrgeojson/EDRGeoJSONEncoding.java b/src/main/java/org/opengis/cite/ogcapiedr10/encodings/edrgeojson/EDRGeoJSONEncoding.java index 76d276b..6c4592f 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/encodings/edrgeojson/EDRGeoJSONEncoding.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/encodings/edrgeojson/EDRGeoJSONEncoding.java @@ -23,129 +23,114 @@ public class EDRGeoJSONEncoding extends CommonFixture { + private String schemaToApply = "/org/opengis/cite/ogcapiedr10/jsonschema/edrgeojson.json"; - private String schemaToApply = "/org/opengis/cite/ogcapiedr10/jsonschema/edrgeojson.json"; - protected URI iut; - - - - /** - *
    -     * Abstract Test 22: Verify support for the EDR GeoJSON Schema
    -     * Abstract Test 23: Verify the content of an EDR GeoJSON document given an input document and schema.
    -     * Note that the first positions resource that supports GeoJSON is tested.
    -     * 
    - */ - @Test(description = "Implements Abstract Test 22 (/conf/edr-geojson/definition), Abstract Test 23 (/conf/edr-geojson/content)") - public void validateResponseForEDRGeoJSON(ITestContext testContext) { - - List requirementClasses = (List) testContext.getSuite().getAttribute( REQUIREMENTCLASSES.getName()); - - if(!requirementClasses.contains(RequirementClass.EDRGEOJSON)) { - throw new SkipException(String.format("Requirements class %s not implemented.", RequirementClass.EDRGEOJSON.getConformanceClass())); - } - - StringBuffer sb = new StringBuffer(); - boolean atLeastOneCollectionTested = false; //we test the first locations resource we find - Response response = getCollectionResponse(null); - JsonPath jsonResponse = response.jsonPath(); - - - - ArrayList collectionsList = (ArrayList) jsonResponse.getList("collections"); - - - - - for(int i=0; (i< collectionsList.size()) && (atLeastOneCollectionTested==false); i++) - { - HashMap collectionItem = (HashMap) collectionsList.get(i); - - String collectionId = collectionItem.get("id").toString(); - - if(!collectionItem.containsKey("data_queries")) { - continue; //we loop until we find a collection that supports data_queries - } - - - HashMap dataQueries = (HashMap) collectionItem.get("data_queries"); - boolean supportsPositionQuery = dataQueries.containsKey("position"); - - if(supportsPositionQuery) { - HashMap positionQuery = (HashMap) dataQueries.get("position"); - HashMap link = (HashMap) positionQuery.get("link"); - HashMap variables = (HashMap) link.get("variables"); - - - - - - ArrayList outputFormatList = (ArrayList) variables.get("output_formats"); - String supportedFormat = null; - - for (int f = 0; f < outputFormatList.size(); f++) { - if (outputFormatList.get(f).equals("GeoJSON")) { - supportedFormat = outputFormatList.get(f); - } - } - - - - ArrayList crsList = (ArrayList) collectionItem.get("crs"); - - String supportedCRS = null; - for (int f = 0; f < crsList.size(); f++) { - if (crsList.get(f).equals("CRS84") || - crsList.get(f).equals("CRS:84") || - crsList.get(f).equals("WGS84") || - crsList.get(f).equals("EPSG:4326") || - crsList.get(f).contains("www.opengis.net/def/crs/OGC/1.3/CRS84")) { - supportedCRS = crsList.get(f); - } - } - - - - - double medianx = 0d; - double mediany = 0d; + protected URI iut; - HashMap extent = (HashMap) collectionItem.get("extent"); - if (extent.containsKey("spatial")) { + /** + *
    +	 * Abstract Test 22: Verify support for the EDR GeoJSON Schema
    +	 * Abstract Test 23: Verify the content of an EDR GeoJSON document given an input document and schema.
    +	 * Note that the first positions resource that supports GeoJSON is tested.
    +	 * 
    + */ + @Test(description = "Implements Abstract Test 22 (/conf/edr-geojson/definition), Abstract Test 23 (/conf/edr-geojson/content)") + public void validateResponseForEDRGeoJSON(ITestContext testContext) { + List requirementClasses = (List) testContext.getSuite().getAttribute(REQUIREMENTCLASSES.getName()); - HashMap spatial = (HashMap) extent.get("spatial"); + if (!requirementClasses.contains(RequirementClass.EDRGEOJSON)) { + throw new SkipException(String.format("Requirements class %s not implemented.", + RequirementClass.EDRGEOJSON.getConformanceClass())); + } - if (!spatial.containsKey("bbox")) - { + StringBuffer sb = new StringBuffer(); + boolean atLeastOneCollectionTested = false; // we test the first locations + // resource we find + Response response = getCollectionResponse(null); + JsonPath jsonResponse = response.jsonPath(); - sb.append("spatial extent of collection "+collectionId+" missing bbox\n"); - continue; - } + ArrayList collectionsList = (ArrayList) jsonResponse.getList("collections"); + for (int i = 0; (i < collectionsList.size()) && (atLeastOneCollectionTested == false); i++) { + HashMap collectionItem = (HashMap) collectionsList.get(i); - + String collectionId = collectionItem.get("id").toString(); - ArrayList bboxEnv = (ArrayList) spatial.get("bbox"); // for some unknown reason the library returns JSON types as Integers only + if (!collectionItem.containsKey("data_queries")) { + continue; // we loop until we find a collection that supports data_queries + } + HashMap dataQueries = (HashMap) collectionItem.get("data_queries"); + boolean supportsPositionQuery = dataQueries.containsKey("position"); - ArrayList bbox = null; + if (supportsPositionQuery) { + HashMap positionQuery = (HashMap) dataQueries.get("position"); + HashMap link = (HashMap) positionQuery.get("link"); + HashMap variables = (HashMap) link.get("variables"); - if(bboxEnv.get(0).getClass().toString().contains("java.lang.Integer") || - bboxEnv.get(0).getClass().toString().contains("java.lang.Double")|| - bboxEnv.get(0).getClass().toString().contains("java.lang.Float")) { //for EDR API V1.0.0 - bbox = bboxEnv; + ArrayList outputFormatList = (ArrayList) variables.get("output_formats"); + String supportedFormat = null; - } - else if(bboxEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { //for EDR API V1.0.1 - bbox = (ArrayList) bboxEnv.get(0); - } + for (int f = 0; f < outputFormatList.size(); f++) { + if (outputFormatList.get(f).equals("GeoJSON")) { + supportedFormat = outputFormatList.get(f); + } + } - - - if (bbox.size() > 3) { - + ArrayList crsList = (ArrayList) collectionItem.get("crs"); + + String supportedCRS = null; + for (int f = 0; f < crsList.size(); f++) { + if (crsList.get(f).equals("CRS84") || crsList.get(f).equals("CRS:84") + || crsList.get(f).equals("WGS84") || crsList.get(f).equals("EPSG:4326") + || crsList.get(f).contains("www.opengis.net/def/crs/OGC/1.3/CRS84")) { + supportedCRS = crsList.get(f); + } + } + + double medianx = 0d; + double mediany = 0d; + HashMap extent = (HashMap) collectionItem.get("extent"); + if (extent.containsKey("spatial")) { + + HashMap spatial = (HashMap) extent.get("spatial"); + + if (!spatial.containsKey("bbox")) { + + sb.append("spatial extent of collection " + collectionId + " missing bbox\n"); + continue; + } + + ArrayList bboxEnv = (ArrayList) spatial.get("bbox"); // for some + // unknown + // reason the + // library + // returns + // JSON types + // as Integers + // only + + ArrayList bbox = null; + + if (bboxEnv.get(0).getClass().toString().contains("java.lang.Integer") + || bboxEnv.get(0).getClass().toString().contains("java.lang.Double") + || bboxEnv.get(0).getClass().toString().contains("java.lang.Float")) { // for + // EDR + // API + // V1.0.0 + bbox = bboxEnv; + + } + else if (bboxEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { // for + // EDR + // API + // V1.0.1 + bbox = (ArrayList) bboxEnv.get(0); + } + + if (bbox.size() > 3) { if (bbox.get(0).getClass().toString().contains("Integer") || bbox.get(0).getClass().toString().contains("Double") @@ -157,20 +142,16 @@ else if(bboxEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { medianx = minx + ((maxx - minx) / 2d); mediany = miny + ((maxy - miny) / 2d); - - - - + } - } else { + } + else { sb.append("bbox of spatial extent of collection" + collectionId + " has fewer than four coordinates\n"); } - } - - + } HashMap parameterNames = (HashMap) collectionItem.get("parameter_names"); Set parameterNamesSet = parameterNames.keySet(); @@ -181,118 +162,117 @@ else if(bboxEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { String sampleParamaterNameSafe = null; try { - sampleParamaterNameSafe = URLEncoder.encode(sampleParamaterName,"UTF8"); + sampleParamaterNameSafe = URLEncoder.encode(sampleParamaterName, "UTF8"); } - catch(Exception ex) {ex.printStackTrace();} + catch (Exception ex) { + ex.printStackTrace(); + } - - String sampleDateTime = null; if (extent.containsKey("temporal")) { - HashMap temporal = (HashMap) extent.get("temporal"); - if (!temporal.containsKey("interval")) - { + if (!temporal.containsKey("interval")) { - sb.append("temporal extent of collection "+collectionId+" missing interval\n"); - continue; - } - - - + sb.append("temporal extent of collection " + collectionId + " missing interval\n"); + continue; + } - ArrayList intervalEnv = (ArrayList) temporal.get("interval"); // for some unknown reason the library returns + ArrayList intervalEnv = (ArrayList) temporal.get("interval"); // for + // some + // unknown + // reason + // the + // library + // returns - + ArrayList interval = null; - ArrayList interval = null; - - - if(intervalEnv.get(0).getClass().toString().contains("java.lang.String")) { //EDR API v1.0.0 - interval = intervalEnv; - } - else { //EDR API v1.0.1 - interval = (ArrayList) intervalEnv.get(0); - } - - + if (intervalEnv.get(0).getClass().toString().contains("java.lang.String")) { // EDR + // API + // v1.0.0 + interval = intervalEnv; + } + else { // EDR API v1.0.1 + interval = (ArrayList) intervalEnv.get(0); + } - if (interval.size() > 1) { - - sampleDateTime = interval.get(0)+"/"+interval.get(1); - + sampleDateTime = interval.get(0) + "/" + interval.get(1); + + } - } - } - - try { - if(supportedFormat!=null && supportedCRS!=null) { - if(supportedFormat.equals("GeoJSON") && - - (supportedCRS.equals("CRS84") || - supportedCRS.equals("CRS:84") || - supportedCRS.equals("WGS84") || - supportedCRS.equals("EPSG:4326") || - supportedCRS.contains("www.opengis.net/def/crs/OGC/1.3/CRS84")) - - ) { - - String locationsURL = null; - - if(supportedCRS.equals("EPSG:4326")) { - locationsURL = link.get("href").toString()+"?f="+supportedFormat+"&crs=EPSG:4326"+"&coords=POINT("+mediany+"+"+medianx+")"+"¶meter-name="+sampleParamaterNameSafe+"&datetime="+sampleDateTime ; - } - else { - locationsURL = link.get("href").toString()+"?f="+supportedFormat+"&crs=CRS84"+"&coords=POINT("+medianx+"+"+mediany+")"+"¶meter-name="+sampleParamaterNameSafe+"&datetime="+sampleDateTime ; - } - - GeoJSONValidator validator = new GeoJSONValidator(); - boolean result = validator.isGeoJSONValidPerSchema(locationsURL,GeoJSONValidator.EDRGeoJSON); - - atLeastOneCollectionTested = true; - if(result==false) { - String msg = " GeoJSON returned by Collection "+collectionId+" failed the schema validation test.\n"; - - sb.append(msg); - } - } - else { - continue; //loop until we find a collection that supports GeoJSON encoded responses that are referenced to CRS84. - } - } - else { - continue; //loop until we find a collection that supports GeoJSON encoded responses that are referenced to CRS84. - } - } - catch(Exception ex) { - ex.printStackTrace(); - sb.append(" "+ex.getMessage()+"\n"); - } - - - } - else { - continue; //we loop until we find a collection that supports position data queries - } - - } - - - - - //String resultMessage = sb.toString(); //verbose error message - //EtsAssert.assertTrue(atLeastOneCollectionTested, "Fails Abstract Test 23. " + resultMessage); - - EtsAssert.assertTrue(atLeastOneCollectionTested, "Fails Abstract Test 23. None of the collections were found to offer Position resources that return GeoJSON conforming to EDR GeoJSON.\n"); - - - } + try { + if (supportedFormat != null && supportedCRS != null) { + if (supportedFormat.equals("GeoJSON") && + + (supportedCRS.equals("CRS84") || supportedCRS.equals("CRS:84") + || supportedCRS.equals("WGS84") || supportedCRS.equals("EPSG:4326") + || supportedCRS.contains("www.opengis.net/def/crs/OGC/1.3/CRS84")) + + ) { + + String locationsURL = null; + + if (supportedCRS.equals("EPSG:4326")) { + locationsURL = link.get("href").toString() + "?f=" + supportedFormat + "&crs=EPSG:4326" + + "&coords=POINT(" + mediany + "+" + medianx + ")" + "¶meter-name=" + + sampleParamaterNameSafe + "&datetime=" + sampleDateTime; + } + else { + locationsURL = link.get("href").toString() + "?f=" + supportedFormat + "&crs=CRS84" + + "&coords=POINT(" + medianx + "+" + mediany + ")" + "¶meter-name=" + + sampleParamaterNameSafe + "&datetime=" + sampleDateTime; + } + + GeoJSONValidator validator = new GeoJSONValidator(); + boolean result = validator.isGeoJSONValidPerSchema(locationsURL, + GeoJSONValidator.EDRGeoJSON); + + atLeastOneCollectionTested = true; + if (result == false) { + String msg = " GeoJSON returned by Collection " + collectionId + + " failed the schema validation test.\n"; + + sb.append(msg); + } + } + else { + continue; // loop until we find a collection that supports + // GeoJSON encoded responses that are referenced + // to CRS84. + } + } + else { + continue; // loop until we find a collection that supports GeoJSON + // encoded responses that are referenced to CRS84. + } + } + catch (Exception ex) { + ex.printStackTrace(); + sb.append(" " + ex.getMessage() + "\n"); + } + + } + else { + continue; // we loop until we find a collection that supports position + // data queries + } + + } + + // String resultMessage = sb.toString(); //verbose error message + // EtsAssert.assertTrue(atLeastOneCollectionTested, "Fails Abstract Test 23. " + + // resultMessage); + + EtsAssert.assertTrue(atLeastOneCollectionTested, + "Fails Abstract Test 23. None of the collections were found to offer Position resources that return GeoJSON conforming to EDR GeoJSON.\n"); + + } } \ No newline at end of file diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/encodings/geojson/GeoJSONEncoding.java b/src/main/java/org/opengis/cite/ogcapiedr10/encodings/geojson/GeoJSONEncoding.java index 2221188..d76345d 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/encodings/geojson/GeoJSONEncoding.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/encodings/geojson/GeoJSONEncoding.java @@ -19,91 +19,91 @@ public class GeoJSONEncoding extends CommonFixture { - - - protected URI iut; - - - - /** - *
    -     * Abstract Test 20: Verify support for JSON and GeoJSON
    -     * Abstract Test 21: Verify the content of a JSON document given an input document and schema.
    -     * Note that the first locations resource that supports GeoJSON is tested.
    -     * 
    - */ - @Test(description = "Implements Abstract Test 20 (/conf/geojson/definition), Abstract Test 21 (/conf/geojson/content)") - public void validateResponseForGeoJSON(ITestContext testContext) { - - List requirementClasses = (List) testContext.getSuite().getAttribute( REQUIREMENTCLASSES.getName()); - - if(!requirementClasses.contains(RequirementClass.GEOJSON)) { - throw new SkipException(String.format("Requirements class %s not implemented.", RequirementClass.GEOJSON.getConformanceClass())); - } - - StringBuffer sb = new StringBuffer(); - boolean atLeastOneCollectionTested = false; //we test the first locations resource we find - Response response = getCollectionResponse(null); - JsonPath jsonResponse = response.jsonPath(); - ArrayList collectionsList = (ArrayList) jsonResponse.getList("collections"); - - for(int i=0; (i< collectionsList.size()) && (atLeastOneCollectionTested==false); i++) - { - HashMap collectionItem = (HashMap) collectionsList.get(i); - - if(!collectionItem.containsKey("data_queries")) { - continue; //we loop until we find a collection that supports data_queries - } - - HashMap dataQueries = (HashMap) collectionItem.get("data_queries"); - boolean supportsLocationsQuery = dataQueries.containsKey("locations"); - - if(supportsLocationsQuery) { - HashMap locationsQuery = (HashMap) dataQueries.get("locations"); - HashMap link = (HashMap) locationsQuery.get("link"); - HashMap variables = (HashMap) link.get("variables"); - ArrayList outputFormatList = (ArrayList) variables.get("output_formats"); - String supportedFormat = null; - for (int f = 0; f < outputFormatList.size(); f++) { - if (outputFormatList.get(f).equals("GeoJSON")) { - supportedFormat = outputFormatList.get(f); - } - } - - try { - if(supportedFormat!=null) { - String locationsURL = link.get("href").toString()+"?f="+supportedFormat; - - GeoJSONValidator validator = new GeoJSONValidator(); - boolean result = validator.isGeoJSONValidPerSchema(locationsURL,GeoJSONValidator.GeoJSON); - atLeastOneCollectionTested = true; - if(result==false) { - sb.append(" None of the collections with locations resources were found to offer GeoJSON encoded responses.\n"); - } - } - else { - continue; // We loop until we find a collection that supports GeoJSON. - } - } - catch(Exception ex) { - ex.printStackTrace(); - sb.append(" "+ex.getMessage()+"\n"); - } - - - } - else { - continue; //we loop until we find a collection that supports the Locations query - } - - } - - - //String resultMessage = sb.toString(); //verbose error message - //EtsAssert.assertTrue(resultMessage.length()==0, "Fails Abstract Test 21. " + resultMessage); - - EtsAssert.assertTrue(atLeastOneCollectionTested, "Fails Abstract Test 21. None of the collections were found to offer Locations resources that return valid GeoJSON\n"); - - } + protected URI iut; + + /** + *
    +	 * Abstract Test 20: Verify support for JSON and GeoJSON
    +	 * Abstract Test 21: Verify the content of a JSON document given an input document and schema.
    +	 * Note that the first locations resource that supports GeoJSON is tested.
    +	 * 
    + */ + @Test(description = "Implements Abstract Test 20 (/conf/geojson/definition), Abstract Test 21 (/conf/geojson/content)") + public void validateResponseForGeoJSON(ITestContext testContext) { + + List requirementClasses = (List) testContext.getSuite().getAttribute(REQUIREMENTCLASSES.getName()); + + if (!requirementClasses.contains(RequirementClass.GEOJSON)) { + throw new SkipException(String.format("Requirements class %s not implemented.", + RequirementClass.GEOJSON.getConformanceClass())); + } + + StringBuffer sb = new StringBuffer(); + boolean atLeastOneCollectionTested = false; // we test the first locations + // resource we find + Response response = getCollectionResponse(null); + JsonPath jsonResponse = response.jsonPath(); + ArrayList collectionsList = (ArrayList) jsonResponse.getList("collections"); + + for (int i = 0; (i < collectionsList.size()) && (atLeastOneCollectionTested == false); i++) { + HashMap collectionItem = (HashMap) collectionsList.get(i); + + if (!collectionItem.containsKey("data_queries")) { + continue; // we loop until we find a collection that supports data_queries + } + + HashMap dataQueries = (HashMap) collectionItem.get("data_queries"); + boolean supportsLocationsQuery = dataQueries.containsKey("locations"); + + if (supportsLocationsQuery) { + HashMap locationsQuery = (HashMap) dataQueries.get("locations"); + HashMap link = (HashMap) locationsQuery.get("link"); + HashMap variables = (HashMap) link.get("variables"); + ArrayList outputFormatList = (ArrayList) variables.get("output_formats"); + String supportedFormat = null; + for (int f = 0; f < outputFormatList.size(); f++) { + if (outputFormatList.get(f).equals("GeoJSON")) { + supportedFormat = outputFormatList.get(f); + } + } + + try { + if (supportedFormat != null) { + String locationsURL = link.get("href").toString() + "?f=" + supportedFormat; + + GeoJSONValidator validator = new GeoJSONValidator(); + boolean result = validator.isGeoJSONValidPerSchema(locationsURL, GeoJSONValidator.GeoJSON); + atLeastOneCollectionTested = true; + if (result == false) { + sb.append( + " None of the collections with locations resources were found to offer GeoJSON encoded responses.\n"); + } + } + else { + continue; // We loop until we find a collection that supports + // GeoJSON. + } + } + catch (Exception ex) { + ex.printStackTrace(); + sb.append(" " + ex.getMessage() + "\n"); + } + + } + else { + continue; // we loop until we find a collection that supports the + // Locations query + } + + } + + // String resultMessage = sb.toString(); //verbose error message + // EtsAssert.assertTrue(resultMessage.length()==0, "Fails Abstract Test 21. " + + // resultMessage); + + EtsAssert.assertTrue(atLeastOneCollectionTested, + "Fails Abstract Test 21. None of the collections were found to offer Locations resources that return valid GeoJSON\n"); + + } } \ No newline at end of file diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/encodings/geojson/GeoJSONValidator.java b/src/main/java/org/opengis/cite/ogcapiedr10/encodings/geojson/GeoJSONValidator.java index da15f6c..4dceff8 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/encodings/geojson/GeoJSONValidator.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/encodings/geojson/GeoJSONValidator.java @@ -13,58 +13,60 @@ import org.json.JSONObject; public class GeoJSONValidator { - public static final int GeoJSON = -1; - public static final int EDRGeoJSON = -2; - protected final int DEFAULT_BUFFER_SIZE = 8192; - public boolean isGeoJSONValidPerSchema(String docURL, int schemaFlag) throws Exception { - String schemaToApply = "/org/opengis/cite/ogcapiedr10/jsonschema/geojson.json"; - if(schemaFlag == EDRGeoJSON){ - schemaToApply = "/org/opengis/cite/ogcapiedr10/jsonschema/edrgeojson.json"; - } + public static final int GeoJSON = -1; - boolean valid = false; + public static final int EDRGeoJSON = -2; - InputStream inputStream = getClass() - .getResourceAsStream(schemaToApply); - JSONObject rawSchema = new JSONObject(otherConvertInputStreamToString(inputStream)); - Schema schema = SchemaLoader.load(rawSchema); - schema.validate(readJSONObjectFromURL(new URL(docURL))); // throws a ValidationException if this object is invalid - valid = true; + protected final int DEFAULT_BUFFER_SIZE = 8192; + public boolean isGeoJSONValidPerSchema(String docURL, int schemaFlag) throws Exception { + String schemaToApply = "/org/opengis/cite/ogcapiedr10/jsonschema/geojson.json"; - return valid; + if (schemaFlag == EDRGeoJSON) { + schemaToApply = "/org/opengis/cite/ogcapiedr10/jsonschema/edrgeojson.json"; + } - } + boolean valid = false; - public JSONObject readJSONObjectFromURL(URL requestURL) throws IOException { + InputStream inputStream = getClass().getResourceAsStream(schemaToApply); + JSONObject rawSchema = new JSONObject(otherConvertInputStreamToString(inputStream)); + Schema schema = SchemaLoader.load(rawSchema); + schema.validate(readJSONObjectFromURL(new URL(docURL))); // throws a + // ValidationException + // if this object is + // invalid + valid = true; - HttpURLConnection urlConnection = (HttpURLConnection) requestURL.openConnection(); - urlConnection.setRequestProperty("Accept","application/json"); - InputStream is = urlConnection.getInputStream(); - try ( Scanner scanner = new Scanner(is, - StandardCharsets.UTF_8.toString())) { - scanner.useDelimiter("\\A"); + return valid; - return new JSONObject(scanner.hasNext() ? scanner.next() : ""); - } + } - } - - // from https://mkyong.com/java/how-to-convert-inputstream-to-string-in-java/ - public String otherConvertInputStreamToString(InputStream is) throws IOException { + public JSONObject readJSONObjectFromURL(URL requestURL) 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); - } + HttpURLConnection urlConnection = (HttpURLConnection) requestURL.openConnection(); + urlConnection.setRequestProperty("Accept", "application/json"); + InputStream is = urlConnection.getInputStream(); + try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.toString())) { + scanner.useDelimiter("\\A"); + return new JSONObject(scanner.hasNext() ? scanner.next() : ""); + } + } - return result.toString("UTF-8"); + // 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"); + + } - } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/encodings/json/JSONEncoding.java b/src/main/java/org/opengis/cite/ogcapiedr10/encodings/json/JSONEncoding.java index 1ddb108..ae417b9 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/encodings/json/JSONEncoding.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/encodings/json/JSONEncoding.java @@ -18,11 +18,8 @@ import io.restassured.response.Response; public class JSONEncoding extends CommonFixture { - - protected URI iut; - /** *
    @@ -39,13 +36,15 @@ public void validateResponseForJSON() {
     		assertTrue(isJSONValidPerSchema(response.asString(), "/"),
     				"Fails Abstract Test 19, landing page response not valid JSON");
     
    -
    -		response = init().baseUri(apiDefUri.toString()).accept( OPEN_API_MIME_TYPE ).when().request( GET );
    +		response = init().baseUri(apiDefUri.toString()).accept(OPEN_API_MIME_TYPE).when().request(GET);
     		assertTrue(response.getStatusCode() == 200,
    -				"Fails Abstract Test 18, JSON response not supported for api description \nCODE"+response.getStatusCode()+"\n"+apiDefUri.toString());
    +				"Fails Abstract Test 18, JSON response not supported for api description \nCODE"
    +						+ response.getStatusCode() + "\n" + apiDefUri.toString());
     
    -		response = init().baseUri(rootUri.toString()).accept(ContentType.JSON).when().request(Method.GET,
    -				"/conformance");
    +		response = init().baseUri(rootUri.toString())
    +			.accept(ContentType.JSON)
    +			.when()
    +			.request(Method.GET, "/conformance");
     		assertTrue(response.getStatusCode() == 200,
     				"Fails Abstract Test 18, JSON response not supported for conformance declaration");
     		assertTrue(isJSONValidPerSchema(response.asString(), "/conformance"),
    @@ -64,26 +63,32 @@ private boolean isJSONValidPerSchema(String doc, String path) {
     
     		if (path.equals("/")) {
     			try (InputStream inputStream = getClass()
    -					.getResourceAsStream("/org/opengis/cite/ogcapiedr10/jsonschema/landingPage.json")) {
    -			
    +				.getResourceAsStream("/org/opengis/cite/ogcapiedr10/jsonschema/landingPage.json")) {
    +
     				JSONObject rawSchema = new JSONObject(convertInputStreamToString(inputStream));
     				Schema schema = SchemaLoader.load(rawSchema);
    -				schema.validate(new JSONObject(doc)); // throws a ValidationException if this object is invalid
    +				schema.validate(new JSONObject(doc)); // throws a ValidationException if
    +														// this object is invalid
     				valid = true;
    -			} catch (Exception ee) {
    +			}
    +			catch (Exception ee) {
     				ee.printStackTrace();
     			}
    -		} else if (path.equals("/conformance")) {
    +		}
    +		else if (path.equals("/conformance")) {
     			try (InputStream inputStream = getClass()
    -					.getResourceAsStream("/org/opengis/cite/ogcapiedr10/jsonschema/confClasses.json")) {
    +				.getResourceAsStream("/org/opengis/cite/ogcapiedr10/jsonschema/confClasses.json")) {
     				JSONObject rawSchema = new JSONObject(convertInputStreamToString(inputStream));
     				Schema schema = SchemaLoader.load(rawSchema);
    -				schema.validate(new JSONObject(doc)); // throws a ValidationException if this object is invalid
    +				schema.validate(new JSONObject(doc)); // throws a ValidationException if
    +														// this object is invalid
     				valid = true;
    -			} catch (Exception ee) {
    +			}
    +			catch (Exception ee) {
     				ee.printStackTrace();
     			}
    -		} else {
    +		}
    +		else {
     			valid = true;
     		}
     
    @@ -91,5 +96,4 @@ private boolean isJSONValidPerSchema(String doc, String path) {
     
     	}
     
    -
     }
    diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/landingpage/LandingPage.java b/src/main/java/org/opengis/cite/ogcapiedr10/landingpage/LandingPage.java
    index f9aa0a1..e16ace9 100644
    --- a/src/main/java/org/opengis/cite/ogcapiedr10/landingpage/LandingPage.java
    +++ b/src/main/java/org/opengis/cite/ogcapiedr10/landingpage/LandingPage.java
    @@ -23,43 +23,38 @@
      */
     public class LandingPage extends CommonFixture {
     
    -    private JsonPath jsonPath;
    +	private JsonPath jsonPath;
    +
    +	/**
    +	 * 
    +	 * Abstract Test 2: Validate that a landing page can be retrieved from the expected location.
    +	 * Abstract Test 3: Validate that the landing page complies with the require structure and contents.
    +	 * 
    + */ + @Test(description = "Implements Abstract Test 2 (/conf/core/root-op) and Abstract Test 3 (/conf/core/root-success) - Landing Page validation", + groups = "landingpage") + public void edrLandingPageValidation(ITestContext testContext) { + + jsonPath = (JsonPath) testContext.getSuite().getAttribute(SuiteAttribute.LANDINGPAGEJSONPATH.getName()); + + List links = jsonPath.getList("links"); + Set linkTypes = collectLinkTypes(links); + boolean expectedLinkTypesExists = (linkTypes.contains("service-desc") || linkTypes.contains("service-doc")) + && linkTypes.contains("conformance") && linkTypes.contains("data"); + + assertTrue(expectedLinkTypesExists, + "The landing page must include at least links with relation types ('service-desc' and/or 'service-doc' ) and 'data' and 'conformance', but contains " + + String.join(", ", linkTypes)); + } + + private Set collectLinkTypes(List links) { + Set linkTypes = new HashSet<>(); + for (Object link : links) { + Map linkMap = (Map) link; + Object linkType = linkMap.get("rel"); + linkTypes.add((String) linkType); + } + return linkTypes; + } - - /** - *
    -     * Abstract Test 2: Validate that a landing page can be retrieved from the expected location.
    -     * Abstract Test 3: Validate that the landing page complies with the require structure and contents.
    -     * 
    - */ - @Test(description = "Implements Abstract Test 2 (/conf/core/root-op) and Abstract Test 3 (/conf/core/root-success) - Landing Page validation", groups = "landingpage") - public void edrLandingPageValidation(ITestContext testContext) { - - jsonPath = (JsonPath) testContext.getSuite().getAttribute(SuiteAttribute.LANDINGPAGEJSONPATH.getName()); - - List links = jsonPath.getList( "links" ); - Set linkTypes = collectLinkTypes( links ); - boolean expectedLinkTypesExists = ( linkTypes.contains( "service-desc" ) - || linkTypes.contains( "service-doc" ) ) - && linkTypes.contains( "conformance" ) && linkTypes.contains( "data" ); - - assertTrue( expectedLinkTypesExists, - "The landing page must include at least links with relation types ('service-desc' and/or 'service-doc' ) and 'data' and 'conformance', but contains " - + String.join( ", ", linkTypes ) ); - } - - private Set collectLinkTypes( List links ) { - Set linkTypes = new HashSet<>(); - for ( Object link : links ) { - Map linkMap = (Map) link; - Object linkType = linkMap.get( "rel" ); - linkTypes.add( (String) linkType ); - } - return linkTypes; - } - - - - - } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/openapi3/OpenApiUtils.java b/src/main/java/org/opengis/cite/ogcapiedr10/openapi3/OpenApiUtils.java index cee85f7..18d103f 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/openapi3/OpenApiUtils.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/openapi3/OpenApiUtils.java @@ -41,7 +41,9 @@ public class OpenApiUtils { @FunctionalInterface private interface PathMatcherFunction { + A apply(B b, C c); + } enum PATH { @@ -58,15 +60,18 @@ enum PATH { private String getPathItem() { return pathItem; } + } private static class PathMatcher implements PathMatcherFunction { + @Override public Boolean apply(String pathUnderTest, String pathToMatch) { UriTemplateParser parser = new UriTemplateParser(pathUnderTest); Matcher matcher = parser.getPattern().matcher(pathToMatch); return matcher.matches(); } + } private static class ExactMatchFilter implements Predicate { @@ -90,34 +95,33 @@ public boolean test(TestPoint testPoint) { Pattern pattern = Pattern.compile(uri); return pattern.matcher(requestedPath).matches(); } + } private OpenApiUtils() { } /** - * Parse all test points from the passed OpenApi3 document as described in - * A.4.3. Identify the Test Points. - * + * Parse all test points from the passed OpenApi3 document as described in A.4.3. + * Identify the Test Points. * @param apiModel never null - * @param iut the url of the instance under test, never null + * @param iut the url of the instance under test, never null * @return the parsed test points, may be empty but never null */ static List retrieveTestPoints(OpenApi3 apiModel, URI iut) { - + List pathItemObjects = identifyTestPoints(apiModel); List pathItemAndServers = identifyServerUrls(apiModel, iut, pathItemObjects); - + return processServerObjects(pathItemAndServers, true); } /** - * Parse the CONFORMANCE test points from the passed OpenApi3 document as - * described in A.4.3. Identify the Test Points. - * + * Parse the CONFORMANCE test points from the passed OpenApi3 document as described in + * A.4.3. Identify the Test Points. * @param apiModel never null - * @param iut the url of the instance under test, never null + * @param iut the url of the instance under test, never null * @return the parsed test points, may be empty but never null */ public static List retrieveTestPointsForConformance(OpenApi3 apiModel, URI iut) { @@ -125,11 +129,10 @@ public static List retrieveTestPointsForConformance(OpenApi3 apiModel } /** - * Parse the COLLECTIONS METADATA test points from the passed OpenApi3 document - * as described in A.4.3. Identify the Test Points. - * + * Parse the COLLECTIONS METADATA test points from the passed OpenApi3 document as + * described in A.4.3. Identify the Test Points. * @param apiModel never null - * @param iut the url of the instance under test, never null + * @param iut the url of the instance under test, never null * @return the parsed test points, may be empty but never null */ public static List retrieveTestPointsForCollectionsMetadata(OpenApi3 apiModel, URI iut) { @@ -137,13 +140,11 @@ public static List retrieveTestPointsForCollectionsMetadata(OpenApi3 } /** - * Parse the COLLECTION METADATA test points for the passed collectionName - * including the extended path from the passed OpenApi3 document as described in - * A.4.3. Identify the Test Points. - * - * @param apiModel never null - * @param iut the url of the instance under test, never - * null + * Parse the COLLECTION METADATA test points for the passed collectionName including + * the extended path from the passed OpenApi3 document as described in A.4.3. Identify + * the Test Points. + * @param apiModel never null + * @param iut the url of the instance under test, never null * @param collectionName the extended path, may be null * @return the parsed test points, may be empty but never null */ @@ -160,46 +161,36 @@ public static List retrieveTestPointsForCollectionMetadata(OpenApi3 a } /** - * Parse the COLLECTIONS test points from the passed OpenApi3 document as - * described in A.4.3. Identify the Test Points. - * - * @param apiModel never null - * @param iut the url of the instance under test, never - * null - * @param noOfCollection the number of collections to return test points for (-1 - * means the test points of all collections should be - * returned) + * Parse the COLLECTIONS test points from the passed OpenApi3 document as described in + * A.4.3. Identify the Test Points. + * @param apiModel never null + * @param iut the url of the instance under test, never null + * @param noOfCollection the number of collections to return test points for (-1 means + * the test points of all collections should be returned) * @return the parsed test points, may be empty but never null */ public static List retrieveTestPointsForCollections(OpenApi3 apiModel, URI iut, int noOfCollection) { - String[] resources = { "locations", "position", "radius", "area", "trajectory" }; - - - + String[] resources = { "locations", "position", "radius", "area", "trajectory" }; + List allTestPoints = new ArrayList(); try { - for (String res : resources) { - StringBuilder requestedPath = new StringBuilder(); - requestedPath.append("/"); - requestedPath.append(COLLECTIONS.getPathItem()); - requestedPath.append("/.*/"+res); + for (String res : resources) { + StringBuilder requestedPath = new StringBuilder(); + requestedPath.append("/"); + requestedPath.append(COLLECTIONS.getPathItem()); + requestedPath.append("/.*/" + res); - - - boolean r = allTestPoints + boolean r = allTestPoints .addAll(retrieveTestPoints(apiModel, iut, requestedPath.toString(), (a, b) -> a.matches(b), true)); - - - } + + } } - catch(Exception er) - { - + catch (Exception er) { + er.printStackTrace(); } - if (noOfCollection < 0 || allTestPoints.size() <= noOfCollection) { return allTestPoints; @@ -209,12 +200,10 @@ public static List retrieveTestPointsForCollections(OpenApi3 apiModel } /** - * Parse the test points with the passed path including the extended path from - * the passed OpenApi3 document as described in A.4.3. Identify the Test Points. - * - * @param apiModel never null - * @param iut the url of the instance under test, never - * null + * Parse the test points with the passed path including the extended path from the + * passed OpenApi3 document as described in A.4.3. Identify the Test Points. + * @param apiModel never null + * @param iut the url of the instance under test, never null * @param collectionName the extended path, may be null * @return the parsed test points, may be empty but never null */ @@ -226,14 +215,12 @@ public static List retrieveTestPointsForCollection(OpenApi3 apiModel, } /** - * Parse the test points with the passed path including the extended path from - * the passed OpenApi3 document as described in A.4.3. Identify the Test Points. - * - * @param apiModel never null - * @param iut the url of the instance under test, never - * null + * Parse the test points with the passed path including the extended path from the + * passed OpenApi3 document as described in A.4.3. Identify the Test Points. + * @param apiModel never null + * @param iut the url of the instance under test, never null * @param collectionName the extended path, may be null - * @param featureId the id of the feature, never null + * @param featureId the id of the feature, never null * @return the parsed test points, may be empty but never null */ public static List retrieveTestPointsForFeature(OpenApi3 apiModel, URI iut, String collectionName, @@ -295,33 +282,25 @@ public static boolean isParameterSupportedForCollection(OpenApi3 apiModel, Strin return false; } - public static Link parseApiUrl( JsonPath jsonPath ) { - - - - for ( Object link : jsonPath.getList( "links" ) ) { - Map linkMap = (Map) link; - Object rel = linkMap.get( "rel" ); - Object type = linkMap.get( "type" ); - if ("service-desc".equals( rel )) //Check service-desc first - { - return new Link((String) linkMap.get( "href" ), - (String)rel, - (String)type); - - - } - else if ("service-doc".equals( rel )) - { - - return new Link((String) linkMap.get( "href" ), - (String)rel, - (String)type); - - } - } - return null; - } + public static Link parseApiUrl(JsonPath jsonPath) { + + for (Object link : jsonPath.getList("links")) { + Map linkMap = (Map) link; + Object rel = linkMap.get("rel"); + Object type = linkMap.get("type"); + if ("service-desc".equals(rel)) // Check service-desc first + { + return new Link((String) linkMap.get("href"), (String) rel, (String) type); + + } + else if ("service-doc".equals(rel)) { + + return new Link((String) linkMap.get("href"), (String) rel, (String) type); + + } + } + return null; + } private static String createCollectionPath(String collectionName) { StringBuilder requestedPath = new StringBuilder(); @@ -354,8 +333,8 @@ private static List retrieveTestPoints(OpenApi3 apiModel, URI iut, St /** * A.4.3.1. Identify Test Points: * - * a) Purpose: To identify the test points associated with each Path in the - * OpenAPI document + * a) Purpose: To identify the test points associated with each Path in the OpenAPI + * document * * b) Pre-conditions: * @@ -368,13 +347,12 @@ private static List retrieveTestPoints(OpenApi3 apiModel, URI iut, St * * c) Method: * - * FOR EACH paths property in the OpenAPI document If the path name is one of - * those specified in the WFS 3.0 specification Retrieve the Server URIs using - * A.4.3.2. FOR EACH Server URI Concatenate the Server URI with the path name to - * form a test point. Add that test point to the list. + * FOR EACH paths property in the OpenAPI document If the path name is one of those + * specified in the WFS 3.0 specification Retrieve the Server URIs using A.4.3.2. FOR + * EACH Server URI Concatenate the Server URI with the path name to form a test point. + * Add that test point to the list. * * d) References: None - * * @param apiModel never null */ private static List identifyTestPoints(OpenApi3 apiModel) { @@ -400,8 +378,7 @@ private static List identifyTestPoints(OpenApi3 apiModel, String path, /** * A.4.3.2. Identify Server URIs: * - * a) Purpose: To identify all server URIs applicable to an OpenAPI Operation - * Object + * a) Purpose: To identify all server URIs applicable to an OpenAPI Operation Object * * b) Pre-conditions: * @@ -420,30 +397,29 @@ private static List identifyTestPoints(OpenApi3 apiModel, String path, * * 1) Identify the Server Objects which are in-scope for this operationObject * - * IF Server Objects are defined at the Operation level, then those and only - * those Server Objects apply to that Operation. + * IF Server Objects are defined at the Operation level, then those and only those + * Server Objects apply to that Operation. * - * IF Server Objects are defined at the Path Item level, then those and only - * those Server Objects apply to that Path Item. + * IF Server Objects are defined at the Path Item level, then those and only those + * Server Objects apply to that Path Item. * - * IF Server Objects are not defined at the Operation level, then the Server - * Objects defined for the parent Path Item apply to that Operation. + * IF Server Objects are not defined at the Operation level, then the Server Objects + * defined for the parent Path Item apply to that Operation. * - * IF Server Objects are not defined at the Path Item level, then the Server - * Objects defined for the root level apply to that Path. + * IF Server Objects are not defined at the Path Item level, then the Server Objects + * defined for the root level apply to that Path. * - * IF no Server Objects are defined at the root level, then the default server - * object is assumed as described in the OpenAPI specification. + * IF no Server Objects are defined at the root level, then the default server object + * is assumed as described in the OpenAPI specification. * * 2) Process each Server Object using A.4.3.3. * - * 3) Delete any Server URI which does not reference a server on the list of - * servers to test. + * 3) Delete any Server URI which does not reference a server on the list of servers + * to test. * * d) References: None - * - * @param apiModel never null - * @param iut never null + * @param apiModel never null + * @param iut never null * @param pathItemObjects never null */ private static List identifyServerUrls(OpenApi3 apiModel, URI iut, List pathItemObjects) { @@ -456,7 +432,8 @@ private static List identifyServerUrls(OpenApi3 apiModel, URI for (String serverUrl : serverUrls) { if (DEFAULT_SERVER_URL.equalsIgnoreCase(serverUrl)) { serverUrl = iut.toString(); - } else if (serverUrl.startsWith("/")) { + } + else if (serverUrl.startsWith("/")) { URI resolvedUri = iut.resolve(serverUrl); serverUrl = resolvedUri.toString(); } @@ -472,22 +449,20 @@ private static List identifyServerUrls(OpenApi3 apiModel, URI /** * A.4.3.3. Process Server Object: * - * a) Purpose: To expand the contents of a Server Object into a set of absolute - * URIs. + * a) Purpose: To expand the contents of a Server Object into a set of absolute URIs. * * b) Pre-conditions: A Server Object has been retrieved * * c) Method: * - * Processing the Server Object results in a set of absolute URIs. This set - * contains all of the URIs that can be created given the URI template and - * variables defined in that Server Object. + * Processing the Server Object results in a set of absolute URIs. This set contains + * all of the URIs that can be created given the URI template and variables defined in + * that Server Object. * - * If there are no variables in the URI template, then add the URI to the return - * set. + * If there are no variables in the URI template, then add the URI to the return set. * - * For each variable in the URI template which does not have an enumerated set - * of valid values: + * For each variable in the URI template which does not have an enumerated set of + * valid values: * * generate a URI using the default value, * @@ -495,21 +470,19 @@ private static List identifyServerUrls(OpenApi3 apiModel, URI * * flag this URI as non-exhaustive * - * For each variable in the URI template which has an enumerated set of valid - * values: + * For each variable in the URI template which has an enumerated set of valid values: * * generate a URI for each value in the enumerated set, * * add each generated URI to the return set. * - * Perform this processing in an iterative manner so that there is a unique URI - * for all possible combinations of enumerated and default values. + * Perform this processing in an iterative manner so that there is a unique URI for + * all possible combinations of enumerated and default values. * - * Convert all relative URIs to absolute URIs by rooting them on the URI to the - * server hosting the OpenAPI document. + * Convert all relative URIs to absolute URIs by rooting them on the URI to the server + * hosting the OpenAPI document. * * d) References: None - * * @param pathItemAndServers never null */ private static List processServerObjects(List pathItemAndServers, @@ -533,14 +506,16 @@ private static void processServerObject(List uris, PathItemAndServer if (uriTemplate.getNumberOfTemplateVariables() == 0) { TestPoint testPoint = new TestPoint(pathItemAndServer.serverUrl, pathString, contentMediaTypes); uris.add(testPoint); - } else { + } + else { List> templateReplacements = collectTemplateReplacements(pathItemAndServer, uriTemplate); if (templateReplacements.isEmpty() && allowEmptyTemplateReplacements) { TestPoint testPoint = new TestPoint(pathItemAndServer.serverUrl, pathString, contentMediaTypes); uris.add(testPoint); - } else { + } + else { for (Map templateReplacement : templateReplacements) { TestPoint testPoint = new TestPoint(pathItemAndServer.serverUrl, pathString, templateReplacement, contentMediaTypes); @@ -568,10 +543,13 @@ private static List> collectTemplateReplacements(PathItemAnd Schema schema = parameter.getSchema(); if (schema.hasEnums()) { addEnumTemplateValues(templateReplacements, templateVariable, schema); - } else if (schema.getDefault() != null) { + } + else if (schema.getDefault() != null) { addDefaultTemplateValue(templateReplacements, templateVariable, schema); - } else { - // TODO: What should be done if the parameter does not have a default value and + } + else { + // TODO: What should be done if the parameter does not have a + // default value and // no // enumerated set of valid values? } @@ -590,7 +568,8 @@ private static void addEnumTemplateValues(List> templateRepl replacement.put(templateVariable, enumValue.toString()); templateReplacements.add(replacement); } - } else { + } + else { if (templateReplacements.isEmpty()) { Map replacement = new HashMap<>(); templateReplacements.add(replacement); diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/openapi3/TestPoint.java b/src/main/java/org/opengis/cite/ogcapiedr10/openapi3/TestPoint.java index bbc1608..e56286f 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/openapi3/TestPoint.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/openapi3/TestPoint.java @@ -13,98 +13,93 @@ */ public class TestPoint { - private final String serverUrl; - - private final String path; - - private Map predefinedTemplateReplacement; - - private Map contentMediaTypes; - - /** - * Instantiates a TestPoint with UriTemplate but without predefined replacements. - * - * @param serverUrl - * the serverUrl, never null - * @param path - * the path never, null - * @param contentMediaTypes - * the content media types for the GET operation with response "200", may be null - */ - public TestPoint( String serverUrl, String path, Map contentMediaTypes ) { - this( serverUrl, path, Collections.emptyMap(), contentMediaTypes ); - } - - /** - * Instantiates a TestPoint with UriTemplate and predefined replacements. - * - * @param serverUrl - * the serverUrl, never null - * @param path - * the path, never null - * @param predefinedTemplateReplacement - * a list of predefined replacements never null - * @param contentMediaTypes - * the content media types for the GET operation with response "200", may be null - */ - public TestPoint( String serverUrl, String path, Map predefinedTemplateReplacement, - Map contentMediaTypes ) { - this.serverUrl = serverUrl; - this.path = path; - this.predefinedTemplateReplacement = Collections.unmodifiableMap( predefinedTemplateReplacement ); - this.contentMediaTypes = contentMediaTypes; - } - - /** - * - * @return the serverUrl never null - */ - public String getServerUrl() { - return serverUrl; - } - - /** - * @return the path never, null - */ - public String getPath() { - return path; - } - - /** - * @return an unmodifiable mao with predefined replacements, may be empty but never null - */ - public Map getPredefinedTemplateReplacement() { - return predefinedTemplateReplacement; - } - - /** - * @return the content media types for the GET operation with response "200", may be null - */ - public Map getContentMediaTypes() { - return contentMediaTypes; - } - - @Override - public String toString() { - return "Server URL: " + serverUrl + " , Path: " + path + ", Replacements: " + predefinedTemplateReplacement; - } - - @Override - public boolean equals( Object o ) { - if ( this == o ) - return true; - if ( o == null || getClass() != o.getClass() ) - return false; - TestPoint testPoint = (TestPoint) o; - return Objects.equals( serverUrl, testPoint.serverUrl ) - && Objects.equals( path, testPoint.predefinedTemplateReplacement ) - && Objects.equals( predefinedTemplateReplacement, testPoint.path ) - && Objects.equals( contentMediaTypes, testPoint.contentMediaTypes ); - } - - @Override - public int hashCode() { - return Objects.hash( serverUrl, path, predefinedTemplateReplacement, contentMediaTypes ); - } + private final String serverUrl; + + private final String path; + + private Map predefinedTemplateReplacement; + + private Map contentMediaTypes; + + /** + * Instantiates a TestPoint with UriTemplate but without predefined replacements. + * @param serverUrl the serverUrl, never null + * @param path the path never, null + * @param contentMediaTypes the content media types for the GET operation with + * response "200", may be null + */ + public TestPoint(String serverUrl, String path, Map contentMediaTypes) { + this(serverUrl, path, Collections.emptyMap(), contentMediaTypes); + } + + /** + * Instantiates a TestPoint with UriTemplate and predefined replacements. + * @param serverUrl the serverUrl, never null + * @param path the path, never null + * @param predefinedTemplateReplacement a list of predefined replacements never + * null + * @param contentMediaTypes the content media types for the GET operation with + * response "200", may be null + */ + public TestPoint(String serverUrl, String path, Map predefinedTemplateReplacement, + Map contentMediaTypes) { + this.serverUrl = serverUrl; + this.path = path; + this.predefinedTemplateReplacement = Collections.unmodifiableMap(predefinedTemplateReplacement); + this.contentMediaTypes = contentMediaTypes; + } + + /** + * @return the serverUrl never null + */ + public String getServerUrl() { + return serverUrl; + } + + /** + * @return the path never, null + */ + public String getPath() { + return path; + } + + /** + * @return an unmodifiable mao with predefined replacements, may be empty but never + * null + */ + public Map getPredefinedTemplateReplacement() { + return predefinedTemplateReplacement; + } + + /** + * @return the content media types for the GET operation with response "200", may be + * null + */ + public Map getContentMediaTypes() { + return contentMediaTypes; + } + + @Override + public String toString() { + return "Server URL: " + serverUrl + " , Path: " + path + ", Replacements: " + predefinedTemplateReplacement; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + TestPoint testPoint = (TestPoint) o; + return Objects.equals(serverUrl, testPoint.serverUrl) + && Objects.equals(path, testPoint.predefinedTemplateReplacement) + && Objects.equals(predefinedTemplateReplacement, testPoint.path) + && Objects.equals(contentMediaTypes, testPoint.contentMediaTypes); + } + + @Override + public int hashCode() { + return Objects.hash(serverUrl, path, predefinedTemplateReplacement, contentMediaTypes); + } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/openapi3/UriBuilder.java b/src/main/java/org/opengis/cite/ogcapiedr10/openapi3/UriBuilder.java index 178443c..11e7d83 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/openapi3/UriBuilder.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/openapi3/UriBuilder.java @@ -7,7 +7,6 @@ import org.glassfish.jersey.uri.internal.UriPart; import org.glassfish.jersey.uri.internal.UriTemplateParser; - /** * Builds a URL out of a TestPoint. * @@ -15,78 +14,73 @@ */ public class UriBuilder { - private final TestPoint testPoint; + private final TestPoint testPoint; - private final Map templateReplacements = new HashMap<>(); + private final Map templateReplacements = new HashMap<>(); - /** - * @param testPoint - * never null - */ - public UriBuilder( TestPoint testPoint ) { - this.testPoint = testPoint; - this.templateReplacements.putAll( testPoint.getPredefinedTemplateReplacement() ); - } + /** + * @param testPoint never null + */ + public UriBuilder(TestPoint testPoint) { + this.testPoint = testPoint; + this.templateReplacements.putAll(testPoint.getPredefinedTemplateReplacement()); + } - /** - * Adds the collectionName to the URI - * - * @param collectionName - * never null - * @return this UrlBuilder - */ - public UriBuilder collectionName( String collectionName ) { - String templateName = retrieveCollectionNameTemplateName(); - addTemplateReplacement( collectionName, templateName ); - return this; - } + /** + * Adds the collectionName to the URI + * @param collectionName never null + * @return this UrlBuilder + */ + public UriBuilder collectionName(String collectionName) { + String templateName = retrieveCollectionNameTemplateName(); + addTemplateReplacement(collectionName, templateName); + return this; + } - /** - * Adds the featureId to the URI - * - * @param featureId - * never null - * @return this UrlBuilder - */ - public UriBuilder featureId( String featureId ) { - String templateName = retrieveFeatureIdTemplateName(); - addTemplateReplacement( featureId, templateName ); - return this; - } + /** + * Adds the featureId to the URI + * @param featureId never null + * @return this UrlBuilder + */ + public UriBuilder featureId(String featureId) { + String templateName = retrieveFeatureIdTemplateName(); + addTemplateReplacement(featureId, templateName); + return this; + } - /** - * @return this URI, never null - */ - public String buildUrl() { - UriTemplate uriTemplate = new UriTemplate( testPoint.getServerUrl() + testPoint.getPath() ); - return uriTemplate.createURI( templateReplacements ); - } + /** + * @return this URI, never null + */ + public String buildUrl() { + UriTemplate uriTemplate = new UriTemplate(testPoint.getServerUrl() + testPoint.getPath()); + return uriTemplate.createURI(templateReplacements); + } - private void addTemplateReplacement( String collectionName, String templateName ) { - if ( templateName != null ) - templateReplacements.put( templateName, collectionName ); - } + private void addTemplateReplacement(String collectionName, String templateName) { + if (templateName != null) + templateReplacements.put(templateName, collectionName); + } - private String retrieveCollectionNameTemplateName() { - String path = testPoint.getPath(); - UriTemplateParser uriTemplateParser = new UriTemplateParser( path ); - for ( UriPart uriPart : uriTemplateParser.getNames() ) { - String templateName = uriPart.getPart(); - if ( path.startsWith( "/collections/{" + templateName + "}" ) ) - return templateName; - } - return null; - } + private String retrieveCollectionNameTemplateName() { + String path = testPoint.getPath(); + UriTemplateParser uriTemplateParser = new UriTemplateParser(path); + for (UriPart uriPart : uriTemplateParser.getNames()) { + String templateName = uriPart.getPart(); + if (path.startsWith("/collections/{" + templateName + "}")) + return templateName; + } + return null; + } - private String retrieveFeatureIdTemplateName() { - String path = testPoint.getPath(); - UriTemplateParser uriTemplateParser = new UriTemplateParser( path ); - for ( UriPart uriPart : uriTemplateParser.getNames() ) { - String templateName = uriPart.getPart(); - if ( path.endsWith( "items/{" + templateName + "}" ) ) - return templateName; - } - return null; - } + private String retrieveFeatureIdTemplateName() { + String path = testPoint.getPath(); + UriTemplateParser uriTemplateParser = new UriTemplateParser(path); + for (UriPart uriPart : uriTemplateParser.getNames()) { + String templateName = uriPart.getPart(); + if (path.endsWith("items/{" + templateName + "}")) + return templateName; + } + return null; + } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/package-info.java b/src/main/java/org/opengis/cite/ogcapiedr10/package-info.java index 7496a83..371ed96 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/package-info.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/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.ogcapiedr10; +package org.opengis.cite.ogcapiedr10; diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/queries/AbstractProcessor.java b/src/main/java/org/opengis/cite/ogcapiedr10/queries/AbstractProcessor.java index e60640f..25be7a4 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/queries/AbstractProcessor.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/queries/AbstractProcessor.java @@ -5,29 +5,25 @@ import java.net.URL; public abstract class AbstractProcessor { - - public String readStringFromURL(String urlString,int limit) throws Exception - { - URL requestURL = new URL(urlString); - BufferedReader in = new BufferedReader(new InputStreamReader(requestURL.openConnection().getInputStream())); + public String readStringFromURL(String urlString, int limit) throws Exception { + URL requestURL = new URL(urlString); - StringBuilder response = new StringBuilder(); - String inputLine; + BufferedReader in = new BufferedReader(new InputStreamReader(requestURL.openConnection().getInputStream())); - int i = 0; + StringBuilder response = new StringBuilder(); + String inputLine; + int i = 0; - while (((inputLine = in.readLine()) != null) && (i < limit)) - { - response.append(inputLine+"\n"); - i++; - } + while (((inputLine = in.readLine()) != null) && (i < limit)) { + response.append(inputLine + "\n"); + i++; + } + in.close(); - in.close(); - - return response.toString(); - } + return response.toString(); + } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/queries/AreaQueryProcessor.java b/src/main/java/org/opengis/cite/ogcapiedr10/queries/AreaQueryProcessor.java index f32b10a..047d45c 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/queries/AreaQueryProcessor.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/queries/AreaQueryProcessor.java @@ -13,265 +13,257 @@ import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; -public class AreaQueryProcessor extends AbstractProcessor{ - - double sizeOfLensSide = 1d; //in degrees - - public String validateAreaQueryUsingParameters(Set collectionIds, String rootUri, int noOfCollections, RequestSpecification ini){ - StringBuffer sb = new StringBuffer(); - - ArrayList collectionsList = new ArrayList(); - collectionsList.addAll(collectionIds); - - //if noOfCollections is -1 (meaning check box 'Test all collections' was checked) - //use all collections. Otherwise use the specified noOfCollections - int maximum = noOfCollections == -1 ? collectionsList.size() : noOfCollections; - - for (int c = 0; c < maximum; c++) { - - String collectionId = collectionsList.get(c); - - - - boolean supportsAreaQuery = false; - - String url = JsonUtils.getCollectionURL(rootUri, collectionId); - - Response response = JsonUtils.getCollectionResponse(rootUri, collectionId, ini); - JsonPath jsonResponse = response.jsonPath(); - - HashMap dataQueries = jsonResponse.getJsonObject("data_queries"); - - if(dataQueries==null) { //Avoids Nullpointer Exception - sb.append(" The data_queries element is missing from the collection "+collectionId+" ."); - } - - supportsAreaQuery = dataQueries != null && dataQueries.containsKey("area"); - - if(supportsAreaQuery==false) { //Avoids Nullpointer Exception - sb.append(" The area element is missing from the data_queries element of the collection "+collectionId+" ."); - } - - - if (supportsAreaQuery) { - - if(jsonResponse.getJsonObject("parameter_names")==null) { //Avoids Nullpointer Exception - sb.append(" The parameter_names element is missing from the collection "+collectionId+" ."); - } - - HashMap parameterNames = jsonResponse.getJsonObject("parameter_names"); - Set parameterNamesSet = parameterNames.keySet(); - Iterator parameterNamesIterator = parameterNamesSet.iterator(); +public class AreaQueryProcessor extends AbstractProcessor { + + double sizeOfLensSide = 1d; // in degrees + + public String validateAreaQueryUsingParameters(Set collectionIds, String rootUri, int noOfCollections, + RequestSpecification ini) { + StringBuffer sb = new StringBuffer(); + + ArrayList collectionsList = new ArrayList(); + collectionsList.addAll(collectionIds); - parameterNamesIterator.hasNext(); - String sampleParamaterName = parameterNamesIterator.next(); - - if(jsonResponse.getList("crs")==null) { //Avoids Nullpointer Exception - sb.append(" The crs list is missing from the collection "+collectionId+" ."); - } + // if noOfCollections is -1 (meaning check box 'Test all collections' was checked) + // use all collections. Otherwise use the specified noOfCollections + int maximum = noOfCollections == -1 ? collectionsList.size() : noOfCollections; - List crsList = jsonResponse.getList("crs"); + for (int c = 0; c < maximum; c++) { + + String collectionId = collectionsList.get(c); + + boolean supportsAreaQuery = false; + + String url = JsonUtils.getCollectionURL(rootUri, collectionId); + + Response response = JsonUtils.getCollectionResponse(rootUri, collectionId, ini); + JsonPath jsonResponse = response.jsonPath(); + + HashMap dataQueries = jsonResponse.getJsonObject("data_queries"); + + if (dataQueries == null) { // Avoids Nullpointer Exception + sb.append(" The data_queries element is missing from the collection " + collectionId + " ."); + } + + supportsAreaQuery = dataQueries != null && dataQueries.containsKey("area"); + + if (supportsAreaQuery == false) { // Avoids Nullpointer Exception + sb.append(" The area element is missing from the data_queries element of the collection " + collectionId + + " ."); + } + + if (supportsAreaQuery) { + + if (jsonResponse.getJsonObject("parameter_names") == null) { // Avoids + // Nullpointer + // Exception + sb.append(" The parameter_names element is missing from the collection " + collectionId + " ."); + } + + HashMap parameterNames = jsonResponse.getJsonObject("parameter_names"); + Set parameterNamesSet = parameterNames.keySet(); + Iterator parameterNamesIterator = parameterNamesSet.iterator(); + + parameterNamesIterator.hasNext(); + String sampleParamaterName = parameterNamesIterator.next(); + + if (jsonResponse.getList("crs") == null) { // Avoids Nullpointer Exception + sb.append(" The crs list is missing from the collection " + collectionId + " ."); + } + + List crsList = jsonResponse.getList("crs"); + + String supportedCRS = null; + for (int q = 0; q < crsList.size(); q++) { + if (crsList.get(q).equals("CRS:84") || crsList.get(q).equals("CRS84") + || crsList.get(q).equals("EPSG:4326") + || crsList.get(q).contains("www.opengis.net/def/crs/OGC/1.3/CRS84")) { + supportedCRS = crsList.get(q); + } + } + if (supportedCRS == null) { + sb.append(collectionId + " does not support CRS84 CRS. \n"); + + } + + HashMap areaQuery = (HashMap) dataQueries.get("area"); + HashMap link = (HashMap) areaQuery.get("link"); + HashMap variables = (HashMap) link.get("variables"); + ArrayList outputFormatList = (ArrayList) variables.get("output_formats"); + String supportedFormat = null; + for (int f = 0; f < outputFormatList.size(); f++) { + if (outputFormatList.get(f).equals("CoverageJSON") + || outputFormatList.get(f).contains("CoverageJSON")) { // preference + // for + // CoverageJSON + // if + // supported + supportedFormat = outputFormatList.get(f); + } + else if (outputFormatList.get(f).equals("GeoJSON")) { + supportedFormat = outputFormatList.get(f); + } + } + + double medianx = 0d; + double mediany = 0d; + double lminx = 0d; // lens + double lminy = 0d; // lens + double lmaxx = 0d; // lens + double lmaxy = 0d; // lens + + if (jsonResponse.getJsonObject("extent") == null) { // Avoids Nullpointer + // Exception + sb.append(" The extent element is missing from the collection " + collectionId + " ."); + } + + HashMap extent = jsonResponse.getJsonObject("extent"); + if (extent.containsKey("spatial")) { + + HashMap spatial = (HashMap) extent.get("spatial"); + + if (!spatial.containsKey("bbox")) { + sb.append("spatial extent of collection " + collectionId + " missing bbox. \n"); + continue; + } + + ArrayList bboxEnv = (ArrayList) spatial.get("bbox"); // for some + // unknown + // reason the + // library + // returns + // JSON types + // as Integers + // only + + ArrayList bbox = null; + + if (bboxEnv.get(0).getClass().toString().contains("java.lang.Integer") + || bboxEnv.get(0).getClass().toString().contains("java.lang.Double") + || bboxEnv.get(0).getClass().toString().contains("java.lang.Float")) { // for + // EDR + // API + // V1.0.0 + bbox = bboxEnv; + + } + else if (bboxEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { // for + // EDR + // API + // V1.0.1 + bbox = (ArrayList) bboxEnv.get(0); + } + + if (bbox.size() > 3) { + + if (bbox.get(0).getClass().toString().contains("Integer") + || bbox.get(0).getClass().toString().contains("Double") + || bbox.get(0).getClass().toString().contains("Float")) { + double minx = Double.parseDouble(bbox.get(0).toString()); + double miny = Double.parseDouble(bbox.get(1).toString()); + double maxx = Double.parseDouble(bbox.get(2).toString()); + double maxy = Double.parseDouble(bbox.get(3).toString()); + + medianx = minx + ((maxx - minx) / 2d); + mediany = miny + ((maxy - miny) / 2d); + + lminx = medianx - sizeOfLensSide; + lminy = mediany - sizeOfLensSide; + lmaxx = medianx + sizeOfLensSide; + lmaxy = mediany + sizeOfLensSide; + + } + + } + else { + sb.append("bbox of spatial extent of collection" + collectionId + + " has fewer than four coordinates. \n"); + } + + } + else { // if spatial extent is missing + sb.append(" The spatial extent element is missing from the collection " + collectionId + " ."); + } + + String sampleParamaterNameSafe = null; + try { + sampleParamaterNameSafe = URLEncoder.encode(sampleParamaterName, "UTF8"); + } + catch (Exception ex) { + ex.printStackTrace(); + } + + String sampleDateTime = null; + if (extent.containsKey("temporal")) { + + HashMap temporal = (HashMap) extent.get("temporal"); + + if (!temporal.containsKey("interval")) { + + sb.append("Temporal extent of collection " + collectionId + " missing interval. \n"); + continue; + } + + ArrayList intervalEnv = (ArrayList) temporal.get("interval"); + + ArrayList interval = null; + + if (intervalEnv.get(0).getClass().toString().contains("java.lang.String")) { + interval = intervalEnv; + } + else if (intervalEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { + + interval = (ArrayList) intervalEnv.get(0); + } + + if (interval.size() > 1) { + + sampleDateTime = interval.get(0) + "/" + interval.get(1); + + } + + } + else { // if temporal extent is missing + sb.append(" The temporal extent element is missing from the collection " + collectionId + " ."); + } + + String constructedURL = url + "/area?parameter-name=" + sampleParamaterNameSafe + "&coords=" + + "POLYGON((" + lminx + "+" + lminy + "," + lminx + "+" + lmaxy + "," + lmaxx + "+" + lmaxy + + "," + lmaxx + "+" + lminy + "," + lminx + "+" + lminy + "))" + "&crs=" + supportedCRS + "&f=" + + supportedFormat + "&datetime=" + sampleDateTime; + + String pageContent = null; + try { + pageContent = readStringFromURL(constructedURL, 10); // you can use + // Integer.MAX_VALUE + // for no + // limit + + } + catch (Exception ex) { + ex.printStackTrace(); + } - String supportedCRS = null; - for (int q = 0; q < crsList.size(); q++) { - if (crsList.get(q).equals("CRS:84") || - crsList.get(q).equals("CRS84") || - crsList.get(q).equals("EPSG:4326") || - crsList.get(q).contains("www.opengis.net/def/crs/OGC/1.3/CRS84")) { - supportedCRS = crsList.get(q); - } - } - if (supportedCRS == null) { - sb.append(collectionId + " does not support CRS84 CRS. \n"); + if (pageContent != null) { - } + if (pageContent.contains("Coverage") || pageContent.contains("Feature")) { + // do nothing + } + else { + sb.append("Response of Area Query on collection " + collectionId + + " did not contain a recognised encoding. \n"); + } - HashMap areaQuery = (HashMap) dataQueries.get("area"); - HashMap link = (HashMap) areaQuery.get("link"); - HashMap variables = (HashMap) link.get("variables"); - ArrayList outputFormatList = (ArrayList) variables.get("output_formats"); - String supportedFormat = null; - for (int f = 0; f < outputFormatList.size(); f++) { - if (outputFormatList.get(f).equals("CoverageJSON") || outputFormatList.get(f).contains("CoverageJSON")) { //preference for CoverageJSON if supported - supportedFormat = outputFormatList.get(f); - } - else if (outputFormatList.get(f).equals("GeoJSON")) { - supportedFormat = outputFormatList.get(f); - } - } + } + else { + sb.append("Response of Area Query on collection " + collectionId + " was null. \n"); + } - double medianx = 0d; - double mediany = 0d; - double lminx = 0d; //lens - double lminy = 0d; //lens - double lmaxx = 0d; //lens - double lmaxy = 0d; //lens - - - if(jsonResponse.getJsonObject("extent")==null) { //Avoids Nullpointer Exception - sb.append(" The extent element is missing from the collection "+collectionId+" ."); - } - - HashMap extent = jsonResponse.getJsonObject("extent"); - if (extent.containsKey("spatial")) { - - HashMap spatial = (HashMap) extent.get("spatial"); - - if (!spatial.containsKey("bbox")) - { - sb.append("spatial extent of collection "+collectionId+" missing bbox. \n"); - continue; - } - - ArrayList bboxEnv = (ArrayList) spatial.get("bbox"); // for some unknown reason the library returns JSON types as Integers only - - - ArrayList bbox = null; - - if(bboxEnv.get(0).getClass().toString().contains("java.lang.Integer") || - bboxEnv.get(0).getClass().toString().contains("java.lang.Double")|| - bboxEnv.get(0).getClass().toString().contains("java.lang.Float")) { //for EDR API V1.0.0 - bbox = bboxEnv; - - } - else if(bboxEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { //for EDR API V1.0.1 - bbox = (ArrayList) bboxEnv.get(0); - } - - - - if (bbox.size() > 3) { - - if (bbox.get(0).getClass().toString().contains("Integer") - || bbox.get(0).getClass().toString().contains("Double") - || bbox.get(0).getClass().toString().contains("Float")) { - double minx = Double.parseDouble(bbox.get(0).toString()); - double miny = Double.parseDouble(bbox.get(1).toString()); - double maxx = Double.parseDouble(bbox.get(2).toString()); - double maxy = Double.parseDouble(bbox.get(3).toString()); - - medianx = minx + ((maxx - minx) / 2d); - mediany = miny + ((maxy - miny) / 2d); - - lminx = medianx - sizeOfLensSide; - lminy = mediany - sizeOfLensSide; - lmaxx = medianx + sizeOfLensSide; - lmaxy = mediany + sizeOfLensSide; - - - - } - - } else { - sb.append("bbox of spatial extent of collection" + collectionId - + " has fewer than four coordinates. \n"); - } - - - } - else { //if spatial extent is missing - sb.append(" The spatial extent element is missing from the collection "+collectionId+" ."); - } - - - String sampleParamaterNameSafe = null; - try { - sampleParamaterNameSafe = URLEncoder.encode(sampleParamaterName,"UTF8"); - } - catch(Exception ex) {ex.printStackTrace();} - - - String sampleDateTime = null; - if (extent.containsKey("temporal")) { - - - HashMap temporal = (HashMap) extent.get("temporal"); - - if (!temporal.containsKey("interval")) - { - - sb.append("Temporal extent of collection "+collectionId+" missing interval. \n"); - continue; - } - - - ArrayList intervalEnv = (ArrayList) temporal.get("interval"); - - - ArrayList interval = null; - - if(intervalEnv.get(0).getClass().toString().contains("java.lang.String")) { - interval = intervalEnv; - } - else if(intervalEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { - - interval = (ArrayList) intervalEnv.get(0); - } - - - if (interval.size() > 1) { - - - sampleDateTime = interval.get(0)+"/"+interval.get(1); - - - } - - } - else { //if temporal extent is missing - sb.append(" The temporal extent element is missing from the collection "+collectionId+" ."); - } - - - - - String constructedURL = url + "/area?parameter-name=" - + sampleParamaterNameSafe + "&coords=" + "POLYGON((" + - lminx + "+"+ lminy + ","+ - lminx + "+"+ lmaxy + ","+ - lmaxx + "+"+ lmaxy + ","+ - lmaxx + "+"+ lminy + ","+ - lminx + "+"+ lminy + - "))" + "&crs=" + supportedCRS + "&f=" + supportedFormat+"&datetime="+sampleDateTime; - - - - String pageContent = null; - try { - pageContent = readStringFromURL(constructedURL,10); //you can use Integer.MAX_VALUE for no limit - - } - catch(Exception ex) { ex.printStackTrace();} - - if(pageContent!=null) { - - if(pageContent.contains("Coverage") || pageContent.contains("Feature")) { - //do nothing - } - else { - sb.append("Response of Area Query on collection " + collectionId - + " did not contain a recognised encoding. \n"); - } - - } - else { - sb.append("Response of Area Query on collection " + collectionId - + " was null. \n"); - } - - - - } - - - - } - - - - return sb.toString(); - } + } + } + return sb.toString(); + } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/queries/CorridorQueryProcessor.java b/src/main/java/org/opengis/cite/ogcapiedr10/queries/CorridorQueryProcessor.java index 31ef527..7142817 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/queries/CorridorQueryProcessor.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/queries/CorridorQueryProcessor.java @@ -13,270 +13,268 @@ import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; -public class CorridorQueryProcessor extends AbstractProcessor{ - - double sizeOfLensSide = 1d; //in degrees - double corridorWidth = 2; - String corridorWidthUnit = "m"; - public final String queryTypeNotSupported = "None of the collections support this query type. Increase the number of collections to parse."; - - - public String validateCorridorQueryUsingParameters(Set collectionIds, String rootUri, int noOfCollections, RequestSpecification ini){ - StringBuffer sb = new StringBuffer(); - - ArrayList collectionsList = new ArrayList(); - collectionsList.addAll(collectionIds); - - int numberOfCollectionsWithCorridorSupport = 0; - - //if noOfCollections is -1 (meaning check box 'Test all collections' was checked) - //use all collections. Otherwise use the specified noOfCollections - int maximum = noOfCollections == -1 ? collectionsList.size() : noOfCollections; - - for (int c = 0; c < maximum; c++) { - - String collectionId = collectionsList.get(c); - - - - boolean supportsCorridorQuery = false; - - String url = JsonUtils.getCollectionURL(rootUri, collectionId); +public class CorridorQueryProcessor extends AbstractProcessor { - Response response = JsonUtils.getCollectionResponse(rootUri, collectionId, ini); - JsonPath jsonResponse = response.jsonPath(); - - HashMap dataQueries = jsonResponse.getJsonObject("data_queries"); - - if(dataQueries==null) { //Avoids Nullpointer Exception - sb.append(" The data_queries element is missing from the collection "+collectionId+" ."); - } - supportsCorridorQuery = dataQueries != null && dataQueries.containsKey("corridor"); - - if(supportsCorridorQuery==false) { //Avoids Nullpointer Exception - sb.append(" The corridor element is missing from the data_queries element of the collection "+collectionId+" ."); - } - - - - if (supportsCorridorQuery) { - - numberOfCollectionsWithCorridorSupport++; - - if(jsonResponse.getJsonObject("parameter_names")==null) { //Avoids Nullpointer Exception - sb.append(" The parameter_names element is missing from the collection "+collectionId+" ."); - } + double sizeOfLensSide = 1d; // in degrees - HashMap parameterNames = jsonResponse.getJsonObject("parameter_names"); - Set parameterNamesSet = parameterNames.keySet(); - Iterator parameterNamesIterator = parameterNamesSet.iterator(); + double corridorWidth = 2; - parameterNamesIterator.hasNext(); - String sampleParamaterName = parameterNamesIterator.next(); + String corridorWidthUnit = "m"; - if(jsonResponse.getList("crs")==null) { //Avoids Nullpointer Exception - sb.append(" The crs list is missing from the collection "+collectionId+" ."); - } - - List crsList = jsonResponse.getList("crs"); + public final String queryTypeNotSupported = "None of the collections support this query type. Increase the number of collections to parse."; - String supportedCRS = null; - for (int q = 0; q < crsList.size(); q++) { - if (crsList.get(q).equals("CRS:84") || - crsList.get(q).equals("CRS84") || - crsList.get(q).equals("EPSG:4326") || - crsList.get(q).contains("www.opengis.net/def/crs/OGC/1.3/CRS84")) { - supportedCRS = crsList.get(q); - } - } - if (supportedCRS == null) { - sb.append(collectionId + " does not support CRS84 CRS. \n"); + public String validateCorridorQueryUsingParameters(Set collectionIds, String rootUri, int noOfCollections, + RequestSpecification ini) { + StringBuffer sb = new StringBuffer(); - } + ArrayList collectionsList = new ArrayList(); + collectionsList.addAll(collectionIds); - HashMap corridorQuery = (HashMap) dataQueries.get("corridor"); - HashMap link = (HashMap) corridorQuery.get("link"); - HashMap variables = (HashMap) link.get("variables"); - ArrayList outputFormatList = (ArrayList) variables.get("output_formats"); - String supportedFormat = null; - for (int f = 0; f < outputFormatList.size(); f++) { - if (outputFormatList.get(f).equals("CoverageJSON") || outputFormatList.get(f).contains("CoverageJSON")) { //preference for CoverageJSON if supported - supportedFormat = outputFormatList.get(f); - } - else if (outputFormatList.get(f).equals("GeoJSON")) { - supportedFormat = outputFormatList.get(f); - } - } + int numberOfCollectionsWithCorridorSupport = 0; - double medianx = 0d; - double mediany = 0d; - double lminx = 0d; //lens - double lminy = 0d; //lens - double lmaxx = 0d; //lens - double lmaxy = 0d; //lens + // if noOfCollections is -1 (meaning check box 'Test all collections' was checked) + // use all collections. Otherwise use the specified noOfCollections + int maximum = noOfCollections == -1 ? collectionsList.size() : noOfCollections; - HashMap extent = jsonResponse.getJsonObject("extent"); - if (extent.containsKey("spatial")) { + for (int c = 0; c < maximum; c++) { - HashMap spatial = (HashMap) extent.get("spatial"); + String collectionId = collectionsList.get(c); - if (!spatial.containsKey("bbox")) - { - sb.append("spatial extent of collection "+collectionId+" missing bbox. \n"); - continue; - } + boolean supportsCorridorQuery = false; - ArrayList bboxEnv = (ArrayList) spatial.get("bbox"); // for some unknown reason the library returns JSON types as Integers only + String url = JsonUtils.getCollectionURL(rootUri, collectionId); + Response response = JsonUtils.getCollectionResponse(rootUri, collectionId, ini); + JsonPath jsonResponse = response.jsonPath(); - ArrayList bbox = null; + HashMap dataQueries = jsonResponse.getJsonObject("data_queries"); + + if (dataQueries == null) { // Avoids Nullpointer Exception + sb.append(" The data_queries element is missing from the collection " + collectionId + " ."); + } + supportsCorridorQuery = dataQueries != null && dataQueries.containsKey("corridor"); + + if (supportsCorridorQuery == false) { // Avoids Nullpointer Exception + sb.append(" The corridor element is missing from the data_queries element of the collection " + + collectionId + " ."); + } + + if (supportsCorridorQuery) { + + numberOfCollectionsWithCorridorSupport++; + + if (jsonResponse.getJsonObject("parameter_names") == null) { // Avoids + // Nullpointer + // Exception + sb.append(" The parameter_names element is missing from the collection " + collectionId + " ."); + } + + HashMap parameterNames = jsonResponse.getJsonObject("parameter_names"); + Set parameterNamesSet = parameterNames.keySet(); + Iterator parameterNamesIterator = parameterNamesSet.iterator(); + + parameterNamesIterator.hasNext(); + String sampleParamaterName = parameterNamesIterator.next(); + + if (jsonResponse.getList("crs") == null) { // Avoids Nullpointer Exception + sb.append(" The crs list is missing from the collection " + collectionId + " ."); + } + + List crsList = jsonResponse.getList("crs"); + + String supportedCRS = null; + for (int q = 0; q < crsList.size(); q++) { + if (crsList.get(q).equals("CRS:84") || crsList.get(q).equals("CRS84") + || crsList.get(q).equals("EPSG:4326") + || crsList.get(q).contains("www.opengis.net/def/crs/OGC/1.3/CRS84")) { + supportedCRS = crsList.get(q); + } + } + if (supportedCRS == null) { + sb.append(collectionId + " does not support CRS84 CRS. \n"); + + } + + HashMap corridorQuery = (HashMap) dataQueries.get("corridor"); + HashMap link = (HashMap) corridorQuery.get("link"); + HashMap variables = (HashMap) link.get("variables"); + ArrayList outputFormatList = (ArrayList) variables.get("output_formats"); + String supportedFormat = null; + for (int f = 0; f < outputFormatList.size(); f++) { + if (outputFormatList.get(f).equals("CoverageJSON") + || outputFormatList.get(f).contains("CoverageJSON")) { // preference + // for + // CoverageJSON + // if + // supported + supportedFormat = outputFormatList.get(f); + } + else if (outputFormatList.get(f).equals("GeoJSON")) { + supportedFormat = outputFormatList.get(f); + } + } + + double medianx = 0d; + double mediany = 0d; + double lminx = 0d; // lens + double lminy = 0d; // lens + double lmaxx = 0d; // lens + double lmaxy = 0d; // lens + + HashMap extent = jsonResponse.getJsonObject("extent"); + if (extent.containsKey("spatial")) { + + HashMap spatial = (HashMap) extent.get("spatial"); + + if (!spatial.containsKey("bbox")) { + sb.append("spatial extent of collection " + collectionId + " missing bbox. \n"); + continue; + } + + ArrayList bboxEnv = (ArrayList) spatial.get("bbox"); // for some + // unknown + // reason the + // library + // returns + // JSON types + // as Integers + // only + + ArrayList bbox = null; + + if (bboxEnv.get(0).getClass().toString().contains("java.lang.Integer") + || bboxEnv.get(0).getClass().toString().contains("java.lang.Double") + || bboxEnv.get(0).getClass().toString().contains("java.lang.Float")) { // for + // EDR + // API + // V1.0.0 + bbox = bboxEnv; + + } + else if (bboxEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { // for + // EDR + // API + // V1.0.1 + bbox = (ArrayList) bboxEnv.get(0); + } + + if (bbox.size() > 3) { + + if (bbox.get(0).getClass().toString().contains("Integer") + || bbox.get(0).getClass().toString().contains("Double") + || bbox.get(0).getClass().toString().contains("Float")) { + double minx = Double.parseDouble(bbox.get(0).toString()); + double miny = Double.parseDouble(bbox.get(1).toString()); + double maxx = Double.parseDouble(bbox.get(2).toString()); + double maxy = Double.parseDouble(bbox.get(3).toString()); + + medianx = minx + ((maxx - minx) / 2d); + mediany = miny + ((maxy - miny) / 2d); + + lminx = medianx - sizeOfLensSide; + lminy = mediany - sizeOfLensSide; + lmaxx = medianx + sizeOfLensSide; + lmaxy = mediany + sizeOfLensSide; + + } + + } + else { + sb.append("bbox of spatial extent of collection" + collectionId + + " has fewer than four coordinates. \n"); + } + + } + else { // if spatial extent is missing + sb.append(" The spatial extent element is missing from the collection " + collectionId + " ."); + } + + String sampleParamaterNameSafe = null; + try { + sampleParamaterNameSafe = URLEncoder.encode(sampleParamaterName, "UTF8"); + } + catch (Exception ex) { + ex.printStackTrace(); + } + + String sampleDateTime = null; + if (extent.containsKey("temporal")) { + + HashMap temporal = (HashMap) extent.get("temporal"); + + if (!temporal.containsKey("interval")) { + + sb.append("Temporal extent of collection " + collectionId + " missing interval. \n"); + continue; + } + + ArrayList intervalEnv = (ArrayList) temporal.get("interval"); + + ArrayList interval = null; + + if (intervalEnv.get(0).getClass().toString().contains("java.lang.String")) { + interval = intervalEnv; + } + else if (intervalEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { + + interval = (ArrayList) intervalEnv.get(0); + } + + if (interval.size() > 1) { + + sampleDateTime = interval.get(0) + "/" + interval.get(1); + + } + + } + else { // if temporal extent is missing + sb.append(" The temporal extent element is missing from the collection " + collectionId + " ."); + } + + String constructedURL = url + "/corridor?parameter-name=" + sampleParamaterNameSafe + "&coords=" + + "LINESTRING(" + lminx + "+" + lminy + "," + medianx + "+" + mediany + "," + lmaxx + "+" + + lmaxy + ")" + "&corridor-width=" + corridorWidth + "&width-units=" + corridorWidthUnit + "&f=" + + supportedFormat + "&datetime=" + sampleDateTime; + System.out.println("C " + constructedURL); + + String pageContent = null; + try { + pageContent = readStringFromURL(constructedURL, 10); // you can use + // Integer.MAX_VALUE + // for no + // limit + + } + catch (Exception ex) { + ex.printStackTrace(); + } + + if (pageContent != null) { + + if (pageContent.contains("Coverage") || pageContent.contains("Feature")) { + // do nothing + } + else { + sb.append("Response of Corridor Query on collection " + collectionId + + " did not contain a recognised encoding. \n"); + } - if(bboxEnv.get(0).getClass().toString().contains("java.lang.Integer") || - bboxEnv.get(0).getClass().toString().contains("java.lang.Double")|| - bboxEnv.get(0).getClass().toString().contains("java.lang.Float")) { //for EDR API V1.0.0 - bbox = bboxEnv; + } + else { + sb.append("Response of Corridor Query on collection " + collectionId + " was null. \n"); + } - } - else if(bboxEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { //for EDR API V1.0.1 - bbox = (ArrayList) bboxEnv.get(0); - } + } + else { // does not support Corridor queries + continue; + } + } + if (numberOfCollectionsWithCorridorSupport == 0) { + sb.append(queryTypeNotSupported + "\n"); + } + return sb.toString(); + } - if (bbox.size() > 3) { - - if (bbox.get(0).getClass().toString().contains("Integer") - || bbox.get(0).getClass().toString().contains("Double") - || bbox.get(0).getClass().toString().contains("Float")) { - double minx = Double.parseDouble(bbox.get(0).toString()); - double miny = Double.parseDouble(bbox.get(1).toString()); - double maxx = Double.parseDouble(bbox.get(2).toString()); - double maxy = Double.parseDouble(bbox.get(3).toString()); - - medianx = minx + ((maxx - minx) / 2d); - mediany = miny + ((maxy - miny) / 2d); - - lminx = medianx - sizeOfLensSide; - lminy = mediany - sizeOfLensSide; - lmaxx = medianx + sizeOfLensSide; - lmaxy = mediany + sizeOfLensSide; - - - - } - - } else { - sb.append("bbox of spatial extent of collection" + collectionId - + " has fewer than four coordinates. \n"); - } - - - } - else { //if spatial extent is missing - sb.append(" The spatial extent element is missing from the collection "+collectionId+" ."); - } - - String sampleParamaterNameSafe = null; - try { - sampleParamaterNameSafe = URLEncoder.encode(sampleParamaterName,"UTF8"); - } - catch(Exception ex) {ex.printStackTrace();} - - - String sampleDateTime = null; - if (extent.containsKey("temporal")) { - - - HashMap temporal = (HashMap) extent.get("temporal"); - - if (!temporal.containsKey("interval")) - { - - sb.append("Temporal extent of collection "+collectionId+" missing interval. \n"); - continue; - } - - - ArrayList intervalEnv = (ArrayList) temporal.get("interval"); - - - ArrayList interval = null; - - if(intervalEnv.get(0).getClass().toString().contains("java.lang.String")) { - interval = intervalEnv; - } - else if(intervalEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { - - interval = (ArrayList) intervalEnv.get(0); - } - - - if (interval.size() > 1) { - - - sampleDateTime = interval.get(0)+"/"+interval.get(1); - - - } - - } - else { //if temporal extent is missing - sb.append(" The temporal extent element is missing from the collection "+collectionId+" ."); - } - - - - String constructedURL = url + "/corridor?parameter-name=" - + sampleParamaterNameSafe + "&coords=" + "LINESTRING(" + - lminx + "+"+ lminy + ","+ - medianx + "+"+ mediany + ","+ - lmaxx + "+"+ lmaxy + - ")" + "&corridor-width="+corridorWidth+"&width-units="+corridorWidthUnit+"&f=" + supportedFormat+"&datetime="+sampleDateTime; - System.out.println("C "+constructedURL); - - - - String pageContent = null; - try { - pageContent = readStringFromURL(constructedURL,10); //you can use Integer.MAX_VALUE for no limit - - } - catch(Exception ex) { ex.printStackTrace();} - - if(pageContent!=null) { - - if(pageContent.contains("Coverage") || pageContent.contains("Feature")) { - //do nothing - } - else { - sb.append("Response of Corridor Query on collection " + collectionId - + " did not contain a recognised encoding. \n"); - } - - } - else { - sb.append("Response of Corridor Query on collection " + collectionId - + " was null. \n"); - } - - - - } - else { //does not support Corridor queries - continue; - } - - - - } - if(numberOfCollectionsWithCorridorSupport==0) { - sb.append(queryTypeNotSupported+"\n"); - } - - - return sb.toString(); - } - - - } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/queries/PositionQueryProcessor.java b/src/main/java/org/opengis/cite/ogcapiedr10/queries/PositionQueryProcessor.java index bb38d2f..9e091f9 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/queries/PositionQueryProcessor.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/queries/PositionQueryProcessor.java @@ -13,238 +13,239 @@ import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; -public class PositionQueryProcessor extends AbstractProcessor{ - - public String validatePositionQueryUsingParameters(Set collectionIds, String rootUri, int noOfCollections, RequestSpecification ini){ - StringBuffer sb = new StringBuffer(); - ArrayList collectionsList = new ArrayList(); - collectionsList.addAll(collectionIds); - - //if noOfCollections is -1 (meaning check box 'Test all collections' was checked) - //use all collections. Otherwise use the specified noOfCollections - int maximum = noOfCollections == -1 ? collectionsList.size() : noOfCollections; - - for (int c = 0; c < maximum; c++) { - - String collectionId = collectionsList.get(c); - - boolean supportsPositionQuery = false; - - String url = JsonUtils.getCollectionURL(rootUri, collectionId); - - Response response = JsonUtils.getCollectionResponse(rootUri, collectionId, ini); - JsonPath jsonResponse = response.jsonPath(); - - HashMap dataQueries = jsonResponse.getJsonObject("data_queries"); - - if(dataQueries==null) { //Avoids Nullpointer Exception - sb.append(" The data_queries element is missing from the collection "+collectionId+" ."); - } - - supportsPositionQuery = dataQueries != null && dataQueries.containsKey("position"); - - if(supportsPositionQuery==false) { //Avoids Nullpointer Exception - sb.append(" The position element is missing from the data_queries element of the collection "+collectionId+" ."); - } - - - if (supportsPositionQuery) { - - if(jsonResponse.getJsonObject("parameter_names")==null) { //Avoids Nullpointer Exception - sb.append(" The parameter_names element is missing from the collection "+collectionId+" ."); - } - - HashMap parameterNames = jsonResponse.getJsonObject("parameter_names"); - Set parameterNamesSet = parameterNames.keySet(); - Iterator parameterNamesIterator = parameterNamesSet.iterator(); - - parameterNamesIterator.hasNext(); - String sampleParamaterName = parameterNamesIterator.next(); - - if(jsonResponse.getList("crs")==null) { //Avoids Nullpointer Exception - sb.append(" The crs list is missing from the collection "+collectionId+" ."); - } - - List crsList = jsonResponse.getList("crs"); - - String supportedCRS = null; - for (int q = 0; q < crsList.size(); q++) { - if (crsList.get(q).equals("CRS:84") || - crsList.get(q).equals("CRS84") || - crsList.get(q).equals("EPSG:4326") || - crsList.get(q).contains("www.opengis.net/def/crs/OGC/1.3/CRS84")) { - supportedCRS = crsList.get(q); - } - } - if (supportedCRS == null) { - sb.append(collectionId + " does not support CRS84 CRS. \n"); - - } - - HashMap positionQuery = (HashMap) dataQueries.get("position"); - HashMap link = (HashMap) positionQuery.get("link"); - HashMap variables = (HashMap) link.get("variables"); - ArrayList outputFormatList = (ArrayList) variables.get("output_formats"); - String supportedFormat = null; - for (int f = 0; f < outputFormatList.size(); f++) { - if (outputFormatList.get(f).equals("CoverageJSON") || outputFormatList.get(f).contains("CoverageJSON")) { //preference for CoverageJSON if supported - supportedFormat = outputFormatList.get(f); - } - else if (outputFormatList.get(f).equals("GeoJSON")) { - supportedFormat = outputFormatList.get(f); - } - } +public class PositionQueryProcessor extends AbstractProcessor { - double medianx = 0d; - double mediany = 0d; + public String validatePositionQueryUsingParameters(Set collectionIds, String rootUri, int noOfCollections, + RequestSpecification ini) { + StringBuffer sb = new StringBuffer(); + ArrayList collectionsList = new ArrayList(); + collectionsList.addAll(collectionIds); + + // if noOfCollections is -1 (meaning check box 'Test all collections' was checked) + // use all collections. Otherwise use the specified noOfCollections + int maximum = noOfCollections == -1 ? collectionsList.size() : noOfCollections; + + for (int c = 0; c < maximum; c++) { + + String collectionId = collectionsList.get(c); + + boolean supportsPositionQuery = false; + + String url = JsonUtils.getCollectionURL(rootUri, collectionId); + + Response response = JsonUtils.getCollectionResponse(rootUri, collectionId, ini); + JsonPath jsonResponse = response.jsonPath(); + + HashMap dataQueries = jsonResponse.getJsonObject("data_queries"); + + if (dataQueries == null) { // Avoids Nullpointer Exception + sb.append(" The data_queries element is missing from the collection " + collectionId + " ."); + } + + supportsPositionQuery = dataQueries != null && dataQueries.containsKey("position"); + + if (supportsPositionQuery == false) { // Avoids Nullpointer Exception + sb.append(" The position element is missing from the data_queries element of the collection " + + collectionId + " ."); + } + + if (supportsPositionQuery) { + + if (jsonResponse.getJsonObject("parameter_names") == null) { // Avoids + // Nullpointer + // Exception + sb.append(" The parameter_names element is missing from the collection " + collectionId + " ."); + } + + HashMap parameterNames = jsonResponse.getJsonObject("parameter_names"); + Set parameterNamesSet = parameterNames.keySet(); + Iterator parameterNamesIterator = parameterNamesSet.iterator(); + + parameterNamesIterator.hasNext(); + String sampleParamaterName = parameterNamesIterator.next(); + + if (jsonResponse.getList("crs") == null) { // Avoids Nullpointer Exception + sb.append(" The crs list is missing from the collection " + collectionId + " ."); + } + + List crsList = jsonResponse.getList("crs"); + + String supportedCRS = null; + for (int q = 0; q < crsList.size(); q++) { + if (crsList.get(q).equals("CRS:84") || crsList.get(q).equals("CRS84") + || crsList.get(q).equals("EPSG:4326") + || crsList.get(q).contains("www.opengis.net/def/crs/OGC/1.3/CRS84")) { + supportedCRS = crsList.get(q); + } + } + if (supportedCRS == null) { + sb.append(collectionId + " does not support CRS84 CRS. \n"); + + } + + HashMap positionQuery = (HashMap) dataQueries.get("position"); + HashMap link = (HashMap) positionQuery.get("link"); + HashMap variables = (HashMap) link.get("variables"); + ArrayList outputFormatList = (ArrayList) variables.get("output_formats"); + String supportedFormat = null; + for (int f = 0; f < outputFormatList.size(); f++) { + if (outputFormatList.get(f).equals("CoverageJSON") + || outputFormatList.get(f).contains("CoverageJSON")) { // preference + // for + // CoverageJSON + // if + // supported + supportedFormat = outputFormatList.get(f); + } + else if (outputFormatList.get(f).equals("GeoJSON")) { + supportedFormat = outputFormatList.get(f); + } + } + + double medianx = 0d; + double mediany = 0d; + + HashMap extent = jsonResponse.getJsonObject("extent"); + if (extent.containsKey("spatial")) { + + HashMap spatial = (HashMap) extent.get("spatial"); + + if (!spatial.containsKey("bbox")) { + sb.append("spatial extent of collection " + collectionId + " missing bbox. \n"); + continue; + } + + ArrayList bboxEnv = (ArrayList) spatial.get("bbox"); // for some + // unknown + // reason the + // library + // returns + // JSON types + // as Integers + // only + + ArrayList bbox = null; + + if (bboxEnv.get(0).getClass().toString().contains("java.lang.Integer") + || bboxEnv.get(0).getClass().toString().contains("java.lang.Double") + || bboxEnv.get(0).getClass().toString().contains("java.lang.Float")) { // for + // EDR + // API + // V1.0.0 + bbox = bboxEnv; + + } + else if (bboxEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { // for + // EDR + // API + // V1.0.1 + bbox = (ArrayList) bboxEnv.get(0); + } + + if (bbox.size() > 3) { + + if (bbox.get(0).getClass().toString().contains("Integer") + || bbox.get(0).getClass().toString().contains("Double") + || bbox.get(0).getClass().toString().contains("Float")) { + double minx = Double.parseDouble(bbox.get(0).toString()); + double miny = Double.parseDouble(bbox.get(1).toString()); + double maxx = Double.parseDouble(bbox.get(2).toString()); + double maxy = Double.parseDouble(bbox.get(3).toString()); + + medianx = minx + ((maxx - minx) / 2d); + mediany = miny + ((maxy - miny) / 2d); + + } + + } + else { + sb.append("bbox of spatial extent of collection" + collectionId + + " has fewer than four coordinates. \n"); + } + + } + else { // if spatial extent is missing + sb.append(" The spatial extent element is missing from the collection " + collectionId + " ."); + } + + String sampleParamaterNameSafe = null; + try { + sampleParamaterNameSafe = URLEncoder.encode(sampleParamaterName, "UTF8"); + } + catch (Exception ex) { + ex.printStackTrace(); + } + + String sampleDateTime = null; + if (extent.containsKey("temporal")) { + + HashMap temporal = (HashMap) extent.get("temporal"); + + if (!temporal.containsKey("interval")) { + + sb.append("Temporal extent of collection " + collectionId + " missing interval. \n"); + continue; + } + + ArrayList intervalEnv = (ArrayList) temporal.get("interval"); + + ArrayList interval = null; + + if (intervalEnv.get(0).getClass().toString().contains("java.lang.String")) { + interval = intervalEnv; + } + else if (intervalEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { + + interval = (ArrayList) intervalEnv.get(0); + } + + if (interval.size() > 1) { - HashMap extent = jsonResponse.getJsonObject("extent"); - if (extent.containsKey("spatial")) { + sampleDateTime = interval.get(0) + "/" + interval.get(1); + + } - HashMap spatial = (HashMap) extent.get("spatial"); + } + else { // if temporal extent is missing + sb.append(" The temporal extent element is missing from the collection " + collectionId + " ."); + } + + String constructedURL = url + "/position?parameter-name=" + sampleParamaterNameSafe + "&coords=" + + "POINT(" + medianx + "+" + mediany + ")" + "&crs=" + supportedCRS + "&f=" + supportedFormat + + "&datetime=" + sampleDateTime; + + String pageContent = null; + try { + pageContent = readStringFromURL(constructedURL, 10); // you can use + // Integer.MAX_VALUE + // for no + // limit - if (!spatial.containsKey("bbox")) - { - sb.append("spatial extent of collection "+collectionId+" missing bbox. \n"); - continue; - } + } + catch (Exception ex) { + ex.printStackTrace(); + } - ArrayList bboxEnv = (ArrayList) spatial.get("bbox"); // for some unknown reason the library returns JSON types as Integers only + if (pageContent != null) { + + if (pageContent.contains("Coverage") || pageContent.contains("Feature")) { + // do nothing + } + else { + sb.append("Response of Position Query on collection " + collectionId + + " did not contain a recognised encoding. \n"); + } + } + else { + sb.append("Response of Position Query on collection " + collectionId + " was null. \n"); + } - ArrayList bbox = null; - - if(bboxEnv.get(0).getClass().toString().contains("java.lang.Integer") || - bboxEnv.get(0).getClass().toString().contains("java.lang.Double")|| - bboxEnv.get(0).getClass().toString().contains("java.lang.Float")) { //for EDR API V1.0.0 - bbox = bboxEnv; - - } - else if(bboxEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { //for EDR API V1.0.1 - bbox = (ArrayList) bboxEnv.get(0); - } - - if (bbox.size() > 3) { - - if (bbox.get(0).getClass().toString().contains("Integer") - || bbox.get(0).getClass().toString().contains("Double") - || bbox.get(0).getClass().toString().contains("Float")) { - double minx = Double.parseDouble(bbox.get(0).toString()); - double miny = Double.parseDouble(bbox.get(1).toString()); - double maxx = Double.parseDouble(bbox.get(2).toString()); - double maxy = Double.parseDouble(bbox.get(3).toString()); - - - - medianx = minx + ((maxx - minx) / 2d); - mediany = miny + ((maxy - miny) / 2d); - - } - - } else { - sb.append("bbox of spatial extent of collection" + collectionId - + " has fewer than four coordinates. \n"); - } - - } - else { //if spatial extent is missing - sb.append(" The spatial extent element is missing from the collection "+collectionId+" ."); - } - - String sampleParamaterNameSafe = null; - try { - sampleParamaterNameSafe = URLEncoder.encode(sampleParamaterName,"UTF8"); - } - catch(Exception ex) {ex.printStackTrace();} - - String sampleDateTime = null; - if (extent.containsKey("temporal")) { - - - HashMap temporal = (HashMap) extent.get("temporal"); - - if (!temporal.containsKey("interval")) - { - - sb.append("Temporal extent of collection "+collectionId+" missing interval. \n"); - continue; - } - - - ArrayList intervalEnv = (ArrayList) temporal.get("interval"); - - - ArrayList interval = null; - - if(intervalEnv.get(0).getClass().toString().contains("java.lang.String")) { - interval = intervalEnv; - } - else if(intervalEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { - - interval = (ArrayList) intervalEnv.get(0); - } - - - - - if (interval.size() > 1) { - - - sampleDateTime = interval.get(0)+"/"+interval.get(1); - - - } - - } - else { //if temporal extent is missing - sb.append(" The temporal extent element is missing from the collection "+collectionId+" ."); - } - - - - String constructedURL = url + "/position?parameter-name=" - + sampleParamaterNameSafe + "&coords=" + "POINT(" + medianx + "+" - + mediany + ")" + "&crs=" + supportedCRS + "&f=" + supportedFormat+"&datetime="+sampleDateTime; - - - - - String pageContent = null; - try { - pageContent = readStringFromURL(constructedURL,10); //you can use Integer.MAX_VALUE for no limit - - } - catch(Exception ex) {ex.printStackTrace();} - - if(pageContent!=null) { - - if(pageContent.contains("Coverage") || pageContent.contains("Feature")) { - //do nothing - } - else { - sb.append("Response of Position Query on collection " + collectionId - + " did not contain a recognised encoding. \n"); - } - - } - else { - sb.append("Response of Position Query on collection " + collectionId - + " was null. \n"); - } - - - - - } - - - - } - - return sb.toString(); - } - + } + } + return sb.toString(); + } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/queries/QueryCollections.java b/src/main/java/org/opengis/cite/ogcapiedr10/queries/QueryCollections.java index 2beebe6..410af40 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/queries/QueryCollections.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/queries/QueryCollections.java @@ -34,18 +34,17 @@ */ public class QueryCollections extends CommonFixture { - private int noOfCollections = 0; - + protected URI iut; - + @BeforeClass public void noOfCollections(ITestContext testContext) { Object noOfCollections = testContext.getSuite().getAttribute(NO_OF_COLLECTIONS.getName()); if (noOfCollections != null) { this.noOfCollections = (Integer) noOfCollections; } - } + } @DataProvider(name = "collectionIDs") public Iterator collectionIDs(ITestContext testContext) { @@ -80,30 +79,33 @@ private Set extractCollectionIDs(URI rootUri) { } /** - * Abstract Test 34 : Validate that an error is returned by a Position query if no query parameters are specified. - * Abstract Test 50 : Validate that an error is returned by a Area query if no query parameters are specified. - * Abstract Test 66 : Validate that an error is returned by a Cube query if no query parameters are specified. - * Abstract Test 82 : Validate that an error is returned by a Trajectory query if no query parameters are specified. - * Abstract Test 100 : Validate that an error is returned by a Corridor query if no query parameters are specified. - * Abstract Test 136 : Validate that an error is returned by a Locations query if no query parameters are specified. - * + * Abstract Test 34 : Validate that an error is returned by a Position query if no + * query parameters are specified. Abstract Test 50 : Validate that an error is + * returned by a Area query if no query parameters are specified. Abstract Test 66 : + * Validate that an error is returned by a Cube query if no query parameters are + * specified. Abstract Test 82 : Validate that an error is returned by a Trajectory + * query if no query parameters are specified. Abstract Test 100 : Validate that an + * error is returned by a Corridor query if no query parameters are specified. + * Abstract Test 136 : Validate that an error is returned by a Locations query if no + * query parameters are specified. * @param collectionIdentifiers collection identifiers */ - @Test(dataProvider = "collectionIDs", description = "Implements Abstract Test 34 (/conf/position), Abstract Test 50 (/conf/area), Abstract Test 66 (/conf/cube), Abstract Test 82 (/conf/trajectory), Abstract Test 100 (/conf/corridor), Abstract Test 136 (/conf/locations) ") + @Test(dataProvider = "collectionIDs", + description = "Implements Abstract Test 34 (/conf/position), Abstract Test 50 (/conf/area), Abstract Test 66 (/conf/cube), Abstract Test 82 (/conf/trajectory), Abstract Test 100 (/conf/corridor), Abstract Test 136 (/conf/locations) ") public void validateNoQueryParameters(Object collectionIdentifiers) { Set collectionIds = (Set) collectionIdentifiers; ArrayList collectionsList = new ArrayList(); collectionsList.addAll(collectionIds); boolean foundDataQueries = false; - //if noOfCollections is -1 (meaning check box 'Test all collections' was checked) - //use all collections. Otherwise, use the specified noOfCollections + // if noOfCollections is -1 (meaning check box 'Test all collections' was checked) + // use all collections. Otherwise, use the specified noOfCollections int maximum = this.noOfCollections == -1 ? collectionsList.size() : this.noOfCollections; for (int c = 0; c < maximum; c++) { - + String collectionId = collectionsList.get(c); - + boolean supportsPositionQuery = false; boolean supportsAreaQuery = false; boolean supportsTrajectoryQuery = false; @@ -112,8 +114,8 @@ public void validateNoQueryParameters(Object collectionIdentifiers) { Response response = getCollectionResponse(collectionId); JsonPath jsonResponse = response.jsonPath(); HashMap dataQueries = jsonResponse.getJsonObject("data_queries"); - if(dataQueries == null) { - continue; + if (dataQueries == null) { + continue; } foundDataQueries = true; supportsPositionQuery = dataQueries.containsKey("position"); @@ -122,10 +124,9 @@ public void validateNoQueryParameters(Object collectionIdentifiers) { supportsLocationsQuery = dataQueries.containsKey("locations"); try { - if (supportsPositionQuery) { - + response = getCollectionResponse(collectionId + "/position"); assertTrue(response.getStatusCode() == 400, "Fails Abstract Test 34. Expected status code 400 when a Position query with no query parameters are specified for collection " @@ -133,60 +134,71 @@ public void validateNoQueryParameters(Object collectionIdentifiers) { } if (supportsAreaQuery) { - + response = getCollectionResponse(collectionId + "/area"); assertTrue(response.getStatusCode() == 400, "Fails Abstract Test 50. Expected status code 400 when a Area query with no query parameters are specified for collection " + collectionId); } if (supportsTrajectoryQuery) { - + response = getCollectionResponse(collectionId + "/trajectory"); assertTrue(response.getStatusCode() == 400, "Fails Abstract Test 82. Expected status code 400 when a Trajectory query with no query parameters are specified for collection " + collectionId); } if (supportsLocationsQuery) { - + response = getCollectionResponse(collectionId + "/locations"); assertTrue(response.getStatusCode() == 400, "Fails Abstract Test 136. Expected status code 400 when a Locations query with no query parameters are specified for collection " + collectionId); } - - } catch (Exception ex) { + + } + catch (Exception ex) { } } - if(!foundDataQueries) { - throw new SkipException("No data_queries element was present in tested collections."); + if (!foundDataQueries) { + throw new SkipException("No data_queries element was present in tested collections."); } } /** - * Abstract Test 35 : Validate that an error is returned by a Position query when the coords query parameter is not specified. - * Abstract Test 36 : Validate that an error is returned by a Position query when the coords query parameter does not contain a valid POINT Well Known Text value. - * Abstract Test 51 : Validate that an error is returned by an Area query when the coords query parameter is not specified. - * Abstract Test 52 : Validate that an error is returned by an Area query when the coords query parameter does not contain a valid POLYGON Well Known Text value. - * Abstract Test 83 : Validate that an error is returned by a Trajectory query when the coords query parameter is not specified. - * Abstract Test 84 : Validate that an error is returned by a Trajectory query when the coords query parameter does not contain a valid LINESTRING Well Known Text value. - * Abstract Test 85 : Validate that an error is returned by a Trajectory query when the coords query parameter does not contain a valid LINESTRINGM Well Known Text value. - * Abstract Test 88 : Validate that an error is returned by a Trajectory query when the coords query parameter does not contain a valid LINESTRINGZM Well Known Text value. - * Abstract Test 89 : Validate that an error is returned by a Trajectory query when the coords query parameter does not contain a valid LINESTRINGZ Well Known Text value. - * Abstract Test 101 : Validate that an error is returned by a Corridor query when the coords query parameter is not specified. - * Abstract Test 106 : Validate that an error is returned by a corridor query when the coords query parameter does not contain a valid LINESTRING Well Known Text value. - * + * Abstract Test 35 : Validate that an error is returned by a Position query when the + * coords query parameter is not specified. Abstract Test 36 : Validate that an error + * is returned by a Position query when the coords query parameter does not contain a + * valid POINT Well Known Text value. Abstract Test 51 : Validate that an error is + * returned by an Area query when the coords query parameter is not specified. + * Abstract Test 52 : Validate that an error is returned by an Area query when the + * coords query parameter does not contain a valid POLYGON Well Known Text value. + * Abstract Test 83 : Validate that an error is returned by a Trajectory query when + * the coords query parameter is not specified. Abstract Test 84 : Validate that an + * error is returned by a Trajectory query when the coords query parameter does not + * contain a valid LINESTRING Well Known Text value. Abstract Test 85 : Validate that + * an error is returned by a Trajectory query when the coords query parameter does not + * contain a valid LINESTRINGM Well Known Text value. Abstract Test 88 : Validate that + * an error is returned by a Trajectory query when the coords query parameter does not + * contain a valid LINESTRINGZM Well Known Text value. Abstract Test 89 : Validate + * that an error is returned by a Trajectory query when the coords query parameter + * does not contain a valid LINESTRINGZ Well Known Text value. Abstract Test 101 : + * Validate that an error is returned by a Corridor query when the coords query + * parameter is not specified. Abstract Test 106 : Validate that an error is returned + * by a corridor query when the coords query parameter does not contain a valid + * LINESTRING Well Known Text value. * @param collectionIdentifiers collection identifiers */ @SuppressWarnings("unchecked") - @Test(dataProvider = "collectionIDs", description = "Implements Abstract Test 35 (/conf/position),Abstract Test 36 (/conf/position), Abstract Test 51 (/conf/area), Abstract Test 52 (/conf/area), Abstract Test 83 (/conf/trajectory), Abstract Test 101 (/conf/corridor)") + @Test(dataProvider = "collectionIDs", + description = "Implements Abstract Test 35 (/conf/position),Abstract Test 36 (/conf/position), Abstract Test 51 (/conf/area), Abstract Test 52 (/conf/area), Abstract Test 83 (/conf/trajectory), Abstract Test 101 (/conf/corridor)") public void validateCoordsQueryParameters(Object collectionIdentifiers) { Set collectionIds = (Set) collectionIdentifiers; ArrayList collectionsList = new ArrayList(); collectionsList.addAll(collectionIds); boolean foundDataQueries = false; - //if noOfCollections is -1 (meaning check box 'Test all collections' was checked) - //use all collections. Otherwise, use the specified noOfCollections + // if noOfCollections is -1 (meaning check box 'Test all collections' was checked) + // use all collections. Otherwise, use the specified noOfCollections int maximum = this.noOfCollections == -1 ? collectionsList.size() : this.noOfCollections; for (int c = 0; c < maximum; c++) { @@ -201,20 +213,19 @@ public void validateCoordsQueryParameters(Object collectionIdentifiers) { Response response = getCollectionResponse(collectionId); JsonPath jsonResponse = response.jsonPath(); HashMap dataQueries = jsonResponse.getJsonObject("data_queries"); - if(dataQueries == null) { - continue; - } - foundDataQueries = true; + if (dataQueries == null) { + continue; + } + foundDataQueries = true; supportsPositionQuery = dataQueries.containsKey("position"); supportsAreaQuery = dataQueries.containsKey("area"); supportsTrajectoryQuery = dataQueries.containsKey("trajectory"); supportsCorridorQuery = dataQueries.containsKey("corridor"); try { - if (supportsPositionQuery) { - + response = getCollectionResponse(collectionId + "/position?coords="); assertTrue(response.getStatusCode() == 400, "Fails Abstract Test 35. Expected status code 400 when a Position query with coords query parameter is not specified for collection " @@ -227,7 +238,7 @@ public void validateCoordsQueryParameters(Object collectionIdentifiers) { } if (supportsAreaQuery) { - + response = getCollectionResponse(collectionId + "/area?coords="); assertTrue(response.getStatusCode() == 400, "Fails Abstract Test 51. Expected status code 400 when an Area query with coords query parameter is not specified for collection " @@ -239,7 +250,7 @@ public void validateCoordsQueryParameters(Object collectionIdentifiers) { + collectionId); } if (supportsTrajectoryQuery) { - + response = getCollectionResponse(collectionId + "/trajectory?coords="); assertTrue(response.getStatusCode() == 400, "Fails Abstract Test 83. Expected status code 400 when a Trajectory query with coords query parameter is not specified for collection " @@ -267,61 +278,56 @@ public void validateCoordsQueryParameters(Object collectionIdentifiers) { } if (supportsCorridorQuery) { - + response = getCollectionResponse(collectionId + "/corridor?coords="); assertTrue(response.getStatusCode() == 400, "Expected status code 400 when a Corridor query with coords query parameter is not specified for collection " + collectionId); - response = getCollectionResponse(collectionId + "/corridor?coords=LINESTRING()"); assertTrue(response.getStatusCode() == 400, "Expected status code 400 when a Corridor query with coords query parameter does not contain a valid LINESTRING Well Known Text value for collection " + collectionId); } - - } catch (Exception ex) { + + } + catch (Exception ex) { } } - if(!foundDataQueries) { - throw new SkipException("No data_queries element was present in tested collections."); - } + if (!foundDataQueries) { + throw new SkipException("No data_queries element was present in tested collections."); + } } - /** - * Abstract Test 37 : Validate that resources can be identified and extracted from a Collection with a Position query using query parameters. - * Abstract Test 39 : Validate that the coords query parameters are processed correctly. - * Abstract Test 41 : Validate that the vertical level query parameters are constructed correctly. - * Abstract Test 43 : Validate that the datetime query parameters are processed correctly. - * Abstract Test 45 : Validate that the parameter-name query parameters are processed correctly. - * Abstract Test 47 : Validate that the crs query parameters are processed correctly. - * Abstract Test 49 : Validate that the f query parameters are processed correctly. - * + * Abstract Test 37 : Validate that resources can be identified and extracted from a + * Collection with a Position query using query parameters. Abstract Test 39 : + * Validate that the coords query parameters are processed correctly. Abstract Test 41 + * : Validate that the vertical level query parameters are constructed correctly. + * Abstract Test 43 : Validate that the datetime query parameters are processed + * correctly. Abstract Test 45 : Validate that the parameter-name query parameters are + * processed correctly. Abstract Test 47 : Validate that the crs query parameters are + * processed correctly. Abstract Test 49 : Validate that the f query parameters are + * processed correctly. * @param collectionIdentifiers collection identifiers */ @SuppressWarnings("unchecked") - @Test(dataProvider = "collectionIDs", description = "Implements Abstract Test 37 (/conf/position), Abstract Test 39 (/conf/edr/rc-coords-response), Abstract Test 41 (/conf/edr/rc-z-response), Abstract Test 43 (/conf/core/datetime-response), Abstract Test 45 (/conf/edr/rc-parameter-name-response), Abstract Test 47 (/conf/edr/REQ_rc-crs-response), Abstract Test 49 (/conf/collections/rc-f-response)") + @Test(dataProvider = "collectionIDs", + description = "Implements Abstract Test 37 (/conf/position), Abstract Test 39 (/conf/edr/rc-coords-response), Abstract Test 41 (/conf/edr/rc-z-response), Abstract Test 43 (/conf/core/datetime-response), Abstract Test 45 (/conf/edr/rc-parameter-name-response), Abstract Test 47 (/conf/edr/REQ_rc-crs-response), Abstract Test 49 (/conf/collections/rc-f-response)") public void validatePositionQueryUsingParameters(Object collectionIdentifiers) { - - - Set collectionIds = (Set) collectionIdentifiers; PositionQueryProcessor processor = new PositionQueryProcessor(); - String resultMessage = processor.validatePositionQueryUsingParameters(collectionIds,rootUri.toString(),this.noOfCollections,init()); - assertTrue(resultMessage.length()==0, + String resultMessage = processor.validatePositionQueryUsingParameters(collectionIds, rootUri.toString(), + this.noOfCollections, init()); + assertTrue(resultMessage.length() == 0, "Fails Abstract Test 37. Therefore could not verify the implementation passes Abstract Tests 39, 41, 43, 45, 47, and 49. Expected information that matches the selection criteria is returned for Position query. " + resultMessage); - } - - - private String printKeys(HashMap input) { StringBuffer sb = new StringBuffer(); Iterator inputIterator = input.keySet().iterator(); @@ -333,101 +339,96 @@ private String printKeys(HashMap input) { } - /** - * Abstract Test 53 : Validate that resources can be identified and extracted from a Collection with an Area query using query parameters. - * Abstract Test 55 : Validate that the coords query parameters are processed correctly. - * Abstract Test 57 : Validate that the vertical level query parameters are constructed correctly. - * Abstract Test 59 : Validate that the datetime query parameters are processed correctly. - * Abstract Test 61 : Validate that the parameter-name query parameters are processed correctly. - * Abstract Test 63 : Validate that the crs query parameters are processed correctly. - * Abstract Test 65 : Validate that the f query parameters are processed correctly. - * + * Abstract Test 53 : Validate that resources can be identified and extracted from a + * Collection with an Area query using query parameters. Abstract Test 55 : Validate + * that the coords query parameters are processed correctly. Abstract Test 57 : + * Validate that the vertical level query parameters are constructed correctly. + * Abstract Test 59 : Validate that the datetime query parameters are processed + * correctly. Abstract Test 61 : Validate that the parameter-name query parameters are + * processed correctly. Abstract Test 63 : Validate that the crs query parameters are + * processed correctly. Abstract Test 65 : Validate that the f query parameters are + * processed correctly. * @param collectionIdentifiers collection identifiers */ @SuppressWarnings("unchecked") - @Test(dataProvider = "collectionIDs", description = "Implements Abstract Test 53 (/conf/area), Abstract Test 55 (/conf/edr/rc-coords-response), Abstract Test 57 (/conf/edr/rc-z-response), Abstract Test 59 (/conf/core/datetime-response), Abstract Test 61 (/conf/edr/rc-parameter-name-response), Abstract Test 63 (/conf/edr/REQ_rc-crs-response), Abstract Test 65 (/conf/collections/rc-f-response)") + @Test(dataProvider = "collectionIDs", + description = "Implements Abstract Test 53 (/conf/area), Abstract Test 55 (/conf/edr/rc-coords-response), Abstract Test 57 (/conf/edr/rc-z-response), Abstract Test 59 (/conf/core/datetime-response), Abstract Test 61 (/conf/edr/rc-parameter-name-response), Abstract Test 63 (/conf/edr/REQ_rc-crs-response), Abstract Test 65 (/conf/collections/rc-f-response)") public void validateAreaQueryUsingParameters(Object collectionIdentifiers) { - - Set collectionIds = (Set) collectionIdentifiers; AreaQueryProcessor processor = new AreaQueryProcessor(); - String resultMessage = processor.validateAreaQueryUsingParameters(collectionIds,rootUri.toString(),this.noOfCollections,init()); - assertTrue(resultMessage.length()==0, + String resultMessage = processor.validateAreaQueryUsingParameters(collectionIds, rootUri.toString(), + this.noOfCollections, init()); + assertTrue(resultMessage.length() == 0, "Fails Abstract Test 53. Therefore could not verify the implementation passes Abstract Tests 55, 57, 59, 61, 63, 65. Expected information that matches the selection criteria is returned for Area query. " + resultMessage); - } /** - * Abstract Test 91 : Validate that resources can be identified and extracted from a Collection with a Trajectory query using query parameters. - * Abstract Test 93 : Validate that the coords query parameters are processed correctly. - * Abstract Test 95 : Validate that the parameter-name query parameters are processed correctly. + * Abstract Test 91 : Validate that resources can be identified and extracted from a + * Collection with a Trajectory query using query parameters. Abstract Test 93 : + * Validate that the coords query parameters are processed correctly. Abstract Test 95 + * : Validate that the parameter-name query parameters are processed correctly. * Abstract Test 97 : Validate that the crs query parameters are processed correctly. * Abstract Test 99 : Validate that the f query parameters are processed correctly. - * * @param collectionIdentifiers collection identifiers */ @SuppressWarnings("unchecked") - @Test(dataProvider = "collectionIDs", description = "Implements Abstract Test 91 (/conf/trajectory), Abstract Test 93 (/conf/edr/rc-coords-response), Abstract Test 95 (/conf/edr/rc-parameter-name-response), Abstract Test 97 (/conf/edr/REQ_rc-crs-response), Abstract Test 99 (/conf/collections/rc-f-response)") + @Test(dataProvider = "collectionIDs", + description = "Implements Abstract Test 91 (/conf/trajectory), Abstract Test 93 (/conf/edr/rc-coords-response), Abstract Test 95 (/conf/edr/rc-parameter-name-response), Abstract Test 97 (/conf/edr/REQ_rc-crs-response), Abstract Test 99 (/conf/collections/rc-f-response)") public void validateTrajectoryQueryUsingParameters(Object collectionIdentifiers) { - - Set collectionIds = (Set) collectionIdentifiers; TrajectoryQueryProcessor processor = new TrajectoryQueryProcessor(); - String resultMessage = processor.validateTrajectoryQueryUsingParameters(collectionIds,rootUri.toString(),this.noOfCollections,init()); - if(resultMessage.contains(processor.queryTypeNotSupported)) { + String resultMessage = processor.validateTrajectoryQueryUsingParameters(collectionIds, rootUri.toString(), + this.noOfCollections, init()); + if (resultMessage.contains(processor.queryTypeNotSupported)) { throw new SkipException(processor.queryTypeNotSupported); } - assertTrue(resultMessage.length()==0, + assertTrue(resultMessage.length() == 0, "Fails Abstract Test 91. Therefore could not verify the implementation passes Abstract Tests 91, 93, 95, 97, 99. Expected information that matches the selection criteria is returned for Trajectory query. " + resultMessage); - } - /** - * Abstract Test 115 : Validate that resources can be identified and extracted from a Collection with a Corridor query using query parameters. - * Abstract Test 117 : Validate that the coords query parameters are processed correctly. - * Abstract Test 119 : Validate that the corridor-width query parameters are processed correctly. - * Abstract Test 121 : Validate that the corridor-height query parameters are processed correctly. - * Abstract Test 123 :Validate that the width-units query parameters are processed correctly. - * Abstract Test 125 : Validate that the height-units query parameters are processed correctly. - * Abstract Test 127 : Validate that the parameter-name query parameters are processed correctly. - * Abstract Test 129 : Validate that the crs query parameters are processed correctly. - * Abstract Test 131 : Validate that the f query parameters are processed correctly. - * + * Abstract Test 115 : Validate that resources can be identified and extracted from a + * Collection with a Corridor query using query parameters. Abstract Test 117 : + * Validate that the coords query parameters are processed correctly. Abstract Test + * 119 : Validate that the corridor-width query parameters are processed correctly. + * Abstract Test 121 : Validate that the corridor-height query parameters are + * processed correctly. Abstract Test 123 :Validate that the width-units query + * parameters are processed correctly. Abstract Test 125 : Validate that the + * height-units query parameters are processed correctly. Abstract Test 127 : Validate + * that the parameter-name query parameters are processed correctly. Abstract Test 129 + * : Validate that the crs query parameters are processed correctly. Abstract Test 131 + * : Validate that the f query parameters are processed correctly. * @param collectionIdentifiers collection identifiers */ @SuppressWarnings("unchecked") - @Test(dataProvider = "collectionIDs", description = "Implements Abstract Test 115 (/conf/corridor), Abstract Test 117 (/conf/edr/rc-coords-response), Abstract Test 119 (/conf/collections/REQ_rc-corridor-width-response), Abstract Test 121 (/conf/collections/REQ_rc-corridor-height-response), Abstract Test 123 (/conf/collections/REQ_rc-width-units-response), Abstract Test 125 (/conf/collections/rc-height-units-response), Abstract Test 127 (/conf/edr/rc-parameter-name-response), Abstract Test 129 (/conf/edr/REQ_rc-crs-response), Abstract Test 131 (/conf/collections/rc-f-response)") + @Test(dataProvider = "collectionIDs", + description = "Implements Abstract Test 115 (/conf/corridor), Abstract Test 117 (/conf/edr/rc-coords-response), Abstract Test 119 (/conf/collections/REQ_rc-corridor-width-response), Abstract Test 121 (/conf/collections/REQ_rc-corridor-height-response), Abstract Test 123 (/conf/collections/REQ_rc-width-units-response), Abstract Test 125 (/conf/collections/rc-height-units-response), Abstract Test 127 (/conf/edr/rc-parameter-name-response), Abstract Test 129 (/conf/edr/REQ_rc-crs-response), Abstract Test 131 (/conf/collections/rc-f-response)") public void validateCorridorQueryUsingParameters(Object collectionIdentifiers) { - - Set collectionIds = (Set) collectionIdentifiers; CorridorQueryProcessor processor = new CorridorQueryProcessor(); - String resultMessage = processor.validateCorridorQueryUsingParameters(collectionIds,rootUri.toString(),this.noOfCollections,init()); - if(resultMessage.contains(processor.queryTypeNotSupported)) { + String resultMessage = processor.validateCorridorQueryUsingParameters(collectionIds, rootUri.toString(), + this.noOfCollections, init()); + if (resultMessage.contains(processor.queryTypeNotSupported)) { throw new SkipException(processor.queryTypeNotSupported); } - assertTrue(resultMessage.length()==0, + assertTrue(resultMessage.length() == 0, "Fails Abstract Test 115. Therefore could not verify the implementation passes Abstract Tests 115, 117, 119, 121, 123, 125, 129, 131. Expected information that matches the selection criteria is returned for Corridor query. " + resultMessage); - } - - private String readStringFromURL(String urlString,int limit) throws Exception - { + private String readStringFromURL(String urlString, int limit) throws Exception { URL requestURL = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(requestURL.openConnection().getInputStream())); @@ -437,14 +438,11 @@ private String readStringFromURL(String urlString,int limit) throws Exception int i = 0; - - while (((inputLine = in.readLine()) != null) && (i < limit)) - { - response.append(inputLine+"\n"); + while (((inputLine = in.readLine()) != null) && (i < limit)) { + response.append(inputLine + "\n"); i++; } - in.close(); return response.toString(); diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/queries/TrajectoryQueryProcessor.java b/src/main/java/org/opengis/cite/ogcapiedr10/queries/TrajectoryQueryProcessor.java index a27b33a..46af268 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/queries/TrajectoryQueryProcessor.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/queries/TrajectoryQueryProcessor.java @@ -13,266 +13,264 @@ import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; -public class TrajectoryQueryProcessor extends AbstractProcessor{ - - double sizeOfLensSide = 1d; //in degrees - public final String queryTypeNotSupported = "None of the collections support this query type. Increase the number of collections to parse."; - - public String validateTrajectoryQueryUsingParameters(Set collectionIds, String rootUri, int noOfCollections, RequestSpecification ini){ - StringBuffer sb = new StringBuffer(); - - ArrayList collectionsList = new ArrayList(); - collectionsList.addAll(collectionIds); - - int numberOfCollectionsWithTrajectorySupport = 0; - - //if noOfCollections is -1 (meaning check box 'Test all collections' was checked) - //use all collections. Otherwise use the specified noOfCollections - int maximum = noOfCollections == -1 ? collectionsList.size() : noOfCollections; - - for (int c = 0; c dataQueries = jsonResponse.getJsonObject("data_queries"); - - if(dataQueries==null) { //Avoids Nullpointer Exception - sb.append(" The data_queries element is missing from the collection "+collectionId+" ."); - } - supportsTrajectoryQuery = dataQueries != null && dataQueries.containsKey("trajectory"); - - if(supportsTrajectoryQuery==false) { //Avoids Nullpointer Exception - sb.append(" The trajectory element is missing from the data_queries element of the collection "+collectionId+" ."); - } - - - - if (supportsTrajectoryQuery) { - - numberOfCollectionsWithTrajectorySupport++; - - if(jsonResponse.getJsonObject("parameter_names")==null) { //Avoids Nullpointer Exception - sb.append(" The parameter_names element is missing from the collection "+collectionId+" ."); - } - - HashMap parameterNames = jsonResponse.getJsonObject("parameter_names"); - Set parameterNamesSet = parameterNames.keySet(); - Iterator parameterNamesIterator = parameterNamesSet.iterator(); - - parameterNamesIterator.hasNext(); - String sampleParamaterName = parameterNamesIterator.next(); - - if(jsonResponse.getList("crs")==null) { //Avoids Nullpointer Exception - sb.append(" The crs list is missing from the collection "+collectionId+" ."); - } - - List crsList = jsonResponse.getList("crs"); - - String supportedCRS = null; - for (int q = 0; q < crsList.size(); q++) { - if (crsList.get(q).equals("CRS:84") || - crsList.get(q).equals("CRS84") || - crsList.get(q).equals("EPSG:4326") || - crsList.get(q).contains("www.opengis.net/def/crs/OGC/1.3/CRS84")) { - supportedCRS = crsList.get(q); - } - } - if (supportedCRS == null) { - sb.append(collectionId + " does not support CRS84 CRS. \n"); +public class TrajectoryQueryProcessor extends AbstractProcessor { - } + double sizeOfLensSide = 1d; // in degrees - HashMap trajectoryQuery = (HashMap) dataQueries.get("trajectory"); - HashMap link = (HashMap) trajectoryQuery.get("link"); - HashMap variables = (HashMap) link.get("variables"); - ArrayList outputFormatList = (ArrayList) variables.get("output_formats"); - String supportedFormat = null; - for (int f = 0; f < outputFormatList.size(); f++) { - if (outputFormatList.get(f).equals("CoverageJSON") || outputFormatList.get(f).contains("CoverageJSON")) { //preference for CoverageJSON if supported - supportedFormat = outputFormatList.get(f); - } - else if (outputFormatList.get(f).equals("GeoJSON")) { - supportedFormat = outputFormatList.get(f); - } - } + public final String queryTypeNotSupported = "None of the collections support this query type. Increase the number of collections to parse."; - double medianx = 0d; - double mediany = 0d; - double lminx = 0d; //lens - double lminy = 0d; //lens - double lmaxx = 0d; //lens - double lmaxy = 0d; //lens + public String validateTrajectoryQueryUsingParameters(Set collectionIds, String rootUri, int noOfCollections, + RequestSpecification ini) { + StringBuffer sb = new StringBuffer(); - - HashMap extent = jsonResponse.getJsonObject("extent"); - if (extent.containsKey("spatial")) { - + ArrayList collectionsList = new ArrayList(); + collectionsList.addAll(collectionIds); - HashMap spatial = (HashMap) extent.get("spatial"); + int numberOfCollectionsWithTrajectorySupport = 0; - if (!spatial.containsKey("bbox")) - { - sb.append("spatial extent of collection "+collectionId+" missing bbox. \n"); - continue; - } + // if noOfCollections is -1 (meaning check box 'Test all collections' was checked) + // use all collections. Otherwise use the specified noOfCollections + int maximum = noOfCollections == -1 ? collectionsList.size() : noOfCollections; - ArrayList bboxEnv = (ArrayList) spatial.get("bbox"); // for some unknown reason the library returns JSON types as Integers only + for (int c = 0; c < maximum; c++) { + + String collectionId = collectionsList.get(c); + boolean supportsTrajectoryQuery = false; - ArrayList bbox = null; + String url = JsonUtils.getCollectionURL(rootUri, collectionId); - if(bboxEnv.get(0).getClass().toString().contains("java.lang.Integer") || - bboxEnv.get(0).getClass().toString().contains("java.lang.Double")|| - bboxEnv.get(0).getClass().toString().contains("java.lang.Float")) { //for EDR API V1.0.0 - bbox = bboxEnv; + Response response = JsonUtils.getCollectionResponse(rootUri, collectionId, ini); + JsonPath jsonResponse = response.jsonPath(); + + HashMap dataQueries = jsonResponse.getJsonObject("data_queries"); + + if (dataQueries == null) { // Avoids Nullpointer Exception + sb.append(" The data_queries element is missing from the collection " + collectionId + " ."); + } + supportsTrajectoryQuery = dataQueries != null && dataQueries.containsKey("trajectory"); + + if (supportsTrajectoryQuery == false) { // Avoids Nullpointer Exception + sb.append(" The trajectory element is missing from the data_queries element of the collection " + + collectionId + " ."); + } + + if (supportsTrajectoryQuery) { + + numberOfCollectionsWithTrajectorySupport++; + + if (jsonResponse.getJsonObject("parameter_names") == null) { // Avoids + // Nullpointer + // Exception + sb.append(" The parameter_names element is missing from the collection " + collectionId + " ."); + } + + HashMap parameterNames = jsonResponse.getJsonObject("parameter_names"); + Set parameterNamesSet = parameterNames.keySet(); + Iterator parameterNamesIterator = parameterNamesSet.iterator(); + + parameterNamesIterator.hasNext(); + String sampleParamaterName = parameterNamesIterator.next(); + + if (jsonResponse.getList("crs") == null) { // Avoids Nullpointer Exception + sb.append(" The crs list is missing from the collection " + collectionId + " ."); + } + + List crsList = jsonResponse.getList("crs"); + + String supportedCRS = null; + for (int q = 0; q < crsList.size(); q++) { + if (crsList.get(q).equals("CRS:84") || crsList.get(q).equals("CRS84") + || crsList.get(q).equals("EPSG:4326") + || crsList.get(q).contains("www.opengis.net/def/crs/OGC/1.3/CRS84")) { + supportedCRS = crsList.get(q); + } + } + if (supportedCRS == null) { + sb.append(collectionId + " does not support CRS84 CRS. \n"); + + } + + HashMap trajectoryQuery = (HashMap) dataQueries.get("trajectory"); + HashMap link = (HashMap) trajectoryQuery.get("link"); + HashMap variables = (HashMap) link.get("variables"); + ArrayList outputFormatList = (ArrayList) variables.get("output_formats"); + String supportedFormat = null; + for (int f = 0; f < outputFormatList.size(); f++) { + if (outputFormatList.get(f).equals("CoverageJSON") + || outputFormatList.get(f).contains("CoverageJSON")) { // preference + // for + // CoverageJSON + // if + // supported + supportedFormat = outputFormatList.get(f); + } + else if (outputFormatList.get(f).equals("GeoJSON")) { + supportedFormat = outputFormatList.get(f); + } + } + + double medianx = 0d; + double mediany = 0d; + double lminx = 0d; // lens + double lminy = 0d; // lens + double lmaxx = 0d; // lens + double lmaxy = 0d; // lens + + HashMap extent = jsonResponse.getJsonObject("extent"); + if (extent.containsKey("spatial")) { + + HashMap spatial = (HashMap) extent.get("spatial"); + + if (!spatial.containsKey("bbox")) { + sb.append("spatial extent of collection " + collectionId + " missing bbox. \n"); + continue; + } + + ArrayList bboxEnv = (ArrayList) spatial.get("bbox"); // for some + // unknown + // reason the + // library + // returns + // JSON types + // as Integers + // only + + ArrayList bbox = null; + + if (bboxEnv.get(0).getClass().toString().contains("java.lang.Integer") + || bboxEnv.get(0).getClass().toString().contains("java.lang.Double") + || bboxEnv.get(0).getClass().toString().contains("java.lang.Float")) { // for + // EDR + // API + // V1.0.0 + bbox = bboxEnv; + + } + else if (bboxEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { // for + // EDR + // API + // V1.0.1 + bbox = (ArrayList) bboxEnv.get(0); + } + + if (bbox.size() > 3) { + + if (bbox.get(0).getClass().toString().contains("Integer") + || bbox.get(0).getClass().toString().contains("Double") + || bbox.get(0).getClass().toString().contains("Float")) { + double minx = Double.parseDouble(bbox.get(0).toString()); + double miny = Double.parseDouble(bbox.get(1).toString()); + double maxx = Double.parseDouble(bbox.get(2).toString()); + double maxy = Double.parseDouble(bbox.get(3).toString()); + + medianx = minx + ((maxx - minx) / 2d); + mediany = miny + ((maxy - miny) / 2d); + + lminx = medianx - sizeOfLensSide; + lminy = mediany - sizeOfLensSide; + lmaxx = medianx + sizeOfLensSide; + lmaxy = mediany + sizeOfLensSide; + + } + + } + else { + sb.append("bbox of spatial extent of collection" + collectionId + + " has fewer than four coordinates. \n"); + } + + } + else { // if spatial extent is missing + sb.append(" The spatial extent element is missing from the collection " + collectionId + " ."); + } + + String sampleParamaterNameSafe = null; + try { + sampleParamaterNameSafe = URLEncoder.encode(sampleParamaterName, "UTF8"); + } + catch (Exception ex) { + ex.printStackTrace(); + } + + String sampleDateTime = null; + if (extent.containsKey("temporal")) { + + HashMap temporal = (HashMap) extent.get("temporal"); + + if (!temporal.containsKey("interval")) { + + sb.append("Temporal extent of collection " + collectionId + " missing interval. \n"); + continue; + } + + ArrayList intervalEnv = (ArrayList) temporal.get("interval"); + + ArrayList interval = null; + + if (intervalEnv.get(0).getClass().toString().contains("java.lang.String")) { + interval = intervalEnv; + } + else if (intervalEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { + + interval = (ArrayList) intervalEnv.get(0); + } + + if (interval.size() > 1) { + + sampleDateTime = interval.get(0) + "/" + interval.get(1); + + } + + } + else { // if temporal extent is missing + sb.append(" The temporal extent element is missing from the collection " + collectionId + " ."); + } + + String constructedURL = url + "/trajectory?parameter-name=" + sampleParamaterNameSafe + "&coords=" + + "LINESTRING(" + lminx + "+" + lminy + "," + medianx + "+" + mediany + "," + lmaxx + "+" + + lmaxy + ")" + "&f=" + supportedFormat + "&datetime=" + sampleDateTime; + System.out.println("T " + constructedURL); + + String pageContent = null; + try { + pageContent = readStringFromURL(constructedURL, 10); // you can use + // Integer.MAX_VALUE + // for no + // limit + + } + catch (Exception ex) { + ex.printStackTrace(); + } - } - else if(bboxEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { //for EDR API V1.0.1 - bbox = (ArrayList) bboxEnv.get(0); - } + if (pageContent != null) { + if (pageContent.contains("Coverage") || pageContent.contains("Feature")) { + // do nothing + } + else { + sb.append("Response of Trajectory Query on collection " + collectionId + + " did not contain a recognised encoding. \n"); + } + } + else { + sb.append("Response of Trajectory Query on collection " + collectionId + " was null. \n"); + } - if (bbox.size() > 3) { + } + else { // does not support Trajectory queries + continue; + } - if (bbox.get(0).getClass().toString().contains("Integer") - || bbox.get(0).getClass().toString().contains("Double") - || bbox.get(0).getClass().toString().contains("Float")) { - double minx = Double.parseDouble(bbox.get(0).toString()); - double miny = Double.parseDouble(bbox.get(1).toString()); - double maxx = Double.parseDouble(bbox.get(2).toString()); - double maxy = Double.parseDouble(bbox.get(3).toString()); + } - medianx = minx + ((maxx - minx) / 2d); - mediany = miny + ((maxy - miny) / 2d); + if (numberOfCollectionsWithTrajectorySupport == 0) { + sb.append(queryTypeNotSupported + "\n"); + } - lminx = medianx - sizeOfLensSide; - lminy = mediany - sizeOfLensSide; - lmaxx = medianx + sizeOfLensSide; - lmaxy = mediany + sizeOfLensSide; + return sb.toString(); + } - - - } - - } else { - sb.append("bbox of spatial extent of collection" + collectionId - + " has fewer than four coordinates. \n"); - } - - - } - else { //if spatial extent is missing - sb.append(" The spatial extent element is missing from the collection "+collectionId+" ."); - } - - String sampleParamaterNameSafe = null; - try { - sampleParamaterNameSafe = URLEncoder.encode(sampleParamaterName,"UTF8"); - } - catch(Exception ex) {ex.printStackTrace();} - - - String sampleDateTime = null; - if (extent.containsKey("temporal")) { - - - HashMap temporal = (HashMap) extent.get("temporal"); - - if (!temporal.containsKey("interval")) - { - - sb.append("Temporal extent of collection "+collectionId+" missing interval. \n"); - continue; - } - - - ArrayList intervalEnv = (ArrayList) temporal.get("interval"); - - - ArrayList interval = null; - - if(intervalEnv.get(0).getClass().toString().contains("java.lang.String")) { - interval = intervalEnv; - } - else if(intervalEnv.get(0).getClass().toString().contains("java.util.ArrayList")) { - - interval = (ArrayList) intervalEnv.get(0); - } - - - if (interval.size() > 1) { - - - sampleDateTime = interval.get(0)+"/"+interval.get(1); - - - } - - } - else { //if temporal extent is missing - sb.append(" The temporal extent element is missing from the collection "+collectionId+" ."); - } - - - - String constructedURL = url + "/trajectory?parameter-name=" - + sampleParamaterNameSafe + "&coords=" + "LINESTRING(" + - lminx + "+"+ lminy + ","+ - medianx + "+"+ mediany + ","+ - lmaxx + "+"+ lmaxy + - ")" + "&f=" + supportedFormat+"&datetime="+sampleDateTime; - System.out.println("T "+ constructedURL); - - - - String pageContent = null; - try { - pageContent = readStringFromURL(constructedURL,10); //you can use Integer.MAX_VALUE for no limit - - } - catch(Exception ex) { ex.printStackTrace();} - - if(pageContent!=null) { - - if(pageContent.contains("Coverage") || pageContent.contains("Feature")) { - //do nothing - } - else { - sb.append("Response of Trajectory Query on collection " + collectionId - + " did not contain a recognised encoding. \n"); - } - - } - else { - sb.append("Response of Trajectory Query on collection " + collectionId - + " was null. \n"); - } - - - - } - else { //does not support Trajectory queries - continue; - } - - - } - - if(numberOfCollectionsWithTrajectorySupport==0) { - sb.append(queryTypeNotSupported+"\n"); - } - - return sb.toString(); - } - - - } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/util/BBox.java b/src/main/java/org/opengis/cite/ogcapiedr10/util/BBox.java index 3cf7a45..c445343 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/util/BBox.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/util/BBox.java @@ -10,72 +10,68 @@ */ public class BBox { - private static final String PATTERN = "###.0000000"; + private static final String PATTERN = "###.0000000"; - private final double minX; + private final double minX; - private final double minY; + private final double minY; - private final double maxX; + private final double maxX; - private final double maxY; + private final double maxY; - /** - * @param minX - * Lower left corner, coordinate axis 1 - * @param minY - * Lower left corner, coordinate axis 2 - * @param maxX - * Upper right corner, coordinate axis 1 - * @param maxY - * Upper right corner, coordinate axis 2 - */ - public BBox( double minX, double minY, double maxX, double maxY ) { - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; - } + /** + * @param minX Lower left corner, coordinate axis 1 + * @param minY Lower left corner, coordinate axis 2 + * @param maxX Upper right corner, coordinate axis 1 + * @param maxY Upper right corner, coordinate axis 2 + */ + public BBox(double minX, double minY, double maxX, double maxY) { + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + } - /** - * @return the bbox as query string like '-12,10, 12,20' - */ - public String asQueryParameter() { - StringBuilder sb = new StringBuilder(); - DecimalFormat formatter = formatter(); - sb.append( formatter.format( minX ) ).append( "," ); - sb.append( formatter.format( minY ) ).append( "," ); - sb.append( formatter.format( maxX ) ).append( "," ); - sb.append( formatter.format( maxY ) ); - return sb.toString(); - } + /** + * @return the bbox as query string like '-12,10, 12,20' + */ + public String asQueryParameter() { + StringBuilder sb = new StringBuilder(); + DecimalFormat formatter = formatter(); + sb.append(formatter.format(minX)).append(","); + sb.append(formatter.format(minY)).append(","); + sb.append(formatter.format(maxX)).append(","); + sb.append(formatter.format(maxY)); + return sb.toString(); + } - @Override - public String toString() { - return asQueryParameter(); - } + @Override + public String toString() { + return asQueryParameter(); + } - @Override - public boolean equals( Object o ) { - if ( this == o ) - return true; - if ( o == null || getClass() != o.getClass() ) - return false; - BBox bBox = (BBox) o; - return Double.compare( bBox.minX, minX ) == 0 && Double.compare( bBox.minY, minY ) == 0 - && Double.compare( bBox.maxX, maxX ) == 0 && Double.compare( bBox.maxY, maxY ) == 0; - } + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + BBox bBox = (BBox) o; + return Double.compare(bBox.minX, minX) == 0 && Double.compare(bBox.minY, minY) == 0 + && Double.compare(bBox.maxX, maxX) == 0 && Double.compare(bBox.maxY, maxY) == 0; + } - @Override - public int hashCode() { - return Objects.hash( minX, minY, maxX, maxY ); - } + @Override + public int hashCode() { + return Objects.hash(minX, minY, maxX, maxY); + } - private DecimalFormat formatter() { - NumberFormat nf = NumberFormat.getNumberInstance( Locale.ENGLISH ); - DecimalFormat df = (DecimalFormat) nf; - df.applyPattern( PATTERN ); - return df; - } + private DecimalFormat formatter() { + NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH); + DecimalFormat df = (DecimalFormat) nf; + df.applyPattern(PATTERN); + return df; + } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/util/ClientUtils.java b/src/main/java/org/opengis/cite/ogcapiedr10/util/ClientUtils.java index ef2ebfd..781ba80 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/util/ClientUtils.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/util/ClientUtils.java @@ -24,162 +24,150 @@ import jakarta.ws.rs.core.MediaType; /** - * 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 { - - /** - * 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); - Client client = ClientBuilder.newClient(config); - 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()); - 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); - Client client = ClientBuilder.newClient(config); - 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. -// * -// * @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()); -// } -// } -// URI uri = uriBuilder.build(); -// WebTarget target = buildClient().target(endpoint); -// Builder builder = target.request(); -// if (null == mediaTypes || mediaTypes.length == 0) { -// builder = builder.accept(MediaType.APPLICATION_XML_TYPE); -// } else { -// builder = builder.accept(mediaTypes); -// } -// Invocation invocation = builder.buildGet(); -// ClientRequest req = invocation.invoke() -// return req; -// } - - /** - * 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(ClientResponse response, - String targetURI) { - Source source = response.readEntity(DOMSource.class); - if (null != targetURI && !targetURI.isEmpty()) { - source.setSystemId(targetURI); - } - if (response.getEntityStream().markSupported()) { - try { - // NOTE: entity was buffered by client filter - response.getEntityStream().reset(); - } catch (IOException ex) { - Logger.getLogger(ClientUtils.class.getName()).log(Level.WARNING, - "Failed to reset response entity.", ex); - } - } - return source; - } - - /** - * Obtains the (XML) response entity as a DOM Document and resets the entity - * input stream for subsequent reads. - * - * @param response A representation of an HTTP response message. - * @param targetURI The target URI from which the entity was retrieved (may - * be null). - * @return A Document representing the entity; its base URI is set using the - * given targetURI value (this may be used to resolve any relative URIs - * found in the document). - */ - public static Document getResponseEntityAsDocument(ClientResponse response, - String targetURI) { - DOMSource domSource = (DOMSource) getResponseEntityAsSource(response, - targetURI); - Document entityDoc = (Document) domSource.getNode(); - entityDoc.setDocumentURI(domSource.getSystemId()); - return entityDoc; - } - - /** - * Checks if a GET request to a given URI returns HTTP 200 - OK - * - * @param uri The URI to check - * @return true, if HTTP 200 - OK was returned after a GET request, false otherwise - */ - public static boolean is200Response(URI uri) { - URL url = null; - int code = 0; - - try { - url = uri.toURL(); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - connection.connect(); - - code = connection.getResponseCode(); - - } catch (Exception ee) { - ee.printStackTrace(); - } - - return (code == 200); - } + + /** + * 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); + Client client = ClientBuilder.newClient(config); + 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()); + 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); + Client client = ClientBuilder.newClient(config); + 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. + // * + // * @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()); + // } + // } + // URI uri = uriBuilder.build(); + // WebTarget target = buildClient().target(endpoint); + // Builder builder = target.request(); + // if (null == mediaTypes || mediaTypes.length == 0) { + // builder = builder.accept(MediaType.APPLICATION_XML_TYPE); + // } else { + // builder = builder.accept(mediaTypes); + // } + // Invocation invocation = builder.buildGet(); + // ClientRequest req = invocation.invoke() + // return req; + // } + + /** + * 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(ClientResponse response, String targetURI) { + Source source = response.readEntity(DOMSource.class); + if (null != targetURI && !targetURI.isEmpty()) { + source.setSystemId(targetURI); + } + if (response.getEntityStream().markSupported()) { + try { + // NOTE: entity was buffered by client filter + response.getEntityStream().reset(); + } + catch (IOException ex) { + Logger.getLogger(ClientUtils.class.getName()) + .log(Level.WARNING, "Failed to reset response entity.", ex); + } + } + return source; + } + + /** + * Obtains the (XML) response entity as a DOM Document and resets the entity input + * stream for subsequent reads. + * @param response A representation of an HTTP response message. + * @param targetURI The target URI from which the entity was retrieved (may be null). + * @return A Document representing the entity; its base URI is set using the given + * targetURI value (this may be used to resolve any relative URIs found in the + * document). + */ + public static Document getResponseEntityAsDocument(ClientResponse response, String targetURI) { + DOMSource domSource = (DOMSource) getResponseEntityAsSource(response, targetURI); + Document entityDoc = (Document) domSource.getNode(); + entityDoc.setDocumentURI(domSource.getSystemId()); + return entityDoc; + } + + /** + * Checks if a GET request to a given URI returns HTTP 200 - OK + * @param uri The URI to check + * @return true, if HTTP 200 - OK was returned after a GET request, false otherwise + */ + public static boolean is200Response(URI uri) { + URL url = null; + int code = 0; + + try { + url = uri.toURL(); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.connect(); + + code = connection.getResponseCode(); + + } + catch (Exception ee) { + ee.printStackTrace(); + } + + return (code == 200); + } + } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/util/JsonUtils.java b/src/main/java/org/opengis/cite/ogcapiedr10/util/JsonUtils.java index 9d2af1e..cb5540e 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/util/JsonUtils.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/util/JsonUtils.java @@ -26,382 +26,358 @@ */ public class JsonUtils { - private JsonUtils() { - } - - /** - * Parses the id of the first feature from the passed json. - * - * @param collectionItemJson - * the json document containing the features, never null - * @return the parsed id, may be null if no feature could be found - */ - public static String parseFeatureId( JsonPath collectionItemJson ) { - List> features = collectionItemJson.get( "features" ); - if ( features == null ) - return null; - for ( Map feature : features ) { - if ( feature.containsKey( "id" ) ) - return feature.get( "id" ).toString(); - } - return null; - } - - /** - * Parses the temporal extent from the passed collection. - * - * @param collection - * the collection containing the extent to parse, never null - * @return the parsed temporal extent, null if no extent exists - * @throws IllegalArgumentException - * if the number of items in the extent invalid - * - */ - public static TemporalExtent parseTemporalExtent( Map collection ) { - Object extent = collection.get( "extent" ); - if ( extent == null || !( extent instanceof Map ) ) - return null; - Object spatial = ( (Map) extent ).get( "temporal" ); - if ( spatial == null || !( spatial instanceof List ) ) - return null; - List coords = (List) spatial; - if ( coords.size() == 2 ) { - ZonedDateTime begin = parseAsDate( (String) coords.get( 0 ) ); - ZonedDateTime end = parseAsDate( (String) coords.get( 1 ) ); - return new TemporalExtent( begin, end ); - } - throw new IllegalArgumentException( "Temporal extent with " + coords.size() + " items is invalid" ); - } - - /** - * Parses the passed string as ISO 8601 date. - * - * @param dateTime - * the dateTime to parse, never null - * @return the parsed date, never null - */ - public static ZonedDateTime parseAsDate( String dateTime ) { - return ZonedDateTime.parse( dateTime ); - } - - /** - * Formats the passed string as ISO 8601 date. Example: "2018-02-12T23:20:50Z" - * - * @param dateTime - * the dateTime to format, never null - * @return the formatted date, never null - */ - public static String formatDate( ZonedDateTime dateTime ) { - return DateTimeFormatter.ISO_INSTANT.format( dateTime ); - } - - /** - * Formats the passed string as ISO 8601 date. Example: "2018-02-12" - * - * @param date - * the dateTime to format, never null - * @return the formatted date, never null - */ - public static String formatDate( LocalDate date ) { - return DateTimeFormatter.ISO_DATE.format( date ); - } - - /** - * Formats the passed string as a period using a start and end time. Example: - * "2018-02-12T00:00:00Z/2018-03-18T12:31:12Z" - * - * @param beginDateTime - * the begin dateTime to format, never null - * @param endDateTime - * the end dateTime to format, never null - * @return the formatted date, never null - */ - public static String formatDateRange( ZonedDateTime beginDateTime, ZonedDateTime endDateTime ) { - return formatDate( beginDateTime ) + "/" + formatDate( endDateTime ); - } - - /** - * Formats the passed string as a period using start time and a duration. Example: - * "2018-02-12T00:00:00Z/P1M6DT12H31M12S" - * - * @param beginDate - * the begin date to format, never null - * @param endDate - * the end date to format, never null - * @return the formatted date, never null - */ - public static String formatDateRangeWithDuration( LocalDate beginDate, LocalDate endDate ) { - Period betweenDate = Period.between( beginDate, endDate ); - return formatDate( beginDate ) + "/" + betweenDate; - } - - /** - * Parses the spatial extent from the passed collection. - * - * @param collection - * the collection containing the extent to parse, never null - * @return the parsed bbox, null if no extent exists - * @throws IllegalArgumentException - * if the number of items in the extent invalid - * - */ - public static BBox parseSpatialExtent( Map collection ) { - Object extent = collection.get( "extent" ); - if ( extent == null || !( extent instanceof Map ) ) - return null; - Object spatial = ( (Map) extent ).get( "spatial" ); - if ( spatial == null || !( spatial instanceof List ) ) - return null; - List coords = (List) spatial; - if ( coords.size() == 4 ) { - double minX = parseValueAsDouble( coords.get( 0 ) ); - double minY = parseValueAsDouble( coords.get( 1 ) ); - double maxX = parseValueAsDouble( coords.get( 2 ) ); - double maxY = parseValueAsDouble( coords.get( 3 ) ); - return new BBox( minX, minY, maxX, maxY ); - } else if ( coords.size() == 6 ) { - throw new IllegalArgumentException( "BBox with " + coords.size() - + " coordinates is currently not supported" ); - } - throw new IllegalArgumentException( "BBox with " + coords.size() + " coordinates is invalid" ); - } - - /** - * Parses all links with 'type' of one of the passed mediaTypes and the 'rel' property with the passed value. - * - * @param links - * list of all links, never null - * @param mediaTypesToSupport - * a list of media types the links searched for should support, may be empty but never null - * @param expectedRel - * the expected value of the property 'rel', never null - * @return a list of links supporting one of the media types and with the expected 'rel' property, may be empty but - * never null - */ - public static List> findLinksWithSupportedMediaTypeByRel( List> links, - List mediaTypesToSupport, - String expectedRel ) { - List> alternateLinks = new ArrayList<>(); - for ( Map link : links ) { - Object type = link.get( "type" ); - Object rel = link.get( "rel" ); - if ( expectedRel.equals( rel ) && isSupportedMediaType( type, mediaTypesToSupport ) ) - alternateLinks.add( link ); - } - return alternateLinks; - } - - /** - * Parsing the media types which does not have a link woth property 'type' for. - * - * @param links - * list of links to search in, never null - * @param mediaTypesToSuppport - * a list of media types which should be supported, never null - * @return the media types which does not have a link for. - */ - public static List findUnsupportedTypes( List> links, List mediaTypesToSuppport ) { - List unsupportedType = new ArrayList<>(); - for ( String contentMediaType : mediaTypesToSuppport ) { - boolean hasLinkForContentType = hasLinkForContentType( links, contentMediaType ); - if ( !hasLinkForContentType ) - unsupportedType.add( contentMediaType ); - } - return unsupportedType; - } - - /** - * Parses the links without 'rel' or 'type' property. - * - * @param links - * list of links to search in, never null - * @param rels - * relation types - * @return the links without 'rel' or 'type' property - */ - public static List findLinksWithoutRelOrType( List> links, Set rels ) { - List linksWithoutRelOrType = new ArrayList<>(); - for ( Map link : links ) { - if ( rels.contains(link.get( "rel" )) && !linkIncludesRelAndType( link ) ) - linksWithoutRelOrType.add( (String) link.get( "href" ) ); - } - return linksWithoutRelOrType; - } - - /** - * Parses the link with 'rel=self'. - * - * @param links - * list of links to search in, never null - * @param expectedRel - * the expected value of the property 'rel', never null - * @return the link to itself or null if no such link exists - */ - public static Map findLinkByRel( List> links, String expectedRel ) { - if ( links == null ) - return null; - for ( Map link : links ) { - Object rel = link.get( "rel" ); - if ( expectedRel.equals( rel ) ) - return link; - } - return null; - } - - /** - * Checks if the passed link contains 'rel' and 'type' properties. - * - * @param link - * to check, never null - * @return true if the link contains 'rel' and 'type' properties, false otherwise - */ - public static boolean linkIncludesRelAndType( Map link ) { - Object rel = link.get( "rel" ); - Object type = link.get( "type" ); - if ( rel != null && type != null ) - return true; - return false; - } - - /** - * Checks if a property with the passed name exists in the jsonPath. - * - * @param propertyName - * name of the property to check, never null - * @param jsonPath - * to check, never null - * @return true if the property exists, false otherwise - */ - public static boolean hasProperty( String propertyName, JsonPath jsonPath ) { - return jsonPath.get( propertyName ) != null; - } - - /** - * Collects the number of all returned features by iterating over all 'next' links and summarizing the size of - * features in 'features' array property. - * - * @param jsonPath - * the initial collection, never null - * @param maximumLimit - * the limit parameter value to use, if <= 0 the parameter is omitted - * @return the number of all returned features - * @throws URISyntaxException - * if the creation of a uri fails - */ - public static int collectNumberOfAllReturnedFeatures( JsonPath jsonPath, int maximumLimit ) - throws URISyntaxException { - int numberOfAllReturnedFeatures = jsonPath.getList( "features" ).size(); - Map nextLink = findLinkByRel( jsonPath.getList( "links" ), "next" ); - while ( nextLink != null ) { - String nextUrl = (String) nextLink.get( "href" ); - URI uri = new URI( nextUrl ); - - RequestSpecification accept = given().log().all().baseUri( nextUrl ).accept( GEOJSON_MIME_TYPE ); - String[] pairs = uri.getQuery().split( "&" ); - String limitParamFromUri = null; - for ( String pair : pairs ) { - int idx = pair.indexOf( "=" ); - String key = pair.substring( 0, idx ); - String value = pair.substring( idx + 1 ); - if ( "limit".equals( key ) ) { - limitParamFromUri = value; - } else { - accept.param( key, value ); - } - } - if ( maximumLimit > 0 ) { - accept.param( "limit", maximumLimit ); - } else if ( limitParamFromUri != null ) { - accept.param( "limit", limitParamFromUri ); - } - - Response response = accept.when().request( GET ); - response.then().statusCode( 200 ); - - JsonPath nextJsonPath = response.jsonPath(); - int features = nextJsonPath.getList( "features" ).size(); - if ( features > 0 ) { - numberOfAllReturnedFeatures += features; - nextLink = findLinkByRel( nextJsonPath.getList( "links" ), "next" ); - } else { - nextLink = null; - } - } - return numberOfAllReturnedFeatures; - } - - public static Response getCollectionResponse(String serverUrl, String collectionId, RequestSpecification init) { - return init.baseUri( getCollectionURL(serverUrl, collectionId) ).accept( JSON ).when().request(GET); - } - - public static String getCollectionURL(String serverUrl, String collectionId) { - //https://github.com/opengeospatial/ets-ogcapi-edr10/issues/110 - //check for trailing forward slash - serverUrl = serverUrl.endsWith("/") ? serverUrl.substring(0, serverUrl.length() - 1) : serverUrl; - - String path = "/collections"; - path = collectionId != null ? path.concat("/" + collectionId) : path; - return serverUrl + path; - } - - private static boolean isSameMediaType( String mediaType1, String mediaType2 ) { - if ( mediaType1.contains(";") || mediaType2.contains(";") ) { - // media types are not case sensitive - String[] components1 = mediaType1.toLowerCase().split(";"); - String[] components2 = mediaType2.toLowerCase().split(";"); - // type and subtype must match - if ( !components1[0].trim().equals(components2[0].trim()) ) - return false; - Set parameters1 = new HashSet<>(); - Set parameters2 = new HashSet<>(); - // normalize parameter values and compare them - for ( int i=1; i> alternateLinks, String mediaType ) { - for ( Map alternateLink : alternateLinks ) { - Object type = alternateLink.get( "type" ); - if ( type instanceof String && isSameMediaType( mediaType, (String) type ) ) - return true; - } - return false; - } - - private static boolean isSupportedMediaType( Object type, List mediaTypes ) { - for ( String mediaType : mediaTypes ) { - if ( type instanceof String && isSameMediaType( mediaType, (String) type ) ) - return true; - } - return false; - } - - private static double parseValueAsDouble( Object cords ) { - if ( cords instanceof Integer ) { - return ( (Integer) cords ).doubleValue(); - } else if ( cords instanceof Float ) { - return ( (Float) cords ).doubleValue(); - } else if ( cords instanceof Double ) { - return (Double) cords; - } else { - return Double.parseDouble( cords.toString() ); - } - } + private JsonUtils() { + } + + /** + * Parses the id of the first feature from the passed json. + * @param collectionItemJson the json document containing the features, never + * null + * @return the parsed id, may be null if no feature could be found + */ + public static String parseFeatureId(JsonPath collectionItemJson) { + List> features = collectionItemJson.get("features"); + if (features == null) + return null; + for (Map feature : features) { + if (feature.containsKey("id")) + return feature.get("id").toString(); + } + return null; + } + + /** + * Parses the temporal extent from the passed collection. + * @param collection the collection containing the extent to parse, never + * null + * @return the parsed temporal extent, null if no extent exists + * @throws IllegalArgumentException if the number of items in the extent invalid + * + */ + public static TemporalExtent parseTemporalExtent(Map collection) { + Object extent = collection.get("extent"); + if (extent == null || !(extent instanceof Map)) + return null; + Object spatial = ((Map) extent).get("temporal"); + if (spatial == null || !(spatial instanceof List)) + return null; + List coords = (List) spatial; + if (coords.size() == 2) { + ZonedDateTime begin = parseAsDate((String) coords.get(0)); + ZonedDateTime end = parseAsDate((String) coords.get(1)); + return new TemporalExtent(begin, end); + } + throw new IllegalArgumentException("Temporal extent with " + coords.size() + " items is invalid"); + } + + /** + * Parses the passed string as ISO 8601 date. + * @param dateTime the dateTime to parse, never null + * @return the parsed date, never null + */ + public static ZonedDateTime parseAsDate(String dateTime) { + return ZonedDateTime.parse(dateTime); + } + + /** + * Formats the passed string as ISO 8601 date. Example: "2018-02-12T23:20:50Z" + * @param dateTime the dateTime to format, never null + * @return the formatted date, never null + */ + public static String formatDate(ZonedDateTime dateTime) { + return DateTimeFormatter.ISO_INSTANT.format(dateTime); + } + + /** + * Formats the passed string as ISO 8601 date. Example: "2018-02-12" + * @param date the dateTime to format, never null + * @return the formatted date, never null + */ + public static String formatDate(LocalDate date) { + return DateTimeFormatter.ISO_DATE.format(date); + } + + /** + * Formats the passed string as a period using a start and end time. Example: + * "2018-02-12T00:00:00Z/2018-03-18T12:31:12Z" + * @param beginDateTime the begin dateTime to format, never null + * @param endDateTime the end dateTime to format, never null + * @return the formatted date, never null + */ + public static String formatDateRange(ZonedDateTime beginDateTime, ZonedDateTime endDateTime) { + return formatDate(beginDateTime) + "/" + formatDate(endDateTime); + } + + /** + * Formats the passed string as a period using start time and a duration. Example: + * "2018-02-12T00:00:00Z/P1M6DT12H31M12S" + * @param beginDate the begin date to format, never null + * @param endDate the end date to format, never null + * @return the formatted date, never null + */ + public static String formatDateRangeWithDuration(LocalDate beginDate, LocalDate endDate) { + Period betweenDate = Period.between(beginDate, endDate); + return formatDate(beginDate) + "/" + betweenDate; + } + + /** + * Parses the spatial extent from the passed collection. + * @param collection the collection containing the extent to parse, never + * null + * @return the parsed bbox, null if no extent exists + * @throws IllegalArgumentException if the number of items in the extent invalid + * + */ + public static BBox parseSpatialExtent(Map collection) { + Object extent = collection.get("extent"); + if (extent == null || !(extent instanceof Map)) + return null; + Object spatial = ((Map) extent).get("spatial"); + if (spatial == null || !(spatial instanceof List)) + return null; + List coords = (List) spatial; + if (coords.size() == 4) { + double minX = parseValueAsDouble(coords.get(0)); + double minY = parseValueAsDouble(coords.get(1)); + double maxX = parseValueAsDouble(coords.get(2)); + double maxY = parseValueAsDouble(coords.get(3)); + return new BBox(minX, minY, maxX, maxY); + } + else if (coords.size() == 6) { + throw new IllegalArgumentException( + "BBox with " + coords.size() + " coordinates is currently not supported"); + } + throw new IllegalArgumentException("BBox with " + coords.size() + " coordinates is invalid"); + } + + /** + * Parses all links with 'type' of one of the passed mediaTypes and the 'rel' property + * with the passed value. + * @param links list of all links, never null + * @param mediaTypesToSupport a list of media types the links searched for should + * support, may be empty but never null + * @param expectedRel the expected value of the property 'rel', never + * null + * @return a list of links supporting one of the media types and with the expected + * 'rel' property, may be empty but never null + */ + public static List> findLinksWithSupportedMediaTypeByRel(List> links, + List mediaTypesToSupport, String expectedRel) { + List> alternateLinks = new ArrayList<>(); + for (Map link : links) { + Object type = link.get("type"); + Object rel = link.get("rel"); + if (expectedRel.equals(rel) && isSupportedMediaType(type, mediaTypesToSupport)) + alternateLinks.add(link); + } + return alternateLinks; + } + + /** + * Parsing the media types which does not have a link woth property 'type' for. + * @param links list of links to search in, never null + * @param mediaTypesToSuppport a list of media types which should be supported, never + * null + * @return the media types which does not have a link for. + */ + public static List findUnsupportedTypes(List> links, + List mediaTypesToSuppport) { + List unsupportedType = new ArrayList<>(); + for (String contentMediaType : mediaTypesToSuppport) { + boolean hasLinkForContentType = hasLinkForContentType(links, contentMediaType); + if (!hasLinkForContentType) + unsupportedType.add(contentMediaType); + } + return unsupportedType; + } + + /** + * Parses the links without 'rel' or 'type' property. + * @param links list of links to search in, never null + * @param rels relation types + * @return the links without 'rel' or 'type' property + */ + public static List findLinksWithoutRelOrType(List> links, Set rels) { + List linksWithoutRelOrType = new ArrayList<>(); + for (Map link : links) { + if (rels.contains(link.get("rel")) && !linkIncludesRelAndType(link)) + linksWithoutRelOrType.add((String) link.get("href")); + } + return linksWithoutRelOrType; + } + + /** + * Parses the link with 'rel=self'. + * @param links list of links to search in, never null + * @param expectedRel the expected value of the property 'rel', never + * null + * @return the link to itself or null if no such link exists + */ + public static Map findLinkByRel(List> links, String expectedRel) { + if (links == null) + return null; + for (Map link : links) { + Object rel = link.get("rel"); + if (expectedRel.equals(rel)) + return link; + } + return null; + } + + /** + * Checks if the passed link contains 'rel' and 'type' properties. + * @param link to check, never null + * @return true if the link contains 'rel' and 'type' properties, + * false otherwise + */ + public static boolean linkIncludesRelAndType(Map link) { + Object rel = link.get("rel"); + Object type = link.get("type"); + if (rel != null && type != null) + return true; + return false; + } + + /** + * Checks if a property with the passed name exists in the jsonPath. + * @param propertyName name of the property to check, never null + * @param jsonPath to check, never null + * @return true if the property exists, false otherwise + */ + public static boolean hasProperty(String propertyName, JsonPath jsonPath) { + return jsonPath.get(propertyName) != null; + } + + /** + * Collects the number of all returned features by iterating over all 'next' links and + * summarizing the size of features in 'features' array property. + * @param jsonPath the initial collection, never null + * @param maximumLimit the limit parameter value to use, if <= 0 the parameter is + * omitted + * @return the number of all returned features + * @throws URISyntaxException if the creation of a uri fails + */ + public static int collectNumberOfAllReturnedFeatures(JsonPath jsonPath, int maximumLimit) + throws URISyntaxException { + int numberOfAllReturnedFeatures = jsonPath.getList("features").size(); + Map nextLink = findLinkByRel(jsonPath.getList("links"), "next"); + while (nextLink != null) { + String nextUrl = (String) nextLink.get("href"); + URI uri = new URI(nextUrl); + + RequestSpecification accept = given().log().all().baseUri(nextUrl).accept(GEOJSON_MIME_TYPE); + String[] pairs = uri.getQuery().split("&"); + String limitParamFromUri = null; + for (String pair : pairs) { + int idx = pair.indexOf("="); + String key = pair.substring(0, idx); + String value = pair.substring(idx + 1); + if ("limit".equals(key)) { + limitParamFromUri = value; + } + else { + accept.param(key, value); + } + } + if (maximumLimit > 0) { + accept.param("limit", maximumLimit); + } + else if (limitParamFromUri != null) { + accept.param("limit", limitParamFromUri); + } + + Response response = accept.when().request(GET); + response.then().statusCode(200); + + JsonPath nextJsonPath = response.jsonPath(); + int features = nextJsonPath.getList("features").size(); + if (features > 0) { + numberOfAllReturnedFeatures += features; + nextLink = findLinkByRel(nextJsonPath.getList("links"), "next"); + } + else { + nextLink = null; + } + } + return numberOfAllReturnedFeatures; + } + + public static Response getCollectionResponse(String serverUrl, String collectionId, RequestSpecification init) { + return init.baseUri(getCollectionURL(serverUrl, collectionId)).accept(JSON).when().request(GET); + } + + public static String getCollectionURL(String serverUrl, String collectionId) { + // https://github.com/opengeospatial/ets-ogcapi-edr10/issues/110 + // check for trailing forward slash + serverUrl = serverUrl.endsWith("/") ? serverUrl.substring(0, serverUrl.length() - 1) : serverUrl; + + String path = "/collections"; + path = collectionId != null ? path.concat("/" + collectionId) : path; + return serverUrl + path; + } + + private static boolean isSameMediaType(String mediaType1, String mediaType2) { + if (mediaType1.contains(";") || mediaType2.contains(";")) { + // media types are not case sensitive + String[] components1 = mediaType1.toLowerCase().split(";"); + String[] components2 = mediaType2.toLowerCase().split(";"); + // type and subtype must match + if (!components1[0].trim().equals(components2[0].trim())) + return false; + Set parameters1 = new HashSet<>(); + Set parameters2 = new HashSet<>(); + // normalize parameter values and compare them + for (int i = 1; i < components1.length; i++) { + String parameter = components1[i].trim().replace("\"", ""); + if (!parameter.isEmpty()) + parameters1.add(parameter); + } + for (int i = 1; i < components2.length; i++) { + String parameter = components2[i].trim().replace("\"", ""); + if (!parameter.isEmpty()) + parameters2.add(parameter); + } + if (parameters1.size() != parameters2.size()) + return false; + if (!parameters1.containsAll(parameters2)) + return false; + } + else if (!mediaType1.trim().equalsIgnoreCase(mediaType2.trim())) + return false; + + return true; + } + + private static boolean hasLinkForContentType(List> alternateLinks, String mediaType) { + for (Map alternateLink : alternateLinks) { + Object type = alternateLink.get("type"); + if (type instanceof String && isSameMediaType(mediaType, (String) type)) + return true; + } + return false; + } + + private static boolean isSupportedMediaType(Object type, List mediaTypes) { + for (String mediaType : mediaTypes) { + if (type instanceof String && isSameMediaType(mediaType, (String) type)) + return true; + } + return false; + } + + private static double parseValueAsDouble(Object cords) { + if (cords instanceof Integer) { + return ((Integer) cords).doubleValue(); + } + else if (cords instanceof Float) { + return ((Float) cords).doubleValue(); + } + else if (cords instanceof Double) { + return (Double) cords; + } + else { + return Double.parseDouble(cords.toString()); + } + } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/util/Link.java b/src/main/java/org/opengis/cite/ogcapiedr10/util/Link.java index df4e376..205018c 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/util/Link.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/util/Link.java @@ -1,34 +1,41 @@ package org.opengis.cite.ogcapiedr10.util; public class Link { - private String href = null; - private String rel = null; - private String type = null; - - public Link(String href, String rel, String type) { - this.href = href; - this.rel = rel; - this.type = type; - } - + + private String href = null; + + private String rel = null; + + private String type = null; + + public Link(String href, String rel, String type) { + this.href = href; + this.rel = rel; + this.type = type; + } + public String getHref() { return href; } + public void setHref(String href) { this.href = href; } + public String getRel() { return rel; } + public void setRel(String rel) { this.rel = rel; } + public String getType() { return type; } + public void setType(String type) { this.type = type; } - - + } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/util/NamespaceBindings.java b/src/main/java/org/opengis/cite/ogcapiedr10/util/NamespaceBindings.java index b020f6e..57a7b6e 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/util/NamespaceBindings.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/util/NamespaceBindings.java @@ -11,96 +11,87 @@ import org.opengis.cite.ogcapiedr10.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; - } + @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); - } + @Override + public String getPrefix(String namespaceURI) { + return bindings.get(namespaceURI); + } - @Override - public Iterator getPrefixes(String namespaceURI) { - return Arrays.asList(getPrefix(namespaceURI)).iterator(); - } + @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.ogcapiedr10.Namespaces#OWS}
    • - *
    • xlink: {@value org.opengis.cite.ogcapiedr10.Namespaces#XLINK}
    • - *
    • gml: {@value org.opengis.cite.ogcapiedr10.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.ogcapiedr10.Namespaces#OWS}
    • + *
    • xlink: {@value org.opengis.cite.ogcapiedr10.Namespaces#XLINK}
    • + *
    • gml: {@value org.opengis.cite.ogcapiedr10.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; + } + + @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/ogcapiedr10/util/TemporalExtent.java b/src/main/java/org/opengis/cite/ogcapiedr10/util/TemporalExtent.java index 847b90e..e7f94c3 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/util/TemporalExtent.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/util/TemporalExtent.java @@ -7,21 +7,21 @@ */ public class TemporalExtent { - private ZonedDateTime begin; + private ZonedDateTime begin; - private ZonedDateTime end; + private ZonedDateTime end; - public TemporalExtent( ZonedDateTime begin, ZonedDateTime end ) { - this.begin = begin; - this.end = end; - } + public TemporalExtent(ZonedDateTime begin, ZonedDateTime end) { + this.begin = begin; + this.end = end; + } - public ZonedDateTime getBegin() { - return begin; - } + public ZonedDateTime getBegin() { + return begin; + } - public ZonedDateTime getEnd() { - return end; - } + public ZonedDateTime getEnd() { + return end; + } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/util/TestSuiteLogger.java b/src/main/java/org/opengis/cite/ogcapiedr10/util/TestSuiteLogger.java index f14039a..7ffc106 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/util/TestSuiteLogger.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/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/ogcapiedr10/util/URIUtils.java b/src/main/java/org/opengis/cite/ogcapiedr10/util/URIUtils.java index 00bec9a..2cd1eab 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/util/URIUtils.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/util/URIUtils.java @@ -20,52 +20,49 @@ */ public class URIUtils { - /** - * 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 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; + } } diff --git a/src/main/java/org/opengis/cite/ogcapiedr10/util/XMLUtils.java b/src/main/java/org/opengis/cite/ogcapiedr10/util/XMLUtils.java index bbd7dc0..a21ab32 100644 --- a/src/main/java/org/opengis/cite/ogcapiedr10/util/XMLUtils.java +++ b/src/main/java/org/opengis/cite/ogcapiedr10/util/XMLUtils.java @@ -19,32 +19,32 @@ */ public class XMLUtils { - /** - * 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(); - } + /** + * 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(); + } } diff --git a/src/test/java/org/opengis/cite/ogcapiedr10/VerifySuiteFixtureListener.java b/src/test/java/org/opengis/cite/ogcapiedr10/VerifySuiteFixtureListener.java index f456947..6fd8285 100644 --- a/src/test/java/org/opengis/cite/ogcapiedr10/VerifySuiteFixtureListener.java +++ b/src/test/java/org/opengis/cite/ogcapiedr10/VerifySuiteFixtureListener.java @@ -12,39 +12,38 @@ public class VerifySuiteFixtureListener { - private static XmlSuite xmlSuite; - private static ISuite suite; - - public VerifySuiteFixtureListener() { - } - - @BeforeClass - public static void setUpClass() { - xmlSuite = mock(XmlSuite.class); - suite = mock(ISuite.class); - when(suite.getXmlSuite()).thenReturn(xmlSuite); - } - - @AfterClass - public static void tearDownClass() { - } - - @Before - public void setUp() { - } - - @After - public void tearDown() { - } - - @Test(expected = IllegalArgumentException.class) - public void noSuiteParameters() { - Map params = new HashMap(); - when(xmlSuite.getParameters()).thenReturn(params); - SuiteFixtureListener iut = new SuiteFixtureListener(); - iut.onStart(suite); - } - - + private static XmlSuite xmlSuite; + + private static ISuite suite; + + public VerifySuiteFixtureListener() { + } + + @BeforeClass + public static void setUpClass() { + xmlSuite = mock(XmlSuite.class); + suite = mock(ISuite.class); + when(suite.getXmlSuite()).thenReturn(xmlSuite); + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + @Test(expected = IllegalArgumentException.class) + public void noSuiteParameters() { + Map params = new HashMap(); + when(xmlSuite.getParameters()).thenReturn(params); + SuiteFixtureListener iut = new SuiteFixtureListener(); + iut.onStart(suite); + } } diff --git a/src/test/java/org/opengis/cite/ogcapiedr10/VerifyTestNGController.java b/src/test/java/org/opengis/cite/ogcapiedr10/VerifyTestNGController.java index 2ee217a..693a0d3 100644 --- a/src/test/java/org/opengis/cite/ogcapiedr10/VerifyTestNGController.java +++ b/src/test/java/org/opengis/cite/ogcapiedr10/VerifyTestNGController.java @@ -15,19 +15,20 @@ */ public class VerifyTestNGController { - private static DocumentBuilder docBuilder; - @Rule - public ExpectedException thrown = ExpectedException.none(); + private static DocumentBuilder docBuilder; + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testValidateTestRunArgs() throws Exception { + // Integration Test + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document testRunProps = db.parse(this.getClass().getResourceAsStream("/test-run-props.xml")); + TestNGController controller = new TestNGController(System.getProperty("java.io.tmpdir")); + Source testResults = controller.doTestRun(testRunProps); + System.out.println("Test results: " + testResults.getSystemId()); + } - @Test - public void testValidateTestRunArgs() throws Exception { - // Integration Test - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document testRunProps = db.parse(this.getClass().getResourceAsStream("/test-run-props.xml")); - TestNGController controller = new TestNGController(System.getProperty("java.io.tmpdir")); - Source testResults = controller.doTestRun(testRunProps); - System.out.println("Test results: " + testResults.getSystemId()); - } } \ No newline at end of file