diff --git a/.gitignore b/.gitignore index a44d20e..4bf44e2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,5 @@ .DS_Store /target/ +.settings/ +.classpath +.project diff --git a/pom.xml b/pom.xml index a3a24e1..9007afd 100644 --- a/pom.xml +++ b/pom.xml @@ -3,11 +3,10 @@ org.opengis.cite ets-common - 9 + 14-SNAPSHOT 4.0.0 - org.opengis.cite ets-wps20 1.1-SNAPSHOT jar @@ -47,28 +46,21 @@ wps20 2.0 - 5.6.1 xerces xercesImpl - 2.12.2 org.opengis.cite.teamengine teamengine-spi - 5.6.1 org.opengis.cite schema-utils - - com.sun.jersey - jersey-client - junit junit @@ -77,29 +69,14 @@ org.mockito mockito-core + + org.glassfish.jersey.connectors + jersey-apache-connector + - - maven-javadoc-plugin - 2.10.4 - - true - package - - http://testng.org/javadocs/ - - - - - attach-javadocs - - jar - - - - maven-assembly-plugin @@ -123,67 +100,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.30.0 @@ -191,7 +113,7 @@ ${project.basedir}/src/docker - ${project.version}-teamengine-${docker.teamengine.version} + ${project.version}-teamengine-${teamengine.version} @@ -224,58 +146,11 @@ - - maven-dependency-plugin - 3.0.0 - - - - org.opengis.cite.teamengine - teamengine-web - ${docker.teamengine.version} - war - - - org.opengis.cite.teamengine - teamengine-web - ${docker.teamengine.version} - common-libs - zip - - - org.opengis.cite.teamengine - teamengine-console - ${docker.teamengine.version} - base - zip - - - - - - integration-tests - - - - maven-failsafe-plugin - 2.22.0 - - - - integration-test - verify - - - - - - - docker diff --git a/src/assembly/aio.xml b/src/assembly/aio.xml index 637399b..34c320c 100644 --- a/src/assembly/aio.xml +++ b/src/assembly/aio.xml @@ -12,9 +12,6 @@ true true runtime - - com.sun.jersey:jersey-server - diff --git a/src/assembly/deps.xml b/src/assembly/deps.xml index e878346..080a72e 100644 --- a/src/assembly/deps.xml +++ b/src/assembly/deps.xml @@ -10,21 +10,13 @@ false - - - com.sun.jersey:jersey-client - org.opengis.cite:schema-utils - - / - false - runtime - false - org.opengis.cite.teamengine:teamengine-spi - com.sun.jersey:jersey-client - org.opengis.cite:schema-utils + *:jersey-client + *:jersey-server + *:jersey-common + jakarta.ws.rs:jakarta.ws.rs-api / false diff --git a/src/docker/Dockerfile b/src/docker/Dockerfile index c169d68..92565e8 100644 --- a/src/docker/Dockerfile +++ b/src/docker/Dockerfile @@ -1,4 +1,6 @@ -FROM tomcat:7.0-jre8 +FROM tomcat:10.1-jre17 + +RUN apt update && apt install -y unzip # add TEAM engine webapp ADD maven/dependency/teamengine-web-*.war /root/ @@ -21,5 +23,7 @@ RUN cd /root/ && unzip -q ets-wps20-*-ctl.zip -d /root/te_base/scripts ADD maven/ets-wps20-*-deps.zip /root/ RUN cd /root/ && unzip -q -o ets-wps20-*-deps.zip -d /usr/local/tomcat/webapps/teamengine/WEB-INF/lib +RUN rm -R /root/te_base/scripts/note + # run tomcat CMD ["catalina.sh", "jpda", "run"] \ No newline at end of file diff --git a/src/main/java/org/opengis/cite/wps20/CommandLineArguments.java b/src/main/java/org/opengis/cite/wps20/CommandLineArguments.java index f75ec31..2e2d198 100644 --- a/src/main/java/org/opengis/cite/wps20/CommandLineArguments.java +++ b/src/main/java/org/opengis/cite/wps20/CommandLineArguments.java @@ -1,15 +1,15 @@ package org.opengis.cite.wps20; -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/wps20/CommonFixture.java b/src/main/java/org/opengis/cite/wps20/CommonFixture.java index b42e958..ada48d2 100644 --- a/src/main/java/org/opengis/cite/wps20/CommonFixture.java +++ b/src/main/java/org/opengis/cite/wps20/CommonFixture.java @@ -1,10 +1,12 @@ package org.opengis.cite.wps20; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; - -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; @@ -13,19 +15,20 @@ import java.nio.charset.Charset; import java.util.LinkedHashMap; import java.util.Map; -import javax.ws.rs.core.MediaType; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.*; +import org.glassfish.jersey.client.ClientRequest; import org.opengis.cite.wps20.basictests.BasicTests; import org.opengis.cite.wps20.util.ClientUtils; import org.opengis.cite.wps20.util.URIUtils; import org.testng.ITestContext; -import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.w3c.dom.Document; @@ -34,101 +37,133 @@ import org.xml.sax.InputSource; import org.xml.sax.SAXException; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + /** - * A supporting base class that sets up a common test fixture. These - * configuration methods are invoked before those defined in a subclass. + * 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/wps20/"; - /** - * HTTP client component (JAX-RS Client API). - */ - protected Client client; - /** - * An HTTP request message. - */ - protected ClientRequest request; - /** - * An HTTP response message. - */ - protected ClientResponse response; - - protected URI ServiceUrl; - - /* Define Arguments */ - protected String EchoProcessId; - - protected String LITERAL_INPUT_ID; - protected String LITERAL_OUTPUT_ID; - protected String COMPLEX_INPUT_ID; - protected String COMPLEX_OUTPUT_ID; - - protected String GET_CAPABILITIES_REQUEST_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/GetCapabilities.xml"; - protected String DESCRIBE_PROCESS_REQUEST_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/DescribeProcess.xml"; - protected String LITERAL_REQUEST_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/Echo_Process_Literal.xml"; - protected String COMPLEX_REQUEST_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/Echo_Process_Complex.xml"; - - - protected String INPUT_VALUE_TRANSMISSION_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/ValidInputValue.xml"; - protected String INPUT_REFERENCE_TRANSMISSION_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/ValidInputReference.xml"; + /** + * Root test suite package (absolute path). + */ + public static final String ROOT_PKG_PATH = "/org/opengis/cite/wps20/"; + + /** + * HTTP client component (JAX-RS Client API). + */ + protected Client client; + + /** + * An HTTP request message. + */ + protected ClientRequest request; + + /** + * An HTTP response message. + */ + protected Response response; + + protected URI ServiceUrl; + + /* Define Arguments */ + protected String EchoProcessId; + + protected String LITERAL_INPUT_ID; + + protected String LITERAL_OUTPUT_ID; + + protected String COMPLEX_INPUT_ID; + + protected String COMPLEX_OUTPUT_ID; + + protected String GET_CAPABILITIES_REQUEST_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/GetCapabilities.xml"; + + protected String DESCRIBE_PROCESS_REQUEST_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/DescribeProcess.xml"; + + protected String LITERAL_REQUEST_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/Echo_Process_Literal.xml"; + + protected String COMPLEX_REQUEST_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/Echo_Process_Complex.xml"; + + protected String INPUT_VALUE_TRANSMISSION_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/ValidInputValue.xml"; + + protected String INPUT_REFERENCE_TRANSMISSION_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/ValidInputReference.xml"; + protected String OUTPUT_VALUE_TRANSMISSION_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/ValidOutputValue.xml"; + protected String OUTPUT_REFERENCE_TRANSMISSION_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/ValidOutputReference.xml"; + protected String UNIQUE_JOB_IDS_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/ValidUniqueJobIds.xml"; + protected String GET_STATUS_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/ValidGetStatus.xml"; + protected String GET_RESULT_TEMPLATE_PATH = "/org/opengis/cite/wps20/examples/ValidGetResult.xml"; - /** - * 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) throws Exception { - 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."); - }*/ - - /* Define SERVICE_URL parameter */ - Object ServiceUrlObj = testContext.getSuite().getAttribute(SuiteAttribute.SERVICE_URL.getName()); - if ((null != ServiceUrlObj)){ - this.ServiceUrl = URI.class.cast(ServiceUrlObj); - System.out.println("WPS 2.0 SERVICE URL: " + this.ServiceUrl.toString()); - } - - /* Define ECHO_PROCESS_ID parameter */ - Object EchoProcessIdObj = testContext.getSuite().getAttribute(SuiteAttribute.ECHO_PROCESS_ID.getName()); - if ((null != EchoProcessIdObj)){ - this.EchoProcessId = String.class.cast(EchoProcessIdObj); - System.out.println("WPS 2.0 ECHO PROCESS ID: " + this.EchoProcessId.toString()); - } - - GetEchoProcessInputIdAndOutputId(); - } - - @BeforeMethod - public void clearMessages() { - this.request = null; - this.response = null; - } - - public void GetEchoProcessInputIdAndOutputId() throws URISyntaxException, SAXException, IOException { - String SERVICE_URL = this.ServiceUrl.toString(); - // Get the processid from user and replace the processid in the template xml + /** + * 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. + * @throws java.lang.Exception if any. + */ + @BeforeClass + public void initCommonFixture(ITestContext testContext) throws Exception { + 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."); } + */ + + /* Define SERVICE_URL parameter */ + Object ServiceUrlObj = testContext.getSuite().getAttribute(SuiteAttribute.SERVICE_URL.getName()); + if ((null != ServiceUrlObj)) { + this.ServiceUrl = URI.class.cast(ServiceUrlObj); + System.out.println("WPS 2.0 SERVICE URL: " + this.ServiceUrl.toString()); + } + + /* Define ECHO_PROCESS_ID parameter */ + Object EchoProcessIdObj = testContext.getSuite().getAttribute(SuiteAttribute.ECHO_PROCESS_ID.getName()); + if ((null != EchoProcessIdObj)) { + this.EchoProcessId = String.class.cast(EchoProcessIdObj); + System.out.println("WPS 2.0 ECHO PROCESS ID: " + this.EchoProcessId.toString()); + } + + GetEchoProcessInputIdAndOutputId(); + } + + /** + *

    + * clearMessages. + *

    + */ + @BeforeMethod + public void clearMessages() { + this.request = null; + this.response = null; + } + + /** + *

    + * GetEchoProcessInputIdAndOutputId. + *

    + * @throws java.net.URISyntaxException if any. + * @throws org.xml.sax.SAXException if any. + * @throws java.io.IOException if any. + */ + public void GetEchoProcessInputIdAndOutputId() throws URISyntaxException, SAXException, IOException { + String SERVICE_URL = this.ServiceUrl.toString(); + // Get the processid from user and replace the processid in the template xml // request file String ECHO_PROCESS_ID = this.EchoProcessId; - - + // Parse the input id and output id in DescribeProcess Map DP_Parameters = new LinkedHashMap<>(); DP_Parameters.put("Service", "WPS"); @@ -145,19 +180,24 @@ public void GetEchoProcessInputIdAndOutputId() throws URISyntaxException, SAXExc for (int i = 0; i < inputList.getLength(); i++) { Element element = (Element) inputList.item(i); Element literalInputElement = (Element) element - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "LiteralData").item(0); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "LiteralData") + .item(0); Element dataTypeInputElement = (Element) element - .getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "DataType").item(0); + .getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "DataType") + .item(0); Element complexInputElement = (Element) element - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "ComplexData").item(0); - String Id = element.getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "Identifier").item(0) - .getTextContent(); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "ComplexData") + .item(0); + String Id = element.getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "Identifier") + .item(0) + .getTextContent(); if (literalInputElement != null && dataTypeInputElement != null) { - //check if DataType accepts string + // check if DataType accepts string if (dataTypeInputElement.getTextContent().toLowerCase().equals("string")) literalInputId = Id; - - } else if (complexInputElement != null) { + + } + else if (complexInputElement != null) { complexInputId = Id; } } @@ -168,70 +208,66 @@ public void GetEchoProcessInputIdAndOutputId() throws URISyntaxException, SAXExc for (int i = 0; i < outputList.getLength(); i++) { Element element = (Element) outputList.item(i); Element literalOutputElement = (Element) element - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "LiteralData").item(0); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "LiteralData") + .item(0); Element dataTypeOutputElement = (Element) element - .getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "DataType").item(0); + .getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "DataType") + .item(0); Element complexOutputElement = (Element) element - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "ComplexData").item(0); - String Id = element.getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "Identifier").item(0) - .getTextContent(); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "ComplexData") + .item(0); + String Id = element.getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "Identifier") + .item(0) + .getTextContent(); if (literalOutputElement != null && dataTypeOutputElement != null) { - //check if DataType accepts string + // check if DataType accepts string if (dataTypeOutputElement.getTextContent().toLowerCase().equals("string")) literalOutputId = Id; - } else if (complexOutputElement != null) { + } + else if (complexOutputElement != null) { complexOutputId = Id; } } - + LITERAL_INPUT_ID = literalInputId; LITERAL_OUTPUT_ID = literalOutputId; COMPLEX_INPUT_ID = complexInputId; COMPLEX_OUTPUT_ID = complexOutputId; - } - - /** - * 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 - */ - public ClientRequest buildGetRequest(URI endpoint, - Map qryParams, MediaType... mediaTypes) { - return ClientUtils.buildGetRequest(endpoint, qryParams, mediaTypes); - } + } + + /** + * Obtains the (XML) response entity as a DOM Document. This convenience method wraps + * a static method call to facilitate unit testing (Mockito workaround). + * @param response A representation of an HTTP response message. + * @param targetURI The target URI from which the entity was retrieved (may be null). + * @return A Document representing the entity. + * @see ClientUtils#getResponseEntityAsDocument + */ + public Document getResponseEntityAsDocument(Response response, String targetURI) { + return ClientUtils.getResponseEntityAsDocument(response, targetURI); + } + + /** + * Builds an HTTP request message that uses the GET method. This convenience method + * wraps a static method call to facilitate unit testing (Mockito workaround). + * @param endpoint A URI indicating the target resource. + * @param qryParams A Map containing query parameters (may be null); + * @param mediaTypes A list of acceptable media types; if not specified, generic XML + * ("application/xml") is preferred. + * @return A Response object. + * @see ClientUtils#buildGetRequest + */ + public Response buildGetRequest(URI endpoint, Map qryParams, MediaType... mediaTypes) { + return ClientUtils.buildGetRequest(endpoint, qryParams, mediaTypes); + } + /** * Description: Send POST request with parameters and return Response as String - * - * @param any_url - * @param xml_doc - * @return + * @param any_url a {@link java.lang.String} object + * @param xml_doc a {@link org.w3c.dom.Document} object + * @return a {@link java.lang.String} object */ - public String GetContentFromPOSTXMLRequest(String any_url, Document xml_doc) { + public String GetContentFromPOSTXMLRequest(String any_url, Document xml_doc) { StringBuilder sb = new StringBuilder(); HttpURLConnection urlConn = null; InputStreamReader in = null; @@ -267,18 +303,23 @@ public String GetContentFromPOSTXMLRequest(String any_url, Document xml_doc) { } } in.close(); - //System.out.println(xml); - - } catch (Exception e) { + // System.out.println(xml); + + } + catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + any_url, e); } return sb.toString(); } + /** - * @param xmlString - * @return + *

    + * TransformXMLStringToXMLDocument. + *

    + * @param xmlString a {@link java.lang.String} object + * @return a {@link org.w3c.dom.Document} object */ public Document TransformXMLStringToXMLDocument(String xmlString) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); @@ -288,17 +329,18 @@ public Document TransformXMLStringToXMLDocument(String xmlString) { builder = factory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(xmlString))); return doc; - } catch (Exception e) { + } + catch (Exception e) { e.printStackTrace(); } return null; - } + } + /** * Description: Send GET request with parameters and return Response as String - * - * @param any_url - * @param params - * @return + * @param any_url a {@link java.lang.String} object + * @param params a {@link java.util.Map} object + * @return a {@link java.lang.String} object */ public String GetContentFromGETKVPRequest(String any_url, Map params) { StringBuilder sb = new StringBuilder(); @@ -332,14 +374,19 @@ public String GetContentFromGETKVPRequest(String any_url, Map pa } } in.close(); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException("Exception while calling URL:" + any_url, e); } return sb.toString(); - } + } + /** - * @param URI - * @return + *

    + * TransformXMLFileToXMLDocument. + *

    + * @param URI a {@link java.lang.String} object + * @return a {@link org.w3c.dom.Document} object */ public Document TransformXMLFileToXMLDocument(String URI) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); @@ -349,14 +396,20 @@ public Document TransformXMLFileToXMLDocument(String URI) { builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File(URI)); return doc; - } catch (Exception e) { + } + catch (Exception e) { e.printStackTrace(); } return null; - } + } + /** - * @param xmlDoc - * @throws Exception + *

    + * TransformXMLDocumentToXMLString. + *

    + * @param xmlDoc a {@link org.w3c.dom.Document} object + * @throws java.lang.Exception + * @return a {@link java.lang.String} object */ public String TransformXMLDocumentToXMLString(Document xmlDoc) throws Exception { Transformer tf = TransformerFactory.newInstance().newTransformer(); @@ -368,31 +421,61 @@ public String TransformXMLDocumentToXMLString(Document xmlDoc) throws Exception } /** - * @param xmlDoc - * @throws Exception + *

    + * prettyPrint. + *

    + * @param xmlDoc a {@link org.w3c.dom.Document} object + * @throws java.lang.Exception */ public void prettyPrint(Document xmlDoc) throws Exception { String str = TransformXMLDocumentToXMLString(xmlDoc); System.out.println(str); - } + } + + /** + *

    + * GetConnection. + *

    + * @param serviceURL a {@link java.lang.String} object + * @return a {@link java.net.HttpURLConnection} object + * @throws java.io.IOException if any. + */ public HttpURLConnection GetConnection(String serviceURL) throws IOException { URL urlObj = new URL(serviceURL); return (HttpURLConnection) urlObj.openConnection(); } - - public Document GetDocumentTemplate(String templatePath, String processId, String inputId, String outputId) throws URISyntaxException, SAXException, IOException { + + /** + *

    + * GetDocumentTemplate. + *

    + * @param templatePath a {@link java.lang.String} object + * @param processId a {@link java.lang.String} object + * @param inputId a {@link java.lang.String} object + * @param outputId a {@link java.lang.String} object + * @return a {@link org.w3c.dom.Document} object + * @throws java.net.URISyntaxException if any. + * @throws org.xml.sax.SAXException if any. + * @throws java.io.IOException if any. + */ + public Document GetDocumentTemplate(String templatePath, String processId, String inputId, String outputId) + throws URISyntaxException, SAXException, IOException { URI uriLiteralRequestTemplate = BasicTests.class.getResource(templatePath).toURI(); Document SEPDocument = URIUtils.parseURI(uriLiteralRequestTemplate); Element requestInputElement = (Element) SEPDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Input").item(0); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Input") + .item(0); Element requestOutputElement = (Element) SEPDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Output").item(0); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Output") + .item(0); Element requestIdElement = (Element) SEPDocument - .getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "Identifier").item(0); + .getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "Identifier") + .item(0); // replace id requestIdElement.setTextContent(processId); requestInputElement.setAttribute("id", inputId); requestOutputElement.setAttribute("id", outputId); return SEPDocument; } + } diff --git a/src/main/java/org/opengis/cite/wps20/ETSAssert.java b/src/main/java/org/opengis/cite/wps20/ETSAssert.java index c4c0841..2725183 100644 --- a/src/main/java/org/opengis/cite/wps20/ETSAssert.java +++ b/src/main/java/org/opengis/cite/wps20/ETSAssert.java @@ -15,196 +15,178 @@ import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; -import org.opengis.cite.wps20.util.NamespaceBindings; -import org.opengis.cite.wps20.util.XMLUtils; +import org.glassfish.jersey.client.ClientResponse; import org.opengis.cite.validation.SchematronValidator; import org.opengis.cite.validation.ValidationErrorHandler; +import org.opengis.cite.wps20.util.NamespaceBindings; +import org.opengis.cite.wps20.util.XMLUtils; import org.testng.Assert; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import com.sun.jersey.api.client.ClientResponse; +import jakarta.ws.rs.core.Response.Status; /** * Provides a set of custom assertion methods. */ 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.wps20.Namespaces#OWS}
    • + *
    • xlink: {@value org.opengis.cite.wps20.Namespaces#XLINK}
    • + *
    • gml: {@value org.opengis.cite.wps20.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.wps20.Namespaces#OWS}
    • - *
    • xlink: {@value org.opengis.cite.wps20.Namespaces#XLINK}
    • - *
    • gml: {@value org.opengis.cite.wps20.Namespaces#GML}
    • - *
    - * - * @param expr - * A valid XPath 1.0 expression. - * @param context - * The context node. - * @param namespaceBindings - * A collection of namespace bindings for the XPath expression, - * where each entry maps a namespace URI (key) to a prefix - * (value). It may be {@code null}. - */ - public static void assertXPath(String expr, Node context, Map namespaceBindings) { - if (null == context) { - throw new NullPointerException("Context node is null."); - } - NamespaceBindings bindings = NamespaceBindings.withStandardBindings(); - bindings.addAllBindings(namespaceBindings); - XPath xpath = XPathFactory.newInstance().newXPath(); - xpath.setNamespaceContext(bindings); - Boolean result; - try { - result = (Boolean) xpath.evaluate(expr, context, XPathConstants.BOOLEAN); - } catch (XPathExpressionException xpe) { - String msg = ErrorMessage.format(ErrorMessageKeys.XPATH_ERROR, expr); - LOGR.log(Level.WARNING, msg, xpe); - throw new AssertionError(msg); - } - Element elemNode; - if (Document.class.isInstance(context)) { - elemNode = Document.class.cast(context).getDocumentElement(); - } else { - elemNode = (Element) context; - } - Assert.assertTrue(result, ErrorMessage.format(ErrorMessageKeys.XPATH_RESULT, elemNode.getNodeName(), expr)); - } + /** + * Asserts that an XML resource is schema-valid. + * @param validator The Validator to use. + * @param source The XML Source to be validated. + */ + public static void assertSchemaValid(Validator validator, Source source) { + ValidationErrorHandler errHandler = new ValidationErrorHandler(); + validator.setErrorHandler(errHandler); + try { + validator.validate(source); + } + catch (Exception e) { + throw new AssertionError(ErrorMessage.format(ErrorMessageKeys.XML_ERROR, e.getMessage())); + } + Assert.assertFalse(errHandler.errorsDetected(), ErrorMessage.format(ErrorMessageKeys.NOT_SCHEMA_VALID, + errHandler.getErrorCount(), errHandler.toString())); + } - /** - * Asserts that an XML resource is schema-valid. - * - * @param validator - * The Validator to use. - * @param source - * The XML Source to be validated. - */ - public static void assertSchemaValid(Validator validator, Source source) { - ValidationErrorHandler errHandler = new ValidationErrorHandler(); - validator.setErrorHandler(errHandler); - try { - validator.validate(source); - } catch (Exception e) { - throw new AssertionError(ErrorMessage.format(ErrorMessageKeys.XML_ERROR, e.getMessage())); - } - Assert.assertFalse(errHandler.errorsDetected(), ErrorMessage.format(ErrorMessageKeys.NOT_SCHEMA_VALID, - errHandler.getErrorCount(), errHandler.toString())); - } + /** + * Asserts that an XML resource satisfies all applicable constraints defined for the + * specified phase in a Schematron (ISO 19757-3) schema. The "xslt2" query language + * binding is supported. Two phase names have special meanings: + *
      + *
    • "#ALL": All patterns are active
    • + *
    • "#DEFAULT": The phase identified by the defaultPhase attribute on the schema + * element should be used.
    • + *
    + * @param schemaRef A URL that denotes the location of a Schematron schema. + * @param xmlSource The XML Source to be validated. + * @param activePhase The active phase (pattern set) whose patterns are used for + * validation; this is set to "#ALL" if not specified. + */ + public static void assertSchematronValid(URL schemaRef, Source xmlSource, String activePhase) { + String phase = (null == activePhase || activePhase.isEmpty()) ? "#ALL" : activePhase; + SchematronValidator validator; + try { + validator = new SchematronValidator(new StreamSource(schemaRef.toString()), phase); + } + catch (Exception e) { + StringBuilder msg = new StringBuilder("Failed to process Schematron schema at "); + msg.append(schemaRef).append('\n'); + msg.append(e.getMessage()); + throw new AssertionError(msg); + } + DOMResult result = (DOMResult) validator.validate(xmlSource); + Assert.assertFalse(validator.ruleViolationsDetected(), ErrorMessage.format(ErrorMessageKeys.NOT_SCHEMA_VALID, + validator.getRuleViolationCount(), XMLUtils.writeNodeToString(result.getNode()))); + } - /** - * Asserts that an XML resource satisfies all applicable constraints defined - * for the specified phase in a Schematron (ISO 19757-3) schema. The "xslt2" - * query language binding is supported. Two phase names have special - * meanings: - *
      - *
    • "#ALL": All patterns are active
    • - *
    • "#DEFAULT": The phase identified by the defaultPhase attribute on the - * schema element should be used.
    • - *
    - * - * @param schemaRef - * A URL that denotes the location of a Schematron schema. - * @param xmlSource - * The XML Source to be validated. - * @param activePhase - * The active phase (pattern set) whose patterns are used for - * validation; this is set to "#ALL" if not specified. - */ - public static void assertSchematronValid(URL schemaRef, Source xmlSource, String activePhase) { - String phase = (null == activePhase || activePhase.isEmpty()) ? "#ALL" : activePhase; - SchematronValidator validator; - try { - validator = new SchematronValidator(new StreamSource(schemaRef.toString()), phase); - } catch (Exception e) { - StringBuilder msg = new StringBuilder("Failed to process Schematron schema at "); - msg.append(schemaRef).append('\n'); - msg.append(e.getMessage()); - throw new AssertionError(msg); - } - DOMResult result = (DOMResult) validator.validate(xmlSource); - Assert.assertFalse(validator.ruleViolationsDetected(), ErrorMessage.format(ErrorMessageKeys.NOT_SCHEMA_VALID, - validator.getRuleViolationCount(), XMLUtils.writeNodeToString(result.getNode()))); - } + /** + * Asserts that the given XML entity contains the expected number of descendant + * elements having the specified name. + * @param xmlEntity A Document representing an XML entity. + * @param elementName The qualified name of the element. + * @param expectedCount The expected number of occurrences. + */ + public static void assertDescendantElementCount(Document xmlEntity, QName elementName, int expectedCount) { + NodeList features = xmlEntity.getElementsByTagNameNS(elementName.getNamespaceURI(), elementName.getLocalPart()); + Assert.assertEquals(features.getLength(), expectedCount, + String.format("Unexpected number of %s descendant elements.", elementName)); + } - /** - * Asserts that the given XML entity contains the expected number of - * descendant elements having the specified name. - * - * @param xmlEntity - * A Document representing an XML entity. - * @param elementName - * The qualified name of the element. - * @param expectedCount - * The expected number of occurrences. - */ - public static void assertDescendantElementCount(Document xmlEntity, QName elementName, int expectedCount) { - NodeList features = xmlEntity.getElementsByTagNameNS(elementName.getNamespaceURI(), elementName.getLocalPart()); - Assert.assertEquals(features.getLength(), expectedCount, - String.format("Unexpected number of %s descendant elements.", elementName)); - } + /** + * Asserts that the given response message contains an OGC exception report. The + * message body must contain an XML document that has a document element with the + * following properties: + * + *
      + *
    • [local name] = "ExceptionReport"
    • + *
    • [namespace name] = "http://www.opengis.net/ows/2.0"
    • + *
    + * @param rsp A ClientResponse object representing an HTTP response message. + * @param exceptionCode The expected OGC exception code. + * @param locator A case-insensitive string value expected to occur in the locator + * attribute (e.g. a parameter name); the attribute value will be ignored if the + * argument is null or empty. + */ + public static void assertExceptionReport(ClientResponse rsp, String exceptionCode, String locator) { + Assert.assertEquals(rsp.getStatus(), Status.BAD_REQUEST.getStatusCode(), + ErrorMessage.get(ErrorMessageKeys.UNEXPECTED_STATUS)); + Document doc = rsp.readEntity(Document.class); + String expr = String.format("//ows:Exception[@exceptionCode = '%s']", exceptionCode); + NodeList nodeList = null; + try { + nodeList = XMLUtils.evaluateXPath(doc, expr, null); + } + catch (XPathExpressionException xpe) { + // won't happen + } + Assert.assertTrue(nodeList.getLength() > 0, "Exception not found in response: " + expr); + if (null != locator && !locator.isEmpty()) { + Element exception = (Element) nodeList.item(0); + String locatorValue = exception.getAttribute("locator").toLowerCase(); + Assert.assertTrue(locatorValue.contains(locator.toLowerCase()), + String.format("Expected locator attribute to contain '%s']", locator)); + } + } - /** - * Asserts that the given response message contains an OGC exception report. - * The message body must contain an XML document that has a document element - * with the following properties: - * - *
      - *
    • [local name] = "ExceptionReport"
    • - *
    • [namespace name] = "http://www.opengis.net/ows/2.0"
    • - *
    - * - * @param rsp - * A ClientResponse object representing an HTTP response message. - * @param exceptionCode - * The expected OGC exception code. - * @param locator - * A case-insensitive string value expected to occur in the - * locator attribute (e.g. a parameter name); the attribute value - * will be ignored if the argument is null or empty. - */ - public static void assertExceptionReport(ClientResponse rsp, String exceptionCode, String locator) { - Assert.assertEquals(rsp.getStatus(), 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/wps20/ErrorMessage.java b/src/main/java/org/opengis/cite/wps20/ErrorMessage.java index cf6ceca..c9da5f3 100644 --- a/src/main/java/org/opengis/cite/wps20/ErrorMessage.java +++ b/src/main/java/org/opengis/cite/wps20/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.wps20.MessageBundle"; - private static ResourceBundle msgResources = - ResourceBundle.getBundle(BASE_NAME); + private static final String BASE_NAME = "org.opengis.cite.wps20.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/wps20/ErrorMessageKeys.java b/src/main/java/org/opengis/cite/wps20/ErrorMessageKeys.java index b930136..ff34d21 100644 --- a/src/main/java/org/opengis/cite/wps20/ErrorMessageKeys.java +++ b/src/main/java/org/opengis/cite/wps20/ErrorMessageKeys.java @@ -1,22 +1,44 @@ package org.opengis.cite.wps20; /** - * 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/wps20/Namespaces.java b/src/main/java/org/opengis/cite/wps20/Namespaces.java index 37e5272..c36cdd7 100644 --- a/src/main/java/org/opengis/cite/wps20/Namespaces.java +++ b/src/main/java/org/opengis/cite/wps20/Namespaces.java @@ -4,28 +4,33 @@ /** * 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"; - /** WPS 2.0.0 */ - public static final String WPS = "http://www.opengis.net/wps/2.0.0"; - /** 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"; + + /** WPS 2.0.0 */ + public static final String WPS = "http://www.opengis.net/wps/2.0.0"; + + /** 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/wps20/ReusableEntityFilter.java b/src/main/java/org/opengis/cite/wps20/ReusableEntityFilter.java index 428edfc..e896ed7 100644 --- a/src/main/java/org/opengis/cite/wps20/ReusableEntityFilter.java +++ b/src/main/java/org/opengis/cite/wps20/ReusableEntityFilter.java @@ -1,26 +1,28 @@ package org.opengis.cite.wps20; -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/wps20/SuiteAttribute.java b/src/main/java/org/opengis/cite/wps20/SuiteAttribute.java index cc5a72b..a0a9d4a 100644 --- a/src/main/java/org/opengis/cite/wps20/SuiteAttribute.java +++ b/src/main/java/org/opengis/cite/wps20/SuiteAttribute.java @@ -1,56 +1,71 @@ package org.opengis.cite.wps20; -import com.sun.jersey.api.client.Client; - import java.io.File; import java.net.URI; 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), - - SERVICE_URL("SERVICE_URL", URI.class), - - ECHO_PROCESS_ID("ECHO_PROCESS_ID", String.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), + + SERVICE_URL("SERVICE_URL", URI.class), + + ECHO_PROCESS_ID("ECHO_PROCESS_ID", String.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/wps20/SuiteFixtureListener.java b/src/main/java/org/opengis/cite/wps20/SuiteFixtureListener.java index 0dcc427..cb391e6 100644 --- a/src/main/java/org/opengis/cite/wps20/SuiteFixtureListener.java +++ b/src/main/java/org/opengis/cite/wps20/SuiteFixtureListener.java @@ -1,178 +1,150 @@ package org.opengis.cite.wps20; import java.io.File; -import java.io.IOException; import java.net.URI; import java.util.Map; import java.util.logging.Level; import org.opengis.cite.wps20.util.ClientUtils; import org.opengis.cite.wps20.util.TestSuiteLogger; -import org.opengis.cite.wps20.util.URIUtils; -import org.opengis.cite.wps20.util.XMLUtils; import org.testng.ISuite; import org.testng.ISuiteListener; -import org.w3c.dom.Document; -import com.sun.jersey.api.client.Client; +import jakarta.ws.rs.client.Client; /** - * A listener that performs various tasks before and after a test suite is run, - * usually concerned with maintaining a shared test suite fixture. Since this - * listener is loaded using the ServiceLoader mechanism, its methods will be - * called before those of other suite listeners listed in the test suite - * definition and before any annotated configuration methods. + * A listener that performs various tasks before and after a test suite is run, usually + * concerned with maintaining a shared test suite fixture. Since this listener is loaded + * using the ServiceLoader mechanism, its methods will be called before those of other + * suite listeners listed in the test suite definition and before any annotated + * configuration methods. * - * Attributes set on an ISuite instance are not inherited by constituent test - * group contexts (ITestContext). However, suite attributes are still accessible - * from lower contexts. + * Attributes set on an ISuite instance are not inherited by constituent test group + * contexts (ITestContext). However, suite attributes are still accessible from lower + * contexts. * * @see org.testng.ISuite ISuite interface */ public class SuiteFixtureListener implements ISuiteListener { - @Override - public void onStart(ISuite suite) { - processSuiteParameters(suite); - registerClientComponent(suite); - } + /** {@inheritDoc} */ + @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 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()); } + * catch (Exception x) { throw new + * RuntimeException("Failed to parse resource retrieved from " + iutRef, x); } + * suite.setAttribute(SuiteAttribute.TEST_SUBJECT.getName(), iutDoc); + */ - /** - * 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()); - } catch (Exception x) { - throw new RuntimeException("Failed to parse resource retrieved from " + iutRef, x); - } - suite.setAttribute(SuiteAttribute.TEST_SUBJECT.getName(), iutDoc);*/ - - /* Define SERVICE_URL parameter */ - String ServiceUrlParam = params.get(TestRunArg.IUT.toString()); + /* Define SERVICE_URL parameter */ + String ServiceUrlParam = params.get(TestRunArg.IUT.toString()); if ((null == ServiceUrlParam) || ServiceUrlParam.isEmpty()) { - throw new IllegalArgumentException( - "Required test run parameter not found: " + TestRunArg.IUT.toString()); + throw new IllegalArgumentException("Required test run parameter not found: " + TestRunArg.IUT.toString()); } - //mapping TestRunArg.IUT to SuiteAttribute.SERVICE_URL + // mapping TestRunArg.IUT to SuiteAttribute.SERVICE_URL suite.setAttribute(SuiteAttribute.SERVICE_URL.getName(), URI.create(ServiceUrlParam)); - + /* Define SERVICE_URL parameter */ - String EchoProcessIdParam = params.get(TestRunArg.ECHO_PROCESS_ID.toString()); + String EchoProcessIdParam = params.get(TestRunArg.ECHO_PROCESS_ID.toString()); if ((null == EchoProcessIdParam) || EchoProcessIdParam.isEmpty()) { throw new IllegalArgumentException( "Required test run parameter not found: " + TestRunArg.ECHO_PROCESS_ID.toString()); } String EchoProcessIdRefString = params.get(TestRunArg.ECHO_PROCESS_ID.toString()); - suite.setAttribute(SuiteAttribute.ECHO_PROCESS_ID.getName(), EchoProcessIdRefString); - + suite.setAttribute(SuiteAttribute.ECHO_PROCESS_ID.getName(), EchoProcessIdRefString); + /* - //Define GC_XML_URI parameter - String GcXmlUriParam = params.get(TestRunArg.GC_XML_URI.toString()); - URI GcXmlUriRef = URI.create(GcXmlUriParam.trim()); - File GcXmlUriFile = null; - try { - GcXmlUriFile = URIUtils.dereferenceURI(GcXmlUriRef); - }catch (Exception ex) { - throw new RuntimeException("Failed to dereference resource located at " + GcXmlUriRef, ex); - } - Document GcXmlUriDoc = null; - try { - GcXmlUriDoc = URIUtils.parseURI(GcXmlUriFile.toURI()); - } catch (Exception ex) { - throw new RuntimeException("Failed to parse resource retrieved from " + GcXmlUriRef, ex); - } - suite.setAttribute(SuiteAttribute.GC_XML_URI.getName(), GcXmlUriDoc); - - //Define DP_XML_URI parameter - String DpXmlUriParam = params.get(TestRunArg.DP_XML_URI.toString()); - URI DpXmlUriRef = URI.create(DpXmlUriParam.trim()); - File DpXmlUriFile = null; - try { - DpXmlUriFile = URIUtils.dereferenceURI(DpXmlUriRef); - }catch (Exception ex) { - throw new RuntimeException("Failed to dereference resource located at " + DpXmlUriRef, ex); - } - Document DpXmlUriDoc = null; - try { - DpXmlUriDoc = URIUtils.parseURI(DpXmlUriFile.toURI()); - } catch (Exception ex) { - throw new RuntimeException("Failed to parse resource retrieved from " + DpXmlUriRef, ex); - } - suite.setAttribute(SuiteAttribute.DP_XML_URI.getName(), DpXmlUriDoc); - */ - - - if (TestSuiteLogger.isLoggable(Level.FINE)) { - StringBuilder logMsg = new StringBuilder("Parsed resource retrieved from "); - //logMsg.append(iutRef).append("\n"); - //logMsg.append(XMLUtils.writeNodeToString(iutDoc)); - logMsg.append(ServiceUrlParam).append("\n"); - TestSuiteLogger.log(Level.FINE, logMsg.toString()); - } - } + * //Define GC_XML_URI parameter String GcXmlUriParam = + * params.get(TestRunArg.GC_XML_URI.toString()); URI GcXmlUriRef = + * URI.create(GcXmlUriParam.trim()); File GcXmlUriFile = null; try { GcXmlUriFile + * = URIUtils.dereferenceURI(GcXmlUriRef); }catch (Exception ex) { throw new + * RuntimeException("Failed to dereference resource located at " + GcXmlUriRef, + * ex); } Document GcXmlUriDoc = null; try { GcXmlUriDoc = + * URIUtils.parseURI(GcXmlUriFile.toURI()); } catch (Exception ex) { throw new + * RuntimeException("Failed to parse resource retrieved from " + GcXmlUriRef, ex); + * } suite.setAttribute(SuiteAttribute.GC_XML_URI.getName(), GcXmlUriDoc); + * + * //Define DP_XML_URI parameter String DpXmlUriParam = + * params.get(TestRunArg.DP_XML_URI.toString()); URI DpXmlUriRef = + * URI.create(DpXmlUriParam.trim()); File DpXmlUriFile = null; try { DpXmlUriFile + * = URIUtils.dereferenceURI(DpXmlUriRef); }catch (Exception ex) { throw new + * RuntimeException("Failed to dereference resource located at " + DpXmlUriRef, + * ex); } Document DpXmlUriDoc = null; try { DpXmlUriDoc = + * URIUtils.parseURI(DpXmlUriFile.toURI()); } catch (Exception ex) { throw new + * RuntimeException("Failed to parse resource retrieved from " + DpXmlUriRef, ex); + * } suite.setAttribute(SuiteAttribute.DP_XML_URI.getName(), DpXmlUriDoc); + */ - /** - * 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); - } - } + if (TestSuiteLogger.isLoggable(Level.FINE)) { + StringBuilder logMsg = new StringBuilder("Parsed resource retrieved from "); + // logMsg.append(iutRef).append("\n"); + // logMsg.append(XMLUtils.writeNodeToString(iutDoc)); + logMsg.append(ServiceUrlParam).append("\n"); + 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); + } + } + + /** + * 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/wps20/SuitePreconditions.java b/src/main/java/org/opengis/cite/wps20/SuitePreconditions.java index fb3f9e1..b322312 100644 --- a/src/main/java/org/opengis/cite/wps20/SuitePreconditions.java +++ b/src/main/java/org/opengis/cite/wps20/SuitePreconditions.java @@ -7,33 +7,32 @@ 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. + * @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); + } + } - /** - * 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/wps20/TestFailureListener.java b/src/main/java/org/opengis/cite/wps20/TestFailureListener.java index 4221836..78734a6 100644 --- a/src/main/java/org/opengis/cite/wps20/TestFailureListener.java +++ b/src/main/java/org/opengis/cite/wps20/TestFailureListener.java @@ -1,97 +1,97 @@ package org.opengis.cite.wps20; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; import java.nio.charset.StandardCharsets; -import javax.ws.rs.core.MediaType; + +import org.glassfish.jersey.client.ClientRequest; import org.opengis.cite.wps20.util.ClientUtils; import org.opengis.cite.wps20.util.XMLUtils; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.w3c.dom.Document; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + /** - * A listener that augments a test result with diagnostic information in the - * event that a test method failed. This information will appear in the XML - * report when the test run is completed. + * A listener that augments a test result with diagnostic information in the event that a + * test method failed. This information will appear in the XML report when the test run is + * completed. */ public class TestFailureListener extends TestListenerAdapter { - /** - * Sets the "request" and "response" attributes of a test result. The value - * of these attributes is a string that contains information about the - * content of an outgoing or incoming message: target resource, status code, - * headers, entity (if present). The entity is represented as a String with - * UTF-8 character encoding. - * - * @param result A description of a test result (with a fail verdict). - */ - @Override - public void onTestFailure(ITestResult result) { - super.onTestFailure(result); - Object instance = result.getInstance(); - if (CommonFixture.class.isInstance(instance)) { - CommonFixture fixture = CommonFixture.class.cast(instance); - result.setAttribute("request", getRequestMessageInfo(fixture.request)); - result.setAttribute("response", getResponseMessageInfo(fixture.response)); - } - } + /** + * {@inheritDoc} + * + * Sets the "request" and "response" attributes of a test result. The value of these + * attributes is a string that contains information about the content of an outgoing + * or incoming message: target resource, status code, headers, entity (if present). + * The entity is represented as a String with UTF-8 character encoding. + */ + @Override + public void onTestFailure(ITestResult result) { + super.onTestFailure(result); + Object instance = result.getInstance(); + if (CommonFixture.class.isInstance(instance)) { + CommonFixture fixture = CommonFixture.class.cast(instance); + result.setAttribute("request", getRequestMessageInfo(fixture.request)); + result.setAttribute("response", getResponseMessageInfo(fixture.response)); + } + } - /** - * Gets diagnostic information about a request message. If the request - * contains a message body, it should be represented as a DOM Document node - * or as an object having a meaningful toString() implementation. - * - * @param req An object representing an HTTP request message. - * @return A string containing information gleaned from the request message. - */ - String getRequestMessageInfo(ClientRequest req) { - if (null == req) { - return "No request message."; - } - StringBuilder msgInfo = new StringBuilder(); - msgInfo.append("Method: ").append(req.getMethod()).append('\n'); - msgInfo.append("Target URI: ").append(req.getURI()).append('\n'); - msgInfo.append("Headers: ").append(req.getHeaders()).append('\n'); - if (null != req.getEntity()) { - Object entity = req.getEntity(); - String body; - if (Document.class.isInstance(entity)) { - Document doc = Document.class.cast(entity); - body = XMLUtils.writeNodeToString(doc); - } else { - body = entity.toString(); - } - msgInfo.append(body).append('\n'); - } - return msgInfo.toString(); - } + /** + * Gets diagnostic information about a request message. If the request contains a + * message body, it should be represented as a DOM Document node or as an object + * having a meaningful toString() implementation. + * @param req An object representing an HTTP request message. + * @return A string containing information gleaned from the request message. + */ + String getRequestMessageInfo(ClientRequest req) { + if (null == req) { + return "No request message."; + } + StringBuilder msgInfo = new StringBuilder(); + msgInfo.append("Method: ").append(req.getMethod()).append('\n'); + msgInfo.append("Target URI: ").append(req.getUri()).append('\n'); + msgInfo.append("Headers: ").append(req.getHeaders()).append('\n'); + if (null != req.getEntity()) { + Object entity = req.getEntity(); + String body; + if (Document.class.isInstance(entity)) { + Document doc = Document.class.cast(entity); + body = XMLUtils.writeNodeToString(doc); + } + else { + body = entity.toString(); + } + msgInfo.append(body).append('\n'); + } + return msgInfo.toString(); + } - /** - * Gets diagnostic information about a response message. - * - * @param rsp An object representing an HTTP response message. - * @return A string containing information gleaned from the response - * message. - */ - String getResponseMessageInfo(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/wps20/TestNGController.java b/src/main/java/org/opengis/cite/wps20/TestNGController.java index b6f03a3..2a08090 100644 --- a/src/main/java/org/opengis/cite/wps20/TestNGController.java +++ b/src/main/java/org/opengis/cite/wps20/TestNGController.java @@ -30,140 +30,142 @@ */ public class TestNGController implements TestSuiteController { - private TestRunExecutor executor; - private Properties etsProperties = new Properties(); - - /** - * A convenience method for running the test suite using a command-line - * interface. The default values of the test run arguments are as follows: - *
      - *
    • XML properties file: ${user.home}/test-run-props.xml
    • - *
    • outputDir: ${user.home}
    • - *
    • deleteSubjectOnFinish: false
    • - *
    - *

    - * Synopsis - *

    - * - *
    -     * ets-*-aio.jar [-o|--outputDir $TMPDIR] [-d|--deleteSubjectOnFinish] [test-run-props.xml]
    -     * 
    - * - * @param args - * Test run arguments (optional). The first argument must refer - * to an XML properties file containing the expected set of test - * run arguments. If no argument is supplied, the file located at - * ${user.home}/test-run-props.xml will be used. - * @throws Exception - * If the test run cannot be executed (usually due to - * unsatisfied pre-conditions). - */ - public static void main(String[] args) throws Exception { - CommandLineArguments testRunArgs = new CommandLineArguments(); - JCommander cmd = new JCommander(testRunArgs); - try { - cmd.parse(args); - } catch (ParameterException px) { - System.out.println(px.getMessage()); - cmd.usage(); - } - if (testRunArgs.doDeleteSubjectOnFinish()) { - System.setProperty("deleteSubjectOnFinish", "true"); - } - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - File xmlArgs = testRunArgs.getPropertiesFile(); - Document testRunProps = db.parse(xmlArgs); - TestNGController controller = new TestNGController(testRunArgs.getOutputDir()); - Source testResults = controller.doTestRun(testRunProps); - System.out.println("Test results: " + testResults.getSystemId()); - } - - /** - * Default constructor uses the location given by the "java.io.tmpdir" - * system property as the root output directory. - */ - public TestNGController() { - this(System.getProperty("java.io.tmpdir")); - } - - /** - * Construct a controller that writes results to the given output directory. - * - * @param outputDir - * The location of the directory in which test results will be - * written (a file system path or a 'file' URI). It will be - * created if it does not exist. - */ - public TestNGController(String outputDir) { - InputStream is = getClass().getResourceAsStream("ets.properties"); - try { - this.etsProperties.load(is); - } catch (IOException ex) { - TestSuiteLogger.log(Level.WARNING, "Unable to load ets.properties. " + ex.getMessage()); - } - URL tngSuite = TestNGController.class.getResource("testng.xml"); - File resultsDir; - if (null == outputDir || outputDir.isEmpty()) { - resultsDir = new File(System.getProperty("user.home")); - } else if (outputDir.startsWith("file:")) { - resultsDir = new File(URI.create(outputDir)); - } else { - resultsDir = new File(outputDir); - } - TestSuiteLogger.log(Level.CONFIG, "Using TestNG config: " + tngSuite); - TestSuiteLogger.log(Level.CONFIG, "Using outputDirPath: " + resultsDir.getAbsolutePath()); - // NOTE: setting third argument to 'true' enables the default listeners - this.executor = new TestNGExecutor(tngSuite.toString(), resultsDir.getAbsolutePath(), false); - } - - @Override - public String getCode() { - return etsProperties.getProperty("ets-code"); - } - - @Override - public String getVersion() { - return etsProperties.getProperty("ets-version"); - } - - @Override - public String getTitle() { - return etsProperties.getProperty("ets-title"); - } - - @Override - public Source doTestRun(Document testRunArgs) throws Exception { - validateTestRunArgs(testRunArgs); - return executor.execute(testRunArgs); - } - - /** - * Validates the test run arguments. The test run is aborted if any of these - * checks fail. - * - * @param testRunArgs - * A DOM Document containing a set of XML properties (key-value - * pairs). - * @throws IllegalArgumentException - * If any arguments are missing or invalid for some reason. - */ - void validateTestRunArgs(Document testRunArgs) { - if (null == testRunArgs || !testRunArgs.getDocumentElement().getNodeName().equals("properties")) { - throw new IllegalArgumentException("Input is not an XML properties document."); - } - NodeList entries = testRunArgs.getDocumentElement().getElementsByTagName("entry"); - if (entries.getLength() == 0) { - throw new IllegalArgumentException("No test run arguments found."); - } - Map args = new HashMap(); - for (int i = 0; i < entries.getLength(); i++) { - Element entry = (Element) entries.item(i); - args.put(entry.getAttribute("key").toUpperCase(), 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); + 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").toUpperCase(), 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/wps20/TestRunArg.java b/src/main/java/org/opengis/cite/wps20/TestRunArg.java index 0567dac..3bcfc45 100644 --- a/src/main/java/org/opengis/cite/wps20/TestRunArg.java +++ b/src/main/java/org/opengis/cite/wps20/TestRunArg.java @@ -5,22 +5,20 @@ */ public enum TestRunArg { - /** - * An absolute URI that refers to a representation of the test subject or - * metadata about it. - */ - IUT, - ECHO_PROCESS_ID - /*SERVICE_URL, - GC_XML_URI, - DP_XML_URI, - EX_SNC_XML_URI, - EX_ANC_XML_URI, - EX_ATO_XML_URI*/ + /** + * An absolute URI that refers to a representation of the test subject or metadata + * about it. + */ + IUT, ECHO_PROCESS_ID + /* + * SERVICE_URL, GC_XML_URI, DP_XML_URI, EX_SNC_XML_URI, EX_ANC_XML_URI, EX_ATO_XML_URI + */ ; - @Override - public String toString() { - return name().toUpperCase(); - } + /** {@inheritDoc} */ + @Override + public String toString() { + return name().toUpperCase(); + } + } diff --git a/src/main/java/org/opengis/cite/wps20/TestRunListener.java b/src/main/java/org/opengis/cite/wps20/TestRunListener.java index 71c51f7..4da1a6e 100644 --- a/src/main/java/org/opengis/cite/wps20/TestRunListener.java +++ b/src/main/java/org/opengis/cite/wps20/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/wps20/asynchronous/AsyncTests.java b/src/main/java/org/opengis/cite/wps20/asynchronous/AsyncTests.java index 90ae21f..b0d9816 100644 --- a/src/main/java/org/opengis/cite/wps20/asynchronous/AsyncTests.java +++ b/src/main/java/org/opengis/cite/wps20/asynchronous/AsyncTests.java @@ -1,57 +1,17 @@ package org.opengis.cite.wps20.asynchronous; -import static org.testng.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.File; import java.io.IOException; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; -import java.net.HttpURLConnection; import java.net.URI; //import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; -//import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.charset.Charset; -//import java.util.ArrayList; -//import java.util.HashMap; -import java.util.HashSet; import java.util.LinkedHashMap; //import java.util.List; import java.util.Map; -import java.util.Set; -import java.util.Random; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.OutputKeys; -//import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.Validator; //import org.opengis.cite.wps20.Namespaces; //import org.opengis.cite.wps20.SuiteAttribute; import org.opengis.cite.wps20.CommonFixture; import org.opengis.cite.wps20.basictests.BasicTests; -import org.testng.Assert; -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -//import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /*import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.SaxonApiException; @@ -59,159 +19,198 @@ import net.sf.saxon.s9api.XPathSelector; import net.sf.saxon.s9api.XdmNode; import net.sf.saxon.s9api.XdmValue;*/ +import org.opengis.cite.wps20.util.URIUtils; +import org.testng.Assert; +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; -import org.opengis.cite.wps20.util.*; - +/** + *

    + * AsyncTests class. + *

    + * + */ public class AsyncTests extends CommonFixture { - + /** - * A.5.14. Verify that the server can handle GetStatus requests via POST/XML. - * Flow of Test Description: Send a valid XML Execute request to the server under test, - * setting the “mode” attribute to “async”. Verify that a valid wps:StatusInfo document - * is returned. Extract the wps:JobID. Send a valid XML GetStatus request to the server - * under test using the extracted JobID. Test passes if a valid wps:StatusInfo document - * is returned. - * - * @throws Exception + * A.5.14. Verify that the server can handle GetStatus requests via POST/XML. Flow of + * Test Description: Send a valid XML Execute request to the server under test, + * setting the “mode” attribute to “async”. Verify that a valid wps:StatusInfo + * document is returned. Extract the wps:JobID. Send a valid XML GetStatus request to + * the server under test using the extracted JobID. Test passes if a valid + * wps:StatusInfo document is returned. + * @throws java.lang.Exception */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.14. Verify that the server can handle GetStatus requests via POST/XML.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.14. Verify that the server can handle GetStatus requests via POST/XML.") public void ValidGetStatusViaPOSTXML() throws Exception { String SERVICE_URL = this.ServiceUrl.toString(); - Document literalDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, this.EchoProcessId, LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); + Document literalDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, this.EchoProcessId, + LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); Element executeElement = (Element) literalDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Execute").item(0); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Execute") + .item(0); executeElement.setAttribute("mode", "async"); executeElement.setAttribute("response", "document"); - String VAEXmlString = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); - Document VAEDocument = TransformXMLStringToXMLDocument(VAEXmlString); + String VAEXmlString = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); + Document VAEDocument = TransformXMLStringToXMLDocument(VAEXmlString); - Boolean VAE_Flag = (VAEDocument.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "StatusInfo").getLength() > 0) ? true : false; + Boolean VAE_Flag = (VAEDocument.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "StatusInfo") + .getLength() > 0) ? true : false; + + if (VAE_Flag) { + Element JobIDElement1 = (Element) VAEDocument + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID") + .item(0); - if (VAE_Flag) { - Element JobIDElement1 = (Element) VAEDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID").item(0); - URI URIGetStatusTemplate = BasicTests.class.getResource(GET_STATUS_TEMPLATE_PATH).toURI(); - Document GetStatusDocument = URIUtils.parseURI(URIGetStatusTemplate); - Element JobIDElement2 = (Element) GetStatusDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID").item(0); + Document GetStatusDocument = URIUtils.parseURI(URIGetStatusTemplate); + Element JobIDElement2 = (Element) GetStatusDocument + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID") + .item(0); JobIDElement2.setTextContent(JobIDElement1.getTextContent()); - - String VGSXmlString = GetContentFromPOSTXMLRequest(SERVICE_URL, GetStatusDocument); - Document VGSDocument = TransformXMLStringToXMLDocument(VGSXmlString); - - Boolean VGS_Flag = (VGSDocument.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Status").getLength() > 0) ? true : false; - + + String VGSXmlString = GetContentFromPOSTXMLRequest(SERVICE_URL, GetStatusDocument); + Document VGSDocument = TransformXMLStringToXMLDocument(VGSXmlString); + + Boolean VGS_Flag = (VGSDocument.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Status") + .getLength() > 0) ? true : false; + if (VGS_Flag) { String msg = "Valid GetStatus via POST/XML for WPS 2.0"; Assert.assertTrue(VGS_Flag, msg); - } else { + } + else { String msg = "Invalid GetStatus via POST/XML for WPS 2.0"; Assert.assertTrue(VGS_Flag, msg); } - } else { + } + else { String msg = "Invalid Execute via POST/XML for WPS 2.0"; Assert.assertTrue(VAE_Flag, msg); } } - + /** - * A.5.15. VSend a valid XML Execute request to the server under test, setting the “mode” - * attribute to “async”. Modulate the “response” parameter. Verify that a valid wps:StatusInfo - * document is returned. Extract the wps:JobID. Check the status of the job. If the job - * succeeded, send a valid XML GetResult request to the server under test using the extracted - * JobID. Depending on the value of the “response” parameter of the above Execute request. - * - * @throws Exception + * A.5.15. VSend a valid XML Execute request to the server under test, setting the + * “mode” attribute to “async”. Modulate the “response” parameter. Verify that a valid + * wps:StatusInfo document is returned. Extract the wps:JobID. Check the status of the + * job. If the job succeeded, send a valid XML GetResult request to the server under + * test using the extracted JobID. Depending on the value of the “response” parameter + * of the above Execute request. + * @throws java.lang.Exception */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.15. Verify that the server can handle GetResult requests via POST/XML.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.15. Verify that the server can handle GetResult requests via POST/XML.") public void ValidGetResultViaPOSTXML() throws Exception { String SERVICE_URL = this.ServiceUrl.toString(); - Document literalDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, this.EchoProcessId, LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); + Document literalDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, this.EchoProcessId, + LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); Element executeElement = (Element) literalDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Execute").item(0); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Execute") + .item(0); executeElement.setAttribute("mode", "async"); executeElement.setAttribute("response", "raw"); - String VAEXmlString1 = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); - Document VAEDocument1 = TransformXMLStringToXMLDocument(VAEXmlString1); - Boolean VAE_Flag1 = (VAEDocument1.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "StatusInfo").getLength() > 0) ? true : false; - - executeElement.setAttribute("response", "document"); - String VAEXmlString2 = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); - Document VAEDocument2 = TransformXMLStringToXMLDocument(VAEXmlString2); - Boolean VAE_Flag2 = (VAEDocument2.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "StatusInfo").getLength() > 0) ? true : false; - + String VAEXmlString1 = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); + Document VAEDocument1 = TransformXMLStringToXMLDocument(VAEXmlString1); + Boolean VAE_Flag1 = (VAEDocument1.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "StatusInfo") + .getLength() > 0) ? true : false; + + executeElement.setAttribute("response", "document"); + String VAEXmlString2 = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); + Document VAEDocument2 = TransformXMLStringToXMLDocument(VAEXmlString2); + Boolean VAE_Flag2 = (VAEDocument2.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "StatusInfo") + .getLength() > 0) ? true : false; + Boolean VAE_Flag = VAE_Flag1 && VAE_Flag2; - - if (VAE_Flag) { - URI URIGetResultTemplate1 = BasicTests.class.getResource(GET_RESULT_TEMPLATE_PATH).toURI(); - Element JobIDElement1 = (Element) VAEDocument1.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID").item(0); - Document GetResultDocument1 = URIUtils.parseURI(URIGetResultTemplate1); - Element JobIDElement2 = (Element) GetResultDocument1.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID").item(0); - JobIDElement2.setTextContent(JobIDElement1.getTextContent()); - String VGRXmlString1 = GetContentFromPOSTXMLRequest(SERVICE_URL, GetResultDocument1); - Document VGRDocument1 = TransformXMLStringToXMLDocument(VGRXmlString1); - Boolean VGR_Flag1 = (VGRDocument1.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "LiteralValue").getLength() > 0) ? true : false; - - URI URIGetResultTemplate2 = BasicTests.class.getResource(GET_RESULT_TEMPLATE_PATH).toURI(); - Element JobIDElement3 = (Element) VAEDocument2.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID").item(0); - Document GetResultDocument2 = URIUtils.parseURI(URIGetResultTemplate2); - Element JobIDElement4 = (Element) GetResultDocument2.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID").item(0); - JobIDElement4.setTextContent(JobIDElement3.getTextContent()); - String VGRXmlString2 = GetContentFromPOSTXMLRequest(SERVICE_URL, GetResultDocument2); - - Boolean VGR_Flag2 = VGRXmlString2.contains("LiteralValue") ? true : false; - -// Document VGRDocument2 = TransformXMLStringToXMLDocument(VGRXmlString2); -// Boolean VGR_Flag2 = (VGRDocument2.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Result").getLength() > 0) ? true : false; - - Boolean VGR_Flag = VGR_Flag1 && VGR_Flag2; - + + if (VAE_Flag) { + URI URIGetResultTemplate1 = BasicTests.class.getResource(GET_RESULT_TEMPLATE_PATH).toURI(); + Element JobIDElement1 = (Element) VAEDocument1 + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID") + .item(0); + Document GetResultDocument1 = URIUtils.parseURI(URIGetResultTemplate1); + Element JobIDElement2 = (Element) GetResultDocument1 + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID") + .item(0); + JobIDElement2.setTextContent(JobIDElement1.getTextContent()); + String VGRXmlString1 = GetContentFromPOSTXMLRequest(SERVICE_URL, GetResultDocument1); + Document VGRDocument1 = TransformXMLStringToXMLDocument(VGRXmlString1); + Boolean VGR_Flag1 = (VGRDocument1.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "LiteralValue") + .getLength() > 0) ? true : false; + + URI URIGetResultTemplate2 = BasicTests.class.getResource(GET_RESULT_TEMPLATE_PATH).toURI(); + Element JobIDElement3 = (Element) VAEDocument2 + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID") + .item(0); + Document GetResultDocument2 = URIUtils.parseURI(URIGetResultTemplate2); + Element JobIDElement4 = (Element) GetResultDocument2 + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID") + .item(0); + JobIDElement4.setTextContent(JobIDElement3.getTextContent()); + String VGRXmlString2 = GetContentFromPOSTXMLRequest(SERVICE_URL, GetResultDocument2); + + Boolean VGR_Flag2 = VGRXmlString2.contains("LiteralValue") ? true : false; + + // Document VGRDocument2 = TransformXMLStringToXMLDocument(VGRXmlString2); + // Boolean VGR_Flag2 = + // (VGRDocument2.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", + // "Result").getLength() > 0) ? true : false; + + Boolean VGR_Flag = VGR_Flag1 && VGR_Flag2; + if (VGR_Flag) { String msg = "Valid GetResult via POST/XML for WPS 2.0"; Assert.assertTrue(VGR_Flag, msg); - } else { + } + else { String msg = "Invalid GetResult via POST/XML for WPS 2.0"; Assert.assertTrue(VGR_Flag, msg); } - } else { + } + else { String msg = "Invalid Execute via POST/XML for WPS 2.0"; Assert.assertTrue(VAE_Flag, msg); } } - - /** - * A.5.18. Verify that the server can handle GetStatus requests via GET/KVP. - * Send a valid XML Execute request to the server under test, setting the “mode” attribute - * to “async”. Verify that a valid wps:StatusInfo document is returned. Extract the - * wps:JobID. Send a valid KVP GetStatus request to the server under test, using the - * extracted JobID and modulating upper and lower case of the parameter names. Test passes - * if a valid document of the type wps:StatusInfo is returned. + * A.5.18. Verify that the server can handle GetStatus requests via GET/KVP. Send a + * valid XML Execute request to the server under test, setting the “mode” attribute to + * “async”. Verify that a valid wps:StatusInfo document is returned. Extract the + * wps:JobID. Send a valid KVP GetStatus request to the server under test, using the + * extracted JobID and modulating upper and lower case of the parameter names. Test + * passes if a valid document of the type wps:StatusInfo is returned. * @throws IOException * @throws URISyntaxException * @throws SAXException */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.18. Verify that the server can handle GetStatus requests via GET/KVP.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.18. Verify that the server can handle GetStatus requests via GET/KVP.") private void ValidGetStatusViaGETKVP() throws IOException, URISyntaxException, SAXException { String SERVICE_URL = this.ServiceUrl.toString(); - Document literalDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, this.EchoProcessId, LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); + Document literalDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, this.EchoProcessId, + LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); Element executeElement = (Element) literalDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Execute").item(0); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Execute") + .item(0); executeElement.setAttribute("mode", "async"); executeElement.setAttribute("response", "document"); - String VAEXmlString = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); - Document VAEDocument = TransformXMLStringToXMLDocument(VAEXmlString); + String VAEXmlString = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); + Document VAEDocument = TransformXMLStringToXMLDocument(VAEXmlString); + + Boolean VAE_Flag = (VAEDocument.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "StatusInfo") + .getLength() > 0) ? true : false; + + if (VAE_Flag) { + Element JobIDElement1 = (Element) VAEDocument + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID") + .item(0); - Boolean VAE_Flag = (VAEDocument.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "StatusInfo").getLength() > 0) ? true : false; - - if (VAE_Flag) { - Element JobIDElement1 = (Element) VAEDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID").item(0); - Map GSU_Parameters = new LinkedHashMap<>(); GSU_Parameters.put("Service".toUpperCase(), "WPS"); GSU_Parameters.put("Version".toUpperCase(), "2.0.0"); @@ -228,103 +227,126 @@ private void ValidGetStatusViaGETKVP() throws IOException, URISyntaxException, S String GSL_XmlString = GetContentFromGETKVPRequest(SERVICE_URL, GSL_Parameters); Document GSL_Document = TransformXMLStringToXMLDocument(GSL_XmlString); - Boolean GS_KVP_Flag = (GSU_Document.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Status").getLength() > 0 - && GSL_Document.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Status").getLength() > 0) ? true : false; - + Boolean GS_KVP_Flag = (GSU_Document.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Status") + .getLength() > 0 + && GSL_Document.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Status").getLength() > 0) + ? true : false; + if (GS_KVP_Flag) { String msg = "Valid GetStatus via GET/KVP for WPS 2.0"; Assert.assertTrue(GS_KVP_Flag, msg); - } else { + } + else { String msg = "Invalid GetStatus via GET/KVP for WPS 2.0"; Assert.assertTrue(GS_KVP_Flag, msg); } - } else { + } + else { String msg = "Invalid Execute via POST/XML for WPS 2.0"; Assert.assertTrue(VAE_Flag, msg); } } - + /** - * A.5.19. Verify that the server can handle GetResult requests via GET/KVP. - * Send a valid XML Execute request to the server under test, setting the “mode” attribute - * to “async”. Modulate the “response” parameter. Verify that a valid wps:StatusInfo - * document is returned. Extract the wps:JobID. Check the status of the job. If the job - * succeeded, send a valid KVP GetResult request to the server under test using the - * extracted JobID and modulating upper and lower case of the parameter names. Depending - * on the value of the “response” parameter of the above Execute request: - * - Parameter value equal “document”. Verify that a valid Execute wps:Result document is returned. - * - Parameter equal to “raw”. Verify that raw is returned. + * A.5.19. Verify that the server can handle GetResult requests via GET/KVP. Send a + * valid XML Execute request to the server under test, setting the “mode” attribute to + * “async”. Modulate the “response” parameter. Verify that a valid wps:StatusInfo + * document is returned. Extract the wps:JobID. Check the status of the job. If the + * job succeeded, send a valid KVP GetResult request to the server under test using + * the extracted JobID and modulating upper and lower case of the parameter names. + * Depending on the value of the “response” parameter of the above Execute request: - + * Parameter value equal “document”. Verify that a valid Execute wps:Result document + * is returned. - Parameter equal to “raw”. Verify that raw is returned. * @throws IOException * @throws URISyntaxException * @throws SAXException */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.19. Verify that the server can handle GetResult requests via GET/KVP.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.19. Verify that the server can handle GetResult requests via GET/KVP.") private void ValidGetResultViaGETKVP() throws IOException, URISyntaxException, SAXException { String SERVICE_URL = this.ServiceUrl.toString(); - Document literalDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, this.EchoProcessId, LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); + Document literalDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, this.EchoProcessId, + LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); Element executeElement = (Element) literalDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Execute").item(0); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Execute") + .item(0); executeElement.setAttribute("mode", "async"); - + executeElement.setAttribute("response", "document"); - String VAEXmlString1 = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); - Document VAEDocument1 = TransformXMLStringToXMLDocument(VAEXmlString1); - Boolean VAE_Flag1 = (VAEDocument1.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "StatusInfo").getLength() > 0) ? true : false; - - executeElement.setAttribute("response", "raw"); - String VAEXmlString2 = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); + String VAEXmlString1 = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); + Document VAEDocument1 = TransformXMLStringToXMLDocument(VAEXmlString1); + Boolean VAE_Flag1 = (VAEDocument1.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "StatusInfo") + .getLength() > 0) ? true : false; + + executeElement.setAttribute("response", "raw"); + String VAEXmlString2 = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); System.out.println(VAEXmlString2); - Document VAEDocument2 = TransformXMLStringToXMLDocument(VAEXmlString2); - Boolean VAE_Flag2 = (VAEDocument2.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "StatusInfo").getLength() > 0) ? true : false; - + Document VAEDocument2 = TransformXMLStringToXMLDocument(VAEXmlString2); + Boolean VAE_Flag2 = (VAEDocument2.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "StatusInfo") + .getLength() > 0) ? true : false; + Boolean VAE_Flag = VAE_Flag1 && VAE_Flag2; - + if (VAE_Flag) { - Element JobIDElement1 = (Element) VAEDocument1 - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID").item(0); - CheckGetStatus(SERVICE_URL, JobIDElement1.getTextContent()); + Element JobIDElement1 = (Element) VAEDocument1 + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID") + .item(0); + CheckGetStatus(SERVICE_URL, JobIDElement1.getTextContent()); Map GR_Parameters1 = new LinkedHashMap<>(); GR_Parameters1.put("Service", "WPS"); GR_Parameters1.put("Version", "2.0.0"); GR_Parameters1.put("Request", "GetResult"); GR_Parameters1.put("JobID", JobIDElement1.getTextContent()); - String GR_XmlString1 = GetContentFromGETKVPRequest(SERVICE_URL, GR_Parameters1); - Document GR_Document1 = TransformXMLStringToXMLDocument(GR_XmlString1); - - Boolean VGR_Flag1 = (GR_Document1.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Result").getLength() > 0) ? true : false; - - Element JobIDElement2 = (Element) VAEDocument2 - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID").item(0); - CheckGetStatus(SERVICE_URL, JobIDElement2.getTextContent()); + String GR_XmlString1 = GetContentFromGETKVPRequest(SERVICE_URL, GR_Parameters1); + Document GR_Document1 = TransformXMLStringToXMLDocument(GR_XmlString1); + + Boolean VGR_Flag1 = (GR_Document1.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Result") + .getLength() > 0) ? true : false; + + Element JobIDElement2 = (Element) VAEDocument2 + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID") + .item(0); + CheckGetStatus(SERVICE_URL, JobIDElement2.getTextContent()); Map GR_Parameters2 = new LinkedHashMap<>(); GR_Parameters2.put("Service", "WPS"); GR_Parameters2.put("Version", "2.0.0"); GR_Parameters2.put("Request", "GetResult"); GR_Parameters2.put("JobID", JobIDElement2.getTextContent()); - String GR_XmlString2 = GetContentFromGETKVPRequest(SERVICE_URL, GR_Parameters2); -// System.out.println(GR_XmlString2); -// System.out.println(JobIDElement2.getTextContent()); - -// Boolean VGR_Flag2 = GR_XmlString2.contains("wps:LiteralValue") ? true : false; - - Document GR_Document2 = TransformXMLStringToXMLDocument(GR_XmlString2); - Boolean VGR_Flag2 = (GR_Document2.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "LiteralValue").getLength() > 0) ? true : false; - + String GR_XmlString2 = GetContentFromGETKVPRequest(SERVICE_URL, GR_Parameters2); + // System.out.println(GR_XmlString2); + // System.out.println(JobIDElement2.getTextContent()); + + // Boolean VGR_Flag2 = GR_XmlString2.contains("wps:LiteralValue") ? true : + // false; + + Document GR_Document2 = TransformXMLStringToXMLDocument(GR_XmlString2); + Boolean VGR_Flag2 = (GR_Document2.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "LiteralValue") + .getLength() > 0) ? true : false; + Boolean VGR_Flag = VGR_Flag1 && VGR_Flag2; - + if (VGR_Flag) { String msg = "Valid GetResult via GET/KVP for WPS 2.0"; Assert.assertTrue(VGR_Flag, msg); - } else { + } + else { String msg = "Invalid GetResult via GET/KVP for WPS 2.0"; Assert.assertTrue(VGR_Flag, msg); } - } else { + } + else { String msg = "Invalid Execute via POST/XML for WPS 2.0"; Assert.assertTrue(VAE_Flag, msg); } } - + + /** + *

    + * CheckGetStatus. + *

    + * @param SERVICE_URL a {@link java.lang.String} object + * @param jobID a {@link java.lang.String} object + */ public void CheckGetStatus(String SERVICE_URL, String jobID) { Map GR_Parameters1 = new LinkedHashMap<>(); GR_Parameters1.put("Service", "WPS"); @@ -334,12 +356,15 @@ public void CheckGetStatus(String SERVICE_URL, String jobID) { String GR_XmlString1 = GetContentFromGETKVPRequest(SERVICE_URL, GR_Parameters1); Document docGetStatus = TransformXMLStringToXMLDocument(GR_XmlString1); - Boolean statusFlag = (docGetStatus.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Status").getLength() > 0) ? true : false; + Boolean statusFlag = (docGetStatus.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Status") + .getLength() > 0) ? true : false; String msg = "Invalid GetStatus via GET/KVP for WPS 2.0"; if (!statusFlag) Assert.assertTrue(false, msg); else { - Element statusElement = (Element) docGetStatus.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Status").item(0); + Element statusElement = (Element) docGetStatus + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Status") + .item(0); String status = statusElement.getTextContent(); if (status.toLowerCase().equals("succeeded")) { return; @@ -349,5 +374,5 @@ public void CheckGetStatus(String SERVICE_URL, String jobID) { } } } - + } diff --git a/src/main/java/org/opengis/cite/wps20/basictests/BasicTests.java b/src/main/java/org/opengis/cite/wps20/basictests/BasicTests.java index e2f9f8f..595d961 100644 --- a/src/main/java/org/opengis/cite/wps20/basictests/BasicTests.java +++ b/src/main/java/org/opengis/cite/wps20/basictests/BasicTests.java @@ -2,14 +2,9 @@ import static org.testng.Assert.assertTrue; -import java.io.BufferedReader; import java.io.DataOutputStream; -import java.io.File; import java.io.IOException; -import java.io.InputStreamReader; import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; import java.net.HttpURLConnection; import java.net.URI; //import java.net.URI; @@ -17,24 +12,15 @@ import java.net.URL; //import java.net.URLConnection; import java.net.URLEncoder; -import java.nio.charset.Charset; //import java.util.ArrayList; //import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; //import java.util.List; import java.util.Map; -import java.util.Set; import java.util.Random; +import java.util.Set; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.OutputKeys; -//import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.Validator; @@ -42,16 +28,6 @@ //import org.opengis.cite.wps20.Namespaces; //import org.opengis.cite.wps20.SuiteAttribute; import org.opengis.cite.wps20.CommonFixture; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -//import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /*import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.SaxonApiException; @@ -59,28 +35,41 @@ import net.sf.saxon.s9api.XPathSelector; import net.sf.saxon.s9api.XdmNode; import net.sf.saxon.s9api.XdmValue;*/ +import org.opengis.cite.wps20.util.URIUtils; +import org.opengis.cite.wps20.util.ValidationUtils; +import org.testng.Assert; +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +//import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; -import org.opengis.cite.wps20.util.*; - +/** + *

    + * BasicTests class. + *

    + * + */ public class BasicTests extends CommonFixture { - + /** - * A.4.1. Verify that a given process description is in compliance with the -Process XML encoding. Verify that the tested document fulfils all requirements listed in -req/native-process/xml-encoding/process. - * + * A.4.1. Verify that a given process description is in compliance with the Process + * XML encoding. Verify that the tested document fulfils all requirements listed in + * req/native-process/xml-encoding/process. * @throws IOException * @throws URISyntaxException * @throws SAXException */ - @Test(enabled = true, dependsOnMethods = {}, groups = "A.4. WPS Process Model Encoding", description = "A.4.1. Verify that a given process description is in compliance with the Process XML encoding") - private void VerifyProcessXMLEncoding() throws IOException, URISyntaxException, SAXException { + @Test(enabled = true, dependsOnMethods = {}, groups = "A.4. WPS Process Model Encoding", + description = "A.4.1. Verify that a given process description is in compliance with the Process XML encoding") + private void VerifyProcessXMLEncoding() throws IOException, URISyntaxException, SAXException { String SERVICE_URL = this.ServiceUrl.toString(); URI uriLiteralRequestTemplate = BasicTests.class.getResource(LITERAL_REQUEST_TEMPLATE_PATH).toURI(); Document SEPDocument = URIUtils.parseURI(uriLiteralRequestTemplate); String ECHO_PROCESS_ID = this.EchoProcessId; - + Map DP_Parameters = new LinkedHashMap<>(); DP_Parameters.put("Service", "WPS"); DP_Parameters.put("Version", "2.0.0"); @@ -93,27 +82,29 @@ private void VerifyProcessXMLEncoding() throws IOException, URISyntaxException, VPE_Flag = true; String msg = "Valid Process XML Encoding for WPS 2.0"; Assert.assertTrue(VPE_Flag, msg); - } else { + } + else { VPE_Flag = false; String msg = "Invalid Process XML Encoding for WPS 2.0"; Assert.assertTrue(VPE_Flag, msg); } } - + /** - * A.4.3. Verify that a given process description is in compliance with the -Process XML encoding. Verify that the tested document fulfills all requirements listed in -req/native-process/xml-encoding/process. - * @throws Exception + * A.4.3. Verify that a given process description is in compliance with the Process + * XML encoding. Verify that the tested document fulfills all requirements listed in + * req/native-process/xml-encoding/process. + * @throws Exception */ - @Test(enabled = true, dependsOnMethods = {}, groups = "A.4. WPS Process Model Encoding", description = "A.4.3. Verify that any XML data type description and values that are used in conjunction with the native process model are encoded in compliance with the process model XML encoding.") + @Test(enabled = true, dependsOnMethods = {}, groups = "A.4. WPS Process Model Encoding", + description = "A.4.3. Verify that any XML data type description and values that are used in conjunction with the native process model are encoded in compliance with the process model XML encoding.") private void VerifyProcessDataTypeXMLEncoding() throws Exception { String SERVICE_URL = this.ServiceUrl.toString(); URI uriLiteralRequestTemplate = BasicTests.class.getResource(LITERAL_REQUEST_TEMPLATE_PATH).toURI(); Document SEPDocument = URIUtils.parseURI(uriLiteralRequestTemplate); String ECHO_PROCESS_ID = this.EchoProcessId; - + Map DP_Parameters = new LinkedHashMap<>(); DP_Parameters.put("Service", "WPS"); DP_Parameters.put("Version", "2.0.0"); @@ -121,66 +112,74 @@ private void VerifyProcessDataTypeXMLEncoding() throws Exception { DP_Parameters.put("Identifier", ECHO_PROCESS_ID); String VPE_String = GetContentFromGETKVPRequest(SERVICE_URL, DP_Parameters); Document VPE_Document = TransformXMLStringToXMLDocument(VPE_String); - + Boolean HLCB_Flag = true; - - if(VPE_Document.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "LiteralData").getLength() == 0) { + + if (VPE_Document.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "LiteralData").getLength() == 0) { HLCB_Flag = false; } - - if(VPE_Document.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "ComplexData").getLength() == 0) { + + if (VPE_Document.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "ComplexData").getLength() == 0) { HLCB_Flag = false; } - - if(VPE_Document.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "BoundingBoxData").getLength() == 0) { + + if (VPE_Document.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "BoundingBoxData").getLength() == 0) { HLCB_Flag = false; } - - if(HLCB_Flag) { + + if (HLCB_Flag) { Boolean VPE_Flag = null; String msg = null; - + if (isXMLSchemaValid(VPE_String, "xsd/opengis/wps/2.0/wps.xsd")) { VPE_Flag = true; msg = "Valid Process DataTypes XML Encoding for WPS 2.0"; - } else { + } + else { VPE_Flag = false; msg = "Invalid Process DataTypes XML Encoding for WPS 2.0"; } - + Assert.assertTrue(VPE_Flag, msg); - } else { + } + else { String msg = "The process should include ComplexData, LiteralData and BoundingBoxData"; Assert.assertTrue(HLCB_Flag, msg); } } - + /** - * Precondition. Verify that the server can handle echo process - * Flow of Test Description - Step 1: Send a valid DescribeProcess request to the server under test, setting the identifier to the echo process id. Verify that the server offers an echo process. - * Flow of Test Description - Step 2: Send a valid Execute request to the server under test, setting the identifier to the echo process id. Verify that the server can handle echo process. + * Precondition. Verify that the server can handle echo process Flow of Test + * Description - Step 1: Send a valid DescribeProcess request to the server under + * test, setting the identifier to the echo process id. Verify that the server offers + * an echo process. Flow of Test Description - Step 2: Send a valid Execute request to + * the server under test, setting the identifier to the echo process id. Verify that + * the server can handle echo process. + * @throws java.lang.Exception if any. */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "Precondition: Verify that the server can handle echo process") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "Precondition: Verify that the server can handle echo process") public void ValidEchoProcess() throws Exception { String SERVICE_URL = this.ServiceUrl.toString(); // Get the processid from user and replace the processid in the template xml // request file String ECHO_PROCESS_ID = this.EchoProcessId; - - + // Test LiteralData - Document SEPDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, ECHO_PROCESS_ID, LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); + Document SEPDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, ECHO_PROCESS_ID, LITERAL_INPUT_ID, + LITERAL_OUTPUT_ID); String resultLiteral = GetContentFromPOSTXMLRequest(SERVICE_URL, SEPDocument); - //System.out.println("【Test LiteralData】\n" + resultLiteral); + // System.out.println("【Test LiteralData】\n" + resultLiteral); String msgLiteral = "Echo Process LiteralData Test Failed"; // Check the response string is equal to hello_literal(hello_literal is defined // in file from LITERAL_REQUEST_TEMPLATE_PATH) Assert.assertTrue(resultLiteral.contains("hello_literal"), msgLiteral); // Test ComplexData - SEPDocument = GetDocumentTemplate(COMPLEX_REQUEST_TEMPLATE_PATH, ECHO_PROCESS_ID, COMPLEX_INPUT_ID, COMPLEX_OUTPUT_ID); + SEPDocument = GetDocumentTemplate(COMPLEX_REQUEST_TEMPLATE_PATH, ECHO_PROCESS_ID, COMPLEX_INPUT_ID, + COMPLEX_OUTPUT_ID); String responseComplex = GetContentFromPOSTXMLRequest(SERVICE_URL, SEPDocument); - //System.out.println("【Test ComplexData】\n" + responseComplex); + // System.out.println("【Test ComplexData】\n" + responseComplex); Document complexOutputDocument = TransformXMLStringToXMLDocument(responseComplex); String resultComplex = complexOutputDocument.getElementsByTagName("testElement").item(0).getTextContent(); String msgComplex = "Echo Process ComplexData Test Failed"; @@ -188,16 +187,21 @@ public void ValidEchoProcess() throws Exception { // is defined in file from COMPLEX_REQUEST_TEMPLATE_PATH) Assert.assertTrue(resultComplex.equals("hello_complex"), msgComplex); } - - public Document GetDocumentTemplate(String templatePath, String processId, String inputId, String outputId) throws URISyntaxException, SAXException, IOException { + + /** {@inheritDoc} */ + public Document GetDocumentTemplate(String templatePath, String processId, String inputId, String outputId) + throws URISyntaxException, SAXException, IOException { URI uriLiteralRequestTemplate = BasicTests.class.getResource(templatePath).toURI(); Document SEPDocument = URIUtils.parseURI(uriLiteralRequestTemplate); Element requestInputElement = (Element) SEPDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Input").item(0); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Input") + .item(0); Element requestOutputElement = (Element) SEPDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Output").item(0); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Output") + .item(0); Element requestIdElement = (Element) SEPDocument - .getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "Identifier").item(0); + .getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "Identifier") + .item(0); // replace id requestIdElement.setTextContent(processId); requestInputElement.setAttribute("id", inputId); @@ -206,16 +210,16 @@ public Document GetDocumentTemplate(String templatePath, String processId, Strin } /** - * A.5.1. Verify that the correctly handles the service name parameter Flow of - * Test Description: Send a parameter value equal to what is required. Verify - * that request succeeds. Send a parameter value not equal to what is required. - * Verify that request fails. Overall test passes if all individual tests pass. - * + * A.5.1. Verify that the correctly handles the service name parameter Flow of Test + * Description: Send a parameter value equal to what is required. Verify that request + * succeeds. Send a parameter value not equal to what is required. Verify that request + * fails. Overall test passes if all individual tests pass. * @throws IOException * @throws URISyntaxException * @throws SAXException */ - @Test(enabled = true, dependsOnMethods = {}, groups = "A.5. Basic Tests", description = "A.5.1. Verify that the correctly handles the service name parameter.") + @Test(enabled = true, dependsOnMethods = {}, groups = "A.5. Basic Tests", + description = "A.5.1. Verify that the correctly handles the service name parameter.") private void ValidServiceName() throws IOException, URISyntaxException, SAXException { String SERVICE_URL = this.ServiceUrl.toString(); @@ -234,7 +238,8 @@ private void ValidServiceName() throws IOException, URISyntaxException, SAXExcep GC_Flag = true; String msg = "Valid Service Name for WPS 2.0"; Assert.assertTrue(GC_Flag, msg); - } else { + } + else { GC_Flag = false; String msg = "Invalid Service Name for WPS 2.0"; Assert.assertTrue(GC_Flag, msg); @@ -242,16 +247,16 @@ private void ValidServiceName() throws IOException, URISyntaxException, SAXExcep } /** - * A.5.2. Verify that the correctly handles the service version parameter Flow - * of Test Description: Send a parameter value equal to what is required. Verify - * that request succeeds. Send a parameter value not equal to what is required. - * Verify that request fails. Overall test passes if all individual tests pass. - * + * A.5.2. Verify that the correctly handles the service version parameter Flow of Test + * Description: Send a parameter value equal to what is required. Verify that request + * succeeds. Send a parameter value not equal to what is required. Verify that request + * fails. Overall test passes if all individual tests pass. * @throws IOException * @throws URISyntaxException * @throws SAXException */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.2. Verify that the correctly handles the service version parameter.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.2. Verify that the correctly handles the service version parameter.") private void ValidServiceVersion() throws IOException, URISyntaxException, SAXException { String SERVICE_URL = this.ServiceUrl.toString(); @@ -270,7 +275,8 @@ private void ValidServiceVersion() throws IOException, URISyntaxException, SAXEx GC_Flag = true; String msg = "Valid Service Version for WPS 2.0"; Assert.assertTrue(GC_Flag, msg); - } else { + } + else { GC_Flag = false; String msg = "Invalid Service Version for WPS 2.0"; Assert.assertTrue(GC_Flag, msg); @@ -278,17 +284,18 @@ private void ValidServiceVersion() throws IOException, URISyntaxException, SAXEx } /** - * A.5.3. Verify that the server correctly handles input data transmission by - * value. Flow of Test Description: Send Execute requests to the server under - * test with valid inputs passed by value. Test passed if the execution finishes - * successfully. - * @throws Exception + * A.5.3. Verify that the server correctly handles input data transmission by value. + * Flow of Test Description: Send Execute requests to the server under test with valid + * inputs passed by value. Test passed if the execution finishes successfully. + * @throws Exception */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.3. Verify that the server correctly handles input data transmission by value.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.3. Verify that the server correctly handles input data transmission by value.") private void ValidInputDataTranmissionByValue() throws Exception { String SERVICE_URL = this.ServiceUrl.toString(); - Document InputValueDocument = GetDocumentTemplate(INPUT_VALUE_TRANSMISSION_TEMPLATE_PATH, this.EchoProcessId, LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); + Document InputValueDocument = GetDocumentTemplate(INPUT_VALUE_TRANSMISSION_TEMPLATE_PATH, this.EchoProcessId, + LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); String InputValueResponse = GetContentFromPOSTXMLRequest(SERVICE_URL, InputValueDocument); Document InputValueResponseDocument = TransformXMLStringToXMLDocument(InputValueResponse); @@ -299,7 +306,8 @@ private void ValidInputDataTranmissionByValue() throws Exception { if (IVRD_Flag) { String msg = "Valid Input Data Transmission by Value for WPS 2.0"; Assert.assertTrue(IVRD_Flag, msg); - } else { + } + else { String msg = "Invalid Input Data Transmission by Value for WPS 2.0"; Assert.assertTrue(IVRD_Flag, msg); } @@ -307,16 +315,18 @@ private void ValidInputDataTranmissionByValue() throws Exception { /** * A.5.4. Verify that the server correctly handles input data transmission by - * reference. Flow of Test Description: Send Execute requests to the server - * under test with valid inputs passed by reference. Test passed if the - * execution finishes successfully. + * reference. Flow of Test Description: Send Execute requests to the server under test + * with valid inputs passed by reference. Test passed if the execution finishes + * successfully. * @throws Exception */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.4. Verify that the server correctly handles input data transmission by reference.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.4. Verify that the server correctly handles input data transmission by reference.") private void ValidInputDataTranmissionByReference() throws Exception { String SERVICE_URL = this.ServiceUrl.toString(); - Document InputReferenceDocument = GetDocumentTemplate(INPUT_REFERENCE_TRANSMISSION_TEMPLATE_PATH, this.EchoProcessId, LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); + Document InputReferenceDocument = GetDocumentTemplate(INPUT_REFERENCE_TRANSMISSION_TEMPLATE_PATH, + this.EchoProcessId, LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); String InputReferenceResponse = GetContentFromPOSTXMLRequest(SERVICE_URL, InputReferenceDocument); System.out.println(InputReferenceResponse); @@ -328,30 +338,31 @@ private void ValidInputDataTranmissionByReference() throws Exception { if (IRRD_Flag) { String msg = "Valid Input Data Transmission by Reference for WPS 2.0"; Assert.assertTrue(IRRD_Flag, msg); - } else { + } + else { String msg = "Invalid Input Data Transmission by Reference for WPS 2.0"; Assert.assertTrue(IRRD_Flag, msg); } } /** - * A.5.5. Verify that the server correctly handles output data transmission by - * value. Flow of Test Description: Check the available process offerings for - * outputs that can be retrieved by value. If there is an output that can be - * retrieved by value, send an Execute request to the server requesting the - * output by value. Test passes if a valid Execute response is returned - * containing the requested output. Skip this test if no output can be retrieved - * by value. - * + * A.5.5. Verify that the server correctly handles output data transmission by value. + * Flow of Test Description: Check the available process offerings for outputs that + * can be retrieved by value. If there is an output that can be retrieved by value, + * send an Execute request to the server requesting the output by value. Test passes + * if a valid Execute response is returned containing the requested output. Skip this + * test if no output can be retrieved by value. * @throws IOException * @throws URISyntaxException * @throws SAXException */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.5. Verify that the server correctly handles output data transmission by value.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.5. Verify that the server correctly handles output data transmission by value.") private void ValidOutDataTranmissionByValue() throws IOException, URISyntaxException, SAXException { String SERVICE_URL = this.ServiceUrl.toString(); - Document OutputValueDocument = GetDocumentTemplate(OUTPUT_VALUE_TRANSMISSION_TEMPLATE_PATH, this.EchoProcessId, LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); + Document OutputValueDocument = GetDocumentTemplate(OUTPUT_VALUE_TRANSMISSION_TEMPLATE_PATH, this.EchoProcessId, + LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); String OutputValueResponse = GetContentFromPOSTXMLRequest(SERVICE_URL, OutputValueDocument); Document OutputValueResponseDocument = TransformXMLStringToXMLDocument(OutputValueResponse); @@ -362,7 +373,8 @@ private void ValidOutDataTranmissionByValue() throws IOException, URISyntaxExcep if (OVRD_Flag) { String msg = "Valid Output Data Transmission by Value for WPS 2.0"; Assert.assertTrue(OVRD_Flag, msg); - } else { + } + else { String msg = "Invalid Output Data Transmission by Value for WPS 2.0"; Assert.assertTrue(OVRD_Flag, msg); } @@ -370,19 +382,20 @@ private void ValidOutDataTranmissionByValue() throws IOException, URISyntaxExcep /** * A.5.6. Verify that the server correctly handles output data transmission by - * reference. Flow of Test Description: Check the available process offerings - * for outputs that can be retrieved by value. If there is an output that can be - * retrieved by value, send an Execute request to the server requesting the - * output by reference. Test passes if a valid Execute response is returned - * containing the requested output. Skip this test if no output can be retrieved - * by reference. - * @throws Exception + * reference. Flow of Test Description: Check the available process offerings for + * outputs that can be retrieved by value. If there is an output that can be retrieved + * by value, send an Execute request to the server requesting the output by reference. + * Test passes if a valid Execute response is returned containing the requested + * output. Skip this test if no output can be retrieved by reference. + * @throws Exception */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.6. Verify that the server correctly handles output data transmission by reference.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.6. Verify that the server correctly handles output data transmission by reference.") private void ValidOutDataTranmissionByReference() throws Exception { String SERVICE_URL = this.ServiceUrl.toString(); - Document OutputReferenceDocument = GetDocumentTemplate(OUTPUT_REFERENCE_TRANSMISSION_TEMPLATE_PATH, this.EchoProcessId, LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); + Document OutputReferenceDocument = GetDocumentTemplate(OUTPUT_REFERENCE_TRANSMISSION_TEMPLATE_PATH, + this.EchoProcessId, LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); String OutputReferenceResponse = GetContentFromPOSTXMLRequest(SERVICE_URL, OutputReferenceDocument); System.out.println(OutputReferenceResponse); @@ -394,22 +407,23 @@ private void ValidOutDataTranmissionByReference() throws Exception { if (ORRD_Flag) { String msg = "Valid Output Data Transmission by Reference for WPS 2.0"; Assert.assertTrue(ORRD_Flag, msg); - } else { + } + else { String msg = "Invalid Output Data Transmission by Reference for WPS 2.0"; Assert.assertTrue(ORRD_Flag, msg); } } /** - * A.5.7. Verify that each process the server offers has a unique identifier - * Flow of Test Description: Get all available processes from the server under - * test. Test passes if all processes have a unique identifier. - * + * A.5.7. Verify that each process the server offers has a unique identifier Flow of + * Test Description: Get all available processes from the server under test. Test + * passes if all processes have a unique identifier. * @throws IOException * @throws URISyntaxException * @throws SAXException */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.7. Verify that each process the server offers has a unique identifier.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.7. Verify that each process the server offers has a unique identifier.") private void ValidUniqueIdentifier() { String SERVICE_URL = this.ServiceUrl.toString(); @@ -426,8 +440,9 @@ private void ValidUniqueIdentifier() { Set PNameList = new HashSet<>(); for (int i = 0; i < DPList.getLength(); i++) { Element PDocument = (Element) DPList.item(i); - String PName = PDocument.getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "Identifier").item(0) - .getTextContent(); + String PName = PDocument.getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "Identifier") + .item(0) + .getTextContent(); if (PNameList.add(PName) == false) { UI_Flag = false; break; @@ -437,23 +452,23 @@ private void ValidUniqueIdentifier() { if (UI_Flag) { String msg = "Valid Unique Identifier for WPS 2.0"; Assert.assertTrue(UI_Flag, msg); - } else { + } + else { String msg = "Invalid Unique Identifier for WPS 2.0"; Assert.assertTrue(UI_Flag, msg); } } /** - * A.5.8. Verify that the server creates a unique jobID for each job Flow of - * Test Description: Send more than one asynchronous Execute requests to the - * server under test. Test passes if the retrieved JobIDs differ from each - * other. - * + * A.5.8. Verify that the server creates a unique jobID for each job Flow of Test + * Description: Send more than one asynchronous Execute requests to the server under + * test. Test passes if the retrieved JobIDs differ from each other. * @throws IOException * @throws URISyntaxException * @throws SAXException */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.8. Verify that the server creates a unique jobID for each job.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.8. Verify that the server creates a unique jobID for each job.") private void ValidUniqueJobIdentifier() throws URISyntaxException, SAXException, IOException { String SERVICE_URL = this.ServiceUrl.toString(); @@ -469,7 +484,9 @@ private void ValidUniqueJobIdentifier() throws URISyntaxException, SAXException, String UniqueJobIdsResponse = GetContentFromPOSTXMLRequest(SERVICE_URL, UniqueJobIdsDocument); Document UniqueJobIdsResponseDocument = TransformXMLStringToXMLDocument(UniqueJobIdsResponse); String JName = UniqueJobIdsResponseDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID").item(0).getTextContent(); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "JobID") + .item(0) + .getTextContent(); if (JNameList.add(JName) == false) { UJRD_Flag = false; break; @@ -479,70 +496,72 @@ private void ValidUniqueJobIdentifier() throws URISyntaxException, SAXException, if (UJRD_Flag) { String msg = "Valid Unique Job Ids for WPS 2.0"; Assert.assertTrue(UJRD_Flag, msg); - } else { + } + else { String msg = "Invalid Unique Job Ids for WPS 2.0"; Assert.assertTrue(UJRD_Flag, msg); } } /** - * A.5.9. Verify that the server can handle GetCapabilities requests via - * POST/XML Flow of Test Description: Send a valid GetCapabilities request to - * the server under test. Test passes if a valid document of the type - * wps:Capabilities is returned. - * - * @throws IOException - * @throws URISyntaxException - * @throws SAXException + * A.5.9. Verify that the server can handle GetCapabilities requests via POST/XML Flow + * of Test Description: Send a valid GetCapabilities request to the server under test. + * Test passes if a valid document of the type wps:Capabilities is returned. + * @throws java.io.IOException + * @throws java.net.URISyntaxException + * @throws org.xml.sax.SAXException */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.9. Verify that the server can handle GetCapabilities requests via POST/XML.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.9. Verify that the server can handle GetCapabilities requests via POST/XML.") public void ValidGetCapabilitiesViaPOSTXML() throws IOException, URISyntaxException, SAXException { String SERVICE_URL = this.ServiceUrl.toString(); URI uriGetCapabilitiesRequestTemplate = BasicTests.class.getResource(GET_CAPABILITIES_REQUEST_TEMPLATE_PATH) - .toURI(); + .toURI(); Document GCDocument = URIUtils.parseURI(uriGetCapabilitiesRequestTemplate); String GCRXmlString = GetContentFromPOSTXMLRequest(SERVICE_URL, GCDocument); Document GCRDocument = TransformXMLStringToXMLDocument(GCRXmlString); Boolean GCP_Flag = (GCRDocument.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Capabilities") - .getLength() > 0) ? true : false; + .getLength() > 0) ? true : false; if (GCP_Flag) { String msg = "Valid GetCapabilities via POST/XML for WPS 2.0"; Assert.assertTrue(GCP_Flag, msg); - } else { + } + else { String msg = "Invalid GetCapabilities via POST/XML for WPS 2.0"; Assert.assertTrue(GCP_Flag, msg); } } /** - * A.5.10. Verify that the server can handle DescribeProcess requests via - * POST/XML Flow of Test Description: Send a valid DescribeProcess request to - * the server under test. Test passes if a valid document of the type - * wps:ProcessOfferings is returned. - * - * @throws IOException - * @throws URISyntaxException - * @throws SAXException + * A.5.10. Verify that the server can handle DescribeProcess requests via POST/XML + * Flow of Test Description: Send a valid DescribeProcess request to the server under + * test. Test passes if a valid document of the type wps:ProcessOfferings is returned. + * @throws java.io.IOException + * @throws java.net.URISyntaxException + * @throws org.xml.sax.SAXException */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.10. Verify that the server can handle DescribeProcess requests via POST/XML.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.10. Verify that the server can handle DescribeProcess requests via POST/XML.") public void ValidDescribeProcessViaPOSTXML() throws IOException, URISyntaxException, SAXException { String SERVICE_URL = this.ServiceUrl.toString(); URI uriDescribeProcessRequestTemplate = BasicTests.class.getResource(DESCRIBE_PROCESS_REQUEST_TEMPLATE_PATH) - .toURI(); + .toURI(); Document DPDocument = URIUtils.parseURI(uriDescribeProcessRequestTemplate); - DPDocument.getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "Identifier").item(0) - .setTextContent(this.EchoProcessId); + DPDocument.getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "Identifier") + .item(0) + .setTextContent(this.EchoProcessId); String DPRXmlString = GetContentFromPOSTXMLRequest(SERVICE_URL, DPDocument); Document DPRDocument = TransformXMLStringToXMLDocument(DPRXmlString); Boolean DPP_Flag = (DPRDocument.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "ProcessOfferings") - .getLength() > 0) ? true : false; + .getLength() > 0) ? true : false; if (DPP_Flag) { String msg = "Valid DescribeProcess via POST/XML for WPS 2.0"; Assert.assertTrue(DPP_Flag, msg); - } else { + } + else { String msg = "Invalid DescribeProcess via POST/XML for WPS 2.0"; Assert.assertTrue(DPP_Flag, msg); } @@ -550,20 +569,22 @@ public void ValidDescribeProcessViaPOSTXML() throws IOException, URISyntaxExcept /** * A.5.12. Verify that the server can handle the execution mode 'asynchronous' - * requested via POST/XML Flow of Test Description: Flow of Test Description: - * Send a valid XML Execute request to the server under test, setting the “mode” - * attribute to “async”. Verify that a valid Execute wps:Result is returned. - * - * @throws Exception + * requested via POST/XML Flow of Test Description: Flow of Test Description: Send a + * valid XML Execute request to the server under test, setting the “mode” attribute to + * “async”. Verify that a valid Execute wps:Result is returned. + * @throws java.lang.Exception */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.12. Verify that the server can handle the execution mode 'asynchronous' requested via POST/XML.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.12. Verify that the server can handle the execution mode 'asynchronous' requested via POST/XML.") public void ValidAsyncExcecuteViaPOSTXML() throws Exception { String SERVICE_URL = this.ServiceUrl.toString(); - Document literalDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, this.EchoProcessId, LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); + Document literalDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, this.EchoProcessId, + LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); // Response document Element executeElement = (Element) literalDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Execute").item(0); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Execute") + .item(0); executeElement.setAttribute("mode", "async"); executeElement.setAttribute("response", "document"); @@ -572,59 +593,62 @@ public void ValidAsyncExcecuteViaPOSTXML() throws Exception { String VAEXmlString = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); Document VAEDocument = TransformXMLStringToXMLDocument(VAEXmlString); - Boolean VAE_Flag = (VAEDocument.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Status").getLength() > 0) ? true : false; + Boolean VAE_Flag = (VAEDocument.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Status") + .getLength() > 0) ? true : false; if (VAE_Flag) { String msg = "Valid AsyncExecute via POST/XML for WPS 2.0"; Assert.assertTrue(VAE_Flag, msg); - } else { + } + else { String msg = "Invalid AsyncExecute via POST/XML for WPS 2.0"; Assert.assertTrue(VAE_Flag, msg); } /* - * Code by Aries //status code is 200 response validation HttpURLConnection conn - * = GetConnection(SERVICE_URL); conn.setRequestMethod("POST"); + * Code by Aries //status code is 200 response validation HttpURLConnection conn = + * GetConnection(SERVICE_URL); conn.setRequestMethod("POST"); * conn.setRequestProperty("Content-Type", "application/xml"); * conn.setDoOutput(true); - * + * * DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream()); * String xml = TransformXMLDocumentToXMLString(literalDocument); * outputStream.writeBytes(xml); outputStream.flush(); outputStream.close(); - * + * * int responseCode = conn.getResponseCode(); StringBuilder builder = new - * StringBuilder(); // read response BufferedReader in; if(responseCode > 299) - * in = new BufferedReader(new InputStreamReader(conn.getErrorStream())); else - * in = new BufferedReader(new InputStreamReader(conn.getInputStream())); - * + * StringBuilder(); // read response BufferedReader in; if(responseCode > 299) in + * = new BufferedReader(new InputStreamReader(conn.getErrorStream())); else in = + * new BufferedReader(new InputStreamReader(conn.getInputStream())); + * * String str; while ((str = in.readLine()) != null) { builder.append(str); } * in.close(); System.out.println(builder.toString()); - * + * * boolean respDocFlag = (responseCode == HttpURLConnection.HTTP_OK); - * - * if (respDocFlag) { String msg = - * "Valid AsyncExecute via POST/XML for WPS 2.0"; Assert.assertTrue(respDocFlag, - * msg); } else { String msg = "Invalid AsyncExecute via POST/XML for WPS 2.0"; - * Assert.assertTrue(respDocFlag, msg); } + * + * if (respDocFlag) { String msg = "Valid AsyncExecute via POST/XML for WPS 2.0"; + * Assert.assertTrue(respDocFlag, msg); } else { String msg = + * "Invalid AsyncExecute via POST/XML for WPS 2.0"; Assert.assertTrue(respDocFlag, + * msg); } */ } /** - * A.5.13. Verify that the server can handle the execution mode 'auto' requested - * via POST/XML Flow of Test Description: Flow of Test Description: Send a valid - * XML Execute request to the server under test, setting the “mode” attribute to - * “auto”. Verify that a valid Execute wps:Result is returned. - * - * @throws Exception + * A.5.13. Verify that the server can handle the execution mode 'auto' requested via + * POST/XML Flow of Test Description: Flow of Test Description: Send a valid XML + * Execute request to the server under test, setting the “mode” attribute to “auto”. + * Verify that a valid Execute wps:Result is returned. + * @throws java.lang.Exception */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.13. Verify that the server can handle the execution mode 'auto' requested via POST/XML.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.13. Verify that the server can handle the execution mode 'auto' requested via POST/XML.") public void ValidAutoExcecuteViaPOSTXML() throws Exception { String SERVICE_URL = this.ServiceUrl.toString(); - + // Get the processid from user and replace the processid in the template xml // request file String ECHO_PROCESS_ID = this.EchoProcessId; - Document literalDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, ECHO_PROCESS_ID, LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); + Document literalDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, ECHO_PROCESS_ID, LITERAL_INPUT_ID, + LITERAL_OUTPUT_ID); prettyPrint(literalDocument); // Parse the input id and output id in DescribeProcess @@ -637,7 +661,8 @@ public void ValidAutoExcecuteViaPOSTXML() throws Exception { Document responseDescribeProcessDocument = TransformXMLStringToXMLDocument(responseDescribeProcess); Element ProcessOfferingElement = (Element) responseDescribeProcessDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "ProcessOffering").item(0); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "ProcessOffering") + .item(0); // Element ProcessOfferingElement = (Element) // responseDescribeProcessDocument.getElementsByTagName("wps:ProcessOffering").item(0); // System.out.println(ProcessOfferingElement.getAttribute("outputTransmission")); @@ -645,7 +670,8 @@ public void ValidAutoExcecuteViaPOSTXML() throws Exception { String jobControlOptions = ProcessOfferingElement.getAttribute("jobControlOptions"); Element executeElement = (Element) literalDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Execute").item(0); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Execute") + .item(0); // case 1 if (outputTransmission.contains("reference")) { @@ -693,14 +719,13 @@ public void ValidAutoExcecuteViaPOSTXML() throws Exception { } /** - * A.5.16. Verify that the server can handle GetCapabilities requests via - * GET/KVP - * + * A.5.16. Verify that the server can handle GetCapabilities requests via GET/KVP * @throws IOException * @throws URISyntaxException * @throws SAXException */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.16. Verify that the server can handle GetCapabilities requests via GET/KVP.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.16. Verify that the server can handle GetCapabilities requests via GET/KVP.") private void ValidGetCapabilitiesViaGETKVP() throws IOException, URISyntaxException, SAXException { String SERVICE_URL = this.ServiceUrl.toString(); @@ -719,27 +744,27 @@ private void ValidGetCapabilitiesViaGETKVP() throws IOException, URISyntaxExcept Document GCL_Document = TransformXMLStringToXMLDocument(GCL_XmlString); Boolean GC_KVP_Flag = (GCU_Document.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Capabilities") - .getLength() > 0 + .getLength() > 0 && GCL_Document.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Capabilities") - .getLength() > 0) ? true : false; + .getLength() > 0) ? true : false; if (GC_KVP_Flag) { String msg = "Valid GetCapabilities via KVP for WPS 2.0"; Assert.assertTrue(GC_KVP_Flag, msg); - } else { + } + else { String msg = "Invalid GetCapabilities via KVP for WPS 2.0"; Assert.assertTrue(GC_KVP_Flag, msg); } } /** - * A.5.17. Verify that the server can handle DescribeProcess requests via - * GET/KVP - * + * A.5.17. Verify that the server can handle DescribeProcess requests via GET/KVP * @throws IOException * @throws URISyntaxException * @throws SAXException */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.17. Verify that the server can handle DescribeProcess requests via GET/KVP.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.17. Verify that the server can handle DescribeProcess requests via GET/KVP.") private void ValidDescribeProcessViaGETKVP() throws IOException, URISyntaxException, SAXException { String SERVICE_URL = this.ServiceUrl.toString(); @@ -750,7 +775,8 @@ private void ValidDescribeProcessViaGETKVP() throws IOException, URISyntaxExcept String GC_XmlString = GetContentFromGETKVPRequest(SERVICE_URL, GC_Parameters); Document GC_Document = TransformXMLStringToXMLDocument(GC_XmlString); String IdentifierName = GC_Document.getElementsByTagNameNS("http://www.opengis.net/ows/2.0", "Identifier") - .item(0).getTextContent(); + .item(0) + .getTextContent(); Map DPU_Parameters = new LinkedHashMap<>(); DPU_Parameters.put("Service".toUpperCase(), "WPS"); @@ -769,18 +795,28 @@ private void ValidDescribeProcessViaGETKVP() throws IOException, URISyntaxExcept Document DPL_Document = TransformXMLStringToXMLDocument(DPL_XmlString); Boolean DP_KVP_Flag = (DPU_Document.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "ProcessOfferings") - .getLength() > 0 + .getLength() > 0 && DPL_Document.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "ProcessOfferings") - .getLength() > 0) ? true : false; + .getLength() > 0) ? true : false; if (DP_KVP_Flag) { String msg = "Valid DescribeProcess via KVP for WPS 2.0"; Assert.assertTrue(DP_KVP_Flag, msg); - } else { + } + else { String msg = "Invalid DescribeProcess via KVP for WPS 2.0"; Assert.assertTrue(DP_KVP_Flag, msg); } } - + + /** + *

    + * TestPostWithDocumentAndAssertMessage. + *

    + * @param SERVICE_URL a {@link java.lang.String} object + * @param literalDocument a {@link org.w3c.dom.Document} object + * @param message a {@link java.lang.String} object + * @throws java.lang.Exception if any. + */ public void TestPostWithDocumentAndAssertMessage(String SERVICE_URL, Document literalDocument, String message) throws Exception { // status code is 200 response validation @@ -802,7 +838,6 @@ public void TestPostWithDocumentAndAssertMessage(String SERVICE_URL, Document li /** * Description: Identify that a XML document is valid with XSD Template or not - * * @param xmlString * @param xsdPath * @return @@ -812,21 +847,16 @@ private static boolean isXMLSchemaValid(String xmlString, String xsdPath) { Schema schema = ValidationUtils.createSchema(xsdPath); Validator validator = schema.newValidator(); validator.validate(new StreamSource(new StringReader(xmlString))); - } catch (IOException | SAXException e) { + } + catch (IOException | SAXException e) { System.out.println("Exception: " + e.getMessage()); return false; } return true; } - - - - - /** * Description: Identify that URL could get the response or not - * * @param any_url * @return * @throws IOException @@ -847,6 +877,4 @@ private static Boolean IsValidHTTP(String any_url, Map params) t return (responseCode != HttpURLConnection.HTTP_OK) ? false : true; } - - } diff --git a/src/main/java/org/opengis/cite/wps20/package-info.java b/src/main/java/org/opengis/cite/wps20/package-info.java index 97e91dd..0f521cb 100644 --- a/src/main/java/org/opengis/cite/wps20/package-info.java +++ b/src/main/java/org/opengis/cite/wps20/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.wps20; \ No newline at end of file +package org.opengis.cite.wps20; \ No newline at end of file diff --git a/src/main/java/org/opengis/cite/wps20/synchronous/SyncTests.java b/src/main/java/org/opengis/cite/wps20/synchronous/SyncTests.java index 8b730cf..14a0fe5 100644 --- a/src/main/java/org/opengis/cite/wps20/synchronous/SyncTests.java +++ b/src/main/java/org/opengis/cite/wps20/synchronous/SyncTests.java @@ -2,84 +2,40 @@ import static org.testng.Assert.assertTrue; -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; -import java.net.HttpURLConnection; -import java.net.URI; -//import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -//import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.charset.Charset; -//import java.util.ArrayList; -//import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -//import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Random; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.OutputKeys; -//import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.Validator; - //import org.opengis.cite.wps20.Namespaces; //import org.opengis.cite.wps20.SuiteAttribute; import org.opengis.cite.wps20.CommonFixture; -import org.opengis.cite.wps20.basictests.BasicTests; import org.testng.Assert; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.Node; -//import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -/*import net.sf.saxon.s9api.Processor; -import net.sf.saxon.s9api.SaxonApiException; -import net.sf.saxon.s9api.XPathCompiler; -import net.sf.saxon.s9api.XPathSelector; -import net.sf.saxon.s9api.XdmNode; -import net.sf.saxon.s9api.XdmValue;*/ - -import org.opengis.cite.wps20.util.*; +/** + *

    + * SyncTests class. + *

    + * + */ public class SyncTests extends CommonFixture { - + /** * A.5.11. Verify that the server can handle the execution mode 'synchronous' - * requested via POST/XML Flow of Test Description: Send a valid XML Execute - * request to the server under test, setting the “mode” attribute to “sync”. - * Verify that a valid Execute wps:Result is returned. - * - * @throws Exception + * requested via POST/XML Flow of Test Description: Send a valid XML Execute request + * to the server under test, setting the “mode” attribute to “sync”. Verify that a + * valid Execute wps:Result is returned. + * @throws java.lang.Exception */ - @Test(enabled = true, groups = "A.5. Basic Tests", description = "A.5.11. Verify that the server can handle the execution mode 'synchronous' requested via POST/XML.") + @Test(enabled = true, groups = "A.5. Basic Tests", + description = "A.5.11. Verify that the server can handle the execution mode 'synchronous' requested via POST/XML.") public void ValidSyncExcecuteViaPOSTXML() throws Exception { String SERVICE_URL = this.ServiceUrl.toString(); - Document literalDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, this.EchoProcessId, LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); + Document literalDocument = GetDocumentTemplate(LITERAL_REQUEST_TEMPLATE_PATH, this.EchoProcessId, + LITERAL_INPUT_ID, LITERAL_OUTPUT_ID); // Response document Element executeElement = (Element) literalDocument - .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Execute").item(0); + .getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Execute") + .item(0); executeElement.setAttribute("mode", "sync"); executeElement.setAttribute("response", "document"); @@ -88,26 +44,26 @@ public void ValidSyncExcecuteViaPOSTXML() throws Exception { * Auto-generated catch block e.printStackTrace(); } */ - /* * // Code by Aries //status code is 200 response validation HttpURLConnection * conn = GetConnection(SERVICE_URL); conn.setRequestMethod("POST"); * conn.setRequestProperty("Content-Type", "application/xml"); * conn.setDoOutput(true); - * + * * DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream()); * String xml = TransformXMLDocumentToXMLString(literalDocument); * outputStream.writeBytes(xml); outputStream.flush(); outputStream.close(); - * - * int responseCode = conn.getResponseCode(); boolean respDocFlag = - * (responseCode == HttpURLConnection.HTTP_OK); + * + * int responseCode = conn.getResponseCode(); boolean respDocFlag = (responseCode + * == HttpURLConnection.HTTP_OK); */ - - String respDocResult = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); + + String respDocResult = GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); Document respDocResultDocument = TransformXMLStringToXMLDocument(respDocResult); - boolean respDocFlag = respDocResultDocument.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Result").getLength() > 0; + boolean respDocFlag = respDocResultDocument.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", "Result") + .getLength() > 0; String msg = "Invalid SyncExecute via POST/XML for WPS 2.0"; - assertTrue(respDocFlag, msg); + assertTrue(respDocFlag, msg); // Raw data output executeElement.setAttribute("response", "raw"); @@ -123,7 +79,8 @@ public void ValidSyncExcecuteViaPOSTXML() throws Exception { if (VSE_Flag) { String msg1 = "Valid SyncExecute via POST/XML for WPS 2.0"; Assert.assertTrue(VSE_Flag, msg1); - } else { + } + else { String msg1 = "Invalid SyncExecute via POST/XML for WPS 2.0"; Assert.assertTrue(VSE_Flag, msg1); } @@ -131,13 +88,13 @@ public void ValidSyncExcecuteViaPOSTXML() throws Exception { /* * // The Process Flow should as this one String VSEXmlString = * GetContentFromPOSTXMLRequest(SERVICE_URL, literalDocument); Document - * VSEDocument = TransformXMLStringToXMLDocument(VSEXmlString); Boolean VSE_Flag - * = (VSEDocument.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", + * VSEDocument = TransformXMLStringToXMLDocument(VSEXmlString); Boolean VSE_Flag = + * (VSEDocument.getElementsByTagNameNS("http://www.opengis.net/wps/2.0", * "Result").getLength() > 0) ? true : false; if (VSE_Flag) { String msg = - * "Valid SyncExecute via POST/XML for WPS 2.0"; Assert.assertTrue(VSE_Flag, - * msg); } else { String msg = "Invalid SyncExecute via POST/XML for WPS 2.0"; + * "Valid SyncExecute via POST/XML for WPS 2.0"; Assert.assertTrue(VSE_Flag, msg); + * } else { String msg = "Invalid SyncExecute via POST/XML for WPS 2.0"; * Assert.assertTrue(VSE_Flag, msg); } */ } - + } diff --git a/src/main/java/org/opengis/cite/wps20/util/ClientUtils.java b/src/main/java/org/opengis/cite/wps20/util/ClientUtils.java index 4620542..54a6709 100644 --- a/src/main/java/org/opengis/cite/wps20/util/ClientUtils.java +++ b/src/main/java/org/opengis/cite/wps20/util/ClientUtils.java @@ -1,173 +1,144 @@ package org.opengis.cite.wps20.util; -import java.io.IOException; -import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.SocketAddress; -import java.net.URL; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.client.filter.LoggingFilter; -import com.sun.jersey.client.urlconnection.HttpURLConnectionFactory; -import com.sun.jersey.client.urlconnection.URLConnectionClientHandler; import java.net.URI; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; -import javax.ws.rs.HttpMethod; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.UriBuilder; + import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; + +import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.logging.LoggingFeature; import org.opengis.cite.wps20.ReusableEntityFilter; import org.w3c.dom.Document; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.client.Invocation.Builder; +import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriBuilder; + /** - * Provides various utility methods for creating and configuring HTTP client - * components. + * 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; - } + private static final Logger LOGGER = Logger.getLogger(ClientUtils.class.getName()); + + /** + * Builds a client component for interacting with HTTP endpoints. The client will + * automatically redirect to the URI declared in 3xx responses. The connection timeout + * is 10 s. Request and response messages may be logged to a JDK logger (in the + * namespace "com.sun.jersey.api.client"). + * @return A Client component. + */ + public static Client buildClient() { + ClientConfig config = new ClientConfig(); + config.property(ClientProperties.FOLLOW_REDIRECTS, true); + config.property(ClientProperties.CONNECT_TIMEOUT, 10000); + config.register(new LoggingFeature(LOGGER, Level.ALL, LoggingFeature.Verbosity.PAYLOAD_ANY, 5000)); + Client client = ClientBuilder.newClient(config); + client.register(new ReusableEntityFilter()); + return client; + } - /** - * 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. + */ + public static Client buildClientWithProxy(final String proxyHost, final int proxyPort) { + ClientConfig config = new ClientConfig(); + config.connectorProvider(new ApacheConnectorProvider()); + config.register(new LoggingFeature(LOGGER, Level.ALL, LoggingFeature.Verbosity.PAYLOAD_ANY, 5000)); + SocketAddress addr = new InetSocketAddress(proxyHost, proxyPort); + Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); + config.property(ClientProperties.PROXY_URI, proxy); + config.property(ClientProperties.FOLLOW_REDIRECTS, true); + config.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY_CLIENT, LoggingFeature.Verbosity.PAYLOAD_ANY); + config.property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_CLIENT, Level.ALL); + Client client = ClientBuilder.newClient(config); + client.register(new ReusableEntityFilter()); + return client; + } - @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, the Accept + * header is omitted. + * @return A ClientRequest object. + */ + public static Response buildGetRequest(URI endpoint, Map qryParams, MediaType... mediaTypes) { + UriBuilder uriBuilder = UriBuilder.fromUri(endpoint); + if (null != qryParams) { + for (Map.Entry param : qryParams.entrySet()) { + uriBuilder.queryParam(param.getKey(), param.getValue()); + } + } + URI uri = uriBuilder.build(); + WebTarget target = buildClient().target(uri); + Builder reqBuilder = target.request(); + if (null != mediaTypes && mediaTypes.length > 0) { + reqBuilder = reqBuilder.accept(mediaTypes); + } + Invocation req = reqBuilder.buildGet(); + return req.invoke(); + } - /** - * Builds an HTTP request message that uses the GET method. - * - * @param endpoint A URI indicating the target resource. - * @param qryParams A Map containing query parameters (may be null); - * @param mediaTypes A list of acceptable media types; if not specified, - * 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. + */ + public static MediaType removeParameters(MediaType mediaType) { + return new MediaType(mediaType.getType(), mediaType.getSubtype()); + } - /** - * Creates a copy of the given MediaType object but without any parameters. - * - * @param mediaType A MediaType descriptor. - * @return A new (immutable) MediaType object having the same type and - * subtype. - */ - public static MediaType removeParameters(MediaType mediaType) { - return new MediaType(mediaType.getType(), mediaType.getSubtype()); - } + /** + * Obtains the (XML) response entity as a JAXP Source object and resets the entity + * input stream for subsequent reads. + * @param response A representation of an HTTP response message. + * @param targetURI The target URI from which the entity was retrieved (may be null). + * @return A Source to read the entity from; its system identifier is set using the + * given targetURI value (this may be used to resolve any relative URIs found in the + * source). + */ + public static Source getResponseEntityAsSource(Response response, String targetURI) { + Source source = response.readEntity(DOMSource.class); + if (null != targetURI && !targetURI.isEmpty()) { + source.setSystemId(targetURI); + } + return source; + } - /** - * Obtains the (XML) response entity as a JAXP Source object and resets the - * entity input stream for subsequent reads. - * - * @param response A representation of an HTTP response message. - * @param targetURI The target URI from which the entity was retrieved (may - * be null). - * @return A Source to read the entity from; its system identifier is set - * using the given targetURI value (this may be used to resolve any relative - * URIs found in the source). - */ - public static Source getResponseEntityAsSource(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/wps20/util/NamespaceBindings.java b/src/main/java/org/opengis/cite/wps20/util/NamespaceBindings.java index 0a01a68..ab25187 100644 --- a/src/main/java/org/opengis/cite/wps20/util/NamespaceBindings.java +++ b/src/main/java/org/opengis/cite/wps20/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.wps20.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.wps20.Namespaces#OWS}
    • + *
    • xlink: {@value org.opengis.cite.wps20.Namespaces#XLINK}
    • + *
    • gml: {@value org.opengis.cite.wps20.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.wps20.Namespaces#OWS}
    • - *
    • xlink: {@value org.opengis.cite.wps20.Namespaces#XLINK}
    • - *
    • gml: {@value org.opengis.cite.wps20.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/wps20/util/TestSuiteLogger.java b/src/main/java/org/opengis/cite/wps20/util/TestSuiteLogger.java index f95e3ac..2ada745 100644 --- a/src/main/java/org/opengis/cite/wps20/util/TestSuiteLogger.java +++ b/src/main/java/org/opengis/cite/wps20/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/wps20/util/URIUtils.java b/src/main/java/org/opengis/cite/wps20/util/URIUtils.java index 8746fa6..4d93d7c 100644 --- a/src/main/java/org/opengis/cite/wps20/util/URIUtils.java +++ b/src/main/java/org/opengis/cite/wps20/util/URIUtils.java @@ -8,7 +8,6 @@ import java.net.URI; import java.util.logging.Level; -import javax.ws.rs.core.HttpHeaders; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -16,122 +15,111 @@ import org.w3c.dom.Document; import org.xml.sax.SAXException; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.Invocation.Builder; +import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.Response; /** - * Provides a collection of utility methods for manipulating or resolving URI - * references. + * Provides a collection of utility methods for manipulating or resolving URI references. */ public class URIUtils { - private static final String FIXUP_BASE_URI = "http://apache.org/xml/features/xinclude/fixup-base-uris"; + private static final String FIXUP_BASE_URI = "http://apache.org/xml/features/xinclude/fixup-base-uris"; - /** - * Parses the content of the given URI as an XML document and returns a new - * DOM Document object. Entity reference nodes will not be expanded. XML - * inclusions (xi:include elements) will be processed if present. - * - * @param uriRef - * An absolute URI specifying the location of an XML resource. - * @return A DOM Document node representing an XML resource. - * @throws SAXException - * If the resource cannot be parsed. - * @throws IOException - * If the resource is not accessible. - */ - public static Document parseURI(URI uriRef) throws SAXException, - IOException { - if ((null == uriRef) || !uriRef.isAbsolute()) { - throw new IllegalArgumentException( - "Absolute URI is required, but received " + uriRef); - } - DocumentBuilderFactory docFactory = DocumentBuilderFactory - .newInstance(); - docFactory.setNamespaceAware(true); - docFactory.setExpandEntityReferences(false); - docFactory.setXIncludeAware(true); - Document doc = null; - try { - // XInclude processor will not add xml:base attributes - docFactory.setFeature(FIXUP_BASE_URI, false); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - doc = docBuilder.parse(uriRef.toString()); - } catch (ParserConfigurationException x) { - TestSuiteLogger.log(Level.WARNING, - "Failed to create DocumentBuilder." + x); - } - if (null != doc) { - doc.setDocumentURI(uriRef.toString()); - } - return doc; - } + /** + * Parses the content of the given URI as an XML document and returns a new DOM + * Document object. Entity reference nodes will not be expanded. XML inclusions + * (xi:include elements) will be processed if present. + * @param uriRef An absolute URI specifying the location of an XML resource. + * @return A DOM Document node representing an XML resource. + * @throws org.xml.sax.SAXException If the resource cannot be parsed. + * @throws java.io.IOException If the resource is not accessible. + */ + public static Document parseURI(URI uriRef) throws SAXException, IOException { + if ((null == uriRef) || !uriRef.isAbsolute()) { + throw new IllegalArgumentException("Absolute URI is required, but received " + uriRef); + } + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setNamespaceAware(true); + docFactory.setExpandEntityReferences(false); + docFactory.setXIncludeAware(true); + Document doc = null; + try { + // XInclude processor will not add xml:base attributes + docFactory.setFeature(FIXUP_BASE_URI, false); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + doc = docBuilder.parse(uriRef.toString()); + } + catch (ParserConfigurationException x) { + TestSuiteLogger.log(Level.WARNING, "Failed to create DocumentBuilder." + x); + } + if (null != doc) { + doc.setDocumentURI(uriRef.toString()); + } + return doc; + } - /** - * Dereferences the given URI and stores the resulting resource - * representation in a local file. The file will be located in the default - * temporary file directory. - * - * @param uriRef - * An absolute URI specifying the location of some resource. - * @return A File containing the content of the resource; it may be empty if - * resolution failed for any reason. - * @throws IOException - * If an IO error occurred. - */ - public static File dereferenceURI(URI uriRef) throws IOException { - if ((null == uriRef) || !uriRef.isAbsolute()) { - throw new IllegalArgumentException( - "Absolute URI is required, but received " + uriRef); - } - if (uriRef.getScheme().equalsIgnoreCase("file")) { - return new File(uriRef); - } - Client client = Client.create(); - WebResource webRes = client.resource(uriRef); - ClientResponse rsp = webRes.get(ClientResponse.class); - String suffix = null; - if (rsp.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE).endsWith("xml")) { - suffix = ".xml"; - } - File destFile = File.createTempFile("entity-", suffix); - if (rsp.hasEntity()) { - InputStream is = rsp.getEntityInputStream(); - OutputStream os = new FileOutputStream(destFile); - byte[] buffer = new byte[8 * 1024]; - int bytesRead; - while ((bytesRead = is.read(buffer)) != -1) { - os.write(buffer, 0, bytesRead); - } - is.close(); - os.flush(); - os.close(); - } - TestSuiteLogger.log(Level.FINE, "Wrote " + destFile.length() - + " bytes to file at " + destFile.getAbsolutePath()); - return destFile; - } + /** + * Dereferences the given URI and stores the resulting resource representation in a + * local file. The file will be located in the default temporary file directory. + * @param uriRef An absolute URI specifying the location of some resource. + * @return A File containing the content of the resource; it may be empty if + * resolution failed for any reason. + * @throws java.io.IOException If an IO error occurred. + */ + public static File dereferenceURI(URI uriRef) throws IOException { + if ((null == uriRef) || !uriRef.isAbsolute()) { + throw new IllegalArgumentException("Absolute URI is required, but received " + uriRef); + } + if (uriRef.getScheme().equalsIgnoreCase("file")) { + return new File(uriRef); + } + Client client = ClientUtils.buildClient(); + WebTarget target = client.target(uriRef); + Builder builder = target.request(); + Response rsp = builder.buildGet().invoke(); + String suffix = null; + if (rsp.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE).toString().endsWith("xml")) { + suffix = ".xml"; + } + File destFile = File.createTempFile("entity-", suffix); + if (rsp.hasEntity()) { + Object entity = rsp.getEntity(); + if (!(entity instanceof InputStream)) { + return null; + } + InputStream is = (InputStream) entity; + OutputStream os = new FileOutputStream(destFile); + byte[] buffer = new byte[8 * 1024]; + int bytesRead; + while ((bytesRead = is.read(buffer)) != -1) { + os.write(buffer, 0, bytesRead); + } + is.close(); + os.flush(); + os.close(); + } + TestSuiteLogger.log(Level.FINE, + "Wrote " + destFile.length() + " bytes to file at " + destFile.getAbsolutePath()); + return destFile; + } + + /** + * Constructs an absolute URI from the given URI reference and a base URI. + * + * @see RFC 3986, 5.2 + * @param baseURI The base URI; if present, it must be an absolute URI. + * @param uriRef A URI reference that may be relative to the given base URI. + * @return The resulting URI. + */ + public static URI resolveRelativeURI(String baseURI, String uriRef) { + URI uri = (null != baseURI) ? URI.create(baseURI) : URI.create(""); + if (null != baseURI && null == uri.getScheme()) { + throw new IllegalArgumentException("Base URI has no scheme component: " + baseURI); + } + return uri.resolve(uriRef); + } - /** - * Constructs an absolute URI from the given URI reference and a base URI. - * - * @see RFC 3986, - * 5.2 - * - * @param baseURI - * The base URI; if present, it must be an absolute URI. - * @param uriRef - * A URI reference that may be relative to the given base URI. - * @return The resulting URI. - * - */ - public static URI resolveRelativeURI(String baseURI, String uriRef) { - URI uri = (null != baseURI) ? URI.create(baseURI) : URI.create(""); - if (null != baseURI && null == uri.getScheme()) { - throw new IllegalArgumentException( - "Base URI has no scheme component: " + baseURI); - } - return uri.resolve(uriRef); - } } diff --git a/src/main/java/org/opengis/cite/wps20/util/ValidationUtils.java b/src/main/java/org/opengis/cite/wps20/util/ValidationUtils.java index e0d5abe..4adcd10 100644 --- a/src/main/java/org/opengis/cite/wps20/util/ValidationUtils.java +++ b/src/main/java/org/opengis/cite/wps20/util/ValidationUtils.java @@ -21,164 +21,149 @@ import javax.xml.validation.Schema; import org.apache.xerces.util.XMLCatalogResolver; -import org.opengis.cite.wps20.Namespaces; import org.opengis.cite.validation.SchematronValidator; import org.opengis.cite.validation.XmlSchemaCompiler; -import org.opengis.cite.wps20.util.ValidationUtils; +import org.opengis.cite.wps20.Namespaces; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.SAXException; /** - * 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/wps20/"; - private static final XMLCatalogResolver SCH_RESOLVER = initCatalogResolver(); + static final String ROOT_PKG = "/org/opengis/cite/wps20/"; + + private static final XMLCatalogResolver SCH_RESOLVER = initCatalogResolver(); + + private static XMLCatalogResolver initCatalogResolver() { + return (XMLCatalogResolver) createSchemaResolver(Namespaces.SCH); + } + + /** + * 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; - } + /** + * 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; + } - /** - * 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; - } + /** + *

    + * createSchema. + *

    + * @param xsdPath a {@link java.lang.String} object + * @return a {@link javax.xml.validation.Schema} object + */ + public static Schema createSchema(String xsdPath) { + URL entityCatalog = ValidationUtils.class.getResource(ROOT_PKG + "schema-catalog.xml"); + XmlSchemaCompiler xsdCompiler = new XmlSchemaCompiler(entityCatalog); + Schema wpsSchema = null; + try { + URL schemaURL = ValidationUtils.class.getResource(ROOT_PKG + xsdPath); + Source xsdSource = new StreamSource(schemaURL.toString()); + wpsSchema = xsdCompiler.compileXmlSchema(new Source[] { xsdSource }); + } + catch (SAXException e) { + TestSuiteLogger.log(Level.WARNING, "Failed to create WFS Schema object.", e); + } + return wpsSchema; + } - /** - * 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; - } - - public static Schema createSchema(String xsdPath) { - URL entityCatalog = ValidationUtils.class.getResource(ROOT_PKG - + "schema-catalog.xml"); - XmlSchemaCompiler xsdCompiler = new XmlSchemaCompiler(entityCatalog); - Schema wpsSchema = null; - try { - URL schemaURL = ValidationUtils.class.getResource(ROOT_PKG - + xsdPath); - Source xsdSource = new StreamSource(schemaURL.toString()); - wpsSchema = xsdCompiler - .compileXmlSchema(new Source[] { xsdSource }); - } catch (SAXException e) { - TestSuiteLogger.log(Level.WARNING, - "Failed to create WFS Schema object.", e); - } - return wpsSchema; - } } diff --git a/src/main/java/org/opengis/cite/wps20/util/XMLUtils.java b/src/main/java/org/opengis/cite/wps20/util/XMLUtils.java index 729d7ab..56ea007 100644 --- a/src/main/java/org/opengis/cite/wps20/util/XMLUtils.java +++ b/src/main/java/org/opengis/cite/wps20/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.wps20.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.wps20.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/wps20/VerifyETSAssert.java b/src/test/java/org/opengis/cite/wps20/VerifyETSAssert.java index 8505024..c5e4dc9 100644 --- a/src/test/java/org/opengis/cite/wps20/VerifyETSAssert.java +++ b/src/test/java/org/opengis/cite/wps20/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/wps20/VerifySuiteFixtureListener.java b/src/test/java/org/opengis/cite/wps20/VerifySuiteFixtureListener.java index a1b8f25..507141e 100644 --- a/src/test/java/org/opengis/cite/wps20/VerifySuiteFixtureListener.java +++ b/src/test/java/org/opengis/cite/wps20/VerifySuiteFixtureListener.java @@ -4,7 +4,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; @@ -16,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"); - Map params = new HashMap(); - params.put(TestRunArg.IUT.toString(), url.toURI().toString()); - //params.put(TestRunArg.SERVICE_URL.toString(), url.toURI().toString()); - params.put(TestRunArg.ECHO_PROCESS_ID.toString(), url.toURI().toString()); - when(xmlSuite.getParameters()).thenReturn(params); - SuiteFixtureListener iut = new SuiteFixtureListener(); - iut.onStart(suite); - verify(suite).setAttribute( - Matchers.eq(SuiteAttribute.SERVICE_URL.getName()), - Matchers.isA(URI.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"); + Map params = new HashMap(); + params.put(TestRunArg.IUT.toString(), url.toURI().toString()); + // params.put(TestRunArg.SERVICE_URL.toString(), url.toURI().toString()); + params.put(TestRunArg.ECHO_PROCESS_ID.toString(), url.toURI().toString()); + when(xmlSuite.getParameters()).thenReturn(params); + SuiteFixtureListener iut = new SuiteFixtureListener(); + iut.onStart(suite); + verify(suite).setAttribute(ArgumentMatchers.eq(SuiteAttribute.SERVICE_URL.getName()), + ArgumentMatchers.isA(URI.class)); + } } diff --git a/src/test/java/org/opengis/cite/wps20/VerifyTestNGController.java b/src/test/java/org/opengis/cite/wps20/VerifyTestNGController.java index 93af3f9..bba725c 100644 --- a/src/test/java/org/opengis/cite/wps20/VerifyTestNGController.java +++ b/src/test/java/org/opengis/cite/wps20/VerifyTestNGController.java @@ -1,11 +1,10 @@ package org.opengis.cite.wps20; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.net.URL; import java.util.InvalidPropertiesFormatException; import java.util.Properties; @@ -14,59 +13,55 @@ import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Source; -import net.sf.saxon.s9api.XdmValue; - import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.opengis.cite.wps20.util.XMLUtils; import org.w3c.dom.Document; +import net.sf.saxon.s9api.XdmValue; + /** * 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(); + } - @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")); + } - @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"); + // this.testRunProps.setProperty(TestRunArg.IUT.toString(), testSubject + // .toURI().toString()); + ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024); + this.testRunProps.storeToXML(outStream, "Integration test"); + Document testRunArgs = docBuilder.parse(new ByteArrayInputStream(outStream.toByteArray())); + TestNGController controller = new TestNGController(); + Source results = controller.doTestRun(testRunArgs); + String xpath = "/testng-results/@failed"; + XdmValue failed = XMLUtils.evaluateXPath2(results, xpath, null); + int numFailed = Integer.parseInt(failed.getUnderlyingValue().getStringValue()); + // assertEquals("Unexpected number of fail verdicts.", 2, numFailed); + assertEquals("Unexpected number of fail verdicts.", 0, numFailed); + } - @Test - public void doTestRun() throws Exception { - //URL testSubject = getClass().getResource("/atom-feed-2.xml"); - //this.testRunProps.setProperty(TestRunArg.IUT.toString(), testSubject - // .toURI().toString()); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024); - this.testRunProps.storeToXML(outStream, "Integration test"); - Document testRunArgs = docBuilder.parse(new ByteArrayInputStream( - outStream.toByteArray())); - TestNGController controller = new TestNGController(); - Source results = controller.doTestRun(testRunArgs); - String xpath = "/testng-results/@failed"; - XdmValue failed = XMLUtils.evaluateXPath2(results, xpath, null); - int numFailed = Integer.parseInt(failed.getUnderlyingValue() - .getStringValue()); -// assertEquals("Unexpected number of fail verdicts.", 2, numFailed); - assertEquals("Unexpected number of fail verdicts.", 0, numFailed); - } } diff --git a/src/test/java/org/opengis/cite/wps20/util/VerifyURIUtils.java b/src/test/java/org/opengis/cite/wps20/util/VerifyURIUtils.java index 948f163..bd4ffdb 100644 --- a/src/test/java/org/opengis/cite/wps20/util/VerifyURIUtils.java +++ b/src/test/java/org/opengis/cite/wps20/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/wps20/util/VerifyValidationUtils.java b/src/test/java/org/opengis/cite/wps20/util/VerifyValidationUtils.java index ea3531b..a882e3e 100644 --- a/src/test/java/org/opengis/cite/wps20/util/VerifyValidationUtils.java +++ b/src/test/java/org/opengis/cite/wps20/util/VerifyValidationUtils.java @@ -1,6 +1,7 @@ package org.opengis.cite.wps20.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/wps20/util/VerifyXMLUtils.java b/src/test/java/org/opengis/cite/wps20/util/VerifyXMLUtils.java index 2cff20f..5efc62d 100644 --- a/src/test/java/org/opengis/cite/wps20/util/VerifyXMLUtils.java +++ b/src/test/java/org/opengis/cite/wps20/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); + } + }