();
+ 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 hhhh;} 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 hhhh;} 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);
+ }
+
}