diff --git a/pom.xml b/pom.xml index 966a5f8..9aefe9e 100644 --- a/pom.xml +++ b/pom.xml @@ -3,11 +3,9 @@ org.opengis.cite ets-common - 9 + 14-SNAPSHOT - 4.0.0 - org.opengis.cite ets-geotiff11 1.2-SNAPSHOT jar @@ -47,109 +45,75 @@ geotiff11 1.1 - 5.4.1 - 1.16.6 + 6.0.0-RC2 org.opengis.cite.teamengine teamengine-spi + org.opengis.cite schema-utils - - com.sun.jersey - jersey-client - + junit junit + test org.mockito mockito-core + test + + + org.apache.commons + commons-lang3 + + + commons-io + commons-io - org.apache.commons - commons-lang3 - 3.9 - - - commons-io - commons-io - 2.7 - - org.apache.commons commons-csv - 1.5 - + org.openpreservation.jhove jhove-modules - ${jhove.version} org.testng testng - 6.9.10 org.opengis.cite.saxon saxon9 - 9.0.0.8 - - - xml-apis - xml-apis - 1.4.01 xerces xercesImpl - 2.12.2 + + + xml-apis + xml-apis + + com.beust jcommander - 1.48 org.openpreservation.jhove jhove-core - ${jhove.version} - - - javax.ws.rs - jsr311-api - 1.1.1 - - - maven-javadoc-plugin - 2.10.4 - - true - package - - http://testng.org/javadocs/ - - - - - attach-javadocs - - jar - - - - maven-assembly-plugin @@ -173,66 +137,12 @@ - - maven-surefire-plugin - - - maven-compiler-plugin - - - maven-jar-plugin - - - maven-release-plugin - 2.5.3 - - true - @{project.version} - release - - - - org.apache.maven.plugins - maven-site-plugin - 3.7.1 - - - site-package - prepare-package - - jar - - - - - - org.asciidoctor - asciidoctor-maven-plugin - 1.5.7.1 - - - - false - - - - org.codehaus.mojo - buildnumber-maven-plugin - - - maven-scm-publish-plugin - 1.1 - - gh-pages - - io.fabric8 docker-maven-plugin - 0.27.2 @@ -273,50 +183,37 @@ - - maven-dependency-plugin - 3.0.0 - - - - org.opengis.cite.teamengine - teamengine-web - ${docker.teamengine.version} - war - - - org.opengis.cite.teamengine - teamengine-web - ${docker.teamengine.version} - common-libs - zip - - - org.opengis.cite.teamengine - teamengine-console - ${docker.teamengine.version} - base - zip - - - - - - org.apache.maven.plugins - maven-resources-plugin - 3.0.1 - - - - exe - dll - tif - - - - + + + src/main/resources + true + + **/*.exe + **/*.dll + **/*.tif + **/*.csv + **/*.zip + + + + src/main/resources + false + + **/*.exe + **/*.dll + **/*.tif + **/*.csv + **/*.zip + + + + src/main/javadoc + true + doc/${ets-code}/${project.version} + + @@ -326,7 +223,6 @@ maven-failsafe-plugin - 2.22.0 @@ -374,32 +270,6 @@ - - release - - - - maven-gpg-plugin - 1.6 - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - - - - diff --git a/src/assembly/aio.xml b/src/assembly/aio.xml index 637399b..34c320c 100644 --- a/src/assembly/aio.xml +++ b/src/assembly/aio.xml @@ -12,9 +12,6 @@ true true runtime - - com.sun.jersey:jersey-server - diff --git a/src/assembly/deps.xml b/src/assembly/deps.xml index dd23742..080a72e 100644 --- a/src/assembly/deps.xml +++ b/src/assembly/deps.xml @@ -10,24 +10,13 @@ false - - - com.sun.jersey:jersey-client - org.opengis.cite:schema-utils - - / - false - runtime - false - org.opengis.cite.teamengine:teamengine-spi - com.sun.jersey:jersey-client - org.opengis.cite:schema-utils - org.testng:testng - com.beust:jcommander - javax.ws.rs:jsr311-api + *:jersey-client + *:jersey-server + *:jersey-common + jakarta.ws.rs:jakarta.ws.rs-api / false diff --git a/src/docker/Dockerfile b/src/docker/Dockerfile index 700edaa..630cd82 100644 --- a/src/docker/Dockerfile +++ b/src/docker/Dockerfile @@ -1,4 +1,6 @@ -FROM tomcat:7.0-jre8 +FROM tomcat:10.1-jre17 + +RUN apt update && apt install -y unzip # add TEAM engine webapp ADD maven/dependency/teamengine-web-*.war /root/ diff --git a/src/main/java/org/opengis/cite/geotiff11/CommandLineArguments.java b/src/main/java/org/opengis/cite/geotiff11/CommandLineArguments.java index d17ef17..70c8a01 100644 --- a/src/main/java/org/opengis/cite/geotiff11/CommandLineArguments.java +++ b/src/main/java/org/opengis/cite/geotiff11/CommandLineArguments.java @@ -1,15 +1,15 @@ package org.opengis.cite.geotiff11; -import com.beust.jcommander.Parameter; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.List; +import com.beust.jcommander.Parameter; + /** - * Declares supported command line arguments that are parsed using the - * JCommander library. All arguments are optional. The default values are as - * follows: + * Declares supported command line arguments that are parsed using the JCommander library. + * All arguments are optional. The default values are as follows: *
    *
  • XML properties file: ${user.home}/test-run-props.xml
  • *
  • outputDir: ${user.home}
  • @@ -26,35 +26,61 @@ */ public class CommandLineArguments { - @Parameter(description = "Properties file") - private final List xmlProps; - - @Parameter(names = {"-o", "--outputDir"}, description = "Output directory") - private String outputDir; - - @Parameter(names = {"-d", "--deleteSubjectOnFinish"}, description = "Delete file containing representation of test subject when finished") - private boolean deleteSubjectOnFinish = false; - - public CommandLineArguments() { - this.xmlProps = new ArrayList<>(); - } - - public File getPropertiesFile() { - File fileRef; - if (xmlProps.isEmpty()) { - fileRef = new File(System.getProperty("user.home"), "test-run-props.xml"); - } else { - String propsFile = xmlProps.get(0); - fileRef = (propsFile.startsWith("file:")) ? new File(URI.create(propsFile)) : new File(propsFile); - } - return fileRef; - } - - public String getOutputDir() { - return (null != outputDir) ? outputDir : System.getProperty("user.home"); - } - - public boolean doDeleteSubjectOnFinish() { - return deleteSubjectOnFinish; - } + @Parameter(description = "Properties file") + private List xmlProps; + + @Parameter(names = { "-o", "--outputDir" }, description = "Output directory") + private String outputDir; + + @Parameter(names = { "-d", "--deleteSubjectOnFinish" }, + description = "Delete file containing representation of test subject when finished") + private boolean deleteSubjectOnFinish = false; + + /** + *

    + * Constructor for CommandLineArguments. + *

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

    + * getPropertiesFile. + *

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

    + * Getter for the field outputDir. + *

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

    + * doDeleteSubjectOnFinish. + *

    + * @return a boolean + */ + public boolean doDeleteSubjectOnFinish() { + return deleteSubjectOnFinish; + } + } diff --git a/src/main/java/org/opengis/cite/geotiff11/CommonFixture.java b/src/main/java/org/opengis/cite/geotiff11/CommonFixture.java index 4f5f052..6246283 100644 --- a/src/main/java/org/opengis/cite/geotiff11/CommonFixture.java +++ b/src/main/java/org/opengis/cite/geotiff11/CommonFixture.java @@ -1,20 +1,5 @@ package org.opengis.cite.geotiff11; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import javax.ws.rs.core.MediaType; import org.opengis.cite.geotiff11.util.ClientUtils; import org.testng.ITestContext; import org.testng.SkipException; @@ -22,86 +7,93 @@ import org.testng.annotations.BeforeMethod; import org.w3c.dom.Document; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientRequestContext; +import jakarta.ws.rs.core.Response; + /** - * A supporting base class that sets up a common test fixture. These - * configuration methods are invoked before those defined in a subclass. + * A supporting base class that sets up a common test fixture. These configuration methods + * are invoked before those defined in a subclass. */ public class CommonFixture { - /** - * Root test suite package (absolute path). - */ - public static final String ROOT_PKG_PATH = "/org/opengis/cite/geotiff11/"; - /** - * HTTP client component (JAX-RS Client API). - */ - protected Client client; - /** - * An HTTP request message. - */ - protected ClientRequest request; - /** - * An HTTP response message. - */ - protected ClientResponse response; + /** + * Root test suite package (absolute path). + */ + public static final String ROOT_PKG_PATH = "/org/opengis/cite/geotiff11/"; + + // TODO: are the members below ever set? + /** + * HTTP client component (JAX-RS Client API). + */ + protected Client client; + + /** + * An HTTP request message. + */ + protected ClientRequestContext request; + + /** + * An HTTP response message. + */ + protected Response response; + + /** + * Initializes the common test fixture with a client component for interacting with + * HTTP endpoints. + * @param testContext The test context that contains all the information for a test + * run, including suite attributes. + */ + @BeforeClass + public void initCommonFixture(ITestContext testContext) { + Object obj = testContext.getSuite().getAttribute(SuiteAttribute.CLIENT.getName()); + if (null != obj) { + this.client = Client.class.cast(obj); + } + obj = testContext.getSuite().getAttribute(SuiteAttribute.TEST_SUBJECT.getName()); + if (null == obj) { + throw new SkipException("Test subject not found in ITestContext."); + } + } - /** - * Initializes the common test fixture with a client component for - * interacting with HTTP endpoints. - * - * @param testContext The test context that contains all the information for - * a test run, including suite attributes. - */ - @BeforeClass - public void initCommonFixture(ITestContext testContext) { - Object obj = testContext.getSuite().getAttribute(SuiteAttribute.CLIENT.getName()); - if (null != obj) { - this.client = Client.class.cast(obj); - } - obj = testContext.getSuite().getAttribute(SuiteAttribute.TEST_SUBJECT.getName()); - if (null == obj) { - throw new SkipException("Test subject not found in ITestContext."); - } - } + /** + *

    + * clearMessages. + *

    + */ + @BeforeMethod + public void clearMessages() { + this.request = null; + this.response = null; + } - @BeforeMethod - public void clearMessages() { - this.request = null; - this.response = null; - } + /** + * Obtains the (XML) response entity as a DOM Document. This convenience method wraps + * a static method call to facilitate unit testing (Mockito workaround). + * @param response A representation of an HTTP response message. + * @param targetURI The target URI from which the entity was retrieved (may be null). + * @return A Document representing the entity. + * @see ClientUtils#getResponseEntityAsDocument + */ + public Document getResponseEntityAsDocument(Response response, String targetURI) { + return ClientUtils.getResponseEntityAsDocument(response, targetURI); + } - /** - * 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). + * @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. + * + * @see ClientUtils#buildGetRequest + */ + /* + * seems unused public ClientRequestContext buildGetRequest(URI endpoint, Map qryParams, MediaType... mediaTypes) { return + * ClientUtils.buildGetRequest(endpoint, qryParams, mediaTypes); } + */ - /** - * Builds an HTTP request message that uses the GET method. This convenience - * method wraps a static method call to facilitate unit testing (Mockito - * workaround). - * - * @param endpoint A URI indicating the target resource. - * @param qryParams A Map containing query parameters (may be null); - * @param mediaTypes A list of acceptable media types; if not specified, - * generic XML ("application/xml") is preferred. - * @return A ClientRequest object. - * - * @see ClientUtils#buildGetRequest - */ - public ClientRequest buildGetRequest(URI endpoint, - Map qryParams, MediaType... mediaTypes) { - return ClientUtils.buildGetRequest(endpoint, qryParams, mediaTypes); - } } diff --git a/src/main/java/org/opengis/cite/geotiff11/ETSAssert.java b/src/main/java/org/opengis/cite/geotiff11/ETSAssert.java index 5d6e529..0b56e51 100644 --- a/src/main/java/org/opengis/cite/geotiff11/ETSAssert.java +++ b/src/main/java/org/opengis/cite/geotiff11/ETSAssert.java @@ -25,186 +25,161 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import com.sun.jersey.api.client.ClientResponse; - /** * Provides a set of custom assertion methods. */ public class ETSAssert { - private static final Logger LOGR = Logger.getLogger(ETSAssert.class.getPackage().getName()); + private static final Logger LOGR = Logger.getLogger(ETSAssert.class.getPackage().getName()); + + private ETSAssert() { + } - private ETSAssert() { - } + /** + * Asserts that the qualified name of a DOM Node matches the expected value. + * @param node The Node to check. + * @param qName A QName object containing a namespace name (URI) and a local part. + */ + public static void assertQualifiedName(Node node, QName qName) { + Assert.assertEquals(node.getLocalName(), qName.getLocalPart(), ErrorMessage.get(ErrorMessageKeys.LOCAL_NAME)); + Assert.assertEquals(node.getNamespaceURI(), qName.getNamespaceURI(), + ErrorMessage.get(ErrorMessageKeys.NAMESPACE_NAME)); + } - /** - * Asserts that the qualified name of a DOM Node matches the expected value. - * - * @param node - * The Node to check. - * @param qName - * A QName object containing a namespace name (URI) and a local - * part. - */ - public static void assertQualifiedName(Node node, QName qName) { - Assert.assertEquals(node.getLocalName(), qName.getLocalPart(), ErrorMessage.get(ErrorMessageKeys.LOCAL_NAME)); - Assert.assertEquals(node.getNamespaceURI(), qName.getNamespaceURI(), - ErrorMessage.get(ErrorMessageKeys.NAMESPACE_NAME)); - } + /** + * Asserts that an XPath 1.0 expression holds true for the given evaluation context. + * The following standard namespace bindings do not need to be explicitly declared: + * + *
      + *
    • ows: {@value org.opengis.cite.geotiff11.Namespaces#OWS}
    • + *
    • xlink: {@value org.opengis.cite.geotiff11.Namespaces#XLINK}
    • + *
    • gml: {@value org.opengis.cite.geotiff11.Namespaces#GML}
    • + *
    + * @param expr A valid XPath 1.0 expression. + * @param context The context node. + * @param namespaceBindings A collection of namespace bindings for the XPath + * expression, where each entry maps a namespace URI (key) to a prefix (value). It may + * be {@code null}. + */ + public static void assertXPath(String expr, Node context, Map namespaceBindings) { + if (null == context) { + throw new NullPointerException("Context node is null."); + } + NamespaceBindings bindings = NamespaceBindings.withStandardBindings(); + bindings.addAllBindings(namespaceBindings); + XPath xpath = XPathFactory.newInstance().newXPath(); + xpath.setNamespaceContext(bindings); + Boolean result; + try { + result = (Boolean) xpath.evaluate(expr, context, XPathConstants.BOOLEAN); + } + catch (XPathExpressionException xpe) { + String msg = ErrorMessage.format(ErrorMessageKeys.XPATH_ERROR, expr); + LOGR.log(Level.WARNING, msg, xpe); + throw new AssertionError(msg); + } + Element elemNode; + if (Document.class.isInstance(context)) { + elemNode = Document.class.cast(context).getDocumentElement(); + } + else { + elemNode = (Element) context; + } + Assert.assertTrue(result, ErrorMessage.format(ErrorMessageKeys.XPATH_RESULT, elemNode.getNodeName(), expr)); + } - /** - * Asserts that an XPath 1.0 expression holds true for the given evaluation - * context. The following standard namespace bindings do not need to be - * explicitly declared: - * - *
      - *
    • ows: {@value org.opengis.cite.geotiff11.Namespaces#OWS}
    • - *
    • xlink: {@value org.opengis.cite.geotiff11.Namespaces#XLINK}
    • - *
    • gml: {@value org.opengis.cite.geotiff11.Namespaces#GML}
    • - *
    - * - * @param expr - * A valid XPath 1.0 expression. - * @param context - * The context node. - * @param namespaceBindings - * A collection of namespace bindings for the XPath expression, - * where each entry maps a namespace URI (key) to a prefix - * (value). It may be {@code null}. - */ - public static void assertXPath(String expr, Node context, Map namespaceBindings) { - if (null == context) { - throw new NullPointerException("Context node is null."); - } - NamespaceBindings bindings = NamespaceBindings.withStandardBindings(); - bindings.addAllBindings(namespaceBindings); - XPath xpath = XPathFactory.newInstance().newXPath(); - xpath.setNamespaceContext(bindings); - Boolean result; - try { - result = (Boolean) xpath.evaluate(expr, context, XPathConstants.BOOLEAN); - } catch (XPathExpressionException xpe) { - String msg = ErrorMessage.format(ErrorMessageKeys.XPATH_ERROR, expr); - LOGR.log(Level.WARNING, msg, xpe); - throw new AssertionError(msg); - } - Element elemNode; - if (Document.class.isInstance(context)) { - elemNode = Document.class.cast(context).getDocumentElement(); - } else { - elemNode = (Element) context; - } - Assert.assertTrue(result, ErrorMessage.format(ErrorMessageKeys.XPATH_RESULT, elemNode.getNodeName(), expr)); - } + /** + * Asserts that an XML resource is schema-valid. + * @param validator The Validator to use. + * @param source The XML Source to be validated. + */ + public static void assertSchemaValid(Validator validator, Source source) { + ValidationErrorHandler errHandler = new ValidationErrorHandler(); + validator.setErrorHandler(errHandler); + try { + validator.validate(source); + } + catch (Exception e) { + throw new AssertionError(ErrorMessage.format(ErrorMessageKeys.XML_ERROR, e.getMessage())); + } + Assert.assertFalse(errHandler.errorsDetected(), ErrorMessage.format(ErrorMessageKeys.NOT_SCHEMA_VALID, + errHandler.getErrorCount(), errHandler.toString())); + } - /** - * Asserts that an XML resource is schema-valid. - * - * @param validator - * The Validator to use. - * @param source - * The XML Source to be validated. - */ - public static void assertSchemaValid(Validator validator, Source source) { - ValidationErrorHandler errHandler = new ValidationErrorHandler(); - validator.setErrorHandler(errHandler); - try { - validator.validate(source); - } catch (Exception e) { - throw new AssertionError(ErrorMessage.format(ErrorMessageKeys.XML_ERROR, e.getMessage())); - } - Assert.assertFalse(errHandler.errorsDetected(), ErrorMessage.format(ErrorMessageKeys.NOT_SCHEMA_VALID, - errHandler.getErrorCount(), errHandler.toString())); - } + /** + * Asserts that an XML resource satisfies all applicable constraints defined for the + * specified phase in a Schematron (ISO 19757-3) schema. The "xslt2" query language + * binding is supported. Two phase names have special meanings: + *
      + *
    • "#ALL": All patterns are active
    • + *
    • "#DEFAULT": The phase identified by the defaultPhase attribute on the schema + * element should be used.
    • + *
    + * @param schemaRef A URL that denotes the location of a Schematron schema. + * @param xmlSource The XML Source to be validated. + * @param activePhase The active phase (pattern set) whose patterns are used for + * validation; this is set to "#ALL" if not specified. + */ + public static void assertSchematronValid(URL schemaRef, Source xmlSource, String activePhase) { + String phase = (null == activePhase || activePhase.isEmpty()) ? "#ALL" : activePhase; + SchematronValidator validator; + try { + validator = new SchematronValidator(new StreamSource(schemaRef.toString()), phase); + } + catch (Exception e) { + StringBuilder msg = new StringBuilder("Failed to process Schematron schema at "); + msg.append(schemaRef).append('\n'); + msg.append(e.getMessage()); + throw new AssertionError(msg); + } + DOMResult result = (DOMResult) validator.validate(xmlSource); + Assert.assertFalse(validator.ruleViolationsDetected(), ErrorMessage.format(ErrorMessageKeys.NOT_SCHEMA_VALID, + validator.getRuleViolationCount(), XMLUtils.writeNodeToString(result.getNode()))); + } - /** - * Asserts that an XML resource satisfies all applicable constraints defined - * for the specified phase in a Schematron (ISO 19757-3) schema. The "xslt2" - * query language binding is supported. Two phase names have special - * meanings: - *
      - *
    • "#ALL": All patterns are active
    • - *
    • "#DEFAULT": The phase identified by the defaultPhase attribute on the - * schema element should be used.
    • - *
    - * - * @param schemaRef - * A URL that denotes the location of a Schematron schema. - * @param xmlSource - * The XML Source to be validated. - * @param activePhase - * The active phase (pattern set) whose patterns are used for - * validation; this is set to "#ALL" if not specified. - */ - public static void assertSchematronValid(URL schemaRef, Source xmlSource, String activePhase) { - String phase = (null == activePhase || activePhase.isEmpty()) ? "#ALL" : activePhase; - SchematronValidator validator; - try { - validator = new SchematronValidator(new StreamSource(schemaRef.toString()), phase); - } catch (Exception e) { - StringBuilder msg = new StringBuilder("Failed to process Schematron schema at "); - msg.append(schemaRef).append('\n'); - msg.append(e.getMessage()); - throw new AssertionError(msg); - } - DOMResult result = (DOMResult) validator.validate(xmlSource); - Assert.assertFalse(validator.ruleViolationsDetected(), ErrorMessage.format(ErrorMessageKeys.NOT_SCHEMA_VALID, - validator.getRuleViolationCount(), XMLUtils.writeNodeToString(result.getNode()))); - } + /** + * Asserts that the given XML entity contains the expected number of descendant + * elements having the specified name. + * @param xmlEntity A Document representing an XML entity. + * @param elementName The qualified name of the element. + * @param expectedCount The expected number of occurrences. + */ + public static void assertDescendantElementCount(Document xmlEntity, QName elementName, int expectedCount) { + NodeList features = xmlEntity.getElementsByTagNameNS(elementName.getNamespaceURI(), elementName.getLocalPart()); + Assert.assertEquals(features.getLength(), expectedCount, + String.format("Unexpected number of %s descendant elements.", elementName)); + } - /** - * Asserts that the given XML entity contains the expected number of - * descendant elements having the specified name. - * - * @param xmlEntity - * A Document representing an XML entity. - * @param elementName - * The qualified name of the element. - * @param expectedCount - * The expected number of occurrences. - */ - public static void assertDescendantElementCount(Document xmlEntity, QName elementName, int expectedCount) { - NodeList features = xmlEntity.getElementsByTagNameNS(elementName.getNamespaceURI(), elementName.getLocalPart()); - Assert.assertEquals(features.getLength(), expectedCount, - String.format("Unexpected number of %s descendant elements.", elementName)); - } + /** + * Asserts that the given response message contains an OGC exception report. The + * message body must contain an XML document that has a document element with the + * following properties: + * + *
      + *
    • [local name] = "ExceptionReport"
    • + *
    • [namespace name] = "http://www.opengis.net/ows/2.0"
    • + *
    + * @param rsp A ClientResponse object representing an HTTP response message. + * @param exceptionCode The expected OGC exception code. + * @param locator A case-insensitive string value expected to occur in the locator + * attribute (e.g. a parameter name); the attribute value will be ignored if the + * argument is null or empty. + */ + /* + * seems unused public static void assertExceptionReport(Response rsp, String + * exceptionCode, String locator) { Assert.assertEquals(rsp.getStatus(), + * Response.Status.BAD_REQUEST.getStatusCode(), + * ErrorMessage.get(ErrorMessageKeys.UNEXPECTED_STATUS)); Document doc = + * rsp.getEntity(Document.class); String expr = + * String.format("//ows:Exception[@exceptionCode = '%s']", exceptionCode); NodeList + * nodeList = null; try { nodeList = XMLUtils.evaluateXPath(doc, expr, null); } catch + * (XPathExpressionException xpe) { // won't happen } + * Assert.assertTrue(nodeList.getLength() > 0, "Exception not found in response: " + + * expr); if (null != locator && !locator.isEmpty()) { Element exception = (Element) + * nodeList.item(0); String locatorValue = + * exception.getAttribute("locator").toLowerCase(); + * Assert.assertTrue(locatorValue.contains(locator.toLowerCase()), + * String.format("Expected locator attribute to contain '%s']", locator)); } } + */ - /** - * Asserts that the given response message contains an OGC exception report. - * The message body must contain an XML document that has a document element - * with the following properties: - * - *
      - *
    • [local name] = "ExceptionReport"
    • - *
    • [namespace name] = "http://www.opengis.net/ows/2.0"
    • - *
    - * - * @param rsp - * A ClientResponse object representing an HTTP response message. - * @param exceptionCode - * The expected OGC exception code. - * @param locator - * A case-insensitive string value expected to occur in the - * locator attribute (e.g. a parameter name); the attribute value - * will be ignored if the argument is null or empty. - */ - public static void assertExceptionReport(ClientResponse rsp, String exceptionCode, String locator) { - Assert.assertEquals(rsp.getStatus(), ClientResponse.Status.BAD_REQUEST.getStatusCode(), - ErrorMessage.get(ErrorMessageKeys.UNEXPECTED_STATUS)); - Document doc = rsp.getEntity(Document.class); - String expr = String.format("//ows:Exception[@exceptionCode = '%s']", exceptionCode); - NodeList nodeList = null; - try { - nodeList = XMLUtils.evaluateXPath(doc, expr, null); - } catch (XPathExpressionException xpe) { - // won't happen - } - Assert.assertTrue(nodeList.getLength() > 0, "Exception not found in response: " + expr); - if (null != locator && !locator.isEmpty()) { - Element exception = (Element) nodeList.item(0); - String locatorValue = exception.getAttribute("locator").toLowerCase(); - Assert.assertTrue(locatorValue.contains(locator.toLowerCase()), - String.format("Expected locator attribute to contain '%s']", locator)); - } - } } diff --git a/src/main/java/org/opengis/cite/geotiff11/ErrorMessage.java b/src/main/java/org/opengis/cite/geotiff11/ErrorMessage.java index e43ef51..e15c69e 100644 --- a/src/main/java/org/opengis/cite/geotiff11/ErrorMessage.java +++ b/src/main/java/org/opengis/cite/geotiff11/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.geotiff11.MessageBundle"; - private static ResourceBundle msgResources = - ResourceBundle.getBundle(BASE_NAME); + private static final String BASE_NAME = "org.opengis.cite.geotiff11.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/geotiff11/ErrorMessageKeys.java b/src/main/java/org/opengis/cite/geotiff11/ErrorMessageKeys.java index 13a10fa..20adc25 100644 --- a/src/main/java/org/opengis/cite/geotiff11/ErrorMessageKeys.java +++ b/src/main/java/org/opengis/cite/geotiff11/ErrorMessageKeys.java @@ -1,22 +1,44 @@ package org.opengis.cite.geotiff11; /** - * Defines keys used to access localized messages for assertion errors. The - * messages are stored in Properties files that are encoded in ISO-8859-1 - * (Latin-1). For some languages the {@code native2ascii} tool must be used to - * process the files and produce escaped Unicode characters. + * Defines keys used to access localized messages for assertion errors. The messages are + * stored in Properties files that are encoded in ISO-8859-1 (Latin-1). For some languages + * the {@code native2ascii} tool must be used to process the files and produce escaped + * Unicode characters. */ public class ErrorMessageKeys { - public static final String NOT_SCHEMA_VALID = "NotSchemaValid"; - public static final String EMPTY_STRING = "EmptyString"; - public static final String XPATH_RESULT = "XPathResult"; - public static final String NAMESPACE_NAME = "NamespaceName"; - public static final String LOCAL_NAME = "LocalName"; - public static final String XML_ERROR = "XMLError"; - public static final String XPATH_ERROR = "XPathError"; - public static final String MISSING_INFOSET_ITEM = "MissingInfosetItem"; - public static final String UNEXPECTED_STATUS = "UnexpectedStatus"; - public static final String UNEXPECTED_MEDIA_TYPE = "UnexpectedMediaType"; - public static final String MISSING_ENTITY = "MissingEntity"; + /** Constant NOT_SCHEMA_VALID="NotSchemaValid" */ + public static final String NOT_SCHEMA_VALID = "NotSchemaValid"; + + /** Constant EMPTY_STRING="EmptyString" */ + public static final String EMPTY_STRING = "EmptyString"; + + /** Constant XPATH_RESULT="XPathResult" */ + public static final String XPATH_RESULT = "XPathResult"; + + /** Constant NAMESPACE_NAME="NamespaceName" */ + public static final String NAMESPACE_NAME = "NamespaceName"; + + /** Constant LOCAL_NAME="LocalName" */ + public static final String LOCAL_NAME = "LocalName"; + + /** Constant XML_ERROR="XMLError" */ + public static final String XML_ERROR = "XMLError"; + + /** Constant XPATH_ERROR="XPathError" */ + public static final String XPATH_ERROR = "XPathError"; + + /** Constant MISSING_INFOSET_ITEM="MissingInfosetItem" */ + public static final String MISSING_INFOSET_ITEM = "MissingInfosetItem"; + + /** Constant UNEXPECTED_STATUS="UnexpectedStatus" */ + public static final String UNEXPECTED_STATUS = "UnexpectedStatus"; + + /** Constant UNEXPECTED_MEDIA_TYPE="UnexpectedMediaType" */ + public static final String UNEXPECTED_MEDIA_TYPE = "UnexpectedMediaType"; + + /** Constant MISSING_ENTITY="MissingEntity" */ + public static final String MISSING_ENTITY = "MissingEntity"; + } diff --git a/src/main/java/org/opengis/cite/geotiff11/Namespaces.java b/src/main/java/org/opengis/cite/geotiff11/Namespaces.java index d76285e..488c598 100644 --- a/src/main/java/org/opengis/cite/geotiff11/Namespaces.java +++ b/src/main/java/org/opengis/cite/geotiff11/Namespaces.java @@ -4,28 +4,30 @@ /** * XML namespace names. - * - * @see Namespaces in XML 1.0 * + * @see Namespaces in XML 1.0 */ public class Namespaces { - private Namespaces() { - } - - /** SOAP 1.2 message envelopes. */ - public static final String SOAP_ENV = "http://www.w3.org/2003/05/soap-envelope"; - /** W3C XLink */ - public static final String XLINK = "http://www.w3.org/1999/xlink"; - /** OGC 06-121r3 (OWS 1.1) */ - public static final String OWS = "http://www.opengis.net/ows/1.1"; - /** ISO 19136 (GML 3.2) */ - public static final String GML = "http://www.opengis.net/gml/3.2"; - /** W3C XML Schema namespace */ - public static final URI XSD = URI - .create("http://www.w3.org/2001/XMLSchema"); - /** Schematron (ISO 19757-3) namespace */ - public static final URI SCH = URI - .create("http://purl.oclc.org/dsdl/schematron"); + private Namespaces() { + } + + /** SOAP 1.2 message envelopes. */ + public static final String SOAP_ENV = "http://www.w3.org/2003/05/soap-envelope"; + + /** W3C XLink */ + public static final String XLINK = "http://www.w3.org/1999/xlink"; + + /** OGC 06-121r3 (OWS 1.1) */ + public static final String OWS = "http://www.opengis.net/ows/1.1"; + + /** ISO 19136 (GML 3.2) */ + public static final String GML = "http://www.opengis.net/gml/3.2"; + + /** W3C XML Schema namespace */ + public static final URI XSD = URI.create("http://www.w3.org/2001/XMLSchema"); + + /** Schematron (ISO 19757-3) namespace */ + public static final URI SCH = URI.create("http://purl.oclc.org/dsdl/schematron"); } diff --git a/src/main/java/org/opengis/cite/geotiff11/ReusableEntityFilter.java b/src/main/java/org/opengis/cite/geotiff11/ReusableEntityFilter.java index 49e26d6..478e08e 100644 --- a/src/main/java/org/opengis/cite/geotiff11/ReusableEntityFilter.java +++ b/src/main/java/org/opengis/cite/geotiff11/ReusableEntityFilter.java @@ -1,26 +1,28 @@ package org.opengis.cite.geotiff11; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.filter.ClientFilter; +import java.io.IOException; + +import org.glassfish.jersey.client.ClientResponse; + +import jakarta.ws.rs.client.ClientRequestContext; +import jakarta.ws.rs.client.ClientResponseContext; +import jakarta.ws.rs.client.ClientResponseFilter; /** * Buffers the (response) entity so it can be read multiple times. * - *

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

    + *

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

    */ -public class ReusableEntityFilter extends ClientFilter { +public class ReusableEntityFilter implements ClientResponseFilter { - @Override - public ClientResponse handle(ClientRequest req) throws ClientHandlerException { - // leave request entity--it can usually be read multiple times - ClientResponse rsp = getNext().handle(req); - if (rsp.hasEntity()) { - rsp.bufferEntity(); - } - return rsp; - } + /** {@inheritDoc} */ + @Override + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { + if (responseContext instanceof ClientResponse) { + ((ClientResponse) responseContext).bufferEntity(); + } + } } diff --git a/src/main/java/org/opengis/cite/geotiff11/SuiteAttribute.java b/src/main/java/org/opengis/cite/geotiff11/SuiteAttribute.java index 8b3743f..4cabf22 100644 --- a/src/main/java/org/opengis/cite/geotiff11/SuiteAttribute.java +++ b/src/main/java/org/opengis/cite/geotiff11/SuiteAttribute.java @@ -1,55 +1,70 @@ package org.opengis.cite.geotiff11; -import com.sun.jersey.api.client.Client; - import java.io.File; import org.w3c.dom.Document; +import jakarta.ws.rs.client.Client; + /** - * An enumerated type defining ISuite attributes that may be set to constitute a - * shared test fixture. + * An enumerated type defining ISuite attributes that may be set to constitute a shared + * test fixture. */ @SuppressWarnings("rawtypes") public enum SuiteAttribute { - /** - * A client component for interacting with HTTP endpoints. - */ - CLIENT("httpClient", Client.class), - /** - * A DOM Document that represents the test subject or metadata about it. - */ - TEST_SUBJECT("testSubject", Document.class), - /** - * A File containing the test subject or a description of it. - */ - TEST_SUBJ_FILE("testSubjectFile", File.class), - /** - * GeoTiff metadata document. - */ - TEST_SUBJ_GEOTIFF("testSubjGeotiff", Document.class); - - private final Class attrType; - private final String attrName; - - private SuiteAttribute(String attrName, Class attrType) { - this.attrName = attrName; - this.attrType = attrType; - } - - public Class getType() { - return attrType; - } - - public String getName() { - return attrName; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(attrName); - sb.append('(').append(attrType.getName()).append(')'); - return sb.toString(); - } + /** + * A client component for interacting with HTTP endpoints. + */ + CLIENT("httpClient", Client.class), + /** + * A DOM Document that represents the test subject or metadata about it. + */ + TEST_SUBJECT("testSubject", Document.class), + /** + * A File containing the test subject or a description of it. + */ + TEST_SUBJ_FILE("testSubjectFile", File.class), + /** + * GeoTiff metadata document. + */ + TEST_SUBJ_GEOTIFF("testSubjGeotiff", Document.class); + + private final Class attrType; + + private final String attrName; + + private SuiteAttribute(String attrName, Class attrType) { + this.attrName = attrName; + this.attrType = attrType; + } + + /** + *

    + * getType. + *

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

    + * getName. + *

    + * @return a {@link java.lang.String} object + */ + public String getName() { + return attrName; + } + + /** {@inheritDoc} */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(attrName); + sb.append('(').append(attrType.getName()).append(')'); + return sb.toString(); + } + } diff --git a/src/main/java/org/opengis/cite/geotiff11/SuiteFixtureListener.java b/src/main/java/org/opengis/cite/geotiff11/SuiteFixtureListener.java index 43a4eac..01ab3b9 100644 --- a/src/main/java/org/opengis/cite/geotiff11/SuiteFixtureListener.java +++ b/src/main/java/org/opengis/cite/geotiff11/SuiteFixtureListener.java @@ -2,137 +2,136 @@ import java.io.File; import java.io.IOException; -import java.io.InputStream; import java.net.URI; -import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.logging.Level; -import org.apache.commons.io.IOUtils; -import org.opengis.cite.geotiff11.SuiteAttribute; import org.opengis.cite.geotiff11.util.ClientUtils; import org.opengis.cite.geotiff11.util.TestSuiteLogger; import org.opengis.cite.geotiff11.util.URIUtils; import org.testng.ISuite; import org.testng.ISuiteListener; -import com.sun.jersey.api.client.Client; + +import jakarta.ws.rs.client.Client; /** - * A listener that performs various tasks before and after a test suite is run, - * usually concerned with maintaining a shared test suite fixture. Since this - * listener is loaded using the ServiceLoader mechanism, its methods will be - * called before those of other suite listeners listed in the test suite - * definition and before any annotated configuration methods. + * A listener that performs various tasks before and after a test suite is run, usually + * concerned with maintaining a shared test suite fixture. Since this listener is loaded + * using the ServiceLoader mechanism, its methods will be called before those of other + * suite listeners listed in the test suite definition and before any annotated + * configuration methods. * - * Attributes set on an ISuite instance are not inherited by constituent test - * group contexts (ITestContext). However, suite attributes are still accessible - * from lower contexts. + * Attributes set on an ISuite instance are not inherited by constituent test group + * contexts (ITestContext). However, suite attributes are still accessible from lower + * contexts. * * @see org.testng.ISuite ISuite interface */ public class SuiteFixtureListener implements ISuiteListener { + private static final String GEOTIFF_TXT = "tiffMeta.txt"; - - @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"); - } - } + /** {@inheritDoc} */ + @Override + public void onStart(ISuite suite) { + processSuiteParameters(suite); + registerClientComponent(suite); + } + + /** {@inheritDoc} */ + @Override + public void onFinish(ISuite suite) { + if (null != System.getProperty("deleteSubjectOnFinish")) { + deleteTempFiles(suite); + System.getProperties().remove("deleteSubjectOnFinish"); + } + } + + /** + * Processes test suite arguments and sets suite attributes accordingly. The entity + * referenced by the {@link TestRunArg#IUT iut} argument is retrieved and written to a + * File that is set as the value of the suite attribute + * {@link SuiteAttribute#TEST_SUBJ_FILE testSubjectFile}. + * @param suite An ISuite object representing a TestNG test suite. + */ + void processSuiteParameters(ISuite suite) { + Map params = suite.getXmlSuite().getParameters(); + TestSuiteLogger.log(Level.CONFIG, "Suite parameters\n" + params.toString()); + String iutParam = params.get(TestRunArg.IUT.toString()); + if ((null == iutParam) || iutParam.isEmpty()) { + throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.IUT.toString()); + } + URI iutRef = URI.create(iutParam.trim()); + File entityFile = null; + try { + entityFile = URIUtils.dereferenceURI(iutRef); + } + catch (IOException iox) { + throw new RuntimeException("Failed to dereference resource located at " + iutRef, iox); + } + 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); + // Document iutDoc = null; + try { + // iutDoc = URIUtils.parseURI(entityFile.toURI()); + boolean result = URIUtils.parseGeoTiff(suite, entityFile.toURI(), GEOTIFF_TXT); + + // if the parse fails + if (!result) { + return; + } + } + catch (Exception x) { + throw new RuntimeException("Failed to parse resource retrieved from " + iutRef, x); + } + + // try { + // InputStream inputStream = URIUtils.class.getResourceAsStream("/tmp/" + + // GEOTIFF_TXT); + // suite.setAttribute(SuiteAttribute.TEST_SUBJECT.getName(), + // IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + // + //// System.out.println("Suite: " + + // suite.getAttribute(SuiteAttribute.TEST_SUBJECT.getName())); + // } catch (IOException e) { + // e.printStackTrace(); + // } - /** - * 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()); - 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); - //Document iutDoc = null; - try { - //iutDoc = URIUtils.parseURI(entityFile.toURI()); - boolean result = URIUtils.parseGeoTiff(suite, entityFile.toURI(), GEOTIFF_TXT); + if (TestSuiteLogger.isLoggable(Level.FINE)) { + StringBuilder logMsg = new StringBuilder("Parsed resource retrieved from "); + logMsg.append(iutRef).append("\n"); + // logMsg.append(XMLUtils.writeNodeToString(iutDoc)); + TestSuiteLogger.log(Level.FINE, logMsg.toString()); + } + } - //if the parse fails - if (!result) { - return; - } - } catch (Exception x) { - throw new RuntimeException("Failed to parse resource retrieved from " + iutRef, x); - } - -// try { -// InputStream inputStream = URIUtils.class.getResourceAsStream("/tmp/" + GEOTIFF_TXT); -// suite.setAttribute(SuiteAttribute.TEST_SUBJECT.getName(), IOUtils.toString(inputStream, StandardCharsets.UTF_8)); -// -//// System.out.println("Suite: " + suite.getAttribute(SuiteAttribute.TEST_SUBJECT.getName())); -// } catch (IOException e) { -// e.printStackTrace(); -// } - - if (TestSuiteLogger.isLoggable(Level.FINE)) { - StringBuilder logMsg = new StringBuilder("Parsed resource retrieved from "); - logMsg.append(iutRef).append("\n"); - //logMsg.append(XMLUtils.writeNodeToString(iutDoc)); - TestSuiteLogger.log(Level.FINE, logMsg.toString()); - } - } + /** + * 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); + } + } - /** - * 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(); + } + } - /** - * 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/geotiff11/SuitePreconditions.java b/src/main/java/org/opengis/cite/geotiff11/SuitePreconditions.java index 31dd2ca..465f2e3 100644 --- a/src/main/java/org/opengis/cite/geotiff11/SuitePreconditions.java +++ b/src/main/java/org/opengis/cite/geotiff11/SuitePreconditions.java @@ -4,36 +4,36 @@ import java.util.logging.Logger; import org.testng.ITestContext; +import org.testng.Reporter; import org.testng.annotations.BeforeSuite; /** - * Checks that various preconditions are satisfied before the test suite is run. - * If any of these (BeforeSuite) methods fail, all tests will be skipped. + * Checks that various preconditions are satisfied before the test suite is run. If any of + * these (BeforeSuite) methods fail, all tests will be skipped. */ public class SuitePreconditions { - private static final Logger LOGR = Logger.getLogger(SuitePreconditions.class.getName()); + private static final Logger LOGR = Logger.getLogger(SuitePreconditions.class.getName()); + + /** + * Verifies that the referenced test subject exists and has the expected type. + */ + @BeforeSuite + @SuppressWarnings("rawtypes") + public void verifyTestSubject() { + SuiteAttribute testFileAttr = SuiteAttribute.TEST_SUBJ_FILE; + ITestContext testContext = Reporter.getCurrentTestResult().getTestContext(); + 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. - * - * @param testContext - * Information about the (pending) test run. - */ - @BeforeSuite - @SuppressWarnings("rawtypes") - public void verifyTestSubject(ITestContext testContext) { - 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/geotiff11/SyncPipe.java b/src/main/java/org/opengis/cite/geotiff11/SyncPipe.java index e0afdb7..add7934 100644 --- a/src/main/java/org/opengis/cite/geotiff11/SyncPipe.java +++ b/src/main/java/org/opengis/cite/geotiff11/SyncPipe.java @@ -3,26 +3,45 @@ import java.io.InputStream; import java.io.OutputStream; -public class SyncPipe implements Runnable -{ -public SyncPipe(InputStream istrm, OutputStream ostrm) { - this.istrm_ = istrm; - this.ostrm_ = ostrm; - } - public void run() { - try - { - final byte[] buffer = new byte[1024]; - for (int length = 0; (length = this.istrm_.read(buffer)) != -1; ) - { - this.ostrm_.write(buffer, 0, length); - } - } - catch (Exception e) - { - e.printStackTrace(); - } - } - private final OutputStream ostrm_; - private final InputStream istrm_; -} \ No newline at end of file +/** + *

    + * SyncPipe class. + *

    + * + */ +public class SyncPipe implements Runnable { + + /** + *

    + * Constructor for SyncPipe. + *

    + * @param istrm a {@link java.io.InputStream} object + * @param ostrm a {@link java.io.OutputStream} object + */ + public SyncPipe(InputStream istrm, OutputStream ostrm) { + this.istrm_ = istrm; + this.ostrm_ = ostrm; + } + + /** + *

    + * run. + *

    + */ + public void run() { + try { + final byte[] buffer = new byte[1024]; + for (int length = 0; (length = this.istrm_.read(buffer)) != -1;) { + this.ostrm_.write(buffer, 0, length); + } + } + catch (Exception e) { + e.printStackTrace(); + } + } + + private final OutputStream ostrm_; + + private final InputStream istrm_; + +} diff --git a/src/main/java/org/opengis/cite/geotiff11/TestFailureListener.java b/src/main/java/org/opengis/cite/geotiff11/TestFailureListener.java index 8332ea1..9b4346b 100644 --- a/src/main/java/org/opengis/cite/geotiff11/TestFailureListener.java +++ b/src/main/java/org/opengis/cite/geotiff11/TestFailureListener.java @@ -1,97 +1,97 @@ package org.opengis.cite.geotiff11; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; import java.nio.charset.StandardCharsets; -import javax.ws.rs.core.MediaType; + import org.opengis.cite.geotiff11.util.ClientUtils; import org.opengis.cite.geotiff11.util.XMLUtils; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.w3c.dom.Document; +import jakarta.ws.rs.client.ClientRequestContext; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + /** - * A listener that augments a test result with diagnostic information in the - * event that a test method failed. This information will appear in the XML - * report when the test run is completed. + * A listener that augments a test result with diagnostic information in the event that a + * test method failed. This information will appear in the XML report when the test run is + * completed. */ public class TestFailureListener extends TestListenerAdapter { - /** - * Sets the "request" and "response" attributes of a test result. The value - * of these attributes is a string that contains information about the - * content of an outgoing or incoming message: target resource, status code, - * headers, entity (if present). The entity is represented as a String with - * UTF-8 character encoding. - * - * @param result A description of a test result (with a fail verdict). - */ - @Override - public void onTestFailure(ITestResult result) { - super.onTestFailure(result); - Object instance = result.getInstance(); - if (CommonFixture.class.isInstance(instance)) { - CommonFixture fixture = CommonFixture.class.cast(instance); - result.setAttribute("request", getRequestMessageInfo(fixture.request)); - result.setAttribute("response", getResponseMessageInfo(fixture.response)); - } - } + /** + * {@inheritDoc} + * + * Sets the "request" and "response" attributes of a test result. The value of these + * attributes is a string that contains information about the content of an outgoing + * or incoming message: target resource, status code, headers, entity (if present). + * The entity is represented as a String with UTF-8 character encoding. + */ + @Override + public void onTestFailure(ITestResult result) { + super.onTestFailure(result); + Object instance = result.getInstance(); + if (CommonFixture.class.isInstance(instance)) { + CommonFixture fixture = CommonFixture.class.cast(instance); + result.setAttribute("request", getRequestMessageInfo(fixture.request)); + result.setAttribute("response", getResponseMessageInfo(fixture.response)); + } + } - /** - * Gets diagnostic information about a request message. If the request - * contains a message body, it should be represented as a DOM Document node - * or as an object having a meaningful toString() implementation. - * - * @param req An object representing an HTTP request message. - * @return A string containing information gleaned from the request message. - */ - String getRequestMessageInfo(ClientRequest req) { - if (null == req) { - return "No request message."; - } - StringBuilder msgInfo = new StringBuilder(); - msgInfo.append("Method: ").append(req.getMethod()).append('\n'); - msgInfo.append("Target URI: ").append(req.getURI()).append('\n'); - msgInfo.append("Headers: ").append(req.getHeaders()).append('\n'); - if (null != req.getEntity()) { - Object entity = req.getEntity(); - String body; - if (Document.class.isInstance(entity)) { - Document doc = Document.class.cast(entity); - body = XMLUtils.writeNodeToString(doc); - } else { - body = entity.toString(); - } - msgInfo.append(body).append('\n'); - } - return msgInfo.toString(); - } + /** + * Gets diagnostic information about a request message. If the request contains a + * message body, it should be represented as a DOM Document node or as an object + * having a meaningful toString() implementation. + * @param req An object representing an HTTP request message. + * @return A string containing information gleaned from the request message. + */ + String getRequestMessageInfo(ClientRequestContext 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.getType().isCompatible(MediaType.APPLICATION_XML_TYPE)) { - Document doc = ClientUtils.getResponseEntityAsDocument(rsp, null); - msgInfo.append(XMLUtils.writeNodeToString(doc)); - } else { - byte[] body = rsp.getEntity(byte[].class); - msgInfo.append(new String(body, StandardCharsets.UTF_8)); - } - msgInfo.append('\n'); - } - return msgInfo.toString(); - } + /** + * Gets diagnostic information about a response message. + * @param rsp An object representing an HTTP response message. + * @return A string containing information gleaned from the response message. + */ + String getResponseMessageInfo(Response rsp) { + if (null == rsp) { + return "No response message."; + } + StringBuilder msgInfo = new StringBuilder(); + msgInfo.append("Status: ").append(rsp.getStatus()).append('\n'); + msgInfo.append("Headers: ").append(rsp.getHeaders()).append('\n'); + if (rsp.hasEntity()) { + if (rsp.getMediaType().isCompatible(MediaType.APPLICATION_XML_TYPE)) { + Document doc = ClientUtils.getResponseEntityAsDocument(rsp, null); + msgInfo.append(XMLUtils.writeNodeToString(doc)); + } + else { + byte[] body = rsp.readEntity(byte[].class); + msgInfo.append(new String(body, StandardCharsets.UTF_8)); + } + msgInfo.append('\n'); + } + return msgInfo.toString(); + } } diff --git a/src/main/java/org/opengis/cite/geotiff11/TestNGController.java b/src/main/java/org/opengis/cite/geotiff11/TestNGController.java index 876e188..a220c3a 100644 --- a/src/main/java/org/opengis/cite/geotiff11/TestNGController.java +++ b/src/main/java/org/opengis/cite/geotiff11/TestNGController.java @@ -30,142 +30,144 @@ */ 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); - // TODO: next steps to make this run tests on multiple files if a folder is given - //executor.execute(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 java.lang.Exception If the test run cannot be executed (usually due to + * unsatisfied pre-conditions). + */ + public static void main(String[] args) throws Exception { + CommandLineArguments testRunArgs = new CommandLineArguments(); + JCommander cmd = new JCommander(testRunArgs); + try { + cmd.parse(args); + } + catch (ParameterException px) { + System.out.println(px.getMessage()); + cmd.usage(); + } + if (testRunArgs.doDeleteSubjectOnFinish()) { + System.setProperty("deleteSubjectOnFinish", "true"); + } + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + File xmlArgs = testRunArgs.getPropertiesFile(); + Document testRunProps = db.parse(xmlArgs); + TestNGController controller = new TestNGController(testRunArgs.getOutputDir()); + Source testResults = controller.doTestRun(testRunProps); + System.out.println("Test results: " + testResults.getSystemId()); + } + + /** + * Default constructor uses the location given by the "java.io.tmpdir" system property + * as the root output directory. + */ + public TestNGController() { + this(System.getProperty("java.io.tmpdir")); + } + + /** + * Construct a controller that writes results to the given output directory. + * @param outputDir The location of the directory in which test results will be + * written (a file system path or a 'file' URI). It will be created if it does not + * exist. + */ + public TestNGController(String outputDir) { + InputStream is = getClass().getResourceAsStream("ets.properties"); + try { + this.etsProperties.load(is); + } + catch (IOException ex) { + TestSuiteLogger.log(Level.WARNING, "Unable to load ets.properties. " + ex.getMessage()); + } + URL tngSuite = TestNGController.class.getResource("testng.xml"); + File resultsDir; + if (null == outputDir || outputDir.isEmpty()) { + resultsDir = new File(System.getProperty("user.home")); + } + else if (outputDir.startsWith("file:")) { + resultsDir = new File(URI.create(outputDir)); + } + else { + resultsDir = new File(outputDir); + } + TestSuiteLogger.log(Level.CONFIG, "Using TestNG config: " + tngSuite); + TestSuiteLogger.log(Level.CONFIG, "Using outputDirPath: " + resultsDir.getAbsolutePath()); + // NOTE: setting third argument to 'true' enables the default listeners + this.executor = new TestNGExecutor(tngSuite.toString(), resultsDir.getAbsolutePath(), false); + } + + /** {@inheritDoc} */ + @Override + public String getCode() { + return etsProperties.getProperty("ets-code"); + } + + /** {@inheritDoc} */ + @Override + public String getVersion() { + return etsProperties.getProperty("ets-version"); + } + + /** {@inheritDoc} */ + @Override + public String getTitle() { + return etsProperties.getProperty("ets-title"); + } + + /** {@inheritDoc} */ + @Override + public Source doTestRun(Document testRunArgs) throws Exception { + validateTestRunArgs(testRunArgs); + // TODO: next steps to make this run tests on multiple files if a folder is given + // executor.execute(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/geotiff11/TestRunArg.java b/src/main/java/org/opengis/cite/geotiff11/TestRunArg.java index 346384f..d5f43eb 100644 --- a/src/main/java/org/opengis/cite/geotiff11/TestRunArg.java +++ b/src/main/java/org/opengis/cite/geotiff11/TestRunArg.java @@ -5,14 +5,16 @@ */ 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; + + /** {@inheritDoc} */ + @Override + public String toString() { + return name().toLowerCase(); + } - @Override - public String toString() { - return name().toLowerCase(); - } } diff --git a/src/main/java/org/opengis/cite/geotiff11/TestRunListener.java b/src/main/java/org/opengis/cite/geotiff11/TestRunListener.java index 7e07276..fd4b398 100644 --- a/src/main/java/org/opengis/cite/geotiff11/TestRunListener.java +++ b/src/main/java/org/opengis/cite/geotiff11/TestRunListener.java @@ -3,24 +3,28 @@ import org.testng.IExecutionListener; /** - * A listener that is invoked before and after a test run. It is often used to - * configure a shared fixture that endures for the duration of the entire test - * run. A FixtureManager may be used to manage such a fixture. + * A listener that is invoked before and after a test run. It is often used to configure a + * shared fixture that endures for the duration of the entire test run. A FixtureManager + * may be used to manage such a fixture. * - *

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

    + *

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

    * * @see com.occamlab.te.spi.executors.FixtureManager FixtureManager - * */ public class TestRunListener implements IExecutionListener { - @Override - public void onExecutionStart() { - } + /** {@inheritDoc} */ + @Override + public void onExecutionStart() { + } + + /** {@inheritDoc} */ + @Override + public void onExecutionFinish() { + } - @Override - public void onExecutionFinish() { - } } diff --git a/src/main/java/org/opengis/cite/geotiff11/package-info.java b/src/main/java/org/opengis/cite/geotiff11/package-info.java index 796c567..26089ae 100644 --- a/src/main/java/org/opengis/cite/geotiff11/package-info.java +++ b/src/main/java/org/opengis/cite/geotiff11/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.geotiff11; \ No newline at end of file +package org.opengis.cite.geotiff11; \ No newline at end of file diff --git a/src/main/java/org/opengis/cite/geotiff11/tiffTests/AsciiParamsTests.java b/src/main/java/org/opengis/cite/geotiff11/tiffTests/AsciiParamsTests.java index 91aacf5..e71645b 100644 --- a/src/main/java/org/opengis/cite/geotiff11/tiffTests/AsciiParamsTests.java +++ b/src/main/java/org/opengis/cite/geotiff11/tiffTests/AsciiParamsTests.java @@ -1,200 +1,263 @@ package org.opengis.cite.geotiff11.tiffTests; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOASCIIPARAMSTAG; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEODETICCITATIONGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GTCITATIONGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJECTEDCITATIONGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.VERTICALCITATIONGEOKEY; + import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import static org.opengis.cite.geotiff11.util.GeoKeyID.*; - // https://github.com/opengeospatial/geotiff/blob/master/GeoTIFF_Standard/standard/abstract_tests/TIFF_Tests/TEST_Double_Param.adoc +/** + *

    + * AsciiParamsTests class. + *

    + * + */ public class AsciiParamsTests extends GeoKeysTests { /* - * ASCII Parameters Test - * Test id: TIFF_Test/AsciiParameters - * Requirements: - * http://www.opengis.net/spec/GeoTIFF/1.1/GeoKeyDirectoryTag.KeyEntry.ID - * http://www.opengis.net/spec/GeoTIFF/1.1/GeoKeyDirectoryTag.keyEntryTIFFTagLocation - * http://www.opengis.net/spec/GeoTIFF/1.1/GeoKeyDirectoryTag.keyEntryKeyCount - * http://www.opengis.net/spec/GeoTIFF/1.1/GeoKeyDirectoryTag.keyEntryValueOffset - * http://www.opengis.net/spec/GeoTIFF/1.1/GeoAsciiParamsTag.ID - * http://www.opengis.net/spec/GeoTIFF/1.1/GeoAsciiParamsTag.count - * http://www.opengis.net/spec/GeoTIFF/1.1/CitationGeoKeys.ID - * http://www.opengis.net/spec/GeoTIFF/1.1/CitationGeoKeys.type - * Purpose: Verify an ASCII parameter - * Pre-conditions: The GeoKeyDirectory, ASCIIValues and GeoKeyOffset values have been set. - * Test Variables: - * Variable Scope Description - * GeoKeyDirectory Global Location of the GeoTIFF GeoKey directory - * ASCIIValues Global Location of the ASCII values for GeoTIFF ASCII GeoKeys - * GeoKeyOffset Parameter Location of this Key Entry Set in the GeoKey directory - * GeoKey Local Temporary value of the GeoKey - * KeyLength Local Temporary value for the length of the value for the GeoKey - * KeyValueOffset Local The location of the GeoKey value in the file - - */ - + * ASCII Parameters Test Test id: TIFF_Test/AsciiParameters Requirements: + * http://www.opengis.net/spec/GeoTIFF/1.1/GeoKeyDirectoryTag.KeyEntry.ID + * http://www.opengis.net/spec/GeoTIFF/1.1/GeoKeyDirectoryTag.keyEntryTIFFTagLocation + * http://www.opengis.net/spec/GeoTIFF/1.1/GeoKeyDirectoryTag.keyEntryKeyCount + * http://www.opengis.net/spec/GeoTIFF/1.1/GeoKeyDirectoryTag.keyEntryValueOffset + * http://www.opengis.net/spec/GeoTIFF/1.1/GeoAsciiParamsTag.ID + * http://www.opengis.net/spec/GeoTIFF/1.1/GeoAsciiParamsTag.count + * http://www.opengis.net/spec/GeoTIFF/1.1/CitationGeoKeys.ID + * http://www.opengis.net/spec/GeoTIFF/1.1/CitationGeoKeys.type Purpose: Verify an + * ASCII parameter Pre-conditions: The GeoKeyDirectory, ASCIIValues and GeoKeyOffset + * values have been set. Test Variables: Variable Scope Description GeoKeyDirectory + * Global Location of the GeoTIFF GeoKey directory ASCIIValues Global Location of the + * ASCII values for GeoTIFF ASCII GeoKeys GeoKeyOffset Parameter Location of this Key + * Entry Set in the GeoKey directory GeoKey Local Temporary value of the GeoKey + * KeyLength Local Temporary value for the length of the value for the GeoKey + * KeyValueOffset Local The location of the GeoKey value in the file + * + */ + String asciiParamsSet; - + + /** + *

    + * setUpAsciiParamsSet. + *

    + */ @BeforeClass public void setUpAsciiParamsSet() { - if (directory.hasTag(GEOASCIIPARAMSTAG)) - { - asciiParamsSet = directory.getTag(GEOASCIIPARAMSTAG).getValuesAsString().toString(); + if (directory.hasTag(GEOASCIIPARAMSTAG)) { + asciiParamsSet = directory.getTag(GEOASCIIPARAMSTAG).getValuesAsString().toString(); asciiParamsSet = asciiParamsSet.replace("\\0", "\0"); } } - - @Test(description = "Ascii Params Tag Count Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + /** + *

    + * verifyGeoAsciiParamsTagCount. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Ascii Params Tag Count Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyGeoAsciiParamsTagCount() throws Exception { - if(keyEntrySet.contains(GEOASCIIPARAMSTAG)) - { - // The GeoAsciiParamsTag SHALL contain the values of the key parameters of type = ASCII referenced by the GeoKeyDirectoryTag. - Assert.assertTrue(directory.hasTag(GEOASCIIPARAMSTAG), "the GeoAsciiParamsTag SHALL contain the values of the key parameters of type = ASCII referenced by the GeoKeyDirectoryTag"); + if (keyEntrySet.contains(GEOASCIIPARAMSTAG)) { + // The GeoAsciiParamsTag SHALL contain the values of the key parameters of + // type = ASCII referenced by the GeoKeyDirectoryTag. + Assert.assertTrue(directory.hasTag(GEOASCIIPARAMSTAG), + "the GeoAsciiParamsTag SHALL contain the values of the key parameters of type = ASCII referenced by the GeoKeyDirectoryTag"); } - else - { - // TODO: ??? If there is no key parameters of type = ASCII, it SHALL not be present - Assert.assertFalse(directory.hasTag(GEOASCIIPARAMSTAG), "if there is no key parameters of type = ASCII, it SHALL not be present"); + else { + // TODO: ??? If there is no key parameters of type = ASCII, it SHALL not be + // present + Assert.assertFalse(directory.hasTag(GEOASCIIPARAMSTAG), + "if there is no key parameters of type = ASCII, it SHALL not be present"); } } - - // TODO: this is redoing some TiffTagsTests stuff. Gotta decide how to properly organize this. - @Test(description = "Ascii Params Tag Type Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // TODO: this is redoing some TiffTagsTests stuff. Gotta decide how to properly + // organize this. + /** + *

    + * verifyGeoAsciiParamsTagType. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Ascii Params Tag Type Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyGeoAsciiParamsTagType() throws Exception { // the GeoAsciiParamsTag SHALL have type = ASCII - if(directory.hasTag(GEOASCIIPARAMSTAG)) - Assert.assertTrue(directory.getTag(GEOASCIIPARAMSTAG).getTypeValue() == 2, "the GeoAsciiParamsTag SHALL have type = ASCII"); + if (directory.hasTag(GEOASCIIPARAMSTAG)) + Assert.assertTrue(directory.getTag(GEOASCIIPARAMSTAG).getTypeValue() == 2, + "the GeoAsciiParamsTag SHALL have type = ASCII"); } - - @Test(description = "Ascii Params Tag NULLWrite Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + /** + *

    + * verifyGeoAsciiParamsTagNULLWrite. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Ascii Params Tag NULLWrite Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyGeoAsciiParamsTagNULLWrite() throws Exception { - // NULL (ASCII code = 0) characters SHALL not be present in the string content written in the GeoAsciiParamsTag - if (asciiParamsSet == null) return; - - for(int i = 0; i < asciiParamsSet.length() - 1; i++) { - Assert.assertTrue(asciiParamsSet.charAt(i) != '\0', "NULL (ASCII code = 0) characters SHALL not be present in the string content written in the GeoAsciiParamsTag"); + // NULL (ASCII code = 0) characters SHALL not be present in the string content + // written in the GeoAsciiParamsTag + if (asciiParamsSet == null) + return; + + for (int i = 0; i < asciiParamsSet.length() - 1; i++) { + Assert.assertTrue(asciiParamsSet.charAt(i) != '\0', + "NULL (ASCII code = 0) characters SHALL not be present in the string content written in the GeoAsciiParamsTag"); } - - Assert.assertTrue(asciiParamsSet.charAt(asciiParamsSet.length() - 1) == '\0', "the string content written in the GeoAsciiParamsTag should end in NULL (ASCII code = 0) characters "); + + Assert.assertTrue(asciiParamsSet.charAt(asciiParamsSet.length() - 1) == '\0', + "the string content written in the GeoAsciiParamsTag should end in NULL (ASCII code = 0) characters "); } - - + String processFourthShortForAscii(int index, int keyLength) { // process the fourth Short integer in the Key Entry Set - int asciiIndex = (int) keyEntrySet.get(index+3); - - //Assert.assertTrue(directory.hasTag(GEOASCIIPARAMSTAG)); - + int asciiIndex = (int) keyEntrySet.get(index + 3); + + // Assert.assertTrue(directory.hasTag(GEOASCIIPARAMSTAG)); + // SET KeyValueOffset to the value - - // Read the contents of the GeoTIFF file starting at KeyValueOffset up to and including the first NULL. + + // Read the contents of the GeoTIFF file starting at KeyValueOffset up to and + // including the first NULL. // Verify that the contents read consists of ASCII characters. - // Verify that the contents read is KeyLength characters long not including the NULL. + // Verify that the contents read is KeyLength characters long not including the + // NULL. String value = ""; - - for(int i = asciiIndex; ; i++) - { - Assert.assertTrue(i < asciiParamsSet.length()); - //Assert.assertTrue(asciiParamsSet.charAt(i) != '\0'); - - // The pipe character | in the GeoAsciiParamsTag SHALL be used as the character to terminate a string written in as ASCII tag - if(asciiParamsSet.charAt(i) == '|') { - Assert.assertTrue(value.length() == keyLength - 1, "the pipe character | in the GeoAsciiParamsTag SHALL be used as the character to terminate a string written in as ASCII tag"); + + for (int i = asciiIndex;; i++) { + Assert.assertTrue(i < asciiParamsSet.length()); + // Assert.assertTrue(asciiParamsSet.charAt(i) != '\0'); + + // The pipe character | in the GeoAsciiParamsTag SHALL be used as the + // character to terminate a string written in as ASCII tag + if (asciiParamsSet.charAt(i) == '|') { + Assert.assertTrue(value.length() == keyLength - 1, + "the pipe character | in the GeoAsciiParamsTag SHALL be used as the character to terminate a string written in as ASCII tag"); break; } value += asciiParamsSet.charAt(i); } - + return value; } - - -// GeoKey Requirements Class - -// 1026 CitationGeoKeys/GTCitationGeoKey - - @Test(description = "Ascii Params GTCitationGeoKey (1026) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // GeoKey Requirements Class + + // 1026 CitationGeoKeys/GTCitationGeoKey + + /** + *

    + * verifyGTCitationGeoKey. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Ascii Params GTCitationGeoKey (1026) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyGTCitationGeoKey() throws Exception { // the GTCitationGeoKey SHALL have ID = 1026 int index = getKeyIndex(GTCITATIONGEOKEY); - + // not required - if(index == -1) { + if (index == -1) { return; } - + int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); String value = processFourthShortForAscii(index, keyLength); - - // the GeogLinearUnitSizeGeoKey SHALL have type = ASCII + + // the GeogLinearUnitSizeGeoKey SHALL have type = ASCII Assert.assertTrue(type == GEOASCIIPARAMSTAG, "the GeogLinearUnitSizeGeoKey SHALL have type = ASCII"); } - -// 2049 CitationGeoKeys/GeodeticCitationGeoKey - - @Test(description = "Ascii Params GeodeticCitationGeoKey (2049) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 2049 CitationGeoKeys/GeodeticCitationGeoKey + + /** + *

    + * verifyGeodeticCitationGeoKey. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Ascii Params GeodeticCitationGeoKey (2049) Test", + dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyGeodeticCitationGeoKey() throws Exception { // the GeodeticCitationGeoKey SHALL have ID = 2049 int index = getKeyIndex(GEODETICCITATIONGEOKEY); - + // not required - if(index == -1) { + if (index == -1) { return; } - + int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); String value = processFourthShortForAscii(index, keyLength); - - // the GeogLinearUnitSizeGeoKey SHALL have type = ASCII + + // the GeogLinearUnitSizeGeoKey SHALL have type = ASCII Assert.assertTrue(type == GEOASCIIPARAMSTAG, "the GeogLinearUnitSizeGeoKey SHALL have type = ASCII"); } - -// 3073 CitationGeoKeys/ProjectedCitationGeoKey - - @Test(description = "Ascii Params ProjectedCitationGeoKey (3073) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 3073 CitationGeoKeys/ProjectedCitationGeoKey + + /** + *

    + * verifyProjectedCitationGeoKey. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Ascii Params ProjectedCitationGeoKey (3073) Test", + dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyProjectedCitationGeoKey() throws Exception { // the ProjectedCitationGeoKey SHALL have ID = 3073 int index = getKeyIndex(PROJECTEDCITATIONGEOKEY); - + // not required - if(index == -1) { + if (index == -1) { return; } - + int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); String value = processFourthShortForAscii(index, keyLength); - - // the GeogLinearUnitSizeGeoKey SHALL have type = ASCII + + // the GeogLinearUnitSizeGeoKey SHALL have type = ASCII Assert.assertTrue(type == GEOASCIIPARAMSTAG, "the GeogLinearUnitSizeGeoKey SHALL have type = ASCII"); } - -// 4097 CitationGeoKeys/VerticalCitationGeoKey - @Test(description = "Ascii Params VerticalCitationGeoKey (4097) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + // 4097 CitationGeoKeys/VerticalCitationGeoKey + + /** + *

    + * verifyVerticalCitationGeoKey. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Ascii Params VerticalCitationGeoKey (4097) Test", + dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyVerticalCitationGeoKey() throws Exception { // the VerticalCitationGeoKey SHALL have ID = 4097 int index = getKeyIndex(VERTICALCITATIONGEOKEY); - + // not required - if(index == -1) { + if (index == -1) { return; } - + int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); String value = processFourthShortForAscii(index, keyLength); - - // the GeogLinearUnitSizeGeoKey SHALL have type = ASCII + + // the GeogLinearUnitSizeGeoKey SHALL have type = ASCII Assert.assertTrue(type == GEOASCIIPARAMSTAG, "the GeogLinearUnitSizeGeoKey SHALL have type = ASCII"); } - + } diff --git a/src/main/java/org/opengis/cite/geotiff11/tiffTests/CommonTiffMeta.java b/src/main/java/org/opengis/cite/geotiff11/tiffTests/CommonTiffMeta.java index e547b85..1428750 100644 --- a/src/main/java/org/opengis/cite/geotiff11/tiffTests/CommonTiffMeta.java +++ b/src/main/java/org/opengis/cite/geotiff11/tiffTests/CommonTiffMeta.java @@ -6,29 +6,36 @@ import org.testng.ITestContext; import org.testng.annotations.BeforeClass; +/** + *

    + * CommonTiffMeta class. + *

    + * + */ public class CommonTiffMeta extends CommonFixture { + protected TiffDump tiffDump; - + /** * Obtains the test subject from the ISuite context. The suite attribute - * {@link org.opengis.cite.geotiff11.SuiteAttribute#TEST_SUBJECT} should - * evaluate to a file node. - * - * @param testContext - * The test (group) context. + * {@link org.opengis.cite.geotiff11.SuiteAttribute#TEST_SUBJECT} should evaluate to a + * file node. + * @param testContext The test (group) context. */ @BeforeClass public void obtainTestSubject(ITestContext testContext) { - //System.out.println("obtaining test subject."); + // System.out.println("obtaining test subject."); Object obj = testContext.getSuite().getAttribute(SuiteAttribute.TEST_SUBJECT.getName()); - - if(obj != null && obj instanceof String) { + + if (obj != null && obj instanceof String) { try { tiffDump = new TiffDump((String) obj); - } catch (Exception e) { + } + catch (Exception e) { e.printStackTrace(); } } - + } + } diff --git a/src/main/java/org/opengis/cite/geotiff11/tiffTests/DoubleParamsTests.java b/src/main/java/org/opengis/cite/geotiff11/tiffTests/DoubleParamsTests.java index 5100fe2..197347c 100644 --- a/src/main/java/org/opengis/cite/geotiff11/tiffTests/DoubleParamsTests.java +++ b/src/main/java/org/opengis/cite/geotiff11/tiffTests/DoubleParamsTests.java @@ -1,366 +1,477 @@ package org.opengis.cite.geotiff11.tiffTests; +import static org.opengis.cite.geotiff11.util.GeoKeyID.ELLIPSOIDINVFLATTENINGGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.ELLIPSOIDSEMIMAJORAXISGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.ELLIPSOIDSEMIMINORAXISGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEODOUBLEPARAMSTAG; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOGANGULARUNITSGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOGANGULARUNITSIZEGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOGAZIMUTHUNITSGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOGLINEARUNITSGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOGLINEARUNITSIZEGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PRIMEMERIDIANLONGITUDEGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJAZIMUTHANGLEGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJCENTEREASTINGGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJCENTERLATGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJCENTERLONGGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJCENTERNORTHINGGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJFALSEEASTINGGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJFALSENORTHINGGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJFALSEORIGINEASTINGGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJFALSEORIGINLATGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJFALSEORIGINLONGGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJFALSEORIGINNORTHINGGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJLINEARUNITSGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJLINEARUNITSIZEGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJNATORIGINLATGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJNATORIGINLONGGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJSCALEATCENTERGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJSCALEATNATORIGINGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJSTDPARALLEL1GEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJSTDPARALLEL2GEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJSTRAIGHTVERTPOLELONGGEOKEY; + import java.util.List; import org.opengis.cite.geotiff11.util.EPSGDataSet; import org.testng.Assert; import org.testng.annotations.Test; -import static org.opengis.cite.geotiff11.util.GeoKeyID.*; - // https://github.com/opengeospatial/geotiff/blob/master/GeoTIFF_Standard/standard/abstract_tests/TIFF_Tests/TEST_Double_Param.adoc +/** + *

    + * DoubleParamsTests class. + *

    + * + */ public class DoubleParamsTests extends GeoKeysTests { /* - * Double Parameters Test - * Test id: http://www.opengis.net/spec/GeoTIFF/1.1/conf/DoubleParameters - * Requirements: - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.KeyEntry.ID - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyEntryTIFFTagLocation - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyEntryKeyCount - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyEntryValueOffset - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoDoubleParamsTag.ID - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoDoubleParamsTag.count - * http://www.opengis.net/spec/GeoTIFF/1.1/req/PrimeMeridianLongitudeGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/UnitSizeGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/EllipsoidSemiMajorAxisGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/EllipsoidSemiMinorAxisGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/EllipsoidInvFlatteningGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ProjAngularParameterGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ProjLinearParameterGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ProjScalarParameterGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ProjAzimuthAngleGeoKey - * Purpose: Verify Double parameters - * Pre-conditions The GeoKeyDirectory, DoubleValues and GeoKeyOffset values have been set. - * Test Variables: - * Variable Scope Description - * GeoKeyDirectory Global Location of the GeoTIFF GeoKey directory - * DoubleValues Global Location of the Double values for GeoTIFF Double GeoKeys - * GeoKeyOffset Parameter Location of this Key Entry Set in the GeoKey directory - * GeoKey Local Temporary value of the GeoKey - * KeyLength Local Temporary value for the length of the value for the GeoKey - * KeyValueOffset Local The location of the GeoKey value in the file - */ - + * Double Parameters Test Test + * id: http://www.opengis.net/spec/GeoTIFF/1.1/conf/DoubleParameters Requirements: + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.KeyEntry.ID + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag. + * keyEntryTIFFTagLocation + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyEntryKeyCount + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyEntryValueOffset + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoDoubleParamsTag.ID + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoDoubleParamsTag.count + * http://www.opengis.net/spec/GeoTIFF/1.1/req/PrimeMeridianLongitudeGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/UnitSizeGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/EllipsoidSemiMajorAxisGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/EllipsoidSemiMinorAxisGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/EllipsoidInvFlatteningGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ProjAngularParameterGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ProjLinearParameterGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ProjScalarParameterGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ProjAzimuthAngleGeoKey Purpose: Verify + * Double parameters Pre-conditions The GeoKeyDirectory, DoubleValues and GeoKeyOffset + * values have been set. Test Variables: Variable Scope Description GeoKeyDirectory + * Global Location of the GeoTIFF GeoKey directory DoubleValues Global Location of the + * Double values for GeoTIFF Double GeoKeys GeoKeyOffset Parameter Location of this + * Key Entry Set in the GeoKey directory GeoKey Local Temporary value of the GeoKey + * KeyLength Local Temporary value for the length of the value for the GeoKey + * KeyValueOffset Local The location of the GeoKey value in the file + */ + float processFourthShortForDouble(int index) { - int doubleIndex = (int) keyEntrySet.get(index+3); + int doubleIndex = (int) keyEntrySet.get(index + 3); // process the fourth Short integer in the Key Entry Set - List doubleParamsSet = directory.getTag(GEODOUBLEPARAMSTAG).getValues(); + List doubleParamsSet = directory.getTag(GEODOUBLEPARAMSTAG).getValues(); Assert.assertTrue(doubleParamsSet != null); // SET KeyValueOffset = DoubleValues + (KeyValueOffset * 8) - return (float) doubleParamsSet.get(doubleIndex); + return (float) doubleParamsSet.get(doubleIndex); } - - - // GeoKey Requirements Class - - // 2053 UnitSizeGeoKey (Geog Linear) - - @Test(description = "Double Params GeogLinearUnitSizeGeoKey (2053) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // GeoKey Requirements Class + + // 2053 UnitSizeGeoKey (Geog Linear) + + /** + *

    + * verifyGeogLinearUnitSizeGeoKey. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Double Params GeogLinearUnitSizeGeoKey (2053) Test", + dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyGeogLinearUnitSizeGeoKey() throws Exception { // the GeogLinearUnitSizeGeoKey SHALL have ID = 2053 int index = getKeyIndex(GEOGLINEARUNITSIZEGEOKEY); - + // not required - if(index == -1) { + if (index == -1) { return; } - + int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); float value = processFourthShortForDouble(index); - - // the GeogLinearUnitSizeGeoKey SHALL have type = DOUBLE + + // the GeogLinearUnitSizeGeoKey SHALL have type = DOUBLE Assert.assertTrue(type == GEODOUBLEPARAMSTAG, "the GeogLinearUnitSizeGeoKey SHALL have type = DOUBLE"); - + // the units of the GeogLinearUnitSizeGeoKey value SHALL be meters - Assert.assertTrue(keyExists(GEOGLINEARUNITSGEOKEY), "the units of the GeogLinearUnitSizeGeoKey value SHALL be meters"); - int unitsValue = (int) processFourthShortForShort(getKeyIndex(GEOGLINEARUNITSGEOKEY), processThirdShort(getKeyIndex(GEOGLINEARUNITSGEOKEY))); - if(unitsValue != 32767) Assert.assertTrue(EPSGDataSet.getItem(EPSGDataSet.UOM, "UOM_CODE", unitsValue, "TARGET_UOM_CODE").equals(EPSGDataSet.METERS), "the units of the GeogLinearUnitSizeGeoKey value SHALL be meters"); + Assert.assertTrue(keyExists(GEOGLINEARUNITSGEOKEY), + "the units of the GeogLinearUnitSizeGeoKey value SHALL be meters"); + int unitsValue = (int) processFourthShortForShort(getKeyIndex(GEOGLINEARUNITSGEOKEY), + processThirdShort(getKeyIndex(GEOGLINEARUNITSGEOKEY))); + if (unitsValue != 32767) + Assert.assertTrue(EPSGDataSet.getItem(EPSGDataSet.UOM, "UOM_CODE", unitsValue, "TARGET_UOM_CODE") + .equals(EPSGDataSet.METERS), "the units of the GeogLinearUnitSizeGeoKey value SHALL be meters"); } - -// 2055 UnitSizeGeoKey (Geog Angular) - - @Test(description = "Double Params GeogAngularUnitSizeGeoKey (2055) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 2055 UnitSizeGeoKey (Geog Angular) + + /** + *

    + * verifyGeogAngularUnitSizeGeoKey. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Double Params GeogAngularUnitSizeGeoKey (2055) Test", + dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyGeogAngularUnitSizeGeoKey() throws Exception { // the GeogAngularUnitSizeGeoKey SHALL have ID = 2055 int index = getKeyIndex(GEOGANGULARUNITSIZEGEOKEY); - + // not required - if(index == -1) { + if (index == -1) { return; } - + int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); float value = processFourthShortForDouble(index); - - // the GeogAngularUnitSizeGeoKey SHALL have type = DOUBLE + + // the GeogAngularUnitSizeGeoKey SHALL have type = DOUBLE Assert.assertTrue(type == GEODOUBLEPARAMSTAG, "the GeogAngularUnitSizeGeoKey SHALL have type = DOUBLE"); - + // the units of the GeogAngularUnitSizeGeoKey value SHALL be radians Assert.assertTrue(keyExists(GEOGANGULARUNITSGEOKEY)); - int unitsValue = (int) processFourthShortForShort(getKeyIndex(GEOGANGULARUNITSGEOKEY), processThirdShort(getKeyIndex(GEOGANGULARUNITSGEOKEY))); - if(unitsValue != 32767) Assert.assertTrue(EPSGDataSet.getItem(EPSGDataSet.UOM, "UOM_CODE", unitsValue, "TARGET_UOM_CODE").equals(EPSGDataSet.RADIANS), "the units of the GeogAngularUnitSizeGeoKey value SHALL be radians"); + int unitsValue = (int) processFourthShortForShort(getKeyIndex(GEOGANGULARUNITSGEOKEY), + processThirdShort(getKeyIndex(GEOGANGULARUNITSGEOKEY))); + if (unitsValue != 32767) + Assert.assertTrue( + EPSGDataSet.getItem(EPSGDataSet.UOM, "UOM_CODE", unitsValue, "TARGET_UOM_CODE") + .equals(EPSGDataSet.RADIANS), + "the units of the GeogAngularUnitSizeGeoKey value SHALL be radians"); } - -// 2057 EllipsoidSemiMajorAxisGeoKey - - @Test(description = "Double Params EllipsoidSemiMajorAxisGeoKey (2057) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 2057 EllipsoidSemiMajorAxisGeoKey + + /** + *

    + * verifyEllipsoidSemiMajorAxisGeoKey. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Double Params EllipsoidSemiMajorAxisGeoKey (2057) Test", + dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyEllipsoidSemiMajorAxisGeoKey() throws Exception { // the EllipsoidSemiMajorAxisGeoKey SHALL have ID = 2057 int index = getKeyIndex(ELLIPSOIDSEMIMAJORAXISGEOKEY); - + // not required - if(index == -1) { + if (index == -1) { return; } - + int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); float value = processFourthShortForDouble(index); - + // the EllipsoidSemiMajorAxisGeoKey SHALL have type = DOUBLE Assert.assertTrue(type == GEODOUBLEPARAMSTAG, "the EllipsoidSemiMajorAxisGeoKey SHALL have type = DOUBLE"); - - // the units of the EllipsoidSemiMajorAxisGeoKey SHALL be defined by the value of GeogLinearUnitsGeoKey - Assert.assertTrue(keyExists(GEOGLINEARUNITSGEOKEY), "the units of the EllipsoidSemiMajorAxisGeoKey SHALL be defined by the value of GeogLinearUnitsGeoKey"); + + // the units of the EllipsoidSemiMajorAxisGeoKey SHALL be defined by the value of + // GeogLinearUnitsGeoKey + Assert.assertTrue(keyExists(GEOGLINEARUNITSGEOKEY), + "the units of the EllipsoidSemiMajorAxisGeoKey SHALL be defined by the value of GeogLinearUnitsGeoKey"); } - -// 2058 EllipsoidSemiMinorAxisGeoKey - - @Test(description = "Double Params EllipsoidSemiMinorAxisGeoKey (2058) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 2058 EllipsoidSemiMinorAxisGeoKey + + /** + *

    + * verifyEllipsoidSemiMinorAxisGeoKey. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Double Params EllipsoidSemiMinorAxisGeoKey (2058) Test", + dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyEllipsoidSemiMinorAxisGeoKey() throws Exception { // the EllipsoidSemiMinorAxisGeoKey SHALL have ID = 2058 int index = getKeyIndex(ELLIPSOIDSEMIMINORAXISGEOKEY); - + // not required - if(index == -1) { + if (index == -1) { return; } - + int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); float value = processFourthShortForDouble(index); - + // the EllipsoidSemiMinorAxisGeoKey SHALL have type = DOUBLE Assert.assertTrue(type == GEODOUBLEPARAMSTAG, "the EllipsoidSemiMinorAxisGeoKey SHALL have type = DOUBLE"); - - // the units of the EllipsoidSemiMinorAxisGeoKey SHALL be defined by the value of GeogLinearUnitsGeoKey - Assert.assertTrue(keyExists(GEOGLINEARUNITSGEOKEY), "the units of the EllipsoidSemiMinorAxisGeoKey SHALL be defined by the value of GeogLinearUnitsGeoKey"); + + // the units of the EllipsoidSemiMinorAxisGeoKey SHALL be defined by the value of + // GeogLinearUnitsGeoKey + Assert.assertTrue(keyExists(GEOGLINEARUNITSGEOKEY), + "the units of the EllipsoidSemiMinorAxisGeoKey SHALL be defined by the value of GeogLinearUnitsGeoKey"); } - -// 2059 EllipsoidInvFlatteningGeoKey - - @Test(description = "Double Params EllipsoidInvFlatteningGeoKey (2059) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 2059 EllipsoidInvFlatteningGeoKey + + /** + *

    + * verifyEllipsoidInvFlatteningGeoKey. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Double Params EllipsoidInvFlatteningGeoKey (2059) Test", + dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyEllipsoidInvFlatteningGeoKey() throws Exception { // The EllipsoidInvFlatteningGeoKey SHALL have ID = 2059 int index = getKeyIndex(ELLIPSOIDINVFLATTENINGGEOKEY); - + // not required - if(index == -1) { + if (index == -1) { return; } - + int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); float value = processFourthShortForDouble(index); - + // the EllipsoidInvFlatteningGeoKey SHALL have type = DOUBLE - Assert.assertTrue(type == GEODOUBLEPARAMSTAG, "the EllipsoidInvFlatteningGeoKey SHALL have type = DOUBLE"); + Assert.assertTrue(type == GEODOUBLEPARAMSTAG, "the EllipsoidInvFlatteningGeoKey SHALL have type = DOUBLE"); } - -// 2061 PrimeMeridianLongitudeGeoKey - - @Test(description = "Double Params PrimeMeridianLongitudeGeoKey (2061) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 2061 PrimeMeridianLongitudeGeoKey + + /** + *

    + * verifyPrimeMeridianLongitudeGeoKey. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Double Params PrimeMeridianLongitudeGeoKey (2061) Test", + dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyPrimeMeridianLongitudeGeoKey() throws Exception { // the PrimeMeridianLongitudeGeoKey SHALL have ID = 2061 int index = getKeyIndex(PRIMEMERIDIANLONGITUDEGEOKEY); - + // not required - if(index == -1) { + if (index == -1) { return; } - + int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); float value = processFourthShortForDouble(index); - + // the PrimeMeridianLongitudeGeoKey SHALL have type = DOUBLE Assert.assertTrue(type == GEODOUBLEPARAMSTAG, "the PrimeMeridianLongitudeGeoKey SHALL have type = DOUBLE"); - + // the unit for the PrimeMeridianLongitudeGeoKey value SHALL be GeogAngularUnits - Assert.assertTrue(keyExists(GEOGANGULARUNITSGEOKEY), "the unit for the PrimeMeridianLongitudeGeoKey value SHALL be GeogAngularUnits"); + Assert.assertTrue(keyExists(GEOGANGULARUNITSGEOKEY), + "the unit for the PrimeMeridianLongitudeGeoKey value SHALL be GeogAngularUnits"); } - - -// 3077 UnitSizeGeoKey (Projected Linear) - - @Test(description = "Double Params ProjLinearUnitSizeGeoKey (3077) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 3077 UnitSizeGeoKey (Projected Linear) + + /** + *

    + * verifyProjLinearUnitSizeGeoKey. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Double Params ProjLinearUnitSizeGeoKey (3077) Test", + dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyProjLinearUnitSizeGeoKey() throws Exception { // the ProjLinearUnitSizeGeoKey SHALL have ID = 3077 int index = getKeyIndex(PROJLINEARUNITSIZEGEOKEY); - + // not required - if(index == -1) { + if (index == -1) { return; } - + int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); float value = processFourthShortForDouble(index); - - // the ProjLinearUnitSizeGeoKey SHALL have type = DOUBLE + + // the ProjLinearUnitSizeGeoKey SHALL have type = DOUBLE Assert.assertTrue(type == GEODOUBLEPARAMSTAG, "the ProjLinearUnitSizeGeoKey SHALL have type = DOUBLE"); - + // the units of the ProjLinearUnitSizeGeoKey value SHALL be meters - Assert.assertTrue(keyExists(PROJLINEARUNITSGEOKEY), "the units of the ProjLinearUnitSizeGeoKey value SHALL be meters"); - int unitsValue = (int) processFourthShortForShort(getKeyIndex(PROJLINEARUNITSGEOKEY), processThirdShort(getKeyIndex(PROJLINEARUNITSGEOKEY))); - if(unitsValue != 32767) Assert.assertTrue(EPSGDataSet.getItem(EPSGDataSet.UOM, "UOM_CODE", unitsValue, "TARGET_UOM_CODE").equals(EPSGDataSet.METERS), "the units of the ProjLinearUnitSizeGeoKey value SHALL be meters"); + Assert.assertTrue(keyExists(PROJLINEARUNITSGEOKEY), + "the units of the ProjLinearUnitSizeGeoKey value SHALL be meters"); + int unitsValue = (int) processFourthShortForShort(getKeyIndex(PROJLINEARUNITSGEOKEY), + processThirdShort(getKeyIndex(PROJLINEARUNITSGEOKEY))); + if (unitsValue != 32767) + Assert.assertTrue(EPSGDataSet.getItem(EPSGDataSet.UOM, "UOM_CODE", unitsValue, "TARGET_UOM_CODE") + .equals(EPSGDataSet.METERS), "the units of the ProjLinearUnitSizeGeoKey value SHALL be meters"); } -// 3092 ProjScalarParameters (Scale at Natural Origin) -// 3093 ProjScalarParameters (Scale at Center) - - @Test(description = "ProjScalarParameters Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + // 3092 ProjScalarParameters (Scale at Natural Origin) + // 3093 ProjScalarParameters (Scale at Center) + + /** + *

    + * verifyProjScalarParameters. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "ProjScalarParameters Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyProjScalarParameters() throws Exception { - + // the ProjScalarParameters SHALL have ID = XXX - int[] projScalarParameters = { - PROJSCALEATNATORIGINGEOKEY, - PROJSCALEATCENTERGEOKEY - }; - - for(int geoKey : projScalarParameters) { - + int[] projScalarParameters = { PROJSCALEATNATORIGINGEOKEY, PROJSCALEATCENTERGEOKEY }; + + for (int geoKey : projScalarParameters) { + int index = getKeyIndex(geoKey); - + // not required - if(index == -1) { + if (index == -1) { continue; } - + int type = processSecondShort(index); - + // all parameters in this requirements class SHALL have type = DOUBLE Assert.assertTrue(type == GEODOUBLEPARAMSTAG, "the ProjScalarParameters SHALL have type = DOUBLE"); } - } - - -// 3094 ProjAzimuthAngleGeoKey + } + + // 3094 ProjAzimuthAngleGeoKey - @Test(description = "Double Params ProjAzimuthAngleGeoKey (3094) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + /** + *

    + * verifyProjAzimuthAngleGeoKey. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "Double Params ProjAzimuthAngleGeoKey (3094) Test", + dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyProjAzimuthAngleGeoKey() throws Exception { // the ProjAzimuthAngleGeoKey SHALL have ID = 3094 int index = getKeyIndex(PROJAZIMUTHANGLEGEOKEY); - + // not required - if(index == -1) { + if (index == -1) { return; } - + int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); float value = processFourthShortForDouble(index); - - // the ProjAzimuthAngleGeoKey SHALL have type = DOUBLE + + // the ProjAzimuthAngleGeoKey SHALL have type = DOUBLE Assert.assertTrue(type == GEODOUBLEPARAMSTAG, "the ProjAzimuthAngleGeoKey SHALL have type = DOUBLE"); - - // the ProjAzimuthAngleGeoKey SHALL have units as specified by the GeogAzimuthUnitsGeoKey - Assert.assertTrue(keyExists(GEOGAZIMUTHUNITSGEOKEY), "the ProjAzimuthAngleGeoKey SHALL have units as specified by the GeogAzimuthUnitsGeoKey"); + + // the ProjAzimuthAngleGeoKey SHALL have units as specified by the + // GeogAzimuthUnitsGeoKey + Assert.assertTrue(keyExists(GEOGAZIMUTHUNITSGEOKEY), + "the ProjAzimuthAngleGeoKey SHALL have units as specified by the GeogAzimuthUnitsGeoKey"); } - -// 3078 ProjAngularParameters (Standard Parallel 1) -// 3079 ProjAngularParameters (Standard Parallel 2) -// 3080 ProjAngularParameters (Natural Origin Longitude) -// 3081 ProjAngularParameters (Natural Origin Latitude) -// 3084 ProjAngularParameters (False Origin Longitude) -// 3085 ProjAngularParameters (False Origin Latitude) -// 3088 ProjAngularParameters (Center Longitude) -// 3089 ProjAngularParameters (Center Latitude) -// 3095 ProjAngularParameters (Straight Vertical Pole) - - @Test(description = "ProjAngularParameters Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 3078 ProjAngularParameters (Standard Parallel 1) + // 3079 ProjAngularParameters (Standard Parallel 2) + // 3080 ProjAngularParameters (Natural Origin Longitude) + // 3081 ProjAngularParameters (Natural Origin Latitude) + // 3084 ProjAngularParameters (False Origin Longitude) + // 3085 ProjAngularParameters (False Origin Latitude) + // 3088 ProjAngularParameters (Center Longitude) + // 3089 ProjAngularParameters (Center Latitude) + // 3095 ProjAngularParameters (Straight Vertical Pole) + + /** + *

    + * verifyProjAngularParameters. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "ProjAngularParameters Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyProjAngularParameters() throws Exception { - + // the ProjAngularParameter SHALL have ID = XXX - int[] projAngularParameters = { - PROJSTDPARALLEL1GEOKEY, - PROJSTDPARALLEL2GEOKEY, - PROJNATORIGINLONGGEOKEY, - PROJNATORIGINLATGEOKEY, - PROJFALSEORIGINLONGGEOKEY, - PROJFALSEORIGINLATGEOKEY, - PROJCENTERLONGGEOKEY, - PROJCENTERLATGEOKEY, - PROJSTRAIGHTVERTPOLELONGGEOKEY - }; - - for(int geoKey : projAngularParameters) { - + int[] projAngularParameters = { PROJSTDPARALLEL1GEOKEY, PROJSTDPARALLEL2GEOKEY, PROJNATORIGINLONGGEOKEY, + PROJNATORIGINLATGEOKEY, PROJFALSEORIGINLONGGEOKEY, PROJFALSEORIGINLATGEOKEY, PROJCENTERLONGGEOKEY, + PROJCENTERLATGEOKEY, PROJSTRAIGHTVERTPOLELONGGEOKEY }; + + for (int geoKey : projAngularParameters) { + int index = getKeyIndex(geoKey); - + // not required - if(index == -1) { + if (index == -1) { continue; } - + int type = processSecondShort(index); - + // all parameters in this requirements class SHALL have type = DOUBLE Assert.assertTrue(type == GEODOUBLEPARAMSTAG, "the ProjAngularParameters SHALL have type = DOUBLE"); - - // all parameters in this requirements class SHALL have units as specified by the GeogAngularUnitsGeoKey - Assert.assertTrue(keyExists(GEOGANGULARUNITSGEOKEY), "all parameters in this requirements class SHALL have units as specified by the GeogAngularUnitsGeoKey"); + + // all parameters in this requirements class SHALL have units as specified by + // the GeogAngularUnitsGeoKey + Assert.assertTrue(keyExists(GEOGANGULARUNITSGEOKEY), + "all parameters in this requirements class SHALL have units as specified by the GeogAngularUnitsGeoKey"); } } - -// 3082 ProjLinearParameters (False Easting) -// 3083 ProjLinearParameters (False Northing) -// 3086 ProjLinearParameters (False Origin Easting) -// 3087 ProjLinearParameters (False Origin Northing) -// 3090 ProjLinearParameters (Projection Center Easting) -// 3091 ProjLinearParameters (Projection Center Northing) - - @Test(description = "ProjLinearParameters Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 3082 ProjLinearParameters (False Easting) + // 3083 ProjLinearParameters (False Northing) + // 3086 ProjLinearParameters (False Origin Easting) + // 3087 ProjLinearParameters (False Origin Northing) + // 3090 ProjLinearParameters (Projection Center Easting) + // 3091 ProjLinearParameters (Projection Center Northing) + + /** + *

    + * verifyProjLinearParameters. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "ProjLinearParameters Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyProjLinearParameters() throws Exception { - + // the ProjLinearParameter SHALL have ID = XXX - int[] projLinearParameters = { - PROJFALSEEASTINGGEOKEY, - PROJFALSENORTHINGGEOKEY, - PROJFALSEORIGINEASTINGGEOKEY, - PROJFALSEORIGINNORTHINGGEOKEY, - PROJCENTEREASTINGGEOKEY, - PROJCENTERNORTHINGGEOKEY - }; - - for(int geoKey : projLinearParameters) { - + int[] projLinearParameters = { PROJFALSEEASTINGGEOKEY, PROJFALSENORTHINGGEOKEY, PROJFALSEORIGINEASTINGGEOKEY, + PROJFALSEORIGINNORTHINGGEOKEY, PROJCENTEREASTINGGEOKEY, PROJCENTERNORTHINGGEOKEY }; + + for (int geoKey : projLinearParameters) { + int index = getKeyIndex(geoKey); - + // not required - if(index == -1) { + if (index == -1) { continue; } - + int type = processSecondShort(index); - + // all parameters in this requirements class SHALL have type = DOUBLE Assert.assertTrue(type == GEODOUBLEPARAMSTAG, "the ProjLinearParameters SHALL have type = DOUBLE"); - - // all parameters in this requirements class SHALL have units as specified by the ProjLinearUnitsGeoKey - Assert.assertTrue(keyExists(PROJLINEARUNITSGEOKEY), "all parameters in this requirements class SHALL have units as specified by the ProjLinearUnitsGeoKey"); + + // all parameters in this requirements class SHALL have units as specified by + // the ProjLinearUnitsGeoKey + Assert.assertTrue(keyExists(PROJLINEARUNITSGEOKEY), + "all parameters in this requirements class SHALL have units as specified by the ProjLinearUnitsGeoKey"); } } + } diff --git a/src/main/java/org/opengis/cite/geotiff11/tiffTests/GeoKeyDirectoryTests.java b/src/main/java/org/opengis/cite/geotiff11/tiffTests/GeoKeyDirectoryTests.java index f1d1266..a630598 100644 --- a/src/main/java/org/opengis/cite/geotiff11/tiffTests/GeoKeyDirectoryTests.java +++ b/src/main/java/org/opengis/cite/geotiff11/tiffTests/GeoKeyDirectoryTests.java @@ -1,124 +1,163 @@ package org.opengis.cite.geotiff11.tiffTests; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOKEYDIRECTORYTAG; + import java.util.List; import org.opengis.cite.geotiff11.util.TiffDump; import org.testng.Assert; import org.testng.annotations.Test; -import static org.opengis.cite.geotiff11.util.GeoKeyID.*; - // https://github.com/opengeospatial/geotiff/blob/5d6ab0ba54f1ed0174901dd84240817dc9dbe011/GeoTIFF_Standard/standard/abstract_tests/TIFF_Tests/TEST_GeoKeyDirectory.adoc +/** + *

    + * GeoKeyDirectoryTests class. + *

    + * + */ public class GeoKeyDirectoryTests extends CommonTiffMeta { // TODO: execute tests [...] - + /* * GeoKey Directory Test Test - * id: http://www.opengis.net/spec/GeoTIFF/1.1/conf/GeoKeyDirectory - * Requirements: - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyDirectoryVersion - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyDirectoryVersionValue - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyRevision - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyRevisionValue - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.minorRevision - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.minorRevisionValue - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.numberOfKeys - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyEntrySetCount - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.KeyEntry - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.KeyEntryKeyID - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.KeyEntryTIFFTagLocation - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeySort + * id: http://www.opengis.net/spec/GeoTIFF/1.1/conf/GeoKeyDirectory Requirements: + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyDirectoryVersion + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag. + * keyDirectoryVersionValue + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyRevision + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyRevisionValue + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.minorRevision + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.minorRevisionValue + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.numberOfKeys + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyEntrySetCount + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.KeyEntry + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.KeyEntryKeyID + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag. + * KeyEntryTIFFTagLocation http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeySort * Purpose: Verify the TIFF header and prepare for processing the GeoTIFF tags. - * Pre-conditions: None - * Test Variables: Variable Scope Description IFD_Offset Local Location within - * the TIFF file of an IFD GeoKeyDirectory Global Location of the GeoTIFF GeoKey - * directory ASCIIValues Global Location of the ASCII values for GeoTIFF ASCII - * GeoKeys DoubleValues Global Location of the Double values for GeoTIFF Double - * GeoKeys GeoKeyOffset Parameter Location of this GeoKey in the GeoKey + * Pre-conditions: None Test Variables: Variable Scope Description IFD_Offset Local + * Location within the TIFF file of an IFD GeoKeyDirectory Global Location of the + * GeoTIFF GeoKey directory ASCIIValues Global Location of the ASCII values for + * GeoTIFF ASCII GeoKeys DoubleValues Global Location of the Double values for GeoTIFF + * Double GeoKeys GeoKeyOffset Parameter Location of this GeoKey in the GeoKey * directory KeySetCount Local The number of entries in the GeoKey directory */ - @Test(description = "GeoKey Directory Test", groups = {"verifyGeoKeyDirectory"}) + /** + *

    + * verifyGeoKeyDirectory. + *

    + * @throws java.lang.Exception if any. + */ + @Test(description = "GeoKey Directory Test", groups = { "verifyGeoKeyDirectory" }) public void verifyGeoKeyDirectory() throws Exception { - + for (TiffDump.Directory directory : tiffDump.getDirectories()) { - + TiffDump.Tag geoKeyDirectory = directory.getTag(GEOKEYDIRECTORYTAG); // verify specific tag values if (directory.getOffset() != 0 && geoKeyDirectory != null) { - + // the GeoKeyDirectoryTag SHALL have ID = 34735 List keyEntrySet = geoKeyDirectory.getValues(); - - // the GeoKeyDirectoryTag SHALL have type = SHORT (2-byte unsigned integer) - Assert.assertTrue(geoKeyDirectory.getTypeValue() == 3, "the GeoKeyDirectoryTag SHALL have type = SHORT (2-byte unsigned integer)"); - + + // the GeoKeyDirectoryTag SHALL have type = SHORT (2-byte unsigned + // integer) + Assert.assertTrue(geoKeyDirectory.getTypeValue() == 3, + "the GeoKeyDirectoryTag SHALL have type = SHORT (2-byte unsigned integer)"); + if (keyEntrySet != null) { - - // the GeoKeyDirectoryTag SHALL include at least 4 keys (short integers) as header information - Assert.assertTrue(keyEntrySet.size() >= 4, "the GeoKeyDirectoryTag SHALL include at least 4 keys (short integers) as header information"); - - // each Key Entry in the Key Entry Set SHALL include 4 unsigned short integer values + + // the GeoKeyDirectoryTag SHALL include at least 4 keys (short + // integers) as header information + Assert.assertTrue(keyEntrySet.size() >= 4, + "the GeoKeyDirectoryTag SHALL include at least 4 keys (short integers) as header information"); + + // each Key Entry in the Key Entry Set SHALL include 4 unsigned short + // integer values // TODO: is this comprehensive enough? - Assert.assertTrue(keyEntrySet.size() % 4 == 0, "each Key Entry in the Key Entry Set SHALL include 4 unsigned short integer values"); - - // verify that Bytes 0-1 = 1 (the value of KeyDirectoryVersion SHALL be 1) - // the first unsigned short integer in the GeoKeyDirectoryTag SHALL hold the KeyDirectoryVersion + Assert.assertTrue(keyEntrySet.size() % 4 == 0, + "each Key Entry in the Key Entry Set SHALL include 4 unsigned short integer values"); + + // verify that Bytes 0-1 = 1 (the value of KeyDirectoryVersion SHALL + // be 1) + // the first unsigned short integer in the GeoKeyDirectoryTag SHALL + // hold the KeyDirectoryVersion Assert.assertTrue(keyEntrySet.get(0).equals(1), "the value of KeyDirectoryVersion SHALL be 1"); - + // verify that Bytes 2-3 = 1 (the value of KeyRevision SHALL be 1) - // the second unsigned short integer in the GeoKeyDirectoryTag SHALL hold the KeyRevision + // the second unsigned short integer in the GeoKeyDirectoryTag SHALL + // hold the KeyRevision Assert.assertTrue(keyEntrySet.get(1).equals(1), "the value of KeyRevision SHALL be 1"); - - // verify that Bytes 4-5 = 0 or 1 (the MinorRevision for this standard SHALL be O or 1) - // the third unsigned short integer in the GeoKeyDirectoryTag SHALL hold the MinorRevision - Assert.assertTrue(keyEntrySet.get(2).equals(0) || keyEntrySet.get(2).equals(1), "the MinorRevision for this standard SHALL be O or 1"); - - // bytes 6-7 contain the number of Key Entry Sets in this directory (the GeoKeyDirectoryTag SHALL hold NumberOfKeys KeyEntry Sets in addition to the header information) - // the fourth unsigned short integer in the GeoKeyDirectoryTag SHALL hold the NumberOfKeys defined in the rest of the GeoKeyDirectoryTag + + // verify that Bytes 4-5 = 0 or 1 (the MinorRevision for this standard + // SHALL be O or 1) + // the third unsigned short integer in the GeoKeyDirectoryTag SHALL + // hold the MinorRevision + Assert.assertTrue(keyEntrySet.get(2).equals(0) || keyEntrySet.get(2).equals(1), + "the MinorRevision for this standard SHALL be O or 1"); + + // bytes 6-7 contain the number of Key Entry Sets in this directory + // (the GeoKeyDirectoryTag SHALL hold NumberOfKeys KeyEntry Sets in + // addition to the header information) + // the fourth unsigned short integer in the GeoKeyDirectoryTag SHALL + // hold the NumberOfKeys defined in the rest of the GeoKeyDirectoryTag int keySetCount = (int) keyEntrySet.get(3); - + int count = 0; int previousGeoKey = -1000; - for(int i = 4; i < keyEntrySet.size(); i += 4) { + for (int i = 4; i < keyEntrySet.size(); i += 4) { int geoKey = (int) keyEntrySet.get(i); - - // if the current entry is less than the last geokey, check that it is not a key and is an additional param - if(geoKey < previousGeoKey) - { - // the GeoKeyDirectoryTag SHALL hold NumberOfKeys KeyEntry Sets in addition to the header information - // validate that the number of Key Sets processed equal the number specified in the header - Assert.assertTrue(count == keySetCount, "the GeoKeyDirectoryTag SHALL hold NumberOfKeys KeyEntry Sets in addition to the header information"); + + // if the current entry is less than the last geokey, check that + // it is not a key and is an additional param + if (geoKey < previousGeoKey) { + // the GeoKeyDirectoryTag SHALL hold NumberOfKeys KeyEntry + // Sets in addition to the header information + // validate that the number of Key Sets processed equal the + // number specified in the header + Assert.assertTrue(count == keySetCount, + "the GeoKeyDirectoryTag SHALL hold NumberOfKeys KeyEntry Sets in addition to the header information"); break; } - - // the GeoKey entries in a GeoTIFF file SHALL be written out to the file with the key-IDs sorted in ascending order - // verify that the GeoKey (first Short integer) is greater than the previous GeoKey - Assert.assertTrue(geoKey > previousGeoKey, "the GeoKey entries in a GeoTIFF file SHALL be written out to the file with the key-IDs sorted in ascending order"); + + // the GeoKey entries in a GeoTIFF file SHALL be written out to + // the file with the key-IDs sorted in ascending order + // verify that the GeoKey (first Short integer) is greater than + // the previous GeoKey + Assert.assertTrue(geoKey > previousGeoKey, + "the GeoKey entries in a GeoTIFF file SHALL be written out to the file with the key-IDs sorted in ascending order"); previousGeoKey = geoKey; count++; - + // process the second Short integer in the Key Entry Set - int type = (int) keyEntrySet.get(i+1); - + int type = (int) keyEntrySet.get(i + 1); + // this is all done elsewhere - - if(type == 0 || type == 34735) { - // execute test http://www.opengis.net/spec/GeoTIFF/1.1/conf/Short_Param passing GeoKeyOffset as a parameter - } - if(type == 34736) { - // execute test http://www.opengis.net/spec/GeoTIFF/1.1/conf/Double_Param passing GeoKeyOffset as a parameter - } - if(type == 34737) { - // execute test http://www.opengis.net/spec/GeoTIFF/1.1/conf/ASCII_Param passing GeoKeyOffset as a parameter + + if (type == 0 || type == 34735) { + // execute test + // http://www.opengis.net/spec/GeoTIFF/1.1/conf/Short_Param + // passing GeoKeyOffset as a parameter + } + if (type == 34736) { + // execute test + // http://www.opengis.net/spec/GeoTIFF/1.1/conf/Double_Param + // passing GeoKeyOffset as a parameter + } + if (type == 34737) { + // execute test + // http://www.opengis.net/spec/GeoTIFF/1.1/conf/ASCII_Param + // passing GeoKeyOffset as a parameter } } - } + } return; } - } + } Assert.fail("GeoKeyDirectoryTag not found"); } -} \ No newline at end of file + +} diff --git a/src/main/java/org/opengis/cite/geotiff11/tiffTests/GeoKeysTests.java b/src/main/java/org/opengis/cite/geotiff11/tiffTests/GeoKeysTests.java index 086d7fd..6f84b19 100644 --- a/src/main/java/org/opengis/cite/geotiff11/tiffTests/GeoKeysTests.java +++ b/src/main/java/org/opengis/cite/geotiff11/tiffTests/GeoKeysTests.java @@ -11,69 +11,88 @@ /* * Holds common functionalities of param tests */ +/** + *

    + * Abstract GeoKeysTests class. + *

    + * + */ public abstract class GeoKeysTests extends CommonTiffMeta { TiffDump.Directory directory; + List keyEntrySet; + int minorRevision; - + /* * Prepare directory and key entry set, fail the test if the geotiff is invalid. */ + /** + *

    + * setUpGeoKeyDirectory. + *

    + */ @BeforeClass public void setUpGeoKeyDirectory() { Assert.assertTrue(tiffDump != null, "TiffDump wrapping returned null"); directory = tiffDump.getGeoKeyDirectory(); Assert.assertTrue(directory != null, "GeoKeyDirectory not found"); Assert.assertTrue(directory.getTag(GEOKEYDIRECTORYTAG) != null, "GeoKeyDirectoryTag not found"); - keyEntrySet = directory.getTag(GEOKEYDIRECTORYTAG).getValues(); + keyEntrySet = directory.getTag(GEOKEYDIRECTORYTAG).getValues(); Assert.assertTrue(keyEntrySet != null, "GeoKeyDirectoryTag does not contain any values"); minorRevision = (int) keyEntrySet.get(2); } - + // helper functions - - // the fourth unsigned short integer in the Key Entry SHALL hold either the key value (if TIFF Tag location = or the index into the tag indicated by the TIFF Tag Location value. + + // the fourth unsigned short integer in the Key Entry SHALL hold either the key value + // (if TIFF Tag location = or the index into the tag indicated by the TIFF Tag + // Location value. int processFourthShortForShort(int index, int keyLength) { // process the fourth Short integer in the Key Entry Set - if(keyLength == 1) { + if (keyLength == 1) { // SET KeyValueOffset = GeoKeyDirectory + GeoKeyOffset + 6 - return (int) keyEntrySet.get(index+3); - } else { + return (int) keyEntrySet.get(index + 3); + } + else { // SET KeyValueOffset = GeoKeyDirectory + (KeyValueOffset * 2) return (int) keyEntrySet.get(keyLength); } } - - // the Third unsigned short integer in the Key Entry SHALL indicate the number of values associated with this key. + + // the Third unsigned short integer in the Key Entry SHALL indicate the number of + // values associated with this key. int processThirdShort(int index) { // process the third Short integer in the Key Entry Set return (int) keyEntrySet.get(index + 2); } - - // the second unsigned short integer in the Key Entry SHALL hold the TIFF Tag Location. The value of this entry shall be a valid GeoTIFF tag identifier or a zero (0) + + // the second unsigned short integer in the Key Entry SHALL hold the TIFF Tag + // Location. The value of this entry shall be a valid GeoTIFF tag identifier or a zero + // (0) int processSecondShort(int index) { // process the second Short integer in the Key Entry Set return (int) keyEntrySet.get(index + 1); } - + // the first unsigned short integer in the Key Entry SHALL hold the key identifier. int processFirstShort(int index) { // process the first Short integer in the Key Entry Set return (int) keyEntrySet.get(index); } - + boolean keyExists(int key) { return getKeyIndex(key) != -1; } - + int getKeyIndex(int key) { int index = keyEntrySet.indexOf(key); - - if(index % 4 != 0) { // keys occur every 4th short + + if (index % 4 != 0) { // keys occur every 4th short return -1; } return index; } - + } diff --git a/src/main/java/org/opengis/cite/geotiff11/tiffTests/ShortParamsTests.java b/src/main/java/org/opengis/cite/geotiff11/tiffTests/ShortParamsTests.java index c75a57c..b9342e6 100644 --- a/src/main/java/org/opengis/cite/geotiff11/tiffTests/ShortParamsTests.java +++ b/src/main/java/org/opengis/cite/geotiff11/tiffTests/ShortParamsTests.java @@ -1,713 +1,1047 @@ package org.opengis.cite.geotiff11.tiffTests; +import static org.opengis.cite.geotiff11.util.GeoKeyID.ELLIPSOIDGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.ELLIPSOIDINVFLATTENINGGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.ELLIPSOIDSEMIMAJORAXISGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.ELLIPSOIDSEMIMINORAXISGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEODETICCITATIONGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEODETICCRSGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEODETICDATUMGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOGANGULARUNITSGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOGANGULARUNITSIZEGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOGAZIMUTHUNITSGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOGLINEARUNITSGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOGLINEARUNITSIZEGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOKEYDIRECTORYTAG; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GTCITATIONGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GTMODELTYPEGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GTRASTERTYPEGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PRIMEMERIDIANGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PRIMEMERIDIANLONGITUDEGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJECTEDCITATIONGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJECTEDCRSGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJECTIONGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJLINEARUNITSGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJLINEARUNITSIZEGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.PROJMETHODGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.VERTICALCITATIONGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.VERTICALDATUMGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.VERTICALGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.VERTICALUNITSGEOKEY; + import java.io.IOException; import java.util.Arrays; + import org.apache.commons.csv.CSVRecord; import org.opengis.cite.geotiff11.util.EPSGDataSet; import org.testng.Assert; import org.testng.annotations.Test; -import static org.opengis.cite.geotiff11.util.GeoKeyID.*; - // https://github.com/opengeospatial/geotiff/blob/5d6ab0ba54f1ed0174901dd84240817dc9dbe011/GeoTIFF_Standard/standard/abstract_tests/TIFF_Tests/TEST_Short_Param.adoc +/** + *

    + * ShortParamsTests class. + *

    + * + */ public class ShortParamsTests extends GeoKeysTests { - + /* - * GeoKey Directory Test Test - * id: http://www.opengis.net/spec/GeoTIFF/1.1/conf/ShortParameters - * Requirements: - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.KeyEntry.ID - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyEntryTIFFTagLocation - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyEntryKeyCount - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyEntryValueOffset - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoShortParams.Criteria - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoShortParams.Location - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GTModelTypeGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GTRasterTypeGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeodeticCRSGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeodeticDatumGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/PrimeMeridianGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/UnitsGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/EllipsoidGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ProjectedCRSGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ProjectionGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ProjMethodGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/VerticalGeoKey - * http://www.opengis.net/spec/GeoTIFF/1.1/req/VerticalDatumGeoKey - * Purpose: Verify a Short parameter - * Pre-conditions: The GeoKeyDirectory and GeoKeyOffset values have been set Test Variables: - * Test Variables: ... + * GeoKey Directory Test Test id: + * http://www.opengis.net/spec/GeoTIFF/1.1/conf/ShortParameters Requirements: + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.KeyEntry.ID + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag. + * keyEntryTIFFTagLocation + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyEntryKeyCount + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.keyEntryValueOffset + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoShortParams.Criteria + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoShortParams.Location + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GTModelTypeGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GTRasterTypeGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeodeticCRSGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeodeticDatumGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/PrimeMeridianGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/UnitsGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/EllipsoidGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ProjectedCRSGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ProjectionGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ProjMethodGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/VerticalGeoKey + * http://www.opengis.net/spec/GeoTIFF/1.1/req/VerticalDatumGeoKey Purpose: Verify a + * Short parameter Pre-conditions: The GeoKeyDirectory and GeoKeyOffset values have + * been set Test Variables: Test Variables: ... */ - - // In the case where a Parameter of type Short has more than one value, those values SHALL be stored in the GeoKeysDirectory - // TODO: Parameter values stored in the GeoKeysDirectory SHALL appear after the last Key Entry ??? How to implement this? - + + // In the case where a Parameter of type Short has more than one value, those values + // SHALL be stored in the GeoKeysDirectory + // TODO: Parameter values stored in the GeoKeysDirectory SHALL appear after the last + // Key Entry ??? How to implement this? + // GeoKeys with a value of 0 SHALL indicate intentionally omitted parameters // GeoKeys with a value of 32767 SHALL indicate user-defined parameters - - // https://github.com/opengeospatial/geotiff/blob/68d8f902293ad64526889daa055892ea30f9e9ea/GeoTIFF_Standard/Detailed%20Test%20Suite/abstract_tests/Requirements_Trace_Matrix.adoc - // GeoKey Requirements Class - // 0 ignore - // 1024 GTModelTypeGeoKey - - @Test(description = "Short Params GTModelTypeGeoKey (1024) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // https://github.com/opengeospatial/geotiff/blob/68d8f902293ad64526889daa055892ea30f9e9ea/GeoTIFF_Standard/Detailed%20Test%20Suite/abstract_tests/Requirements_Trace_Matrix.adoc + // GeoKey Requirements Class + // 0 ignore + // 1024 GTModelTypeGeoKey + + /** + *

    + * verifyGTModelTypeGeoKey. + *

    + */ + @Test(description = "Short Params GTModelTypeGeoKey (1024) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyGTModelTypeGeoKey() { // the GTModelTypeGeoKey SHALL have ID = 1024 int index = getKeyIndex(GTMODELTYPEGEOKEY); // a GeoTIFF file SHALL include a GTModelTypeGeoKey Assert.assertTrue(index != -1, "a GeoTIFF file SHALL include a GTModelTypeGeoKey"); - + int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the GTModelTypeGeoKey SHALL have type = SHORT + + // the GTModelTypeGeoKey SHALL have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the GTModelTypeGeoKey SHALL have type = SHORT"); - + // GTModelTypeGeoKey values in the range 4-32766 SHALL be reserved - Assert.assertFalse(value >= 4 && value <= 32766, "GTModelTypeGeoKey values in the range 4-32766 SHALL be reserved"); - + Assert.assertFalse(value >= 4 && value <= 32766, + "GTModelTypeGeoKey values in the range 4-32766 SHALL be reserved"); + // GTModelTypeGeoKey values in the range 32768-65535 SHALL be private - Assert.assertFalse(value > 65535 || value < 0, "GTModelTypeGeoKey values in the range 32768-65535 SHALL be private"); - - switch(value) { - // if the GTModelTypeGeoKey value is 1 (Model CRS is a projected 2D CRS) then the GeoTIFF file SHALL include a ProjectedCRSGeoKey 3072 + Assert.assertFalse(value > 65535 || value < 0, + "GTModelTypeGeoKey values in the range 32768-65535 SHALL be private"); + + switch (value) { + // if the GTModelTypeGeoKey value is 1 (Model CRS is a projected 2D CRS) then + // the GeoTIFF file SHALL include a ProjectedCRSGeoKey 3072 case 1: - Assert.assertTrue(keyExists(PROJECTEDCRSGEOKEY), "if the GTModelTypeGeoKey value is 1 (Model CRS is a projected 2D CRS) then the GeoTIFF file SHALL include a ProjectedCRSGeoKey 3072"); + Assert.assertTrue(keyExists(PROJECTEDCRSGEOKEY), + "if the GTModelTypeGeoKey value is 1 (Model CRS is a projected 2D CRS) then the GeoTIFF file SHALL include a ProjectedCRSGeoKey 3072"); break; - // if the GTModelTypeGeoKey value is 2 (Model CRS is a geographic 2D CRS) then the GeoTIFF file SHALL include a GeodeticCRSGeoKey 2048 - // if the GTModelTypeGeoKey value is 3 (Model CRS is a geocentric CRS) then the GeoTIFF file SHALL include a GeodeticCRSGeoKey 2048 + // if the GTModelTypeGeoKey value is 2 (Model CRS is a geographic 2D CRS) then + // the GeoTIFF file SHALL include a GeodeticCRSGeoKey 2048 + // if the GTModelTypeGeoKey value is 3 (Model CRS is a geocentric CRS) then + // the GeoTIFF file SHALL include a GeodeticCRSGeoKey 2048 case 2: case 3: // TODO: check model? - Assert.assertTrue(keyExists(GEODETICCRSGEOKEY), "if the GTModelTypeGeoKey value is 2/3 then the GeoTIFF file SHALL include a GeodeticCRSGeoKey"); + Assert.assertTrue(keyExists(GEODETICCRSGEOKEY), + "if the GTModelTypeGeoKey value is 2/3 then the GeoTIFF file SHALL include a GeodeticCRSGeoKey"); break; - // if the GTModelTypeGeoKey value is 32767 (user-defined) then the GTCitationGeoKey SHALL be populated + // if the GTModelTypeGeoKey value is 32767 (user-defined) then the + // GTCitationGeoKey SHALL be populated case 32767: - Assert.assertTrue(keyExists(GTCITATIONGEOKEY), "if the GTModelTypeGeoKey value is 32767 (user-defined) then the GTCitationGeoKey SHALL be populated"); + Assert.assertTrue(keyExists(GTCITATIONGEOKEY), + "if the GTModelTypeGeoKey value is 32767 (user-defined) then the GTCitationGeoKey SHALL be populated"); break; } } - // 1025 GTRasterTypeGeoKey - - @Test(description = "Short Params GTRasterTypeGeoKey (1025) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + // 1025 GTRasterTypeGeoKey + + /** + *

    + * verifyGTRasterTypeGeoKey. + *

    + */ + @Test(description = "Short Params GTRasterTypeGeoKey (1025) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyGTRasterTypeGeoKey() { // the GTRasterTypeGeoKey SHALL have ID = 1025 int index = getKeyIndex(GTRASTERTYPEGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the GTRasterTypeGeoKey SHALL have type = SHORT + + // the GTRasterTypeGeoKey SHALL have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the GTRasterTypeGeoKey SHALL have type = SHORT"); - + // the GTRasterTypeGeoKey value SHALL be: 0, 1, 2, 32767, else - if (!Arrays.asList(0, 1, 2, 32767).contains(value)) - { + if (!Arrays.asList(0, 1, 2, 32767).contains(value)) { // GTRasterTypeGeoKey values in the range 3-32766 SHALL be reserved - Assert.assertFalse(value >= 3 && value <= 32766, "GTRasterTypeGeoKey values in the range 3-32766 SHALL be reserved"); - + Assert.assertFalse(value >= 3 && value <= 32766, + "GTRasterTypeGeoKey values in the range 3-32766 SHALL be reserved"); + // GTRasterTypeGeoKey values in the range 32768-65535 SHALL be private // value out of bounds Assert.assertFalse(value > 65535 || value < 0, "GTRasterTypeGeoKey value out of bounds"); } } - - // 2048 GeodeticCRSGeoKey - - @Test(description = "Short Params GeodeticCRSGeoKey (2048) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 2048 GeodeticCRSGeoKey + + /** + *

    + * verifyGeodeticCRSGeoKey. + *

    + * @throws java.io.IOException if any. + */ + @Test(description = "Short Params GeodeticCRSGeoKey (2048) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyGeodeticCRSGeoKey() throws IOException { // the GeodeticCRSGeoKey SHALL have ID = 2048 int index = getKeyIndex(GEODETICCRSGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the GeodeticCRSGeoKey SHALL have type = SHORT + + // the GeodeticCRSGeoKey SHALL have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the GeodeticCRSGeoKey SHALL have type = SHORT"); - - // if the GeodeticCRSGeoKey value is 32767 (User-Defined) then the GeodeticCitationGeoKey 2049, GeodeticDatumGeoKey 2050 and at least one of GeogAngularUnitsGeoKey 2054 or GeogLinearUnitsGeoKey 2052 SHALL be populated - if(value == 32767) { - Assert.assertTrue(keyExists(GEODETICCITATIONGEOKEY) && keyExists(GEODETICDATUMGEOKEY) && (keyExists(GEOGANGULARUNITSGEOKEY) || keyExists(GEOGLINEARUNITSGEOKEY)), "if the GeodeticCRSGeoKey value is 32767 (User-Defined) then the GeodeticCitationGeoKey 2049, GeodeticDatumGeoKey 2050 and at least one of GeogAngularUnitsGeoKey 2054 or GeogLinearUnitsGeoKey 2052 SHALL be populated"); - } else if(value >= 1024 && value <= 32766) { - // GeodeticCRSGeoKey values in the range 1024-32766 SHALL be EPSG geodetic CRS codes (geographic 2D CRS, geographic 3D CRS, and geocentric CRS) + + // if the GeodeticCRSGeoKey value is 32767 (User-Defined) then the + // GeodeticCitationGeoKey 2049, GeodeticDatumGeoKey 2050 and at least one of + // GeogAngularUnitsGeoKey 2054 or GeogLinearUnitsGeoKey 2052 SHALL be populated + if (value == 32767) { + Assert.assertTrue( + keyExists(GEODETICCITATIONGEOKEY) && keyExists(GEODETICDATUMGEOKEY) + && (keyExists(GEOGANGULARUNITSGEOKEY) || keyExists(GEOGLINEARUNITSGEOKEY)), + "if the GeodeticCRSGeoKey value is 32767 (User-Defined) then the GeodeticCitationGeoKey 2049, GeodeticDatumGeoKey 2050 and at least one of GeogAngularUnitsGeoKey 2054 or GeogLinearUnitsGeoKey 2052 SHALL be populated"); + } + else if (value >= 1024 && value <= 32766) { + // GeodeticCRSGeoKey values in the range 1024-32766 SHALL be EPSG geodetic CRS + // codes (geographic 2D CRS, geographic 3D CRS, and geocentric CRS) CSVRecord record = EPSGDataSet.getRecord(EPSGDataSet.CRS, "COORD_REF_SYS_CODE", Integer.toString(value)); - Assert.assertTrue(record != null, "GeodeticCRSGeoKey values in the range 1024-32766 SHALL be EPSG geodetic CRS codes (geographic 2D CRS, geographic 3D CRS, and geocentric CRS)"); + Assert.assertTrue(record != null, + "GeodeticCRSGeoKey values in the range 1024-32766 SHALL be EPSG geodetic CRS codes (geographic 2D CRS, geographic 3D CRS, and geocentric CRS)"); // Assert.assertTrue(minorRevision == 1); // not necessary - Assert.assertTrue(record.get("DEPRECATED").equals("0"), "GeodeticCRSGeoKey values in the range 1024-32766 SHALL be EPSG geodetic CRS codes (geographic 2D CRS, geographic 3D CRS, and geocentric CRS)"); - Assert.assertTrue(record.get("COORD_REF_SYS_KIND").equals("geographic 2D") || record.get("COORD_REF_SYS_KIND").equals("geographic 3D") || record.get("COORD_REF_SYS_KIND").equals("geocentric"), "GeodeticCRSGeoKey values in the range 1024-32766 SHALL be EPSG geodetic CRS codes (geographic 2D CRS, geographic 3D CRS, and geocentric CRS)"); - } else if(value >= 1 && value <= 1000) { - // GeodeticCRSGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POC Geographic Codes - Assert.assertTrue(minorRevision == 0, "GeodeticCRSGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POC Geographic Codes"); - } else { + Assert.assertTrue(record.get("DEPRECATED").equals("0"), + "GeodeticCRSGeoKey values in the range 1024-32766 SHALL be EPSG geodetic CRS codes (geographic 2D CRS, geographic 3D CRS, and geocentric CRS)"); + Assert.assertTrue( + record.get("COORD_REF_SYS_KIND").equals("geographic 2D") + || record.get("COORD_REF_SYS_KIND").equals("geographic 3D") + || record.get("COORD_REF_SYS_KIND").equals("geocentric"), + "GeodeticCRSGeoKey values in the range 1024-32766 SHALL be EPSG geodetic CRS codes (geographic 2D CRS, geographic 3D CRS, and geocentric CRS)"); + } + else if (value >= 1 && value <= 1000) { + // GeodeticCRSGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POC + // Geographic Codes + Assert.assertTrue(minorRevision == 0, + "GeodeticCRSGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POC Geographic Codes"); + } + else { // GeodeticCRSGeoKey values in the range 1001-1023 SHALL be reserved - Assert.assertFalse(value >= 1001 && value <= 1023, "GeodeticCRSGeoKey values in the range 1001-1023 SHALL be reserved"); - + Assert.assertFalse(value >= 1001 && value <= 1023, + "GeodeticCRSGeoKey values in the range 1001-1023 SHALL be reserved"); + // GeodeticCRSGeoKeyvalues in the range 32768-65535 SHALL be private // value out of bounds Assert.assertFalse(value > 65535 || value < 0, "GeodeticCRSGeoKeyvalues value out of bounds"); } } - - // 2050 GeodeticDatumGeoKey - - @Test(description = "Short Params GeodeticDatumGeoKey (2050) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 2050 GeodeticDatumGeoKey + + /** + *

    + * verifyGeodeticDatumGeoKey. + *

    + * @throws java.io.IOException if any. + */ + @Test(description = "Short Params GeodeticDatumGeoKey (2050) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyGeodeticDatumGeoKey() throws IOException { // the GeodeticDatumGeoKey SHALL have ID = 2050 int index = getKeyIndex(GEODETICDATUMGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the GeodeticDatumGeoKey SHALL have type = SHORT + + // the GeodeticDatumGeoKey SHALL have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the GeodeticDatumGeoKey SHALL have type = SHORT"); - - if(value == 32767) { - // If the GeodeticDatumGeoKey value is 32767 (User-Defined) then the GeodeticCitationGeoKey 2049, PrimeMeridianGeoKey 2051 and EllipsoidGeoKey 2056 SHALL be populated - Assert.assertTrue(keyExists(GEODETICCITATIONGEOKEY) && keyExists(PRIMEMERIDIANGEOKEY) && keyExists(ELLIPSOIDGEOKEY), "if the GeodeticDatumGeoKey value is 32767 (User-Defined) then the GeodeticCitationGeoKey 2049, PrimeMeridianGeoKey 2051 and EllipsoidGeoKey 2056 SHALL be populated"); - } else if(value >= 1024 && value <= 32766) { - // GeodeticDatumGeoKey values in the range 1024-32766 SHALL be EPSG geodetic datum codes + + if (value == 32767) { + // If the GeodeticDatumGeoKey value is 32767 (User-Defined) then the + // GeodeticCitationGeoKey 2049, PrimeMeridianGeoKey 2051 and EllipsoidGeoKey + // 2056 SHALL be populated + Assert.assertTrue( + keyExists(GEODETICCITATIONGEOKEY) && keyExists(PRIMEMERIDIANGEOKEY) && keyExists(ELLIPSOIDGEOKEY), + "if the GeodeticDatumGeoKey value is 32767 (User-Defined) then the GeodeticCitationGeoKey 2049, PrimeMeridianGeoKey 2051 and EllipsoidGeoKey 2056 SHALL be populated"); + } + else if (value >= 1024 && value <= 32766) { + // GeodeticDatumGeoKey values in the range 1024-32766 SHALL be EPSG geodetic + // datum codes CSVRecord record = EPSGDataSet.getRecord(EPSGDataSet.DATUM, "DATUM_CODE", Integer.toString(value)); - Assert.assertTrue(record != null, "GeodeticDatumGeoKey values in the range 1024-32766 SHALL be EPSG geodetic datum codes"); + Assert.assertTrue(record != null, + "GeodeticDatumGeoKey values in the range 1024-32766 SHALL be EPSG geodetic datum codes"); // Assert.assertTrue(minorRevision == 1); // not necessary Assert.assertTrue(record.get("DEPRECATED").equals("0")); Assert.assertTrue(record.get("DATUM_TYPE").equals("geodetic")); - } else { - // GeodeticDatumGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POS Datum Codes - Assert.assertFalse(minorRevision != 0 && value >= 1 && value <= 1000, "GeodeticDatumGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POS Datum Codes"); - + } + else { + // GeodeticDatumGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POS + // Datum Codes + Assert.assertFalse(minorRevision != 0 && value >= 1 && value <= 1000, + "GeodeticDatumGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POS Datum Codes"); + // GeodeticDatumGeoKey values in the range 1001-1023 SHALL be reserved - Assert.assertFalse(value >= 1001 && value <= 1023, "GeodeticDatumGeoKey values in the range 1001-1023 SHALL be reserved"); - + Assert.assertFalse(value >= 1001 && value <= 1023, + "GeodeticDatumGeoKey values in the range 1001-1023 SHALL be reserved"); + // GeodeticDatumGeoKey values in the range 32768-65535 SHALL be private // value out of bounds Assert.assertFalse(value > 65535 || value < 0, "GeodeticDatumGeoKey value out of bounds"); } } - - // 2051 PrimeMeridianGeoKey - - @Test(description = "Short Params PrimeMeridianGeoKey (2051) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 2051 PrimeMeridianGeoKey + + /** + *

    + * verifyPrimeMeridianGeoKey. + *

    + * @throws java.io.IOException if any. + */ + @Test(description = "Short Params PrimeMeridianGeoKey (2051) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyPrimeMeridianGeoKey() throws IOException { // the PrimeMeridianGeoKey SHALL have ID = 2051 int index = getKeyIndex(PRIMEMERIDIANGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the PrimeMeridianGeoKey SHALL have type = SHORT + + // the PrimeMeridianGeoKey SHALL have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the PrimeMeridianGeoKey SHALL have type = SHORT"); - - if(value == 32767) { - // If the PrimeMeridianGeoKey value is 32767 (User-Defined) then the GeodeticCitationGeoKey, and PrimeMeridianLongGeoKey SHALL be populated - Assert.assertTrue(keyExists(GEODETICCITATIONGEOKEY) && keyExists(PRIMEMERIDIANLONGITUDEGEOKEY), "if the PrimeMeridianGeoKey value is 32767 (User-Defined) then the GeodeticCitationGeoKey, and PrimeMeridianLongGeoKey SHALL be populated"); - } else if(value >= 1024 && value <= 32766) { - // PrimeMeridianGeoKey values in the range 1024-32766 SHALL be EPSG Prime Meridian Codes - CSVRecord record = EPSGDataSet.getRecord(EPSGDataSet.PRIMEMERIDIAN, "PRIME_MERIDIAN_CODE", Integer.toString(value)); - Assert.assertTrue(record != null, "PrimeMeridianGeoKey values in the range 1024-32766 SHALL be EPSG Prime Meridian Codes"); + + if (value == 32767) { + // If the PrimeMeridianGeoKey value is 32767 (User-Defined) then the + // GeodeticCitationGeoKey, and PrimeMeridianLongGeoKey SHALL be populated + Assert.assertTrue(keyExists(GEODETICCITATIONGEOKEY) && keyExists(PRIMEMERIDIANLONGITUDEGEOKEY), + "if the PrimeMeridianGeoKey value is 32767 (User-Defined) then the GeodeticCitationGeoKey, and PrimeMeridianLongGeoKey SHALL be populated"); + } + else if (value >= 1024 && value <= 32766) { + // PrimeMeridianGeoKey values in the range 1024-32766 SHALL be EPSG Prime + // Meridian Codes + CSVRecord record = EPSGDataSet.getRecord(EPSGDataSet.PRIMEMERIDIAN, "PRIME_MERIDIAN_CODE", + Integer.toString(value)); + Assert.assertTrue(record != null, + "PrimeMeridianGeoKey values in the range 1024-32766 SHALL be EPSG Prime Meridian Codes"); // Assert.assertTrue(minorRevision == 1); // not necessary - Assert.assertTrue(record.get("DEPRECATED").equals("0"), "PrimeMeridianGeoKey values in the range 1024-32766 SHALL be EPSG Prime Meridian Codes"); - } else { - - // PrimeMeridianGeoKey values in the range 1-100 SHALL be obsolete EPSG/POSC Datum Codes - Assert.assertFalse(minorRevision != 0 && value >= 1 && value <= 100, "PrimeMeridianGeoKey values in the range 1-100 SHALL be obsolete EPSG/POSC Datum Codes"); - + Assert.assertTrue(record.get("DEPRECATED").equals("0"), + "PrimeMeridianGeoKey values in the range 1024-32766 SHALL be EPSG Prime Meridian Codes"); + } + else { + + // PrimeMeridianGeoKey values in the range 1-100 SHALL be obsolete EPSG/POSC + // Datum Codes + Assert.assertFalse(minorRevision != 0 && value >= 1 && value <= 100, + "PrimeMeridianGeoKey values in the range 1-100 SHALL be obsolete EPSG/POSC Datum Codes"); + // PrimeMeridianGeoKey values in the range 101-1023 SHALL be reserved - Assert.assertFalse(value >= 101 && value <= 1023, "PrimeMeridianGeoKey values in the range 101-1023 SHALL be reserved"); - + Assert.assertFalse(value >= 101 && value <= 1023, + "PrimeMeridianGeoKey values in the range 101-1023 SHALL be reserved"); + // PrimeMeridianGeoKey values in the range 32768-65535 SHALL be private // value out of bounds Assert.assertFalse(value > 65535 || value < 0, "PrimeMeridianGeoKey value out of bounds"); } } - - // 2052 UnitsGeoKey (Linear Units) GeogLinearUnitsGeoKey - - @Test(description = "Short Params GeogLinearUnitsGeoKey (2052) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 2052 UnitsGeoKey (Linear Units) GeogLinearUnitsGeoKey + + /** + *

    + * verifyGeogLinearUnitsGeoKey. + *

    + * @throws java.io.IOException if any. + */ + @Test(description = "Short Params GeogLinearUnitsGeoKey (2052) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyGeogLinearUnitsGeoKey() throws IOException { // the GeogLinearUnitsGeoKey SHALL have ID = 2052 int index = getKeyIndex(GEOGLINEARUNITSGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the GeogAngularUnitsGeoKey, the GeogAzimuthUnitsGeoKey, the GeogLinearUnitsGeoKey, the ProjLinearUnitsGeoKey and the VerticalUnitsGeoKey SHALL each have type = SHORT + + // the GeogAngularUnitsGeoKey, the GeogAzimuthUnitsGeoKey, the + // GeogLinearUnitsGeoKey, the ProjLinearUnitsGeoKey and the VerticalUnitsGeoKey + // SHALL each have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the GeogLinearUnitsGeoKey SHALL have type = SHORT"); - - if(value == 32767) { - // A GeogLinearUnitsGeoKey value of 32767 SHALL be a user-defined linear unit. If the value is 32767 (User-Defined) then the GeodeticCitationGeoKey and the GeogLinearUnitSizeGeoKey SHALL be populated - Assert.assertTrue(keyExists(GEODETICCITATIONGEOKEY) && keyExists(GEOGLINEARUNITSIZEGEOKEY), "a GeogLinearUnitsGeoKey value of 32767 SHALL be a user-defined linear unit. If the value is 32767 (User-Defined) then the GeodeticCitationGeoKey and the GeogLinearUnitSizeGeoKey SHALL be populated"); - } else if(value >= 1024 && value <= 32766) { - // GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length + + if (value == 32767) { + // A GeogLinearUnitsGeoKey value of 32767 SHALL be a user-defined linear unit. + // If the value is 32767 (User-Defined) then the GeodeticCitationGeoKey and + // the GeogLinearUnitSizeGeoKey SHALL be populated + Assert.assertTrue(keyExists(GEODETICCITATIONGEOKEY) && keyExists(GEOGLINEARUNITSIZEGEOKEY), + "a GeogLinearUnitsGeoKey value of 32767 SHALL be a user-defined linear unit. If the value is 32767 (User-Defined) then the GeodeticCitationGeoKey and the GeogLinearUnitSizeGeoKey SHALL be populated"); + } + else if (value >= 1024 && value <= 32766) { + // GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values + // in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type + // = length CSVRecord record = EPSGDataSet.getRecord(EPSGDataSet.UOM, "UOM_CODE", Integer.toString(value)); - Assert.assertTrue(record != null, "GeogLinearUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); + Assert.assertTrue(record != null, + "GeogLinearUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); // Assert.assertTrue(minorRevision == 1); // not necessary - Assert.assertTrue(record.get("DEPRECATED").equals("0"), "GeogLinearUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); - Assert.assertTrue(record.get("UNIT_OF_MEAS_TYPE").equals("length"), "GeogLinearUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); - } else { - // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 1-1023 SHALL be reserved - Assert.assertFalse(value >= 1 && value <= 1023, "GeogLinearUnitsGeoKey values in the range 1-1023 SHALL be reserved"); - - // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 32768-65535 SHALL be private + Assert.assertTrue(record.get("DEPRECATED").equals("0"), + "GeogLinearUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); + Assert.assertTrue(record.get("UNIT_OF_MEAS_TYPE").equals("length"), + "GeogLinearUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); + } + else { + // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, + // ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 1-1023 + // SHALL be reserved + Assert.assertFalse(value >= 1 && value <= 1023, + "GeogLinearUnitsGeoKey values in the range 1-1023 SHALL be reserved"); + + // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, + // ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range + // 32768-65535 SHALL be private // value out of bounds Assert.assertFalse(value > 65535 || value < 0, "GeogLinearUnitsGeoKey value out of bounds"); } } - - // 2054 UnitsGeoKey (Angular Units) GeogAngularUnitsGeoKey - - @Test(description = "Short Params GeogAngularUnitsGeoKey (2054) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 2054 UnitsGeoKey (Angular Units) GeogAngularUnitsGeoKey + + /** + *

    + * verifyGeogAngularUnitsGeoKey. + *

    + * @throws java.io.IOException if any. + */ + @Test(description = "Short Params GeogAngularUnitsGeoKey (2054) Test", + dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyGeogAngularUnitsGeoKey() throws IOException { // the GeogAngularUnitsGeoKey SHALL have ID = 2054 int index = getKeyIndex(GEOGANGULARUNITSGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the GeogAngularUnitsGeoKey, the GeogAzimuthUnitsGeoKey, the GeogLinearUnitsGeoKey, the ProjLinearUnitsGeoKey and the VerticalUnitsGeoKey SHALL each have type = SHORT - Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the GeogAngularUnitsGeoKey SHALL have type = SHORT"); - - if(value == 32767) { - // A GeogAngularUnitsGeoKey or a GeogAzimuthUnitsGeoKey value of 32767 SHALL be a user-defined angular unit. If the value is 32767 (User-Defined) then the GeodeticCitationGeoKey and the GeogAngularUnitSizeGeoKey SHALL be populated - Assert.assertTrue(keyExists(GEODETICCITATIONGEOKEY) && keyExists(GEOGANGULARUNITSIZEGEOKEY), "A GeogAngularUnitsGeoKey or a GeogAzimuthUnitsGeoKey value of 32767 SHALL be a user-defined angular unit. If the value is 32767 (User-Defined) then the GeodeticCitationGeoKey and the GeogAngularUnitSizeGeoKey SHALL be populated"); - } else if(value >= 1024 && value <= 32766) { - // GeogAngularUnitsGeoKey and GeogAzimuthUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle + + // the GeogAngularUnitsGeoKey, the GeogAzimuthUnitsGeoKey, the + // GeogLinearUnitsGeoKey, the ProjLinearUnitsGeoKey and the VerticalUnitsGeoKey + // SHALL each have type = SHORT + Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, + "the GeogAngularUnitsGeoKey SHALL have type = SHORT"); + + if (value == 32767) { + // A GeogAngularUnitsGeoKey or a GeogAzimuthUnitsGeoKey value of 32767 SHALL + // be a user-defined angular unit. If the value is 32767 (User-Defined) then + // the GeodeticCitationGeoKey and the GeogAngularUnitSizeGeoKey SHALL be + // populated + Assert.assertTrue(keyExists(GEODETICCITATIONGEOKEY) && keyExists(GEOGANGULARUNITSIZEGEOKEY), + "A GeogAngularUnitsGeoKey or a GeogAzimuthUnitsGeoKey value of 32767 SHALL be a user-defined angular unit. If the value is 32767 (User-Defined) then the GeodeticCitationGeoKey and the GeogAngularUnitSizeGeoKey SHALL be populated"); + } + else if (value >= 1024 && value <= 32766) { + // GeogAngularUnitsGeoKey and GeogAzimuthUnitsGeoKey values in the range + // 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle CSVRecord record = EPSGDataSet.getRecord(EPSGDataSet.UOM, "UOM_CODE", Integer.toString(value)); - Assert.assertTrue(record != null, "GeogAzimuthUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle"); + Assert.assertTrue(record != null, + "GeogAzimuthUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle"); // Assert.assertTrue(minorRevision == 1); // not necessary - Assert.assertTrue(record.get("DEPRECATED").equals("0"), "GeogAzimuthUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle"); - Assert.assertTrue(record.get("UNIT_OF_MEAS_TYPE").equals("angle"), "GeogAzimuthUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle"); - } else { - // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 1-1023 SHALL be reserved - Assert.assertFalse(value >= 1 && value <= 1023, "GeogAngularUnitsGeoKey values in the range 1-1023 SHALL be reserved"); - - // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 32768-65535 SHALL be private + Assert.assertTrue(record.get("DEPRECATED").equals("0"), + "GeogAzimuthUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle"); + Assert.assertTrue(record.get("UNIT_OF_MEAS_TYPE").equals("angle"), + "GeogAzimuthUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle"); + } + else { + // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, + // ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 1-1023 + // SHALL be reserved + Assert.assertFalse(value >= 1 && value <= 1023, + "GeogAngularUnitsGeoKey values in the range 1-1023 SHALL be reserved"); + + // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, + // ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range + // 32768-65535 SHALL be private // value out of bounds Assert.assertFalse(value > 65535 || value < 0, "GeogAngularUnitsGeoKey value out of bounds"); } } - - // 2056 EllipsoidGeoKey - - @Test(description = "Short Params EllipsoidGeoKey (2056) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 2056 EllipsoidGeoKey + + /** + *

    + * verifyEllipsoidGeoKey. + *

    + * @throws java.io.IOException if any. + */ + @Test(description = "Short Params EllipsoidGeoKey (2056) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyEllipsoidGeoKey() throws IOException { // the PrimeMeridianGeoKey SHALL have ID = 2056 int index = getKeyIndex(ELLIPSOIDGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the EllipsoidGeoKey SHALL have type = SHORT + + // the EllipsoidGeoKey SHALL have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the EllipsoidGeoKey SHALL have type = SHORT"); - - if(value == 32767) { - // If the EllipsoidGeoKey value is 32767 (User-Defined) then the GTCitationGeoKey and the EllipsoidSemiMajorAxisGeoKey SHALL be populated together with the one of either the EllipsoidSemiMinorAxisGeoKey or the EllipsoidInvFlatteningGeoKey - Assert.assertTrue(keyExists(GEODETICCITATIONGEOKEY) && keyExists(ELLIPSOIDSEMIMAJORAXISGEOKEY) && (keyExists(ELLIPSOIDSEMIMINORAXISGEOKEY) || keyExists(ELLIPSOIDINVFLATTENINGGEOKEY)), "if the EllipsoidGeoKey value is 32767 (User-Defined) then the GTCitationGeoKey and the EllipsoidSemiMajorAxisGeoKey SHALL be populated together with the one of either the EllipsoidSemiMinorAxisGeoKey or the EllipsoidInvFlatteningGeoKey"); - } else if(value >= 1024 && value <= 32766) { - // EllipsoidGeoKey values in the range 1024-32766 SHALL be EPSG ellipsoid Codes + + if (value == 32767) { + // If the EllipsoidGeoKey value is 32767 (User-Defined) then the + // GTCitationGeoKey and the EllipsoidSemiMajorAxisGeoKey SHALL be populated + // together with the one of either the EllipsoidSemiMinorAxisGeoKey or the + // EllipsoidInvFlatteningGeoKey + Assert.assertTrue( + keyExists(GEODETICCITATIONGEOKEY) && keyExists(ELLIPSOIDSEMIMAJORAXISGEOKEY) + && (keyExists(ELLIPSOIDSEMIMINORAXISGEOKEY) || keyExists(ELLIPSOIDINVFLATTENINGGEOKEY)), + "if the EllipsoidGeoKey value is 32767 (User-Defined) then the GTCitationGeoKey and the EllipsoidSemiMajorAxisGeoKey SHALL be populated together with the one of either the EllipsoidSemiMinorAxisGeoKey or the EllipsoidInvFlatteningGeoKey"); + } + else if (value >= 1024 && value <= 32766) { + // EllipsoidGeoKey values in the range 1024-32766 SHALL be EPSG ellipsoid + // Codes CSVRecord record = EPSGDataSet.getRecord(EPSGDataSet.ELLIPSOID, "ELLIPSOID_CODE", Integer.toString(value)); - Assert.assertTrue(record != null, "EllipsoidGeoKey values in the range 1024-32766 SHALL be EPSG ellipsoid Codes"); + Assert.assertTrue(record != null, + "EllipsoidGeoKey values in the range 1024-32766 SHALL be EPSG ellipsoid Codes"); // Assert.assertTrue(minorRevision == 1); // not necessary - Assert.assertTrue(record.get("DEPRECATED").equals("0"), "EllipsoidGeoKey values in the range 1024-32766 SHALL be EPSG ellipsoid Codes"); - } else { - // EllipsoidGeoKey values in the range 1024-32766 SHALL be EPSG ellipsoid Codes - Assert.assertFalse(minorRevision != 1 && value >= 1024 && value <= 32766, "EllipsoidGeoKey values in the range 1024-32766 SHALL be EPSG ellipsoid Codes"); - - // EllipsoidGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POSC Datum Codes + Assert.assertTrue(record.get("DEPRECATED").equals("0"), + "EllipsoidGeoKey values in the range 1024-32766 SHALL be EPSG ellipsoid Codes"); + } + else { + // EllipsoidGeoKey values in the range 1024-32766 SHALL be EPSG ellipsoid + // Codes + Assert.assertFalse(minorRevision != 1 && value >= 1024 && value <= 32766, + "EllipsoidGeoKey values in the range 1024-32766 SHALL be EPSG ellipsoid Codes"); + + // EllipsoidGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POSC + // Datum Codes // Chuck said code lookup wasn't necessary here - Assert.assertFalse(minorRevision != 0 && value >= 1 && value <= 1000, "EllipsoidGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POSC Datum Codes"); - + Assert.assertFalse(minorRevision != 0 && value >= 1 && value <= 1000, + "EllipsoidGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POSC Datum Codes"); + // EllipsoidGeoKey values in the range 32768-65535 SHALL be private // value out of bounds - Assert.assertFalse(value > 65535 || value < 0, "EllipsoidGeoKey value out of bounds"); // TODO: Check if between 1000-1023? + Assert.assertFalse(value > 65535 || value < 0, "EllipsoidGeoKey value out of bounds"); // TODO: + // Check + // if + // between + // 1000-1023? } } - - // 2060 UnitsGeoKey (Azimuth Units) GeogAzimuthUnitsGeoKey - - @Test(description = "Short Params GeogAzimuthUnitsGeoKey (2060) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 2060 UnitsGeoKey (Azimuth Units) GeogAzimuthUnitsGeoKey + + /** + *

    + * verifyGeogAzimuthUnitsGeoKey. + *

    + * @throws java.io.IOException if any. + */ + @Test(description = "Short Params GeogAzimuthUnitsGeoKey (2060) Test", + dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyGeogAzimuthUnitsGeoKey() throws IOException { // the GeogAzimuthUnitsGeoKey SHALL have ID = 2060 int index = getKeyIndex(GEOGAZIMUTHUNITSGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the GeogAngularUnitsGeoKey, the GeogAzimuthUnitsGeoKey, the GeogLinearUnitsGeoKey, the ProjLinearUnitsGeoKey and the VerticalUnitsGeoKey SHALL each have type = SHORT + + // the GeogAngularUnitsGeoKey, the GeogAzimuthUnitsGeoKey, the + // GeogLinearUnitsGeoKey, the ProjLinearUnitsGeoKey and the VerticalUnitsGeoKey + // SHALL each have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "GeogAzimuthUnitsGeoKey SHALL have type = SHORT"); - - if(value == 32767) { - // A GeogAngularUnitsGeoKey or a GeogAzimuthUnitsGeoKey value of 32767 SHALL be a user-defined angular unit. If the value is 32767 (User-Defined) then the GeodeticCitationGeoKey and the GeogAngularUnitSizeGeoKey SHALL be populated - Assert.assertTrue(keyExists(GEODETICCITATIONGEOKEY) && keyExists(GEOGANGULARUNITSIZEGEOKEY), "a GeogAngularUnitsGeoKey or a GeogAzimuthUnitsGeoKey value of 32767 SHALL be a user-defined angular unit. If the value is 32767 (User-Defined) then the GeodeticCitationGeoKey and the GeogAngularUnitSizeGeoKey SHALL be populated"); - } else if(value >= 1024 && value <= 32766) { - // GeogAngularUnitsGeoKey and GeogAzimuthUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle + + if (value == 32767) { + // A GeogAngularUnitsGeoKey or a GeogAzimuthUnitsGeoKey value of 32767 SHALL + // be a user-defined angular unit. If the value is 32767 (User-Defined) then + // the GeodeticCitationGeoKey and the GeogAngularUnitSizeGeoKey SHALL be + // populated + Assert.assertTrue(keyExists(GEODETICCITATIONGEOKEY) && keyExists(GEOGANGULARUNITSIZEGEOKEY), + "a GeogAngularUnitsGeoKey or a GeogAzimuthUnitsGeoKey value of 32767 SHALL be a user-defined angular unit. If the value is 32767 (User-Defined) then the GeodeticCitationGeoKey and the GeogAngularUnitSizeGeoKey SHALL be populated"); + } + else if (value >= 1024 && value <= 32766) { + // GeogAngularUnitsGeoKey and GeogAzimuthUnitsGeoKey values in the range + // 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle CSVRecord record = EPSGDataSet.getRecord(EPSGDataSet.UOM, "UOM_CODE", Integer.toString(value)); - Assert.assertTrue(record != null, "GeogAzimuthUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle"); + Assert.assertTrue(record != null, + "GeogAzimuthUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle"); // Assert.assertTrue(minorRevision == 1); // not necessary - Assert.assertTrue(record.get("DEPRECATED").equals("0"), "GeogAzimuthUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle"); - Assert.assertTrue(record.get("UNIT_OF_MEAS_TYPE").equals("angle"), "GeogAzimuthUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle"); - } else { - // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 1-1023 SHALL be reserved - Assert.assertFalse(value >= 1 && value <= 1023, "GeogAzimuthUnitsGeoKey values in the range 1-1023 SHALL be reserved"); - - // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 32768-65535 SHALL be private + Assert.assertTrue(record.get("DEPRECATED").equals("0"), + "GeogAzimuthUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle"); + Assert.assertTrue(record.get("UNIT_OF_MEAS_TYPE").equals("angle"), + "GeogAzimuthUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = angle"); + } + else { + // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, + // ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 1-1023 + // SHALL be reserved + Assert.assertFalse(value >= 1 && value <= 1023, + "GeogAzimuthUnitsGeoKey values in the range 1-1023 SHALL be reserved"); + + // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, + // ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range + // 32768-65535 SHALL be private // value out of bounds Assert.assertFalse(value > 65535 || value < 0, "GeogAzimuthUnitsGeoKey value out of bounds"); } } - - // 3072 ProjectedCRSGeoKey - - @Test(description = "Short Params ProjectedCRSGeoKey (2056) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 3072 ProjectedCRSGeoKey + + /** + *

    + * verifyProjectedCRSGeoKey. + *

    + * @throws java.io.IOException if any. + */ + @Test(description = "Short Params ProjectedCRSGeoKey (2056) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyProjectedCRSGeoKey() throws IOException { // the ProjectedCRSGeoKey SHALL have ID = 3072 int index = getKeyIndex(PROJECTEDCRSGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the ProjectedCRSGeoKey SHALL have type = SHORT + + // the ProjectedCRSGeoKey SHALL have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the ProjectedCRSGeoKey SHALL have type = SHORT"); - - if(value == 32767) { - // A ProjectedCRSGeoKey value of 32767 SHALL be a user-defined projected CRS. If the ProjectedCRSGeoKey value is 32767 (User-Defined) then the ProjectedCitationGeoKey, GeodeticCRSGeoKey and ProjectionGeoKey SHALL be populated - Assert.assertTrue(keyExists(PROJECTEDCITATIONGEOKEY) && keyExists(GEODETICCRSGEOKEY) && keyExists(PROJECTIONGEOKEY), "a ProjectedCRSGeoKey value of 32767 SHALL be a user-defined projected CRS. If the ProjectedCRSGeoKey value is 32767 (User-Defined) then the ProjectedCitationGeoKey, GeodeticCRSGeoKey and ProjectionGeoKey SHALL be populated"); - } else if(value >= 1024 && value <= 32766) { - // ProjectedCRSGeoKey values in the range 1024-32766 SHALL be EPSG Projected CRS Codes + + if (value == 32767) { + // A ProjectedCRSGeoKey value of 32767 SHALL be a user-defined projected CRS. + // If the ProjectedCRSGeoKey value is 32767 (User-Defined) then the + // ProjectedCitationGeoKey, GeodeticCRSGeoKey and ProjectionGeoKey SHALL be + // populated + Assert.assertTrue( + keyExists(PROJECTEDCITATIONGEOKEY) && keyExists(GEODETICCRSGEOKEY) && keyExists(PROJECTIONGEOKEY), + "a ProjectedCRSGeoKey value of 32767 SHALL be a user-defined projected CRS. If the ProjectedCRSGeoKey value is 32767 (User-Defined) then the ProjectedCitationGeoKey, GeodeticCRSGeoKey and ProjectionGeoKey SHALL be populated"); + } + else if (value >= 1024 && value <= 32766) { + // ProjectedCRSGeoKey values in the range 1024-32766 SHALL be EPSG Projected + // CRS Codes CSVRecord record = EPSGDataSet.getRecord(EPSGDataSet.CRS, "COORD_REF_SYS_CODE", Integer.toString(value)); - Assert.assertTrue(record != null, "ProjectedCRSGeoKey values in the range 1024-32766 SHALL be EPSG Projected CRS Codes"); + Assert.assertTrue(record != null, + "ProjectedCRSGeoKey values in the range 1024-32766 SHALL be EPSG Projected CRS Codes"); // Assert.assertTrue(minorRevision == 1); // not necessary - Assert.assertTrue(record.get("DEPRECATED").equals("0"), "ProjectedCRSGeoKey values in the range 1024-32766 SHALL be EPSG Projected CRS Codes"); - Assert.assertTrue(record.get("COORD_REF_SYS_KIND").equals("projected"), "ProjectedCRSGeoKey values in the range 1024-32766 SHALL be EPSG Projected CRS Codes"); - } else { - // ProjectedCRSGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POC Datum Codes - Assert.assertFalse(minorRevision != 0 && value >= 1 && value <= 1000, "ProjectedCRSGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POC Datum Codes"); - + Assert.assertTrue(record.get("DEPRECATED").equals("0"), + "ProjectedCRSGeoKey values in the range 1024-32766 SHALL be EPSG Projected CRS Codes"); + Assert.assertTrue(record.get("COORD_REF_SYS_KIND").equals("projected"), + "ProjectedCRSGeoKey values in the range 1024-32766 SHALL be EPSG Projected CRS Codes"); + } + else { + // ProjectedCRSGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POC + // Datum Codes + Assert.assertFalse(minorRevision != 0 && value >= 1 && value <= 1000, + "ProjectedCRSGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POC Datum Codes"); + // ProjectedCRSGeoKey values in the range 1001-1023 SHALL be reserved - Assert.assertFalse(value >= 1001 && value <= 1023, "ProjectedCRSGeoKey values in the range 1001-1023 SHALL be reserved"); - + Assert.assertFalse(value >= 1001 && value <= 1023, + "ProjectedCRSGeoKey values in the range 1001-1023 SHALL be reserved"); + // ProjectedCRSGeoKey values in the range 32768-65535 SHALL be private // value out of bounds Assert.assertFalse(value > 65535 || value < 0, "ProjectedCRSGeoKey value out of bounds"); } } - - // 3074 ProjectionGeoKey - - @Test(description = "Short Params ProjectionGeoKey (3074) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 3074 ProjectionGeoKey + + /** + *

    + * verifyProjectionGeoKey. + *

    + * @throws java.io.IOException if any. + */ + @Test(description = "Short Params ProjectionGeoKey (3074) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyProjectionGeoKey() throws IOException { // the ProjectionGeoKey SHALL have ID = 3074 int index = getKeyIndex(PROJECTIONGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the ProjectionGeoKey SHALL have type = SHORT + + // the ProjectionGeoKey SHALL have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the ProjectionGeoKey SHALL have type = SHORT"); - - if(value == 32767) { - // If the ProjectionGeoKey value is 32767 (User-Defined) then the ProjectedCitationGeoKey, ProjectionMethodGeoKey, and ProjLinearUnitsGeoKey SHALL be populated - Assert.assertTrue(keyExists(PROJECTEDCITATIONGEOKEY) && keyExists(PROJMETHODGEOKEY) && keyExists(PROJLINEARUNITSGEOKEY), "If the ProjectionGeoKey value is 32767 (User-Defined) then the ProjectedCitationGeoKey, ProjectionMethodGeoKey, and ProjLinearUnitsGeoKey SHALL be populated"); - } else if(value >= 1024 && value <= 32766) { - // ProjectionGeoKey values in the range 1024-32766 SHALL be valid EPSG map projection (coordinate operation) codes + + if (value == 32767) { + // If the ProjectionGeoKey value is 32767 (User-Defined) then the + // ProjectedCitationGeoKey, ProjectionMethodGeoKey, and ProjLinearUnitsGeoKey + // SHALL be populated + Assert.assertTrue( + keyExists(PROJECTEDCITATIONGEOKEY) && keyExists(PROJMETHODGEOKEY) + && keyExists(PROJLINEARUNITSGEOKEY), + "If the ProjectionGeoKey value is 32767 (User-Defined) then the ProjectedCitationGeoKey, ProjectionMethodGeoKey, and ProjLinearUnitsGeoKey SHALL be populated"); + } + else if (value >= 1024 && value <= 32766) { + // ProjectionGeoKey values in the range 1024-32766 SHALL be valid EPSG map + // projection (coordinate operation) codes CSVRecord record = EPSGDataSet.getRecord(EPSGDataSet.CO, "COORD_OP_CODE", Integer.toString(value)); - Assert.assertTrue(record != null, "ProjectionGeoKey values in the range 1024-32766 SHALL be valid EPSG map projection (coordinate operation) codes"); + Assert.assertTrue(record != null, + "ProjectionGeoKey values in the range 1024-32766 SHALL be valid EPSG map projection (coordinate operation) codes"); // Assert.assertTrue(minorRevision == 1); // not necessary - Assert.assertTrue(record.get("DEPRECATED").equals("0"), "ProjectionGeoKey values in the range 1024-32766 SHALL be valid EPSG map projection (coordinate operation) codes"); - } else { + Assert.assertTrue(record.get("DEPRECATED").equals("0"), + "ProjectionGeoKey values in the range 1024-32766 SHALL be valid EPSG map projection (coordinate operation) codes"); + } + else { // ProjectionGeoKey values in the range 1-1023 SHALL be reserved - Assert.assertFalse(value >= 1 && value <= 1023, "ProjectionGeoKey values in the range 1-1023 SHALL be reserved"); - + Assert.assertFalse(value >= 1 && value <= 1023, + "ProjectionGeoKey values in the range 1-1023 SHALL be reserved"); + // ProjectionGeoKey values in the range 32768-65535 SHALL be private // value out of bounds Assert.assertFalse(value > 65535 || value < 0, "ProjectionGeoKey value out of bounds"); } } - - // 3075 ProjMethodGeoKey - - @Test(description = "Short Params ProjMethodGeoKey (3075) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 3075 ProjMethodGeoKey + + /** + *

    + * verifyProjMethodGeoKey. + *

    + */ + @Test(description = "Short Params ProjMethodGeoKey (3075) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyProjMethodGeoKey() { // the ProjMethodGeoKey SHALL have ID = 3075 int index = getKeyIndex(PROJMETHODGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the ProjMethodGeoKey SHALL have type = SHORT + + // the ProjMethodGeoKey SHALL have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the ProjMethodGeoKey SHALL have type = SHORT"); - - if(value == 32767) { - // If the ProjectionMethodGeoKey value is 32767 (User-Defined) then the ProjectedCitationGeoKey - Assert.assertTrue(keyExists(PROJECTEDCITATIONGEOKEY), "if the ProjectionMethodGeoKey value is 32767 (User-Defined) then the ProjectedCitationGeoKey "); - // and keys for each map projection parameter (coordinate operation parameter) appropriate to that method SHALL be populated + + if (value == 32767) { + // If the ProjectionMethodGeoKey value is 32767 (User-Defined) then the + // ProjectedCitationGeoKey + Assert.assertTrue(keyExists(PROJECTEDCITATIONGEOKEY), + "if the ProjectionMethodGeoKey value is 32767 (User-Defined) then the ProjectedCitationGeoKey "); + // and keys for each map projection parameter (coordinate operation parameter) + // appropriate to that method SHALL be populated // TODO: can I even test this? - } else { - // ProjMethodGeoKey values in the range 1-27 SHALL be GeoTIFF map projection method codes + } + else { + // ProjMethodGeoKey values in the range 1-27 SHALL be GeoTIFF map projection + // method codes // nothing to check here, is valid if passes - + // ProjMethodGeoKey values in the range 28-32766 SHALL be reserved - Assert.assertFalse(value >= 28 && value <= 32766, "ProjMethodGeoKey values in the range 28-32766 SHALL be reserved"); - + Assert.assertFalse(value >= 28 && value <= 32766, + "ProjMethodGeoKey values in the range 28-32766 SHALL be reserved"); + // ProjMethodGeoKey values in the range 32768-65535 SHALL be private // value out of bounds Assert.assertFalse(value > 65535 || value < 0, "ProjMethodGeoKey value out of bounds"); } } - - // 3076 UnitsGeoKey (Linear Units) ProjLinearUnitsGeoKey - - @Test(description = "Short Params ProjLinearUnitsGeoKey (3076) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 3076 UnitsGeoKey (Linear Units) ProjLinearUnitsGeoKey + + /** + *

    + * verifyProjLinearUnitsGeoKey. + *

    + * @throws java.io.IOException if any. + */ + @Test(description = "Short Params ProjLinearUnitsGeoKey (3076) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyProjLinearUnitsGeoKey() throws IOException { // the ProjLinearUnitsGeoKey SHALL have ID = 3076 int index = getKeyIndex(PROJLINEARUNITSGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the GeogAngularUnitsGeoKey, the GeogAzimuthUnitsGeoKey, the GeogLinearUnitsGeoKey, the ProjLinearUnitsGeoKey and the VerticalUnitsGeoKey SHALL each have type = SHORT + + // the GeogAngularUnitsGeoKey, the GeogAzimuthUnitsGeoKey, the + // GeogLinearUnitsGeoKey, the ProjLinearUnitsGeoKey and the VerticalUnitsGeoKey + // SHALL each have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the ProjLinearUnitsGeoKey SHALL have type = SHORT"); - - if(value == 32767) { - // A ProjLinearUnitsGeoKey value of 32767 SHALL be a user-defined linear unit. If the value is 32767 (User-Defined) then the ProjectedCitationGeoKey and the ProjLinearUnitSizeGeoKey SHALL be populated - Assert.assertTrue(keyExists(PROJECTEDCITATIONGEOKEY) && keyExists(PROJLINEARUNITSIZEGEOKEY), "a ProjLinearUnitsGeoKey value of 32767 SHALL be a user-defined linear unit. If the value is 32767 (User-Defined) then the ProjectedCitationGeoKey and the ProjLinearUnitSizeGeoKey SHALL be populated"); - } else if(value >= 1024 && value <= 32766) { - // GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length + + if (value == 32767) { + // A ProjLinearUnitsGeoKey value of 32767 SHALL be a user-defined linear unit. + // If the value is 32767 (User-Defined) then the ProjectedCitationGeoKey and + // the ProjLinearUnitSizeGeoKey SHALL be populated + Assert.assertTrue(keyExists(PROJECTEDCITATIONGEOKEY) && keyExists(PROJLINEARUNITSIZEGEOKEY), + "a ProjLinearUnitsGeoKey value of 32767 SHALL be a user-defined linear unit. If the value is 32767 (User-Defined) then the ProjectedCitationGeoKey and the ProjLinearUnitSizeGeoKey SHALL be populated"); + } + else if (value >= 1024 && value <= 32766) { + // GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values + // in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type + // = length CSVRecord record = EPSGDataSet.getRecord(EPSGDataSet.UOM, "UOM_CODE", Integer.toString(value)); - Assert.assertTrue(record != null, "ProjLinearUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); + Assert.assertTrue(record != null, + "ProjLinearUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); // Assert.assertTrue(minorRevision == 1); // not necessary - Assert.assertTrue(record.get("DEPRECATED").equals("0"),"ProjLinearUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); - Assert.assertTrue(record.get("UNIT_OF_MEAS_TYPE").equals("length"), "ProjLinearUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); - } else { - // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 1-1023 SHALL be reserved - Assert.assertFalse(value >= 1 && value <= 1023, "ProjLinearUnitsGeoKey values in the range 1-1023 SHALL be reserved"); - - // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 32768-65535 SHALL be private + Assert.assertTrue(record.get("DEPRECATED").equals("0"), + "ProjLinearUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); + Assert.assertTrue(record.get("UNIT_OF_MEAS_TYPE").equals("length"), + "ProjLinearUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); + } + else { + // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, + // ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 1-1023 + // SHALL be reserved + Assert.assertFalse(value >= 1 && value <= 1023, + "ProjLinearUnitsGeoKey values in the range 1-1023 SHALL be reserved"); + + // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, + // ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range + // 32768-65535 SHALL be private // value out of bounds Assert.assertFalse(value > 65535 || value < 0, "ProjLinearUnitsGeoKey value out of bounds"); } } - - // 4096 VerticalGeoKey - - @Test(description = "Short Params VerticalGeoKey (4096) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 4096 VerticalGeoKey + + /** + *

    + * verifyVerticalGeoKey. + *

    + * @throws java.io.IOException if any. + */ + @Test(description = "Short Params VerticalGeoKey (4096) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyVerticalGeoKey() throws IOException { // the VerticalGeoKey SHALL have ID = 4096 int index = getKeyIndex(VERTICALGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the VerticalGeoKey SHALL have type = SHORT + + // the VerticalGeoKey SHALL have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the VerticalGeoKey SHALL have type = SHORT"); - - if(value == 32767) { - // If the VerticalGeoKey value is 32767 (User-Defined) then the VerticalCitationGeoKey, the VerticalUnitsGeoKey and VerticalDatumGeoKey SHALL be populated - Assert.assertTrue(keyExists(VERTICALCITATIONGEOKEY) && keyExists(VERTICALUNITSGEOKEY) && keyExists(VERTICALDATUMGEOKEY), "if the VerticalGeoKey value is 32767 (User-Defined) then the VerticalCitationGeoKey, the VerticalUnitsGeoKey and VerticalDatumGeoKey SHALL be populated"); - } else if(value >= 1024 && value <= 32766) { - // VerticalGeoKey values in the range 1024-32766 SHALL be either EPSG Vertical CRS Codes or EPSG geographic 3D CRS codes + + if (value == 32767) { + // If the VerticalGeoKey value is 32767 (User-Defined) then the + // VerticalCitationGeoKey, the VerticalUnitsGeoKey and VerticalDatumGeoKey + // SHALL be populated + Assert.assertTrue( + keyExists(VERTICALCITATIONGEOKEY) && keyExists(VERTICALUNITSGEOKEY) + && keyExists(VERTICALDATUMGEOKEY), + "if the VerticalGeoKey value is 32767 (User-Defined) then the VerticalCitationGeoKey, the VerticalUnitsGeoKey and VerticalDatumGeoKey SHALL be populated"); + } + else if (value >= 1024 && value <= 32766) { + // VerticalGeoKey values in the range 1024-32766 SHALL be either EPSG Vertical + // CRS Codes or EPSG geographic 3D CRS codes CSVRecord record = EPSGDataSet.getRecord(EPSGDataSet.CRS, "COORD_REF_SYS_CODE", Integer.toString(value)); - Assert.assertTrue(record != null, "VerticalGeoKey values in the range 1024-32766 SHALL be either EPSG Vertical CRS Codes or EPSG geographic 3D CRS codes"); + Assert.assertTrue(record != null, + "VerticalGeoKey values in the range 1024-32766 SHALL be either EPSG Vertical CRS Codes or EPSG geographic 3D CRS codes"); // Assert.assertTrue(minorRevision == 1); // not necessary - Assert.assertTrue(record.get("DEPRECATED").equals("0"), "VerticalGeoKey values in the range 1024-32766 SHALL be either EPSG Vertical CRS Codes or EPSG geographic 3D CRS codes"); - Assert.assertTrue(record.get("COORD_REF_SYS_KIND").equals("vertical") || record.get("COORD_REF_SYS_KIND").equals("geographic 3D"), "VerticalGeoKey values in the range 1024-32766 SHALL be either EPSG Vertical CRS Codes or EPSG geographic 3D CRS codes"); - } else { + Assert.assertTrue(record.get("DEPRECATED").equals("0"), + "VerticalGeoKey values in the range 1024-32766 SHALL be either EPSG Vertical CRS Codes or EPSG geographic 3D CRS codes"); + Assert.assertTrue( + record.get("COORD_REF_SYS_KIND").equals("vertical") + || record.get("COORD_REF_SYS_KIND").equals("geographic 3D"), + "VerticalGeoKey values in the range 1024-32766 SHALL be either EPSG Vertical CRS Codes or EPSG geographic 3D CRS codes"); + } + else { // VerticalGeoKey values in the range 1-1023 SHALL be reserved - Assert.assertFalse(value >= 1 && value <= 1023, "VerticalGeoKey values in the range 1-1023 SHALL be reserved"); - + Assert.assertFalse(value >= 1 && value <= 1023, + "VerticalGeoKey values in the range 1-1023 SHALL be reserved"); + // VerticalGeoKey values in the range 32768-65535 SHALL be private // value out of bounds Assert.assertFalse(value > 65535 || value < 0, "VerticalGeoKey value out of bounds"); } } - - // 4098 VerticalDatumGeoKey - - @Test(description = "Short Params VerticalDatumGeoKey (2050) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + + // 4098 VerticalDatumGeoKey + + /** + *

    + * verifyVerticalDatumGeoKey. + *

    + * @throws java.io.IOException if any. + */ + @Test(description = "Short Params VerticalDatumGeoKey (2050) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyVerticalDatumGeoKey() throws IOException { // the VerticalDatumGeoKey SHALL have ID = 4098 int index = getKeyIndex(VERTICALDATUMGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the VerticalDatumGeoKey SHALL have type = SHORT + + // the VerticalDatumGeoKey SHALL have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the VerticalDatumGeoKey SHALL have type = SHORT"); - - if(value == 32767) { - // If the VerticalDatumGeoKey value is 32767 (User-Defined) then the VerticalCitationGeoKey SHALL be populated. - Assert.assertTrue(keyExists(VERTICALCITATIONGEOKEY), "if the VerticalDatumGeoKey value is 32767 (User-Defined) then the VerticalCitationGeoKey SHALL be populated"); - } else if(value >= 1024 && value <= 32766) { - // VerticalDatumGeoKey values in the range 1024-32766 SHALL be EPSG vertical datum codes + + if (value == 32767) { + // If the VerticalDatumGeoKey value is 32767 (User-Defined) then the + // VerticalCitationGeoKey SHALL be populated. + Assert.assertTrue(keyExists(VERTICALCITATIONGEOKEY), + "if the VerticalDatumGeoKey value is 32767 (User-Defined) then the VerticalCitationGeoKey SHALL be populated"); + } + else if (value >= 1024 && value <= 32766) { + // VerticalDatumGeoKey values in the range 1024-32766 SHALL be EPSG vertical + // datum codes CSVRecord record = EPSGDataSet.getRecord(EPSGDataSet.DATUM, "DATUM_CODE", Integer.toString(value)); - Assert.assertTrue(record != null, "VerticalDatumGeoKey values in the range 1024-32766 SHALL be EPSG vertical datum codes"); + Assert.assertTrue(record != null, + "VerticalDatumGeoKey values in the range 1024-32766 SHALL be EPSG vertical datum codes"); // Assert.assertTrue(minorRevision == 1); // not necessary - Assert.assertTrue(record.get("DEPRECATED").equals("0"), "VerticalDatumGeoKey values in the range 1024-32766 SHALL be EPSG vertical datum codes"); - Assert.assertTrue(record.get("DATUM_TYPE").equals("vertical"), "VerticalDatumGeoKey values in the range 1024-32766 SHALL be EPSG vertical datum codes"); - } else { + Assert.assertTrue(record.get("DEPRECATED").equals("0"), + "VerticalDatumGeoKey values in the range 1024-32766 SHALL be EPSG vertical datum codes"); + Assert.assertTrue(record.get("DATUM_TYPE").equals("vertical"), + "VerticalDatumGeoKey values in the range 1024-32766 SHALL be EPSG vertical datum codes"); + } + else { // VerticalDatumGeoKey values in the range 1-1023 SHALL be reserved - Assert.assertFalse(value >= 1 && value <= 1023, "VerticalDatumGeoKey values in the range 1-1023 SHALL be reserved"); - + Assert.assertFalse(value >= 1 && value <= 1023, + "VerticalDatumGeoKey values in the range 1-1023 SHALL be reserved"); + // VerticalDatumGeoKey values in the range 32768-65535 SHALL be private // value out of bounds Assert.assertFalse(value > 65535 || value < 0, "VerticalDatumGeoKey value out of bounds"); } } - - // 4099 UnitsGeoKey (Vertical Units) VerticalUnitsGeoKey - @Test(description = "Short Params VerticalUnitsGeoKey (4099) Test", dependsOnGroups ={"verifyGeoKeyDirectory"}) + // 4099 UnitsGeoKey (Vertical Units) VerticalUnitsGeoKey + + /** + *

    + * verifyVerticalUnitsGeoKey. + *

    + * @throws java.io.IOException if any. + */ + @Test(description = "Short Params VerticalUnitsGeoKey (4099) Test", dependsOnGroups = { "verifyGeoKeyDirectory" }) public void verifyVerticalUnitsGeoKey() throws IOException { // the VerticalUnitsGeoKey SHALL have ID = 4099 int index = getKeyIndex(VERTICALUNITSGEOKEY); // not required - if(index == -1) { + if (index == -1) { return; } - + // process the second Short integer in the Key Entry Set int type = processSecondShort(index); int geoKey = processFirstShort(index); int keyLength = processThirdShort(index); int value = processFourthShortForShort(index, keyLength); - - // the GeogAngularUnitsGeoKey, the GeogAzimuthUnitsGeoKey, the GeogLinearUnitsGeoKey, the ProjLinearUnitsGeoKey and the VerticalUnitsGeoKey SHALL each have type = SHORT + + // the GeogAngularUnitsGeoKey, the GeogAzimuthUnitsGeoKey, the + // GeogLinearUnitsGeoKey, the ProjLinearUnitsGeoKey and the VerticalUnitsGeoKey + // SHALL each have type = SHORT Assert.assertTrue(type == 0 || type == GEOKEYDIRECTORYTAG, "the VerticalUnitsGeoKey SHALL have type = SHORT"); - + // a VerticalUnitsGeoKey value of 32767 (user defined) SHALL not be used Assert.assertFalse(value == 32767, "a VerticalUnitsGeoKey value of 32767 (user defined) SHALL not be used"); - - if(value >= 1024 && value <= 32766) { - // GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length + + if (value >= 1024 && value <= 32766) { + // GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values + // in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type + // = length CSVRecord record = EPSGDataSet.getRecord(EPSGDataSet.UOM, "UOM_CODE", Integer.toString(value)); - Assert.assertTrue(record != null, "VerticalUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); + Assert.assertTrue(record != null, + "VerticalUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); // Assert.assertTrue(minorRevision == 1); // not necessary - Assert.assertTrue(record.get("DEPRECATED").equals("0"), "VerticalUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); - Assert.assertTrue(record.get("UNIT_OF_MEAS_TYPE").equals("length"), "VerticalUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); - } - - // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 1-1023 SHALL be reserved - Assert.assertFalse(value >= 1 && value <= 1023, "VerticalUnitsGeoKey values in the range 1-1023 SHALL be reserved"); - - // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 32768-65535 SHALL be private + Assert.assertTrue(record.get("DEPRECATED").equals("0"), + "VerticalUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); + Assert.assertTrue(record.get("UNIT_OF_MEAS_TYPE").equals("length"), + "VerticalUnitsGeoKey values in the range 1024-32766 SHALL be EPSG Unit Of Measure (UOM) codes with type = length"); + } + + // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, + // ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 1-1023 SHALL + // be reserved + Assert.assertFalse(value >= 1 && value <= 1023, + "VerticalUnitsGeoKey values in the range 1-1023 SHALL be reserved"); + + // GeogAngularUnitsGeoKey, GeogAzimuthUnitsGeoKey, GeogLinearUnitsGeoKey, + // ProjLinearUnitsGeoKey and VerticalUnitsGeoKey values in the range 32768-65535 + // SHALL be private // value out of bounds Assert.assertFalse(value > 65535 || value < 0, "VerticalUnitsGeoKey value out of bounds"); - + } + } diff --git a/src/main/java/org/opengis/cite/geotiff11/tiffTests/TiffCoreTests.java b/src/main/java/org/opengis/cite/geotiff11/tiffTests/TiffCoreTests.java index 0ceec3b..570e85a 100644 --- a/src/main/java/org/opengis/cite/geotiff11/tiffTests/TiffCoreTests.java +++ b/src/main/java/org/opengis/cite/geotiff11/tiffTests/TiffCoreTests.java @@ -6,8 +6,6 @@ import java.util.Scanner; import java.util.logging.Level; -import org.apache.commons.io.FilenameUtils; -import org.opengis.cite.geotiff11.SuiteAttribute; import org.opengis.cite.geotiff11.TestRunArg; import org.opengis.cite.geotiff11.util.TestSuiteLogger; import org.testng.Assert; @@ -21,105 +19,135 @@ import edu.harvard.hul.ois.jhove.Module; import edu.harvard.hul.ois.jhove.OutputHandler; import edu.harvard.hul.ois.jhove.handler.XmlHandler; -import edu.harvard.hul.ois.jhove.module.TiffModule; -//import edu.harvard.hul.ois.jhove.*; // https://github.com/opengeospatial/geotiff/blob/5d6ab0ba54f1ed0174901dd84240817dc9dbe011/GeoTIFF_Standard/standard/abstract_tests/TIFF_Tests/TEST_TIFF_Core.adoc +/** + *

    + * TiffCoreTests class. + *

    + * + */ public class TiffCoreTests extends CommonTiffMeta { private static final String CWD = System.getProperty("user.dir"); + private static final String TCR = "tiff-compliance-report.txt"; + private static final String FULL_TCR = Paths.get(CWD, TCR).toString(); + private String tiffPath; - + private static final String VALID = ""; - + + /** + *

    + * Setter for the field tiffPath. + *

    + * @param testContext a {@link org.testng.ITestContext} object + */ @BeforeClass public void setTiffPath(ITestContext testContext) { ISuite suite = testContext.getSuite(); Map params = suite.getXmlSuite().getParameters(); - TestSuiteLogger.log(Level.CONFIG, "Suite parameters\n" + params.toString()); - tiffPath = params.get(TestRunArg.IUT.toString()); + TestSuiteLogger.log(Level.CONFIG, "Suite parameters\n" + params.toString()); + tiffPath = params.get(TestRunArg.IUT.toString()); } - + /* * TIFF Core Tests - * + * * Test id: http://www.opengis.net/spec/GeoTIFF/1.1/conf/Core - * + * * Requirements: - * - * http://www.opengis.net/spec/GeoTIFF/1.1/req/TIFF - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ByteOrder - * http://www.opengis.net/spec/GeoTIFF/1.1/req/DataTypes - * + * + * http://www.opengis.net/spec/GeoTIFF/1.1/req/TIFF + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ByteOrder + * http://www.opengis.net/spec/GeoTIFF/1.1/req/DataTypes + * * Purpose: Verify that the GeoTIFF file conforms to the TIFF specification. - * Pre-conditions: None - * Test Variables: None + * Pre-conditions: None Test Variables: None */ - - @Test(description = "TIFF Core Endianness Test") // may be covered by verifyTiffVersionSixCompliance but can't hurt - public void verifyTiffEndianness() { + + /** + *

    + * verifyTiffEndianness. + *

    + */ + @Test(description = "TIFF Core Endianness Test") // may be covered by + // verifyTiffVersionSixCompliance + // but can't hurt + public void verifyTiffEndianness() { // verify endianness is 0x4949 or 0X4D4D - Assert.assertTrue(tiffDump.getMagic().equals("0x4949") || tiffDump.getMagic().equals("0x4d4d")); + Assert.assertTrue(tiffDump.getMagic().equals("0x4949") || tiffDump.getMagic().equals("0x4d4d")); } - - @Test(description = "TIFF Core Version Test") // may be covered by verifyTiffVersionSixCompliance but can't hurt - public void verifyTiffVersion() { + + /** + *

    + * verifyTiffVersion. + *

    + */ + @Test(description = "TIFF Core Version Test") // may be covered by + // verifyTiffVersionSixCompliance but + // can't hurt + public void verifyTiffVersion() { // verify version is 42 Assert.assertTrue(tiffDump.getVersion().contains("2a")); } - + // a GeoTIFF file SHALL be compliant with the TIFF 6.0 specification + /** + *

    + * verifyTiffVersionSixCompliance. + *

    + * @throws java.lang.Exception if any. + */ @Test(description = "TIFF Core 6.0 Compliance Test") public void verifyTiffVersionSixCompliance() throws Exception { - + // https://www.javatips.net/api/jhove-master/jhove-apps/src/main/java/Jhove.java App app = App.newAppWithName("Tiff Test"); - + JhoveBase je = new JhoveBase(); - je.setLogLevel ("SEVERE"); - je.setEncoding ("utf-8"); - //je.setTempDirectory (Paths.get(tmpFile).getParent().toString()); - je.setBufferSize (4096); - je.setChecksumFlag (false); - je.setShowRawFlag (false); - je.setSignatureFlag (false); - + je.setLogLevel("SEVERE"); + je.setEncoding("utf-8"); + // je.setTempDirectory (Paths.get(tmpFile).getParent().toString()); + je.setBufferSize(4096); + je.setChecksumFlag(false); + je.setShowRawFlag(false); + je.setSignatureFlag(false); + Module tiffModule = je.getModule("TIFF-hul"); -// TiffModule tiffModule = new TiffModule(); + // TiffModule tiffModule = new TiffModule(); OutputHandler handler = new XmlHandler(); - + boolean isValid = false; - + File tempFile = File.createTempFile("tiff-compliance-report", ".txt"); - + tempFile.deleteOnExit(); try { - je.dispatch(app, tiffModule, null, handler, tempFile.getAbsolutePath(), new String[] {tiffPath}); + je.dispatch(app, tiffModule, null, handler, tempFile.getAbsolutePath(), new String[] { tiffPath }); } - catch (NullPointerException e) - { + catch (NullPointerException e) { Assert.fail("JHove failed to generate a compliance report"); } - - Scanner scanner = new Scanner(tempFile); - - while (scanner.hasNextLine()) { - String line = scanner.nextLine(); - if(line.contains(VALID)) { - isValid = true; - break; - } - } - - scanner.close(); -// file.deleteOnExit(); - - - - Assert.assertTrue(isValid, "a GeoTIFF file SHALL be compliant with the TIFF 6.0 specification"); + + Scanner scanner = new Scanner(tempFile); + + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + if (line.contains(VALID)) { + isValid = true; + break; + } + } + + scanner.close(); + // file.deleteOnExit(); + + Assert.assertTrue(isValid, "a GeoTIFF file SHALL be compliant with the TIFF 6.0 specification"); } -} \ No newline at end of file + +} diff --git a/src/main/java/org/opengis/cite/geotiff11/tiffTests/TiffTagsTests.java b/src/main/java/org/opengis/cite/geotiff11/tiffTests/TiffTagsTests.java index d3a9481..cf7a52b 100644 --- a/src/main/java/org/opengis/cite/geotiff11/tiffTests/TiffTagsTests.java +++ b/src/main/java/org/opengis/cite/geotiff11/tiffTests/TiffTagsTests.java @@ -1,148 +1,189 @@ package org.opengis.cite.geotiff11.tiffTests; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOASCIIPARAMSTAG; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEODOUBLEPARAMSTAG; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GEOKEYDIRECTORYTAG; +import static org.opengis.cite.geotiff11.util.GeoKeyID.GTMODELTYPEGEOKEY; +import static org.opengis.cite.geotiff11.util.GeoKeyID.MODELPIXELSCALETAG; +import static org.opengis.cite.geotiff11.util.GeoKeyID.MODELTIEPOINTTAG; +import static org.opengis.cite.geotiff11.util.GeoKeyID.MODELTRANSFORMATIONTAG; + import org.opengis.cite.geotiff11.util.TiffDump; import org.testng.Assert; import org.testng.annotations.Test; -import static org.opengis.cite.geotiff11.util.GeoKeyID.*; - -import java.util.List; - // https://github.com/opengeospatial/geotiff/blob/5d6ab0ba54f1ed0174901dd84240817dc9dbe011/GeoTIFF_Standard/standard/abstract_tests/TIFF_Tests/TEST_TIFF_Tags.adoc +/** + *

    + * TiffTagsTests class. + *

    + * + */ public class TiffTagsTests extends CommonTiffMeta { - + /* - * TIFF Tags Test - * Test id: http://www.opengis.net/spec/GeoTIFF/1.1/conf/TIFF.Tags - * Requirements: - * http://www.opengis.net/spec/GeoTIFF/1.1/req/TIFF - * http://www.opengis.net/spec/GeoTIFF/1.1/req/DataGeoTags - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ByteOrder - * http://www.opengis.net/spec/GeoTIFF/1.1/req/TagSort - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.ID - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.type - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.count - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoDoubleParamsTag.ID - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoDoubleParamsTag.count - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoAsciiParamsTag.ID - * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoAsciiParamsTag.type - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ModelTransformationTag.ID - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ModelTransformationTag.type - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ModelPixelScaleTag.ID - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ModelPixelScaleTag.type - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ModelTiepointTag.ID - * http://www.opengis.net/spec/GeoTIFF/1.1/req/ModelTiepointTag.type - * Purpose: Verify the TIFF header and prepare for processing the GeoTIFF tags. - * Pre-conditions: None - * Test Variables: - * Variable Scope Description - * IFD_Offset Local Location within the TIFF file of an IFD - * GeoKeyDirectory Global Location of the GeoTIFF GeoKey directory - * ASCIIValues Global Location of the ASCII values for GeoTIFF ASCII GeoKeys - * DoubleValues Global Location of the Double values for GeoTIFF Double GeoKeys - * TransformTag Local Location of the Model Transform Tag - * PixelScaleTag Local Location of the ModelPixelScale Tag - * TiepointTag Local Location of the ModelTiepoint Tag - * TagLength Parameter Length of the value of a TIFF Tag - * TagValue Parameter Location of the value of a TIFF tag in the GeoTIFF file - */ - - // TODO: This duplicates a lot of test in order to more closely resemble the ATS. In the future, + * TIFF Tags Test Test id: http://www.opengis.net/spec/GeoTIFF/1.1/conf/TIFF.Tags + * Requirements: http://www.opengis.net/spec/GeoTIFF/1.1/req/TIFF + * http://www.opengis.net/spec/GeoTIFF/1.1/req/DataGeoTags + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ByteOrder + * http://www.opengis.net/spec/GeoTIFF/1.1/req/TagSort + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.ID + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.type + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoKeyDirectoryTag.count + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoDoubleParamsTag.ID + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoDoubleParamsTag.count + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoAsciiParamsTag.ID + * http://www.opengis.net/spec/GeoTIFF/1.1/req/GeoAsciiParamsTag.type + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ModelTransformationTag.ID + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ModelTransformationTag.type + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ModelPixelScaleTag.ID + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ModelPixelScaleTag.type + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ModelTiepointTag.ID + * http://www.opengis.net/spec/GeoTIFF/1.1/req/ModelTiepointTag.type Purpose: Verify + * the TIFF header and prepare for processing the GeoTIFF tags. Pre-conditions: None + * Test Variables: Variable Scope Description IFD_Offset Local Location within the + * TIFF file of an IFD GeoKeyDirectory Global Location of the GeoTIFF GeoKey directory + * ASCIIValues Global Location of the ASCII values for GeoTIFF ASCII GeoKeys + * DoubleValues Global Location of the Double values for GeoTIFF Double GeoKeys + * TransformTag Local Location of the Model Transform Tag PixelScaleTag Local Location + * of the ModelPixelScale Tag TiepointTag Local Location of the ModelTiepoint Tag + * TagLength Parameter Length of the value of a TIFF Tag TagValue Parameter Location + * of the value of a TIFF tag in the GeoTIFF file + */ + + // TODO: This duplicates a lot of test in order to more closely resemble the ATS. In + // the future, // this may be replaced entirely? - + + /** + *

    + * verifyTiffTags. + *

    + * @throws java.lang.Exception if any. + */ @Test(description = "TIFF Tags Test") - public void verifyTiffTags() throws Exception { - - for(TiffDump.Directory directory : tiffDump.getDirectories()) { - - // The TIFF tags in a GeoTIFF file SHALL be written out to the file with the tag-IDs sorted in ascending order + public void verifyTiffTags() throws Exception { + + for (TiffDump.Directory directory : tiffDump.getDirectories()) { + + // The TIFF tags in a GeoTIFF file SHALL be written out to the file with the + // tag-IDs sorted in ascending order int previousValue = Integer.MIN_VALUE; for (TiffDump.Tag tag : directory.getTags()) { - Assert.assertTrue(tag.getNameValue() > previousValue, "the TIFF tags in a GeoTIFF file SHALL be written out to the file with the tag-IDs sorted in ascending order"); + Assert.assertTrue(tag.getNameValue() > previousValue, + "the TIFF tags in a GeoTIFF file SHALL be written out to the file with the tag-IDs sorted in ascending order"); previousValue = tag.getNameValue(); - } - + } + // verify specific tag values // WHILE IFD_Offset is not 0, process this IFD - if(directory.getOffset() != 0) { - + if (directory.getOffset() != 0) { + TiffDump.Tag geoKeyDirectory = directory.getTag(GEOKEYDIRECTORYTAG); - if(geoKeyDirectory != null) { + if (geoKeyDirectory != null) { // validate that Bytes 2-3 = 3 (Short Integer) - Assert.assertTrue(geoKeyDirectory.getTypeValue() == 3, "the GeoKeyDirectoryTag SHALL have type = SHORT"); - // validate that Bytes 4-7 represent an Integer value greater than or equal to 4 - Assert.assertTrue(geoKeyDirectory.getCount() >= 4, "the GeoKeyDirectoryTag SHALL have at least 4 values"); - - if(geoKeyDirectory.getValues() != null) { - // validate that there is a GTModelType GeoKey in the GeoKey Directory - Assert.assertTrue(geoKeyDirectory.containsValue(GTMODELTYPEGEOKEY), "validate that there is a GTModelType GeoKey in the GeoKey Directory"); - - // execute test http://www.opengis.net/spec/GeoTIFF/1.1/conf/GeoKeyDirectory - - } else { + Assert.assertTrue(geoKeyDirectory.getTypeValue() == 3, + "the GeoKeyDirectoryTag SHALL have type = SHORT"); + // validate that Bytes 4-7 represent an Integer value greater than or + // equal to 4 + Assert.assertTrue(geoKeyDirectory.getCount() >= 4, + "the GeoKeyDirectoryTag SHALL have at least 4 values"); + + if (geoKeyDirectory.getValues() != null) { + // validate that there is a GTModelType GeoKey in the GeoKey + // Directory + Assert.assertTrue(geoKeyDirectory.containsValue(GTMODELTYPEGEOKEY), + "validate that there is a GTModelType GeoKey in the GeoKey Directory"); + + // execute test + // http://www.opengis.net/spec/GeoTIFF/1.1/conf/GeoKeyDirectory + + } + else { throw new Exception("GeoKeyDirectory does not exist."); } - + // the GeoDoubleParamsTag SHALL have ID = 34736 TiffDump.Tag doubles = directory.getTag(GEODOUBLEPARAMSTAG); - if(doubles != null) { - // the GeoDoubleParamsTag MAY hold any number of key parameters with type = double - Assert.assertTrue(doubles.getTypeValue() == 12, "the GeoDoubleParamsTag MAY hold any number of key parameters with type = double"); - //List doubleValues = doubles.getValues(); + if (doubles != null) { + // the GeoDoubleParamsTag MAY hold any number of key parameters + // with type = double + Assert.assertTrue(doubles.getTypeValue() == 12, + "the GeoDoubleParamsTag MAY hold any number of key parameters with type = double"); + // List doubleValues = doubles.getValues(); } - + // the GeoAsciiParamsTag SHALL have ID = 34737 TiffDump.Tag asciis = directory.getTag(GEOASCIIPARAMSTAG); - if(asciis != null) { + if (asciis != null) { Assert.assertTrue(asciis.getTypeValue() == 2, "the GeoAsciiParamsTag SHALL have type = ASCII"); - //asciiValues = asciis.getValues(); + // asciiValues = asciis.getValues(); } - + // the ModelTiepointTag SHALL have ID = 33922 - TiffDump.Tag tiepointTag = directory.getTag(MODELTIEPOINTTAG); - if(tiepointTag != null) { - Assert.assertTrue(tiepointTag.getTypeValue() == 12, "the ModelTiepointTag SHALL have type = DOUBLE"); - - // execute test http://www.opengis.net/spec/GeoTIFF/1.1/conf/Raster2Model_CoordinateTransformation_GeoKey/ModelTiepointTag - - // the ModelTiepointTag SHALL have 6 values for each of the K tiepoints - Assert.assertTrue(tiepointTag.getCount() == 6, "the ModelTiepointTag SHALL have 6 values for each of the K tiepoints"); - } - + TiffDump.Tag tiepointTag = directory.getTag(MODELTIEPOINTTAG); + if (tiepointTag != null) { + Assert.assertTrue(tiepointTag.getTypeValue() == 12, + "the ModelTiepointTag SHALL have type = DOUBLE"); + + // execute test + // http://www.opengis.net/spec/GeoTIFF/1.1/conf/Raster2Model_CoordinateTransformation_GeoKey/ModelTiepointTag + + // the ModelTiepointTag SHALL have 6 values for each of the K + // tiepoints + Assert.assertTrue(tiepointTag.getCount() == 6, + "the ModelTiepointTag SHALL have 6 values for each of the K tiepoints"); + } + // the ModelPixelScaleTag SHALL have ID = 33550 TiffDump.Tag pixelScaleTag = directory.getTag(MODELPIXELSCALETAG); - if(pixelScaleTag != null) { - Assert.assertTrue(pixelScaleTag.getTypeValue() == 12, "the ModelPixelScaleTag SHALL have type = DOUBLE"); - + if (pixelScaleTag != null) { + Assert.assertTrue(pixelScaleTag.getTypeValue() == 12, + "the ModelPixelScaleTag SHALL have type = DOUBLE"); + // validate that this IFD contains a ModelTiepointTag - Assert.assertTrue(tiepointTag != null, "validate that this IFD (containing ModelPixelScaleTag) contains a ModelTiepointTag"); - - // execute test http://www.opengis.net/spec/GeoTIFF/1.1/conf/Raster2Model_CoordinateTransformation_GeoKey/ModelPixelScaleTag - - // the ModelPixelScaleTag SHALL have 3 values representing the scale factor in the X, Y, and Z directions - Assert.assertTrue(pixelScaleTag.getCount() == 3, "the ModelPixelScaleTag SHALL have 3 values representing the scale factor in the X, Y, and Z directions"); + Assert.assertTrue(tiepointTag != null, + "validate that this IFD (containing ModelPixelScaleTag) contains a ModelTiepointTag"); + + // execute test + // http://www.opengis.net/spec/GeoTIFF/1.1/conf/Raster2Model_CoordinateTransformation_GeoKey/ModelPixelScaleTag + + // the ModelPixelScaleTag SHALL have 3 values representing the + // scale factor in the X, Y, and Z directions + Assert.assertTrue(pixelScaleTag.getCount() == 3, + "the ModelPixelScaleTag SHALL have 3 values representing the scale factor in the X, Y, and Z directions"); } - + // the ModelTransformationTag SHALL have ID = 34264 TiffDump.Tag transformTag = directory.getTag(MODELTRANSFORMATIONTAG); - if(transformTag != null) { - Assert.assertTrue(transformTag.getTypeValue() == 12, "the ModelTransformationTag SHALL have type = DOUBLE"); - + if (transformTag != null) { + Assert.assertTrue(transformTag.getTypeValue() == 12, + "the ModelTransformationTag SHALL have type = DOUBLE"); + // validate that this IFD does not contain a ModelPixelScaleTag - Assert.assertTrue(pixelScaleTag == null, "validate that this IFD (containing ModelTransformationTag) does not contain a ModelPixelScaleTag"); - - // execute test http://www.opengis.net/spec/GeoTIFF/1.1/conf/Raster2Model_CoordinateTransformation_GeoKey/ModelTransformationTag - - // The ModelTransformationTag SHALL have 16 values representing the terms of the 4 by 4 transformation matrix. The terms SHALL be in row-major order - Assert.assertTrue(transformTag.getValues().size() == 16, "the ModelTransformationTag SHALL have 16 values representing the terms of the 4 by 4 transformation matrix"); - // TODO: The terms SHALL be in row-major order. Is this possible to ensure? + Assert.assertTrue(pixelScaleTag == null, + "validate that this IFD (containing ModelTransformationTag) does not contain a ModelPixelScaleTag"); + + // execute test + // http://www.opengis.net/spec/GeoTIFF/1.1/conf/Raster2Model_CoordinateTransformation_GeoKey/ModelTransformationTag + + // The ModelTransformationTag SHALL have 16 values representing + // the terms of the 4 by 4 transformation matrix. The terms SHALL + // be in row-major order + Assert.assertTrue(transformTag.getValues().size() == 16, + "the ModelTransformationTag SHALL have 16 values representing the terms of the 4 by 4 transformation matrix"); + // TODO: The terms SHALL be in row-major order. Is this possible + // to ensure? } - // validate that this IFD contains either a ModelTransformationTag or a ModelTiepointTag + // validate that this IFD contains either a ModelTransformationTag or + // a ModelTiepointTag // this could probably be it's own test? - Assert.assertTrue(transformTag != null || tiepointTag != null, "validate that this IFD contains either a ModelTransformationTag or a ModelTiepointTag"); + Assert.assertTrue(transformTag != null || tiepointTag != null, + "validate that this IFD contains either a ModelTransformationTag or a ModelTiepointTag"); } - } + } } } -} \ No newline at end of file + +} diff --git a/src/main/java/org/opengis/cite/geotiff11/tiffTests/package-info.java b/src/main/java/org/opengis/cite/geotiff11/tiffTests/package-info.java index 5364ff6..b712078 100644 --- a/src/main/java/org/opengis/cite/geotiff11/tiffTests/package-info.java +++ b/src/main/java/org/opengis/cite/geotiff11/tiffTests/package-info.java @@ -1,12 +1,11 @@ /** - * Conformance Tiff Tests includes all tiff tests. The following capabilities - * must be supported: + * Conformance Tiff Tests includes all tiff tests. The following capabilities must be + * supported: *
      *
    • TODO
    • *
    * - * @see HTML5 + * @see HTML5 * - Conformance classes */ package org.opengis.cite.geotiff11.tiffTests; diff --git a/src/main/java/org/opengis/cite/geotiff11/util/ClientUtils.java b/src/main/java/org/opengis/cite/geotiff11/util/ClientUtils.java index 98e1a5e..3130d4d 100644 --- a/src/main/java/org/opengis/cite/geotiff11/util/ClientUtils.java +++ b/src/main/java/org/opengis/cite/geotiff11/util/ClientUtils.java @@ -1,173 +1,148 @@ package org.opengis.cite.geotiff11.util; import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.InetSocketAddress; -import java.net.Proxy; -import java.net.SocketAddress; -import java.net.URL; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.client.filter.LoggingFilter; -import com.sun.jersey.client.urlconnection.HttpURLConnectionFactory; -import com.sun.jersey.client.urlconnection.URLConnectionClientHandler; -import java.net.URI; -import java.util.Map; +import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; -import javax.ws.rs.HttpMethod; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.UriBuilder; + import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.client.JerseyClientBuilder; +import org.glassfish.jersey.logging.LoggingFeature; import org.opengis.cite.geotiff11.ReusableEntityFilter; import org.w3c.dom.Document; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.core.Response; + /** - * Provides various utility methods for creating and configuring HTTP client - * components. + * 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 DefaultClientConfig(); - config.getProperties().put( - ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); - config.getProperties().put( - ClientConfig.PROPERTY_CONNECT_TIMEOUT, 10000); - Client client = Client.create(config); - client.addFilter(new ReusableEntityFilter()); - client.addFilter(new LoggingFilter()); - return client; - } + /** + * 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(); + // TODO: currently ReusableEntityFilter doesn't do anything + // config.register(ReusableEntityFilter.class); + config.property(ClientProperties.FOLLOW_REDIRECTS, true); + config.property(ClientProperties.CONNECT_TIMEOUT, 10000); + config.register(new LoggingFeature()); // TODO: verify if this works + Client client = JerseyClientBuilder.newClient(config); + client.register(new ReusableEntityFilter()); + return client; + } - /** - * Constructs a client component that uses a specified web proxy. Proxy - * authentication is not supported. Configuring the client to use an - * intercepting proxy can be useful when debugging a test. - * - * @param proxyHost The host name or IP address of the proxy server. - * @param proxyPort The port number of the proxy listener. - * - * @return A Client component that submits requests through a web proxy. - */ - public static Client buildClientWithProxy(final String proxyHost, - final int proxyPort) { - ClientConfig config = new DefaultClientConfig(); - config.getProperties().put( - ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); - Client client = new Client(new URLConnectionClientHandler( - new HttpURLConnectionFactory() { - SocketAddress addr = new InetSocketAddress(proxyHost, proxyPort); - Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); + /** + * 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. + */ + /* + * seems unused public static Client buildClientWithProxy(final String proxyHost, + * final int proxyPort) { ClientConfig config = new DefaultClientConfig(); + * config.getProperties().put( ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); Client + * client = new Client(new URLConnectionClientHandler( new HttpURLConnectionFactory() + * { SocketAddress addr = new InetSocketAddress(proxyHost, proxyPort); Proxy proxy = + * new Proxy(Proxy.Type.HTTP, addr); + * + * @Override public HttpURLConnection getHttpURLConnection(URL url) throws IOException + * { return (HttpURLConnection) url.openConnection(proxy); } }), config); + * client.addFilter(new LoggingFilter()); return client; } + */ - @Override - public HttpURLConnection getHttpURLConnection(URL url) throws IOException { - return (HttpURLConnection) url.openConnection(proxy); - } - }), config); - client.addFilter(new LoggingFilter()); - 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. + */ + /* + * seems unused public static ClientRequestContext 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(); ClientRequest.Builder + * reqBuilder = ClientRequest.create(); if (null == mediaTypes || mediaTypes.length == + * 0) { reqBuilder = reqBuilder.accept(MediaType.APPLICATION_XML_TYPE); } else { + * reqBuilder = reqBuilder.accept(mediaTypes); } ClientRequest req = + * reqBuilder.build(uri, HttpMethod.GET); return req; } + */ - /** - * 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(); - ClientRequest.Builder reqBuilder = ClientRequest.create(); - if (null == mediaTypes || mediaTypes.length == 0) { - reqBuilder = reqBuilder.accept(MediaType.APPLICATION_XML_TYPE); - } else { - reqBuilder = reqBuilder.accept(mediaTypes); - } - ClientRequest req = reqBuilder.build(uri, HttpMethod.GET); - return req; - } + /** + * 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. + */ + /* + * seems unused public static MediaType removeParameters(MediaType mediaType) { return + * new MediaType(mediaType.getType(), mediaType.getSubtype()); } + */ - /** - * Creates a copy of the given MediaType object but without any parameters. - * - * @param mediaType A MediaType descriptor. - * @return A new (immutable) MediaType object having the same type and - * subtype. - */ - public static MediaType removeParameters(MediaType mediaType) { - return new MediaType(mediaType.getType(), mediaType.getSubtype()); - } + /** + * Obtains the (XML) response entity as a JAXP Source object and resets the entity + * input stream for subsequent reads. + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + * @param response A representation of an HTTP response message. + * @param targetURI The target URI from which the entity was retrieved (may be null). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + */ + public static Source getResponseEntityAsSource(Response response, String targetURI) { + Source source = response.readEntity(DOMSource.class); + if (null != targetURI && !targetURI.isEmpty()) { + source.setSystemId(targetURI); + } + if (response.readEntity(InputStream.class).markSupported()) { + try { + // NOTE: entity was buffered by client filter + response.readEntity(InputStream.class).reset(); + } + catch (IOException ex) { + Logger.getLogger(ClientUtils.class.getName()) + .log(Level.WARNING, "Failed to reset response entity.", ex); + } + } + return source; + } - /** - * Obtains the (XML) response entity as a 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.getEntity(DOMSource.class); - if (null != targetURI && !targetURI.isEmpty()) { - source.setSystemId(targetURI); - } - if (response.getEntityInputStream().markSupported()) { - try { - // NOTE: entity was buffered by client filter - response.getEntityInputStream().reset(); - } catch (IOException ex) { - Logger.getLogger(ClientUtils.class.getName()).log(Level.WARNING, - "Failed to reset response entity.", ex); - } - } - return source; - } + /** + * Obtains the (XML) response entity as a DOM Document and resets the entity input + * stream for subsequent reads. + * @param response A representation of an HTTP response message. + * @param targetURI The target URI from which the entity was retrieved (may be null). + * @return A Document representing the entity; its base URI is set using the given + * targetURI value (this may be used to resolve any relative URIs found in the + * document). + */ + public static Document getResponseEntityAsDocument(Response response, String targetURI) { + DOMSource domSource = (DOMSource) getResponseEntityAsSource(response, targetURI); + Document entityDoc = (Document) domSource.getNode(); + entityDoc.setDocumentURI(domSource.getSystemId()); + return entityDoc; + } - /** - * Obtains the (XML) response entity as a DOM Document and resets the entity - * input stream for subsequent reads. - * - * @param response A representation of an HTTP response message. - * @param targetURI The target URI from which the entity was retrieved (may - * be null). - * @return A Document representing the entity; its base URI is set using the - * given targetURI value (this may be used to resolve any relative URIs - * found in the document). - */ - public static Document getResponseEntityAsDocument(ClientResponse response, - String targetURI) { - DOMSource domSource = (DOMSource) getResponseEntityAsSource(response, - targetURI); - Document entityDoc = (Document) domSource.getNode(); - entityDoc.setDocumentURI(domSource.getSystemId()); - return entityDoc; - } } diff --git a/src/main/java/org/opengis/cite/geotiff11/util/DirectoryUtil.java b/src/main/java/org/opengis/cite/geotiff11/util/DirectoryUtil.java index 200f1d8..8a50993 100644 --- a/src/main/java/org/opengis/cite/geotiff11/util/DirectoryUtil.java +++ b/src/main/java/org/opengis/cite/geotiff11/util/DirectoryUtil.java @@ -2,26 +2,45 @@ import java.io.File; import java.net.URISyntaxException; -import java.nio.file.Path; import java.nio.file.Paths; +/** + *

    + * DirectoryUtil class. + *

    + * + */ public class DirectoryUtil { - - public static String getDirectory() - { + /** + *

    + * getDirectory. + *

    + * @return a {@link java.lang.String} object + */ + public static String getDirectory() { try { - return Paths.get(new File(DirectoryUtil.class.getProtectionDomain().getCodeSource().getLocation() - .toURI()).getPath(), "../..").toString(); - } catch (URISyntaxException e) { + return Paths + .get(new File(DirectoryUtil.class.getProtectionDomain().getCodeSource().getLocation().toURI()) + .getPath(), "../..") + .toString(); + } + catch (URISyntaxException e) { e.printStackTrace(); return System.getProperty("user.dir"); } } - - public static String getDirectory(String local) - { + + /** + *

    + * getDirectory. + *

    + * @param local a {@link java.lang.String} object + * @return a {@link java.lang.String} object + */ + public static String getDirectory(String local) { return Paths.get(getDirectory(), local).toString(); - + } + } diff --git a/src/main/java/org/opengis/cite/geotiff11/util/EPSGDataSet.java b/src/main/java/org/opengis/cite/geotiff11/util/EPSGDataSet.java index ff387bc..2ff484e 100644 --- a/src/main/java/org/opengis/cite/geotiff11/util/EPSGDataSet.java +++ b/src/main/java/org/opengis/cite/geotiff11/util/EPSGDataSet.java @@ -1,13 +1,8 @@ package org.opengis.cite.geotiff11.util; import java.io.BufferedReader; -import java.io.File; import java.io.IOException; import java.io.InputStreamReader; -import java.net.URISyntaxException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Paths; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; @@ -16,56 +11,126 @@ /* * For referencing the path of an EPSG data set. */ +/** + *

    + * EPSGDataSet class. + *

    + * + */ public final class EPSGDataSet { // UOM types + /** Constant METERS="9001" */ public static final String METERS = "9001"; + + /** Constant RADIANS="9101" */ public static final String RADIANS = "9101"; - + // path and extension - //public static final String DIRECTORY = System.getProperty("user.dir") + "/src/main/resources/epsg/"; -// private static final String DIRECTORY = DirectoryUtil.getDirectory("/src/main/resources/epsg/"); -// private static final String DIRECTORY = new File(EPSGDataSet.class.getResource("/epsg").getFile()).getAbsolutePath(); + // public static final String DIRECTORY = System.getProperty("user.dir") + + // "/src/main/resources/epsg/"; + // private static final String DIRECTORY = + // DirectoryUtil.getDirectory("/src/main/resources/epsg/"); + // private static final String DIRECTORY = new + // File(EPSGDataSet.class.getResource("/epsg").getFile()).getAbsolutePath(); private static final String EXTENSION = ".csv"; - + // table paths + /** Constant UOM="unit-of-measure" */ public static final String UOM = "unit-of-measure"; + + /** Constant CRS="coordinate-reference-system" */ public static final String CRS = "coordinate-reference-system"; + + /** Constant DATUM="datum" */ public static final String DATUM = "datum"; + + /** Constant PRIMEMERIDIAN="prime-meridian" */ public static final String PRIMEMERIDIAN = "prime-meridian"; + + /** Constant ELLIPSOID="ellipsoid" */ public static final String ELLIPSOID = "ellipsoid"; + + /** Constant CO="coordinate-operation" */ public static final String CO = "coordinate-operation"; + + /** Constant COM="coordinate-operation-method" */ public static final String COM = "coordinate-operation-method"; + + /** Constant COP="coordinate-operation-parameter" */ public static final String COP = "coordinate-operation-parameter"; - - private static InputStreamReader getResourceISR(String name) - { + + private static InputStreamReader getResourceISR(String name) { return new InputStreamReader(EPSGDataSet.class.getResourceAsStream("/epsg/" + name + EXTENSION)); } - + + /** + *

    + * readTable. + *

    + * @param tableName a {@link java.lang.String} object + * @return a {@link java.io.BufferedReader} object + * @throws java.io.IOException if any. + */ protected static BufferedReader readTable(String tableName) throws IOException { return new BufferedReader(getResourceISR(tableName)); -// return Files.newBufferedReader(Paths.get(DIRECTORY, tableName + EXTENSION), Charset.forName("Cp1252")); + // return Files.newBufferedReader(Paths.get(DIRECTORY, tableName + EXTENSION), + // Charset.forName("Cp1252")); } - + + /** + *

    + * getRecord. + *

    + * @param tableName a {@link java.lang.String} object + * @param column a {@link java.lang.String} object + * @param value a {@link java.lang.String} object + * @return a {@link org.apache.commons.csv.CSVRecord} object + * @throws java.io.IOException if any. + */ public static CSVRecord getRecord(String tableName, String column, String value) throws IOException { - BufferedReader reader = readTable(tableName); - CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withTrim()); - for (CSVRecord csvRecord: csvParser) { - - if(csvRecord.get(column).equals(value)) { - csvParser.close(); - return csvRecord; - } - } - csvParser.close(); - return null; + BufferedReader reader = readTable(tableName); + CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withTrim()); + for (CSVRecord csvRecord : csvParser) { + + if (csvRecord.get(column).equals(value)) { + csvParser.close(); + return csvRecord; + } + } + csvParser.close(); + return null; } - - public static String getItem(String tableName, String column, String value, String returnColumn) throws IOException { - return getRecord(tableName, column, value).get(returnColumn); + + /** + *

    + * getItem. + *

    + * @param tableName a {@link java.lang.String} object + * @param column a {@link java.lang.String} object + * @param value a {@link java.lang.String} object + * @param returnColumn a {@link java.lang.String} object + * @return a {@link java.lang.String} object + * @throws java.io.IOException if any. + */ + public static String getItem(String tableName, String column, String value, String returnColumn) + throws IOException { + return getRecord(tableName, column, value).get(returnColumn); } + + /** + *

    + * getItem. + *

    + * @param tableName a {@link java.lang.String} object + * @param column a {@link java.lang.String} object + * @param value a int + * @param returnColumn a {@link java.lang.String} object + * @return a {@link java.lang.String} object + * @throws java.io.IOException if any. + */ public static String getItem(String tableName, String column, int value, String returnColumn) throws IOException { return getItem(tableName, column, Integer.toString(value), returnColumn); } + } diff --git a/src/main/java/org/opengis/cite/geotiff11/util/GeoKeyID.java b/src/main/java/org/opengis/cite/geotiff11/util/GeoKeyID.java index 62c7eb1..f1d5ddb 100644 --- a/src/main/java/org/opengis/cite/geotiff11/util/GeoKeyID.java +++ b/src/main/java/org/opengis/cite/geotiff11/util/GeoKeyID.java @@ -3,58 +3,165 @@ /* * For referencing the integer ID of a geokey. */ +/** + *

    + * GeoKeyID class. + *

    + * + */ public final class GeoKeyID { + /** Constant GTMODELTYPEGEOKEY=1024 */ public static final int GTMODELTYPEGEOKEY = 1024; + + /** Constant GTRASTERTYPEGEOKEY=1025 */ public static final int GTRASTERTYPEGEOKEY = 1025; + + /** Constant GTCITATIONGEOKEY=1026 */ public static final int GTCITATIONGEOKEY = 1026; + + /** Constant GEODETICCRSGEOKEY=2048 */ public static final int GEODETICCRSGEOKEY = 2048; + + /** Constant GEODETICCITATIONGEOKEY=2049 */ public static final int GEODETICCITATIONGEOKEY = 2049; + + /** Constant GEODETICDATUMGEOKEY=2050 */ public static final int GEODETICDATUMGEOKEY = 2050; + + /** Constant PRIMEMERIDIANGEOKEY=2051 */ public static final int PRIMEMERIDIANGEOKEY = 2051; + + /** Constant GEOGLINEARUNITSGEOKEY=2052 */ public static final int GEOGLINEARUNITSGEOKEY = 2052; + + /** Constant GEOGLINEARUNITSIZEGEOKEY=2053 */ public static final int GEOGLINEARUNITSIZEGEOKEY = 2053; + + /** Constant GEOGANGULARUNITSGEOKEY=2054 */ public static final int GEOGANGULARUNITSGEOKEY = 2054; + + /** Constant GEOGANGULARUNITSIZEGEOKEY=2055 */ public static final int GEOGANGULARUNITSIZEGEOKEY = 2055; + + /** Constant ELLIPSOIDGEOKEY=2056 */ public static final int ELLIPSOIDGEOKEY = 2056; + + /** Constant ELLIPSOIDSEMIMAJORAXISGEOKEY=2057 */ public static final int ELLIPSOIDSEMIMAJORAXISGEOKEY = 2057; + + /** Constant ELLIPSOIDSEMIMINORAXISGEOKEY=2058 */ public static final int ELLIPSOIDSEMIMINORAXISGEOKEY = 2058; + + /** Constant ELLIPSOIDINVFLATTENINGGEOKEY=2059 */ public static final int ELLIPSOIDINVFLATTENINGGEOKEY = 2059; + + /** Constant GEOGAZIMUTHUNITSGEOKEY=2060 */ public static final int GEOGAZIMUTHUNITSGEOKEY = 2060; + + /** Constant PRIMEMERIDIANLONGITUDEGEOKEY=2061 */ public static final int PRIMEMERIDIANLONGITUDEGEOKEY = 2061; + + /** Constant PROJECTEDCRSGEOKEY=3072 */ public static final int PROJECTEDCRSGEOKEY = 3072; + + /** Constant PROJECTEDCITATIONGEOKEY=3073 */ public static final int PROJECTEDCITATIONGEOKEY = 3073; + + /** Constant PROJECTIONGEOKEY=3074 */ public static final int PROJECTIONGEOKEY = 3074; + + /** Constant PROJMETHODGEOKEY=3075 */ public static final int PROJMETHODGEOKEY = 3075; + + /** Constant PROJLINEARUNITSGEOKEY=3076 */ public static final int PROJLINEARUNITSGEOKEY = 3076; + + /** Constant PROJLINEARUNITSIZEGEOKEY=3077 */ public static final int PROJLINEARUNITSIZEGEOKEY = 3077; + + /** Constant PROJSTDPARALLEL1GEOKEY=3078 */ public static final int PROJSTDPARALLEL1GEOKEY = 3078; + + /** Constant PROJSTDPARALLEL2GEOKEY=3079 */ public static final int PROJSTDPARALLEL2GEOKEY = 3079; + + /** Constant PROJNATORIGINLONGGEOKEY=3080 */ public static final int PROJNATORIGINLONGGEOKEY = 3080; + + /** Constant PROJNATORIGINLATGEOKEY=3081 */ public static final int PROJNATORIGINLATGEOKEY = 3081; + + /** Constant PROJFALSEEASTINGGEOKEY=3082 */ public static final int PROJFALSEEASTINGGEOKEY = 3082; + + /** Constant PROJFALSENORTHINGGEOKEY=3083 */ public static final int PROJFALSENORTHINGGEOKEY = 3083; + + /** Constant PROJFALSEORIGINLONGGEOKEY=3084 */ public static final int PROJFALSEORIGINLONGGEOKEY = 3084; + + /** Constant PROJFALSEORIGINLATGEOKEY=3085 */ public static final int PROJFALSEORIGINLATGEOKEY = 3085; + + /** Constant PROJFALSEORIGINEASTINGGEOKEY=3086 */ public static final int PROJFALSEORIGINEASTINGGEOKEY = 3086; + + /** Constant PROJFALSEORIGINNORTHINGGEOKEY=3087 */ public static final int PROJFALSEORIGINNORTHINGGEOKEY = 3087; + + /** Constant PROJCENTERLONGGEOKEY=3088 */ public static final int PROJCENTERLONGGEOKEY = 3088; + + /** Constant PROJCENTERLATGEOKEY=3089 */ public static final int PROJCENTERLATGEOKEY = 3089; + + /** Constant PROJCENTEREASTINGGEOKEY=3090 */ public static final int PROJCENTEREASTINGGEOKEY = 3090; + + /** Constant PROJCENTERNORTHINGGEOKEY=3091 */ public static final int PROJCENTERNORTHINGGEOKEY = 3091; + + /** Constant PROJSCALEATNATORIGINGEOKEY=3092 */ public static final int PROJSCALEATNATORIGINGEOKEY = 3092; + + /** Constant PROJSCALEATCENTERGEOKEY=3093 */ public static final int PROJSCALEATCENTERGEOKEY = 3093; + + /** Constant PROJAZIMUTHANGLEGEOKEY=3094 */ public static final int PROJAZIMUTHANGLEGEOKEY = 3094; + + /** Constant PROJSTRAIGHTVERTPOLELONGGEOKEY=3095 */ public static final int PROJSTRAIGHTVERTPOLELONGGEOKEY = 3095; + + /** Constant MODELPIXELSCALETAG=33550 */ public static final int MODELPIXELSCALETAG = 33550; + + /** Constant MODELTIEPOINTTAG=33922 */ public static final int MODELTIEPOINTTAG = 33922; + + /** Constant MODELTRANSFORMATIONTAG=34264 */ public static final int MODELTRANSFORMATIONTAG = 34264; + + /** Constant GEOKEYDIRECTORYTAG=34735 */ public static final int GEOKEYDIRECTORYTAG = 34735; + + /** Constant GEODOUBLEPARAMSTAG=34736 */ public static final int GEODOUBLEPARAMSTAG = 34736; + + /** Constant GEOASCIIPARAMSTAG=34737 */ public static final int GEOASCIIPARAMSTAG = 34737; + + /** Constant VERTICALGEOKEY=4096 */ public static final int VERTICALGEOKEY = 4096; + + /** Constant VERTICALCITATIONGEOKEY=4097 */ public static final int VERTICALCITATIONGEOKEY = 4097; + + /** Constant VERTICALDATUMGEOKEY=4098 */ public static final int VERTICALDATUMGEOKEY = 4098; + + /** Constant VERTICALUNITSGEOKEY=4099 */ public static final int VERTICALUNITSGEOKEY = 4099; } diff --git a/src/main/java/org/opengis/cite/geotiff11/util/NamespaceBindings.java b/src/main/java/org/opengis/cite/geotiff11/util/NamespaceBindings.java index e93323c..96e8bcd 100644 --- a/src/main/java/org/opengis/cite/geotiff11/util/NamespaceBindings.java +++ b/src/main/java/org/opengis/cite/geotiff11/util/NamespaceBindings.java @@ -5,100 +5,97 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; + import javax.xml.namespace.NamespaceContext; + import org.opengis.cite.geotiff11.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(); + + /** {@inheritDoc} */ + @Override + public String getNamespaceURI(String prefix) { + String nsName = null; + for (Map.Entry binding : bindings.entrySet()) { + if (binding.getValue().equals(prefix)) { + nsName = binding.getKey(); + break; + } + } + return nsName; + } - @Override - public String getNamespaceURI(String prefix) { - String nsName = null; - for (Map.Entry binding : bindings.entrySet()) { - if (binding.getValue().equals(prefix)) { - nsName = binding.getKey(); - break; - } - } - return nsName; - } + /** {@inheritDoc} */ + @Override + public String getPrefix(String namespaceURI) { + return bindings.get(namespaceURI); + } - @Override - public String getPrefix(String namespaceURI) { - return bindings.get(namespaceURI); - } + /** {@inheritDoc} */ + @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.geotiff11.Namespaces#OWS}
    • + *
    • xlink: {@value org.opengis.cite.geotiff11.Namespaces#XLINK}
    • + *
    • gml: {@value org.opengis.cite.geotiff11.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.geotiff11.Namespaces#OWS}
    • - *
    • xlink: {@value org.opengis.cite.geotiff11.Namespaces#XLINK}
    • - *
    • gml: {@value org.opengis.cite.geotiff11.Namespaces#GML}
    • - *
    - * - * @return A NamespaceBindings object. - */ - public static NamespaceBindings withStandardBindings() { - NamespaceBindings nsBindings = new NamespaceBindings(); - nsBindings.addNamespaceBinding(Namespaces.OWS, "ows"); - nsBindings.addNamespaceBinding(Namespaces.XLINK, "xlink"); - nsBindings.addNamespaceBinding(Namespaces.GML, "gml"); - return nsBindings; - } + /** {@inheritDoc} */ + @Override + public String toString() { + return "NamespaceBindings:\n" + bindings; + } - @Override - public String toString() { - return "NamespaceBindings:\n" + bindings; - } } diff --git a/src/main/java/org/opengis/cite/geotiff11/util/TestSuiteLogger.java b/src/main/java/org/opengis/cite/geotiff11/util/TestSuiteLogger.java index 454324f..fb1c749 100644 --- a/src/main/java/org/opengis/cite/geotiff11/util/TestSuiteLogger.java +++ b/src/main/java/org/opengis/cite/geotiff11/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/geotiff11/util/TiffDump.java b/src/main/java/org/opengis/cite/geotiff11/util/TiffDump.java index d7206ae..5704d73 100644 --- a/src/main/java/org/opengis/cite/geotiff11/util/TiffDump.java +++ b/src/main/java/org/opengis/cite/geotiff11/util/TiffDump.java @@ -8,93 +8,95 @@ /** * A (rough) wrapper class for the output of TiffDump.exe - * - * @author Dustin Jutras, AGC * + * @author Dustin Jutras, AGC */ public class TiffDump { - public static void main(String[] args) { - TiffDump td; - String test = "Tile L(ength (0x323) SHORT (3) 231<256 789 87 45>\\r\\n"; - - try { - td = new TiffDump(new String("c:/Users/RDAGCDLJ/Documents/FY20/GeoTIFF/example_tiffs/COG_DEF_OR/LC08_L1TP_016030_20140602_20170305_01_T1_B1.TIF:\r\n" + - "Magic: 0x4949 Version: 0x2a \r\n" + - "Directory 0: offset 8 (0x8) next 3034 (0xbda)\r\n" + - "ImageWidth (256) SHORT (3) 1<7901>\r\n" + - "ImageLength (257) SHORT (3) 1<8011>\r\n" + - "BitsPerSample (258) SHORT (3) 1<16>\r\n" + - "Compression (259) SHORT (3) 1<8>\r\n" + - "Photometric (262) SHORT (3) 1<1>\r\n" + - "SamplesPerPixel (277) SHORT (3) 1<1>\r\n" + - "PlanarConfig (284) SHORT (3) 1<1>\r\n" + - "Predictor (317) SHORT (3) 1<1>\r\n" + - "TileWidth (322) SHORT (3) 1<512>\r\n" + - "TileLength (323) SHORT (3) 1<512>\r\n" + - "SampleFormat (339) SHORT (3) 1<1>\r\n" + - "33550 (0x830e) DOUBLE (12) 3<30 30 0>\r\n" + - "33922 (0x8482) DOUBLE (12) 6<0 0 0 217200 4.9029e+06 0>\r\n" + - "34735 (0x87af) SHORT (3) 64<1 1 0 14 1024 0 1 1 1025 0 1 2 1026 34737 33 0 2048 0 1 32767 2049 34737 84 33 2054 0 1 9102 2055 34736 1 0 2057 34736 1 1 2059 34736 1 2 2061 34736 1 3 3072 0 1 32767 3073 34737 406 117 3074 0 1 16018 3076 0 1 9001 0 0 0 0>\r\n" + - "34736 (0x87b0) DOUBLE (12) 4<0.0174533 6.37814e+06 298.257 0>\r\n" + - "34737 (0x87b1) ASCII (2) 524\r\n" - )); - - System.out.println(td); - - System.out.println(td.getDirectory(0)); - System.out.println(td.getDirectory(0).getTag("34737")); - System.out.println(); - - } catch (Exception e) { + /** + *

    + * main. + *

    + * @param args an array of {@link java.lang.String} objects + */ + public static void main(String[] args) { + TiffDump td; + String test = "Tile L(ength (0x323) SHORT (3) 231<256 789 87 45>\\r\\n"; + + try { + td = new TiffDump(new String( + "c:/Users/RDAGCDLJ/Documents/FY20/GeoTIFF/example_tiffs/COG_DEF_OR/LC08_L1TP_016030_20140602_20170305_01_T1_B1.TIF:\r\n" + + "Magic: 0x4949 Version: 0x2a \r\n" + + "Directory 0: offset 8 (0x8) next 3034 (0xbda)\r\n" + + "ImageWidth (256) SHORT (3) 1<7901>\r\n" + "ImageLength (257) SHORT (3) 1<8011>\r\n" + + "BitsPerSample (258) SHORT (3) 1<16>\r\n" + "Compression (259) SHORT (3) 1<8>\r\n" + + "Photometric (262) SHORT (3) 1<1>\r\n" + "SamplesPerPixel (277) SHORT (3) 1<1>\r\n" + + "PlanarConfig (284) SHORT (3) 1<1>\r\n" + "Predictor (317) SHORT (3) 1<1>\r\n" + + "TileWidth (322) SHORT (3) 1<512>\r\n" + "TileLength (323) SHORT (3) 1<512>\r\n" + + "SampleFormat (339) SHORT (3) 1<1>\r\n" + "33550 (0x830e) DOUBLE (12) 3<30 30 0>\r\n" + + "33922 (0x8482) DOUBLE (12) 6<0 0 0 217200 4.9029e+06 0>\r\n" + + "34735 (0x87af) SHORT (3) 64<1 1 0 14 1024 0 1 1 1025 0 1 2 1026 34737 33 0 2048 0 1 32767 2049 34737 84 33 2054 0 1 9102 2055 34736 1 0 2057 34736 1 1 2059 34736 1 2 2061 34736 1 3 3072 0 1 32767 3073 34737 406 117 3074 0 1 16018 3076 0 1 9001 0 0 0 0>\r\n" + + "34736 (0x87b0) DOUBLE (12) 4<0.0174533 6.37814e+06 298.257 0>\r\n" + + "34737 (0x87b1) ASCII (2) 524\r\n")); + + System.out.println(td); + + System.out.println(td.getDirectory(0)); + System.out.println(td.getDirectory(0).getTag("34737")); + System.out.println(); + + } + catch (Exception e) { e.printStackTrace(); - } - - - } - - /** - * A class representing a directory within a tiff - * - * @author Dustin Jutras, AGC - * - */ + } + + } + + /** + * A class representing a directory within a tiff + * + * @author Dustin Jutras, AGC + * + */ public class Directory { - + private int index; + private int offset; + private int next; + private List tags = new ArrayList<>(); - + public Directory(String directoryLine) { List info = new ArrayList(Arrays.asList(directoryLine.replace(":", "").split(" "))); index = Integer.parseInt(info.get(info.indexOf("directory") + 1).trim()); offset = Integer.parseInt(info.get(info.indexOf("offset") + 1).trim()); next = Integer.parseInt(info.get(info.indexOf("next") + 1).trim()); } - + public void addTag(String line) { this.tags.add(new Tag(line)); } - + public Tag getTag(String s) { for (Tag tag : tags) { - if(tag.getName().equals(s.toLowerCase())) { + if (tag.getName().equals(s.toLowerCase())) { return tag; } } return null; } - + public Tag getTag(int value) { for (Tag tag : tags) { - if(tag.getNameValue() == value) { + if (tag.getNameValue() == value) { return tag; } } return null; - } - + } + public List getTags() { return tags; } @@ -109,102 +111,109 @@ public int getNext() { @Override public String toString() { - + String tagsString = ""; - - for(Tag tag : tags) { + + for (Tag tag : tags) { tagsString += tag.toString() + "\n"; } - - return String.format("Directory %d:\nOffset: %d\tNext: %d\nTags:\n%s\n%s\n", index, offset, next, tagHeaderString(), tagsString); + + return String.format("Directory %d:\nOffset: %d\tNext: %d\nTags:\n%s\n%s\n", index, offset, next, + tagHeaderString(), tagsString); } public boolean hasTag(int tag) { return getTag(tag) != null; } + } - - /** - * A class representing a tag within a tiff - * - * @author Dustin Jutras, AGC - * - */ + + /** + * A class representing a tag within a tiff + * + * @author Dustin Jutras, AGC + * + */ public class Tag { - + private String line; + private String name, type; + private int nameValue, typeValue, count; + private String valuesAsString; + private List values = new ArrayList<>(); - + public Tag(String line) { this.line = line; - Matcher matcher; - - String regexNameValue = ".+?(?= \\([0-9])"; - String regexNumbers = "\\((0x[0-9a-f]+?|[0-9]+?)\\)"; - String regexCount = "([0-9]+)\\<"; - String regexValues = "[0-9]\\<(.*?)\\>\\s*$"; - + Matcher matcher; + + String regexNameValue = ".+?(?= \\([0-9])"; + String regexNumbers = "\\((0x[0-9a-f]+?|[0-9]+?)\\)"; + String regexCount = "([0-9]+)\\<"; + String regexValues = "[0-9]\\<(.*?)\\>\\s*$"; + matcher = Pattern.compile(regexNumbers).matcher(line); -// if(matcher.f) != 2) { -// System.out.println("BIG ERROR"); -// } + // if(matcher.f) != 2) { + // System.out.println("BIG ERROR"); + // } matcher.find(); String nameValueString = matcher.group(1); - nameValue = nameValueString.contains("x") ? - Integer.parseInt(nameValueString.replace("0x", ""), 16) : - Integer.parseInt(nameValueString); + nameValue = nameValueString.contains("x") ? Integer.parseInt(nameValueString.replace("0x", ""), 16) + : Integer.parseInt(nameValueString); matcher.find(); typeValue = Integer.parseInt(matcher.group(1)); - + matcher = Pattern.compile(regexCount).matcher(line); matcher.find(); count = Integer.parseInt(matcher.group(1)); - + matcher = Pattern.compile(regexValues).matcher(line); matcher.find(); valuesAsString = matcher.group(1).trim(); - String[] stringValues; - + String[] stringValues; + name = line.split(regexNumbers)[0].trim(); type = line.split(regexNumbers)[1].trim(); - - switch(type.toUpperCase()) { + + switch (type.toUpperCase()) { case "ASCII": stringValues = valuesAsString.split("\\|"); break; - case "SHORT": case "RATIONAL": case "DOUBLE": default: + case "SHORT": + case "RATIONAL": + case "DOUBLE": + default: stringValues = valuesAsString.split(" "); break; } - - if(stringValues[stringValues.length - 1].contains("...")) { + + if (stringValues[stringValues.length - 1].contains("...")) { System.out.println("Value list has been truncated."); stringValues = Arrays.copyOfRange(stringValues, 0, stringValues.length - 1); } - // is this really necessary? probably not - - switch(type.toUpperCase()) { - case "SHORT": - for(String value : stringValues) { + + switch (type.toUpperCase()) { + case "SHORT": + for (String value : stringValues) { values.add(Integer.parseInt(value)); } break; case "RATIONAL": case "DOUBLE": - for(String value : stringValues) { + for (String value : stringValues) { values.add(Float.parseFloat(value)); } break; case "ASCII": default: - for(String value : stringValues) { + for (String value : stringValues) { values.add(value); } break; @@ -219,11 +228,11 @@ public String getLine() { public String getName() { return name; } - + public int getNameValue() { return nameValue; } - + public int getTypeValue() { return typeValue; } @@ -231,94 +240,156 @@ public int getTypeValue() { public int getCount() { return count; } - + public boolean containsValue(Object value) { return values.contains(value); } - + public List getValues() { return values; } - + public String getValuesAsString() { return valuesAsString; } @Override - public String toString() { - return String.format("%20s (%d)\t%10s (%d)\t%10d %s", name.toUpperCase(), nameValue, type, typeValue, count, values.toString()); - } + public String toString() { + return String.format("%20s (%d)\t%10s (%d)\t%10d %s", name.toUpperCase(), nameValue, type, typeValue, count, + values.toString()); + } + } - + private String filePath; + private String magic; + private String version; + private List directories = new ArrayList<>(); + private Directory geoKeyDirectory; - - public TiffDump(String contents) throws Exception { + + /** + *

    + * Constructor for TiffDump. + *

    + * @param contents a {@link java.lang.String} object + * @throws java.lang.Exception if any. + */ + public TiffDump(String contents) throws Exception { Directory currentDirectory = null; - for(String line : contents.toLowerCase().split("\n")) { - if(currentDirectory == null && (line.contains(".tif") || line.contains(".tmp")) ) { + for (String line : contents.toLowerCase().split("\n")) { + if (currentDirectory == null && (line.contains(".tif") || line.contains(".tmp"))) { filePath = line.substring(0, line.length() - 2); continue; } - if(currentDirectory == null && line.contains("magic:") && line.contains("version:")) { + if (currentDirectory == null && line.contains("magic:") && line.contains("version:")) { List info = Arrays.asList(line.replace(":", "").split(" ")); magic = info.get(info.indexOf("magic") + 1).trim(); version = info.get(info.indexOf("version") + 1).trim(); continue; } - if(line.toLowerCase().indexOf("directory") == 0 && line.toLowerCase().contains("offset") && line.toLowerCase().contains("next")) { + if (line.toLowerCase().indexOf("directory") == 0 && line.toLowerCase().contains("offset") + && line.toLowerCase().contains("next")) { currentDirectory = new Directory(line); directories.add(currentDirectory); continue; } - if(currentDirectory != null && !line.trim().equals("")) { + if (currentDirectory != null && !line.trim().equals("")) { currentDirectory.addTag(line); - if(currentDirectory.hasTag(GeoKeyID.GEOKEYDIRECTORYTAG)) { + if (currentDirectory.hasTag(GeoKeyID.GEOKEYDIRECTORYTAG)) { geoKeyDirectory = currentDirectory; } } } - - if(!valid()) { + + if (!valid()) { System.out.println("Tiff contents invalid/parsed incorrectly:\n" + contents); throw new Exception("Tiff contents invalid/parsed incorrectly."); } } - + + /** + *

    + * valid. + *

    + * @return a boolean + */ public boolean valid() { - if(magic == null || version == null || directories.size() < 1) { + if (magic == null || version == null || directories.size() < 1) { return false; } return true; } - + + /** + *

    + * getDirectory. + *

    + * @param index a int + * @return a {@link org.opengis.cite.geotiff11.util.TiffDump.Directory} object + */ public Directory getDirectory(int index) { return directories.get(index); } + + /** + *

    + * Getter for the field directories. + *

    + * @return a {@link java.util.List} object + */ public List getDirectories() { return directories; } + + /** + *

    + * Getter for the field geoKeyDirectory. + *

    + * @return a {@link org.opengis.cite.geotiff11.util.TiffDump.Directory} object + */ public Directory getGeoKeyDirectory() { return geoKeyDirectory; } - + + /** {@inheritDoc} */ @Override - public String toString() { - return String.format("TiffDump:\n%s\nMagic: %s Version: %s\n%s", filePath == null ? "filepath unavailable" : filePath, magic, version, directories.toString()); - } + public String toString() { + return String.format("TiffDump:\n%s\nMagic: %s Version: %s\n%s", + filePath == null ? "filepath unavailable" : filePath, magic, version, directories.toString()); + } + /** + *

    + * Getter for the field magic. + *

    + * @return a {@link java.lang.String} object + */ public String getMagic() { return magic; } + /** + *

    + * Getter for the field version. + *

    + * @return a {@link java.lang.String} object + */ public String getVersion() { return version; } - + + /** + *

    + * tagHeaderString. + *

    + * @return a {@link java.lang.String} object + */ static public String tagHeaderString() { return String.format("%20s (%s)\t%10s (%s)\t%10s %s", "NAME", "ID", "TYPE", "T", "CNT", "[VALUES]"); } + } diff --git a/src/main/java/org/opengis/cite/geotiff11/util/URIUtils.java b/src/main/java/org/opengis/cite/geotiff11/util/URIUtils.java index 3b26dbc..069aab9 100644 --- a/src/main/java/org/opengis/cite/geotiff11/util/URIUtils.java +++ b/src/main/java/org/opengis/cite/geotiff11/util/URIUtils.java @@ -8,67 +8,52 @@ import java.io.OutputStream; import java.io.PrintWriter; import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; import java.nio.file.Paths; -import java.util.NoSuchElementException; -import java.util.Scanner; import java.util.logging.Level; -import javax.ws.rs.core.HttpHeaders; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.SystemUtils; import org.opengis.cite.geotiff11.SuiteAttribute; import org.opengis.cite.geotiff11.SyncPipe; -import org.opengis.cite.geotiff11.util.URIUtils; import org.testng.ISuite; import org.w3c.dom.Document; import org.xml.sax.SAXException; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.Response; /** - * Provides a collection of utility methods for manipulating or resolving URI - * references. + * Provides a collection of utility methods for manipulating or resolving URI references. */ public class URIUtils { private static final String FIXUP_BASE_URI = "http://apache.org/xml/features/xinclude/fixup-base-uris"; + private static final String EXE = "exe"; + private static final String TIFFDUMP = "tiffdump"; /** - * Parses the content of the given URI as an XML document and returns a new - * DOM Document object. Entity reference nodes will not be expanded. XML - * inclusions (xi:include elements) will be processed if present. - * - * @param uriRef - * An absolute URI specifying the location of an XML resource. + * Parses the content of the given URI as an XML document and returns a new DOM + * Document object. Entity reference nodes will not be expanded. XML inclusions + * (xi:include elements) will be processed if present. + * @param uriRef An absolute URI specifying the location of an XML resource. * @return A DOM Document node representing an XML resource. - * @throws SAXException - * If the resource cannot be parsed. - * @throws IOException - * If the resource is not accessible. + * @throws org.xml.sax.SAXException If the resource cannot be parsed. + * @throws java.io.IOException If the resource is not accessible. */ - public static Document parseURI(URI uriRef) throws SAXException, - IOException { + public static Document parseURI(URI uriRef) throws SAXException, IOException { if ((null == uriRef) || !uriRef.isAbsolute()) { - throw new IllegalArgumentException( - "Absolute URI is required, but received " + uriRef); + throw new IllegalArgumentException("Absolute URI is required, but received " + uriRef); } - DocumentBuilderFactory docFactory = DocumentBuilderFactory - .newInstance(); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); docFactory.setExpandEntityReferences(false); docFactory.setXIncludeAware(true); @@ -78,9 +63,9 @@ public static Document parseURI(URI uriRef) throws SAXException, docFactory.setFeature(FIXUP_BASE_URI, false); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); doc = docBuilder.parse(uriRef.toString()); - } catch (ParserConfigurationException x) { - TestSuiteLogger.log(Level.WARNING, - "Failed to create DocumentBuilder." + x); + } + catch (ParserConfigurationException x) { + TestSuiteLogger.log(Level.WARNING, "Failed to create DocumentBuilder." + x); } if (null != doc) { doc.setDocumentURI(uriRef.toString()); @@ -89,17 +74,16 @@ public static Document parseURI(URI uriRef) throws SAXException, } /** - * Parses the content of the given URI as a GeoTIFF document. Execute - * tiffdump command lines to spit out the metadata into a local file. - * + * Parses the content of the given URI as a GeoTIFF document. Execute tiffdump command + * lines to spit out the metadata into a local file. * @param uriRef In order to extract the file path where the exe is located * @param geoTiffFile To extract the metadata * @return String of file location - * @throws SAXException - * @throws IOException + * @throws org.xml.sax.SAXException + * @throws java.io.IOException + * @param suite a {@link org.testng.ISuite} object */ - public static boolean parseGeoTiff(ISuite suite, URI uriRef, String geoTiffFile) - throws SAXException, IOException { + public static boolean parseGeoTiff(ISuite suite, URI uriRef, String geoTiffFile) throws SAXException, IOException { // TODO: multiple files capability? if ((null == uriRef)) { @@ -107,10 +91,11 @@ public static boolean parseGeoTiff(ISuite suite, URI uriRef, String geoTiffFile) } // Start running commands - // String geotiffFilePath = uriRef.getPath().substring(1, uriRef.getPath().length()); + // String geotiffFilePath = uriRef.getPath().substring(1, + // uriRef.getPath().length()); String geotiffFilePath = prepPath(uriRef.getPath()); - // System.out.println("GeoTIFF path: " + geotiffFilePath); + // System.out.println("GeoTIFF path: " + geotiffFilePath); if (!readMetaData(suite, geotiffFilePath, geoTiffFile)) return false; @@ -120,25 +105,25 @@ public static boolean parseGeoTiff(ISuite suite, URI uriRef, String geoTiffFile) /** * Create the metadata commands to read the geotiff file - * * @param exeCommand * @param geotiffFilePath * @param fileOutput * @return */ - private static String initMetadataComm(String exeCommand, String outLocation, String geotiffFilePath, String option) { - // String location = prepPath(URIUtils.class.getResource("/tmp").getPath()); - return exeCommand + " " + option + " " + geotiffFilePath + " > " + outLocation;//Paths.get(location, fileOutput); + private static String initMetadataComm(String exeCommand, String outLocation, String geotiffFilePath, + String option) { + // String location = prepPath(URIUtils.class.getResource("/tmp").getPath()); + return exeCommand + " " + option + " " + geotiffFilePath + " > " + outLocation;// Paths.get(location, + // fileOutput); } /** * Run the commands to read the TiffDump output on Windows/Linux - * * @param geotiffFilePath * @param geoTiffFile * @return */ - private static boolean readMetaData(ISuite suite, String geotiffFilePath, String geoTiffFile) { + private static boolean readMetaData(ISuite suite, String geotiffFilePath, String geoTiffFile) { Process p = startCmd(); if (p == null) return false; @@ -150,20 +135,20 @@ private static boolean readMetaData(ISuite suite, String geotiffFilePath, String File outTempFile = File.createTempFile("tiffMeta", ".txt"); InputStream input; - if(SystemUtils.IS_OS_WINDOWS) { - + if (SystemUtils.IS_OS_WINDOWS) { + // WINDOWS - + File exeTempFile; String exe; - + exeTempFile = File.createTempFile("tiffdump", ".exe"); input = URIUtils.class.getResourceAsStream("/exe/tiffdump.exe"); FileOutputStream output = new FileOutputStream(exeTempFile); - byte [] buffer = new byte[4096]; + byte[] buffer = new byte[4096]; int bytesRead = input.read(buffer); while (bytesRead != -1) { output.write(buffer, 0, bytesRead); @@ -172,107 +157,108 @@ private static boolean readMetaData(ISuite suite, String geotiffFilePath, String exeTempFile.deleteOnExit(); - // System.out.println(exeTempFile); - // System.out.println(exeTempFile.getPath()); + // System.out.println(exeTempFile); + // System.out.println(exeTempFile.getPath()); - // exe = exeTempFile.getPath(); - exe = Paths.get(System.getProperty("user.dir")).relativize(exeTempFile.toPath()).toString(); - // System.out.println(Paths.get(System.getProperty("user.dir"))); - // System.out.println(exeTempFile.toPath()); - // System.out.println(exe); + // exe = exeTempFile.getPath(); + exe = exeTempFile.toPath().toString(); + // System.out.println(Paths.get(System.getProperty("user.dir"))); + // System.out.println(exeTempFile.toPath()); + // System.out.println(exe); output.close(); input.close(); try (PrintWriter stdin = new PrintWriter(p.getOutputStream())) { - stdin.println(initMetadataComm(exe, outTempFile.getAbsolutePath(), geotiffFilePath, "-m 10000")); + stdin.println(initMetadataComm(exe, outTempFile.getAbsolutePath(), geotiffFilePath, "-m 10000")); stdin.flush(); } - } else { - + } + else { + // LINUX - -// File tifTempFile = File.createTempFile("iut", ".tif"); - + + // File tifTempFile = File.createTempFile("iut", ".tif"); + try (PrintWriter stdin = new PrintWriter(p.getOutputStream())) { stdin.println("cat /etc/os-release"); stdin.println("apt-get upgrade -y"); stdin.println("apt-get update -y"); -// stdin.println("apt -q install -y libtiff5"); + // stdin.println("apt -q install -y libtiff5"); stdin.println("apt-get install -y libtiff-tools"); - + stdin.println("apt-get update -y"); - + stdin.flush(); - -// stdin.println("dpkg -l libtiff-tools"); -// String outPath = "./" + Paths.get(System.getProperty("user.dir")).relativize(outTempFile.toPath()).toString(); + // stdin.println("dpkg -l libtiff-tools"); + + // String outPath = "./" + + // Paths.get(System.getProperty("user.dir")).relativize(outTempFile.toPath()).toString(); String outPath = outTempFile.getAbsolutePath(); - + stdin.println("cd /"); - + stdin.println("echo '" + initMetadataComm("tiffdump", outPath, geotiffFilePath, "-m 10000") + "'"); stdin.println(initMetadataComm("tiffdump", outPath, geotiffFilePath, "-m 10000")); stdin.println("echo 'cat " + outPath + "'"); - stdin.println("cat " + outPath); + stdin.println("cat " + outPath); stdin.flush(); -// stdin.println("cat " + geotiffFilePath); + // stdin.println("cat " + geotiffFilePath); } - } + } int returnCode; try { returnCode = p.waitFor(); InputStream inputStream = new FileInputStream(outTempFile.getAbsolutePath()); - suite.setAttribute(SuiteAttribute.TEST_SUBJECT.getName(), IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + suite.setAttribute(SuiteAttribute.TEST_SUBJECT.getName(), + IOUtils.toString(inputStream, StandardCharsets.UTF_8)); inputStream.close(); -// System.out.println((String) suite.getAttribute(SuiteAttribute.TEST_SUBJECT.getName())); + // System.out.println((String) + // suite.getAttribute(SuiteAttribute.TEST_SUBJECT.getName())); - } catch (InterruptedException e) { + } + catch (InterruptedException e) { e.printStackTrace(); return false; } return true; - } catch (IOException e) { + } + catch (IOException e) { e.printStackTrace(); return false; } } - private static String prepPath(String string) { string = string.replace("jar:", ""); string = string.replace("file:", ""); - if(SystemUtils.IS_OS_WINDOWS) + if (SystemUtils.IS_OS_WINDOWS) string = string.replace("/", "\\"); else string = string.replace("\\", "/"); - while(string.charAt(0) == '\\' || string.charAt(0) == '/') - { + while (string.charAt(0) == '\\' || string.charAt(0) == '/') { string = string.substring(1); - } - // System.out.println("Path prepped: " + string); + } + // System.out.println("Path prepped: " + string); return string; } /** * Starts a command prompt - * * @return */ private static Process startCmd() { String command; // = { "cmd", }; - if(SystemUtils.IS_OS_WINDOWS) - { + if (SystemUtils.IS_OS_WINDOWS) { command = "cmd"; } - else - { + else { command = "bash"; } @@ -280,42 +266,37 @@ private static Process startCmd() { try { p = Runtime.getRuntime().exec(command); return p; - } catch (IOException e) { + } + catch (IOException e) { e.printStackTrace(); return null; } } /** - * 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. + * 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. + * resolution failed for any reason. + * @throws java.io.IOException If an IO error occurred. */ public static File dereferenceURI(URI uriRef) throws IOException { if ((null == uriRef) || !uriRef.isAbsolute()) { - throw new IllegalArgumentException( - "Absolute URI is required, but received " + uriRef); + throw new IllegalArgumentException("Absolute URI is required, but received " + uriRef); } if (uriRef.getScheme().equalsIgnoreCase("file")) { return new File(uriRef); } - Client client = Client.create(); - WebResource webRes = client.resource(uriRef); - ClientResponse rsp = webRes.get(ClientResponse.class); + Client client = ClientBuilder.newClient(); + Response rsp = client.target(uriRef).request().get(); String suffix = null; - if (rsp.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE).endsWith("tif")) { + if (rsp.getHeaderString(HttpHeaders.CONTENT_TYPE).endsWith("tif")) { suffix = ".tif"; } File destFile = File.createTempFile("entity-", suffix); if (rsp.hasEntity()) { - InputStream is = rsp.getEntityInputStream(); + InputStream is = rsp.readEntity(InputStream.class); OutputStream os = new FileOutputStream(destFile); byte[] buffer = new byte[8 * 1024]; int bytesRead; @@ -326,30 +307,25 @@ public static File dereferenceURI(URI uriRef) throws IOException { os.flush(); os.close(); } - TestSuiteLogger.log(Level.FINE, "Wrote " + destFile.length() - + " bytes to file at " + destFile.getAbsolutePath()); + TestSuiteLogger.log(Level.FINE, + "Wrote " + destFile.length() + " bytes to file at " + destFile.getAbsolutePath()); return destFile; } /** * Constructs an absolute URI from the given URI reference and a base URI. - * - * @see RFC 3986, - * 5.2 - * - * @param baseURI - * The base URI; if present, it must be an absolute URI. - * @param uriRef - * A URI reference that may be relative to the given base URI. + * + * @see RFC 3986, 5.2 + * @param baseURI The base URI; if present, it must be an absolute URI. + * @param uriRef A URI reference that may be relative to the given base URI. * @return The resulting URI. - * */ public static URI resolveRelativeURI(String baseURI, String uriRef) { URI uri = (null != baseURI) ? URI.create(baseURI) : URI.create(""); if (null != baseURI && null == uri.getScheme()) { - throw new IllegalArgumentException( - "Base URI has no scheme component: " + baseURI); + throw new IllegalArgumentException("Base URI has no scheme component: " + baseURI); } return uri.resolve(uriRef); } -} \ No newline at end of file + +} diff --git a/src/main/java/org/opengis/cite/geotiff11/util/ValidationUtils.java b/src/main/java/org/opengis/cite/geotiff11/util/ValidationUtils.java index 5e510db..1d7eef5 100644 --- a/src/main/java/org/opengis/cite/geotiff11/util/ValidationUtils.java +++ b/src/main/java/org/opengis/cite/geotiff11/util/ValidationUtils.java @@ -25,138 +25,120 @@ import org.w3c.dom.ls.LSResourceResolver; /** - * A utility class that provides convenience methods to support schema - * validation. + * A utility class that provides convenience methods to support schema validation. */ public class ValidationUtils { - static final String ROOT_PKG = "/org/opengis/cite/geotiff11/"; - private static final XMLCatalogResolver SCH_RESOLVER = initCatalogResolver(); + static final String ROOT_PKG = "/org/opengis/cite/geotiff11/"; - private static XMLCatalogResolver initCatalogResolver() { - return (XMLCatalogResolver) createSchemaResolver(Namespaces.SCH); - } + private static final XMLCatalogResolver SCH_RESOLVER = initCatalogResolver(); - /** - * Creates a resource resolver suitable for locating schemas using an entity - * catalog. In effect, local copies of standard schemas are returned instead - * of retrieving them from external repositories. - * - * @param schemaLanguage - * A URI that identifies a schema language by namespace name. - * @return A {@code LSResourceResolver} object that is configured to use an - * OASIS entity catalog. - */ - public static LSResourceResolver createSchemaResolver(URI schemaLanguage) { - String catalogFileName; - if (schemaLanguage.equals(Namespaces.XSD)) { - catalogFileName = "schema-catalog.xml"; - } else { - catalogFileName = "schematron-catalog.xml"; - } - URL catalogURL = ValidationUtils.class.getResource(ROOT_PKG - + catalogFileName); - XMLCatalogResolver resolver = new XMLCatalogResolver(); - resolver.setCatalogList(new String[] { catalogURL.toString() }); - return resolver; - } + private static XMLCatalogResolver initCatalogResolver() { + return (XMLCatalogResolver) createSchemaResolver(Namespaces.SCH); + } - /** - * Constructs a SchematronValidator that will check an XML resource against - * the rules defined in a Schematron schema. An attempt is made to resolve - * the schema reference using an entity catalog; if this fails the reference - * is used as given. - * - * @param schemaRef - * A reference to a Schematron schema; this is expected to be a - * relative or absolute URI value, possibly matching the system - * identifier for some entry in an entity catalog. - * @param phase - * The name of the phase to invoke. - * @return A SchematronValidator instance, or {@code null} if the validator - * cannot be constructed (e.g. invalid schema reference or phase - * name). - */ - public static SchematronValidator buildSchematronValidator( - String schemaRef, String phase) { - Source source = null; - try { - String catalogRef = SCH_RESOLVER - .resolveSystem(schemaRef.toString()); - if (null != catalogRef) { - source = new StreamSource(URI.create(catalogRef).toString()); - } else { - source = new StreamSource(schemaRef); - } - } catch (IOException x) { - TestSuiteLogger.log(Level.WARNING, - "Error reading Schematron schema catalog.", x); - } - SchematronValidator validator = null; - try { - validator = new SchematronValidator(source, phase); - } catch (Exception e) { - TestSuiteLogger.log(Level.WARNING, - "Error creating Schematron validator.", e); - } - return validator; - } + /** + * Creates a resource resolver suitable for locating schemas using an entity catalog. + * In effect, local copies of standard schemas are returned instead of retrieving them + * from external repositories. + * @param schemaLanguage A URI that identifies a schema language by namespace name. + * @return A {@code LSResourceResolver} object that is configured to use an OASIS + * entity catalog. + */ + public static LSResourceResolver createSchemaResolver(URI schemaLanguage) { + String catalogFileName; + if (schemaLanguage.equals(Namespaces.XSD)) { + catalogFileName = "schema-catalog.xml"; + } + else { + catalogFileName = "schematron-catalog.xml"; + } + URL catalogURL = ValidationUtils.class.getResource(ROOT_PKG + catalogFileName); + XMLCatalogResolver resolver = new XMLCatalogResolver(); + resolver.setCatalogList(new String[] { catalogURL.toString() }); + return resolver; + } + + /** + * Constructs a SchematronValidator that will check an XML resource against the rules + * defined in a Schematron schema. An attempt is made to resolve the schema reference + * using an entity catalog; if this fails the reference is used as given. + * @param schemaRef A reference to a Schematron schema; this is expected to be a + * relative or absolute URI value, possibly matching the system identifier for some + * entry in an entity catalog. + * @param phase The name of the phase to invoke. + * @return A SchematronValidator instance, or {@code null} if the validator cannot be + * constructed (e.g. invalid schema reference or phase name). + */ + public static SchematronValidator buildSchematronValidator(String schemaRef, String phase) { + Source source = null; + try { + String catalogRef = SCH_RESOLVER.resolveSystem(schemaRef.toString()); + if (null != catalogRef) { + source = new StreamSource(URI.create(catalogRef).toString()); + } + else { + source = new StreamSource(schemaRef); + } + } + catch (IOException x) { + TestSuiteLogger.log(Level.WARNING, "Error reading Schematron schema catalog.", x); + } + SchematronValidator validator = null; + try { + validator = new SchematronValidator(source, phase); + } + catch (Exception e) { + TestSuiteLogger.log(Level.WARNING, "Error creating Schematron validator.", e); + } + return validator; + } + + /** + * Extracts a set of XML Schema references from a source XML document. The document + * element is expected to include the standard xsi:schemaLocation attribute. + * @param source The source instance to read from; its base URI (systemId) should be + * set. + * @param baseURI An alternative base URI to use if the source does not have a system + * identifier set or if its system id is a {@code file} URI. This will usually be the + * URI used to retrieve the resource; it may be null. + * @return A Set containing absolute URI references that specify the locations of XML + * Schema resources. + * @throws javax.xml.stream.XMLStreamException If an error occurs while reading the + * source instance. + */ + public static Set extractSchemaReferences(Source source, String baseURI) throws XMLStreamException { + XMLInputFactory factory = XMLInputFactory.newInstance(); + XMLEventReader reader = factory.createXMLEventReader(source); + // advance to document element + StartElement docElem = reader.nextTag().asStartElement(); + Attribute schemaLoc = docElem + .getAttributeByName(new QName(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "schemaLocation")); + if (null == schemaLoc) { + throw new RuntimeException("No xsi:schemaLocation attribute found. See ISO 19136, A.3.1."); + } + String[] uriValues = schemaLoc.getValue().split("\\s+"); + if (uriValues.length % 2 != 0) { + throw new RuntimeException("xsi:schemaLocation attribute contains an odd number of URI values:\n" + + Arrays.toString(uriValues)); + } + Set schemaURIs = new HashSet(); + // one or more pairs of [namespace name] [schema location] + for (int i = 0; i < uriValues.length; i += 2) { + URI schemaURI = null; + if (!URI.create(uriValues[i + 1]).isAbsolute() && (null != source.getSystemId())) { + String schemaRef = URIUtils.resolveRelativeURI(source.getSystemId(), uriValues[i + 1]).toString(); + if (schemaRef.startsWith("file") && !new File(schemaRef).exists() && (null != baseURI)) { + schemaRef = URIUtils.resolveRelativeURI(baseURI, uriValues[i + 1]).toString(); + } + schemaURI = URI.create(schemaRef); + } + else { + schemaURI = URI.create(uriValues[i + 1]); + } + schemaURIs.add(schemaURI); + } + return schemaURIs; + } - /** - * Extracts a set of XML Schema references from a source XML document. The - * document element is expected to include the standard xsi:schemaLocation - * attribute. - * - * @param source - * The source instance to read from; its base URI (systemId) - * should be set. - * @param baseURI - * An alternative base URI to use if the source does not have a - * system identifier set or if its system id is a {@code file} - * URI. This will usually be the URI used to retrieve the - * resource; it may be null. - * @return A Set containing absolute URI references that specify the - * locations of XML Schema resources. - * @throws XMLStreamException - * If an error occurs while reading the source instance. - */ - public static Set extractSchemaReferences(Source source, String baseURI) - throws XMLStreamException { - XMLInputFactory factory = XMLInputFactory.newInstance(); - XMLEventReader reader = factory.createXMLEventReader(source); - // advance to document element - StartElement docElem = reader.nextTag().asStartElement(); - Attribute schemaLoc = docElem.getAttributeByName(new QName( - XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "schemaLocation")); - if (null == schemaLoc) { - throw new RuntimeException( - "No xsi:schemaLocation attribute found. See ISO 19136, A.3.1."); - } - String[] uriValues = schemaLoc.getValue().split("\\s+"); - if (uriValues.length % 2 != 0) { - throw new RuntimeException( - "xsi:schemaLocation attribute contains an odd number of URI values:\n" - + Arrays.toString(uriValues)); - } - Set schemaURIs = new HashSet(); - // one or more pairs of [namespace name] [schema location] - for (int i = 0; i < uriValues.length; i += 2) { - URI schemaURI = null; - if (!URI.create(uriValues[i + 1]).isAbsolute() - && (null != source.getSystemId())) { - String schemaRef = URIUtils.resolveRelativeURI( - source.getSystemId(), uriValues[i + 1]).toString(); - if (schemaRef.startsWith("file") - && !new File(schemaRef).exists() && (null != baseURI)) { - schemaRef = URIUtils.resolveRelativeURI(baseURI, - uriValues[i + 1]).toString(); - } - schemaURI = URI.create(schemaRef); - } else { - schemaURI = URI.create(uriValues[i + 1]); - } - schemaURIs.add(schemaURI); - } - return schemaURIs; - } } diff --git a/src/main/java/org/opengis/cite/geotiff11/util/XMLUtils.java b/src/main/java/org/opengis/cite/geotiff11/util/XMLUtils.java index a7d37d7..4942abd 100644 --- a/src/main/java/org/opengis/cite/geotiff11/util/XMLUtils.java +++ b/src/main/java/org/opengis/cite/geotiff11/util/XMLUtils.java @@ -30,6 +30,11 @@ import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + import net.sf.saxon.s9api.DOMDestination; import net.sf.saxon.s9api.DocumentBuilder; import net.sf.saxon.s9api.Processor; @@ -45,366 +50,330 @@ import net.sf.saxon.s9api.XsltExecutable; import net.sf.saxon.s9api.XsltTransformer; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - /** - * Provides various utility methods for accessing or manipulating XML - * representations. + * Provides various utility methods for accessing or manipulating XML representations. */ public class XMLUtils { - private static final Logger LOGR = Logger.getLogger(XMLUtils.class.getPackage().getName()); - private static final XMLInputFactory STAX_FACTORY = initXMLInputFactory(); - private static final XPathFactory XPATH_FACTORY = initXPathFactory(); + private static final Logger LOGR = Logger.getLogger(XMLUtils.class.getPackage().getName()); + + private static final XMLInputFactory STAX_FACTORY = initXMLInputFactory(); + + private static final XPathFactory XPATH_FACTORY = initXPathFactory(); + + private static XPathFactory initXPathFactory() { + XPathFactory factory = XPathFactory.newInstance(); + return factory; + } - private static XPathFactory initXPathFactory() { - XPathFactory factory = XPathFactory.newInstance(); - return factory; - } + private static XMLInputFactory initXMLInputFactory() { + XMLInputFactory factory = XMLInputFactory.newInstance(); + factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); + return factory; + } - private static XMLInputFactory initXMLInputFactory() { - XMLInputFactory factory = XMLInputFactory.newInstance(); - factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); - return factory; - } + /** + * 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(); - } + /** + * Writes the content of a DOM Node to a byte stream. An XML declaration is always + * omitted. + * @param node The DOM Node to be serialized. + * @param outputStream The destination OutputStream reference. + */ + public static void writeNode(Node node, OutputStream outputStream) { + try { + Transformer idTransformer = TransformerFactory.newInstance().newTransformer(); + Properties outProps = new Properties(); + outProps.setProperty(OutputKeys.METHOD, "xml"); + outProps.setProperty(OutputKeys.ENCODING, "UTF-8"); + outProps.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + outProps.setProperty(OutputKeys.INDENT, "yes"); + idTransformer.setOutputProperties(outProps); + idTransformer.transform(new DOMSource(node), new StreamResult(outputStream)); + } + catch (TransformerException ex) { + String nodeName = (node.getNodeType() == Node.DOCUMENT_NODE) + ? Document.class.cast(node).getDocumentElement().getNodeName() : node.getNodeName(); + TestSuiteLogger.log(Level.WARNING, "Failed to serialize DOM node: " + nodeName, ex); + } + } - /** - * Writes the content of a DOM Node to a byte stream. An XML declaration is - * always omitted. - * - * @param node - * The DOM Node to be serialized. - * @param outputStream - * The destination OutputStream reference. - */ - public static void writeNode(Node node, OutputStream outputStream) { - try { - Transformer idTransformer = TransformerFactory.newInstance().newTransformer(); - Properties outProps = new Properties(); - outProps.setProperty(OutputKeys.METHOD, "xml"); - outProps.setProperty(OutputKeys.ENCODING, "UTF-8"); - outProps.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - outProps.setProperty(OutputKeys.INDENT, "yes"); - idTransformer.setOutputProperties(outProps); - idTransformer.transform(new DOMSource(node), new StreamResult(outputStream)); - } catch (TransformerException ex) { - String nodeName = (node.getNodeType() == Node.DOCUMENT_NODE) - ? Document.class.cast(node).getDocumentElement().getNodeName() : node.getNodeName(); - TestSuiteLogger.log(Level.WARNING, "Failed to serialize DOM node: " + nodeName, ex); - } - } + /** + * Evaluates an XPath 1.0 expression using the given context and returns the result as + * a node set. + * @param context The context node. + * @param expr An XPath expression. + * @param namespaceBindings A collection of namespace bindings for the XPath + * expression, where each entry maps a namespace URI (key) to a prefix (value). + * Standard bindings do not need to be declared (see + * {@link org.opengis.cite.geotiff11.util.NamespaceBindings#withStandardBindings()}. + * @return A NodeList containing nodes that satisfy the expression (it may be empty). + * @throws javax.xml.xpath.XPathExpressionException If the expression cannot be + * evaluated for any reason. + */ + public static NodeList evaluateXPath(Node context, String expr, Map namespaceBindings) + throws XPathExpressionException { + Object result = evaluateXPath(context, expr, namespaceBindings, XPathConstants.NODESET); + if (!NodeList.class.isInstance(result)) { + throw new XPathExpressionException("Expression does not evaluate to a NodeList: " + expr); + } + return (NodeList) result; + } - /** - * Evaluates an XPath 1.0 expression using the given context and returns the - * result as a node set. - * - * @param context - * The context node. - * @param expr - * An XPath expression. - * @param namespaceBindings - * A collection of namespace bindings for the XPath expression, - * where each entry maps a namespace URI (key) to a prefix - * (value). Standard bindings do not need to be declared (see - * {@link NamespaceBindings#withStandardBindings()}. - * @return A NodeList containing nodes that satisfy the expression (it may - * be empty). - * @throws XPathExpressionException - * If the expression cannot be evaluated for any reason. - */ - public static NodeList evaluateXPath(Node context, String expr, Map namespaceBindings) - throws XPathExpressionException { - Object result = evaluateXPath(context, expr, namespaceBindings, XPathConstants.NODESET); - if (!NodeList.class.isInstance(result)) { - throw new XPathExpressionException("Expression does not evaluate to a NodeList: " + expr); - } - return (NodeList) result; - } + /** + * Evaluates an XPath expression using the given context and returns the result as the + * specified type. + * + *

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

    + * @param context The context node. + * @param expr An XPath expression. + * @param namespaceBindings A collection of namespace bindings for the XPath + * expression, where each entry maps a namespace URI (key) to a prefix (value). + * Standard bindings do not need to be declared (see + * {@link org.opengis.cite.geotiff11.util.NamespaceBindings#withStandardBindings()}. + * @param returnType The desired return type (as declared in + * {@link javax.xml.xpath.XPathConstants} ). + * @return The result converted to the desired returnType. + * @throws javax.xml.xpath.XPathExpressionException If the expression cannot be + * evaluated for any reason. + */ + public static Object evaluateXPath(Node context, String expr, Map namespaceBindings, + QName returnType) throws XPathExpressionException { + NamespaceBindings bindings = NamespaceBindings.withStandardBindings(); + bindings.addAllBindings(namespaceBindings); + XPathFactory factory = XPATH_FACTORY; + // WARNING: If context node is Saxon NodeOverNodeInfo, the factory must + // use the same Configuration object to avoid IllegalArgumentException + XPath xpath = factory.newXPath(); + xpath.setNamespaceContext(bindings); + Object result = xpath.evaluate(expr, context, returnType); + return result; + } - /** - * Evaluates an XPath expression using the given context and returns the - * result as the specified type. - * - *

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

    - * - * @param context - * The context node. - * @param expr - * An XPath expression. - * @param namespaceBindings - * A collection of namespace bindings for the XPath expression, - * where each entry maps a namespace URI (key) to a prefix - * (value). Standard bindings do not need to be declared (see - * {@link NamespaceBindings#withStandardBindings()}. - * @param returnType - * The desired return type (as declared in {@link XPathConstants} - * ). - * @return The result converted to the desired returnType. - * @throws XPathExpressionException - * If the expression cannot be evaluated for any reason. - */ - public static Object evaluateXPath(Node context, String expr, Map namespaceBindings, - QName returnType) throws XPathExpressionException { - NamespaceBindings bindings = NamespaceBindings.withStandardBindings(); - bindings.addAllBindings(namespaceBindings); - XPathFactory factory = XPATH_FACTORY; - // WARNING: If context node is Saxon NodeOverNodeInfo, the factory must - // use the same Configuration object to avoid IllegalArgumentException - XPath xpath = factory.newXPath(); - xpath.setNamespaceContext(bindings); - Object result = xpath.evaluate(expr, context, returnType); - return result; - } + /** + * Evaluates an XPath 2.0 expression using the Saxon s9api interfaces. + * @param xmlSource The XML Source. + * @param expr The XPath expression to be evaluated. + * @param nsBindings A collection of namespace bindings required to evaluate the XPath + * expression, where each entry maps a namespace URI (key) to a prefix (value); this + * may be {@code null} if not needed. + * @return An XdmValue object representing a value in the XDM data model; this is a + * sequence of zero or more items, where each item is either an atomic value or a + * node. + * @throws net.sf.saxon.s9api.SaxonApiException If an error occurs while evaluating + * the expression; this always wraps some other underlying exception. + */ + public static XdmValue evaluateXPath2(Source xmlSource, String expr, Map nsBindings) + throws SaxonApiException { + Processor proc = new Processor(false); + XPathCompiler compiler = proc.newXPathCompiler(); + if (null != nsBindings) { + for (String nsURI : nsBindings.keySet()) { + compiler.declareNamespace(nsBindings.get(nsURI), nsURI); + } + } + XPathSelector xpath = compiler.compile(expr).load(); + DocumentBuilder builder = proc.newDocumentBuilder(); + XdmNode node = null; + if (DOMSource.class.isInstance(xmlSource)) { + DOMSource domSource = (DOMSource) xmlSource; + node = builder.wrap(domSource.getNode()); + } + else { + node = builder.build(xmlSource); + } + xpath.setContextItem(node); + return xpath.evaluate(); + } - /** - * Evaluates an XPath 2.0 expression using the Saxon s9api interfaces. - * - * @param xmlSource - * The XML Source. - * @param expr - * The XPath expression to be evaluated. - * @param nsBindings - * A collection of namespace bindings required to evaluate the - * XPath expression, where each entry maps a namespace URI (key) - * to a prefix (value); this may be {@code null} if not needed. - * @return An XdmValue object representing a value in the XDM data model; - * this is a sequence of zero or more items, where each item is - * either an atomic value or a node. - * @throws SaxonApiException - * If an error occurs while evaluating the expression; this - * always wraps some other underlying exception. - */ - public static XdmValue evaluateXPath2(Source xmlSource, String expr, Map nsBindings) - throws SaxonApiException { - Processor proc = new Processor(false); - XPathCompiler compiler = proc.newXPathCompiler(); - if (null != nsBindings) { - for (String nsURI : nsBindings.keySet()) { - compiler.declareNamespace(nsBindings.get(nsURI), nsURI); - } - } - XPathSelector xpath = compiler.compile(expr).load(); - DocumentBuilder builder = proc.newDocumentBuilder(); - XdmNode node = null; - if (DOMSource.class.isInstance(xmlSource)) { - DOMSource domSource = (DOMSource) xmlSource; - node = builder.wrap(domSource.getNode()); - } else { - node = builder.build(xmlSource); - } - xpath.setContextItem(node); - return xpath.evaluate(); - } + /** + * Evaluates an XQuery 1.0 expression using the Saxon s9api interfaces. + * @param source The XML Source. + * @param query The query expression. + * @param nsBindings A collection of namespace bindings required to evaluate the + * query, where each entry maps a namespace URI (key) to a prefix (value). + * @return An XdmValue object representing a value in the XDM data model. + * @throws net.sf.saxon.s9api.SaxonApiException If an error occurs while evaluating + * the query (this always wraps some other underlying exception). + */ + public static XdmValue evaluateXQuery(Source source, String query, Map nsBindings) + throws SaxonApiException { + Processor proc = new Processor(false); + XQueryCompiler xqCompiler = proc.newXQueryCompiler(); + if (null != nsBindings) { + for (String nsURI : nsBindings.keySet()) { + xqCompiler.declareNamespace(nsBindings.get(nsURI), nsURI); + } + } + XQueryExecutable xqExec = xqCompiler.compile(query); + XQueryEvaluator xqEval = xqExec.load(); + xqEval.setSource(source); + return xqEval.evaluate(); + } - /** - * Evaluates an XQuery 1.0 expression using the Saxon s9api interfaces. - * - * @param source - * The XML Source. - * @param query - * The query expression. - * @param nsBindings - * A collection of namespace bindings required to evaluate the - * query, where each entry maps a namespace URI (key) to a prefix - * (value). - * @return An XdmValue object representing a value in the XDM data model. - * @throws SaxonApiException - * If an error occurs while evaluating the query (this always - * wraps some other underlying exception). - */ - public static XdmValue evaluateXQuery(Source source, String query, Map nsBindings) - throws SaxonApiException { - Processor proc = new Processor(false); - XQueryCompiler xqCompiler = proc.newXQueryCompiler(); - if (null != nsBindings) { - for (String nsURI : nsBindings.keySet()) { - xqCompiler.declareNamespace(nsBindings.get(nsURI), nsURI); - } - } - XQueryExecutable xqExec = xqCompiler.compile(query); - XQueryEvaluator xqEval = xqExec.load(); - xqEval.setSource(source); - return xqEval.evaluate(); - } + /** + * Creates a new Element having the specified qualified name. The element must be + * {@link org.w3c.dom.Document#adoptNode(Node) adopted} when inserted into another + * Document. + * @param qName A QName object. + * @return An Element node (with a Document owner but no parent). + */ + public static Element createElement(QName qName) { + Document doc = null; + try { + doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + } + catch (ParserConfigurationException e) { + throw new RuntimeException(e); + } + Element elem = doc.createElementNS(qName.getNamespaceURI(), qName.getLocalPart()); + return elem; + } - /** - * Creates a new Element having the specified qualified name. The element - * must be {@link Document#adoptNode(Node) adopted} when inserted into - * another Document. - * - * @param qName - * A QName object. - * @return An Element node (with a Document owner but no parent). - */ - public static Element createElement(QName qName) { - Document doc = null; - try { - doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); - } catch (ParserConfigurationException e) { - throw new RuntimeException(e); - } - Element elem = doc.createElementNS(qName.getNamespaceURI(), qName.getLocalPart()); - return elem; - } + /** + * Returns a List of all descendant Element nodes having the specified [namespace + * name] property. The elements are listed in document order. + * @param node The node to search from. + * @param namespaceURI An absolute URI denoting a namespace name. + * @return A List containing elements in the specified namespace; the list is empty if + * there are no elements in the namespace. + */ + public static List getElementsByNamespaceURI(Node node, String namespaceURI) { + List list = new ArrayList(); + NodeList children = node.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + Node child = children.item(i); + if (child.getNodeType() != Node.ELEMENT_NODE) + continue; + if (child.getNamespaceURI().equals(namespaceURI)) + list.add((Element) child); + } + return list; + } - /** - * Returns a List of all descendant Element nodes having the specified - * [namespace name] property. The elements are listed in document order. - * - * @param node - * The node to search from. - * @param namespaceURI - * An absolute URI denoting a namespace name. - * @return A List containing elements in the specified namespace; the list - * is empty if there are no elements in the namespace. - */ - public static List getElementsByNamespaceURI(Node node, String namespaceURI) { - List list = new ArrayList(); - NodeList children = node.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - if (child.getNodeType() != Node.ELEMENT_NODE) - continue; - if (child.getNamespaceURI().equals(namespaceURI)) - list.add((Element) child); - } - return list; - } + /** + * Transforms the content of a DOM Node using a specified XSLT stylesheet. + * @param xslt A Source object representing a stylesheet (XSLT 1.0 or 2.0). + * @param source A Node representing the XML source. If it is an Element node it will + * be imported into a new DOM Document. + * @return A DOM Document containing the result of the transformation. + */ + public static Document transform(Source xslt, Node source) { + Document sourceDoc = null; + Document resultDoc = null; + try { + resultDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + if (source.getNodeType() == Node.DOCUMENT_NODE) { + sourceDoc = (Document) source; + } + else { + sourceDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + sourceDoc.appendChild(sourceDoc.importNode(source, true)); + } + } + catch (ParserConfigurationException pce) { + throw new RuntimeException(pce); + } + Processor processor = new Processor(false); + XsltCompiler compiler = processor.newXsltCompiler(); + try { + XsltExecutable exec = compiler.compile(xslt); + XsltTransformer transformer = exec.load(); + transformer.setSource(new DOMSource(sourceDoc)); + transformer.setDestination(new DOMDestination(resultDoc)); + transformer.transform(); + } + catch (SaxonApiException e) { + throw new RuntimeException(e); + } + return resultDoc; + } - /** - * Transforms the content of a DOM Node using a specified XSLT stylesheet. - * - * @param xslt - * A Source object representing a stylesheet (XSLT 1.0 or 2.0). - * @param source - * A Node representing the XML source. If it is an Element node - * it will be imported into a new DOM Document. - * @return A DOM Document containing the result of the transformation. - */ - public static Document transform(Source xslt, Node source) { - Document sourceDoc = null; - Document resultDoc = null; - try { - resultDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); - if (source.getNodeType() == Node.DOCUMENT_NODE) { - sourceDoc = (Document) source; - } else { - sourceDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); - sourceDoc.appendChild(sourceDoc.importNode(source, true)); - } - } catch (ParserConfigurationException pce) { - throw new RuntimeException(pce); - } - Processor processor = new Processor(false); - XsltCompiler compiler = processor.newXsltCompiler(); - try { - XsltExecutable exec = compiler.compile(xslt); - XsltTransformer transformer = exec.load(); - transformer.setSource(new DOMSource(sourceDoc)); - transformer.setDestination(new DOMDestination(resultDoc)); - transformer.transform(); - } catch (SaxonApiException e) { - throw new RuntimeException(e); - } - return resultDoc; - } + /** + * Expands character entity ({@literal &name;}) and numeric references ( + * {@literal &#xhhhh;} or {@literal &dddd;}) that occur within a given string value. + * It may be necessary to do this before processing an XPath expression. + * @param value A string representing text content. + * @return A string with all included references expanded. + */ + public static String expandReferencesInText(String value) { + StringBuilder wrapper = new StringBuilder(""); + wrapper.append(value).append(""); + Reader reader = new StringReader(wrapper.toString()); + String str = null; + try { + XMLStreamReader xsr = STAX_FACTORY.createXMLStreamReader(reader); + xsr.nextTag(); // document element + str = xsr.getElementText(); + } + catch (XMLStreamException xse) { + LOGR.log(Level.WARNING, xse.getMessage(), xse); + } + return str; + } - /** - * Expands character entity ({@literal &name;}) and numeric references ( - * {@literal &#xhhhh;} or {@literal &dddd;}) that occur within a given - * string value. It may be necessary to do this before processing an XPath - * expression. - * - * @param value - * A string representing text content. - * @return A string with all included references expanded. - */ - public static String expandReferencesInText(String value) { - StringBuilder wrapper = new StringBuilder(""); - wrapper.append(value).append(""); - Reader reader = new StringReader(wrapper.toString()); - String str = null; - try { - XMLStreamReader xsr = STAX_FACTORY.createXMLStreamReader(reader); - xsr.nextTag(); // document element - str = xsr.getElementText(); - } catch (XMLStreamException xse) { - LOGR.log(Level.WARNING, xse.getMessage(), xse); - } - return str; - } + /** + * Creates a DOM Document with the given Element as the document element. A deep copy + * of the element is imported; the source element is not altered. + * @param elem An Element node. + * @return A Document node. + */ + public static Document importElement(Element elem) { + javax.xml.parsers.DocumentBuilder docBuilder = null; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + docBuilder = factory.newDocumentBuilder(); + } + catch (ParserConfigurationException ex) { + LOGR.log(Level.WARNING, null, ex); + } + Document newDoc = docBuilder.newDocument(); + Node newNode = newDoc.importNode(elem, true); + newDoc.appendChild(newNode); + return newDoc; + } - /** - * Creates a DOM Document with the given Element as the document element. A - * deep copy of the element is imported; the source element is not altered. - * - * @param elem - * An Element node. - * @return A Document node. - */ - public static Document importElement(Element elem) { - javax.xml.parsers.DocumentBuilder docBuilder = null; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - docBuilder = factory.newDocumentBuilder(); - } catch (ParserConfigurationException ex) { - LOGR.log(Level.WARNING, null, ex); - } - Document newDoc = docBuilder.newDocument(); - Node newNode = newDoc.importNode(elem, true); - newDoc.appendChild(newNode); - return newDoc; - } + /** + * Returns a List view of the nodes in the given NodeList collection. + * @param nodeList An ordered collection of DOM nodes. + * @return A List containing the original sequence of Node objects. + */ + public static List asList(NodeList nodeList) { + List nodes = new ArrayList<>(); + for (int i = 0; i < nodeList.getLength(); i++) { + nodes.add(nodeList.item(i)); + } + return nodes; + } - /** - * Returns a List view of the nodes in the given NodeList collection. - * - * @param nodeList - * An ordered collection of DOM nodes. - * @return A List containing the original sequence of Node objects. - */ - public static List asList(NodeList nodeList) { - List nodes = new ArrayList<>(); - for (int i = 0; i < nodeList.getLength(); i++) { - nodes.add(nodeList.item(i)); - } - return nodes; - } } diff --git a/src/test/java/org/opengis/cite/geotiff11/VerifyETSAssert.java b/src/test/java/org/opengis/cite/geotiff11/VerifyETSAssert.java index d87c9cc..5591741 100644 --- a/src/test/java/org/opengis/cite/geotiff11/VerifyETSAssert.java +++ b/src/test/java/org/opengis/cite/geotiff11/VerifyETSAssert.java @@ -4,6 +4,7 @@ import java.net.URL; import java.util.HashMap; import java.util.Map; + import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -12,6 +13,7 @@ import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; + import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; @@ -21,53 +23,53 @@ public class VerifyETSAssert { - private static final String WADL_NS = "http://wadl.dev.java.net/2009/02"; - private static DocumentBuilder docBuilder; - private static SchemaFactory factory; - @Rule - public ExpectedException thrown = ExpectedException.none(); + private static final String WADL_NS = "http://wadl.dev.java.net/2009/02"; + + private static DocumentBuilder docBuilder; + + private static SchemaFactory factory; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + public VerifyETSAssert() { + } - public VerifyETSAssert() { - } + @BeforeClass + public static void setUpClass() throws ParserConfigurationException { + factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + docBuilder = dbf.newDocumentBuilder(); + } - @BeforeClass - public static void setUpClass() throws ParserConfigurationException { - factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - docBuilder = dbf.newDocumentBuilder(); - } + @Test + public void validateUsingSchemaHints_expect2Errors() throws SAXException { + thrown.expect(AssertionError.class); + thrown.expectMessage("2 schema validation error(s) detected"); + URL url = this.getClass().getResource("/Gamma.xml"); + Schema schema = factory.newSchema(); + Validator validator = schema.newValidator(); + ETSAssert.assertSchemaValid(validator, new StreamSource(url.toString())); + } - @Test - public void validateUsingSchemaHints_expect2Errors() throws SAXException { - thrown.expect(AssertionError.class); - thrown.expectMessage("2 schema validation error(s) detected"); - URL url = this.getClass().getResource("/Gamma.xml"); - Schema schema = factory.newSchema(); - Validator validator = schema.newValidator(); - ETSAssert - .assertSchemaValid(validator, new StreamSource(url.toString())); - } + @Test + public void assertXPathWithNamespaceBindings() throws SAXException, IOException { + Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/capabilities-simple.xml")); + Map nsBindings = new HashMap(); + nsBindings.put(WADL_NS, "ns1"); + String xpath = "//ns1:resources"; + ETSAssert.assertXPath(xpath, doc, nsBindings); + } - @Test - public void assertXPathWithNamespaceBindings() throws SAXException, - IOException { - Document doc = docBuilder.parse(this.getClass().getResourceAsStream( - "/capabilities-simple.xml")); - Map nsBindings = new HashMap(); - nsBindings.put(WADL_NS, "ns1"); - String xpath = "//ns1:resources"; - ETSAssert.assertXPath(xpath, doc, nsBindings); - } + @Test + public void assertXPath_expectFalse() throws SAXException, IOException { + thrown.expect(AssertionError.class); + thrown.expectMessage("Unexpected result evaluating XPath expression"); + Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/capabilities-simple.xml")); + // using built-in namespace binding + String xpath = "//ows:OperationsMetadata/ows:Constraint[@name='XMLEncoding']/ows:DefaultValue = 'TRUE'"; + ETSAssert.assertXPath(xpath, doc, null); + } - @Test - public void assertXPath_expectFalse() throws SAXException, IOException { - thrown.expect(AssertionError.class); - thrown.expectMessage("Unexpected result evaluating XPath expression"); - Document doc = docBuilder.parse(this.getClass().getResourceAsStream( - "/capabilities-simple.xml")); - // using built-in namespace binding - String xpath = "//ows:OperationsMetadata/ows:Constraint[@name='XMLEncoding']/ows:DefaultValue = 'TRUE'"; - ETSAssert.assertXPath(xpath, doc, null); - } } diff --git a/src/test/java/org/opengis/cite/geotiff11/VerifySuiteFixtureListener.java b/src/test/java/org/opengis/cite/geotiff11/VerifySuiteFixtureListener.java index 495dec0..e8a96cb 100644 --- a/src/test/java/org/opengis/cite/geotiff11/VerifySuiteFixtureListener.java +++ b/src/test/java/org/opengis/cite/geotiff11/VerifySuiteFixtureListener.java @@ -15,58 +15,58 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.mockito.Matchers; +import org.mockito.ArgumentMatchers; import org.testng.ISuite; import org.testng.xml.XmlSuite; public class VerifySuiteFixtureListener { - private static XmlSuite xmlSuite; - private static ISuite suite; + private static XmlSuite xmlSuite; - public VerifySuiteFixtureListener() { - } + private static ISuite suite; - @BeforeClass - public static void setUpClass() { - xmlSuite = mock(XmlSuite.class); - suite = mock(ISuite.class); - when(suite.getXmlSuite()).thenReturn(xmlSuite); - } + public VerifySuiteFixtureListener() { + } - @AfterClass - public static void tearDownClass() { - } + @BeforeClass + public static void setUpClass() { + xmlSuite = mock(XmlSuite.class); + suite = mock(ISuite.class); + when(suite.getXmlSuite()).thenReturn(xmlSuite); + } - @Before - public void setUp() { - } + @AfterClass + public static void tearDownClass() { + } - @After - public void tearDown() { - } + @Before + public void setUp() { + } - @Test(expected = IllegalArgumentException.class) - public void noSuiteParameters() { - Map params = new HashMap(); - when(xmlSuite.getParameters()).thenReturn(params); - SuiteFixtureListener iut = new SuiteFixtureListener(); - iut.onStart(suite); - } + @After + public void tearDown() { + } - @Test - public void processIUTParameter() throws URISyntaxException { - // URL url = this.getClass().getResource("/atom-feed.xml"); - // redirect to tif - URL url = this.getClass().getResource("/tif/cea.tif"); - Map params = new HashMap(); - params.put(TestRunArg.IUT.toString(), url.toURI().toString()); - when(xmlSuite.getParameters()).thenReturn(params); - SuiteFixtureListener iut = new SuiteFixtureListener(); - iut.onStart(suite); - verify(suite).setAttribute( - Matchers.eq(SuiteAttribute.TEST_SUBJ_FILE.getName()), - Matchers.isA(File.class)); - } + @Test(expected = IllegalArgumentException.class) + public void noSuiteParameters() { + Map params = new HashMap(); + when(xmlSuite.getParameters()).thenReturn(params); + SuiteFixtureListener iut = new SuiteFixtureListener(); + iut.onStart(suite); + } + + @Test + public void processIUTParameter() throws URISyntaxException { + // URL url = this.getClass().getResource("/atom-feed.xml"); + // redirect to tif + URL url = this.getClass().getResource("/tif/cea.tif"); + Map params = new HashMap(); + params.put(TestRunArg.IUT.toString(), url.toURI().toString()); + when(xmlSuite.getParameters()).thenReturn(params); + SuiteFixtureListener iut = new SuiteFixtureListener(); + iut.onStart(suite); + verify(suite).setAttribute(ArgumentMatchers.eq(SuiteAttribute.TEST_SUBJ_FILE.getName()), + ArgumentMatchers.isA(File.class)); + } } diff --git a/src/test/java/org/opengis/cite/geotiff11/VerifyTestNGController.java b/src/test/java/org/opengis/cite/geotiff11/VerifyTestNGController.java index 178e05e..5a9a24f 100644 --- a/src/test/java/org/opengis/cite/geotiff11/VerifyTestNGController.java +++ b/src/test/java/org/opengis/cite/geotiff11/VerifyTestNGController.java @@ -21,46 +21,42 @@ /** * Verifies the results of executing a test run using the main controller * (TestNGController). - * + * */ public class VerifyTestNGController { - private static DocumentBuilder docBuilder; - private Properties testRunProps; + private static DocumentBuilder docBuilder; + + private Properties testRunProps; + + @BeforeClass + public static void initParser() throws ParserConfigurationException { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setValidating(false); + dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); + docBuilder = dbf.newDocumentBuilder(); + } + + @Before + public void loadDefaultTestRunProperties() throws InvalidPropertiesFormatException, IOException { + this.testRunProps = new Properties(); + this.testRunProps.loadFromXML(getClass().getResourceAsStream("/test-run-props.xml")); + } + + @Test + public void doTestRun() throws Exception { + // URL testSubject = getClass().getResource("/atom-feed-2.xml"); + // redirect to tif + URL testSubject = getClass().getResource("/tif/cea.tif"); + this.testRunProps.setProperty(TestRunArg.IUT.toString(), testSubject.toURI().toString()); + ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024); + this.testRunProps.storeToXML(outStream, "Integration test"); + Document testRunArgs = docBuilder.parse(new ByteArrayInputStream(outStream.toByteArray())); + System.out.println(testRunArgs); + TestNGController controller = new TestNGController(); + Source results = controller.doTestRun(testRunArgs); + Assert.assertNotNull(results); + } - @BeforeClass - public static void initParser() throws ParserConfigurationException { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setValidating(false); - dbf.setFeature( - "http://apache.org/xml/features/nonvalidating/load-external-dtd", - false); - docBuilder = dbf.newDocumentBuilder(); - } - - @Before - public void loadDefaultTestRunProperties() - throws InvalidPropertiesFormatException, IOException { - this.testRunProps = new Properties(); - this.testRunProps.loadFromXML(getClass().getResourceAsStream( - "/test-run-props.xml")); - } - - @Test - public void doTestRun() throws Exception { - //URL testSubject = getClass().getResource("/atom-feed-2.xml"); - // redirect to tif - URL testSubject = getClass().getResource("/tif/cea.tif"); - this.testRunProps.setProperty(TestRunArg.IUT.toString(), testSubject - .toURI().toString()); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024); - this.testRunProps.storeToXML(outStream, "Integration test"); - Document testRunArgs = docBuilder.parse(new ByteArrayInputStream( - outStream.toByteArray())); - System.out.println(testRunArgs); - TestNGController controller = new TestNGController(); - Source results = controller.doTestRun(testRunArgs); - Assert.assertNotNull(results); - } } diff --git a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyAsciiParamsTests.java b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyAsciiParamsTests.java index df32869..838d650 100644 --- a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyAsciiParamsTests.java +++ b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyAsciiParamsTests.java @@ -4,6 +4,7 @@ import static org.mockito.Mockito.when; import java.io.InputStream; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.experimental.theories.Theories; @@ -14,26 +15,26 @@ import org.testng.ITestContext; /** - * Verifies the behavior of the TiffTagsTests test class. Test stubs replace - * fixture constituents where appropriate. + * Verifies the behavior of the TiffTagsTests test class. Test stubs replace fixture + * constituents where appropriate. */ @RunWith(Theories.class) -public class VerifyAsciiParamsTests extends CreateDataSets{ +public class VerifyAsciiParamsTests extends CreateDataSets { // TODO: this should be expanded greatly... - + private static ITestContext testContext; + AsciiParamsTests iut; public VerifyAsciiParamsTests() { } - - private void dataSetSetUp(InputStream inputStream) - { + + private void dataSetSetUp(InputStream inputStream) { testDataSets(inputStream); iut = new AsciiParamsTests(); } - + @BeforeClass public static void setUpClass() throws Exception { testContext = mock(ITestContext.class); @@ -42,75 +43,77 @@ public static void setUpClass() throws Exception { } @AfterClass - public static void tearDownClass() throws Exception { } - + public static void tearDownClass() throws Exception { + } + @Theory public void verifyGTCitationGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.setUpAsciiParamsSet(); iut.verifyGTCitationGeoKey(); } - + @Theory public void verifyGeodeticCitationGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.setUpAsciiParamsSet(); iut.verifyGeodeticCitationGeoKey(); } - + @Theory public void verifyProjectedCitationGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.setUpAsciiParamsSet(); iut.verifyProjectedCitationGeoKey(); } - + @Theory public void verifyVerticalCitationGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.setUpAsciiParamsSet(); iut.verifyVerticalCitationGeoKey(); } - + @Theory public void verifyGeoAsciiParamsTagCount(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.setUpAsciiParamsSet(); iut.verifyGeoAsciiParamsTagCount(); } - + @Theory public void verifyGeoAsciiParamsTagType(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.setUpAsciiParamsSet(); iut.verifyGeoAsciiParamsTagType(); } - + @Theory public void verifyGeoAsciiParamsTagNULLWrite(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.setUpAsciiParamsSet(); iut.verifyGeoAsciiParamsTagNULLWrite(); } + } \ No newline at end of file diff --git a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyDoubleParamsTests.java b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyDoubleParamsTests.java index f42613c..e5c8343 100644 --- a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyDoubleParamsTests.java +++ b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyDoubleParamsTests.java @@ -2,38 +2,42 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + import java.io.InputStream; + import org.junit.AfterClass; import org.junit.BeforeClass; -import org.junit.experimental.theories.*; +import org.junit.experimental.theories.Theories; +import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.opengis.cite.geotiff11.util.CreateDataSets; import org.testng.ISuite; import org.testng.ITestContext; /** - * Verifies the behavior of the TiffTagsTests test class. Test stubs replace - * fixture constituents where appropriate. + * Verifies the behavior of the TiffTagsTests test class. Test stubs replace fixture + * constituents where appropriate. */ @RunWith(Theories.class) -public class VerifyDoubleParamsTests extends CreateDataSets{ +public class VerifyDoubleParamsTests extends CreateDataSets { // TODO: this should be expanded greatly... - + private static ITestContext testContext; + DoubleParamsTests iut; - + public VerifyDoubleParamsTests() { // This is the code for setting up the objects for the environment. - // The code should be parallel with processSuiteParameters(ISuite suite) in SuiteFixtureListener.java + // The code should be parallel with processSuiteParameters(ISuite suite) in + // SuiteFixtureListener.java } - - private void dataSetSetUp(InputStream inputStream) - { + + private void dataSetSetUp(InputStream inputStream) { testDataSets(inputStream); iut = new DoubleParamsTests(); } - + @BeforeClass public static void setUpClass() throws Exception { testContext = mock(ITestContext.class); @@ -42,104 +46,106 @@ public static void setUpClass() throws Exception { } @AfterClass - public static void tearDownClass() throws Exception { } - + public static void tearDownClass() throws Exception { + } + @Theory public void verifyGeogLinearUnitSizeGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyGeogLinearUnitSizeGeoKey(); } - + @Theory public void verifyGeogAngularUnitSizeGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyGeogAngularUnitSizeGeoKey(); } - + @Theory public void verifyEllipsoidSemiMajorAxisGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyEllipsoidSemiMajorAxisGeoKey(); } - + @Theory public void verifyEllipsoidSemiMinorAxisGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyEllipsoidSemiMinorAxisGeoKey(); } - + @Theory public void verifyEllipsoidInvFlatteningGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyEllipsoidInvFlatteningGeoKey(); } - + @Theory public void verifyPrimeMeridianLongitudeGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyPrimeMeridianLongitudeGeoKey(); } - + @Theory public void verifyProjLinearUnitSizeGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyProjLinearUnitSizeGeoKey(); } - + @Theory public void verifyProjScalarParameters(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyProjScalarParameters(); } - + @Theory public void verifyProjAzimuthAngleGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyProjAzimuthAngleGeoKey(); } - + @Theory public void verifyProjAngularParameters(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyProjAngularParameters(); } - + @Theory public void verifyProjLinearParameters(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyProjLinearParameters(); } + } \ No newline at end of file diff --git a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyGeoKeyDirectoryTests.java b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyGeoKeyDirectoryTests.java index 07855dd..92197a5 100644 --- a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyGeoKeyDirectoryTests.java +++ b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyGeoKeyDirectoryTests.java @@ -4,6 +4,7 @@ import static org.mockito.Mockito.when; import java.io.InputStream; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.experimental.theories.Theories; @@ -14,25 +15,24 @@ import org.testng.ITestContext; /** - * Verifies the behavior of the TiffTagsTests test class. Test stubs replace - * fixture constituents where appropriate. + * Verifies the behavior of the TiffTagsTests test class. Test stubs replace fixture + * constituents where appropriate. */ @RunWith(Theories.class) -public class VerifyGeoKeyDirectoryTests extends CreateDataSets{ +public class VerifyGeoKeyDirectoryTests extends CreateDataSets { private static ITestContext testContext; + GeoKeyDirectoryTests iut; public VerifyGeoKeyDirectoryTests() { } - - private void dataSetSetUp(InputStream inputStream) - { + + private void dataSetSetUp(InputStream inputStream) { testDataSets(inputStream); iut = new GeoKeyDirectoryTests(); } - - + @BeforeClass public static void setUpClass() throws Exception { testContext = mock(ITestContext.class); @@ -42,15 +42,16 @@ public static void setUpClass() throws Exception { @AfterClass public static void tearDownClass() throws Exception { - + } - + @Theory public void verifyTiffTags(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut = new GeoKeyDirectoryTests(); iut.obtainTestSubject(testContext); iut.verifyGeoKeyDirectory(); } + } diff --git a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyMiscFailTests.java b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyMiscFailTests.java index a2cbe56..4a8c225 100644 --- a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyMiscFailTests.java +++ b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyMiscFailTests.java @@ -15,32 +15,36 @@ import org.testng.ITestContext; /** - * Verifies the behavior of the TiffTagsTests test class. Test stubs replace - * fixture constituents where appropriate. + * Verifies the behavior of the TiffTagsTests test class. Test stubs replace fixture + * constituents where appropriate. */ public class VerifyMiscFailTests { // TODO: this should be expanded greatly... - private static ITestContext testContext; - ShortParamsTests iut; + private static ITestContext testContext; + + ShortParamsTests iut; + private static final String SUBJ = "testSubject"; + protected static ISuite suite; public VerifyMiscFailTests() { // This is the code for setting up the objects for the environment. - // The code should be parallel with processSuiteParameters(ISuite suite) in SuiteFixtureListener.java - //The below is specifically for those test cases that should fail. - InputStream inputStream = this.getClass().getResourceAsStream("/tif/MiscFailValues.txt"); + // The code should be parallel with processSuiteParameters(ISuite suite) in + // SuiteFixtureListener.java + // The below is specifically for those test cases that should fail. + InputStream inputStream = this.getClass().getResourceAsStream("/tif/MiscFailValues.txt"); try { when(suite.getAttribute(SUBJ)).thenReturn(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - } catch (IOException e) { + } + catch (IOException e) { e.printStackTrace(); } - iut = new ShortParamsTests(); + iut = new ShortParamsTests(); } - @BeforeClass public static void setUpClass() throws Exception { testContext = mock(ITestContext.class); @@ -50,50 +54,51 @@ public static void setUpClass() throws Exception { @AfterClass public static void tearDownClass() throws Exception { - + } - - /* + + /* * A VerticalUnitsGeoKey value of 32767 (user defined) SHALL not be used + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyVerticalUnitsGeoKeyFail() throws Exception { + public void verifyVerticalUnitsGeoKeyFail() throws Exception { iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyVerticalUnitsGeoKey(); } - - /* - * If the EllipsoidGeoKey value is 32767 (User-Defined) then the - * GTCitationGeoKey and the EllipsoidSemiMajorAxisGeoKey SHALL be - * populated together with the one of either the EllipsoidSemiMinorAxisGeoKey - * or the EllipsoidInvFlatteningGeoKey - * [test case for both of them there (this one should fail) + + /* + * If the EllipsoidGeoKey value is 32767 (User-Defined) then the GTCitationGeoKey and + * the EllipsoidSemiMajorAxisGeoKey SHALL be populated together with the one of either + * the EllipsoidSemiMinorAxisGeoKey or the EllipsoidInvFlatteningGeoKey [test case for + * both of them there (this one should fail) + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyEllipsoidGeoKeyFail() throws Exception { + public void verifyEllipsoidGeoKeyFail() throws Exception { iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyEllipsoidGeoKey(); } - - - /* - * NULL (ASCII code = 0) characters SHALL not be present in the string content written in the GeoAsciiParamsTag + + /* + * NULL (ASCII code = 0) characters SHALL not be present in the string content written + * in the GeoAsciiParamsTag + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyGeoAsciiParamsTagNULLWriteFail() throws Exception { + public void verifyGeoAsciiParamsTagNULLWriteFail() throws Exception { AsciiParamsTests iut2 = new AsciiParamsTests(); - iut2 = new AsciiParamsTests(); - + iut2 = new AsciiParamsTests(); + iut2.obtainTestSubject(testContext); iut2.setUpGeoKeyDirectory(); iut2.setUpAsciiParamsSet(); iut2.verifyGeoAsciiParamsTagNULLWrite(); } - } \ No newline at end of file diff --git a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyObsoleteShortParamsTests.java b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyObsoleteShortParamsTests.java index f269f6e..199f7ca 100644 --- a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyObsoleteShortParamsTests.java +++ b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyObsoleteShortParamsTests.java @@ -15,32 +15,36 @@ import org.testng.ITestContext; /** - * Verifies the behavior of the TiffTagsTests test class. Test stubs replace - * fixture constituents where appropriate. + * Verifies the behavior of the TiffTagsTests test class. Test stubs replace fixture + * constituents where appropriate. */ public class VerifyObsoleteShortParamsTests { // TODO: this should be expanded greatly... - private static ITestContext testContext; - ShortParamsTests iut; + private static ITestContext testContext; + + ShortParamsTests iut; + private static final String SUBJ = "testSubject"; + protected static ISuite suite; public VerifyObsoleteShortParamsTests() { // This is the code for setting up the objects for the environment. - // The code should be parallel with processSuiteParameters(ISuite suite) in SuiteFixtureListener.java - //The below is specifically for those test cases that should fail. - InputStream inputStream = this.getClass().getResourceAsStream("/tif/ObsoleteValues.txt"); + // The code should be parallel with processSuiteParameters(ISuite suite) in + // SuiteFixtureListener.java + // The below is specifically for those test cases that should fail. + InputStream inputStream = this.getClass().getResourceAsStream("/tif/ObsoleteValues.txt"); try { when(suite.getAttribute(SUBJ)).thenReturn(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - } catch (IOException e) { + } + catch (IOException e) { e.printStackTrace(); } - iut = new ShortParamsTests(); + iut = new ShortParamsTests(); } - @BeforeClass public static void setUpClass() throws Exception { testContext = mock(ITestContext.class); @@ -50,65 +54,71 @@ public static void setUpClass() throws Exception { @AfterClass public static void tearDownClass() throws Exception { - + } - - /* - * ProjectedCRSGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POC Datum Codes. + + /* + * ProjectedCRSGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POC Datum + * Codes. + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyProjectedCRSGeoKeyObsolete() throws Exception { + public void verifyProjectedCRSGeoKeyObsolete() throws Exception { iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyProjectedCRSGeoKey(); } - - /* - * GeodeticCRSGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POC Geographic Codes + + /* + * GeodeticCRSGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POC Geographic + * Codes + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyGeodeticCRSGeoKeyObsolete() throws Exception { + public void verifyGeodeticCRSGeoKeyObsolete() throws Exception { iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyGeodeticCRSGeoKey(); } - - /* - * GeodeticDatumGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POS Datum Codes. + + /* + * GeodeticDatumGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POS Datum + * Codes. + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyGeodeticDatumGeoKeyObsolete() throws Exception { + public void verifyGeodeticDatumGeoKeyObsolete() throws Exception { iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyGeodeticDatumGeoKey(); } - - /* - * PrimeMeridianGeoKey values in the range 1-100 SHALL be obsolete EPSG/POSC Datum Codes + + /* + * PrimeMeridianGeoKey values in the range 1-100 SHALL be obsolete EPSG/POSC Datum + * Codes + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyPrimeMeridianGeoKeyObsolete() throws Exception { + public void verifyPrimeMeridianGeoKeyObsolete() throws Exception { iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyPrimeMeridianGeoKey(); } - - /* + + /* * EllipsoidGeoKey values in the range 1-1000 SHALL be obsolete EPSG/POSC Datum Codes + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyEllipsoidGeoKeyObsolete() throws Exception { + public void verifyEllipsoidGeoKeyObsolete() throws Exception { iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyEllipsoidGeoKey(); } - - - } \ No newline at end of file diff --git a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyReservedShortParamsTests.java b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyReservedShortParamsTests.java index ec2ec55..31e7414 100644 --- a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyReservedShortParamsTests.java +++ b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyReservedShortParamsTests.java @@ -15,32 +15,36 @@ import org.testng.ITestContext; /** - * Verifies the behavior of the TiffTagsTests test class. Test stubs replace - * fixture constituents where appropriate. + * Verifies the behavior of the TiffTagsTests test class. Test stubs replace fixture + * constituents where appropriate. */ public class VerifyReservedShortParamsTests { // TODO: this should be expanded greatly... - private static ITestContext testContext; - ShortParamsTests iutReserved; + private static ITestContext testContext; + + ShortParamsTests iutReserved; + private static final String SUBJ = "testSubject"; + protected static ISuite suite; public VerifyReservedShortParamsTests() { // This is the code for setting up the objects for the environment. - // The code should be parallel with processSuiteParameters(ISuite suite) in SuiteFixtureListener.java - //The below is specifically for those test cases that should fail. - InputStream inputStream = this.getClass().getResourceAsStream("/tif/ReservedValues.txt"); + // The code should be parallel with processSuiteParameters(ISuite suite) in + // SuiteFixtureListener.java + // The below is specifically for those test cases that should fail. + InputStream inputStream = this.getClass().getResourceAsStream("/tif/ReservedValues.txt"); try { when(suite.getAttribute(SUBJ)).thenReturn(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); - } catch (IOException e) { + } + catch (IOException e) { e.printStackTrace(); } - iutReserved = new ShortParamsTests(); + iutReserved = new ShortParamsTests(); } - @BeforeClass public static void setUpClass() throws Exception { testContext = mock(ITestContext.class); @@ -50,190 +54,201 @@ public static void setUpClass() throws Exception { @AfterClass public static void tearDownClass() throws Exception { - + } - + /** - * Use mockito to define value within the reserved range (4-32766) - * and to expect an assertion error + * Use mockito to define value within the reserved range (4-32766) and to expect an + * assertion error * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyGTModelTypeGeoKeyReserved() throws Exception { + public void verifyGTModelTypeGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyGTModelTypeGeoKey(); } - + /** - * Use mockito to define value within the reserved range (3-32766) - * and to expect an assertion error + * Use mockito to define value within the reserved range (3-32766) and to expect an + * assertion error * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyGTRasterTypeGeoKeyReserved() throws Exception { + public void verifyGTRasterTypeGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyGTRasterTypeGeoKey(); } - - /* - * Use mockito to define value within the reserved range (1001-1023) - * and to expect an assertion error + + /* + * Use mockito to define value within the reserved range (1001-1023) and to expect an + * assertion error + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyProjectedCRSGeoKeyReserved() throws Exception { + public void verifyProjectedCRSGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyProjectedCRSGeoKey(); } - - /* - * Use mockito to define value within the reserved range (28 to 32766) - * and to expect an assertion error + + /* + * Use mockito to define value within the reserved range (28 to 32766) and to expect + * an assertion error + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyProjMethodGeoKeyReserved() throws Exception { + public void verifyProjMethodGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyProjMethodGeoKey(); } - - /* - * Use mockito to define value within the reserved range (1001-1023) - * and to expect an assertion error + + /* + * Use mockito to define value within the reserved range (1001-1023) and to expect an + * assertion error + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyGeodeticCRSGeoKeyReserved() throws Exception { + public void verifyGeodeticCRSGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyGeodeticCRSGeoKey(); } - /* - * Use mockito to define value within the reserved range (1-1023) - * and to expect an assertion error + /* + * Use mockito to define value within the reserved range (1-1023) and to expect an + * assertion error + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyVerticalGeoKeyReserved() throws Exception { + public void verifyVerticalGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyVerticalGeoKey(); } - - /* - * Use mockito to define value within the reserved range (1-1023) - * and to expect an assertion error + + /* + * Use mockito to define value within the reserved range (1-1023) and to expect an + * assertion error + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyVerticalDatumGeoKeyReserved() throws Exception { + public void verifyVerticalDatumGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyVerticalDatumGeoKey(); } - - /* - * Use mockito to define value within the reserved range (1-1023) - * and to expect an assertion error + + /* + * Use mockito to define value within the reserved range (1-1023) and to expect an + * assertion error + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyGeogAngularUnitsGeoKeyReserved() throws Exception { + public void verifyGeogAngularUnitsGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyGeogAngularUnitsGeoKey(); } - - /* - * Use mockito to define value within the reserved range (1-1023) - * and to expect an assertion error + + /* + * Use mockito to define value within the reserved range (1-1023) and to expect an + * assertion error + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyGeogAzimuthUnitsGeoKeyReserved() throws Exception { + public void verifyGeogAzimuthUnitsGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyGeogAzimuthUnitsGeoKey(); } - - /* - * Use mockito to define value within the reserved range (1-1023) - * and to expect an assertion error + + /* + * Use mockito to define value within the reserved range (1-1023) and to expect an + * assertion error + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyGeogLinearUnitsGeoKeyReserved() throws Exception { + public void verifyGeogLinearUnitsGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyGeogLinearUnitsGeoKey(); } - - /* - * Use mockito to define value within the reserved range (1-1023) - * and to expect an assertion error + + /* + * Use mockito to define value within the reserved range (1-1023) and to expect an + * assertion error + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyProjLinearUnitsGeoKeyReserved() throws Exception { + public void verifyProjLinearUnitsGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyProjLinearUnitsGeoKey(); } - - /* - * Use mockito to define value within the reserved range (1-1023) - * and to expect an assertion error + + /* + * Use mockito to define value within the reserved range (1-1023) and to expect an + * assertion error + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyVerticalUnitsGeoKeyReserved() throws Exception { + public void verifyVerticalUnitsGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyVerticalUnitsGeoKey(); } - - /* - * Use mockito to define value within the reserved range (1001-1023) - * and to expect an assertion error + + /* + * Use mockito to define value within the reserved range (1001-1023) and to expect an + * assertion error + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyGeodeticDatumGeoKeyReserved() throws Exception { + public void verifyGeodeticDatumGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyGeodeticDatumGeoKey(); } - - /* - * Use mockito to define value within the reserved range (101-1023) - * and to expect an assertion error + + /* + * Use mockito to define value within the reserved range (101-1023) and to expect an + * assertion error + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyPrimeMeridianGeoKeyReserved() throws Exception { + public void verifyPrimeMeridianGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyPrimeMeridianGeoKey(); } - - /* - * Use mockito to define value within the reserved range (1-1023) - * and to expect an assertion error + + /* + * Use mockito to define value within the reserved range (1-1023) and to expect an + * assertion error + * * @throws Exception */ @Test(expected = AssertionError.class) - public void verifyProjectionGeoKeyReserved() throws Exception { + public void verifyProjectionGeoKeyReserved() throws Exception { iutReserved.obtainTestSubject(testContext); iutReserved.setUpGeoKeyDirectory(); iutReserved.verifyProjectionGeoKey(); } - - } \ No newline at end of file diff --git a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyShortParamsTests.java b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyShortParamsTests.java index 2054413..da47e1c 100644 --- a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyShortParamsTests.java +++ b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyShortParamsTests.java @@ -4,41 +4,40 @@ import static org.mockito.Mockito.when; import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import org.apache.commons.io.IOUtils; import org.junit.AfterClass; import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.theories.*; +import org.junit.experimental.theories.Theories; +import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.opengis.cite.geotiff11.util.CreateDataSets; import org.testng.ISuite; import org.testng.ITestContext; /** - * Verifies the behavior of the TiffTagsTests test class. Test stubs replace - * fixture constituents where appropriate. + * Verifies the behavior of the TiffTagsTests test class. Test stubs replace fixture + * constituents where appropriate. */ @RunWith(Theories.class) public class VerifyShortParamsTests extends CreateDataSets { // TODO: this should be expanded greatly... - private static ITestContext testContext; + private static ITestContext testContext; + ShortParamsTests iut; public VerifyShortParamsTests() { // This is the code for setting up the objects for the environment. - // The code should be parallel with processSuiteParameters(ISuite suite) in SuiteFixtureListener.java + // The code should be parallel with processSuiteParameters(ISuite suite) in + // SuiteFixtureListener.java } - private void dataSetSetUp(InputStream inputStream) - { + private void dataSetSetUp(InputStream inputStream) { testDataSets(inputStream); iut = new ShortParamsTests(); } - + @BeforeClass public static void setUpClass() throws Exception { testContext = mock(ITestContext.class); @@ -48,150 +47,151 @@ public static void setUpClass() throws Exception { @AfterClass public static void tearDownClass() throws Exception { - - } - -// @Theory -// public void verifyGTModelTypeGeoKey(InputStream inputStream) throws Exception { -// dataSetSetUp(inputStream); -// -// iut.obtainTestSubject(testContext); -// iut.setUpGeoKeyDirectory(); -// iut.verifyGTModelTypeGeoKey(); -// } - + + } + + // @Theory + // public void verifyGTModelTypeGeoKey(InputStream inputStream) throws Exception { + // dataSetSetUp(inputStream); + // + // iut.obtainTestSubject(testContext); + // iut.setUpGeoKeyDirectory(); + // iut.verifyGTModelTypeGeoKey(); + // } + @Theory public void verifyGTRasterTypeGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyGTRasterTypeGeoKey(); } - + @Theory public void verifyGeodeticCRSGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyGeodeticCRSGeoKey(); } - + @Theory public void verifyGeodeticDatumGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyGeodeticDatumGeoKey(); } - + @Theory public void verifyPrimeMeridianGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyPrimeMeridianGeoKey(); } - + @Theory public void verifyGeogLinearUnitsGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyGeogLinearUnitsGeoKey(); } - + @Theory public void verifyGeogAngularUnitsGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyGeogAngularUnitsGeoKey(); } - + @Theory public void verifyEllipsoidGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyEllipsoidGeoKey(); } - + @Theory public void verifyGeogAzimuthUnitsGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyGeogAzimuthUnitsGeoKey(); } - + @Theory public void verifyProjectedCRSGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyProjectedCRSGeoKey(); } - + @Theory public void verifyProjectionGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyProjectionGeoKey(); } - + @Theory public void verifyProjMethodGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyProjMethodGeoKey(); } - + @Theory public void verifyProjLinearUnitsGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyProjLinearUnitsGeoKey(); } - + @Theory public void verifyVerticalUnitsGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyVerticalUnitsGeoKey(); } - + @Theory public void verifyVerticalGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyVerticalGeoKey(); } - + @Theory public void verifyVerticalDatumGeoKey(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut.obtainTestSubject(testContext); iut.setUpGeoKeyDirectory(); iut.verifyVerticalDatumGeoKey(); } + } \ No newline at end of file diff --git a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyTiffCoreTests.java b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyTiffCoreTests.java index 446a9c3..4de79c2 100644 --- a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyTiffCoreTests.java +++ b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyTiffCoreTests.java @@ -4,6 +4,7 @@ import static org.mockito.Mockito.when; import java.io.InputStream; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.experimental.theories.Theories; @@ -14,24 +15,24 @@ import org.testng.ITestContext; /** - * Verifies the behavior of the TiffCoreTests test class. Test stubs replace - * fixture constituents where appropriate. + * Verifies the behavior of the TiffCoreTests test class. Test stubs replace fixture + * constituents where appropriate. */ @RunWith(Theories.class) -public class VerifyTiffCoreTests extends CreateDataSets{ +public class VerifyTiffCoreTests extends CreateDataSets { private static ITestContext testContext; + TiffCoreTests iut; public VerifyTiffCoreTests() { } - - private void dataSetSetUp(InputStream inputStream) - { + + private void dataSetSetUp(InputStream inputStream) { testDataSets(inputStream); iut = new TiffCoreTests(); } - + @BeforeClass public static void setUpClass() throws Exception { testContext = mock(ITestContext.class); @@ -41,13 +42,13 @@ public static void setUpClass() throws Exception { @AfterClass public static void tearDownClass() throws Exception { - + } - + @Theory public void verifyTiffVersion(InputStream inputStream) { dataSetSetUp(inputStream); - + iut = new TiffCoreTests(); iut.obtainTestSubject(testContext); iut.verifyTiffVersion(); @@ -56,9 +57,10 @@ public void verifyTiffVersion(InputStream inputStream) { @Theory public void verifyTiffEndianness(InputStream inputStream) { dataSetSetUp(inputStream); - + iut = new TiffCoreTests(); iut.obtainTestSubject(testContext); - iut.verifyTiffEndianness(); + iut.verifyTiffEndianness(); } + } diff --git a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyTiffTagTests.java b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyTiffTagTests.java index e637159..00255cf 100644 --- a/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyTiffTagTests.java +++ b/src/test/java/org/opengis/cite/geotiff11/tiffTests/VerifyTiffTagTests.java @@ -4,6 +4,7 @@ import static org.mockito.Mockito.when; import java.io.InputStream; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.experimental.theories.Theories; @@ -14,24 +15,24 @@ import org.testng.ITestContext; /** - * Verifies the behavior of the TiffTagsTests test class. Test stubs replace - * fixture constituents where appropriate. + * Verifies the behavior of the TiffTagsTests test class. Test stubs replace fixture + * constituents where appropriate. */ @RunWith(Theories.class) public class VerifyTiffTagTests extends CreateDataSets { private static ITestContext testContext; + TiffTagsTests iut; public VerifyTiffTagTests() { } - - private void dataSetSetUp(InputStream inputStream) - { + + private void dataSetSetUp(InputStream inputStream) { testDataSets(inputStream); iut = new TiffTagsTests(); } - + @BeforeClass public static void setUpClass() throws Exception { testContext = mock(ITestContext.class); @@ -41,15 +42,16 @@ public static void setUpClass() throws Exception { @AfterClass public static void tearDownClass() throws Exception { - + } - + @Theory public void verifyTiffTags(InputStream inputStream) throws Exception { dataSetSetUp(inputStream); - + iut = new TiffTagsTests(); iut.obtainTestSubject(testContext); iut.verifyTiffTags(); } + } diff --git a/src/test/java/org/opengis/cite/geotiff11/util/CreateDataSets.java b/src/test/java/org/opengis/cite/geotiff11/util/CreateDataSets.java index 454c7ea..e1ccbf6 100644 --- a/src/test/java/org/opengis/cite/geotiff11/util/CreateDataSets.java +++ b/src/test/java/org/opengis/cite/geotiff11/util/CreateDataSets.java @@ -7,98 +7,122 @@ import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; -import org.junit.experimental.theories.*; +import org.junit.experimental.theories.DataPoint; import org.testng.ISuite; public class CreateDataSets { + private static final String SUBJ = "testSubject"; + protected static ISuite suite; - public static @DataPoint InputStream PrivateValuesFile = CreateDataSets.class.getResourceAsStream("/tif/PrivateValues.txt"); - public static @DataPoint InputStream UserDefinedFile = CreateDataSets.class.getResourceAsStream("/tif/ComprehensiveAndUserDefined.txt"); - public static @DataPoint InputStream EPSGValuesFile = CreateDataSets.class.getResourceAsStream("/tif/EPSGValues.txt"); + + public static @DataPoint InputStream PrivateValuesFile = CreateDataSets.class + .getResourceAsStream("/tif/PrivateValues.txt"); + + public static @DataPoint InputStream UserDefinedFile = CreateDataSets.class + .getResourceAsStream("/tif/ComprehensiveAndUserDefined.txt"); + + public static @DataPoint InputStream EPSGValuesFile = CreateDataSets.class + .getResourceAsStream("/tif/EPSGValues.txt"); + public static @DataPoint InputStream OneValuesFile = CreateDataSets.class.getResourceAsStream("/tif/OneValues.txt"); + public static @DataPoint InputStream TwoValuesFile = CreateDataSets.class.getResourceAsStream("/tif/TwoValues.txt"); - public static @DataPoint InputStream ThreeValuesFile = CreateDataSets.class.getResourceAsStream("/tif/ThreeValuesAndSupplement.txt"); - public static @DataPoint InputStream ZeroValuesFile = CreateDataSets.class.getResourceAsStream("/tif/ZeroValues.txt"); - public static @DataPoint InputStream AsciiValuesFile = CreateDataSets.class.getResourceAsStream("/tif/AsciiValues.txt"); - + + public static @DataPoint InputStream ThreeValuesFile = CreateDataSets.class + .getResourceAsStream("/tif/ThreeValuesAndSupplement.txt"); + + public static @DataPoint InputStream ZeroValuesFile = CreateDataSets.class + .getResourceAsStream("/tif/ZeroValues.txt"); + + public static @DataPoint InputStream AsciiValuesFile = CreateDataSets.class + .getResourceAsStream("/tif/AsciiValues.txt"); + private static String privateValuesString; + private static String userDefinedString; + private static String EPSGValuesString; + private static String OneValuesString; + private static String TwoValuesString; + private static String ThreeValuesString; + private static String ZeroValuesString; + private static String AsciiValuesString; - - public void testDataSets(InputStream inputStream) { - + + public void testDataSets(InputStream inputStream) { + try { - //check each input to set value for validation + // check each input to set value for validation String value = null; - if(inputStream.equals(PrivateValuesFile)) { - //set the return value for validation - if (privateValuesString == null || privateValuesString.isEmpty()) { - privateValuesString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - } - value = privateValuesString; - } + if (inputStream.equals(PrivateValuesFile)) { + // set the return value for validation + if (privateValuesString == null || privateValuesString.isEmpty()) { + privateValuesString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); + } + value = privateValuesString; + } else if (inputStream.equals(UserDefinedFile)) { - //set the return value for validation - if (userDefinedString == null || userDefinedString.isEmpty()) { - userDefinedString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); + // set the return value for validation + if (userDefinedString == null || userDefinedString.isEmpty()) { + userDefinedString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } value = userDefinedString; } else if (inputStream.equals(EPSGValuesFile)) { - //set the return value for validation - if (EPSGValuesString == null || EPSGValuesString.isEmpty()) { - EPSGValuesString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); + // set the return value for validation + if (EPSGValuesString == null || EPSGValuesString.isEmpty()) { + EPSGValuesString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } value = EPSGValuesString; } else if (inputStream.equals(OneValuesFile)) { - //set the return value for validation - if (OneValuesString == null || OneValuesString.isEmpty()){ - OneValuesString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); + // set the return value for validation + if (OneValuesString == null || OneValuesString.isEmpty()) { + OneValuesString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } value = OneValuesString; } else if (inputStream.equals(TwoValuesFile)) { - //set the return value for validation - if (TwoValuesString == null || TwoValuesString.isEmpty()){ - TwoValuesString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); + // set the return value for validation + if (TwoValuesString == null || TwoValuesString.isEmpty()) { + TwoValuesString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } value = TwoValuesString; } else if (inputStream.equals(ThreeValuesFile)) { - //set the return value for validation - if (ThreeValuesString == null || ThreeValuesString.isEmpty()){ - ThreeValuesString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); + // set the return value for validation + if (ThreeValuesString == null || ThreeValuesString.isEmpty()) { + ThreeValuesString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } value = ThreeValuesString; } else if (inputStream.equals(ZeroValuesFile)) { - //set the return value for validation - if (ZeroValuesString == null || ZeroValuesString.isEmpty()){ - ZeroValuesString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); + // set the return value for validation + if (ZeroValuesString == null || ZeroValuesString.isEmpty()) { + ZeroValuesString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } value = ZeroValuesString; } else if (inputStream.equals(AsciiValuesFile)) { - //set the return value for validation - if (AsciiValuesString == null || AsciiValuesString.isEmpty()){ - AsciiValuesString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); + // set the return value for validation + if (AsciiValuesString == null || AsciiValuesString.isEmpty()) { + AsciiValuesString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } value = AsciiValuesString; } - + when(suite.getAttribute(SUBJ)).thenReturn(value); - } + } catch (IOException e) { e.printStackTrace(); } } + } diff --git a/src/test/java/org/opengis/cite/geotiff11/util/VerifyEPSGDataSet.java b/src/test/java/org/opengis/cite/geotiff11/util/VerifyEPSGDataSet.java index 37932e2..91b2ba7 100644 --- a/src/test/java/org/opengis/cite/geotiff11/util/VerifyEPSGDataSet.java +++ b/src/test/java/org/opengis/cite/geotiff11/util/VerifyEPSGDataSet.java @@ -3,35 +3,28 @@ import static org.junit.Assert.assertTrue; import java.io.IOException; + import org.junit.BeforeClass; import org.junit.Test; -import org.opengis.cite.geotiff11.util.EPSGDataSet; public class VerifyEPSGDataSet { - + // TODO: coverage of EPSGDataSet tools - String[] tables = new String[] { - EPSGDataSet.UOM, - EPSGDataSet.CRS, - EPSGDataSet.DATUM, - EPSGDataSet.PRIMEMERIDIAN, - EPSGDataSet.ELLIPSOID, - EPSGDataSet.CO, - EPSGDataSet.COM, - EPSGDataSet.COP - }; - - @BeforeClass - public static void setUpClass() { - } - - @Test - public void verifyTablesExist() throws IOException { - for(String table : tables) { - assertTrue(EPSGDataSet.readTable(table) != null); - } - } - - // etc. + String[] tables = new String[] { EPSGDataSet.UOM, EPSGDataSet.CRS, EPSGDataSet.DATUM, EPSGDataSet.PRIMEMERIDIAN, + EPSGDataSet.ELLIPSOID, EPSGDataSet.CO, EPSGDataSet.COM, EPSGDataSet.COP }; + + @BeforeClass + public static void setUpClass() { + } + + @Test + public void verifyTablesExist() throws IOException { + for (String table : tables) { + assertTrue(EPSGDataSet.readTable(table) != null); + } + } + + // etc. + } diff --git a/src/test/java/org/opengis/cite/geotiff11/util/VerifyURIUtils.java b/src/test/java/org/opengis/cite/geotiff11/util/VerifyURIUtils.java index 13529ce..62796a5 100644 --- a/src/test/java/org/opengis/cite/geotiff11/util/VerifyURIUtils.java +++ b/src/test/java/org/opengis/cite/geotiff11/util/VerifyURIUtils.java @@ -19,65 +19,60 @@ */ public class VerifyURIUtils { - public VerifyURIUtils() { - } + public VerifyURIUtils() { + } - @BeforeClass - public static void setUpClass() { - } + @BeforeClass + public static void setUpClass() { + } - @Ignore - @Test - // comment out @Ignore to run test (requires network connection) - public void resolveHttpUriAsDocument() throws SAXException, IOException { - URI uriRef = URI.create("http://www.w3schools.com/xml/note.xml"); - Document doc = URIUtils.parseURI(uriRef); - Assert.assertNotNull(doc); - Assert.assertEquals("Document element has unexpected [local name].", - "note", doc.getDocumentElement().getLocalName()); - } + @Ignore + @Test + // comment out @Ignore to run test (requires network connection) + public void resolveHttpUriAsDocument() throws SAXException, IOException { + URI uriRef = URI.create("http://www.w3schools.com/xml/note.xml"); + Document doc = URIUtils.parseURI(uriRef); + Assert.assertNotNull(doc); + Assert.assertEquals("Document element has unexpected [local name].", "note", + doc.getDocumentElement().getLocalName()); + } - @Ignore - @Test - // comment out @Ignore to run test (requires network connection) - public void resolveHttpUriAsFile() throws SAXException, IOException { - URI uriRef = URI.create("http://www.w3schools.com/xml/note.xml"); - File file = URIUtils.dereferenceURI(uriRef); - Assert.assertNotNull(file); - Assert.assertTrue("File should not be empty", file.length() > 0); - } + @Ignore + @Test + // comment out @Ignore to run test (requires network connection) + public void resolveHttpUriAsFile() throws SAXException, IOException { + URI uriRef = URI.create("http://www.w3schools.com/xml/note.xml"); + File file = URIUtils.dereferenceURI(uriRef); + Assert.assertNotNull(file); + Assert.assertTrue("File should not be empty", file.length() > 0); + } - @Test - public void resolveClasspathResource() throws SAXException, IOException, - URISyntaxException { - URL url = this.getClass().getResource("/atom-feed.xml"); - Document doc = URIUtils.parseURI(url.toURI()); - Assert.assertNotNull(doc); - Assert.assertEquals("Document element has unexpected [local name].", - "feed", doc.getDocumentElement().getLocalName()); - } + @Test + public void resolveClasspathResource() throws SAXException, IOException, URISyntaxException { + URL url = this.getClass().getResource("/atom-feed.xml"); + Document doc = URIUtils.parseURI(url.toURI()); + Assert.assertNotNull(doc); + Assert.assertEquals("Document element has unexpected [local name].", "feed", + doc.getDocumentElement().getLocalName()); + } - @Test - public void resolveFileRefWithXInclude() throws SAXException, IOException, - URISyntaxException { - File file = new File("src/test/resources/Alpha-xinclude.xml"); - Document doc = URIUtils.parseURI(file.toURI()); - Assert.assertNotNull(doc); - Assert.assertEquals("Document element has unexpected [local name].", - "Alpha", doc.getDocumentElement().getLocalName()); - NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS( - "http://www.example.net/gamma", "Gamma"); - Assert.assertEquals( - "Expected element {http://www.example.net/gamma}Gamma", 1, - nodes.getLength()); - } + @Test + public void resolveFileRefWithXInclude() throws SAXException, IOException, URISyntaxException { + File file = new File("src/test/resources/Alpha-xinclude.xml"); + Document doc = URIUtils.parseURI(file.toURI()); + Assert.assertNotNull(doc); + Assert.assertEquals("Document element has unexpected [local name].", "Alpha", + doc.getDocumentElement().getLocalName()); + NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS("http://www.example.net/gamma", "Gamma"); + Assert.assertEquals("Expected element {http://www.example.net/gamma}Gamma", 1, nodes.getLength()); + } + + @Test(expected = IllegalArgumentException.class) + public void resolveMissingClasspathResource() throws SAXException, URISyntaxException, IOException { + URL url = this.getClass().getResource("/alpha.xml"); + URI uri = (null != url) ? url.toURI() : null; + Document doc = URIUtils.parseURI(uri); + Assert.assertNull(doc); + } - @Test(expected = IllegalArgumentException.class) - public void resolveMissingClasspathResource() throws SAXException, - URISyntaxException, IOException { - URL url = this.getClass().getResource("/alpha.xml"); - URI uri = (null != url) ? url.toURI() : null; - Document doc = URIUtils.parseURI(uri); - Assert.assertNull(doc); - } } diff --git a/src/test/java/org/opengis/cite/geotiff11/util/VerifyValidationUtils.java b/src/test/java/org/opengis/cite/geotiff11/util/VerifyValidationUtils.java index 8f03f55..422f1ce 100644 --- a/src/test/java/org/opengis/cite/geotiff11/util/VerifyValidationUtils.java +++ b/src/test/java/org/opengis/cite/geotiff11/util/VerifyValidationUtils.java @@ -1,6 +1,7 @@ package org.opengis.cite.geotiff11.util; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; @@ -18,26 +19,23 @@ */ public class VerifyValidationUtils { - public VerifyValidationUtils() { - } - - @Test - public void testBuildSchematronValidator() { - String schemaRef = "http://schemas.opengis.net/gml/3.2.1/SchematronConstraints.xml"; - String phase = ""; - SchematronValidator result = ValidationUtils.buildSchematronValidator( - schemaRef, phase); - assertNotNull(result); - } - - @Test - public void extractRelativeSchemaReference() throws FileNotFoundException, - XMLStreamException { - File xmlFile = new File("src/test/resources/Alpha-1.xml"); - Set xsdSet = ValidationUtils.extractSchemaReferences( - new StreamSource(xmlFile), null); - URI schemaURI = xsdSet.iterator().next(); - assertTrue("Expected schema reference */xsd/alpha.xsd", schemaURI - .toString().endsWith("/xsd/alpha.xsd")); - } + public VerifyValidationUtils() { + } + + @Test + public void testBuildSchematronValidator() { + String schemaRef = "http://schemas.opengis.net/gml/3.2.1/SchematronConstraints.xml"; + String phase = ""; + SchematronValidator result = ValidationUtils.buildSchematronValidator(schemaRef, phase); + assertNotNull(result); + } + + @Test + public void extractRelativeSchemaReference() throws FileNotFoundException, XMLStreamException { + File xmlFile = new File("src/test/resources/Alpha-1.xml"); + Set xsdSet = ValidationUtils.extractSchemaReferences(new StreamSource(xmlFile), null); + URI schemaURI = xsdSet.iterator().next(); + assertTrue("Expected schema reference */xsd/alpha.xsd", schemaURI.toString().endsWith("/xsd/alpha.xsd")); + } + } diff --git a/src/test/java/org/opengis/cite/geotiff11/util/VerifyXMLUtils.java b/src/test/java/org/opengis/cite/geotiff11/util/VerifyXMLUtils.java index 7b7a122..db735e7 100644 --- a/src/test/java/org/opengis/cite/geotiff11/util/VerifyXMLUtils.java +++ b/src/test/java/org/opengis/cite/geotiff11/util/VerifyXMLUtils.java @@ -3,14 +3,12 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; + import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.xpath.XPathExpressionException; -import net.sf.saxon.s9api.SaxonApiException; -import net.sf.saxon.s9api.XdmValue; -import net.sf.saxon.trans.XPathException; import org.junit.Assert; import org.junit.BeforeClass; @@ -21,127 +19,119 @@ import org.w3c.dom.NodeList; import org.xml.sax.SAXException; +import net.sf.saxon.s9api.SaxonApiException; +import net.sf.saxon.s9api.XdmValue; +import net.sf.saxon.trans.XPathException; + /** * Verifies the behavior of the XMLUtils class. */ public class VerifyXMLUtils { - private static final String ATOM_NS = "http://www.w3.org/2005/Atom"; - private static final String EX_NS = "http://example.org/ns1"; - private static DocumentBuilder docBuilder; - - public VerifyXMLUtils() { - } - - @BeforeClass - public static void setUpClass() throws Exception { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - docBuilder = dbf.newDocumentBuilder(); - } - - @Test - public void writeDocToString() throws SAXException, IOException { - Document doc = docBuilder.parse(this.getClass().getResourceAsStream( - "/atom-feed.xml")); - String content = XMLUtils.writeNodeToString(doc); - Assert.assertTrue("String should start with ' nsBindings = new HashMap(); - nsBindings.put(ATOM_NS, "tns"); - nsBindings.put(EX_NS, "ns1"); - NodeList results = XMLUtils.evaluateXPath(doc, expr, nsBindings); - Assert.assertTrue("Expected 1 node in results.", - results.getLength() == 1); - Assert.assertEquals("author", results.item(0).getLocalName()); - } - - @Test - public void evaluateXPathExpression_noMatch() - throws XPathExpressionException, SAXException, IOException { - Document doc = docBuilder.parse(this.getClass().getResourceAsStream( - "/atom-feed.xml")); - String expr = "/tns:feed/tns:author[ns1:blog]"; - Map nsBindings = new HashMap(); - nsBindings.put(ATOM_NS, "tns"); - nsBindings.put(EX_NS, "ns1"); - NodeList results = XMLUtils.evaluateXPath(doc, expr, nsBindings); - Assert.assertTrue("Expected empty results.", results.getLength() == 0); - } - - @Test(expected = XPathExpressionException.class) - public void evaluateXPathExpression_booleanResult() - throws XPathExpressionException, SAXException, IOException { - Document doc = docBuilder.parse(this.getClass().getResourceAsStream( - "/atom-feed.xml")); - String expr = "count(//tns:entry) > 0"; - Map nsBindings = new HashMap(); - nsBindings.put(ATOM_NS, "tns"); - NodeList results = XMLUtils.evaluateXPath(doc, expr, nsBindings); - Assert.assertNull(results); - } - - @Test - public void createElement_Alpha() { - QName qName = new QName("http://example.org", "Alpha"); - Element elem = XMLUtils.createElement(qName); - Assert.assertEquals("Alpha", elem.getLocalName()); - Assert.assertNull(elem.getParentNode()); - Assert.assertNotNull(elem.getOwnerDocument()); - } - - @Test - public void evaluateXPath2ExpressionAgainstDocument() throws SAXException, - IOException, SaxonApiException, XPathException { - Document doc = docBuilder.parse(this.getClass().getResourceAsStream( - "/atom-feed.xml")); - String expr = "matches(//tns:entry/tns:title, '.*Robots')"; - Map nsBindings = new HashMap(); - nsBindings.put(ATOM_NS, "tns"); - XdmValue result = XMLUtils.evaluateXPath2(new DOMSource(doc), expr, - nsBindings); - Assert.assertTrue("Expected non-empty result.", result.size() > 0); - Assert.assertEquals("Result has unexpected string value.", "true", - result.getUnderlyingValue().getStringValue()); - } - - @Test - public void evaluateXPath2ExpressionAgainstElement() throws SAXException, - IOException, SaxonApiException, XPathException { - Document doc = docBuilder.parse(this.getClass().getResourceAsStream( - "/atom-feed.xml")); - Node entry = doc.getElementsByTagNameNS(ATOM_NS, "entry").item(0); - String expr = "matches(tns:title, '.*Robots')"; - Map nsBindings = new HashMap(); - nsBindings.put(ATOM_NS, "tns"); - XdmValue result = XMLUtils.evaluateXPath2(new DOMSource(entry), expr, - nsBindings); - Assert.assertTrue("Expected non-empty result.", result.size() > 0); - Assert.assertEquals("Result has unexpected string value.", "true", - result.getUnderlyingValue().getStringValue()); - } - - @Test - public void expandCharacterEntity() { - String text = "Ce n'est pas"; - String result = XMLUtils.expandReferencesInText(text); - Assert.assertTrue("Expected result to contain an apostrophe (')", - result.contains("'")); - } - - @Test - public void expandNumericCharacterReference() { - String text = "Montréal"; - String result = XMLUtils.expandReferencesInText(text); - Assert.assertEquals("Expected result to contain character é (U+00E9)", - "Montréal", result); - } + private static final String ATOM_NS = "http://www.w3.org/2005/Atom"; + + private static final String EX_NS = "http://example.org/ns1"; + + private static DocumentBuilder docBuilder; + + public VerifyXMLUtils() { + } + + @BeforeClass + public static void setUpClass() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + docBuilder = dbf.newDocumentBuilder(); + } + + @Test + public void writeDocToString() throws SAXException, IOException { + Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/atom-feed.xml")); + String content = XMLUtils.writeNodeToString(doc); + Assert.assertTrue("String should start with ' nsBindings = new HashMap(); + nsBindings.put(ATOM_NS, "tns"); + nsBindings.put(EX_NS, "ns1"); + NodeList results = XMLUtils.evaluateXPath(doc, expr, nsBindings); + Assert.assertTrue("Expected 1 node in results.", results.getLength() == 1); + Assert.assertEquals("author", results.item(0).getLocalName()); + } + + @Test + public void evaluateXPathExpression_noMatch() throws XPathExpressionException, SAXException, IOException { + Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/atom-feed.xml")); + String expr = "/tns:feed/tns:author[ns1:blog]"; + Map nsBindings = new HashMap(); + nsBindings.put(ATOM_NS, "tns"); + nsBindings.put(EX_NS, "ns1"); + NodeList results = XMLUtils.evaluateXPath(doc, expr, nsBindings); + Assert.assertTrue("Expected empty results.", results.getLength() == 0); + } + + @Test(expected = XPathExpressionException.class) + public void evaluateXPathExpression_booleanResult() throws XPathExpressionException, SAXException, IOException { + Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/atom-feed.xml")); + String expr = "count(//tns:entry) > 0"; + Map nsBindings = new HashMap(); + nsBindings.put(ATOM_NS, "tns"); + NodeList results = XMLUtils.evaluateXPath(doc, expr, nsBindings); + Assert.assertNull(results); + } + + @Test + public void createElement_Alpha() { + QName qName = new QName("http://example.org", "Alpha"); + Element elem = XMLUtils.createElement(qName); + Assert.assertEquals("Alpha", elem.getLocalName()); + Assert.assertNull(elem.getParentNode()); + Assert.assertNotNull(elem.getOwnerDocument()); + } + + @Test + public void evaluateXPath2ExpressionAgainstDocument() + throws SAXException, IOException, SaxonApiException, XPathException { + Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/atom-feed.xml")); + String expr = "matches(//tns:entry/tns:title, '.*Robots')"; + Map nsBindings = new HashMap(); + nsBindings.put(ATOM_NS, "tns"); + XdmValue result = XMLUtils.evaluateXPath2(new DOMSource(doc), expr, nsBindings); + Assert.assertTrue("Expected non-empty result.", result.size() > 0); + Assert.assertEquals("Result has unexpected string value.", "true", + result.getUnderlyingValue().getStringValue()); + } + + @Test + public void evaluateXPath2ExpressionAgainstElement() + throws SAXException, IOException, SaxonApiException, XPathException { + Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/atom-feed.xml")); + Node entry = doc.getElementsByTagNameNS(ATOM_NS, "entry").item(0); + String expr = "matches(tns:title, '.*Robots')"; + Map nsBindings = new HashMap(); + nsBindings.put(ATOM_NS, "tns"); + XdmValue result = XMLUtils.evaluateXPath2(new DOMSource(entry), expr, nsBindings); + Assert.assertTrue("Expected non-empty result.", result.size() > 0); + Assert.assertEquals("Result has unexpected string value.", "true", + result.getUnderlyingValue().getStringValue()); + } + + @Test + public void expandCharacterEntity() { + String text = "Ce n'est pas"; + String result = XMLUtils.expandReferencesInText(text); + Assert.assertTrue("Expected result to contain an apostrophe (')", result.contains("'")); + } + + @Test + public void expandNumericCharacterReference() { + String text = "Montréal"; + String result = XMLUtils.expandReferencesInText(text); + Assert.assertEquals("Expected result to contain character é (U+00E9)", "Montréal", result); + } + }