it = sources.iterator();
+ while (it.hasNext()) {
+ File source = it.next();
+ LOGR.log(Level.FINE, "Processing CTL source files in {0}", source.getAbsolutePath());
+ String encodedName = createEncodedName(source);
+ if (docMode) {
+ encodedName += "d";
+ }
+ File workingDir = new File(opts.getWorkDir(), encodedName);
+ if (!workingDir.exists() && !workingDir.mkdir()) {
+ LOGR.log(Level.WARNING, "Unable to create working directory at {0}", workingDir.getAbsolutePath());
+ }
+ if (source.isDirectory()) {
+ String[] children = source.list();
+ for (int i = 0; i < children.length; i++) {
+ // Finds all .ctl and .xml files in the directory to use
+ String lowerName = children[i].toLowerCase();
+ if (lowerName.endsWith(".ctl") || lowerName.endsWith(".xml")) {
+ File file = new File(source, children[i]);
+ if (file.isFile()) {
+ sourceFiles.add(file);
+ String basename = children[i].substring(0, children[i].length() - 4);
+ File subdir = new File(workingDir, basename);
+ subdir.mkdir();
+ workDirs.add(subdir);
+ }
+ }
+ }
+ }
+ else {
+ sourceFiles.add(source);
+ workDirs.add(workingDir);
+ }
+ }
+
+ // resolve xinclude elements but omit xml:base attributes
+ SAXParser parser = XMLParserUtils.createXIncludeAwareSAXParser(false);
+
+ File generatorStylesheet = Misc.getResourceAsFile(generatorStylesheetResource);
+
+ // Process each CTL source file
+ for (int i = 0; i < sourceFiles.size(); i++) {
+ File sourceFile = sourceFiles.get(i);
+ File workingDir = workDirs.get(i);
+
+ // Read previous index for this file (if any), and determine whether
+ // the index and xsl need to be regenerated
+ File indexFile = new File(workingDir, "index.xml");
+ Index index = null;
+ boolean regenerate = true;
+
+ if (generatorStylesheet == null) {
+ // generatorStylesheet couldn't be found as a file (it was loaded from
+ // classpath jar)
+ regenerate = true;
+ }
+ else if (indexFile.isFile()) {
+ try {
+ if (indexFile.lastModified() > generatorStylesheet.lastModified()) {
+ index = new Index(indexFile);
+ regenerate = index.outOfDate();
+ }
+ }
+ catch (Exception e) {
+ // If there was an exception reading the index file, it is
+ // likely corrupt. Regenerate it.
+ regenerate = true;
+ }
+ }
+
+ if (regenerate) {
+ // Validate the source CTL file
+ boolean validationErrors = false;
+ if (opts.isValidate()) {
+ int old_count = validation_eh.getErrorCount();
+ LOGR.log(Level.CONFIG, "Validating " + sourceFile);
+ ctl_validator.validate(new StreamSource(sourceFile));
+ validationErrors = (validation_eh.getErrorCount() > old_count);
+ }
+
+ if (!validationErrors) {
+ // Clean up the working directory
+ Misc.deleteDirContents(workingDir);
+
+ InputSource input = new InputSource(new FileInputStream(sourceFile));
+ input.setSystemId(sourceFile.toURI().toString());
+ // Fortify Mods to prevent External Entity Injection
+ XMLReader reader = parser.getXMLReader();
+ reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ Source ctlSource = new SAXSource(reader, input);
+ // Source ctlSource = new SAXSource(parser.getXMLReader(),input);
+ // End Fortify Mods
+ // Run the generator transformation. Output is an index file
+ // and is saved to disk. The generator also creates XSL
+ // template files in the working dir.
+ generatorTransformer.setSource(ctlSource);
+ Serializer generatorSerializer = new Serializer();
+ generatorSerializer.setOutputFile(indexFile);
+ generatorTransformer.setDestination(generatorSerializer);
+ XdmAtomicValue av = new XdmAtomicValue(workingDir.getAbsolutePath());
+ generatorTransformer.setParameter(new QName("outdir"), av);
+ generatorTransformer.transform();
+
+ // Read the generated index
+ index = new Index(indexFile);
+ }
+ }
+ // Add new index entries to the master index
+ masterIndex.add(index);
+ }
+
+ // If there were any validation errors, display them and throw an
+ // exception
+ int error_count = validation_eh.getErrorCount();
+ if (error_count > 0) {
+ String msg = error_count + " validation error" + (error_count == 1 ? "" : "s");
+ int warning_count = validation_eh.getWarningCount();
+ if (warning_count > 0) {
+ msg += " and " + warning_count + " warning" + (warning_count == 1 ? "" : "s");
+ }
+ msg += " detected.";
+ // appLogger.severe(msg);
+ throw new Exception(msg);
+ }
+
+ return masterIndex;
+ }
+
+ /**
+ * Creates a directory name from a file path.
+ * @param source A File reference.
+ * @return A String representing a legal directory name.
+ */
+ public static String createEncodedName(File source) {
+ String fileURI = source.toURI().toString();
+ String userDirURI = new File(System.getProperty("user.dir")).toURI().toString();
+ fileURI = fileURI.replace(userDirURI, "");
+ return fileURI.substring(fileURI.lastIndexOf(':') + 1).replace("%20", "-").replace('/', '_');
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/ListSuites.java b/teamengine-core/src/main/java/com/occamlab/te/ListSuites.java
index 52c45905e..4bff7ca1f 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/ListSuites.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/ListSuites.java
@@ -1,114 +1,134 @@
-package com.occamlab.te;
-
-import java.io.File;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-
-import com.occamlab.te.index.Index;
-import com.occamlab.te.index.SuiteEntry;
-
-/**
- * Command line utility for listing test suites in CTL sources.
- *
- * C. Heazel: modified to address Fortify issues 1/24/18
- *
- */
-public class ListSuites {
-
- public static void main(String[] args) throws Exception {
- SetupOptions setupOpts = new SetupOptions();
- File scriptsDir = new File(SetupOptions.getBaseConfigDirectory(), "scripts");
- String cmd = "java com.occamlab.te.ListSuites";
-
- // Parse source command-line argument
- for (int i = 0; i < args.length; i++) {
- if (args[i].startsWith("-source=")) {
- File f = new File(scriptsDir, args[i].substring(8));
- // Fortify Mod: make sure that the -source argument
- // is not pointing to an illegal location
- if (!f.exists() || !setupOpts.addSourceWithValidation(f)) {
- System.out.println("Error: Can't find CTL script(s) at " + f.getAbsolutePath());
- return;
- }
- }
- else if (args[i].startsWith("-cmd=")) {
- cmd = args[i].substring(5);
- }
- else if (args[i].equals("-h") || args[i].equals("-help") || args[i].equals("-?")) {
- syntax(cmd);
- return;
- }
- }
-
- if (setupOpts.getSources().isEmpty()) {
- String path = SetupOptions.getBaseConfigDirectory() + "/config.xml";
- if (new File(path).exists()) {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setExpandEntityReferences(false);
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document doc = db.parse(path);
- NodeList nl = doc.getElementsByTagName("source");
- if (nl != null) {
- for (int i = 0; i < nl.getLength(); i++) {
- Element source = (Element) nl.item(i);
- File f = new File(scriptsDir, source.getTextContent());
- if (!f.exists() || !setupOpts.addSourceWithValidation(f)) {
- System.out.println("Error: Can't find CTL script(s) at " + f.getAbsolutePath());
- }
- listSuites(setupOpts, true);
- setupOpts.getSources().clear();
- }
- }
- }
- else {
- System.out.println("No config.xml file found in TE_BASE path " + SetupOptions.getBaseConfigDirectory());
- }
- }
- else {
- listSuites(setupOpts, false);
- }
- }
-
- static void listSuites(SetupOptions setupOpts, boolean printSource) throws Exception {
- Index index = Generator.generateXsl(setupOpts);
- if (printSource) {
- System.out.println("Source: " + setupOpts.getSources().get(0));
- }
- for (String suiteId : index.getSuiteKeys()) {
- SuiteEntry suite = index.getSuite(suiteId);
- if (printSource) {
- System.out.print(" ");
- }
- System.out.print("Suite " + suite.getPrefix() + ":" + suite.getLocalName());
- System.out.println(" (" + suiteId + ")");
- System.out.println(" Title: " + suite.getTitle());
- String desc = suite.getDescription();
- if (desc != null) {
- System.out.println(" Description: " + desc);
- }
- String link = suite.getLink();
- if (link != null) {
- System.out.println(" Link: " + link);
- }
- System.out.println();
- }
- if (index.getSuiteKeys().isEmpty()) {
- System.out.println("No suites found.");
- System.out.println("Check the sources in config.xml or supply -source=path option(s).");
- }
- System.out.println();
- }
-
- static void syntax(String cmd) {
- System.out.println();
- System.out.println("Lists available test suites:");
- System.out.println();
- System.out.println(cmd + " [-source=ctlfile|dir]...\n");
- }
-
-}
+package com.occamlab.te;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.File;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import com.occamlab.te.index.Index;
+import com.occamlab.te.index.SuiteEntry;
+
+/**
+ * Command line utility for listing test suites in CTL sources.
+ *
+ * C. Heazel: modified to address Fortify issues 1/24/18
+ *
+ */
+public class ListSuites {
+
+ public static void main(String[] args) throws Exception {
+ SetupOptions setupOpts = new SetupOptions();
+ File scriptsDir = new File(SetupOptions.getBaseConfigDirectory(), "scripts");
+ String cmd = "java com.occamlab.te.ListSuites";
+
+ // Parse source command-line argument
+ for (int i = 0; i < args.length; i++) {
+ if (args[i].startsWith("-source=")) {
+ File f = new File(scriptsDir, args[i].substring(8));
+ // Fortify Mod: make sure that the -source argument
+ // is not pointing to an illegal location
+ if (!f.exists() || !setupOpts.addSourceWithValidation(f)) {
+ System.out.println("Error: Can't find CTL script(s) at " + f.getAbsolutePath());
+ return;
+ }
+ }
+ else if (args[i].startsWith("-cmd=")) {
+ cmd = args[i].substring(5);
+ }
+ else if (args[i].equals("-h") || args[i].equals("-help") || args[i].equals("-?")) {
+ syntax(cmd);
+ return;
+ }
+ }
+
+ if (setupOpts.getSources().isEmpty()) {
+ String path = SetupOptions.getBaseConfigDirectory() + "/config.xml";
+ if (new File(path).exists()) {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setExpandEntityReferences(false);
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ Document doc = db.parse(path);
+ NodeList nl = doc.getElementsByTagName("source");
+ if (nl != null) {
+ for (int i = 0; i < nl.getLength(); i++) {
+ Element source = (Element) nl.item(i);
+ File f = new File(scriptsDir, source.getTextContent());
+ if (!f.exists() || !setupOpts.addSourceWithValidation(f)) {
+ System.out.println("Error: Can't find CTL script(s) at " + f.getAbsolutePath());
+ }
+ listSuites(setupOpts, true);
+ setupOpts.getSources().clear();
+ }
+ }
+ }
+ else {
+ System.out.println("No config.xml file found in TE_BASE path " + SetupOptions.getBaseConfigDirectory());
+ }
+ }
+ else {
+ listSuites(setupOpts, false);
+ }
+ }
+
+ static void listSuites(SetupOptions setupOpts, boolean printSource) throws Exception {
+ Index index = Generator.generateXsl(setupOpts);
+ if (printSource) {
+ System.out.println("Source: " + setupOpts.getSources().get(0));
+ }
+ for (String suiteId : index.getSuiteKeys()) {
+ SuiteEntry suite = index.getSuite(suiteId);
+ if (printSource) {
+ System.out.print(" ");
+ }
+ System.out.print("Suite " + suite.getPrefix() + ":" + suite.getLocalName());
+ System.out.println(" (" + suiteId + ")");
+ System.out.println(" Title: " + suite.getTitle());
+ String desc = suite.getDescription();
+ if (desc != null) {
+ System.out.println(" Description: " + desc);
+ }
+ String link = suite.getLink();
+ if (link != null) {
+ System.out.println(" Link: " + link);
+ }
+ System.out.println();
+ }
+ if (index.getSuiteKeys().isEmpty()) {
+ System.out.println("No suites found.");
+ System.out.println("Check the sources in config.xml or supply -source=path option(s).");
+ }
+ System.out.println();
+ }
+
+ static void syntax(String cmd) {
+ System.out.println();
+ System.out.println("Lists available test suites:");
+ System.out.println();
+ System.out.println(cmd + " [-source=ctlfile|dir]...\n");
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/NullErrorListener.java b/teamengine-core/src/main/java/com/occamlab/te/NullErrorListener.java
index a99e4693e..25c6742dc 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/NullErrorListener.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/NullErrorListener.java
@@ -12,6 +12,26 @@ Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
****************************************************************************/
package com.occamlab.te;
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
import javax.xml.transform.ErrorListener;
import javax.xml.transform.TransformerException;
diff --git a/teamengine-core/src/main/java/com/occamlab/te/RecordTestResult.java b/teamengine-core/src/main/java/com/occamlab/te/RecordTestResult.java
index 1406ade53..62d54f1b9 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/RecordTestResult.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/RecordTestResult.java
@@ -10,6 +10,26 @@
*/
package com.occamlab.te;
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
import static com.occamlab.te.TECore.getResultDescription;
import com.occamlab.te.index.SuiteEntry;
import com.occamlab.te.index.TestEntry;
diff --git a/teamengine-core/src/main/java/com/occamlab/te/RecordedForm.java b/teamengine-core/src/main/java/com/occamlab/te/RecordedForm.java
index 1c787f711..d5d46c62e 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/RecordedForm.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/RecordedForm.java
@@ -8,6 +8,26 @@
*/
package com.occamlab.te;
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
@@ -41,4 +61,4 @@ public static RecordedForm create(File formFile, TECore teCore) {
return new RecordedForm(formFile, teCore);
}
-}
\ No newline at end of file
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/RecordedForms.java b/teamengine-core/src/main/java/com/occamlab/te/RecordedForms.java
index f1b4d4b32..353229247 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/RecordedForms.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/RecordedForms.java
@@ -1,5 +1,25 @@
package com.occamlab.te;
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
import java.io.File;
import java.util.ArrayList;
import java.util.List;
diff --git a/teamengine-core/src/main/java/com/occamlab/te/RuntimeOptions.java b/teamengine-core/src/main/java/com/occamlab/te/RuntimeOptions.java
index 06b1e5682..4216411d7 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/RuntimeOptions.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/RuntimeOptions.java
@@ -1,303 +1,323 @@
-/*
-
- The Original Code is TEAM Engine.
-
- The Initial Developer of the Original Code is Northrop Grumman Corporation
- jointly with The National Technology Alliance. Portions created by
- Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
- Grumman Corporation. All Rights Reserved.
-
- January 2018 - Modified all set operations to validate the input prior
- to updating the runtime properties. This included converting these
- operations to return a boolean vs. a void.
-
- Contributor(s):
- C. Heazel (WiSC):
- - Modifications to address Fortify issues
- - Modifications to validate parameters on set operations
- */
-
-package com.occamlab.te;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import com.occamlab.te.util.TEPath; // Fortify addition
-
-import net.sf.saxon.s9api.XdmNode;
-
-/**
- * The RuntimeOptions class provides runtime configuration settings for use by a test. It
- * is not enough for this class to hold the settings. It also must assure that the
- * settings are correct and valid. A bad configuration value will result in incorrect
- * behavior for the test and may even crash the Engine. Therefor, this class implements
- * the following requirements: 1) A RuntimeOptions object may be used without setting any
- * of the settings. Therefore, the constructor shall initialize all settings to valid
- * values. 2) Users may overwrite the RuntimeOption settings Therefore, each "set"
- * operation shall validate its argument prior to modifying the setting. 3) The integrity
- * of the settings must be protected. Therefore the settings can only be modified through
- * the "set" operations. 4) Users must know the state of the runtime settings. Therefore,
- * all operations shall return a value.
- *
- * The Runtime settings are:
- *
- * testLogDir: This is the directory where the log file will be written. workDir:
- * sessionId: suiteName: A suite is a set of tests. This is the name of the current suite
- * testName: The name of the current test. sourcesName: baseURI: profiles: testPaths:
- * params: recordedForms:
- *
- * The configuration settings are:
- *
- * testLogDir: -- Constraint: Must be a valid TE directory path. -- Constraint: Null is
- * not allowed. -- Comment: Initialized to the TE_BASE/users/ directory
- * workDir: -- Constraint: Must be a valid TE directory path. -- Constraint: Null is not
- * allowed. -- Comment: Initialized from setupOptions sessionId: -- Constraint: Required
- * format is UUID although others are tolerated for now -- Constraint: Null is not
- * allowed. suiteName: -- Constraint: Cannot be null -- Comment: initialized to an empty
- * string testName: -- Constraint: Cannot be null -- Comment: initialized to an empty
- * string sourcesName: -- Constraint: Cannot be null -- Comment: initialized to "default"
- * -- TO-DO: determine why any other default breaks TE. baseURI: -- Constraint: Cannot be
- * null -- Comment: initialized to an empty string profiles: -- Comment: initialized to an
- * empty array list testPaths: -- Comment: initialized to an empty array list params: --
- * Comment: initialized to an empty array list recordedForms: -- Comment: initialized to
- * an empty array list
- */
-
-public class RuntimeOptions {
-
- private int mode = Test.TEST_MODE;
-
- private File testLogDir = null;
-
- private File workDir = null;
-
- private String sessionId;
-
- private String testName = "";
-
- private String suiteName = "";
-
- private String sourcesName = "default";
-
- private String baseURI = "";
-
- private ArrayList profiles = new ArrayList<>();
-
- private ArrayList testPaths = new ArrayList<>();
-
- private ArrayList params = new ArrayList<>();
-
- private List recordedForms = new ArrayList<>();
-
- private static Logger jLogger = Logger.getLogger("com.occamlab.te.RuntimeOptions");
-
- private static final String UUID_PATTERN = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$";
-
- /**
- * Default constructor sets the location of the test log directory to
- * TE_BASE/users/{user.name}; it is created if it does not exist.
- */
- public RuntimeOptions() {
- File baseDir = SetupOptions.getBaseConfigDirectory();
- File usersDir = new File(baseDir, "users");
- File userDir = new File(usersDir, System.getProperty("user.name"));
- if (!userDir.exists()) {
- userDir.mkdirs();
- }
- this.testLogDir = userDir;
- SetupOptions sopts = new SetupOptions();
- this.workDir = sopts.getWorkDir();
- jLogger.setLevel(Level.INFO);
- }
-
- public String getBaseURI() {
- return baseURI;
- }
-
- // Validate the baseURI argument then update the runtime parameter
- public boolean setBaseURI(String baseURI) {
- Logger.getLogger(RuntimeOptions.class.getName()).log(Level.CONFIG, "Setting baseURI = " + baseURI);
- if (baseURI == null)
- return false;
- this.baseURI = baseURI;
- return true;
- }
-
- public String getSourcesName() {
- return sourcesName;
- }
-
- // Validate the sourcesName argument then update the runtime parameter
- public boolean setSourcesName(String sourcesName) {
- if (sourcesName == null)
- return false;
- this.sourcesName = sourcesName;
- return true;
- }
-
- /**
- * Returns the location of the directory for writing test logs to.
- * @return A File denoting a directory.
- */
- public File getLogDir() {
- return testLogDir;
- }
-
- // Validate the logDir argument then update the runtime parameter
- public boolean setLogDir(File logDir) {
- // Fortify Mod: validate that this is a legal path
- if (logDir == null)
- return false;
- TEPath tpath = new TEPath(logDir.getAbsolutePath());
- if (tpath.isValid()) {
- this.testLogDir = logDir;
- return true;
- }
- return false;
- }
-
- public File getWorkDir() {
- return workDir;
- }
-
- // Validate the workDir argument then update the runtime parameter
- public boolean setWorkDir(File workDir) {
- // Fortify Mod: validate that this is a legal path
- if (workDir == null)
- return false;
- TEPath tpath = new TEPath(workDir.getAbsolutePath());
- if (tpath.isValid()) {
- this.workDir = workDir;
- return true;
- }
- return false;
- }
-
- public int getMode() {
- return mode;
- }
-
- // Validate the mode argument then update the runtime parameter
- public boolean setMode(int mode) {
- if (mode != Test.TEST_MODE && mode != Test.RETEST_MODE && mode != Test.RESUME_MODE
- && mode != Test.REDO_FROM_CACHE_MODE && mode != Test.DOC_MODE && mode != Test.CHECK_MODE)
- return false;
- this.mode = mode;
- return true;
- }
-
- public String getSessionId() {
- return sessionId;
- }
-
- // Validate the sessionId argument then update the runtime parameter
- public boolean setSessionId(String sessionId) {
- jLogger.log(Level.INFO, "RuntimeOptions: Setting session to " + sessionId);
- if (sessionId == null) {
- return false;
- }
- this.sessionId = sessionId;
- return true;
- }
-
- public String getSuiteName() {
- return suiteName;
- }
-
- // Validate the suiteName argument then update the runtime parameter
- public boolean setSuiteName(String suiteName) {
- if (suiteName == null)
- return false;
- this.suiteName = suiteName;
- return true;
- }
-
- public ArrayList getProfiles() {
- return profiles;
- }
-
- // Validate the profile argument then update the runtime parameter
- public boolean addProfile(String profile) {
- if (profile == null)
- return false;
- this.profiles.add(profile);
- return true;
- }
-
- public ArrayList getTestPaths() {
- return testPaths;
- }
-
- // Validate the testPath argument then update the runtime parameter
- public boolean addTestPath(String testPath) {
- if (testPath == null)
- return false;
- this.testPaths.add(testPath);
- return true;
- }
-
- public ArrayList getParams() {
- return params;
- }
-
- // Validate the param argument then update the runtime parameter
- public boolean addParam(String param) {
- if (param == null)
- return false;
- this.params.add(param);
- return true;
- }
-
- public XdmNode getContextNode() {
- return null;
- }
-
- public String getTestName() {
- return testName;
- }
-
- // Validate the testName argument then update the runtime parameter
- public boolean setTestName(String testName) {
- if (testName == null)
- return false;
- this.testName = testName;
- return true;
- }
-
- // Validate the recordedForm argument then update the runtime parameter
- public boolean addRecordedForm(String recordedForm) {
- if (recordedForm == null)
- return false;
- recordedForms.add(new File(recordedForm));
- return true;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder("RuntimeOptions {\n");
- sb.append("mode=").append(mode).append(",\n");
- sb.append("testLogDir=").append(testLogDir).append(",\n");
- sb.append("workDir=").append(workDir).append(",\n");
- sb.append("sessionId=").append(sessionId).append(",\n");
- sb.append("testName=").append(testName).append(",\n");
- sb.append("suiteName=").append(suiteName).append(",\n");
- sb.append("sourcesName=").append(sourcesName).append(",\n");
- sb.append("baseURI=").append(baseURI).append(",\n");
- sb.append("profiles=").append(profiles).append(",\n");
- sb.append("testPaths=").append(testPaths).append(",\n");
- sb.append("recordedFroms=").append(recordedForms).append(",\n");
- sb.append("params=").append(params).append("\n}");
- return sb.toString();
- }
-
- /**
- * @return the recordedForms
- */
- public List getRecordedForms() {
- return recordedForms;
- }
-
-}
+/*
+
+ The Original Code is TEAM Engine.
+
+ The Initial Developer of the Original Code is Northrop Grumman Corporation
+ jointly with The National Technology Alliance. Portions created by
+ Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
+ Grumman Corporation. All Rights Reserved.
+
+ January 2018 - Modified all set operations to validate the input prior
+ to updating the runtime properties. This included converting these
+ operations to return a boolean vs. a void.
+
+ Contributor(s):
+ C. Heazel (WiSC):
+ - Modifications to address Fortify issues
+ - Modifications to validate parameters on set operations
+ */
+
+package com.occamlab.te;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import com.occamlab.te.util.TEPath; // Fortify addition
+
+import net.sf.saxon.s9api.XdmNode;
+
+/**
+ * The RuntimeOptions class provides runtime configuration settings for use by a test. It
+ * is not enough for this class to hold the settings. It also must assure that the
+ * settings are correct and valid. A bad configuration value will result in incorrect
+ * behavior for the test and may even crash the Engine. Therefor, this class implements
+ * the following requirements: 1) A RuntimeOptions object may be used without setting any
+ * of the settings. Therefore, the constructor shall initialize all settings to valid
+ * values. 2) Users may overwrite the RuntimeOption settings Therefore, each "set"
+ * operation shall validate its argument prior to modifying the setting. 3) The integrity
+ * of the settings must be protected. Therefore the settings can only be modified through
+ * the "set" operations. 4) Users must know the state of the runtime settings. Therefore,
+ * all operations shall return a value.
+ *
+ * The Runtime settings are:
+ *
+ * testLogDir: This is the directory where the log file will be written. workDir:
+ * sessionId: suiteName: A suite is a set of tests. This is the name of the current suite
+ * testName: The name of the current test. sourcesName: baseURI: profiles: testPaths:
+ * params: recordedForms:
+ *
+ * The configuration settings are:
+ *
+ * testLogDir: -- Constraint: Must be a valid TE directory path. -- Constraint: Null is
+ * not allowed. -- Comment: Initialized to the TE_BASE/users/ directory
+ * workDir: -- Constraint: Must be a valid TE directory path. -- Constraint: Null is not
+ * allowed. -- Comment: Initialized from setupOptions sessionId: -- Constraint: Required
+ * format is UUID although others are tolerated for now -- Constraint: Null is not
+ * allowed. suiteName: -- Constraint: Cannot be null -- Comment: initialized to an empty
+ * string testName: -- Constraint: Cannot be null -- Comment: initialized to an empty
+ * string sourcesName: -- Constraint: Cannot be null -- Comment: initialized to "default"
+ * -- TO-DO: determine why any other default breaks TE. baseURI: -- Constraint: Cannot be
+ * null -- Comment: initialized to an empty string profiles: -- Comment: initialized to an
+ * empty array list testPaths: -- Comment: initialized to an empty array list params: --
+ * Comment: initialized to an empty array list recordedForms: -- Comment: initialized to
+ * an empty array list
+ */
+
+public class RuntimeOptions {
+
+ private int mode = Test.TEST_MODE;
+
+ private File testLogDir = null;
+
+ private File workDir = null;
+
+ private String sessionId;
+
+ private String testName = "";
+
+ private String suiteName = "";
+
+ private String sourcesName = "default";
+
+ private String baseURI = "";
+
+ private ArrayList profiles = new ArrayList<>();
+
+ private ArrayList testPaths = new ArrayList<>();
+
+ private ArrayList params = new ArrayList<>();
+
+ private List recordedForms = new ArrayList<>();
+
+ private static Logger jLogger = Logger.getLogger("com.occamlab.te.RuntimeOptions");
+
+ private static final String UUID_PATTERN = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$";
+
+ /**
+ * Default constructor sets the location of the test log directory to
+ * TE_BASE/users/{user.name}; it is created if it does not exist.
+ */
+ public RuntimeOptions() {
+ File baseDir = SetupOptions.getBaseConfigDirectory();
+ File usersDir = new File(baseDir, "users");
+ File userDir = new File(usersDir, System.getProperty("user.name"));
+ if (!userDir.exists()) {
+ userDir.mkdirs();
+ }
+ this.testLogDir = userDir;
+ SetupOptions sopts = new SetupOptions();
+ this.workDir = sopts.getWorkDir();
+ jLogger.setLevel(Level.INFO);
+ }
+
+ public String getBaseURI() {
+ return baseURI;
+ }
+
+ // Validate the baseURI argument then update the runtime parameter
+ public boolean setBaseURI(String baseURI) {
+ Logger.getLogger(RuntimeOptions.class.getName()).log(Level.CONFIG, "Setting baseURI = " + baseURI);
+ if (baseURI == null)
+ return false;
+ this.baseURI = baseURI;
+ return true;
+ }
+
+ public String getSourcesName() {
+ return sourcesName;
+ }
+
+ // Validate the sourcesName argument then update the runtime parameter
+ public boolean setSourcesName(String sourcesName) {
+ if (sourcesName == null)
+ return false;
+ this.sourcesName = sourcesName;
+ return true;
+ }
+
+ /**
+ * Returns the location of the directory for writing test logs to.
+ * @return A File denoting a directory.
+ */
+ public File getLogDir() {
+ return testLogDir;
+ }
+
+ // Validate the logDir argument then update the runtime parameter
+ public boolean setLogDir(File logDir) {
+ // Fortify Mod: validate that this is a legal path
+ if (logDir == null)
+ return false;
+ TEPath tpath = new TEPath(logDir.getAbsolutePath());
+ if (tpath.isValid()) {
+ this.testLogDir = logDir;
+ return true;
+ }
+ return false;
+ }
+
+ public File getWorkDir() {
+ return workDir;
+ }
+
+ // Validate the workDir argument then update the runtime parameter
+ public boolean setWorkDir(File workDir) {
+ // Fortify Mod: validate that this is a legal path
+ if (workDir == null)
+ return false;
+ TEPath tpath = new TEPath(workDir.getAbsolutePath());
+ if (tpath.isValid()) {
+ this.workDir = workDir;
+ return true;
+ }
+ return false;
+ }
+
+ public int getMode() {
+ return mode;
+ }
+
+ // Validate the mode argument then update the runtime parameter
+ public boolean setMode(int mode) {
+ if (mode != Test.TEST_MODE && mode != Test.RETEST_MODE && mode != Test.RESUME_MODE
+ && mode != Test.REDO_FROM_CACHE_MODE && mode != Test.DOC_MODE && mode != Test.CHECK_MODE)
+ return false;
+ this.mode = mode;
+ return true;
+ }
+
+ public String getSessionId() {
+ return sessionId;
+ }
+
+ // Validate the sessionId argument then update the runtime parameter
+ public boolean setSessionId(String sessionId) {
+ jLogger.log(Level.INFO, "RuntimeOptions: Setting session to " + sessionId);
+ if (sessionId == null) {
+ return false;
+ }
+ this.sessionId = sessionId;
+ return true;
+ }
+
+ public String getSuiteName() {
+ return suiteName;
+ }
+
+ // Validate the suiteName argument then update the runtime parameter
+ public boolean setSuiteName(String suiteName) {
+ if (suiteName == null)
+ return false;
+ this.suiteName = suiteName;
+ return true;
+ }
+
+ public ArrayList getProfiles() {
+ return profiles;
+ }
+
+ // Validate the profile argument then update the runtime parameter
+ public boolean addProfile(String profile) {
+ if (profile == null)
+ return false;
+ this.profiles.add(profile);
+ return true;
+ }
+
+ public ArrayList getTestPaths() {
+ return testPaths;
+ }
+
+ // Validate the testPath argument then update the runtime parameter
+ public boolean addTestPath(String testPath) {
+ if (testPath == null)
+ return false;
+ this.testPaths.add(testPath);
+ return true;
+ }
+
+ public ArrayList getParams() {
+ return params;
+ }
+
+ // Validate the param argument then update the runtime parameter
+ public boolean addParam(String param) {
+ if (param == null)
+ return false;
+ this.params.add(param);
+ return true;
+ }
+
+ public XdmNode getContextNode() {
+ return null;
+ }
+
+ public String getTestName() {
+ return testName;
+ }
+
+ // Validate the testName argument then update the runtime parameter
+ public boolean setTestName(String testName) {
+ if (testName == null)
+ return false;
+ this.testName = testName;
+ return true;
+ }
+
+ // Validate the recordedForm argument then update the runtime parameter
+ public boolean addRecordedForm(String recordedForm) {
+ if (recordedForm == null)
+ return false;
+ recordedForms.add(new File(recordedForm));
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder("RuntimeOptions {\n");
+ sb.append("mode=").append(mode).append(",\n");
+ sb.append("testLogDir=").append(testLogDir).append(",\n");
+ sb.append("workDir=").append(workDir).append(",\n");
+ sb.append("sessionId=").append(sessionId).append(",\n");
+ sb.append("testName=").append(testName).append(",\n");
+ sb.append("suiteName=").append(suiteName).append(",\n");
+ sb.append("sourcesName=").append(sourcesName).append(",\n");
+ sb.append("baseURI=").append(baseURI).append(",\n");
+ sb.append("profiles=").append(profiles).append(",\n");
+ sb.append("testPaths=").append(testPaths).append(",\n");
+ sb.append("recordedFroms=").append(recordedForms).append(",\n");
+ sb.append("params=").append(params).append("\n}");
+ return sb.toString();
+ }
+
+ /**
+ * @return the recordedForms
+ */
+ public List getRecordedForms() {
+ return recordedForms;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/SetupOptions.java b/teamengine-core/src/main/java/com/occamlab/te/SetupOptions.java
index 3fe5ba801..12d333fd8 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/SetupOptions.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/SetupOptions.java
@@ -1,232 +1,252 @@
-/**
- * **************************************************************************
- *
- * Contributor(s):
- * C. Heazel (WiSC): Added Fortify adjudication changes
- *
- ***************************************************************************
- */
-package com.occamlab.te;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.FileSystems;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import org.w3c.dom.Document;
-
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
-
-import com.occamlab.te.util.TEPath; // Fortify addition
-
-/**
- * Provides static configuration settings. The {@code TE_BASE} system property or
- * environment variable specifies the location of the main configuration directory that
- * contains several essential sub-directories.
- *
- *
- *
- *
- * TE_BASE
- * |-- config.xml
- * |-- resources/
- * |-- scripts/
- * |-- work/
- * +-- users/
- * |-- {username1}/
- * +-- {usernameN}/
- *
- *
- *
- *
- */
-public class SetupOptions {
-
- public static final String TE_BASE = "TE_BASE";
-
- private static File teBaseDir = getBaseConfigDirectory();
-
- boolean validate = true;
-
- boolean preload = false;
-
- File workDir = null;
-
- String sourcesName = "default";
-
- ArrayList sources = new ArrayList<>();
-
- private static Logger jLogger = Logger.getLogger("com.occamlab.te.SetupOptions");
-
- /**
- * Default constructor. Creates the TE_BASE/scripts directory if it does not exist.
- */
- public SetupOptions() {
- File scriptsDir = new File(teBaseDir, "scripts");
- if (!scriptsDir.exists() && !scriptsDir.mkdirs()) {
- throw new RuntimeException("Failed to create directory at " + scriptsDir.getAbsolutePath());
- }
- }
-
- /**
- * Determines the location of the TE_BASE directory by looking for either 1) a system
- * property or 2) an environment variable named {@value #TE_BASE}. Finally, if neither
- * is set then the "teamengine" subdirectory is created in the user home directory
- * (${user.home}/teamengine).
- * @return A File denoting the location of the base configuration directory.
- */
- public static File getBaseConfigDirectory() {
- if (null != teBaseDir) {
- return teBaseDir;
- }
- String basePath = System.getProperty(TE_BASE);
- if (null == basePath) {
- basePath = System.getenv(TE_BASE);
- }
- if (null == basePath) {
- basePath = System.getProperty("user.home") + FileSystems.getDefault().getSeparator() + "teamengine";
- }
- File baseDir = new File(basePath);
- if (!baseDir.isDirectory()) {
- baseDir.mkdirs();
- }
- Logger.getLogger(SetupOptions.class.getName()).log(Level.CONFIG, "Using TE_BASE at " + baseDir);
- return baseDir;
- }
-
- /**
- * Determine the test recording is on or off.
- * @param testName
- * @return boolean
- * @throws javax.xml.parsers.ParserConfigurationException
- * @throws org.xml.sax.SAXException
- * @throws java.io.IOException
- */
- public static boolean recordingInfo(String testName)
- throws ParserConfigurationException, SAXException, IOException {
- TECore.rootTestName.clear();
- String path = getBaseConfigDirectory() + "/config.xml";
- if (new File(path).exists()) {
- // Fortify Mod: prevent external entity injection
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setExpandEntityReferences(false);
- DocumentBuilder db = dbf.newDocumentBuilder();
- // DocumentBuilder db =
- // DocumentBuilderFactory.newInstance().newDocumentBuilder();
- Document doc = db.parse(path);
- NodeList nodeListForStandardTag = doc.getElementsByTagName("standard");
- if (null != nodeListForStandardTag && nodeListForStandardTag.getLength() > 0) {
- for (int i = 0; i < nodeListForStandardTag.getLength(); i++) {
- Element elementStandard = (Element) nodeListForStandardTag.item(i);
- if (testName.equals(elementStandard.getElementsByTagName("local-name").item(0).getTextContent())) {
- if (null != elementStandard.getElementsByTagName("record").item(0)) {
- System.setProperty("Record", "True");
- NodeList rootTestNameArray = elementStandard.getElementsByTagName("test-name");
- if (null != rootTestNameArray && rootTestNameArray.getLength() > 0) {
- for (int counter = 0; counter < rootTestNameArray.getLength(); counter++) {
- Element rootTestName = (Element) rootTestNameArray.item(counter);
- TECore.rootTestName.add(rootTestName.getTextContent());
- }
- }
- return true;
- }
- }
-
- }
- }
- }
- System.setProperty("Record", "False");
- return false;
- }
-
- public String getSourcesName() {
- return sourcesName;
- }
-
- public void setSourcesName(String sourcesName) {
- this.sourcesName = sourcesName;
- }
-
- /**
- * Returns the location of the work directory (TE_BASE/work).
- * @return A File denoting a directory location; it is created if it does not exist.
- */
- public File getWorkDir() {
- if (null == this.workDir) {
- File dir = new File(teBaseDir, "work");
- if (!dir.exists() && !dir.mkdir()) {
- throw new RuntimeException("Failed to create directory at " + dir.getAbsolutePath());
- }
- this.workDir = dir;
- }
- return workDir;
- }
-
- /**
- * Returns a list of file system resources (directories and files) containing CTL test
- * scripts.
- * @return A List containing one or more File references (TE_BASE/scripts is the
- * default location).
- */
- public List getSources() {
- return sources;
- }
-
- /**
- * Adds a file system resource to the collection of known scripts.
- * @param source A File object representing a file or directory.
- * @deprecated Use {@link SetupOptions#addSourceWithValidation(File source)} instead
- */
- @Deprecated
- public void addSource(File source) {
- this.sources.add(source);
- }
-
- /**
- * Adds a file system resource to the collection of known scripts. Fortify Mod:
- * validate the argument and return success or failure
- * @param source A File object representing a file or directory.
- */
- public boolean addSourceWithValidation(File source) {
- // Fortify Mod: validate that source is on a valid path
- if (source != null) {
- TEPath tpath = new TEPath(source.getAbsolutePath());
- if (tpath.isValid()) {
- this.sources.add(source);
- return true;
- }
- else {
- jLogger.log(Level.INFO, "SetupOptions: Attempt to set invalid source " + source);
- }
- }
- return false;
- }
-
- public Element getParamsElement() {
- return null;
- }
-
- public boolean isValidate() {
- return validate;
- }
-
- public void setValidate(boolean validate) {
- this.validate = validate;
- }
-
- public boolean isPreload() {
- return preload;
- }
-
- public void setPreload(boolean preload) {
- this.preload = preload;
- }
-
-}
+/**
+ * **************************************************************************
+ *
+ * Contributor(s):
+ * C. Heazel (WiSC): Added Fortify adjudication changes
+ *
+ ***************************************************************************
+ */
+package com.occamlab.te;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.FileSystems;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import org.w3c.dom.Document;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+import com.occamlab.te.util.TEPath; // Fortify addition
+
+/**
+ * Provides static configuration settings. The {@code TE_BASE} system property or
+ * environment variable specifies the location of the main configuration directory that
+ * contains several essential sub-directories.
+ *
+ *
+ *
+ *
+ * TE_BASE
+ * |-- config.xml
+ * |-- resources/
+ * |-- scripts/
+ * |-- work/
+ * +-- users/
+ * |-- {username1}/
+ * +-- {usernameN}/
+ *
+ *
+ *
+ *
+ */
+public class SetupOptions {
+
+ public static final String TE_BASE = "TE_BASE";
+
+ private static File teBaseDir = getBaseConfigDirectory();
+
+ boolean validate = true;
+
+ boolean preload = false;
+
+ File workDir = null;
+
+ String sourcesName = "default";
+
+ ArrayList sources = new ArrayList<>();
+
+ private static Logger jLogger = Logger.getLogger("com.occamlab.te.SetupOptions");
+
+ /**
+ * Default constructor. Creates the TE_BASE/scripts directory if it does not exist.
+ */
+ public SetupOptions() {
+ File scriptsDir = new File(teBaseDir, "scripts");
+ if (!scriptsDir.exists() && !scriptsDir.mkdirs()) {
+ throw new RuntimeException("Failed to create directory at " + scriptsDir.getAbsolutePath());
+ }
+ }
+
+ /**
+ * Determines the location of the TE_BASE directory by looking for either 1) a system
+ * property or 2) an environment variable named {@value #TE_BASE}. Finally, if neither
+ * is set then the "teamengine" subdirectory is created in the user home directory
+ * (${user.home}/teamengine).
+ * @return A File denoting the location of the base configuration directory.
+ */
+ public static File getBaseConfigDirectory() {
+ if (null != teBaseDir) {
+ return teBaseDir;
+ }
+ String basePath = System.getProperty(TE_BASE);
+ if (null == basePath) {
+ basePath = System.getenv(TE_BASE);
+ }
+ if (null == basePath) {
+ basePath = System.getProperty("user.home") + FileSystems.getDefault().getSeparator() + "teamengine";
+ }
+ File baseDir = new File(basePath);
+ if (!baseDir.isDirectory()) {
+ baseDir.mkdirs();
+ }
+ Logger.getLogger(SetupOptions.class.getName()).log(Level.CONFIG, "Using TE_BASE at " + baseDir);
+ return baseDir;
+ }
+
+ /**
+ * Determine the test recording is on or off.
+ * @param testName
+ * @return boolean
+ * @throws javax.xml.parsers.ParserConfigurationException
+ * @throws org.xml.sax.SAXException
+ * @throws java.io.IOException
+ */
+ public static boolean recordingInfo(String testName)
+ throws ParserConfigurationException, SAXException, IOException {
+ TECore.rootTestName.clear();
+ String path = getBaseConfigDirectory() + "/config.xml";
+ if (new File(path).exists()) {
+ // Fortify Mod: prevent external entity injection
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setExpandEntityReferences(false);
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ // DocumentBuilder db =
+ // DocumentBuilderFactory.newInstance().newDocumentBuilder();
+ Document doc = db.parse(path);
+ NodeList nodeListForStandardTag = doc.getElementsByTagName("standard");
+ if (null != nodeListForStandardTag && nodeListForStandardTag.getLength() > 0) {
+ for (int i = 0; i < nodeListForStandardTag.getLength(); i++) {
+ Element elementStandard = (Element) nodeListForStandardTag.item(i);
+ if (testName.equals(elementStandard.getElementsByTagName("local-name").item(0).getTextContent())) {
+ if (null != elementStandard.getElementsByTagName("record").item(0)) {
+ System.setProperty("Record", "True");
+ NodeList rootTestNameArray = elementStandard.getElementsByTagName("test-name");
+ if (null != rootTestNameArray && rootTestNameArray.getLength() > 0) {
+ for (int counter = 0; counter < rootTestNameArray.getLength(); counter++) {
+ Element rootTestName = (Element) rootTestNameArray.item(counter);
+ TECore.rootTestName.add(rootTestName.getTextContent());
+ }
+ }
+ return true;
+ }
+ }
+
+ }
+ }
+ }
+ System.setProperty("Record", "False");
+ return false;
+ }
+
+ public String getSourcesName() {
+ return sourcesName;
+ }
+
+ public void setSourcesName(String sourcesName) {
+ this.sourcesName = sourcesName;
+ }
+
+ /**
+ * Returns the location of the work directory (TE_BASE/work).
+ * @return A File denoting a directory location; it is created if it does not exist.
+ */
+ public File getWorkDir() {
+ if (null == this.workDir) {
+ File dir = new File(teBaseDir, "work");
+ if (!dir.exists() && !dir.mkdir()) {
+ throw new RuntimeException("Failed to create directory at " + dir.getAbsolutePath());
+ }
+ this.workDir = dir;
+ }
+ return workDir;
+ }
+
+ /**
+ * Returns a list of file system resources (directories and files) containing CTL test
+ * scripts.
+ * @return A List containing one or more File references (TE_BASE/scripts is the
+ * default location).
+ */
+ public List getSources() {
+ return sources;
+ }
+
+ /**
+ * Adds a file system resource to the collection of known scripts.
+ * @param source A File object representing a file or directory.
+ * @deprecated Use {@link SetupOptions#addSourceWithValidation(File source)} instead
+ */
+ @Deprecated
+ public void addSource(File source) {
+ this.sources.add(source);
+ }
+
+ /**
+ * Adds a file system resource to the collection of known scripts. Fortify Mod:
+ * validate the argument and return success or failure
+ * @param source A File object representing a file or directory.
+ */
+ public boolean addSourceWithValidation(File source) {
+ // Fortify Mod: validate that source is on a valid path
+ if (source != null) {
+ TEPath tpath = new TEPath(source.getAbsolutePath());
+ if (tpath.isValid()) {
+ this.sources.add(source);
+ return true;
+ }
+ else {
+ jLogger.log(Level.INFO, "SetupOptions: Attempt to set invalid source " + source);
+ }
+ }
+ return false;
+ }
+
+ public Element getParamsElement() {
+ return null;
+ }
+
+ public boolean isValidate() {
+ return validate;
+ }
+
+ public void setValidate(boolean validate) {
+ this.validate = validate;
+ }
+
+ public boolean isPreload() {
+ return preload;
+ }
+
+ public void setPreload(boolean preload) {
+ this.preload = preload;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/Suite.java b/teamengine-core/src/main/java/com/occamlab/te/Suite.java
index 62c6a838b..61d7013f2 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/Suite.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/Suite.java
@@ -1,122 +1,142 @@
-package com.occamlab.te;
-
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-
-/**
- * Provides metadata about a test suite.
- *
- */
-public class Suite {
-
- private String prefix;
-
- private String namespaceUri;
-
- private String localName;
-
- private String title;
-
- private String description;
-
- private String startingTestPrefix;
-
- private String startingTestNamespaceUri;
-
- private String startingTestLocalName;
-
- private String link;
-
- private String dataLink;
-
- private String version;
-
- public Suite(Element suiteElement) {
- String name = suiteElement.getAttribute("name");
- this.version = suiteElement.getAttribute("version");
-
- int colon = name.indexOf(":");
- prefix = name.substring(0, colon);
- localName = name.substring(colon + 1);
- namespaceUri = suiteElement.lookupNamespaceURI(prefix);
-
- NodeList titleElements = suiteElement.getElementsByTagNameNS(Test.CTL_NS, "title");
- title = ((Element) titleElements.item(0)).getTextContent();
-
- NodeList descElements = suiteElement.getElementsByTagNameNS(Test.CTL_NS, "description");
- if (descElements.getLength() > 0) {
- description = ((Element) descElements.item(0)).getTextContent();
- }
- else {
- description = null;
- }
-
- NodeList linkElements = suiteElement.getElementsByTagNameNS(Test.CTL_NS, "link");
- for (int i = 0; i < linkElements.getLength(); i++) {
- Element linkElem = (Element) linkElements.item(i);
- String linkText = linkElem.getTextContent();
- if (linkText.startsWith("data")) {
- this.dataLink = linkText;
- }
- else {
- this.link = linkText;
- }
- }
-
- NodeList startingTestElements = suiteElement.getElementsByTagNameNS(Test.CTL_NS, "starting-test");
- name = ((Element) startingTestElements.item(0)).getTextContent();
- colon = name.indexOf(":");
- startingTestPrefix = name.substring(0, colon);
- startingTestLocalName = name.substring(colon + 1);
- startingTestNamespaceUri = suiteElement.lookupNamespaceURI(startingTestPrefix);
- }
-
- public String getKey() {
- return namespaceUri + "," + localName;
- }
-
- public String getPrefix() {
- return prefix;
- }
-
- public String getNamespaceUri() {
- return namespaceUri;
- }
-
- public String getLocalName() {
- return localName;
- }
-
- public String getTitle() {
- return title;
- }
-
- public String getDescription() {
- return description;
- }
-
- public String getLink() {
- return this.link;
- }
-
- public String getDataLink() {
- return this.dataLink;
- }
-
- public String getStartingTestPrefix() {
- return startingTestPrefix;
- }
-
- public String getStartingTestNamespaceUri() {
- return startingTestNamespaceUri;
- }
-
- public String getStartingTestLocalName() {
- return startingTestLocalName;
- }
-
- public String getVersion() {
- return this.version;
- }
-
-}
+package com.occamlab.te;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+/**
+ * Provides metadata about a test suite.
+ *
+ */
+public class Suite {
+
+ private String prefix;
+
+ private String namespaceUri;
+
+ private String localName;
+
+ private String title;
+
+ private String description;
+
+ private String startingTestPrefix;
+
+ private String startingTestNamespaceUri;
+
+ private String startingTestLocalName;
+
+ private String link;
+
+ private String dataLink;
+
+ private String version;
+
+ public Suite(Element suiteElement) {
+ String name = suiteElement.getAttribute("name");
+ this.version = suiteElement.getAttribute("version");
+
+ int colon = name.indexOf(":");
+ prefix = name.substring(0, colon);
+ localName = name.substring(colon + 1);
+ namespaceUri = suiteElement.lookupNamespaceURI(prefix);
+
+ NodeList titleElements = suiteElement.getElementsByTagNameNS(Test.CTL_NS, "title");
+ title = ((Element) titleElements.item(0)).getTextContent();
+
+ NodeList descElements = suiteElement.getElementsByTagNameNS(Test.CTL_NS, "description");
+ if (descElements.getLength() > 0) {
+ description = ((Element) descElements.item(0)).getTextContent();
+ }
+ else {
+ description = null;
+ }
+
+ NodeList linkElements = suiteElement.getElementsByTagNameNS(Test.CTL_NS, "link");
+ for (int i = 0; i < linkElements.getLength(); i++) {
+ Element linkElem = (Element) linkElements.item(i);
+ String linkText = linkElem.getTextContent();
+ if (linkText.startsWith("data")) {
+ this.dataLink = linkText;
+ }
+ else {
+ this.link = linkText;
+ }
+ }
+
+ NodeList startingTestElements = suiteElement.getElementsByTagNameNS(Test.CTL_NS, "starting-test");
+ name = ((Element) startingTestElements.item(0)).getTextContent();
+ colon = name.indexOf(":");
+ startingTestPrefix = name.substring(0, colon);
+ startingTestLocalName = name.substring(colon + 1);
+ startingTestNamespaceUri = suiteElement.lookupNamespaceURI(startingTestPrefix);
+ }
+
+ public String getKey() {
+ return namespaceUri + "," + localName;
+ }
+
+ public String getPrefix() {
+ return prefix;
+ }
+
+ public String getNamespaceUri() {
+ return namespaceUri;
+ }
+
+ public String getLocalName() {
+ return localName;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String getLink() {
+ return this.link;
+ }
+
+ public String getDataLink() {
+ return this.dataLink;
+ }
+
+ public String getStartingTestPrefix() {
+ return startingTestPrefix;
+ }
+
+ public String getStartingTestNamespaceUri() {
+ return startingTestNamespaceUri;
+ }
+
+ public String getStartingTestLocalName() {
+ return startingTestLocalName;
+ }
+
+ public String getVersion() {
+ return this.version;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/SwingForm.java b/teamengine-core/src/main/java/com/occamlab/te/SwingForm.java
index ee2b27751..991c96947 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/SwingForm.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/SwingForm.java
@@ -1,290 +1,310 @@
-package com.occamlab.te;
-
-import java.awt.BorderLayout;
-import java.net.URL;
-import java.net.URLDecoder;
-import java.io.File;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Enumeration;
-
-import javax.swing.JEditorPane;
-import javax.swing.JFrame;
-import javax.swing.JPanel;
-import javax.swing.JScrollPane;
-import javax.swing.SwingUtilities;
-import javax.swing.event.HyperlinkEvent;
-import javax.swing.event.HyperlinkListener;
-import javax.swing.text.AttributeSet;
-import javax.swing.text.StyleConstants;
-import javax.swing.text.html.FormView;
-import javax.swing.text.html.HTML;
-import javax.swing.text.html.HTMLDocument;
-import javax.swing.text.html.HTMLEditorKit;
-import javax.swing.text.html.HTMLFrameHyperlinkEvent;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import com.occamlab.te.util.DomUtils;
-
-/**
- * Swing-based form created from the content of a <ctl:form> element. This is
- * produced when not running the test harness in a web application context.
- */
-public class SwingForm extends JFrame implements HyperlinkListener {
-
- static final long serialVersionUID = 7907599307261079944L;
-
- public static final String CTL_NS = "http://www.occamlab.com/ctl";
-
- private static SwingForm mainForm = null;
-
- private static SwingForm popupForm = null;
-
- private static TECore core;
-
- private static String popupName = Thread.currentThread().getName();
-
- private JEditorPane jedit;
-
- private ArrayList fileFields = new ArrayList<>();
-
- private static class Invoker implements Runnable {
-
- String name;
-
- int width;
-
- int height;
-
- public void run() {
- if (mainForm == null) {
- mainForm = new SwingForm(name);
- }
-
- String html = core.getFormHtml();
- core.setFormHtml(null);
- // For some reason, the tag generated by SAXON screws up the
- // JEditorPane, so replace it with a dummy tag.
- int i = html.indexOf(" 0) {
- html = html.substring(0, i + 1) + "blah" + html.substring(i + 5);
- }
-
- mainForm.jedit.setText(html);
- mainForm.setSize(width, height);
- mainForm.validate();
- mainForm.setVisible(true);
- }
-
- }
-
- private class CustomFormView extends FormView {
-
- public CustomFormView(javax.swing.text.Element elem) {
- super(elem);
- }
-
- protected void submitData(String data) {
- if (SwingForm.this == popupForm) {
- return;
- }
-
- // System.out.println("data: "+data);
- try {
- String kvps = data + "&=";
- int start = 0;
- int end = data.length();
-
- DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- Document doc = db.newDocument();
- Element root = doc.createElement("values");
- doc.appendChild(root);
- do {
- String key;
- String value;
-
- int eq = kvps.indexOf("=", start);
- int amp = kvps.indexOf("&", start);
- if (amp > eq) {
- key = kvps.substring(start, eq);
- value = kvps.substring(eq + 1, amp);
- }
- else {
- key = kvps.substring(start, amp);
- value = "";
- }
-
- Element valueElement = doc.createElement("value");
- valueElement.setAttribute("key", key);
- // Special case for file inputs
- if (fileFields.contains(key)) {
- File f = new File(URLDecoder.decode(value, StandardCharsets.UTF_8));
- if (f != null) {
- if (core.formParsers.containsKey(key)) {
- Element parser = core.formParsers.get(key);
- URL url = f.toURI().toURL();
- Element response = core.parse(url.openConnection(), parser, doc);
- Element content = DomUtils.getElementByTagName(response, "content");
- if (content != null) {
- Element child = DomUtils.getChildElement(content);
- if (child != null) {
- valueElement.appendChild(child);
- }
- }
- }
- else {
- // value = Core.saveFileToWorkingDir(value); //
- // What does copying the file to a new dir
- // accomplish?
- Element fileEntry = doc.createElementNS(CTL_NS, "file-entry");
- fileEntry.setAttribute("full-path",
- URLDecoder.decode(value, StandardCharsets.UTF_8).replace('\\', '/'));
- valueElement.appendChild(fileEntry);
- }
- }
- }
- else {
- valueElement.appendChild(doc.createTextNode(URLDecoder.decode(value, StandardCharsets.UTF_8)));
- }
- root.appendChild(valueElement);
- start = amp + 1;
- // System.out.println("key|value: "+key+"|"+value);
- }
- while (start < end);
-
- core.setFormResults(doc);
- if (popupForm != null) {
- popupForm.setVisible(false);
- }
- }
- catch (Throwable t) {
- t.printStackTrace(System.out);
- }
- mainForm.setVisible(false);
- }
-
- }
-
- private class CustomViewFactory extends HTMLEditorKit.HTMLFactory {
-
- public javax.swing.text.View create(javax.swing.text.Element elem) {
- AttributeSet as = elem.getAttributes();
- HTML.Tag tag = (HTML.Tag) (as.getAttribute(StyleConstants.NameAttribute));
-
- if (tag == HTML.Tag.INPUT) {
- String type = "";
- String name = "";
- Enumeration e = as.getAttributeNames();
- while (e.hasMoreElements()) {
- Object key = e.nextElement();
- if (key == HTML.Attribute.TYPE) {
- type = as.getAttribute(key).toString();
- }
- if (key == HTML.Attribute.NAME) {
- name = as.getAttribute(key).toString();
- }
- }
-
- if (type.equalsIgnoreCase("submit")) {
- return new CustomFormView(elem);
- }
-
- if (type.equalsIgnoreCase("file")) {
- fileFields.add(name);
- }
- }
-
- return super.create(elem);
- }
-
- }
-
- private class CustomHTMLEditorKit extends HTMLEditorKit {
-
- static final long serialVersionUID = 5742710765916499050L;
-
- public javax.swing.text.ViewFactory getViewFactory() {
- return new CustomViewFactory();
- }
-
- }
-
- private SwingForm(String name) {
- setTitle(name);
- // setBackground(Color.gray);
- getContentPane().setLayout(new BorderLayout());
-
- JPanel topPanel = new JPanel();
- topPanel.setLayout(new BorderLayout());
- getContentPane().add(topPanel, BorderLayout.CENTER);
-
- jedit = new JEditorPane();
- jedit.setEditorKit(new CustomHTMLEditorKit());
- jedit.setEditable(false);
- jedit.addHyperlinkListener(this);
-
- JScrollPane scrollPane = new JScrollPane();
- scrollPane.getViewport().add(jedit, BorderLayout.CENTER);
- topPanel.add(scrollPane, BorderLayout.CENTER);
- }
-
- public void hyperlinkUpdate(HyperlinkEvent e) {
- if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
- JEditorPane pane = (JEditorPane) e.getSource();
- if (e instanceof HTMLFrameHyperlinkEvent) {
- HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e;
- HTMLDocument doc = (HTMLDocument) pane.getDocument();
- doc.processHTMLFrameHyperlinkEvent(evt);
- }
- else {
- try {
- URL target = e.getURL();
- if (target == null) {
- target = new URL(new URL(core.opts.getBaseURI()), e.getDescription());
- }
- if (this == popupForm) {
- pane.setPage(target);
- }
- else {
- if (popupForm == null) {
- popupForm = new SwingForm(popupName);
- popupForm.setSize(700, 500);
- popupForm.setLocation(this.getX() + 30, this.getY() + 30);
- }
- popupForm.jedit.setPage(target);
- popupForm.setVisible(true);
- }
- }
- catch (Throwable t) {
- t.printStackTrace();
- }
- }
- }
- }
-
- public static void create(String name, int width, int height, TECore core) {
- Invoker invoker = new Invoker();
- invoker.name = name;
- invoker.width = width;
- invoker.height = height;
- SwingForm.core = core;
- SwingUtilities.invokeLater(invoker);
- }
-
- public static void destroy() {
- if (popupForm != null) {
- popupForm.dispose();
- popupForm = null;
- }
- if (mainForm != null) {
- mainForm.dispose();
- mainForm = null;
- }
- }
-
-}
+package com.occamlab.te;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.awt.BorderLayout;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Enumeration;
+
+import javax.swing.JEditorPane;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.SwingUtilities;
+import javax.swing.event.HyperlinkEvent;
+import javax.swing.event.HyperlinkListener;
+import javax.swing.text.AttributeSet;
+import javax.swing.text.StyleConstants;
+import javax.swing.text.html.FormView;
+import javax.swing.text.html.HTML;
+import javax.swing.text.html.HTMLDocument;
+import javax.swing.text.html.HTMLEditorKit;
+import javax.swing.text.html.HTMLFrameHyperlinkEvent;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import com.occamlab.te.util.DomUtils;
+
+/**
+ * Swing-based form created from the content of a <ctl:form> element. This is
+ * produced when not running the test harness in a web application context.
+ */
+public class SwingForm extends JFrame implements HyperlinkListener {
+
+ static final long serialVersionUID = 7907599307261079944L;
+
+ public static final String CTL_NS = "http://www.occamlab.com/ctl";
+
+ private static SwingForm mainForm = null;
+
+ private static SwingForm popupForm = null;
+
+ private static TECore core;
+
+ private static String popupName = Thread.currentThread().getName();
+
+ private JEditorPane jedit;
+
+ private ArrayList fileFields = new ArrayList<>();
+
+ private static class Invoker implements Runnable {
+
+ String name;
+
+ int width;
+
+ int height;
+
+ public void run() {
+ if (mainForm == null) {
+ mainForm = new SwingForm(name);
+ }
+
+ String html = core.getFormHtml();
+ core.setFormHtml(null);
+ // For some reason, the tag generated by SAXON screws up the
+ // JEditorPane, so replace it with a dummy tag.
+ int i = html.indexOf(" 0) {
+ html = html.substring(0, i + 1) + "blah" + html.substring(i + 5);
+ }
+
+ mainForm.jedit.setText(html);
+ mainForm.setSize(width, height);
+ mainForm.validate();
+ mainForm.setVisible(true);
+ }
+
+ }
+
+ private class CustomFormView extends FormView {
+
+ public CustomFormView(javax.swing.text.Element elem) {
+ super(elem);
+ }
+
+ protected void submitData(String data) {
+ if (SwingForm.this == popupForm) {
+ return;
+ }
+
+ // System.out.println("data: "+data);
+ try {
+ String kvps = data + "&=";
+ int start = 0;
+ int end = data.length();
+
+ DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+ Document doc = db.newDocument();
+ Element root = doc.createElement("values");
+ doc.appendChild(root);
+ do {
+ String key;
+ String value;
+
+ int eq = kvps.indexOf("=", start);
+ int amp = kvps.indexOf("&", start);
+ if (amp > eq) {
+ key = kvps.substring(start, eq);
+ value = kvps.substring(eq + 1, amp);
+ }
+ else {
+ key = kvps.substring(start, amp);
+ value = "";
+ }
+
+ Element valueElement = doc.createElement("value");
+ valueElement.setAttribute("key", key);
+ // Special case for file inputs
+ if (fileFields.contains(key)) {
+ File f = new File(URLDecoder.decode(value, StandardCharsets.UTF_8));
+ if (f != null) {
+ if (core.formParsers.containsKey(key)) {
+ Element parser = core.formParsers.get(key);
+ URL url = f.toURI().toURL();
+ Element response = core.parse(url.openConnection(), parser, doc);
+ Element content = DomUtils.getElementByTagName(response, "content");
+ if (content != null) {
+ Element child = DomUtils.getChildElement(content);
+ if (child != null) {
+ valueElement.appendChild(child);
+ }
+ }
+ }
+ else {
+ // value = Core.saveFileToWorkingDir(value); //
+ // What does copying the file to a new dir
+ // accomplish?
+ Element fileEntry = doc.createElementNS(CTL_NS, "file-entry");
+ fileEntry.setAttribute("full-path",
+ URLDecoder.decode(value, StandardCharsets.UTF_8).replace('\\', '/'));
+ valueElement.appendChild(fileEntry);
+ }
+ }
+ }
+ else {
+ valueElement.appendChild(doc.createTextNode(URLDecoder.decode(value, StandardCharsets.UTF_8)));
+ }
+ root.appendChild(valueElement);
+ start = amp + 1;
+ // System.out.println("key|value: "+key+"|"+value);
+ }
+ while (start < end);
+
+ core.setFormResults(doc);
+ if (popupForm != null) {
+ popupForm.setVisible(false);
+ }
+ }
+ catch (Throwable t) {
+ t.printStackTrace(System.out);
+ }
+ mainForm.setVisible(false);
+ }
+
+ }
+
+ private class CustomViewFactory extends HTMLEditorKit.HTMLFactory {
+
+ public javax.swing.text.View create(javax.swing.text.Element elem) {
+ AttributeSet as = elem.getAttributes();
+ HTML.Tag tag = (HTML.Tag) (as.getAttribute(StyleConstants.NameAttribute));
+
+ if (tag == HTML.Tag.INPUT) {
+ String type = "";
+ String name = "";
+ Enumeration e = as.getAttributeNames();
+ while (e.hasMoreElements()) {
+ Object key = e.nextElement();
+ if (key == HTML.Attribute.TYPE) {
+ type = as.getAttribute(key).toString();
+ }
+ if (key == HTML.Attribute.NAME) {
+ name = as.getAttribute(key).toString();
+ }
+ }
+
+ if (type.equalsIgnoreCase("submit")) {
+ return new CustomFormView(elem);
+ }
+
+ if (type.equalsIgnoreCase("file")) {
+ fileFields.add(name);
+ }
+ }
+
+ return super.create(elem);
+ }
+
+ }
+
+ private class CustomHTMLEditorKit extends HTMLEditorKit {
+
+ static final long serialVersionUID = 5742710765916499050L;
+
+ public javax.swing.text.ViewFactory getViewFactory() {
+ return new CustomViewFactory();
+ }
+
+ }
+
+ private SwingForm(String name) {
+ setTitle(name);
+ // setBackground(Color.gray);
+ getContentPane().setLayout(new BorderLayout());
+
+ JPanel topPanel = new JPanel();
+ topPanel.setLayout(new BorderLayout());
+ getContentPane().add(topPanel, BorderLayout.CENTER);
+
+ jedit = new JEditorPane();
+ jedit.setEditorKit(new CustomHTMLEditorKit());
+ jedit.setEditable(false);
+ jedit.addHyperlinkListener(this);
+
+ JScrollPane scrollPane = new JScrollPane();
+ scrollPane.getViewport().add(jedit, BorderLayout.CENTER);
+ topPanel.add(scrollPane, BorderLayout.CENTER);
+ }
+
+ public void hyperlinkUpdate(HyperlinkEvent e) {
+ if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
+ JEditorPane pane = (JEditorPane) e.getSource();
+ if (e instanceof HTMLFrameHyperlinkEvent) {
+ HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e;
+ HTMLDocument doc = (HTMLDocument) pane.getDocument();
+ doc.processHTMLFrameHyperlinkEvent(evt);
+ }
+ else {
+ try {
+ URL target = e.getURL();
+ if (target == null) {
+ target = new URL(new URL(core.opts.getBaseURI()), e.getDescription());
+ }
+ if (this == popupForm) {
+ pane.setPage(target);
+ }
+ else {
+ if (popupForm == null) {
+ popupForm = new SwingForm(popupName);
+ popupForm.setSize(700, 500);
+ popupForm.setLocation(this.getX() + 30, this.getY() + 30);
+ }
+ popupForm.jedit.setPage(target);
+ popupForm.setVisible(true);
+ }
+ }
+ catch (Throwable t) {
+ t.printStackTrace();
+ }
+ }
+ }
+ }
+
+ public static void create(String name, int width, int height, TECore core) {
+ Invoker invoker = new Invoker();
+ invoker.name = name;
+ invoker.width = width;
+ invoker.height = height;
+ SwingForm.core = core;
+ SwingUtilities.invokeLater(invoker);
+ }
+
+ public static void destroy() {
+ if (popupForm != null) {
+ popupForm.dispose();
+ popupForm = null;
+ }
+ if (mainForm != null) {
+ mainForm.dispose();
+ mainForm = null;
+ }
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/TEClassLoader.java b/teamengine-core/src/main/java/com/occamlab/te/TEClassLoader.java
index abde13e39..69b4bdc28 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/TEClassLoader.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/TEClassLoader.java
@@ -1,162 +1,182 @@
-/****************************************************************************
-
- The Original Code is TEAM Engine.
-
- The Initial Developer of the Original Code is Northrop Grumman Corporation
- jointly with The National Technology Alliance. Portions created by
- Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
- Grumman Corporation. All Rights Reserved.
-
- Contributor(s): No additional contributors to date
-
- ****************************************************************************/
-package com.occamlab.te;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Vector;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-public class TEClassLoader extends ClassLoader {
-
- List resourcesDirs;
-
- ClassLoader cl;
-
- HashSet registeredClasses;
-
- private static Logger logger = Logger.getLogger("com.occamlab.te.TEClassLoader");
-
- private static List resourcesDirsList(File resourcesDir) {
- List resourcesDirs = new ArrayList<>();
- if (resourcesDir != null) {
- resourcesDirs.add(resourcesDir);
- }
- return resourcesDirs;
- }
-
- public TEClassLoader() {
- this(resourcesDirsList(null));
- }
-
- public TEClassLoader(File resourcesDir) {
- this(resourcesDirsList(resourcesDir));
- }
-
- public TEClassLoader(List resourcesDirs) {
- this.resourcesDirs = resourcesDirs;
- cl = Thread.currentThread().getContextClassLoader();
- registeredClasses = new HashSet<>();
- registeredClasses.add("com.occamlab.te.parsers.HTTPParser");
- registeredClasses.add("com.occamlab.te.parsers.SchematronValidatingParser");
- registeredClasses.add("com.occamlab.te.parsers.XMLValidatingParser");
- registeredClasses.add("com.occamlab.te.parsers.XSLTransformationParser");
- }
-
- public URL getResource(String name) {
- for (File resourcesDir : resourcesDirs) {
- File f = new File(resourcesDir, name);
- try {
- return f.toURI().toURL();
- }
- catch (MalformedURLException e) {
- logger.log(Level.SEVERE, "getResource", e);
- }
- }
- return cl.getResource(name);
- }
-
- public InputStream getResourceAsStream(String name) {
- if (resourcesDirs.size() > 0) {
- URL u = getResource(name);
- if (u != null) {
- try {
- return u.openStream();
- }
- catch (IOException e) {
- }
- }
- }
- return cl.getResourceAsStream(name);
- }
-
- public Enumeration getResources(String name) throws IOException {
- Enumeration resources = cl.getResources(name);
- URL u = getResource(name);
- if (resourcesDirs.size() > 0 && u != null) {
- Vector v = new Vector<>();
- v.add(u);
- while (resources.hasMoreElements()) {
- v.add(resources.nextElement());
- }
- return v.elements();
- }
- return resources;
- }
-
- // public void registerClass(String name) {
- // if (!registeredClasses.contains(name)) {
- // registeredClasses.add(name);
- // }
- // }
-
- private Class> readClass(String name) {
- String filename = name.replace('.', '/') + ".class";
- try {
- InputStream in = getResourceAsStream(filename);
- ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
- int i = in.read();
- while (i >= 0) {
- baos.write(i);
- i = in.read();
- }
- in.close();
- return defineClass(name, baos.toByteArray(), 0, baos.size());
- }
- catch (Exception e) {
- logger.log(Level.SEVERE, "readClass", e);
- return null;
- }
- }
-
- public Class> loadClass(String name, boolean resolve) throws ClassNotFoundException {
- Class> c = findLoadedClass(name);
- if (c == null) {
- for (String registeredClass : registeredClasses) {
- if (name.startsWith(registeredClass)) {
- c = readClass(name);
- break;
- }
- }
- }
- if (c == null) {
- try {
- c = cl.loadClass(name);
- }
- catch (ClassNotFoundException e) {
- }
- }
- if (c == null) {
- c = readClass(name);
- }
- if (c == null) {
- throw new ClassNotFoundException(name);
- }
- else {
- if (resolve) {
- resolveClass(c);
- }
- return c;
- }
- }
-
-}
+/****************************************************************************
+
+ The Original Code is TEAM Engine.
+
+ The Initial Developer of the Original Code is Northrop Grumman Corporation
+ jointly with The National Technology Alliance. Portions created by
+ Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
+ Grumman Corporation. All Rights Reserved.
+
+ Contributor(s): No additional contributors to date
+
+ ****************************************************************************/
+package com.occamlab.te;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Vector;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class TEClassLoader extends ClassLoader {
+
+ List resourcesDirs;
+
+ ClassLoader cl;
+
+ HashSet registeredClasses;
+
+ private static Logger logger = Logger.getLogger("com.occamlab.te.TEClassLoader");
+
+ private static List resourcesDirsList(File resourcesDir) {
+ List resourcesDirs = new ArrayList<>();
+ if (resourcesDir != null) {
+ resourcesDirs.add(resourcesDir);
+ }
+ return resourcesDirs;
+ }
+
+ public TEClassLoader() {
+ this(resourcesDirsList(null));
+ }
+
+ public TEClassLoader(File resourcesDir) {
+ this(resourcesDirsList(resourcesDir));
+ }
+
+ public TEClassLoader(List resourcesDirs) {
+ this.resourcesDirs = resourcesDirs;
+ cl = Thread.currentThread().getContextClassLoader();
+ registeredClasses = new HashSet<>();
+ registeredClasses.add("com.occamlab.te.parsers.HTTPParser");
+ registeredClasses.add("com.occamlab.te.parsers.SchematronValidatingParser");
+ registeredClasses.add("com.occamlab.te.parsers.XMLValidatingParser");
+ registeredClasses.add("com.occamlab.te.parsers.XSLTransformationParser");
+ }
+
+ public URL getResource(String name) {
+ for (File resourcesDir : resourcesDirs) {
+ File f = new File(resourcesDir, name);
+ try {
+ return f.toURI().toURL();
+ }
+ catch (MalformedURLException e) {
+ logger.log(Level.SEVERE, "getResource", e);
+ }
+ }
+ return cl.getResource(name);
+ }
+
+ public InputStream getResourceAsStream(String name) {
+ if (resourcesDirs.size() > 0) {
+ URL u = getResource(name);
+ if (u != null) {
+ try {
+ return u.openStream();
+ }
+ catch (IOException e) {
+ }
+ }
+ }
+ return cl.getResourceAsStream(name);
+ }
+
+ public Enumeration getResources(String name) throws IOException {
+ Enumeration resources = cl.getResources(name);
+ URL u = getResource(name);
+ if (resourcesDirs.size() > 0 && u != null) {
+ Vector v = new Vector<>();
+ v.add(u);
+ while (resources.hasMoreElements()) {
+ v.add(resources.nextElement());
+ }
+ return v.elements();
+ }
+ return resources;
+ }
+
+ // public void registerClass(String name) {
+ // if (!registeredClasses.contains(name)) {
+ // registeredClasses.add(name);
+ // }
+ // }
+
+ private Class> readClass(String name) {
+ String filename = name.replace('.', '/') + ".class";
+ try {
+ InputStream in = getResourceAsStream(filename);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
+ int i = in.read();
+ while (i >= 0) {
+ baos.write(i);
+ i = in.read();
+ }
+ in.close();
+ return defineClass(name, baos.toByteArray(), 0, baos.size());
+ }
+ catch (Exception e) {
+ logger.log(Level.SEVERE, "readClass", e);
+ return null;
+ }
+ }
+
+ public Class> loadClass(String name, boolean resolve) throws ClassNotFoundException {
+ Class> c = findLoadedClass(name);
+ if (c == null) {
+ for (String registeredClass : registeredClasses) {
+ if (name.startsWith(registeredClass)) {
+ c = readClass(name);
+ break;
+ }
+ }
+ }
+ if (c == null) {
+ try {
+ c = cl.loadClass(name);
+ }
+ catch (ClassNotFoundException e) {
+ }
+ }
+ if (c == null) {
+ c = readClass(name);
+ }
+ if (c == null) {
+ throw new ClassNotFoundException(name);
+ }
+ else {
+ if (resolve) {
+ resolveClass(c);
+ }
+ return c;
+ }
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/TECore.java b/teamengine-core/src/main/java/com/occamlab/te/TECore.java
index 42af6c1be..607919f0c 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/TECore.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/TECore.java
@@ -1,2592 +1,2612 @@
-/**
- * **************************************************************************
- *
- * The Original Code is TEAM Engine.
- *
- * The Initial Developer of the Original Code is Northrop Grumman Corporation
- * jointly with The National Technology Alliance. Portions created by Northrop
- * Grumman Corporation are Copyright (C) 2005-2006, Northrop Grumman
- * Corporation. All Rights Reserved.
- *
- * Contributor(s):
- * S. Gianfranceschi (Intecs): Added the SOAP suport
- * C. Heazel (WiSC): Added Fortify adjudication changes
- *
- ***************************************************************************
- */
-package com.occamlab.te;
-
-import java.io.BufferedWriter;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.PrintStream;
-import java.io.PrintWriter;
-import java.io.RandomAccessFile;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.lang.reflect.Method;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.net.URLConnection;
-import java.nio.charset.StandardCharsets;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Stack;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import java.util.zip.CRC32;
-
-import javax.xml.XMLConstants;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMResult;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-import javax.xml.transform.stream.StreamSource;
-
-import com.occamlab.te.form.ImageHandler;
-import com.occamlab.te.html.EarlToHtmlTransformation;
-
-import net.sf.saxon.dom.NodeOverNodeInfo;
-import net.sf.saxon.expr.XPathContext;
-import net.sf.saxon.expr.XPathContextMajor;
-import net.sf.saxon.instruct.Executable;
-import net.sf.saxon.om.NodeInfo;
-import net.sf.saxon.s9api.Axis;
-import net.sf.saxon.s9api.QName;
-import net.sf.saxon.s9api.S9APIUtils;
-import net.sf.saxon.s9api.SaxonApiException;
-import net.sf.saxon.s9api.Serializer;
-import net.sf.saxon.s9api.XdmAtomicValue;
-import net.sf.saxon.s9api.XdmDestination;
-import net.sf.saxon.s9api.XdmItem;
-import net.sf.saxon.s9api.XdmNode;
-import net.sf.saxon.s9api.XdmNodeKind;
-import net.sf.saxon.s9api.XdmSequenceIterator;
-import net.sf.saxon.s9api.XsltExecutable;
-import net.sf.saxon.s9api.XsltTransformer;
-import net.sf.saxon.trans.XPathException;
-
-import org.w3c.dom.Attr;
-import org.w3c.dom.Comment;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.Text;
-
-import com.occamlab.te.index.FunctionEntry;
-import com.occamlab.te.index.Index;
-import com.occamlab.te.index.ParserEntry;
-import com.occamlab.te.index.ProfileEntry;
-import com.occamlab.te.index.SuiteEntry;
-import com.occamlab.te.index.TemplateEntry;
-import com.occamlab.te.index.TestEntry;
-import com.occamlab.te.saxon.ObjValue;
-import com.occamlab.te.util.Constants;
-import com.occamlab.te.util.DomUtils;
-import com.occamlab.te.util.IOUtils;
-import com.occamlab.te.util.LogUtils;
-import com.occamlab.te.util.Misc;
-import com.occamlab.te.util.SoapUtils;
-import com.occamlab.te.util.StringUtils;
-import com.occamlab.te.util.URLConnectionUtils;
-import com.occamlab.te.util.TEPath;
-
-import static java.util.logging.Level.FINE;
-import static java.util.logging.Level.SEVERE;
-
-/**
- * Provides various utility methods to support test execution and logging. Primary ones
- * include implementation and execution of ctl:suite, ctl:profile, ctl:test, ctl:function,
- * ctl:request and ctl:soap-request instructions, and invocation of any parsers specified
- * therein.
- *
- */
-public class TECore implements Runnable {
-
- private static final Logger LOGR = Logger.getLogger(TECore.class.getName());
-
- public static final String SOAP_V_1_1 = "1.1";
-
- public static final String SOAP_V_1_2 = "1.2";
-
- Engine engine; // Engine object
-
- Index index;
-
- public static int testCount = 0;
-
- int reTestCount = 0;
-
- public static int methodCount = 0;
-
- String testName = "";
-
- public static String nameOfTest = "";
-
- final RuntimeOptions opts;
-
- String testServletURL = null;
-
- volatile PrintStream out; // Console destination
-
- boolean web = false; // True when running as a servlet
-
- RecordedForms recordedForms;
-
- private String testPath; // Uniquely identifies a test instance
-
- String fnPath = ""; // Uniquely identifies an XSL function instance within a
-
- // test instance
- String indent = ""; // Contains the appropriate number of spaces for the
-
- // current indent level
- String contextLabel = ""; // Current context label set by ctl:for-each
-
- String testType = "Mandatory"; // Type of current test
-
- String defaultResultName = "Pass"; // Default result name for current test
-
- int defaultResult = PASS; // Default result for current test
-
- ArrayList media = new ArrayList<>();
-
- public File dirPath;
-
- Document prevLog = null; // Log document for current test from previous test
-
- // execution (resume and retest modes only)
- // Log document for suite to enable use of getLogCache by profile test
- Document suiteLog = null;
-
- public static String pathURL = "";
-
- public static String assertionMsz = "";
-
- public static String messageTest = "";
-
- PrintWriter logger = null; // Logger for current test
-
- volatile String formHtml; // HTML representation for an active form
-
- volatile Document formResults; // Holds form results until they are
-
- // retrieved
- Map formParsers = new HashMap<>();
-
- Map functionInstances = new HashMap<>();
-
- Map parserInstances = new HashMap<>();
-
- Map parserMethods = new HashMap<>();
-
- LinkedList testStack = new LinkedList<>();
-
- volatile boolean threadComplete = false;
-
- volatile boolean stop = false;
-
- volatile ByteArrayOutputStream threadOutput;
-
- private Stack fnCallStack;
-
- public static final int CONTINUE = -1;
-
- public static final int BEST_PRACTICE = 0;
-
- public static final int PASS = 1;
-
- public static final int NOT_TESTED = 2;
-
- public static final int SKIPPED = 3;
-
- public static final int WARNING = 4;
-
- public static final int INHERITED_FAILURE = 5;
-
- public static final int FAIL = 6;
-
- public static final String MSG_CONTINUE = "Inconclusive! Continue Test";
-
- public static final String MSG_BEST_PRACTICE = "Passed as Best Practice";
-
- public static final String MSG_PASS = "Passed";
-
- public static final String MSG_NOT_TESTED = "Not Tested";
-
- public static final String MSG_SKIPPED = "Skipped - Prerequisites not satisfied";
-
- public static final String MSG_WARNING = "Warning";
-
- public static final String MSG_INHERITED_FAILURE = "Failed - Inherited";
-
- public static final String MSG_FAIL = "Failed";
-
- public static final int MANDATORY = 0;
-
- public static final int MANDATORY_IF_IMPLEMENTED = 1;
-
- public static final int OPTIONAL = 2;
-
- static final String XSL_NS = Test.XSL_NS;
- static final String CTL_NS = Test.CTL_NS;
- static final String TE_NS = Test.TE_NS;
- static final String INDENT = " ";
- static final QName TECORE_QNAME = new QName("te", TE_NS, "core");
- static final QName TEPARAMS_QNAME = new QName("te", TE_NS, "params");
- static final QName LOCALNAME_QNAME = new QName("local-name");
- static final QName LABEL_QNAME = new QName("label");
- static final String HEADER_BLOCKS = "header-blocks";
-
- private static Logger jlogger = Logger.getLogger("com.occamlab.te.TECore");
-
- public static DocumentBuilderFactory icFactory;
-
- public static DocumentBuilder icBuilder;
-
- public static Document doc;
-
- public static Element mainRootElement;
-
- public static DocumentBuilderFactory icFactoryClause;
-
- public static DocumentBuilder icBuilderClause;
-
- public static Document docClause;
-
- public static Element mainRootElementClause;
-
- public static String TESTNAME = "";
-
- public static int rootNo = 0;
-
- public static String Clause = "";
-
- public static String Purpose = "";
-
- public static ArrayList rootTestName = new ArrayList<>();
-
- public Document userInputs = null;
-
- public Boolean supportHtmlReport = false;
-
- public final ImageHandler imageHandler;
-
- public TECore() {
- this.opts = null;
- this.imageHandler = null;
- }
-
- public TECore(Engine engine, Index index, RuntimeOptions opts) {
- this.engine = engine;
- this.index = index;
- this.opts = opts;
- this.recordedForms = new RecordedForms(opts.getRecordedForms());
- this.testPath = opts.getSessionId();
- this.out = System.out;
- this.imageHandler = new ImageHandler(opts.getLogDir(), opts.getSessionId());
- this.fnCallStack = new Stack<>();
- }
-
- public TestEntry getParentTest() {
- if (testStack.size() < 2) {
- return testStack.peek();
- }
- else {
- return testStack.get(1);
- }
- }
-
- public String getParamsXML(List params) throws Exception {
- String paramsXML = "";
- for (int i = 0; i < params.size(); i++) {
- String param = params.get(i);
- String name = param.substring(0, param.indexOf('='));
- String value = param.substring(param.indexOf('=') + 1);
- if (params.get(i).indexOf('=') != 0) {
- paramsXML += " ";
- paramsXML += " ";
- paramsXML += "";
- }
- }
- paramsXML += " ";
- // System.out.println("paramsXML: "+paramsXML);
- return paramsXML;
- }
-
- XPathContext getXPathContext(TestEntry test, String sourcesName, XdmNode contextNode) throws Exception {
- XPathContext context = null;
- if (test.usesContext() && contextNode != null) {
- XsltExecutable xe = engine.loadExecutable(test, sourcesName);
- Executable ex = xe.getUnderlyingCompiledStylesheet().getExecutable();
- context = new XPathContextMajor(contextNode.getUnderlyingNode(), ex);
- }
- return context;
- }
-
- // Execute tests
- public void execute() throws Exception {
- try {
- TestEntry grandParent = new TestEntry();
- grandParent.setType("Mandatory");
- grandParent.setResult(CONTINUE);
- testStack.push(grandParent);
- String sessionId = opts.getSessionId();
- int mode = opts.getMode();
- ArrayList params = opts.getParams();
-
- if (mode == Test.RESUME_MODE) {
- reexecute_test(sessionId);
- }
- else if (mode == Test.REDO_FROM_CACHE_MODE) {
- reexecute_test(sessionId);
- }
- else if (mode == Test.RETEST_MODE) {
- for (String testPath : opts.getTestPaths()) {
- reexecute_test(testPath);
- }
- }
- else if (mode == Test.TEST_MODE || mode == Test.DOC_MODE) {
- String testName = opts.getTestName();
- if (!testName.isEmpty()) {
- // NOTE: getContextNode() always returns null
- XdmNode contextNode = opts.getContextNode();
- execute_test(testName, params, contextNode);
- }
- else {
- String suiteName = opts.getSuiteName();
- List profiles = opts.getProfiles();
- if (!suiteName.isEmpty() || profiles.size() == 0) {
- execute_suite(suiteName, params);
- }
- if (profiles.contains("*")) {
- for (String profile : index.getProfileKeys()) {
- try {
- execute_profile(profile, params, false);
- }
- catch (Exception e) {
- jlogger.log(Level.WARNING, e.getMessage(), e.getCause());
- }
- }
- }
- else {
- for (String profile : profiles) {
- try {
- execute_profile(profile, params, true);
- }
- catch (Exception e) {
- jlogger.log(Level.WARNING, e.getMessage(), e.getCause());
- }
- }
- }
- }
- }
- else {
- throw new Exception("Unsupported mode");
- }
- }
- finally {
- if (!web) {
- SwingForm.destroy();
- }
- if (opts.getLogDir() != null) {
- // Create xml execution report file
- LogUtils.createFullReportLog(opts.getLogDir().getAbsolutePath() + File.separator + opts.getSessionId());
- File resultsDir = new File(opts.getLogDir(), opts.getSessionId());
- if (supportHtmlReport) {
- Map testInputMap = new HashMap<>();
- testInputMap = extractTestInputs(userInputs, opts);
-
- if (!new File(resultsDir, "testng").exists() && null != testInputMap) {
- /*
- * Transform CTL result into EARL result, when the CTL test is
- * executed through the webapp.
- */
- try {
-
- File testLog = new File(resultsDir, "report_logs.xml");
- CtlEarlReporter report = new CtlEarlReporter();
-
- if (null != opts.getSourcesName()) {
- report.generateEarlReport(resultsDir, testLog, opts.getSourcesName(), testInputMap);
- }
- }
- catch (IOException iox) {
- throw new RuntimeException("Failed to serialize EARL results to " + iox);
- }
- }
- }
- }
- }
- }
-
- public void reexecute_test(String testPath) throws Exception {
- File deleteExistingResultDir = new File(
- opts.getLogDir() + File.separator + testPath + File.separator + "result");
- if (deleteExistingResultDir.exists()) {
- Misc.deleteDir(deleteExistingResultDir);
- }
- File deleteExistingTestngDir = new File(
- opts.getLogDir() + File.separator + testPath + File.separator + "testng");
- if (deleteExistingTestngDir.exists()) {
- Misc.deleteDir(deleteExistingTestngDir);
- }
- Document log = LogUtils.readLog(opts.getLogDir(), testPath);
- String testId = LogUtils.getTestIdFromLog(log);
- TestEntry test = index.getTest(testId);
- net.sf.saxon.s9api.DocumentBuilder builder = engine.getBuilder();
- XdmNode paramsNode = LogUtils.getParamsFromLog(builder, log);
- XdmNode contextNode = LogUtils.getContextFromLog(builder, log);
- XPathContext context = getXPathContext(test, opts.getSourcesName(), contextNode);
- setTestPath(testPath);
- executeTest(test, paramsNode, context);
- if (testPath.equals(opts.getSessionId())) {
- // Profile not executed in retest mode
- suiteLog = LogUtils.readLog(opts.getLogDir(), testPath);
- ArrayList params = opts.getParams();
- List profiles = opts.getProfiles();
- if (profiles.contains("*")) {
- for (String profile : index.getProfileKeys()) {
- try {
- execute_profile(profile, params, false);
- }
- catch (Exception e) {
- jlogger.log(Level.WARNING, e.getMessage(), e.getCause());
- }
- }
- }
- else {
- for (String profile : profiles) {
- try { // 2011-12-21 PwD
- execute_profile(profile, params, true);
- }
- catch (Exception e) {
- jlogger.log(Level.WARNING, e.getMessage(), e.getCause());
- }
- }
- }
- }
- }
-
- public int execute_test(String testName, List params, XdmNode contextNode) throws Exception {
- if (LOGR.isLoggable(FINE)) {
- String logMsg = String.format("Preparing test %s for execution, using params:%n %s", testName, params);
- LOGR.fine(logMsg);
- }
- TestEntry test = index.getTest(testName);
- if (test == null) {
- throw new Exception("Error: Test " + testName + " not found.");
- }
- XdmNode paramsNode = engine.getBuilder().build(new StreamSource(new StringReader(getParamsXML(params))));
- if (contextNode == null && test.usesContext()) {
- String contextNodeXML = "" + test.getContext() + " ";
- contextNode = engine.getBuilder().build(new StreamSource(new StringReader(contextNodeXML)));
- }
- XPathContext context = getXPathContext(test, opts.getSourcesName(), contextNode);
- return executeTest(test, paramsNode, context);
- }
-
- public void execute_suite(String suiteName, List params) throws Exception {
- SuiteEntry suite = null;
- if (suiteName == null || suiteName.isEmpty()) {
- Iterator it = index.getSuiteKeys().iterator();
- if (!it.hasNext()) {
- throw new Exception("Error: No suites in sources.");
- }
- suite = index.getSuite(it.next());
- if (it.hasNext()) {
- throw new Exception(
- "Error: Suite name must be specified since there is more than one suite in sources.");
- }
- }
- else {
- suite = index.getSuite(suiteName);
- if (suite == null) {
- throw new Exception("Error: Suite " + suiteName + " not found.");
- }
- }
- defaultResultName = suite.getDefaultResult();
- defaultResult = defaultResultName.equals("BestPractice") ? BEST_PRACTICE : PASS;
- testStack.peek().setDefaultResult(defaultResult);
- testStack.peek().setResult(defaultResult);
-
- ArrayList kvps = new ArrayList<>(params);
- Document form = suite.getForm();
- if (form != null) {
- Document results = (Document) form(form, suite.getId());
- for (Element value : DomUtils.getElementsByTagName(results, "value")) {
- kvps.add(value.getAttribute("key") + "=" + value.getTextContent());
- }
- }
- String name = suite.getPrefix() + ":" + suite.getLocalName();
- out.println(
- "Testing suite " + name + " in " + getMode() + " with defaultResult of " + defaultResultName + " ...");
- RecordTestResult recordTestResult = new RecordTestResult();
- if (opts.getLogDir() != null) {
- recordTestResult.recordingStartCheck(suite);
- recordTestResult.recordingStartClause(suite);
- }
- setIndentLevel(1);
- int result = execute_test(suite.getStartingTest().toString(), kvps, null);
- recordTestResult.detailTestPath();
- reTestCount = 0;
- out.print("Suite " + suite.getPrefix() + ":" + suite.getLocalName() + " ");
- if (result == TECore.FAIL || result == TECore.INHERITED_FAILURE) {
- out.println(MSG_FAIL);
- }
- else if (result == TECore.WARNING) {
- out.println(MSG_WARNING);
- }
- else if (result == TECore.BEST_PRACTICE) {
- out.println(MSG_BEST_PRACTICE);
- }
- else {
- out.println(MSG_PASS);
- }
- if (opts.getLogDir() != null) {
- recordTestResult.saveRecordingClause(suite, dirPath);
- recordTestResult.saveRecordingData(suite, dirPath);
- }
- }
-
- public void execute_profile(String profileName, List params, boolean required) throws Exception {
- ProfileEntry profile = index.getProfile(profileName);
- if (profile == null) {
- throw new Exception("Error: Profile " + profileName + " not found.");
- }
- SuiteEntry suite = index.getSuite(profile.getBaseSuite());
- if (suite == null) {
- throw new Exception("Error: The base suite (" + profile.getBaseSuite().toString() + ") for the profile ("
- + profileName + ") not found.");
- }
- String sessionId = opts.getSessionId();
- Document log = LogUtils.readLog(opts.getLogDir(), sessionId);
- if (log == null) {
- execute_suite(suite.getId(), params);
- log = LogUtils.readLog(opts.getLogDir(), sessionId);
- }
- suiteLog = log;
- String testId = LogUtils.getTestIdFromLog(log);
- List baseParams = LogUtils.getParamListFromLog(engine.getBuilder(), log);
- TestEntry test = index.getTest(testId);
- if (suite.getStartingTest().equals(test.getQName())) {
- ArrayList kvps = new ArrayList<>();
- kvps.addAll(baseParams);
- kvps.addAll(params);
- Document form = profile.getForm();
- if (form != null) {
- Document results = (Document) form(form, profile.getId());
- for (Element value : DomUtils.getElementsByTagName(results, "value")) {
- kvps.add(value.getAttribute("key") + "=" + value.getTextContent());
- }
- }
- setTestPath(sessionId + "/" + profile.getLocalName());
- String name = profile.getPrefix() + ":" + profile.getLocalName();
- out.println("\nTesting profile " + name + "...");
- Document baseLog = LogUtils.makeTestList(opts.getLogDir(), sessionId, profile.getExcludes());
- Element baseTest = DomUtils.getElement(baseLog);
- // out.println(DomUtils.serializeNode(baseLog));
- out.print(TECore.INDENT + "Base tests from suite " + suite.getPrefix() + ":" + suite.getLocalName() + " ");
- String summary = "Not complete";
- if ("yes".equals(baseTest.getAttribute("complete"))) {
- int baseResult = Integer.parseInt(baseTest.getAttribute("result"));
- summary = getResultDescription(baseResult);
- }
- out.println(summary);
- setIndentLevel(1);
- String defaultResultName = profile.getDefaultResult();
- defaultResult = defaultResultName.equals("BestPractice") ? BEST_PRACTICE : PASS;
- out.println("\nExecuting profile " + name + " with defaultResult of " + defaultResultName + "...");
- int result = execute_test(profile.getStartingTest().toString(), kvps, null);
- out.print("Profile " + profile.getPrefix() + ":" + profile.getLocalName() + " ");
- summary = getResultDescription(result);
- out.println(summary);
- }
- else {
- if (required) {
- throw new Exception(
- "Error: Profile " + profileName + " is not a valid profile for session " + sessionId + ".");
- }
- }
- }
-
- public XdmNode executeTemplate(TemplateEntry template, XdmNode params, XPathContext context) throws Exception {
- if (stop) {
- throw new Exception("Execution was stopped by the user.");
- }
- XsltExecutable executable = engine.loadExecutable(template, opts.getSourcesName());
- XsltTransformer xt = executable.load();
- XdmDestination dest = new XdmDestination();
- xt.setDestination(dest);
- if (template.usesContext() && context != null) {
- xt.setSource((NodeInfo) context.getContextItem());
- }
- else {
- xt.setSource(new StreamSource(new StringReader(" ")));
- }
- xt.setParameter(TECORE_QNAME, new ObjValue(this));
- if (params != null) {
- xt.setParameter(TEPARAMS_QNAME, params);
- }
- // test may set global verdict, e.g. by calling ctl:fail
- if (LOGR.isLoggable(FINE)) {
- LOGR.log(FINE, "Executing TemplateEntry {0}" + template.getQName());
- }
- xt.transform();
- XdmNode ret = dest.getXdmNode();
- if (ret != null && LOGR.isLoggable(FINE)) {
- LOGR.log(FINE, "Output:\n" + ret.toString());
- }
- return ret;
- }
-
- static String getLabel(XdmNode n) {
- String label = n.getAttributeValue(LABEL_QNAME);
- if (label == null) {
- XdmNode value = (XdmNode) n.axisIterator(Axis.CHILD).next();
- XdmItem childItem = null;
- try {
- childItem = value.axisIterator(Axis.CHILD).next();
- }
- catch (Exception e) {
- // Not an error
- }
- if (childItem == null) {
- XdmSequenceIterator it = value.axisIterator(Axis.ATTRIBUTE);
- if (it.hasNext()) {
- label = it.next().getStringValue();
- }
- else {
- label = "";
- }
- }
- else if (childItem.isAtomicValue()) {
- label = childItem.getStringValue();
- }
- else if (childItem instanceof XdmNode) {
- XdmNode n2 = (XdmNode) childItem;
- if (n2.getNodeKind() == XdmNodeKind.ELEMENT) {
- label = "<" + n2.getNodeName().toString() + ">";
- }
- else {
- label = n2.toString();
- }
- }
- }
- return label;
- }
-
- String getAssertionValue(String text, XdmNode paramsVar) {
- if (text.indexOf("$") < 0) {
- return text;
- }
- String newText = text;
- XdmNode params = (XdmNode) paramsVar.axisIterator(Axis.CHILD).next();
- XdmSequenceIterator it = params.axisIterator(Axis.CHILD);
- while (it.hasNext()) {
- XdmNode n = (XdmNode) it.next();
- QName qname = n.getNodeName();
- if (qname != null) {
- String tagname = qname.getLocalName();
- if (tagname.equals("param")) {
- String name = n.getAttributeValue(LOCALNAME_QNAME);
- String label = getLabel(n);
- newText = StringUtils.replaceAll(newText, "{$" + name + "}", label);
- }
- }
- }
- newText = StringUtils.replaceAll(newText, "{$context}", contextLabel);
- return newText;
- }
-
- static String getResultDescription(int result) {
- if (result == CONTINUE) {
- return MSG_CONTINUE;
- }
- else if (result == BEST_PRACTICE) {
- return MSG_BEST_PRACTICE;
- }
- else if (result == PASS) {
- return MSG_PASS;
- }
- else if (result == NOT_TESTED) {
- return MSG_NOT_TESTED;
- }
- else if (result == SKIPPED) {
- return MSG_SKIPPED;
- }
- else if (result == WARNING) {
- return MSG_WARNING;
- }
- else if (result == INHERITED_FAILURE) {
- return MSG_INHERITED_FAILURE;
- }
- else {
- return MSG_FAIL;
- }
- }
-
- /**
- * Executes a test implemented as an XSLT template.
- * @param test Provides information about the test (gleaned from an entry in the test
- * suite index).
- * @param params A node representing test run arguments.
- * @param context A context in which the template is evaluated.
- * @return An integer value indicating the test result.
- * @throws Exception If any error arises while executing the test.
- */
- public int executeTest(TestEntry test, XdmNode params, XPathContext context) throws Exception {
- testType = test.getType();
- // It is possible to get here without setting testPath. Make sure it is set.
- if (testPath == null)
- testPath = opts.getSessionId();
- defaultResult = test.getDefaultResult();
- defaultResultName = (defaultResult == BEST_PRACTICE) ? "BestPractice" : "Pass";
- Document oldPrevLog = prevLog;
- if (opts.getMode() == Test.RESUME_MODE) {
- prevLog = readLog();
- }
- else if (opts.getMode() == Test.REDO_FROM_CACHE_MODE) {
- prevLog = readLog();
- }
- else {
- prevLog = null;
- }
- String assertion = getAssertionValue(test.getAssertion(), params);
- // seperate two sub test.
- out.println(
- "******************************************************************************************************************************");
- out.print(indent + "Testing ");
- out.print(test.getName() + " type " + test.getType());
-
- // Check test is contain client test main layer or not
-
- if (rootTestName != null && rootTestName.size() > 0) {
- for (int i = 0; i < rootTestName.size(); i++) {
- if ((test.getName()).contains(rootTestName.get(i))) {
- methodCount = methodCount + 1;
- }
- }
- }
-
- out.print(" in " + getMode() + " with defaultResult " + defaultResultName + " ");
- String testName = test.getName() + " type " + test.getType();
- System.setProperty("TestName", testName);
- out.println("(" + testPath + ")...");
- if (opts.getLogDir() != null) {
- String logDir = opts.getLogDir() + "/" + testPath.split("/")[0];
- // Fortify Mod: Add TEPath validation of the log directory path
- TEPath tpath = new TEPath(logDir);
- // create log directory
- if (tpath.isValid() && "True".equals(System.getProperty("Record"))) {
- dirPath = new File(logDir + "/test_data");
- if (!dirPath.exists()) {
- if (!dirPath.mkdir()) {
- System.out.println("Failed to create Error Log!");
- }
- }
- }
- }
-
- // Delete files for coverage report.
- if (reTestCount == 0) {
- if (getMode().contains("Retest")) {
- if (null != dirPath) {
- if (dirPath.isDirectory()) {
- File[] files = dirPath.listFiles();
- if (files != null && files.length > 0) {
- for (File aFile : files) {
- aFile.delete();
- }
- }
- dirPath.delete();
- }
- else {
- dirPath.delete();
- }
- }
- reTestCount = 1;
- }
- }
- String oldIndent = indent;
- indent += INDENT;
- if (test.usesContext()) {
- out.println(indent + "Context: " + test.getContext());
- }
- out.println(indent + "Assertion: " + assertion);
- assertionMsz = assertion;
- PrintWriter oldLogger = logger;
- if (opts.getLogDir() != null) {
- logger = createLog();
- logger.println("");
- logger.print("");
- logger.println("" + StringUtils.escapeXML(assertion) + " ");
- if (params != null) {
- logger.println(params.toString());
- pathURL = params.toString();
- }
- if (test.usesContext()) {
- logger.print("");
- logger.print("");
- logger.print(test.getContext());
- logger.print(" ");
- logger.println(" ");
- }
- logger.println(" ");
- logger.flush();
- }
-
- test.setResult(CONTINUE);
- RecordTestResult recordTestResult = new RecordTestResult();
- recordTestResult.storeStartTestDetail(test, dirPath);
- try {
- testStack.push(test);
- executeTemplate(test, params, context);
- if (test.getResult() == CONTINUE) {
- test.setResult(defaultResult);
- }
- }
- catch (SaxonApiException e) {
- jlogger.log(SEVERE, e.getMessage());
- DateFormat dateFormat = new SimpleDateFormat(Constants.YYYY_M_MDD_H_HMMSS);
- Date date = new Date();
- try {
- String path = System.getProperty("PATH") + "/error_log";
- File file = new File(path);
- if (!file.exists()) {
- if (!file.mkdir()) {
- System.out.println("Failed to create Error Log!");
- }
- }
- file = new File(path, "log.txt");
- if (!file.exists()) {
- try {
- boolean fileCreated = file.createNewFile();
- }
- catch (IOException ioe) {
- System.out.println("Error while creating empty file: " + ioe);
- }
- }
- OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file, true),
- StandardCharsets.UTF_8);
- BufferedWriter fbw = new BufferedWriter(writer);
- fbw.write(dateFormat.format(date) + " ERROR");
- fbw.newLine();
- fbw.write("Test Name : " + System.getProperty("TestName"));
- fbw.newLine();
- fbw.write("Failed to execute the extension function: ");
- e.printStackTrace(new PrintWriter(fbw));
- fbw.newLine();
- fbw.close();
- }
- catch (IOException exep) {
- System.out.println("Error: " + e.getMessage());
- }
- if (logger != null) {
- logger.println(" ");
- }
- test.setResult(FAIL);
- }
- finally {
- updateParentTestResult(test);
- testStack.pop();
- if (logger != null) {
- logger.println(" ");
-
- if (test.isConformanceClass()) {
- logger.println(" ");
- supportHtmlReport = true;
- }
- logger.println(" ");
- logger.flush();
- logger.close();
- }
- // Add missing info in the log.xml E.g. endtag ' or' endtest ' '.
- if (opts.getLogDir() != null && testPath != null) {
- String logDir = opts.getLogDir() + "/" + testPath;
- addMissingInfo(logDir, test);
- }
- }
- // Create node which contain all test detail.
- if ("True".equals(System.getProperty("Record"))) {
- mainRootElement.appendChild(RecordTestResult.getMethod());
- }
- assertionMsz = "";
- pathURL = "";
- messageTest = "";
- logger = oldLogger;
- prevLog = oldPrevLog;
- indent = oldIndent;
- DateFormat dateFormat = new SimpleDateFormat(Constants.YYYY_M_MDD_H_HMMSS);
- Calendar cal = Calendar.getInstance();
- out.println(indent + "Test " + test.getName() + " " + getResultDescription(test.getResult()));
- recordTestResult.storeFinalTestDetail(test, dateFormat, cal, dirPath);
- if (LOGR.isLoggable(FINE)) {
- String msg = String.format("Executed test %s - Verdict: %s", test.getLocalName(),
- getResultDescription(test.getResult()));
- LOGR.log(FINE, msg);
- }
-
- return test.getResult();
- }
-
- public void addMissingInfo(String dir, TestEntry test) {
-
- String logdir = dir + File.separator + "log.xml";
- DocumentBuilderFactory dbf = null;
- DocumentBuilder docBuilder = null;
- Document doc = null;
- File logfile = new File(logdir);
- try {
- dbf = DocumentBuilderFactory.newInstance();
- docBuilder = dbf.newDocumentBuilder();
- docBuilder.setErrorHandler(null);
- doc = docBuilder.parse(logfile);
-
- }
- catch (Exception e) {
-
- try {
- FileWriter fw = new FileWriter(logdir, true);
- BufferedWriter bw = new BufferedWriter(fw);
- PrintWriter out = new PrintWriter(bw);
- out.println("");
- out.close();
- bw.close();
- doc = docBuilder.parse(logfile);
- }
- catch (Exception ex) {
- throw new RuntimeException("Unable to update missing information in " + logdir);
- }
-
- }
-
- NodeList nl = doc.getElementsByTagName("endtest");
- if (nl.getLength() == 0) {
-
- Element root = doc.getDocumentElement();
- appendEndTestElement(test, doc, root);
- appendConformanceClassElement(test, doc, root);
- }
-
- try {
- DOMSource source = new DOMSource(doc);
-
- TransformerFactory transformerFactory = TransformerFactory.newInstance();
- Transformer transformer = transformerFactory.newTransformer();
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- StreamResult result = new StreamResult(logfile);
- transformer.transform(source, result);
- }
- catch (Exception ex) {
- throw new RuntimeException("Unable to update missing information in " + logdir);
- }
-
- }
-
- private void appendEndTestElement(TestEntry test, Document doc, Element root) {
- Element endtest = doc.createElement("endtest");
-
- Attr resultAttribute = doc.createAttribute("result");
- resultAttribute.setValue(Integer.toString(test.getResult()));
-
- endtest.setAttributeNode(resultAttribute);
- root.appendChild(endtest);
- }
-
- private void appendConformanceClassElement(TestEntry test, Document doc, Element root) {
- if (test.isConformanceClass()) {
- Element conformanceClass = doc.createElement("conformanceClass");
-
- Attr nameAttribute = doc.createAttribute("name");
- nameAttribute.setValue(test.getLocalName());
-
- Attr isBasicAttribute = doc.createAttribute("isBasic");
- isBasicAttribute.setValue(Boolean.toString(test.isBasic()));
-
- Attr resultAttribute = doc.createAttribute("result");
- resultAttribute.setValue(Integer.toString(test.getResult()));
-
- conformanceClass.setAttributeNode(nameAttribute);
- conformanceClass.setAttributeNode(isBasicAttribute);
- conformanceClass.setAttributeNode(resultAttribute);
- root.appendChild(conformanceClass);
- }
-
- }
-
- /**
- * Runs a subtest as directed by a <ctl:call-test> instruction.
- * @param context The context in which the subtest is executed.
- * @param localName The [local name] of the subtest.
- * @param namespaceURI The [namespace name] of the subtest.
- * @param params A NodeInfo object containing test parameters.
- * @param callId A node identifier used to build a file path reference for the test
- * results.
- * @throws Exception If an error occcurs while executing the test.
- */
- public synchronized void callTest(XPathContext context, String localName, String namespaceURI, NodeInfo params,
- String callId) throws Exception {
- String key = "{" + namespaceURI + "}" + localName;
- TestEntry test = index.getTest(key);
- if (logger != null) {
- logger.println(" ");
- logger.flush();
- }
- if (opts.getMode() == Test.RESUME_MODE) {
- Document doc = LogUtils.readLog(opts.getLogDir(), testPath + "/" + callId);
- int result = LogUtils.getResultFromLog(doc);
- if (result == CONTINUE) {
- throw new IllegalStateException(
- "Error: 'continue' is not allowed when a test is called using 'call-test' instruction");
- }
- else {
- out.println(indent + "Test " + test.getName() + " " + getResultDescription(result));
- test.setResult(result);
- updateParentTestResult(test);
- return;
- }
- }
-
- String oldTestPath = testPath;
- testPath += "/" + callId;
- int result = CONTINUE;
- try {
- result = executeTest(test, S9APIUtils.makeNode(params), context);
- }
- catch (Exception e) {
-
- }
- finally {
- testPath = oldTestPath;
- }
- if (result == CONTINUE) {
- throw new IllegalStateException(
- "Error: 'continue' is not allowed when a test is called using 'call-test' instruction");
- }
- }
-
- /**
- * Modifies the result of the parent test according to the result of the current test.
- * The parent test will be 'tainted' with an inherited failure if (a) a subtest
- * failed, or (b) a required subtest was skipped.
- * @param currTest The TestEntry for the current test.
- */
- private void updateParentTestResult(TestEntry currTest) {
- TestEntry parentTest = getParentTest();
- if (null == parentTest)
- return;
- if (LOGR.isLoggable(FINE)) {
- LOGR.log(FINE, "Entered setParentTestResult with TestEntry {0} (result={1})",
- new Object[] { currTest.getQName(), currTest.getResult() });
- LOGR.log(FINE, "Parent TestEntry is {0} (result={1})",
- new Object[] { parentTest.getQName(), parentTest.getResult() });
- }
- switch (currTest.getResult()) {
- case FAIL:
- // fall through
- case INHERITED_FAILURE:
- parentTest.setResult(INHERITED_FAILURE);
- break;
- case SKIPPED:
- if (currTest.getType().equalsIgnoreCase("Mandatory")) {
- parentTest.setResult(INHERITED_FAILURE);
- }
- break;
- default:
- parentTest.setResult(Integer.max(currTest.getResult(), parentTest.getResult()));
- break;
- }
- }
-
- /*
- * ctl:repeat-test is not documented and is not used in any
- * https://github.com/opengeospatial ETS
- */
- /*
- * public void repeatTest(XPathContext context, String localName, String NamespaceURI,
- * NodeInfo params, String callId, int count, int pause) throws Exception { String key
- * = "{" + NamespaceURI + "}" + localName; TestEntry test = index.getTest(key);
- *
- * if (logger != null) { logger.println(" "); logger.flush(); } if (opts.getMode() == Test.RESUME_MODE) { Document doc
- * = LogUtils.readLog(opts.getLogDir(), testPath + "/" + callId); int result =
- * LogUtils.getResultFromLog(doc); if (result >= 0) { out.println(indent + "Test " +
- * test.getName() + " " + getResultDescription(result)); if (result == WARNING) {
- * warning(); } else if (result != PASS) { inheritedFailure(); } return; } } int
- * oldResult = verdict; String oldTestPath = testPath; testPath += "/" + callId;
- *
- * for (int i = 0; i < count; i++) { executeTest(test, S9APIUtils.makeNode(params),
- * context); testPath = oldTestPath; if (verdict == FAIL && oldResult != FAIL) { // If
- * the child result was FAIL and parent hasn't directly // failed, // set parent
- * result to INHERITED_FAILURE verdict = INHERITED_FAILURE;
- *
- * return; } else if (verdict == CONTINUE) { //
- * System.out.println("Pausing for..."+pause); if (pause > 0 && i < count - 1) {
- *
- * try {
- *
- * Thread.sleep(pause); } catch (Exception e) { e.printStackTrace(); } }
- *
- * } else if (verdict <= oldResult) { // Restore parent result if the child results
- * aren't worse verdict = oldResult; return;
- *
- * } } verdict = FAIL; if (oldResult != FAIL) { // If the child result was FAIL and
- * parent hasn't directly failed, // set parent result to INHERITED_FAILURE verdict =
- * INHERITED_FAILURE; }
- *
- * }
- */
-
- public NodeInfo executeXSLFunction(XPathContext context, FunctionEntry fe, NodeInfo params) throws Exception {
- String oldFnPath = fnPath;
- CRC32 crc = new CRC32();
- crc.update((fe.getPrefix() + fe.getId()).getBytes());
- fnPath += Long.toHexString(crc.getValue()) + "/";
- XdmNode n = executeTemplate(fe, S9APIUtils.makeNode(params), context);
- fnPath = oldFnPath;
- if (n == null) {
- return null;
- }
- return n.getUnderlyingNode();
- }
-
- public Object callFunction(XPathContext context, String localName, String namespaceURI, NodeInfo params)
- throws Exception {
- // System.out.println("callFunction {" + NamespaceURI + "}" +
- // localName);
- String key = "{" + namespaceURI + "}" + localName;
- List functions = index.getFunctions(key);
- Node paramsNode = NodeOverNodeInfo.wrap(params);
- List paramElements = DomUtils.getElementsByTagName(paramsNode, "param");
- for (FunctionEntry fe : functions) {
- if (!fe.isJava()) {
- boolean valid = true;
- for (Element el : paramElements) {
- String uri = el.getAttribute("namespace-uri");
- String name = el.getAttribute("local-name");
- String prefix = el.getAttribute("prefix");
- javax.xml.namespace.QName qname = new javax.xml.namespace.QName(uri, name, prefix);
- if (!fe.getParams().contains(qname)) {
- valid = false;
- break;
- }
- }
- if (valid) {
- if (opts.getMode() == Test.DOC_MODE) {
- if (fnCallStack.contains(key)) {
- return null;
- }
- else {
- fnCallStack.add(key);
- Object result = executeXSLFunction(context, fe, params);
- fnCallStack.pop();
- return result;
- }
- }
- else {
- return executeXSLFunction(context, fe, params);
- }
- }
- }
- }
-
- if (opts.getMode() == Test.DOC_MODE) {
- return null;
- }
-
- for (FunctionEntry fe : functions) {
- if (fe.isJava()) {
- int argCount = paramElements.size();
- if (fe.getMinArgs() >= argCount && fe.getMaxArgs() <= argCount) {
- TEClassLoader cl = engine.getClassLoader(opts.getSourcesName());
- Method method = Misc.getMethod(fe.getClassName(), fe.getMethod(), cl, argCount);
- Class>[] types = method.getParameterTypes();
- Object[] args = new Object[argCount];
- for (int i = 0; i < argCount; i++) {
- Element el = DomUtils.getElementByTagName(paramElements.get(i), "value");
- if (types[i].equals(String.class)) {
- Map attrs = DomUtils.getAttributes(el);
- if (attrs.size() > 0) {
- args[i] = attrs.values().iterator().next();
- }
- else {
- args[i] = el.getTextContent();
- }
- }
- else if (types[i].toString().equals("char")) {
- args[i] = el.getTextContent().charAt(0);
- }
- else if (types[i].toString().equals("boolean")) {
- args[i] = Boolean.parseBoolean(el.getTextContent());
- }
- else if (types[i].toString().equals("byte")) {
- args[i] = Byte.parseByte(el.getTextContent());
- }
- else if (types[i].toString().equals("short")) {
- args[i] = Short.parseShort(el.getTextContent());
- }
- else if (types[i].toString().equals("int")) {
- args[i] = Integer.parseInt(el.getTextContent());
- }
- else if (types[i].toString().equals("long")) {
- args[i] = Long.parseLong(el.getTextContent());
- }
- else if (types[i].toString().equals("float")) {
- args[i] = Float.parseFloat(el.getTextContent());
- }
- else if (types[i].toString().equals("double")) {
- args[i] = Double.parseDouble(el.getTextContent());
- }
- else if (Document.class.isAssignableFrom(types[i])) {
- args[i] = DomUtils.createDocument(DomUtils.getChildElement(el));
- }
- else if (NodeList.class.isAssignableFrom(types[i])) {
- args[i] = el.getChildNodes();
- }
- else if (Node.class.isAssignableFrom(types[i])) {
- args[i] = el.getFirstChild();
- }
- else {
- throw new Exception(
- "Error: Function " + key + " uses unsupported Java type " + types[i].toString());
- }
- }
- try {
- Object instance = null;
- if (fe.isInitialized()) {
- // String instkey = fe.getId() + "," +
- // Integer.toString(fe.getMinArgs()) + "," +
- // Integer.toString(fe.getMaxArgs());
- instance = getFunctionInstance(fe.hashCode());
- if (instance == null) {
- try {
- instance = Misc.makeInstance(fe.getClassName(), fe.getClassParams(), cl);
- putFunctionInstance(fe.hashCode(), instance);
- }
- catch (Exception e) {
- throw new XPathException(e);
- }
- }
- }
- return method.invoke(instance, args);
- }
- catch (java.lang.reflect.InvocationTargetException e) {
- Throwable cause = e.getCause();
- String msg = "Error invoking function " + fe.getId() + "\n" + cause.getClass().getName();
- if (cause.getMessage() != null) {
- msg += ": " + cause.getMessage();
- }
- jlogger.log(SEVERE, "InvocationTargetException", e);
-
- throw new Exception(msg, cause);
- }
- }
- }
- }
- throw new Exception("No function {" + namespaceURI + "}" + localName + " with a compatible signature.");
- }
-
- public void _continue() {
- testStack.peek().setResult(CONTINUE);
- }
-
- public void bestPractice() {
- if (testStack.peek().getResult() < BEST_PRACTICE) {
- testStack.peek().setResult(BEST_PRACTICE);
- }
- }
-
- public void notTested() {
- if (testStack.peek().getResult() < NOT_TESTED) {
- testStack.peek().setResult(NOT_TESTED);
- }
- }
-
- public void skipped() {
- if (testStack.peek().getResult() < SKIPPED) {
- testStack.peek().setResult(SKIPPED);
- }
- }
-
- public void pass() {
- if (testStack.peek().getResult() < PASS) {
- testStack.peek().setResult(PASS);
- }
- }
-
- public void warning() {
- if (testStack.peek().getResult() < WARNING) {
- testStack.peek().setResult(WARNING);
- }
- }
-
- public void inheritedFailure() {
- if (testStack.peek().getResult() < INHERITED_FAILURE) {
- testStack.peek().setResult(INHERITED_FAILURE);
- }
- }
-
- public void fail() {
- testStack.peek().setResult(FAIL);
- }
-
- public String getResult() {
- return getResultDescription(testStack.getLast().getResult());
- }
-
- public String getMode() {
- return Test.getModeName(opts.getMode());
- }
-
- public void setContextLabel(String label) {
- contextLabel = label;
- }
-
- public String getFormHtml() {
- return formHtml;
- }
-
- public void setFormHtml(String html) {
- this.formHtml = html;
- }
-
- public Document getFormResults() {
- return formResults;
- }
-
- public void setFormResults(Document doc) {
- try {
- StringWriter sw = new StringWriter();
- // Fortify Mod: prevent external entity injection
- TransformerFactory tf = TransformerFactory.newInstance();
- tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- Transformer transformer = tf.newTransformer();
- // End Fortify Mod
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
- transformer.transform(new DOMSource(doc), new StreamResult(sw));
- if (userInputs == null) {
- userInputs = doc;
- }
- LOGR.info("Setting form results:\n " + sw.toString());
- }
- catch (Exception e) {
- LOGR.log(SEVERE, "Failed to log the form results", e);
- }
- this.formResults = doc;
- }
-
- public Map getFormParsers() {
- return formParsers;
- }
-
- public Document readLog() throws Exception {
- return LogUtils.readLog(opts.getLogDir(), testPath);
- }
-
- public PrintWriter createLog() throws Exception {
- return LogUtils.createLog(opts.getLogDir(), testPath);
- }
-
- // Get a File pointer to a file reference (in XML)
- public static File getFile(NodeList fileNodes) {
- File file = null;
- for (int i = 0; i < fileNodes.getLength(); i++) {
- Element e = (Element) fileNodes.item(i);
- String type = e.getAttribute("type");
-
- try {
- // URL, File, or Resource
- if (type.equals("url")) {
- URL url = new URL(e.getTextContent());
- file = new File(url.toURI());
- }
- else if (type.equals("file")) {
- file = new File(e.getTextContent());
- }
- else if (type.equals("resource")) {
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- file = new File(cl.getResource(e.getTextContent()).getFile());
- }
- else {
- System.out.println("Incorrect file reference: Unknown type!");
- }
- }
- catch (Exception exception) {
- System.err.println("Error getting file. " + exception.getMessage());
- jlogger.log(SEVERE, "Error getting file. " + exception.getMessage(), e);
-
- return null;
- }
- }
- return file;
- }
-
- // BEGIN SOAP SUPPORT
- public NodeList soap_request(Document ctlRequest, String id) throws Throwable {
- Element request = (Element) ctlRequest.getElementsByTagNameNS(Test.CTL_NS, "soap-request").item(0);
- if (opts.getMode() == Test.RESUME_MODE && prevLog != null) {
- for (Element request_e : DomUtils.getElementsByTagName(prevLog, "soap-request")) {
- if (request_e.getAttribute("id").equals(fnPath + id)) {
- logger.println(DomUtils.serializeNode(request_e));
- logger.flush();
- Element response_e = DomUtils.getElementByTagName(request_e, "response");
- Element content_e = DomUtils.getElementByTagName(response_e, "content");
- return content_e.getChildNodes();
- // return DomUtils.getChildElement(content_e);
- }
- }
- }
-
- String logTag = "\n";
- logTag += DomUtils.serializeNode(request) + "\n";
- // if (logger != null) {
- // logger.println("");
- // logger.println(DomUtils.serializeNode(request));
- // }
- Exception ex = null;
- Element response = null;
- Element parserInstruction = null;
- NodeList nl = request.getChildNodes();
- long elapsedTime = 0;
- for (int i = 0; i < nl.getLength(); i++) {
- Node n = nl.item(i);
- if (n.getNodeType() == Node.ELEMENT_NODE && !n.getNamespaceURI().equals(CTL_NS)) {
- parserInstruction = (Element) n;
- }
- }
- try {
- Date before = new Date();
- URLConnection uc = build_soap_request(request);
- response = parse(uc, parserInstruction);
- Date after = new Date();
- elapsedTime = after.getTime() - before.getTime();
-
- // Adding the exchange time in the response as comment the format is
- // the following
- //
- // the comment is included in the first tag of the response
- // SOAP:Envelope in case a SOAP message is returned the specific
- // interface tag if a SOAP parser is applied
- Element content = DomUtils.getElementByTagName(response, "content");
- if (content != null) {
- nl = content.getChildNodes();
- for (int i = 0; i < nl.getLength(); i++) {
- Node n = nl.item(i);
- if (n.getNodeType() == Node.ELEMENT_NODE) {
- Document doc;
- doc = response.getOwnerDocument();
- Comment comm = doc.createComment("Response received in [" + elapsedTime + "] milliseconds");
- n.appendChild(comm);
- }
- }
- }
-
- logTag += DomUtils.serializeNode(response) + "\n";
- jlogger.log(FINE, DomUtils.serializeNode(response));
- }
- catch (Exception e) {
- ex = e;
- }
- logTag += "";
- logTag += " ";
- if (logger != null) {
- logger.println(logTag);
- logger.flush();
- }
- if (ex == null) {
- Element parser = DomUtils.getElementByTagName(response, "parser");
- if (parser != null) {
- String text = parser.getTextContent();
- if (text.length() > 0) {
- out.println(parser.getTextContent());
- }
- }
- Element content = DomUtils.getElementByTagName(response, "content");
- return content.getChildNodes();
- }
- else {
- throw ex;
- }
- }
-
- /**
- * Create SOAP request, sends it and return an URL Connection ready to be parsed.
- * @param xml the soap-request node (from CTL)
- * @return The URL Connection
- * @throws Exception the exception
- *
- * <soap-request version="1.1|1.2" charset="UTF-8">
- * <url>http://blah</url> <action>Some-URI</action>
- * <headers> <header MutUnderstand="true" rely="true" role="http://etc">
- * <t:Transaction xmlns:t="some-URI" >5</t:Transaction> </header>
- * </headers> <body> <m:GetLastTradePrice xmlns:m="Some-URI">
- * <symbol>DEF</symbol> </m:GetLastTradePrice> </body>
- * <parsers:SOAPParser return="content"> <parsers:XMLValidatingParser>
- * <parsers:schemas> <parsers:schema
- * type="url">http://blah/schema.xsd</parsers:schema>
- * </parsers:schemas> </parsers:XMLValidatingParser>
- * </parsers:SOAPParser> </soap-request>
- */
- static public URLConnection build_soap_request(Node xml) throws Exception {
- String sUrl = null;
- String method = "POST";
- String charset = ((Element) xml).getAttribute("charset").isEmpty() ? ((Element) xml).getAttribute("charset")
- : "UTF-8";
- String version = ((Element) xml).getAttribute("version");
- String action = "";
- String contentType = "";
- Element body = null;
-
- // Read in the test information (from CTL)
- NodeList nl = xml.getChildNodes();
- for (int i = 0; i < nl.getLength(); i++) {
- Node n = nl.item(i);
- if (n.getNodeType() == Node.ELEMENT_NODE) {
- if (n.getLocalName().equals("url")) {
- sUrl = n.getTextContent();
- }
- else if (n.getLocalName().equals("action")) {
- action = n.getTextContent();
- }
- // else if (n.getLocalName().equals("header")) {
- // header = (org.w3c.dom.Element) n;
- /*
- * }
- */else if (n.getLocalName().equals("body")) {
- body = (org.w3c.dom.Element) n;
- }
- }
- }
-
- // Get the list of the header blocks needed to build the SOAP Header
- // section
- List headerBloks = DomUtils.getElementsByTagNameNS(xml, CTL_NS, HEADER_BLOCKS);
- // Open the URLConnection
- URLConnection uc = new URL(sUrl).openConnection();
- if (uc instanceof HttpURLConnection) {
- ((HttpURLConnection) uc).setRequestMethod(method);
- }
-
- uc.setDoOutput(true);
- byte[] bytes = null;
-
- // SOAP POST
- bytes = SoapUtils.getSoapMessageAsByte(version, headerBloks, body, charset);
- // System.out.println("SOAP MESSAGE " + new String(bytes));
-
- uc.setRequestProperty("User-Agent", "Team Engine 1.2");
- uc.setRequestProperty("Cache-Control", "no-cache");
- uc.setRequestProperty("Pragma", "no-cache");
- uc.setRequestProperty("charset", charset);
- uc.setRequestProperty("Content-Length", Integer.toString(bytes.length));
-
- if (version.equals(SOAP_V_1_1)) {
- // Handle HTTP binding for SOAP 1.1
- // uc.setRequestProperty("Accept", "application/soap+xml");
- uc.setRequestProperty("Accept", "text/xml");
- uc.setRequestProperty("SOAPAction", action);
- contentType = "text/xml";
- if (!charset.isEmpty()) {
- contentType = contentType + "; charset=" + charset;
- }
- uc.setRequestProperty("Content-Type", contentType);
- }
- else {
- // Handle HTTP binding for SOAP 1.2
- uc.setRequestProperty("Accept", "application/soap+xml");
- contentType = "application/soap+xml";
- if (!charset.isEmpty()) {
- contentType = contentType + "; charset=" + charset;
- }
- if (!action.isEmpty()) {
- contentType = contentType + "; action=" + action;
- }
- uc.setRequestProperty("Content-Type", contentType);
- }
- OutputStream os = uc.getOutputStream();
- os.write(bytes);
- return uc;
-
- }
-
- /**
- * Implements ctl:request. Create and send an HTTP request then return an
- * HttpResponse. Invoke any specified parsers on the response to validate it, change
- * its format or derive specific information from it.
- */
- public NodeList request(Document ctlRequest, String id) throws Throwable {
- Element request = (Element) ctlRequest.getElementsByTagNameNS(Test.CTL_NS, "request").item(0);
- if (opts.getMode() == Test.RESUME_MODE && prevLog != null) {
- for (Element request_e : DomUtils.getElementsByTagName(prevLog, "request")) {
- if (request_e.getAttribute("id").equals(fnPath + id)) {
- logger.println(DomUtils.serializeNode(request_e));
- logger.flush();
- Element response_e = DomUtils.getElementByTagName(request_e, "response");
- Element content_e = DomUtils.getElementByTagName(response_e, "content");
- return content_e.getChildNodes();
- // return DomUtils.getChildElement(content_e);
- }
- }
- }
-
- String logTag = "\n";
- logTag += DomUtils.serializeNode(request) + "\n";
- // if (logger != null) {
- // logger.println("");
- // logger.println(DomUtils.serializeNode(request));
- // }
- long elapsedTime = 0;
- Exception ex = null;
- Element response = null;
- Element parserInstruction = null;
- NodeList nl = request.getChildNodes();
- for (int i = 0; i < nl.getLength(); i++) {
- Node n = nl.item(i);
- if (n.getNodeType() == Node.ELEMENT_NODE && !n.getNamespaceURI().equals(CTL_NS)) {
- parserInstruction = (Element) n;
- }
- }
-
- try {
- Date before = new Date();
- URLConnection uc = build_request(request);
- response = parse(uc, parserInstruction);
- Date after = new Date();
- elapsedTime = after.getTime() - before.getTime();
-
- // Adding the exchange time in the response as comment the format is
- // the following
- //
- // the comment is included in the first tag of the response
- Element content = DomUtils.getElementByTagName(response, "content");
- if (content != null) {
- nl = content.getChildNodes();
- for (int i = 0; i < nl.getLength(); i++) {
- Node n = nl.item(i);
- if (n.getNodeType() == Node.ELEMENT_NODE) {
- Document doc;
- doc = response.getOwnerDocument();
- Comment comm = doc.createComment("Response received in [" + elapsedTime + "] milliseconds");
- n.appendChild(comm);
- }
- }
- }
-
- logTag += DomUtils.serializeNode(response) + "\n";
- // if (logger != null) {
- // logger.println(DomUtils.serializeNode(response));
- // }
- }
- catch (Exception e) {
- ex = e;
- }
- // logTag += "";
- logTag += " ";
- if (logger != null) {
- // logger.println(" ");
- logger.println(logTag);
- logger.flush();
- }
- if (ex == null) {
- Element parser = DomUtils.getElementByTagName(response, "parser");
- if (parser != null) {
- String text = parser.getTextContent();
- if (text.length() > 0) {
- out.println(parser.getTextContent());
- }
- }
- Element content = DomUtils.getElementByTagName(response, "content");
- return content.getChildNodes();
- }
- else {
- throw ex;
- }
- }
-
- /**
- * Submits a request to some HTTP endpoint using the given request details.
- * @param xml An ctl:request element.
- * @return A URLConnection object representing an open communications link.
- * @throws Exception If any error occurs while submitting the request or establishing
- * a conection.
- */
- public URLConnection build_request(Node xml) throws Exception {
- Node body = null;
- ArrayList headers = new ArrayList<>();
- ArrayList parts = new ArrayList<>();
- String sUrl = null;
- String sParams = "";
- String method = "GET";
- String charset = "UTF-8";
- boolean multipart = false;
-
- // Read in the test information (from CTL)
- NodeList nl = xml.getChildNodes();
- for (int i = 0; i < nl.getLength(); i++) {
- Node n = nl.item(i);
- if (n.getNodeType() == Node.ELEMENT_NODE) {
- if (n.getLocalName().equals("url")) {
- sUrl = n.getTextContent();
- }
- else if (n.getLocalName().equals("method")) {
- method = n.getTextContent().toUpperCase();
- }
- else if (n.getLocalName().equals("header")) {
- headers.add(new String[] { ((Element) n).getAttribute("name"), n.getTextContent() });
- }
- else if (n.getLocalName().equals("param")) {
- if (sParams.length() > 0) {
- sParams += "&";
- }
- sParams += ((Element) n).getAttribute("name") + "=" + n.getTextContent();
- // WARNING! May break some existing test suites
- // + URLEncoder.encode(n.getTextContent(), "UTF-8");
- }
- else if (n.getLocalName().equals("dynamicParam")) {
- String name = null;
- String val = null;
- NodeList dpnl = n.getChildNodes();
- for (int j = 0; j < dpnl.getLength(); j++) {
- Node dpn = dpnl.item(j);
- if (dpn.getNodeType() == Node.ELEMENT_NODE) {
- if (dpn.getLocalName().equals("name")) {
- name = dpn.getTextContent();
- }
- else if (dpn.getLocalName().equals("value")) {
- val = dpn.getTextContent();
- // val =
- // URLEncoder.encode(dpn.getTextContent(),"UTF-8");
- }
- }
- }
- if (name != null && val != null) {
- if (sParams.length() > 0)
- sParams += "&";
- sParams += name + "=" + val;
- }
- }
- else if (n.getLocalName().equals("body")) {
- body = n;
- }
- else if (n.getLocalName().equals("part")) {
- parts.add(n);
- }
- }
- }
-
- // Complete GET KVP syntax
- // Fortify Mod: Added check for null sUrl. Shouldn't happen but ----
- // if (method.equals("GET") && sParams.length() > 0) {
- if (method.equals("GET") && sParams.length() > 0 && sUrl != null) {
- if (sUrl.indexOf("?") == -1) {
- sUrl += "?";
- }
- else if (!sUrl.endsWith("?") && !sUrl.endsWith("&")) {
- sUrl += "&";
- }
- sUrl += sParams;
- }
-
- // System.out.println(sUrl);
- TransformerFactory tf = TransformerFactory.newInstance();
- // Fortify Mod: prevent external entity injection
- tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- Transformer t = tf.newTransformer();
-
- // Open the URLConnection
- URLConnection uc = new URL(sUrl).openConnection();
- if (uc instanceof HttpURLConnection) {
- HttpURLConnection httpUc = (HttpURLConnection) uc;
- httpUc.setRequestMethod(method);
- boolean redirect = checkForRedirect(httpUc);
- if (redirect) {
- String redirectURL = httpUc.getHeaderField("Location");
- uc = new URL(redirectURL).openConnection();
- if (uc instanceof HttpURLConnection) {
- ((HttpURLConnection) uc).setRequestMethod(method);
- }
- }
- else {
- // https://github.com/opengeospatial/teamengine/issues/553
- // need to re-connect, as the check for redirects already opened the
- // connection
- uc = new URL(sUrl).openConnection();
- }
- }
-
- // POST setup (XML payload and header information)
- if (method.equals("POST") || method.equals("PUT")) {
- uc.setDoOutput(true);
- byte[] bytes = null;
- String mime = null;
-
- // KVP over POST
- if (body == null) {
- bytes = sParams.getBytes();
- mime = "application/x-www-form-urlencoded";
- } // XML POST
- else {
- String bodyContent = "";
-
- NodeList children = body.getChildNodes();
- for (int i = 0; i < children.getLength(); i++) {
- if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- t.transform(new DOMSource(children.item(i)), new StreamResult(baos));
- bodyContent = baos.toString();
- bytes = baos.toByteArray();
-
- if (mime == null) {
- mime = "application/xml; charset=" + charset;
- }
- break;
- }
- }
- if (bytes == null) {
- bytes = body.getTextContent().getBytes();
- mime = "text/plain";
- }
-
- // Add parts if present
- if (parts.size() > 0) {
- String prefix = "--";
- String boundary = "7bdc3bba-e2c9-11db-8314-0800200c9a66";
- String newline = "\r\n";
- multipart = true;
-
- // Set main body and related headers
- ByteArrayOutputStream contentBytes = new ByteArrayOutputStream();
- String bodyPart = prefix + boundary + newline;
- bodyPart += "Content-Type: " + mime + newline + newline;
- bodyPart += bodyContent;
- writeBytes(contentBytes, bodyPart.getBytes(charset));
-
- // Append all parts to the original body, seperated by the
- // boundary sequence
- for (int i = 0; i < parts.size(); i++) {
- Element currentPart = (Element) parts.get(i);
- String cid = currentPart.getAttribute("cid");
- if (cid.indexOf("cid:") != -1) {
- cid = cid.substring(cid.indexOf("cid:") + "cid:".length());
- }
- String contentType = currentPart.getAttribute("content-type");
-
- // Default encodings and content-type
- if (contentType.equals("application/xml")) {
- contentType = "application/xml; charset=" + charset;
- }
- if (contentType == null || contentType.isEmpty()) {
- contentType = "application/octet-stream";
- }
-
- // Set headers for each part
- String partHeaders = newline + prefix + boundary + newline;
- partHeaders += "Content-Type: " + contentType + newline;
- partHeaders += "Content-ID: <" + cid + ">" + newline + newline;
- writeBytes(contentBytes, partHeaders.getBytes(charset));
-
- // Get the fileName, if it exists
- NodeList files = currentPart.getElementsByTagNameNS(CTL_NS, "file");
-
- // Get part for a specified file
- if (files.getLength() > 0) {
- File contentFile = getFile(files);
-
- InputStream is = new FileInputStream(contentFile);
- long length = contentFile.length();
- byte[] fileBytes = new byte[(int) length];
- int offset = 0;
- int numRead = 0;
- while (offset < fileBytes.length
- && (numRead = is.read(fileBytes, offset, fileBytes.length - offset)) >= 0) {
- offset += numRead;
- }
- is.close();
-
- writeBytes(contentBytes, fileBytes);
- } // Get part from inline data (or xi:include)
- else {
- // Text
- if (currentPart.getFirstChild() instanceof Text) {
- writeBytes(contentBytes, currentPart.getTextContent().getBytes(charset));
- } // XML
- else {
- writeBytes(contentBytes,
- DomUtils.serializeNode(currentPart.getFirstChild()).getBytes(charset));
- }
- }
- }
-
- String endingBoundary = newline + prefix + boundary + prefix + newline;
- writeBytes(contentBytes, endingBoundary.getBytes(charset));
-
- bytes = contentBytes.toByteArray();
-
- // Global Content-Type and Length to be added after the
- // parts have been parsed
- mime = "multipart/related; type=\"" + mime + "\"; boundary=\"" + boundary + "\"";
-
- // String contentsString = new String(bytes, charset);
- // System.out.println("Content-Type: "+mime+"\n"+contentsString);
- }
- }
-
- // Set headers
- if (body != null) {
- String mid = ((Element) body).getAttribute("mid");
- if (mid != null && !mid.isEmpty()) {
- if (mid.indexOf("mid:") != -1) {
- mid = mid.substring(mid.indexOf("mid:") + "mid:".length());
- }
- uc.setRequestProperty("Message-ID", "<" + mid + ">");
- }
- }
- uc.setRequestProperty("Content-Type", mime);
- uc.setRequestProperty("Content-Length", Integer.toString(bytes.length));
-
- // Enter the custom headers (overwrites the defaults if present)
- for (int i = 0; i < headers.size(); i++) {
- String[] header = headers.get(i);
- if (multipart && header[0].toLowerCase().equals("content-type")) {
- }
- else {
- uc.setRequestProperty(header[0], header[1]);
- }
- }
-
- OutputStream os = uc.getOutputStream();
- os.write(bytes);
- }
- else {
- for (int i = 0; i < headers.size(); ++i) {
- String[] header = headers.get(i);
- uc.setRequestProperty(header[0], header[1]);
- }
- }
-
- return uc;
- }
-
- public static void writeBytes(ByteArrayOutputStream baos, byte[] bytes) {
- baos.write(bytes, 0, bytes.length);
- }
-
- public Element parse(Document parse_instruction, String xsl_version) throws Throwable {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setNamespaceAware(true);
- // Fortify Mod: prevent external entity injection
- dbf.setExpandEntityReferences(false);
- DocumentBuilder db = dbf.newDocumentBuilder();
-
- TransformerFactory tf = TransformerFactory.newInstance();
- // Fortify Mod: prevent external entity injection
- tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- Transformer t = null;
- Node content = null;
- Document parser_instruction = null;
-
- Element parse_element = (Element) parse_instruction.getElementsByTagNameNS(CTL_NS, "parse").item(0);
-
- NodeList children = parse_element.getChildNodes();
- for (int i = 0; i < children.getLength(); i++) {
- if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
- Element e = (Element) children.item(i);
- if (e.getNamespaceURI().equals(XSL_NS) && e.getLocalName().equals("output")) {
- Document doc = db.newDocument();
- Element transform = doc.createElementNS(XSL_NS, "transform");
- transform.setAttribute("version", xsl_version);
- doc.appendChild(transform);
- Element output = doc.createElementNS(XSL_NS, "output");
- NamedNodeMap atts = e.getAttributes();
- for (int j = 0; j < atts.getLength(); j++) {
- Attr a = (Attr) atts.item(i);
- output.setAttribute(a.getName(), a.getValue());
- }
- transform.appendChild(output);
- Element template = doc.createElementNS(XSL_NS, "template");
- template.setAttribute("match", "node()|@*");
- transform.appendChild(template);
- Element copy = doc.createElementNS(XSL_NS, "copy");
- template.appendChild(copy);
- Element apply = doc.createElementNS(XSL_NS, "apply-templates");
- apply.setAttribute("select", "node()|@*");
- copy.appendChild(apply);
- t = tf.newTransformer(new DOMSource(doc));
- }
- else if (e.getLocalName().equals("content")) {
- NodeList children2 = e.getChildNodes();
- for (int j = 0; j < children2.getLength(); j++) {
- if (children2.item(j).getNodeType() == Node.ELEMENT_NODE) {
- content = children2.item(j);
- }
- }
- if (content == null) {
- content = children2.item(0);
- }
- }
- else {
- parser_instruction = db.newDocument();
- tf.newTransformer().transform(new DOMSource(e), new DOMResult(parser_instruction));
- }
- }
- }
- if (t == null) {
- t = tf.newTransformer();
- }
- File temp = File.createTempFile("$te_", ".xml");
- // Fortify Mod: It is possible to get here without assigning a value to content.
- // if (content.getNodeType() == Node.TEXT_NODE) {
- if (content != null && content.getNodeType() == Node.TEXT_NODE) {
- RandomAccessFile raf = new RandomAccessFile(temp, "rw");
- raf.writeBytes(((Text) content).getTextContent());
- raf.close();
- }
- else {
- t.transform(new DOMSource(content), new StreamResult(temp));
- }
- URLConnection uc = temp.toURI().toURL().openConnection();
- Element result = parse(uc, parser_instruction);
- temp.delete();
- return result;
- }
-
- /**
- * Parses the content retrieved from some URI and builds a DOM Document containing
- * information extracted from the response message. Subsidiary parsers are invoked in
- * accord with the supplied parser instructions.
- * @param uc A URLConnection object.
- * @param instruction A Document or Element node containing parser instructions.
- * @return An Element containing selected info from a URLConnection as specified by
- * instruction Element and children.
- */
- public Element parse(URLConnection uc, Node instruction) throws Throwable {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setNamespaceAware(true);
- // Fortify Mod: Disable entity expansion to foil External Entity Injections
- dbf.setExpandEntityReferences(false);
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document response_doc = db.newDocument();
- return parse(uc, instruction, response_doc);
- }
-
- /**
- * Invoke a parser or chain of parsers as specified by instruction element and
- * children. Parsers in chain share uc, strip off their own instructions, and pass
- * child instructions to next parser in chain. Final parser in chain modifies content.
- * All parsers in chain can return info in attributes and child elements of
- * instructions. If parser specified in instruction, call it to return specified info
- * from uc.
- */
- public Element parse(URLConnection uc, Node instruction, Document response_doc) throws Exception {
- // Fortify Mod: To prevent external entity injections
- TransformerFactory tf = TransformerFactory.newInstance();
- tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- Transformer idt = tf.newTransformer();
- // End Fortify Mod
- Element parser_e = response_doc.createElement("parser");
- Element response_e = response_doc.createElement("response");
- Element content_e = response_doc.createElement("content");
- if (instruction == null) {
- InputStream is = null;
- uc.connect();
- String contentType = uc.getContentType();
- try {
- is = URLConnectionUtils.getInputStream(uc);
- if (contentType != null && contentType.contains("xml")) { // a crude check
- idt.transform(new StreamSource(is), new DOMResult(content_e));
- }
- else {
- content_e.setTextContent(IOUtils.inputStreamToString(is));
- }
- }
- finally {
- if (null != is)
- is.close();
- }
- }
- else {
- Element instruction_e;
- if (instruction instanceof Element) {
- instruction_e = (Element) instruction;
- }
- else {
- instruction_e = ((Document) instruction).getDocumentElement();
- }
- String key = "{" + instruction_e.getNamespaceURI() + "}" + instruction_e.getLocalName();
- ParserEntry pe = index.getParser(key);
- Object instance = null;
-
- // Instantiate the parser object if requested.
- if (pe.isInitialized()) {
- instance = parserInstances.get(key);
- if (instance == null) {
- try {
- TEClassLoader cl = engine.getClassLoader(opts.getSourcesName());
- instance = Misc.makeInstance(pe.getClassName(), pe.getClassParams(), cl);
- }
- catch (Exception e) {
- throw new Exception("Can't instantiate parser " + pe.getName(), e);
- }
- parserInstances.put(key, instance);
- }
- }
-
- Method method = parserMethods.get(key);
- if (method == null) {
- TEClassLoader cl = engine.getClassLoader(opts.getSourcesName());
- method = Misc.getMethod(pe.getClassName(), pe.getMethod(), cl, 3, 4);
- parserMethods.put(key, method);
- }
- StringWriter swLogger = new StringWriter();
- PrintWriter pwLogger = new PrintWriter(swLogger);
- int arg_count = method.getParameterTypes().length;
- Object[] args = new Object[arg_count];
- args[0] = uc;
- args[1] = instruction_e;
- args[2] = pwLogger;
- if (arg_count > 3) {
- args[3] = this;
- }
- Object return_object;
- try {
- if (LOGR.isLoggable(Level.FINER)) {
- LOGR.finer("Invoking method " + method.toGenericString() + "size args[] = " + args.length
- + "\n args[0]: " + args[0].toString() + "\n args[1]:\n"
- + DomUtils.serializeNode((Node) args[1]));
- }
- return_object = method.invoke(instance, args);
- }
- catch (java.lang.reflect.InvocationTargetException e) {
- Throwable cause = e.getCause();
- String msg = "Error invoking parser " + pe.getId() + "\n" + cause.getClass().getName();
- if (cause.getMessage() != null) {
- msg += ": " + cause.getMessage();
- }
- jlogger.log(SEVERE, msg, e);
- // CTL says parsers should return null if they encounter an error.
- // Apparently this parser is broken. Wrap the thrown exception in a
- // RuntimeException since we really know nothing about what went wrong.
- throw new RuntimeException("Parser " + pe.getId() + " threw an exception.", cause);
- }
- pwLogger.close();
- if (return_object instanceof Node) {
- idt.transform(new DOMSource((Node) return_object), new DOMResult(content_e));
- }
- else if (return_object != null) {
- content_e.appendChild(response_doc.createTextNode(return_object.toString()));
- }
- parser_e.setAttribute("prefix", instruction_e.getPrefix());
- parser_e.setAttribute("local-name", instruction_e.getLocalName());
- parser_e.setAttribute("namespace-uri", instruction_e.getNamespaceURI());
- parser_e.setTextContent(swLogger.toString());
- }
- response_e.appendChild(parser_e);
- response_e.appendChild(content_e);
- return response_e;
- }
-
- public Node message(String message, String id) {
- String formatted_message = indent + message.trim().replaceAll("\n", "\n" + indent);
- String messageTrim = message.trim().replaceAll("\n", "\n" + indent);
- if (!(messageTrim.contains("Clause") || messageTrim.contains("Purpose") || messageTrim.contains("TestName"))) {
- out.println(formatted_message);
- messageTest = message;
- }
- else {
- if (messageTrim.contains("TestName")) {
- TESTNAME = messageTrim.replace("TestName : ", "");
- if (rootTestName != null && rootTestName.size() > 0) {
- for (int i = 0; i < rootTestName.size(); i++) {
- if (messageTrim.contains(rootTestName.get(i))) {
- rootNo = i + 1;
- }
- }
- }
- }
- else if (messageTrim.contains("Clause")) {
- Clause = messageTrim.replace("Clause : ", "");
- }
- else {
- Purpose = messageTrim.replace("Purpose : ", "");
- }
- if ((rootNo != 0) && (!"".equals(Clause)) && (!"".equals(Purpose))) {
- mainRootElementClause.appendChild(RecordTestResult.getClause());
- Clause = "";
- Purpose = "";
- rootNo = 0;
- }
- }
- if (logger != null) {
- logger.println(" ");
- }
- return null;
- }
-
- public void putLogCache(String id, Document xmlToCache) {
- if (logger != null) {
- String xmlString = DomUtils.serializeNode(xmlToCache);
- logger.println("" + xmlString + " ");
- }
- }
-
- public Element getLogCache(String id) {
- Element child_e = null;
- if (prevLog != null) {
- for (Element cache_e : DomUtils.getElementsByTagName(prevLog, "cache")) {
- if (cache_e.getAttribute("id").equals(id)) {
- child_e = DomUtils.getChildElement(cache_e);
- }
- }
- }
- if (suiteLog != null && child_e == null) {
- for (Element cache_e : DomUtils.getElementsByTagName(suiteLog, "cache")) {
- if (cache_e.getAttribute("id").equals(id)) {
- child_e = DomUtils.getChildElement(cache_e);
- }
- }
- }
- return child_e;
- }
-
- /**
- * Converts CTL input form elements to generate a Swing-based or XHTML form and
- * reports the results of processing the submitted form. The results document is
- * produced in (web context) or
- * {@link com.occamlab.te.SwingForm.CustomFormView#submitData(String)}.
- * @param ctlForm a DOM Document representing a <ctl:form> element.
- * @throws java.lang.Exception
- * @return a DOM Document containing the resulting <values> element as the
- * document element.
- */
- public Node form(Document ctlForm, String id) throws Exception {
- if (opts.getMode() == Test.RESUME_MODE && prevLog != null) {
- for (Element e : DomUtils.getElementsByTagName(prevLog, "formresults")) {
- if (e.getAttribute("id").equals(fnPath + id)) {
- logger.println(DomUtils.serializeNode(e));
- logger.flush();
- return DomUtils.getChildElement(e);
- }
- }
- }
-
- String name = Thread.currentThread().getName();
- Element form = (Element) ctlForm.getElementsByTagNameNS(CTL_NS, "form").item(0);
-
- NamedNodeMap attrs = form.getAttributes();
- Attr attr = (Attr) attrs.getNamedItem("name");
- if (attr != null) {
- name = attr.getValue();
- }
-
- for (Element parseInstruction : DomUtils.getElementsByTagNameNS(form, CTL_NS, "parse")) {
- String key = parseInstruction.getAttribute("file");
- formParsers.put(key, DomUtils.getChildElement(parseInstruction));
- }
-
- // Determine if there are file widgets or not
- boolean hasFiles = false;
- List inputs = DomUtils.getElementsByTagName(form, "input");
- inputs.addAll(DomUtils.getElementsByTagNameNS(form, "http://www.w3.org/1999/xhtml", "input"));
- for (Element input : inputs) {
- if (input.getAttribute("type").toLowerCase().equals("file")) {
- hasFiles = true;
- break;
- }
- }
-
- // Get "method" attribute - "post" or "get"
- attr = (Attr) attrs.getNamedItem("method");
- String method = "get";
- if (attr != null) {
- method = attr.getValue().toLowerCase();
- }
- else if (hasFiles) {
- method = "post";
- }
- imageHandler.saveImages(form);
-
- XsltTransformer formTransformer = engine.getFormExecutable().load();
- formTransformer.setSource(new DOMSource(ctlForm));
- formTransformer.setParameter(new QName("title"), new XdmAtomicValue(name));
- formTransformer.setParameter(new QName("web"), new XdmAtomicValue(web ? "yes" : "no"));
- formTransformer.setParameter(new QName("files"), new XdmAtomicValue(hasFiles ? "yes" : "no"));
- formTransformer.setParameter(new QName("thread"),
- new XdmAtomicValue(Long.toString(Thread.currentThread().getId())));
- formTransformer.setParameter(new QName("method"), new XdmAtomicValue(method));
- formTransformer.setParameter(new QName("base"), new XdmAtomicValue(opts.getBaseURI()));
- formTransformer.setParameter(new QName("action"), new XdmAtomicValue(getTestServletURL()));
- StringWriter sw = new StringWriter();
- Serializer serializer = new Serializer();
- serializer.setOutputWriter(sw);
- serializer.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");
- formTransformer.setDestination(serializer);
- formTransformer.transform();
- this.formHtml = sw.toString();
- if (LOGR.isLoggable(FINE))
- LOGR.fine(this.formHtml);
-
- if (!recordedForms.isEmpty()) {
- RecordedForm.create(recordedForms.next(), this);
- }
- else if (!web) {
- int width = 700;
- int height = 500;
- attr = (Attr) attrs.getNamedItem("width");
- if (attr != null) {
- width = Integer.parseInt(attr.getValue());
- }
- attr = (Attr) attrs.getNamedItem("height");
- if (attr != null) {
- height = Integer.parseInt(attr.getValue());
- }
- SwingForm.create(name, width, height, this);
- }
-
- while (formResults == null) {
- if (stop) {
- formParsers.clear();
- throw new Exception("Execution was stopped by the user.");
- }
- Thread.sleep(250);
- }
-
- Document doc = formResults;
- if (LOGR.isLoggable(FINE))
- LOGR.fine(DomUtils.serializeNode(doc));
- formResults = null;
- formParsers.clear();
-
- if (logger != null) {
- logger.println("");
- logger.println(DomUtils.serializeNode(doc));
- logger.println(" ");
- }
- return doc;
- }
-
- public void setIndentLevel(int level) {
- indent = "";
- for (int i = 0; i < level; i++) {
- indent += INDENT;
- }
- }
-
- public String getOutput() {
- String output = threadOutput.toString();
- threadOutput.reset();
- return output;
- }
-
- public void stopThread() throws Exception {
- stop = true;
- while (!threadComplete) {
- Thread.sleep(100);
- }
- }
-
- public boolean isThreadComplete() {
- return threadComplete;
- }
-
- public void run() {
- threadComplete = false;
- // activeThread = Thread.currentThread();
- try {
- opts.getLogDir().mkdir();
- threadOutput = new ByteArrayOutputStream();
- out = new PrintStream(threadOutput);
- execute();
- out.close();
- }
- catch (Exception e) {
- jlogger.log(SEVERE, "", e);
- }
- // activeThread = null;
- threadComplete = true;
- }
-
- public File getLogDir() {
- return opts.getLogDir();
- }
-
- public PrintStream getOut() {
- return out;
- }
-
- public void setOut(PrintStream out) {
- this.out = out;
- }
-
- public String getTestPath() {
- return testPath;
- }
-
- /**
- * Returns the location of the directory containing the test run output.
- * @return A String representing a file URI denoting the path name of a directory.
- */
- public String getTestRunDirectory() {
- String logDirURI = opts.getLogDir().toURI().toString();
- return logDirURI + opts.getSessionId();
- }
-
- /**
- * Updates the local testPath value. C. Heazel made private since it is never called
- * by an external object Could be removed since local classes can set it directly. Or
- * augmented by value validation.
- */
- private void setTestPath(String testPath) {
- this.testPath = testPath;
- }
-
- public boolean isWeb() {
- return web;
- }
-
- public void setWeb(boolean web) {
- this.web = web;
- }
-
- public Object getFunctionInstance(Integer key) {
- return functionInstances.get(key);
- }
-
- public Object putFunctionInstance(Integer key, Object instance) {
- return functionInstances.put(key, instance);
- }
-
- public Engine getEngine() {
- return engine;
- }
-
- public Index getIndex() {
- return index;
- }
-
- public RuntimeOptions getOpts() {
- return opts;
- }
-
- public String getTestServletURL() {
- return testServletURL;
- }
-
- public void setTestServletURL(String testServletURL) {
- this.testServletURL = testServletURL;
- }
-
- /**
- * Transform EARL result into HTML report using XSLT.
- * @param outputDir
- */
- // Fortify Mod: Changed to a private method so that the value of the
- // outputDir parameter can be managed.
- // Note: that there is no indication that this method is ever called.
- public boolean earlHtmlReport(String outputDir) {
- TEPath tpath = new TEPath(outputDir);
- if (!tpath.isValid()) {
- System.out.println("ViewLog Error: Invalid log file name " + outputDir);
- return false;
- }
- EarlToHtmlTransformation earlToHtml = new EarlToHtmlTransformation();
- earlToHtml.earlHtmlReport(outputDir);
- return true;
- }
-
- /**
- * This method is used to extract the test input into Map from the document element.
- * @param userInput Document node
- * @param runOpts
- * @return User Input Map
- */
- private Map extractTestInputs(Document userInput, RuntimeOptions runOpts) {
- Map inputMap = new HashMap<>();
- if (null != userInputs) {
- NodeList values = userInputs.getDocumentElement().getElementsByTagName("value");
- if (values.getLength() == 0) {
- inputMap = Collections.emptyMap();
- }
- else {
- for (int i = 0; i < values.getLength(); i++) {
- Element value = (Element) values.item(i);
- inputMap.put(value.getAttribute("key"), value.getTextContent());
- }
- }
- }
- else if (null != opts.getParams()) {
- List runParams = opts.getParams();
- for (String param : runParams) {
- String[] kvp = param.split("=");
- inputMap.put(kvp[0], kvp[1]);
- }
- }
- return inputMap;
- }
-
- private boolean checkForRedirect(HttpURLConnection conn) throws IOException {
- int status = conn.getResponseCode();
- if (status != HttpURLConnection.HTTP_OK) {
- if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
- || status == HttpURLConnection.HTTP_SEE_OTHER)
- return true;
- }
- return false;
- }
-
- /**
- * Builds a DOM Document representing a classpath resource.
- * @param name The name of an XML resource.
- * @return A Document node, or {@code null} if the resource cannot be parsed for any
- * reason.
- */
- public Document findXMLResource(String name) {
- URL url = this.getClass().getResource(name);
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- docFactory.setNamespaceAware(true);
- // Fortify Mod: Disable entity expansion to foil External Entity Injections
- docFactory.setExpandEntityReferences(false);
- Document doc = null;
- try {
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- doc = docBuilder.parse(url.toURI().toString());
- }
- catch (Exception e) {
- LOGR.log(Level.WARNING, "Failed to parse classpath resource " + name, e);
- }
- return doc;
- }
-
-}
+/**
+ * **************************************************************************
+ *
+ * The Original Code is TEAM Engine.
+ *
+ * The Initial Developer of the Original Code is Northrop Grumman Corporation
+ * jointly with The National Technology Alliance. Portions created by Northrop
+ * Grumman Corporation are Copyright (C) 2005-2006, Northrop Grumman
+ * Corporation. All Rights Reserved.
+ *
+ * Contributor(s):
+ * S. Gianfranceschi (Intecs): Added the SOAP suport
+ * C. Heazel (WiSC): Added Fortify adjudication changes
+ *
+ ***************************************************************************
+ */
+package com.occamlab.te;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.BufferedWriter;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.io.RandomAccessFile;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.lang.reflect.Method;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLConnection;
+import java.nio.charset.StandardCharsets;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Stack;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.zip.CRC32;
+
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMResult;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+
+import com.occamlab.te.form.ImageHandler;
+import com.occamlab.te.html.EarlToHtmlTransformation;
+
+import net.sf.saxon.dom.NodeOverNodeInfo;
+import net.sf.saxon.expr.XPathContext;
+import net.sf.saxon.expr.XPathContextMajor;
+import net.sf.saxon.instruct.Executable;
+import net.sf.saxon.om.NodeInfo;
+import net.sf.saxon.s9api.Axis;
+import net.sf.saxon.s9api.QName;
+import net.sf.saxon.s9api.S9APIUtils;
+import net.sf.saxon.s9api.SaxonApiException;
+import net.sf.saxon.s9api.Serializer;
+import net.sf.saxon.s9api.XdmAtomicValue;
+import net.sf.saxon.s9api.XdmDestination;
+import net.sf.saxon.s9api.XdmItem;
+import net.sf.saxon.s9api.XdmNode;
+import net.sf.saxon.s9api.XdmNodeKind;
+import net.sf.saxon.s9api.XdmSequenceIterator;
+import net.sf.saxon.s9api.XsltExecutable;
+import net.sf.saxon.s9api.XsltTransformer;
+import net.sf.saxon.trans.XPathException;
+
+import org.w3c.dom.Attr;
+import org.w3c.dom.Comment;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
+
+import com.occamlab.te.index.FunctionEntry;
+import com.occamlab.te.index.Index;
+import com.occamlab.te.index.ParserEntry;
+import com.occamlab.te.index.ProfileEntry;
+import com.occamlab.te.index.SuiteEntry;
+import com.occamlab.te.index.TemplateEntry;
+import com.occamlab.te.index.TestEntry;
+import com.occamlab.te.saxon.ObjValue;
+import com.occamlab.te.util.Constants;
+import com.occamlab.te.util.DomUtils;
+import com.occamlab.te.util.IOUtils;
+import com.occamlab.te.util.LogUtils;
+import com.occamlab.te.util.Misc;
+import com.occamlab.te.util.SoapUtils;
+import com.occamlab.te.util.StringUtils;
+import com.occamlab.te.util.URLConnectionUtils;
+import com.occamlab.te.util.TEPath;
+
+import static java.util.logging.Level.FINE;
+import static java.util.logging.Level.SEVERE;
+
+/**
+ * Provides various utility methods to support test execution and logging. Primary ones
+ * include implementation and execution of ctl:suite, ctl:profile, ctl:test, ctl:function,
+ * ctl:request and ctl:soap-request instructions, and invocation of any parsers specified
+ * therein.
+ *
+ */
+public class TECore implements Runnable {
+
+ private static final Logger LOGR = Logger.getLogger(TECore.class.getName());
+
+ public static final String SOAP_V_1_1 = "1.1";
+
+ public static final String SOAP_V_1_2 = "1.2";
+
+ Engine engine; // Engine object
+
+ Index index;
+
+ public static int testCount = 0;
+
+ int reTestCount = 0;
+
+ public static int methodCount = 0;
+
+ String testName = "";
+
+ public static String nameOfTest = "";
+
+ final RuntimeOptions opts;
+
+ String testServletURL = null;
+
+ volatile PrintStream out; // Console destination
+
+ boolean web = false; // True when running as a servlet
+
+ RecordedForms recordedForms;
+
+ private String testPath; // Uniquely identifies a test instance
+
+ String fnPath = ""; // Uniquely identifies an XSL function instance within a
+
+ // test instance
+ String indent = ""; // Contains the appropriate number of spaces for the
+
+ // current indent level
+ String contextLabel = ""; // Current context label set by ctl:for-each
+
+ String testType = "Mandatory"; // Type of current test
+
+ String defaultResultName = "Pass"; // Default result name for current test
+
+ int defaultResult = PASS; // Default result for current test
+
+ ArrayList media = new ArrayList<>();
+
+ public File dirPath;
+
+ Document prevLog = null; // Log document for current test from previous test
+
+ // execution (resume and retest modes only)
+ // Log document for suite to enable use of getLogCache by profile test
+ Document suiteLog = null;
+
+ public static String pathURL = "";
+
+ public static String assertionMsz = "";
+
+ public static String messageTest = "";
+
+ PrintWriter logger = null; // Logger for current test
+
+ volatile String formHtml; // HTML representation for an active form
+
+ volatile Document formResults; // Holds form results until they are
+
+ // retrieved
+ Map formParsers = new HashMap<>();
+
+ Map functionInstances = new HashMap<>();
+
+ Map parserInstances = new HashMap<>();
+
+ Map parserMethods = new HashMap<>();
+
+ LinkedList testStack = new LinkedList<>();
+
+ volatile boolean threadComplete = false;
+
+ volatile boolean stop = false;
+
+ volatile ByteArrayOutputStream threadOutput;
+
+ private Stack fnCallStack;
+
+ public static final int CONTINUE = -1;
+
+ public static final int BEST_PRACTICE = 0;
+
+ public static final int PASS = 1;
+
+ public static final int NOT_TESTED = 2;
+
+ public static final int SKIPPED = 3;
+
+ public static final int WARNING = 4;
+
+ public static final int INHERITED_FAILURE = 5;
+
+ public static final int FAIL = 6;
+
+ public static final String MSG_CONTINUE = "Inconclusive! Continue Test";
+
+ public static final String MSG_BEST_PRACTICE = "Passed as Best Practice";
+
+ public static final String MSG_PASS = "Passed";
+
+ public static final String MSG_NOT_TESTED = "Not Tested";
+
+ public static final String MSG_SKIPPED = "Skipped - Prerequisites not satisfied";
+
+ public static final String MSG_WARNING = "Warning";
+
+ public static final String MSG_INHERITED_FAILURE = "Failed - Inherited";
+
+ public static final String MSG_FAIL = "Failed";
+
+ public static final int MANDATORY = 0;
+
+ public static final int MANDATORY_IF_IMPLEMENTED = 1;
+
+ public static final int OPTIONAL = 2;
+
+ static final String XSL_NS = Test.XSL_NS;
+ static final String CTL_NS = Test.CTL_NS;
+ static final String TE_NS = Test.TE_NS;
+ static final String INDENT = " ";
+ static final QName TECORE_QNAME = new QName("te", TE_NS, "core");
+ static final QName TEPARAMS_QNAME = new QName("te", TE_NS, "params");
+ static final QName LOCALNAME_QNAME = new QName("local-name");
+ static final QName LABEL_QNAME = new QName("label");
+ static final String HEADER_BLOCKS = "header-blocks";
+
+ private static Logger jlogger = Logger.getLogger("com.occamlab.te.TECore");
+
+ public static DocumentBuilderFactory icFactory;
+
+ public static DocumentBuilder icBuilder;
+
+ public static Document doc;
+
+ public static Element mainRootElement;
+
+ public static DocumentBuilderFactory icFactoryClause;
+
+ public static DocumentBuilder icBuilderClause;
+
+ public static Document docClause;
+
+ public static Element mainRootElementClause;
+
+ public static String TESTNAME = "";
+
+ public static int rootNo = 0;
+
+ public static String Clause = "";
+
+ public static String Purpose = "";
+
+ public static ArrayList rootTestName = new ArrayList<>();
+
+ public Document userInputs = null;
+
+ public Boolean supportHtmlReport = false;
+
+ public final ImageHandler imageHandler;
+
+ public TECore() {
+ this.opts = null;
+ this.imageHandler = null;
+ }
+
+ public TECore(Engine engine, Index index, RuntimeOptions opts) {
+ this.engine = engine;
+ this.index = index;
+ this.opts = opts;
+ this.recordedForms = new RecordedForms(opts.getRecordedForms());
+ this.testPath = opts.getSessionId();
+ this.out = System.out;
+ this.imageHandler = new ImageHandler(opts.getLogDir(), opts.getSessionId());
+ this.fnCallStack = new Stack<>();
+ }
+
+ public TestEntry getParentTest() {
+ if (testStack.size() < 2) {
+ return testStack.peek();
+ }
+ else {
+ return testStack.get(1);
+ }
+ }
+
+ public String getParamsXML(List params) throws Exception {
+ String paramsXML = "";
+ for (int i = 0; i < params.size(); i++) {
+ String param = params.get(i);
+ String name = param.substring(0, param.indexOf('='));
+ String value = param.substring(param.indexOf('=') + 1);
+ if (params.get(i).indexOf('=') != 0) {
+ paramsXML += " ";
+ paramsXML += " ";
+ paramsXML += "";
+ }
+ }
+ paramsXML += " ";
+ // System.out.println("paramsXML: "+paramsXML);
+ return paramsXML;
+ }
+
+ XPathContext getXPathContext(TestEntry test, String sourcesName, XdmNode contextNode) throws Exception {
+ XPathContext context = null;
+ if (test.usesContext() && contextNode != null) {
+ XsltExecutable xe = engine.loadExecutable(test, sourcesName);
+ Executable ex = xe.getUnderlyingCompiledStylesheet().getExecutable();
+ context = new XPathContextMajor(contextNode.getUnderlyingNode(), ex);
+ }
+ return context;
+ }
+
+ // Execute tests
+ public void execute() throws Exception {
+ try {
+ TestEntry grandParent = new TestEntry();
+ grandParent.setType("Mandatory");
+ grandParent.setResult(CONTINUE);
+ testStack.push(grandParent);
+ String sessionId = opts.getSessionId();
+ int mode = opts.getMode();
+ ArrayList params = opts.getParams();
+
+ if (mode == Test.RESUME_MODE) {
+ reexecute_test(sessionId);
+ }
+ else if (mode == Test.REDO_FROM_CACHE_MODE) {
+ reexecute_test(sessionId);
+ }
+ else if (mode == Test.RETEST_MODE) {
+ for (String testPath : opts.getTestPaths()) {
+ reexecute_test(testPath);
+ }
+ }
+ else if (mode == Test.TEST_MODE || mode == Test.DOC_MODE) {
+ String testName = opts.getTestName();
+ if (!testName.isEmpty()) {
+ // NOTE: getContextNode() always returns null
+ XdmNode contextNode = opts.getContextNode();
+ execute_test(testName, params, contextNode);
+ }
+ else {
+ String suiteName = opts.getSuiteName();
+ List profiles = opts.getProfiles();
+ if (!suiteName.isEmpty() || profiles.size() == 0) {
+ execute_suite(suiteName, params);
+ }
+ if (profiles.contains("*")) {
+ for (String profile : index.getProfileKeys()) {
+ try {
+ execute_profile(profile, params, false);
+ }
+ catch (Exception e) {
+ jlogger.log(Level.WARNING, e.getMessage(), e.getCause());
+ }
+ }
+ }
+ else {
+ for (String profile : profiles) {
+ try {
+ execute_profile(profile, params, true);
+ }
+ catch (Exception e) {
+ jlogger.log(Level.WARNING, e.getMessage(), e.getCause());
+ }
+ }
+ }
+ }
+ }
+ else {
+ throw new Exception("Unsupported mode");
+ }
+ }
+ finally {
+ if (!web) {
+ SwingForm.destroy();
+ }
+ if (opts.getLogDir() != null) {
+ // Create xml execution report file
+ LogUtils.createFullReportLog(opts.getLogDir().getAbsolutePath() + File.separator + opts.getSessionId());
+ File resultsDir = new File(opts.getLogDir(), opts.getSessionId());
+ if (supportHtmlReport) {
+ Map testInputMap = new HashMap<>();
+ testInputMap = extractTestInputs(userInputs, opts);
+
+ if (!new File(resultsDir, "testng").exists() && null != testInputMap) {
+ /*
+ * Transform CTL result into EARL result, when the CTL test is
+ * executed through the webapp.
+ */
+ try {
+
+ File testLog = new File(resultsDir, "report_logs.xml");
+ CtlEarlReporter report = new CtlEarlReporter();
+
+ if (null != opts.getSourcesName()) {
+ report.generateEarlReport(resultsDir, testLog, opts.getSourcesName(), testInputMap);
+ }
+ }
+ catch (IOException iox) {
+ throw new RuntimeException("Failed to serialize EARL results to " + iox);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ public void reexecute_test(String testPath) throws Exception {
+ File deleteExistingResultDir = new File(
+ opts.getLogDir() + File.separator + testPath + File.separator + "result");
+ if (deleteExistingResultDir.exists()) {
+ Misc.deleteDir(deleteExistingResultDir);
+ }
+ File deleteExistingTestngDir = new File(
+ opts.getLogDir() + File.separator + testPath + File.separator + "testng");
+ if (deleteExistingTestngDir.exists()) {
+ Misc.deleteDir(deleteExistingTestngDir);
+ }
+ Document log = LogUtils.readLog(opts.getLogDir(), testPath);
+ String testId = LogUtils.getTestIdFromLog(log);
+ TestEntry test = index.getTest(testId);
+ net.sf.saxon.s9api.DocumentBuilder builder = engine.getBuilder();
+ XdmNode paramsNode = LogUtils.getParamsFromLog(builder, log);
+ XdmNode contextNode = LogUtils.getContextFromLog(builder, log);
+ XPathContext context = getXPathContext(test, opts.getSourcesName(), contextNode);
+ setTestPath(testPath);
+ executeTest(test, paramsNode, context);
+ if (testPath.equals(opts.getSessionId())) {
+ // Profile not executed in retest mode
+ suiteLog = LogUtils.readLog(opts.getLogDir(), testPath);
+ ArrayList params = opts.getParams();
+ List profiles = opts.getProfiles();
+ if (profiles.contains("*")) {
+ for (String profile : index.getProfileKeys()) {
+ try {
+ execute_profile(profile, params, false);
+ }
+ catch (Exception e) {
+ jlogger.log(Level.WARNING, e.getMessage(), e.getCause());
+ }
+ }
+ }
+ else {
+ for (String profile : profiles) {
+ try { // 2011-12-21 PwD
+ execute_profile(profile, params, true);
+ }
+ catch (Exception e) {
+ jlogger.log(Level.WARNING, e.getMessage(), e.getCause());
+ }
+ }
+ }
+ }
+ }
+
+ public int execute_test(String testName, List params, XdmNode contextNode) throws Exception {
+ if (LOGR.isLoggable(FINE)) {
+ String logMsg = String.format("Preparing test %s for execution, using params:%n %s", testName, params);
+ LOGR.fine(logMsg);
+ }
+ TestEntry test = index.getTest(testName);
+ if (test == null) {
+ throw new Exception("Error: Test " + testName + " not found.");
+ }
+ XdmNode paramsNode = engine.getBuilder().build(new StreamSource(new StringReader(getParamsXML(params))));
+ if (contextNode == null && test.usesContext()) {
+ String contextNodeXML = "" + test.getContext() + " ";
+ contextNode = engine.getBuilder().build(new StreamSource(new StringReader(contextNodeXML)));
+ }
+ XPathContext context = getXPathContext(test, opts.getSourcesName(), contextNode);
+ return executeTest(test, paramsNode, context);
+ }
+
+ public void execute_suite(String suiteName, List params) throws Exception {
+ SuiteEntry suite = null;
+ if (suiteName == null || suiteName.isEmpty()) {
+ Iterator it = index.getSuiteKeys().iterator();
+ if (!it.hasNext()) {
+ throw new Exception("Error: No suites in sources.");
+ }
+ suite = index.getSuite(it.next());
+ if (it.hasNext()) {
+ throw new Exception(
+ "Error: Suite name must be specified since there is more than one suite in sources.");
+ }
+ }
+ else {
+ suite = index.getSuite(suiteName);
+ if (suite == null) {
+ throw new Exception("Error: Suite " + suiteName + " not found.");
+ }
+ }
+ defaultResultName = suite.getDefaultResult();
+ defaultResult = defaultResultName.equals("BestPractice") ? BEST_PRACTICE : PASS;
+ testStack.peek().setDefaultResult(defaultResult);
+ testStack.peek().setResult(defaultResult);
+
+ ArrayList kvps = new ArrayList<>(params);
+ Document form = suite.getForm();
+ if (form != null) {
+ Document results = (Document) form(form, suite.getId());
+ for (Element value : DomUtils.getElementsByTagName(results, "value")) {
+ kvps.add(value.getAttribute("key") + "=" + value.getTextContent());
+ }
+ }
+ String name = suite.getPrefix() + ":" + suite.getLocalName();
+ out.println(
+ "Testing suite " + name + " in " + getMode() + " with defaultResult of " + defaultResultName + " ...");
+ RecordTestResult recordTestResult = new RecordTestResult();
+ if (opts.getLogDir() != null) {
+ recordTestResult.recordingStartCheck(suite);
+ recordTestResult.recordingStartClause(suite);
+ }
+ setIndentLevel(1);
+ int result = execute_test(suite.getStartingTest().toString(), kvps, null);
+ recordTestResult.detailTestPath();
+ reTestCount = 0;
+ out.print("Suite " + suite.getPrefix() + ":" + suite.getLocalName() + " ");
+ if (result == TECore.FAIL || result == TECore.INHERITED_FAILURE) {
+ out.println(MSG_FAIL);
+ }
+ else if (result == TECore.WARNING) {
+ out.println(MSG_WARNING);
+ }
+ else if (result == TECore.BEST_PRACTICE) {
+ out.println(MSG_BEST_PRACTICE);
+ }
+ else {
+ out.println(MSG_PASS);
+ }
+ if (opts.getLogDir() != null) {
+ recordTestResult.saveRecordingClause(suite, dirPath);
+ recordTestResult.saveRecordingData(suite, dirPath);
+ }
+ }
+
+ public void execute_profile(String profileName, List params, boolean required) throws Exception {
+ ProfileEntry profile = index.getProfile(profileName);
+ if (profile == null) {
+ throw new Exception("Error: Profile " + profileName + " not found.");
+ }
+ SuiteEntry suite = index.getSuite(profile.getBaseSuite());
+ if (suite == null) {
+ throw new Exception("Error: The base suite (" + profile.getBaseSuite().toString() + ") for the profile ("
+ + profileName + ") not found.");
+ }
+ String sessionId = opts.getSessionId();
+ Document log = LogUtils.readLog(opts.getLogDir(), sessionId);
+ if (log == null) {
+ execute_suite(suite.getId(), params);
+ log = LogUtils.readLog(opts.getLogDir(), sessionId);
+ }
+ suiteLog = log;
+ String testId = LogUtils.getTestIdFromLog(log);
+ List baseParams = LogUtils.getParamListFromLog(engine.getBuilder(), log);
+ TestEntry test = index.getTest(testId);
+ if (suite.getStartingTest().equals(test.getQName())) {
+ ArrayList kvps = new ArrayList<>();
+ kvps.addAll(baseParams);
+ kvps.addAll(params);
+ Document form = profile.getForm();
+ if (form != null) {
+ Document results = (Document) form(form, profile.getId());
+ for (Element value : DomUtils.getElementsByTagName(results, "value")) {
+ kvps.add(value.getAttribute("key") + "=" + value.getTextContent());
+ }
+ }
+ setTestPath(sessionId + "/" + profile.getLocalName());
+ String name = profile.getPrefix() + ":" + profile.getLocalName();
+ out.println("\nTesting profile " + name + "...");
+ Document baseLog = LogUtils.makeTestList(opts.getLogDir(), sessionId, profile.getExcludes());
+ Element baseTest = DomUtils.getElement(baseLog);
+ // out.println(DomUtils.serializeNode(baseLog));
+ out.print(TECore.INDENT + "Base tests from suite " + suite.getPrefix() + ":" + suite.getLocalName() + " ");
+ String summary = "Not complete";
+ if ("yes".equals(baseTest.getAttribute("complete"))) {
+ int baseResult = Integer.parseInt(baseTest.getAttribute("result"));
+ summary = getResultDescription(baseResult);
+ }
+ out.println(summary);
+ setIndentLevel(1);
+ String defaultResultName = profile.getDefaultResult();
+ defaultResult = defaultResultName.equals("BestPractice") ? BEST_PRACTICE : PASS;
+ out.println("\nExecuting profile " + name + " with defaultResult of " + defaultResultName + "...");
+ int result = execute_test(profile.getStartingTest().toString(), kvps, null);
+ out.print("Profile " + profile.getPrefix() + ":" + profile.getLocalName() + " ");
+ summary = getResultDescription(result);
+ out.println(summary);
+ }
+ else {
+ if (required) {
+ throw new Exception(
+ "Error: Profile " + profileName + " is not a valid profile for session " + sessionId + ".");
+ }
+ }
+ }
+
+ public XdmNode executeTemplate(TemplateEntry template, XdmNode params, XPathContext context) throws Exception {
+ if (stop) {
+ throw new Exception("Execution was stopped by the user.");
+ }
+ XsltExecutable executable = engine.loadExecutable(template, opts.getSourcesName());
+ XsltTransformer xt = executable.load();
+ XdmDestination dest = new XdmDestination();
+ xt.setDestination(dest);
+ if (template.usesContext() && context != null) {
+ xt.setSource((NodeInfo) context.getContextItem());
+ }
+ else {
+ xt.setSource(new StreamSource(new StringReader(" ")));
+ }
+ xt.setParameter(TECORE_QNAME, new ObjValue(this));
+ if (params != null) {
+ xt.setParameter(TEPARAMS_QNAME, params);
+ }
+ // test may set global verdict, e.g. by calling ctl:fail
+ if (LOGR.isLoggable(FINE)) {
+ LOGR.log(FINE, "Executing TemplateEntry {0}" + template.getQName());
+ }
+ xt.transform();
+ XdmNode ret = dest.getXdmNode();
+ if (ret != null && LOGR.isLoggable(FINE)) {
+ LOGR.log(FINE, "Output:\n" + ret.toString());
+ }
+ return ret;
+ }
+
+ static String getLabel(XdmNode n) {
+ String label = n.getAttributeValue(LABEL_QNAME);
+ if (label == null) {
+ XdmNode value = (XdmNode) n.axisIterator(Axis.CHILD).next();
+ XdmItem childItem = null;
+ try {
+ childItem = value.axisIterator(Axis.CHILD).next();
+ }
+ catch (Exception e) {
+ // Not an error
+ }
+ if (childItem == null) {
+ XdmSequenceIterator it = value.axisIterator(Axis.ATTRIBUTE);
+ if (it.hasNext()) {
+ label = it.next().getStringValue();
+ }
+ else {
+ label = "";
+ }
+ }
+ else if (childItem.isAtomicValue()) {
+ label = childItem.getStringValue();
+ }
+ else if (childItem instanceof XdmNode) {
+ XdmNode n2 = (XdmNode) childItem;
+ if (n2.getNodeKind() == XdmNodeKind.ELEMENT) {
+ label = "<" + n2.getNodeName().toString() + ">";
+ }
+ else {
+ label = n2.toString();
+ }
+ }
+ }
+ return label;
+ }
+
+ String getAssertionValue(String text, XdmNode paramsVar) {
+ if (text.indexOf("$") < 0) {
+ return text;
+ }
+ String newText = text;
+ XdmNode params = (XdmNode) paramsVar.axisIterator(Axis.CHILD).next();
+ XdmSequenceIterator it = params.axisIterator(Axis.CHILD);
+ while (it.hasNext()) {
+ XdmNode n = (XdmNode) it.next();
+ QName qname = n.getNodeName();
+ if (qname != null) {
+ String tagname = qname.getLocalName();
+ if (tagname.equals("param")) {
+ String name = n.getAttributeValue(LOCALNAME_QNAME);
+ String label = getLabel(n);
+ newText = StringUtils.replaceAll(newText, "{$" + name + "}", label);
+ }
+ }
+ }
+ newText = StringUtils.replaceAll(newText, "{$context}", contextLabel);
+ return newText;
+ }
+
+ static String getResultDescription(int result) {
+ if (result == CONTINUE) {
+ return MSG_CONTINUE;
+ }
+ else if (result == BEST_PRACTICE) {
+ return MSG_BEST_PRACTICE;
+ }
+ else if (result == PASS) {
+ return MSG_PASS;
+ }
+ else if (result == NOT_TESTED) {
+ return MSG_NOT_TESTED;
+ }
+ else if (result == SKIPPED) {
+ return MSG_SKIPPED;
+ }
+ else if (result == WARNING) {
+ return MSG_WARNING;
+ }
+ else if (result == INHERITED_FAILURE) {
+ return MSG_INHERITED_FAILURE;
+ }
+ else {
+ return MSG_FAIL;
+ }
+ }
+
+ /**
+ * Executes a test implemented as an XSLT template.
+ * @param test Provides information about the test (gleaned from an entry in the test
+ * suite index).
+ * @param params A node representing test run arguments.
+ * @param context A context in which the template is evaluated.
+ * @return An integer value indicating the test result.
+ * @throws Exception If any error arises while executing the test.
+ */
+ public int executeTest(TestEntry test, XdmNode params, XPathContext context) throws Exception {
+ testType = test.getType();
+ // It is possible to get here without setting testPath. Make sure it is set.
+ if (testPath == null)
+ testPath = opts.getSessionId();
+ defaultResult = test.getDefaultResult();
+ defaultResultName = (defaultResult == BEST_PRACTICE) ? "BestPractice" : "Pass";
+ Document oldPrevLog = prevLog;
+ if (opts.getMode() == Test.RESUME_MODE) {
+ prevLog = readLog();
+ }
+ else if (opts.getMode() == Test.REDO_FROM_CACHE_MODE) {
+ prevLog = readLog();
+ }
+ else {
+ prevLog = null;
+ }
+ String assertion = getAssertionValue(test.getAssertion(), params);
+ // seperate two sub test.
+ out.println(
+ "******************************************************************************************************************************");
+ out.print(indent + "Testing ");
+ out.print(test.getName() + " type " + test.getType());
+
+ // Check test is contain client test main layer or not
+
+ if (rootTestName != null && rootTestName.size() > 0) {
+ for (int i = 0; i < rootTestName.size(); i++) {
+ if ((test.getName()).contains(rootTestName.get(i))) {
+ methodCount = methodCount + 1;
+ }
+ }
+ }
+
+ out.print(" in " + getMode() + " with defaultResult " + defaultResultName + " ");
+ String testName = test.getName() + " type " + test.getType();
+ System.setProperty("TestName", testName);
+ out.println("(" + testPath + ")...");
+ if (opts.getLogDir() != null) {
+ String logDir = opts.getLogDir() + "/" + testPath.split("/")[0];
+ // Fortify Mod: Add TEPath validation of the log directory path
+ TEPath tpath = new TEPath(logDir);
+ // create log directory
+ if (tpath.isValid() && "True".equals(System.getProperty("Record"))) {
+ dirPath = new File(logDir + "/test_data");
+ if (!dirPath.exists()) {
+ if (!dirPath.mkdir()) {
+ System.out.println("Failed to create Error Log!");
+ }
+ }
+ }
+ }
+
+ // Delete files for coverage report.
+ if (reTestCount == 0) {
+ if (getMode().contains("Retest")) {
+ if (null != dirPath) {
+ if (dirPath.isDirectory()) {
+ File[] files = dirPath.listFiles();
+ if (files != null && files.length > 0) {
+ for (File aFile : files) {
+ aFile.delete();
+ }
+ }
+ dirPath.delete();
+ }
+ else {
+ dirPath.delete();
+ }
+ }
+ reTestCount = 1;
+ }
+ }
+ String oldIndent = indent;
+ indent += INDENT;
+ if (test.usesContext()) {
+ out.println(indent + "Context: " + test.getContext());
+ }
+ out.println(indent + "Assertion: " + assertion);
+ assertionMsz = assertion;
+ PrintWriter oldLogger = logger;
+ if (opts.getLogDir() != null) {
+ logger = createLog();
+ logger.println("");
+ logger.print("");
+ logger.println("" + StringUtils.escapeXML(assertion) + " ");
+ if (params != null) {
+ logger.println(params.toString());
+ pathURL = params.toString();
+ }
+ if (test.usesContext()) {
+ logger.print("");
+ logger.print("");
+ logger.print(test.getContext());
+ logger.print(" ");
+ logger.println(" ");
+ }
+ logger.println(" ");
+ logger.flush();
+ }
+
+ test.setResult(CONTINUE);
+ RecordTestResult recordTestResult = new RecordTestResult();
+ recordTestResult.storeStartTestDetail(test, dirPath);
+ try {
+ testStack.push(test);
+ executeTemplate(test, params, context);
+ if (test.getResult() == CONTINUE) {
+ test.setResult(defaultResult);
+ }
+ }
+ catch (SaxonApiException e) {
+ jlogger.log(SEVERE, e.getMessage());
+ DateFormat dateFormat = new SimpleDateFormat(Constants.YYYY_M_MDD_H_HMMSS);
+ Date date = new Date();
+ try {
+ String path = System.getProperty("PATH") + "/error_log";
+ File file = new File(path);
+ if (!file.exists()) {
+ if (!file.mkdir()) {
+ System.out.println("Failed to create Error Log!");
+ }
+ }
+ file = new File(path, "log.txt");
+ if (!file.exists()) {
+ try {
+ boolean fileCreated = file.createNewFile();
+ }
+ catch (IOException ioe) {
+ System.out.println("Error while creating empty file: " + ioe);
+ }
+ }
+ OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file, true),
+ StandardCharsets.UTF_8);
+ BufferedWriter fbw = new BufferedWriter(writer);
+ fbw.write(dateFormat.format(date) + " ERROR");
+ fbw.newLine();
+ fbw.write("Test Name : " + System.getProperty("TestName"));
+ fbw.newLine();
+ fbw.write("Failed to execute the extension function: ");
+ e.printStackTrace(new PrintWriter(fbw));
+ fbw.newLine();
+ fbw.close();
+ }
+ catch (IOException exep) {
+ System.out.println("Error: " + e.getMessage());
+ }
+ if (logger != null) {
+ logger.println(" ");
+ }
+ test.setResult(FAIL);
+ }
+ finally {
+ updateParentTestResult(test);
+ testStack.pop();
+ if (logger != null) {
+ logger.println(" ");
+
+ if (test.isConformanceClass()) {
+ logger.println(" ");
+ supportHtmlReport = true;
+ }
+ logger.println(" ");
+ logger.flush();
+ logger.close();
+ }
+ // Add missing info in the log.xml E.g. endtag ' or' endtest ' '.
+ if (opts.getLogDir() != null && testPath != null) {
+ String logDir = opts.getLogDir() + "/" + testPath;
+ addMissingInfo(logDir, test);
+ }
+ }
+ // Create node which contain all test detail.
+ if ("True".equals(System.getProperty("Record"))) {
+ mainRootElement.appendChild(RecordTestResult.getMethod());
+ }
+ assertionMsz = "";
+ pathURL = "";
+ messageTest = "";
+ logger = oldLogger;
+ prevLog = oldPrevLog;
+ indent = oldIndent;
+ DateFormat dateFormat = new SimpleDateFormat(Constants.YYYY_M_MDD_H_HMMSS);
+ Calendar cal = Calendar.getInstance();
+ out.println(indent + "Test " + test.getName() + " " + getResultDescription(test.getResult()));
+ recordTestResult.storeFinalTestDetail(test, dateFormat, cal, dirPath);
+ if (LOGR.isLoggable(FINE)) {
+ String msg = String.format("Executed test %s - Verdict: %s", test.getLocalName(),
+ getResultDescription(test.getResult()));
+ LOGR.log(FINE, msg);
+ }
+
+ return test.getResult();
+ }
+
+ public void addMissingInfo(String dir, TestEntry test) {
+
+ String logdir = dir + File.separator + "log.xml";
+ DocumentBuilderFactory dbf = null;
+ DocumentBuilder docBuilder = null;
+ Document doc = null;
+ File logfile = new File(logdir);
+ try {
+ dbf = DocumentBuilderFactory.newInstance();
+ docBuilder = dbf.newDocumentBuilder();
+ docBuilder.setErrorHandler(null);
+ doc = docBuilder.parse(logfile);
+
+ }
+ catch (Exception e) {
+
+ try {
+ FileWriter fw = new FileWriter(logdir, true);
+ BufferedWriter bw = new BufferedWriter(fw);
+ PrintWriter out = new PrintWriter(bw);
+ out.println("");
+ out.close();
+ bw.close();
+ doc = docBuilder.parse(logfile);
+ }
+ catch (Exception ex) {
+ throw new RuntimeException("Unable to update missing information in " + logdir);
+ }
+
+ }
+
+ NodeList nl = doc.getElementsByTagName("endtest");
+ if (nl.getLength() == 0) {
+
+ Element root = doc.getDocumentElement();
+ appendEndTestElement(test, doc, root);
+ appendConformanceClassElement(test, doc, root);
+ }
+
+ try {
+ DOMSource source = new DOMSource(doc);
+
+ TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ Transformer transformer = transformerFactory.newTransformer();
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ StreamResult result = new StreamResult(logfile);
+ transformer.transform(source, result);
+ }
+ catch (Exception ex) {
+ throw new RuntimeException("Unable to update missing information in " + logdir);
+ }
+
+ }
+
+ private void appendEndTestElement(TestEntry test, Document doc, Element root) {
+ Element endtest = doc.createElement("endtest");
+
+ Attr resultAttribute = doc.createAttribute("result");
+ resultAttribute.setValue(Integer.toString(test.getResult()));
+
+ endtest.setAttributeNode(resultAttribute);
+ root.appendChild(endtest);
+ }
+
+ private void appendConformanceClassElement(TestEntry test, Document doc, Element root) {
+ if (test.isConformanceClass()) {
+ Element conformanceClass = doc.createElement("conformanceClass");
+
+ Attr nameAttribute = doc.createAttribute("name");
+ nameAttribute.setValue(test.getLocalName());
+
+ Attr isBasicAttribute = doc.createAttribute("isBasic");
+ isBasicAttribute.setValue(Boolean.toString(test.isBasic()));
+
+ Attr resultAttribute = doc.createAttribute("result");
+ resultAttribute.setValue(Integer.toString(test.getResult()));
+
+ conformanceClass.setAttributeNode(nameAttribute);
+ conformanceClass.setAttributeNode(isBasicAttribute);
+ conformanceClass.setAttributeNode(resultAttribute);
+ root.appendChild(conformanceClass);
+ }
+
+ }
+
+ /**
+ * Runs a subtest as directed by a <ctl:call-test> instruction.
+ * @param context The context in which the subtest is executed.
+ * @param localName The [local name] of the subtest.
+ * @param namespaceURI The [namespace name] of the subtest.
+ * @param params A NodeInfo object containing test parameters.
+ * @param callId A node identifier used to build a file path reference for the test
+ * results.
+ * @throws Exception If an error occcurs while executing the test.
+ */
+ public synchronized void callTest(XPathContext context, String localName, String namespaceURI, NodeInfo params,
+ String callId) throws Exception {
+ String key = "{" + namespaceURI + "}" + localName;
+ TestEntry test = index.getTest(key);
+ if (logger != null) {
+ logger.println(" ");
+ logger.flush();
+ }
+ if (opts.getMode() == Test.RESUME_MODE) {
+ Document doc = LogUtils.readLog(opts.getLogDir(), testPath + "/" + callId);
+ int result = LogUtils.getResultFromLog(doc);
+ if (result == CONTINUE) {
+ throw new IllegalStateException(
+ "Error: 'continue' is not allowed when a test is called using 'call-test' instruction");
+ }
+ else {
+ out.println(indent + "Test " + test.getName() + " " + getResultDescription(result));
+ test.setResult(result);
+ updateParentTestResult(test);
+ return;
+ }
+ }
+
+ String oldTestPath = testPath;
+ testPath += "/" + callId;
+ int result = CONTINUE;
+ try {
+ result = executeTest(test, S9APIUtils.makeNode(params), context);
+ }
+ catch (Exception e) {
+
+ }
+ finally {
+ testPath = oldTestPath;
+ }
+ if (result == CONTINUE) {
+ throw new IllegalStateException(
+ "Error: 'continue' is not allowed when a test is called using 'call-test' instruction");
+ }
+ }
+
+ /**
+ * Modifies the result of the parent test according to the result of the current test.
+ * The parent test will be 'tainted' with an inherited failure if (a) a subtest
+ * failed, or (b) a required subtest was skipped.
+ * @param currTest The TestEntry for the current test.
+ */
+ private void updateParentTestResult(TestEntry currTest) {
+ TestEntry parentTest = getParentTest();
+ if (null == parentTest)
+ return;
+ if (LOGR.isLoggable(FINE)) {
+ LOGR.log(FINE, "Entered setParentTestResult with TestEntry {0} (result={1})",
+ new Object[] { currTest.getQName(), currTest.getResult() });
+ LOGR.log(FINE, "Parent TestEntry is {0} (result={1})",
+ new Object[] { parentTest.getQName(), parentTest.getResult() });
+ }
+ switch (currTest.getResult()) {
+ case FAIL:
+ // fall through
+ case INHERITED_FAILURE:
+ parentTest.setResult(INHERITED_FAILURE);
+ break;
+ case SKIPPED:
+ if (currTest.getType().equalsIgnoreCase("Mandatory")) {
+ parentTest.setResult(INHERITED_FAILURE);
+ }
+ break;
+ default:
+ parentTest.setResult(Integer.max(currTest.getResult(), parentTest.getResult()));
+ break;
+ }
+ }
+
+ /*
+ * ctl:repeat-test is not documented and is not used in any
+ * https://github.com/opengeospatial ETS
+ */
+ /*
+ * public void repeatTest(XPathContext context, String localName, String NamespaceURI,
+ * NodeInfo params, String callId, int count, int pause) throws Exception { String key
+ * = "{" + NamespaceURI + "}" + localName; TestEntry test = index.getTest(key);
+ *
+ * if (logger != null) { logger.println(" "); logger.flush(); } if (opts.getMode() == Test.RESUME_MODE) { Document doc
+ * = LogUtils.readLog(opts.getLogDir(), testPath + "/" + callId); int result =
+ * LogUtils.getResultFromLog(doc); if (result >= 0) { out.println(indent + "Test " +
+ * test.getName() + " " + getResultDescription(result)); if (result == WARNING) {
+ * warning(); } else if (result != PASS) { inheritedFailure(); } return; } } int
+ * oldResult = verdict; String oldTestPath = testPath; testPath += "/" + callId;
+ *
+ * for (int i = 0; i < count; i++) { executeTest(test, S9APIUtils.makeNode(params),
+ * context); testPath = oldTestPath; if (verdict == FAIL && oldResult != FAIL) { // If
+ * the child result was FAIL and parent hasn't directly // failed, // set parent
+ * result to INHERITED_FAILURE verdict = INHERITED_FAILURE;
+ *
+ * return; } else if (verdict == CONTINUE) { //
+ * System.out.println("Pausing for..."+pause); if (pause > 0 && i < count - 1) {
+ *
+ * try {
+ *
+ * Thread.sleep(pause); } catch (Exception e) { e.printStackTrace(); } }
+ *
+ * } else if (verdict <= oldResult) { // Restore parent result if the child results
+ * aren't worse verdict = oldResult; return;
+ *
+ * } } verdict = FAIL; if (oldResult != FAIL) { // If the child result was FAIL and
+ * parent hasn't directly failed, // set parent result to INHERITED_FAILURE verdict =
+ * INHERITED_FAILURE; }
+ *
+ * }
+ */
+
+ public NodeInfo executeXSLFunction(XPathContext context, FunctionEntry fe, NodeInfo params) throws Exception {
+ String oldFnPath = fnPath;
+ CRC32 crc = new CRC32();
+ crc.update((fe.getPrefix() + fe.getId()).getBytes());
+ fnPath += Long.toHexString(crc.getValue()) + "/";
+ XdmNode n = executeTemplate(fe, S9APIUtils.makeNode(params), context);
+ fnPath = oldFnPath;
+ if (n == null) {
+ return null;
+ }
+ return n.getUnderlyingNode();
+ }
+
+ public Object callFunction(XPathContext context, String localName, String namespaceURI, NodeInfo params)
+ throws Exception {
+ // System.out.println("callFunction {" + NamespaceURI + "}" +
+ // localName);
+ String key = "{" + namespaceURI + "}" + localName;
+ List functions = index.getFunctions(key);
+ Node paramsNode = NodeOverNodeInfo.wrap(params);
+ List paramElements = DomUtils.getElementsByTagName(paramsNode, "param");
+ for (FunctionEntry fe : functions) {
+ if (!fe.isJava()) {
+ boolean valid = true;
+ for (Element el : paramElements) {
+ String uri = el.getAttribute("namespace-uri");
+ String name = el.getAttribute("local-name");
+ String prefix = el.getAttribute("prefix");
+ javax.xml.namespace.QName qname = new javax.xml.namespace.QName(uri, name, prefix);
+ if (!fe.getParams().contains(qname)) {
+ valid = false;
+ break;
+ }
+ }
+ if (valid) {
+ if (opts.getMode() == Test.DOC_MODE) {
+ if (fnCallStack.contains(key)) {
+ return null;
+ }
+ else {
+ fnCallStack.add(key);
+ Object result = executeXSLFunction(context, fe, params);
+ fnCallStack.pop();
+ return result;
+ }
+ }
+ else {
+ return executeXSLFunction(context, fe, params);
+ }
+ }
+ }
+ }
+
+ if (opts.getMode() == Test.DOC_MODE) {
+ return null;
+ }
+
+ for (FunctionEntry fe : functions) {
+ if (fe.isJava()) {
+ int argCount = paramElements.size();
+ if (fe.getMinArgs() >= argCount && fe.getMaxArgs() <= argCount) {
+ TEClassLoader cl = engine.getClassLoader(opts.getSourcesName());
+ Method method = Misc.getMethod(fe.getClassName(), fe.getMethod(), cl, argCount);
+ Class>[] types = method.getParameterTypes();
+ Object[] args = new Object[argCount];
+ for (int i = 0; i < argCount; i++) {
+ Element el = DomUtils.getElementByTagName(paramElements.get(i), "value");
+ if (types[i].equals(String.class)) {
+ Map attrs = DomUtils.getAttributes(el);
+ if (attrs.size() > 0) {
+ args[i] = attrs.values().iterator().next();
+ }
+ else {
+ args[i] = el.getTextContent();
+ }
+ }
+ else if (types[i].toString().equals("char")) {
+ args[i] = el.getTextContent().charAt(0);
+ }
+ else if (types[i].toString().equals("boolean")) {
+ args[i] = Boolean.parseBoolean(el.getTextContent());
+ }
+ else if (types[i].toString().equals("byte")) {
+ args[i] = Byte.parseByte(el.getTextContent());
+ }
+ else if (types[i].toString().equals("short")) {
+ args[i] = Short.parseShort(el.getTextContent());
+ }
+ else if (types[i].toString().equals("int")) {
+ args[i] = Integer.parseInt(el.getTextContent());
+ }
+ else if (types[i].toString().equals("long")) {
+ args[i] = Long.parseLong(el.getTextContent());
+ }
+ else if (types[i].toString().equals("float")) {
+ args[i] = Float.parseFloat(el.getTextContent());
+ }
+ else if (types[i].toString().equals("double")) {
+ args[i] = Double.parseDouble(el.getTextContent());
+ }
+ else if (Document.class.isAssignableFrom(types[i])) {
+ args[i] = DomUtils.createDocument(DomUtils.getChildElement(el));
+ }
+ else if (NodeList.class.isAssignableFrom(types[i])) {
+ args[i] = el.getChildNodes();
+ }
+ else if (Node.class.isAssignableFrom(types[i])) {
+ args[i] = el.getFirstChild();
+ }
+ else {
+ throw new Exception(
+ "Error: Function " + key + " uses unsupported Java type " + types[i].toString());
+ }
+ }
+ try {
+ Object instance = null;
+ if (fe.isInitialized()) {
+ // String instkey = fe.getId() + "," +
+ // Integer.toString(fe.getMinArgs()) + "," +
+ // Integer.toString(fe.getMaxArgs());
+ instance = getFunctionInstance(fe.hashCode());
+ if (instance == null) {
+ try {
+ instance = Misc.makeInstance(fe.getClassName(), fe.getClassParams(), cl);
+ putFunctionInstance(fe.hashCode(), instance);
+ }
+ catch (Exception e) {
+ throw new XPathException(e);
+ }
+ }
+ }
+ return method.invoke(instance, args);
+ }
+ catch (java.lang.reflect.InvocationTargetException e) {
+ Throwable cause = e.getCause();
+ String msg = "Error invoking function " + fe.getId() + "\n" + cause.getClass().getName();
+ if (cause.getMessage() != null) {
+ msg += ": " + cause.getMessage();
+ }
+ jlogger.log(SEVERE, "InvocationTargetException", e);
+
+ throw new Exception(msg, cause);
+ }
+ }
+ }
+ }
+ throw new Exception("No function {" + namespaceURI + "}" + localName + " with a compatible signature.");
+ }
+
+ public void _continue() {
+ testStack.peek().setResult(CONTINUE);
+ }
+
+ public void bestPractice() {
+ if (testStack.peek().getResult() < BEST_PRACTICE) {
+ testStack.peek().setResult(BEST_PRACTICE);
+ }
+ }
+
+ public void notTested() {
+ if (testStack.peek().getResult() < NOT_TESTED) {
+ testStack.peek().setResult(NOT_TESTED);
+ }
+ }
+
+ public void skipped() {
+ if (testStack.peek().getResult() < SKIPPED) {
+ testStack.peek().setResult(SKIPPED);
+ }
+ }
+
+ public void pass() {
+ if (testStack.peek().getResult() < PASS) {
+ testStack.peek().setResult(PASS);
+ }
+ }
+
+ public void warning() {
+ if (testStack.peek().getResult() < WARNING) {
+ testStack.peek().setResult(WARNING);
+ }
+ }
+
+ public void inheritedFailure() {
+ if (testStack.peek().getResult() < INHERITED_FAILURE) {
+ testStack.peek().setResult(INHERITED_FAILURE);
+ }
+ }
+
+ public void fail() {
+ testStack.peek().setResult(FAIL);
+ }
+
+ public String getResult() {
+ return getResultDescription(testStack.getLast().getResult());
+ }
+
+ public String getMode() {
+ return Test.getModeName(opts.getMode());
+ }
+
+ public void setContextLabel(String label) {
+ contextLabel = label;
+ }
+
+ public String getFormHtml() {
+ return formHtml;
+ }
+
+ public void setFormHtml(String html) {
+ this.formHtml = html;
+ }
+
+ public Document getFormResults() {
+ return formResults;
+ }
+
+ public void setFormResults(Document doc) {
+ try {
+ StringWriter sw = new StringWriter();
+ // Fortify Mod: prevent external entity injection
+ TransformerFactory tf = TransformerFactory.newInstance();
+ tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ Transformer transformer = tf.newTransformer();
+ // End Fortify Mod
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
+ transformer.transform(new DOMSource(doc), new StreamResult(sw));
+ if (userInputs == null) {
+ userInputs = doc;
+ }
+ LOGR.info("Setting form results:\n " + sw.toString());
+ }
+ catch (Exception e) {
+ LOGR.log(SEVERE, "Failed to log the form results", e);
+ }
+ this.formResults = doc;
+ }
+
+ public Map getFormParsers() {
+ return formParsers;
+ }
+
+ public Document readLog() throws Exception {
+ return LogUtils.readLog(opts.getLogDir(), testPath);
+ }
+
+ public PrintWriter createLog() throws Exception {
+ return LogUtils.createLog(opts.getLogDir(), testPath);
+ }
+
+ // Get a File pointer to a file reference (in XML)
+ public static File getFile(NodeList fileNodes) {
+ File file = null;
+ for (int i = 0; i < fileNodes.getLength(); i++) {
+ Element e = (Element) fileNodes.item(i);
+ String type = e.getAttribute("type");
+
+ try {
+ // URL, File, or Resource
+ if (type.equals("url")) {
+ URL url = new URL(e.getTextContent());
+ file = new File(url.toURI());
+ }
+ else if (type.equals("file")) {
+ file = new File(e.getTextContent());
+ }
+ else if (type.equals("resource")) {
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ file = new File(cl.getResource(e.getTextContent()).getFile());
+ }
+ else {
+ System.out.println("Incorrect file reference: Unknown type!");
+ }
+ }
+ catch (Exception exception) {
+ System.err.println("Error getting file. " + exception.getMessage());
+ jlogger.log(SEVERE, "Error getting file. " + exception.getMessage(), e);
+
+ return null;
+ }
+ }
+ return file;
+ }
+
+ // BEGIN SOAP SUPPORT
+ public NodeList soap_request(Document ctlRequest, String id) throws Throwable {
+ Element request = (Element) ctlRequest.getElementsByTagNameNS(Test.CTL_NS, "soap-request").item(0);
+ if (opts.getMode() == Test.RESUME_MODE && prevLog != null) {
+ for (Element request_e : DomUtils.getElementsByTagName(prevLog, "soap-request")) {
+ if (request_e.getAttribute("id").equals(fnPath + id)) {
+ logger.println(DomUtils.serializeNode(request_e));
+ logger.flush();
+ Element response_e = DomUtils.getElementByTagName(request_e, "response");
+ Element content_e = DomUtils.getElementByTagName(response_e, "content");
+ return content_e.getChildNodes();
+ // return DomUtils.getChildElement(content_e);
+ }
+ }
+ }
+
+ String logTag = "\n";
+ logTag += DomUtils.serializeNode(request) + "\n";
+ // if (logger != null) {
+ // logger.println("");
+ // logger.println(DomUtils.serializeNode(request));
+ // }
+ Exception ex = null;
+ Element response = null;
+ Element parserInstruction = null;
+ NodeList nl = request.getChildNodes();
+ long elapsedTime = 0;
+ for (int i = 0; i < nl.getLength(); i++) {
+ Node n = nl.item(i);
+ if (n.getNodeType() == Node.ELEMENT_NODE && !n.getNamespaceURI().equals(CTL_NS)) {
+ parserInstruction = (Element) n;
+ }
+ }
+ try {
+ Date before = new Date();
+ URLConnection uc = build_soap_request(request);
+ response = parse(uc, parserInstruction);
+ Date after = new Date();
+ elapsedTime = after.getTime() - before.getTime();
+
+ // Adding the exchange time in the response as comment the format is
+ // the following
+ //
+ // the comment is included in the first tag of the response
+ // SOAP:Envelope in case a SOAP message is returned the specific
+ // interface tag if a SOAP parser is applied
+ Element content = DomUtils.getElementByTagName(response, "content");
+ if (content != null) {
+ nl = content.getChildNodes();
+ for (int i = 0; i < nl.getLength(); i++) {
+ Node n = nl.item(i);
+ if (n.getNodeType() == Node.ELEMENT_NODE) {
+ Document doc;
+ doc = response.getOwnerDocument();
+ Comment comm = doc.createComment("Response received in [" + elapsedTime + "] milliseconds");
+ n.appendChild(comm);
+ }
+ }
+ }
+
+ logTag += DomUtils.serializeNode(response) + "\n";
+ jlogger.log(FINE, DomUtils.serializeNode(response));
+ }
+ catch (Exception e) {
+ ex = e;
+ }
+ logTag += "";
+ logTag += " ";
+ if (logger != null) {
+ logger.println(logTag);
+ logger.flush();
+ }
+ if (ex == null) {
+ Element parser = DomUtils.getElementByTagName(response, "parser");
+ if (parser != null) {
+ String text = parser.getTextContent();
+ if (text.length() > 0) {
+ out.println(parser.getTextContent());
+ }
+ }
+ Element content = DomUtils.getElementByTagName(response, "content");
+ return content.getChildNodes();
+ }
+ else {
+ throw ex;
+ }
+ }
+
+ /**
+ * Create SOAP request, sends it and return an URL Connection ready to be parsed.
+ * @param xml the soap-request node (from CTL)
+ * @return The URL Connection
+ * @throws Exception the exception
+ *
+ * <soap-request version="1.1|1.2" charset="UTF-8">
+ * <url>http://blah</url> <action>Some-URI</action>
+ * <headers> <header MutUnderstand="true" rely="true" role="http://etc">
+ * <t:Transaction xmlns:t="some-URI" >5</t:Transaction> </header>
+ * </headers> <body> <m:GetLastTradePrice xmlns:m="Some-URI">
+ * <symbol>DEF</symbol> </m:GetLastTradePrice> </body>
+ * <parsers:SOAPParser return="content"> <parsers:XMLValidatingParser>
+ * <parsers:schemas> <parsers:schema
+ * type="url">http://blah/schema.xsd</parsers:schema>
+ * </parsers:schemas> </parsers:XMLValidatingParser>
+ * </parsers:SOAPParser> </soap-request>
+ */
+ static public URLConnection build_soap_request(Node xml) throws Exception {
+ String sUrl = null;
+ String method = "POST";
+ String charset = ((Element) xml).getAttribute("charset").isEmpty() ? ((Element) xml).getAttribute("charset")
+ : "UTF-8";
+ String version = ((Element) xml).getAttribute("version");
+ String action = "";
+ String contentType = "";
+ Element body = null;
+
+ // Read in the test information (from CTL)
+ NodeList nl = xml.getChildNodes();
+ for (int i = 0; i < nl.getLength(); i++) {
+ Node n = nl.item(i);
+ if (n.getNodeType() == Node.ELEMENT_NODE) {
+ if (n.getLocalName().equals("url")) {
+ sUrl = n.getTextContent();
+ }
+ else if (n.getLocalName().equals("action")) {
+ action = n.getTextContent();
+ }
+ // else if (n.getLocalName().equals("header")) {
+ // header = (org.w3c.dom.Element) n;
+ /*
+ * }
+ */else if (n.getLocalName().equals("body")) {
+ body = (org.w3c.dom.Element) n;
+ }
+ }
+ }
+
+ // Get the list of the header blocks needed to build the SOAP Header
+ // section
+ List headerBloks = DomUtils.getElementsByTagNameNS(xml, CTL_NS, HEADER_BLOCKS);
+ // Open the URLConnection
+ URLConnection uc = new URL(sUrl).openConnection();
+ if (uc instanceof HttpURLConnection) {
+ ((HttpURLConnection) uc).setRequestMethod(method);
+ }
+
+ uc.setDoOutput(true);
+ byte[] bytes = null;
+
+ // SOAP POST
+ bytes = SoapUtils.getSoapMessageAsByte(version, headerBloks, body, charset);
+ // System.out.println("SOAP MESSAGE " + new String(bytes));
+
+ uc.setRequestProperty("User-Agent", "Team Engine 1.2");
+ uc.setRequestProperty("Cache-Control", "no-cache");
+ uc.setRequestProperty("Pragma", "no-cache");
+ uc.setRequestProperty("charset", charset);
+ uc.setRequestProperty("Content-Length", Integer.toString(bytes.length));
+
+ if (version.equals(SOAP_V_1_1)) {
+ // Handle HTTP binding for SOAP 1.1
+ // uc.setRequestProperty("Accept", "application/soap+xml");
+ uc.setRequestProperty("Accept", "text/xml");
+ uc.setRequestProperty("SOAPAction", action);
+ contentType = "text/xml";
+ if (!charset.isEmpty()) {
+ contentType = contentType + "; charset=" + charset;
+ }
+ uc.setRequestProperty("Content-Type", contentType);
+ }
+ else {
+ // Handle HTTP binding for SOAP 1.2
+ uc.setRequestProperty("Accept", "application/soap+xml");
+ contentType = "application/soap+xml";
+ if (!charset.isEmpty()) {
+ contentType = contentType + "; charset=" + charset;
+ }
+ if (!action.isEmpty()) {
+ contentType = contentType + "; action=" + action;
+ }
+ uc.setRequestProperty("Content-Type", contentType);
+ }
+ OutputStream os = uc.getOutputStream();
+ os.write(bytes);
+ return uc;
+
+ }
+
+ /**
+ * Implements ctl:request. Create and send an HTTP request then return an
+ * HttpResponse. Invoke any specified parsers on the response to validate it, change
+ * its format or derive specific information from it.
+ */
+ public NodeList request(Document ctlRequest, String id) throws Throwable {
+ Element request = (Element) ctlRequest.getElementsByTagNameNS(Test.CTL_NS, "request").item(0);
+ if (opts.getMode() == Test.RESUME_MODE && prevLog != null) {
+ for (Element request_e : DomUtils.getElementsByTagName(prevLog, "request")) {
+ if (request_e.getAttribute("id").equals(fnPath + id)) {
+ logger.println(DomUtils.serializeNode(request_e));
+ logger.flush();
+ Element response_e = DomUtils.getElementByTagName(request_e, "response");
+ Element content_e = DomUtils.getElementByTagName(response_e, "content");
+ return content_e.getChildNodes();
+ // return DomUtils.getChildElement(content_e);
+ }
+ }
+ }
+
+ String logTag = "\n";
+ logTag += DomUtils.serializeNode(request) + "\n";
+ // if (logger != null) {
+ // logger.println("");
+ // logger.println(DomUtils.serializeNode(request));
+ // }
+ long elapsedTime = 0;
+ Exception ex = null;
+ Element response = null;
+ Element parserInstruction = null;
+ NodeList nl = request.getChildNodes();
+ for (int i = 0; i < nl.getLength(); i++) {
+ Node n = nl.item(i);
+ if (n.getNodeType() == Node.ELEMENT_NODE && !n.getNamespaceURI().equals(CTL_NS)) {
+ parserInstruction = (Element) n;
+ }
+ }
+
+ try {
+ Date before = new Date();
+ URLConnection uc = build_request(request);
+ response = parse(uc, parserInstruction);
+ Date after = new Date();
+ elapsedTime = after.getTime() - before.getTime();
+
+ // Adding the exchange time in the response as comment the format is
+ // the following
+ //
+ // the comment is included in the first tag of the response
+ Element content = DomUtils.getElementByTagName(response, "content");
+ if (content != null) {
+ nl = content.getChildNodes();
+ for (int i = 0; i < nl.getLength(); i++) {
+ Node n = nl.item(i);
+ if (n.getNodeType() == Node.ELEMENT_NODE) {
+ Document doc;
+ doc = response.getOwnerDocument();
+ Comment comm = doc.createComment("Response received in [" + elapsedTime + "] milliseconds");
+ n.appendChild(comm);
+ }
+ }
+ }
+
+ logTag += DomUtils.serializeNode(response) + "\n";
+ // if (logger != null) {
+ // logger.println(DomUtils.serializeNode(response));
+ // }
+ }
+ catch (Exception e) {
+ ex = e;
+ }
+ // logTag += "";
+ logTag += " ";
+ if (logger != null) {
+ // logger.println(" ");
+ logger.println(logTag);
+ logger.flush();
+ }
+ if (ex == null) {
+ Element parser = DomUtils.getElementByTagName(response, "parser");
+ if (parser != null) {
+ String text = parser.getTextContent();
+ if (text.length() > 0) {
+ out.println(parser.getTextContent());
+ }
+ }
+ Element content = DomUtils.getElementByTagName(response, "content");
+ return content.getChildNodes();
+ }
+ else {
+ throw ex;
+ }
+ }
+
+ /**
+ * Submits a request to some HTTP endpoint using the given request details.
+ * @param xml An ctl:request element.
+ * @return A URLConnection object representing an open communications link.
+ * @throws Exception If any error occurs while submitting the request or establishing
+ * a conection.
+ */
+ public URLConnection build_request(Node xml) throws Exception {
+ Node body = null;
+ ArrayList headers = new ArrayList<>();
+ ArrayList parts = new ArrayList<>();
+ String sUrl = null;
+ String sParams = "";
+ String method = "GET";
+ String charset = "UTF-8";
+ boolean multipart = false;
+
+ // Read in the test information (from CTL)
+ NodeList nl = xml.getChildNodes();
+ for (int i = 0; i < nl.getLength(); i++) {
+ Node n = nl.item(i);
+ if (n.getNodeType() == Node.ELEMENT_NODE) {
+ if (n.getLocalName().equals("url")) {
+ sUrl = n.getTextContent();
+ }
+ else if (n.getLocalName().equals("method")) {
+ method = n.getTextContent().toUpperCase();
+ }
+ else if (n.getLocalName().equals("header")) {
+ headers.add(new String[] { ((Element) n).getAttribute("name"), n.getTextContent() });
+ }
+ else if (n.getLocalName().equals("param")) {
+ if (sParams.length() > 0) {
+ sParams += "&";
+ }
+ sParams += ((Element) n).getAttribute("name") + "=" + n.getTextContent();
+ // WARNING! May break some existing test suites
+ // + URLEncoder.encode(n.getTextContent(), "UTF-8");
+ }
+ else if (n.getLocalName().equals("dynamicParam")) {
+ String name = null;
+ String val = null;
+ NodeList dpnl = n.getChildNodes();
+ for (int j = 0; j < dpnl.getLength(); j++) {
+ Node dpn = dpnl.item(j);
+ if (dpn.getNodeType() == Node.ELEMENT_NODE) {
+ if (dpn.getLocalName().equals("name")) {
+ name = dpn.getTextContent();
+ }
+ else if (dpn.getLocalName().equals("value")) {
+ val = dpn.getTextContent();
+ // val =
+ // URLEncoder.encode(dpn.getTextContent(),"UTF-8");
+ }
+ }
+ }
+ if (name != null && val != null) {
+ if (sParams.length() > 0)
+ sParams += "&";
+ sParams += name + "=" + val;
+ }
+ }
+ else if (n.getLocalName().equals("body")) {
+ body = n;
+ }
+ else if (n.getLocalName().equals("part")) {
+ parts.add(n);
+ }
+ }
+ }
+
+ // Complete GET KVP syntax
+ // Fortify Mod: Added check for null sUrl. Shouldn't happen but ----
+ // if (method.equals("GET") && sParams.length() > 0) {
+ if (method.equals("GET") && sParams.length() > 0 && sUrl != null) {
+ if (sUrl.indexOf("?") == -1) {
+ sUrl += "?";
+ }
+ else if (!sUrl.endsWith("?") && !sUrl.endsWith("&")) {
+ sUrl += "&";
+ }
+ sUrl += sParams;
+ }
+
+ // System.out.println(sUrl);
+ TransformerFactory tf = TransformerFactory.newInstance();
+ // Fortify Mod: prevent external entity injection
+ tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ Transformer t = tf.newTransformer();
+
+ // Open the URLConnection
+ URLConnection uc = new URL(sUrl).openConnection();
+ if (uc instanceof HttpURLConnection) {
+ HttpURLConnection httpUc = (HttpURLConnection) uc;
+ httpUc.setRequestMethod(method);
+ boolean redirect = checkForRedirect(httpUc);
+ if (redirect) {
+ String redirectURL = httpUc.getHeaderField("Location");
+ uc = new URL(redirectURL).openConnection();
+ if (uc instanceof HttpURLConnection) {
+ ((HttpURLConnection) uc).setRequestMethod(method);
+ }
+ }
+ else {
+ // https://github.com/opengeospatial/teamengine/issues/553
+ // need to re-connect, as the check for redirects already opened the
+ // connection
+ uc = new URL(sUrl).openConnection();
+ }
+ }
+
+ // POST setup (XML payload and header information)
+ if (method.equals("POST") || method.equals("PUT")) {
+ uc.setDoOutput(true);
+ byte[] bytes = null;
+ String mime = null;
+
+ // KVP over POST
+ if (body == null) {
+ bytes = sParams.getBytes();
+ mime = "application/x-www-form-urlencoded";
+ } // XML POST
+ else {
+ String bodyContent = "";
+
+ NodeList children = body.getChildNodes();
+ for (int i = 0; i < children.getLength(); i++) {
+ if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ t.transform(new DOMSource(children.item(i)), new StreamResult(baos));
+ bodyContent = baos.toString();
+ bytes = baos.toByteArray();
+
+ if (mime == null) {
+ mime = "application/xml; charset=" + charset;
+ }
+ break;
+ }
+ }
+ if (bytes == null) {
+ bytes = body.getTextContent().getBytes();
+ mime = "text/plain";
+ }
+
+ // Add parts if present
+ if (parts.size() > 0) {
+ String prefix = "--";
+ String boundary = "7bdc3bba-e2c9-11db-8314-0800200c9a66";
+ String newline = "\r\n";
+ multipart = true;
+
+ // Set main body and related headers
+ ByteArrayOutputStream contentBytes = new ByteArrayOutputStream();
+ String bodyPart = prefix + boundary + newline;
+ bodyPart += "Content-Type: " + mime + newline + newline;
+ bodyPart += bodyContent;
+ writeBytes(contentBytes, bodyPart.getBytes(charset));
+
+ // Append all parts to the original body, seperated by the
+ // boundary sequence
+ for (int i = 0; i < parts.size(); i++) {
+ Element currentPart = (Element) parts.get(i);
+ String cid = currentPart.getAttribute("cid");
+ if (cid.indexOf("cid:") != -1) {
+ cid = cid.substring(cid.indexOf("cid:") + "cid:".length());
+ }
+ String contentType = currentPart.getAttribute("content-type");
+
+ // Default encodings and content-type
+ if (contentType.equals("application/xml")) {
+ contentType = "application/xml; charset=" + charset;
+ }
+ if (contentType == null || contentType.isEmpty()) {
+ contentType = "application/octet-stream";
+ }
+
+ // Set headers for each part
+ String partHeaders = newline + prefix + boundary + newline;
+ partHeaders += "Content-Type: " + contentType + newline;
+ partHeaders += "Content-ID: <" + cid + ">" + newline + newline;
+ writeBytes(contentBytes, partHeaders.getBytes(charset));
+
+ // Get the fileName, if it exists
+ NodeList files = currentPart.getElementsByTagNameNS(CTL_NS, "file");
+
+ // Get part for a specified file
+ if (files.getLength() > 0) {
+ File contentFile = getFile(files);
+
+ InputStream is = new FileInputStream(contentFile);
+ long length = contentFile.length();
+ byte[] fileBytes = new byte[(int) length];
+ int offset = 0;
+ int numRead = 0;
+ while (offset < fileBytes.length
+ && (numRead = is.read(fileBytes, offset, fileBytes.length - offset)) >= 0) {
+ offset += numRead;
+ }
+ is.close();
+
+ writeBytes(contentBytes, fileBytes);
+ } // Get part from inline data (or xi:include)
+ else {
+ // Text
+ if (currentPart.getFirstChild() instanceof Text) {
+ writeBytes(contentBytes, currentPart.getTextContent().getBytes(charset));
+ } // XML
+ else {
+ writeBytes(contentBytes,
+ DomUtils.serializeNode(currentPart.getFirstChild()).getBytes(charset));
+ }
+ }
+ }
+
+ String endingBoundary = newline + prefix + boundary + prefix + newline;
+ writeBytes(contentBytes, endingBoundary.getBytes(charset));
+
+ bytes = contentBytes.toByteArray();
+
+ // Global Content-Type and Length to be added after the
+ // parts have been parsed
+ mime = "multipart/related; type=\"" + mime + "\"; boundary=\"" + boundary + "\"";
+
+ // String contentsString = new String(bytes, charset);
+ // System.out.println("Content-Type: "+mime+"\n"+contentsString);
+ }
+ }
+
+ // Set headers
+ if (body != null) {
+ String mid = ((Element) body).getAttribute("mid");
+ if (mid != null && !mid.isEmpty()) {
+ if (mid.indexOf("mid:") != -1) {
+ mid = mid.substring(mid.indexOf("mid:") + "mid:".length());
+ }
+ uc.setRequestProperty("Message-ID", "<" + mid + ">");
+ }
+ }
+ uc.setRequestProperty("Content-Type", mime);
+ uc.setRequestProperty("Content-Length", Integer.toString(bytes.length));
+
+ // Enter the custom headers (overwrites the defaults if present)
+ for (int i = 0; i < headers.size(); i++) {
+ String[] header = headers.get(i);
+ if (multipart && header[0].toLowerCase().equals("content-type")) {
+ }
+ else {
+ uc.setRequestProperty(header[0], header[1]);
+ }
+ }
+
+ OutputStream os = uc.getOutputStream();
+ os.write(bytes);
+ }
+ else {
+ for (int i = 0; i < headers.size(); ++i) {
+ String[] header = headers.get(i);
+ uc.setRequestProperty(header[0], header[1]);
+ }
+ }
+
+ return uc;
+ }
+
+ public static void writeBytes(ByteArrayOutputStream baos, byte[] bytes) {
+ baos.write(bytes, 0, bytes.length);
+ }
+
+ public Element parse(Document parse_instruction, String xsl_version) throws Throwable {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setNamespaceAware(true);
+ // Fortify Mod: prevent external entity injection
+ dbf.setExpandEntityReferences(false);
+ DocumentBuilder db = dbf.newDocumentBuilder();
+
+ TransformerFactory tf = TransformerFactory.newInstance();
+ // Fortify Mod: prevent external entity injection
+ tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ Transformer t = null;
+ Node content = null;
+ Document parser_instruction = null;
+
+ Element parse_element = (Element) parse_instruction.getElementsByTagNameNS(CTL_NS, "parse").item(0);
+
+ NodeList children = parse_element.getChildNodes();
+ for (int i = 0; i < children.getLength(); i++) {
+ if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
+ Element e = (Element) children.item(i);
+ if (e.getNamespaceURI().equals(XSL_NS) && e.getLocalName().equals("output")) {
+ Document doc = db.newDocument();
+ Element transform = doc.createElementNS(XSL_NS, "transform");
+ transform.setAttribute("version", xsl_version);
+ doc.appendChild(transform);
+ Element output = doc.createElementNS(XSL_NS, "output");
+ NamedNodeMap atts = e.getAttributes();
+ for (int j = 0; j < atts.getLength(); j++) {
+ Attr a = (Attr) atts.item(i);
+ output.setAttribute(a.getName(), a.getValue());
+ }
+ transform.appendChild(output);
+ Element template = doc.createElementNS(XSL_NS, "template");
+ template.setAttribute("match", "node()|@*");
+ transform.appendChild(template);
+ Element copy = doc.createElementNS(XSL_NS, "copy");
+ template.appendChild(copy);
+ Element apply = doc.createElementNS(XSL_NS, "apply-templates");
+ apply.setAttribute("select", "node()|@*");
+ copy.appendChild(apply);
+ t = tf.newTransformer(new DOMSource(doc));
+ }
+ else if (e.getLocalName().equals("content")) {
+ NodeList children2 = e.getChildNodes();
+ for (int j = 0; j < children2.getLength(); j++) {
+ if (children2.item(j).getNodeType() == Node.ELEMENT_NODE) {
+ content = children2.item(j);
+ }
+ }
+ if (content == null) {
+ content = children2.item(0);
+ }
+ }
+ else {
+ parser_instruction = db.newDocument();
+ tf.newTransformer().transform(new DOMSource(e), new DOMResult(parser_instruction));
+ }
+ }
+ }
+ if (t == null) {
+ t = tf.newTransformer();
+ }
+ File temp = File.createTempFile("$te_", ".xml");
+ // Fortify Mod: It is possible to get here without assigning a value to content.
+ // if (content.getNodeType() == Node.TEXT_NODE) {
+ if (content != null && content.getNodeType() == Node.TEXT_NODE) {
+ RandomAccessFile raf = new RandomAccessFile(temp, "rw");
+ raf.writeBytes(((Text) content).getTextContent());
+ raf.close();
+ }
+ else {
+ t.transform(new DOMSource(content), new StreamResult(temp));
+ }
+ URLConnection uc = temp.toURI().toURL().openConnection();
+ Element result = parse(uc, parser_instruction);
+ temp.delete();
+ return result;
+ }
+
+ /**
+ * Parses the content retrieved from some URI and builds a DOM Document containing
+ * information extracted from the response message. Subsidiary parsers are invoked in
+ * accord with the supplied parser instructions.
+ * @param uc A URLConnection object.
+ * @param instruction A Document or Element node containing parser instructions.
+ * @return An Element containing selected info from a URLConnection as specified by
+ * instruction Element and children.
+ */
+ public Element parse(URLConnection uc, Node instruction) throws Throwable {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setNamespaceAware(true);
+ // Fortify Mod: Disable entity expansion to foil External Entity Injections
+ dbf.setExpandEntityReferences(false);
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ Document response_doc = db.newDocument();
+ return parse(uc, instruction, response_doc);
+ }
+
+ /**
+ * Invoke a parser or chain of parsers as specified by instruction element and
+ * children. Parsers in chain share uc, strip off their own instructions, and pass
+ * child instructions to next parser in chain. Final parser in chain modifies content.
+ * All parsers in chain can return info in attributes and child elements of
+ * instructions. If parser specified in instruction, call it to return specified info
+ * from uc.
+ */
+ public Element parse(URLConnection uc, Node instruction, Document response_doc) throws Exception {
+ // Fortify Mod: To prevent external entity injections
+ TransformerFactory tf = TransformerFactory.newInstance();
+ tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ Transformer idt = tf.newTransformer();
+ // End Fortify Mod
+ Element parser_e = response_doc.createElement("parser");
+ Element response_e = response_doc.createElement("response");
+ Element content_e = response_doc.createElement("content");
+ if (instruction == null) {
+ InputStream is = null;
+ uc.connect();
+ String contentType = uc.getContentType();
+ try {
+ is = URLConnectionUtils.getInputStream(uc);
+ if (contentType != null && contentType.contains("xml")) { // a crude check
+ idt.transform(new StreamSource(is), new DOMResult(content_e));
+ }
+ else {
+ content_e.setTextContent(IOUtils.inputStreamToString(is));
+ }
+ }
+ finally {
+ if (null != is)
+ is.close();
+ }
+ }
+ else {
+ Element instruction_e;
+ if (instruction instanceof Element) {
+ instruction_e = (Element) instruction;
+ }
+ else {
+ instruction_e = ((Document) instruction).getDocumentElement();
+ }
+ String key = "{" + instruction_e.getNamespaceURI() + "}" + instruction_e.getLocalName();
+ ParserEntry pe = index.getParser(key);
+ Object instance = null;
+
+ // Instantiate the parser object if requested.
+ if (pe.isInitialized()) {
+ instance = parserInstances.get(key);
+ if (instance == null) {
+ try {
+ TEClassLoader cl = engine.getClassLoader(opts.getSourcesName());
+ instance = Misc.makeInstance(pe.getClassName(), pe.getClassParams(), cl);
+ }
+ catch (Exception e) {
+ throw new Exception("Can't instantiate parser " + pe.getName(), e);
+ }
+ parserInstances.put(key, instance);
+ }
+ }
+
+ Method method = parserMethods.get(key);
+ if (method == null) {
+ TEClassLoader cl = engine.getClassLoader(opts.getSourcesName());
+ method = Misc.getMethod(pe.getClassName(), pe.getMethod(), cl, 3, 4);
+ parserMethods.put(key, method);
+ }
+ StringWriter swLogger = new StringWriter();
+ PrintWriter pwLogger = new PrintWriter(swLogger);
+ int arg_count = method.getParameterTypes().length;
+ Object[] args = new Object[arg_count];
+ args[0] = uc;
+ args[1] = instruction_e;
+ args[2] = pwLogger;
+ if (arg_count > 3) {
+ args[3] = this;
+ }
+ Object return_object;
+ try {
+ if (LOGR.isLoggable(Level.FINER)) {
+ LOGR.finer("Invoking method " + method.toGenericString() + "size args[] = " + args.length
+ + "\n args[0]: " + args[0].toString() + "\n args[1]:\n"
+ + DomUtils.serializeNode((Node) args[1]));
+ }
+ return_object = method.invoke(instance, args);
+ }
+ catch (java.lang.reflect.InvocationTargetException e) {
+ Throwable cause = e.getCause();
+ String msg = "Error invoking parser " + pe.getId() + "\n" + cause.getClass().getName();
+ if (cause.getMessage() != null) {
+ msg += ": " + cause.getMessage();
+ }
+ jlogger.log(SEVERE, msg, e);
+ // CTL says parsers should return null if they encounter an error.
+ // Apparently this parser is broken. Wrap the thrown exception in a
+ // RuntimeException since we really know nothing about what went wrong.
+ throw new RuntimeException("Parser " + pe.getId() + " threw an exception.", cause);
+ }
+ pwLogger.close();
+ if (return_object instanceof Node) {
+ idt.transform(new DOMSource((Node) return_object), new DOMResult(content_e));
+ }
+ else if (return_object != null) {
+ content_e.appendChild(response_doc.createTextNode(return_object.toString()));
+ }
+ parser_e.setAttribute("prefix", instruction_e.getPrefix());
+ parser_e.setAttribute("local-name", instruction_e.getLocalName());
+ parser_e.setAttribute("namespace-uri", instruction_e.getNamespaceURI());
+ parser_e.setTextContent(swLogger.toString());
+ }
+ response_e.appendChild(parser_e);
+ response_e.appendChild(content_e);
+ return response_e;
+ }
+
+ public Node message(String message, String id) {
+ String formatted_message = indent + message.trim().replaceAll("\n", "\n" + indent);
+ String messageTrim = message.trim().replaceAll("\n", "\n" + indent);
+ if (!(messageTrim.contains("Clause") || messageTrim.contains("Purpose") || messageTrim.contains("TestName"))) {
+ out.println(formatted_message);
+ messageTest = message;
+ }
+ else {
+ if (messageTrim.contains("TestName")) {
+ TESTNAME = messageTrim.replace("TestName : ", "");
+ if (rootTestName != null && rootTestName.size() > 0) {
+ for (int i = 0; i < rootTestName.size(); i++) {
+ if (messageTrim.contains(rootTestName.get(i))) {
+ rootNo = i + 1;
+ }
+ }
+ }
+ }
+ else if (messageTrim.contains("Clause")) {
+ Clause = messageTrim.replace("Clause : ", "");
+ }
+ else {
+ Purpose = messageTrim.replace("Purpose : ", "");
+ }
+ if ((rootNo != 0) && (!"".equals(Clause)) && (!"".equals(Purpose))) {
+ mainRootElementClause.appendChild(RecordTestResult.getClause());
+ Clause = "";
+ Purpose = "";
+ rootNo = 0;
+ }
+ }
+ if (logger != null) {
+ logger.println(" ");
+ }
+ return null;
+ }
+
+ public void putLogCache(String id, Document xmlToCache) {
+ if (logger != null) {
+ String xmlString = DomUtils.serializeNode(xmlToCache);
+ logger.println("" + xmlString + " ");
+ }
+ }
+
+ public Element getLogCache(String id) {
+ Element child_e = null;
+ if (prevLog != null) {
+ for (Element cache_e : DomUtils.getElementsByTagName(prevLog, "cache")) {
+ if (cache_e.getAttribute("id").equals(id)) {
+ child_e = DomUtils.getChildElement(cache_e);
+ }
+ }
+ }
+ if (suiteLog != null && child_e == null) {
+ for (Element cache_e : DomUtils.getElementsByTagName(suiteLog, "cache")) {
+ if (cache_e.getAttribute("id").equals(id)) {
+ child_e = DomUtils.getChildElement(cache_e);
+ }
+ }
+ }
+ return child_e;
+ }
+
+ /**
+ * Converts CTL input form elements to generate a Swing-based or XHTML form and
+ * reports the results of processing the submitted form. The results document is
+ * produced in (web context) or
+ * {@link com.occamlab.te.SwingForm.CustomFormView#submitData(String)}.
+ * @param ctlForm a DOM Document representing a <ctl:form> element.
+ * @throws java.lang.Exception
+ * @return a DOM Document containing the resulting <values> element as the
+ * document element.
+ */
+ public Node form(Document ctlForm, String id) throws Exception {
+ if (opts.getMode() == Test.RESUME_MODE && prevLog != null) {
+ for (Element e : DomUtils.getElementsByTagName(prevLog, "formresults")) {
+ if (e.getAttribute("id").equals(fnPath + id)) {
+ logger.println(DomUtils.serializeNode(e));
+ logger.flush();
+ return DomUtils.getChildElement(e);
+ }
+ }
+ }
+
+ String name = Thread.currentThread().getName();
+ Element form = (Element) ctlForm.getElementsByTagNameNS(CTL_NS, "form").item(0);
+
+ NamedNodeMap attrs = form.getAttributes();
+ Attr attr = (Attr) attrs.getNamedItem("name");
+ if (attr != null) {
+ name = attr.getValue();
+ }
+
+ for (Element parseInstruction : DomUtils.getElementsByTagNameNS(form, CTL_NS, "parse")) {
+ String key = parseInstruction.getAttribute("file");
+ formParsers.put(key, DomUtils.getChildElement(parseInstruction));
+ }
+
+ // Determine if there are file widgets or not
+ boolean hasFiles = false;
+ List inputs = DomUtils.getElementsByTagName(form, "input");
+ inputs.addAll(DomUtils.getElementsByTagNameNS(form, "http://www.w3.org/1999/xhtml", "input"));
+ for (Element input : inputs) {
+ if (input.getAttribute("type").toLowerCase().equals("file")) {
+ hasFiles = true;
+ break;
+ }
+ }
+
+ // Get "method" attribute - "post" or "get"
+ attr = (Attr) attrs.getNamedItem("method");
+ String method = "get";
+ if (attr != null) {
+ method = attr.getValue().toLowerCase();
+ }
+ else if (hasFiles) {
+ method = "post";
+ }
+ imageHandler.saveImages(form);
+
+ XsltTransformer formTransformer = engine.getFormExecutable().load();
+ formTransformer.setSource(new DOMSource(ctlForm));
+ formTransformer.setParameter(new QName("title"), new XdmAtomicValue(name));
+ formTransformer.setParameter(new QName("web"), new XdmAtomicValue(web ? "yes" : "no"));
+ formTransformer.setParameter(new QName("files"), new XdmAtomicValue(hasFiles ? "yes" : "no"));
+ formTransformer.setParameter(new QName("thread"),
+ new XdmAtomicValue(Long.toString(Thread.currentThread().getId())));
+ formTransformer.setParameter(new QName("method"), new XdmAtomicValue(method));
+ formTransformer.setParameter(new QName("base"), new XdmAtomicValue(opts.getBaseURI()));
+ formTransformer.setParameter(new QName("action"), new XdmAtomicValue(getTestServletURL()));
+ StringWriter sw = new StringWriter();
+ Serializer serializer = new Serializer();
+ serializer.setOutputWriter(sw);
+ serializer.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");
+ formTransformer.setDestination(serializer);
+ formTransformer.transform();
+ this.formHtml = sw.toString();
+ if (LOGR.isLoggable(FINE))
+ LOGR.fine(this.formHtml);
+
+ if (!recordedForms.isEmpty()) {
+ RecordedForm.create(recordedForms.next(), this);
+ }
+ else if (!web) {
+ int width = 700;
+ int height = 500;
+ attr = (Attr) attrs.getNamedItem("width");
+ if (attr != null) {
+ width = Integer.parseInt(attr.getValue());
+ }
+ attr = (Attr) attrs.getNamedItem("height");
+ if (attr != null) {
+ height = Integer.parseInt(attr.getValue());
+ }
+ SwingForm.create(name, width, height, this);
+ }
+
+ while (formResults == null) {
+ if (stop) {
+ formParsers.clear();
+ throw new Exception("Execution was stopped by the user.");
+ }
+ Thread.sleep(250);
+ }
+
+ Document doc = formResults;
+ if (LOGR.isLoggable(FINE))
+ LOGR.fine(DomUtils.serializeNode(doc));
+ formResults = null;
+ formParsers.clear();
+
+ if (logger != null) {
+ logger.println("");
+ logger.println(DomUtils.serializeNode(doc));
+ logger.println(" ");
+ }
+ return doc;
+ }
+
+ public void setIndentLevel(int level) {
+ indent = "";
+ for (int i = 0; i < level; i++) {
+ indent += INDENT;
+ }
+ }
+
+ public String getOutput() {
+ String output = threadOutput.toString();
+ threadOutput.reset();
+ return output;
+ }
+
+ public void stopThread() throws Exception {
+ stop = true;
+ while (!threadComplete) {
+ Thread.sleep(100);
+ }
+ }
+
+ public boolean isThreadComplete() {
+ return threadComplete;
+ }
+
+ public void run() {
+ threadComplete = false;
+ // activeThread = Thread.currentThread();
+ try {
+ opts.getLogDir().mkdir();
+ threadOutput = new ByteArrayOutputStream();
+ out = new PrintStream(threadOutput);
+ execute();
+ out.close();
+ }
+ catch (Exception e) {
+ jlogger.log(SEVERE, "", e);
+ }
+ // activeThread = null;
+ threadComplete = true;
+ }
+
+ public File getLogDir() {
+ return opts.getLogDir();
+ }
+
+ public PrintStream getOut() {
+ return out;
+ }
+
+ public void setOut(PrintStream out) {
+ this.out = out;
+ }
+
+ public String getTestPath() {
+ return testPath;
+ }
+
+ /**
+ * Returns the location of the directory containing the test run output.
+ * @return A String representing a file URI denoting the path name of a directory.
+ */
+ public String getTestRunDirectory() {
+ String logDirURI = opts.getLogDir().toURI().toString();
+ return logDirURI + opts.getSessionId();
+ }
+
+ /**
+ * Updates the local testPath value. C. Heazel made private since it is never called
+ * by an external object Could be removed since local classes can set it directly. Or
+ * augmented by value validation.
+ */
+ private void setTestPath(String testPath) {
+ this.testPath = testPath;
+ }
+
+ public boolean isWeb() {
+ return web;
+ }
+
+ public void setWeb(boolean web) {
+ this.web = web;
+ }
+
+ public Object getFunctionInstance(Integer key) {
+ return functionInstances.get(key);
+ }
+
+ public Object putFunctionInstance(Integer key, Object instance) {
+ return functionInstances.put(key, instance);
+ }
+
+ public Engine getEngine() {
+ return engine;
+ }
+
+ public Index getIndex() {
+ return index;
+ }
+
+ public RuntimeOptions getOpts() {
+ return opts;
+ }
+
+ public String getTestServletURL() {
+ return testServletURL;
+ }
+
+ public void setTestServletURL(String testServletURL) {
+ this.testServletURL = testServletURL;
+ }
+
+ /**
+ * Transform EARL result into HTML report using XSLT.
+ * @param outputDir
+ */
+ // Fortify Mod: Changed to a private method so that the value of the
+ // outputDir parameter can be managed.
+ // Note: that there is no indication that this method is ever called.
+ public boolean earlHtmlReport(String outputDir) {
+ TEPath tpath = new TEPath(outputDir);
+ if (!tpath.isValid()) {
+ System.out.println("ViewLog Error: Invalid log file name " + outputDir);
+ return false;
+ }
+ EarlToHtmlTransformation earlToHtml = new EarlToHtmlTransformation();
+ earlToHtml.earlHtmlReport(outputDir);
+ return true;
+ }
+
+ /**
+ * This method is used to extract the test input into Map from the document element.
+ * @param userInput Document node
+ * @param runOpts
+ * @return User Input Map
+ */
+ private Map extractTestInputs(Document userInput, RuntimeOptions runOpts) {
+ Map inputMap = new HashMap<>();
+ if (null != userInputs) {
+ NodeList values = userInputs.getDocumentElement().getElementsByTagName("value");
+ if (values.getLength() == 0) {
+ inputMap = Collections.emptyMap();
+ }
+ else {
+ for (int i = 0; i < values.getLength(); i++) {
+ Element value = (Element) values.item(i);
+ inputMap.put(value.getAttribute("key"), value.getTextContent());
+ }
+ }
+ }
+ else if (null != opts.getParams()) {
+ List runParams = opts.getParams();
+ for (String param : runParams) {
+ String[] kvp = param.split("=");
+ inputMap.put(kvp[0], kvp[1]);
+ }
+ }
+ return inputMap;
+ }
+
+ private boolean checkForRedirect(HttpURLConnection conn) throws IOException {
+ int status = conn.getResponseCode();
+ if (status != HttpURLConnection.HTTP_OK) {
+ if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
+ || status == HttpURLConnection.HTTP_SEE_OTHER)
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Builds a DOM Document representing a classpath resource.
+ * @param name The name of an XML resource.
+ * @return A Document node, or {@code null} if the resource cannot be parsed for any
+ * reason.
+ */
+ public Document findXMLResource(String name) {
+ URL url = this.getClass().getResource(name);
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ docFactory.setNamespaceAware(true);
+ // Fortify Mod: Disable entity expansion to foil External Entity Injections
+ docFactory.setExpandEntityReferences(false);
+ Document doc = null;
+ try {
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+ doc = docBuilder.parse(url.toURI().toString());
+ }
+ catch (Exception e) {
+ LOGR.log(Level.WARNING, "Failed to parse classpath resource " + name, e);
+ }
+ return doc;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/TeErrorListener.java b/teamengine-core/src/main/java/com/occamlab/te/TeErrorListener.java
index d583dfd99..439482289 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/TeErrorListener.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/TeErrorListener.java
@@ -13,6 +13,26 @@ C. Heazel (WiSC) Modifications to address Fortify issues.
****************************************************************************/
package com.occamlab.te;
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.File;
diff --git a/teamengine-core/src/main/java/com/occamlab/te/Test.java b/teamengine-core/src/main/java/com/occamlab/te/Test.java
index c224ced2a..177c335cb 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/Test.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/Test.java
@@ -1,525 +1,545 @@
-/*
-
- The Original Code is TEAM Engine.
-
- The Initial Developer of the Original Code is Northrop Grumman Corporation
- jointly with The National Technology Alliance. Portions created by
- Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
- Grumman Corporation. All Rights Reserved.
-
- Contributor(s):
- 2009 F. Vitale vitale@imaa.cnr.it
- 2018 C. Heazel cheazel@wiscenterprisesl.com
-
- Modifications:
- 2/14/18
- - Addressed path manipulation vulnerabilities and general cleanup.
- - Identified Issues which need further discussion.
-
- */
-
-package com.occamlab.te;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FilenameFilter;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.NodeList;
-
-import com.occamlab.te.index.Index;
-import com.occamlab.te.util.LogUtils;
-
-/**
- *
- * The main class for the TEAM Engine command line interface.
- *
- */
-public class Test {
-
- private static final Logger LOGR = Logger.getLogger(Test.class.getName());
-
- public static final int TEST_MODE = 0;
-
- public static final int RETEST_MODE = 1;
-
- public static final int RESUME_MODE = 2;
-
- public static final int REDO_FROM_CACHE_MODE = 3;
-
- public static final int DOC_MODE = 4;
-
- public static final int CHECK_MODE = 5;
-
- public static final String XSL_NS = "http://www.w3.org/1999/XSL/Transform";
-
- public static final String TE_NS = "http://www.occamlab.com/te";
-
- public static final String CTL_NS = "http://www.occamlab.com/ctl";
-
- public static final String CTLP_NS = "http://www.occamlab.com/te/parsers";
-
- SetupOptions setupOpts;
-
- RuntimeOptions runOpts;
-
- /**
- * Constructs a test executor with default options.
- */
- public Test() {
- this.setupOpts = new SetupOptions();
- this.runOpts = new RuntimeOptions();
- }
-
- /**
- * Replace the SetupOptions with a new copy
- * @param setupOpts The new copy of the setup options
- *
- * ISSUE: SetupOptions are established when the Teamengin is initialized. they should
- * be the same for all tests. Why do we allow them to be modified? ISSUE: when and how
- * are the setup options validated? ANSWER: Delete this method since it is never
- * called.
- */
- // void setSetupOptions(SetupOptions setupOpts) {
- // this.setupOpts = setupOpts;
- // }
-
- /**
- * Replace the RuntimeOptions with a new copy
- * @param runOpts The new copy of the runtime options
- *
- * ISSUE: when and how are the runtime options validated? ANSWER: make RuntimeOptions
- * self-validating.
- */
- void setRuntimeOptions(RuntimeOptions runOpts) {
- this.runOpts = runOpts;
- }
-
- // This method does not appear to be used. Consider deleting it.
- // Changed from public to private until we validate that is can be removed.
-
- private void executeTest(String relativePathToMainCtl) throws Exception {
- // File file =Misc.getResourceAsFile(relativePathToMainCtl);
- String[] arguments = new String[1];
- arguments[0] = "-source=" + relativePathToMainCtl;
- execute(arguments);
- }
-
- /**
- * Entry point from the command line. Creates a new test object then executes it.
- * @param args An array of command line arguments
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- Test test = new Test();
- test.execute(args);
- }
-
- /**
- * Executes a test suite.
- * @param args Command line arguments
- * @throws Exception
- */
- public void execute(String[] args) throws Exception {
- @SuppressWarnings("unused")
- boolean rslt;
-
- // Copy work directory from setup options to runtime
- File workDir = setupOpts.getWorkDir();
- rslt = runOpts.setWorkDir(workDir);
-
- // Initialize the rest of the test context
- String cmd = "java com.occamlab.te.Test";
- File logDir = runOpts.getLogDir();
- String session = null;
- boolean hasSessionArg = false;
- int mode = TEST_MODE;
-
- // Parse arguments from command-line
- for (int i = 0; i < args.length; i++) {
- String arg = args[i];
- if (arg.startsWith("-cmd=")) {
- cmd = arg.substring(5);
- }
- else if (arg.equals("-h") || arg.equals("-help") || arg.equals("-?")) {
- syntax(cmd);
- return;
- // The path to the test script. If the file name is not an absolute
- // path then it must be under the Scripts directory.
- // Issue: should we restrict the range of valid paths for source files?
- }
- else if (arg.startsWith("-source=")) {
- String sourcePath = arg.substring(8);
- File sourceFile = new File(sourcePath);
- if (!sourceFile.isAbsolute()) {
- File scriptsDir = new File(SetupOptions.getBaseConfigDirectory(), "scripts");
- sourceFile = new File(scriptsDir, sourcePath);
- }
- // Fortify Mod: Validate the sourceFile. It must both exist
- // and pass validation by setupOptions
- if (!sourceFile.exists() || !setupOpts.addSourceWithValidation(sourceFile)) {
- System.out.println("Error: Cannot find CTL script(s) at " + sourceFile.getAbsolutePath());
- return;
- }
- }
- else if (args[i].startsWith("-logdir=")) {
- String path = args[i].substring(8);
- File file = new File(path);
- if (file.isAbsolute()) {
- logDir = file;
- }
- else {
- logDir = new File(SetupOptions.getBaseConfigDirectory(), path);
- }
- if (!logDir.exists() || !runOpts.setLogDir(logDir)) {
- System.out.println("Error: Cannot use logdir " + logDir.getAbsolutePath());
- return;
- }
- }
- else if (arg.startsWith("-session=")) {
- // Issue: session is not validated but it is used as part of a file path.
- hasSessionArg = true;
- session = arg.substring(9);
- }
- else if (arg.startsWith("-base=")) {
- rslt = runOpts.setBaseURI(arg.substring(6));
- }
- else if (arg.startsWith("-test=")) {
- rslt = runOpts.setTestName(arg.substring(6));
- }
- else if (arg.startsWith("-suite=")) {
- rslt = runOpts.setSuiteName(arg.substring(7));
- }
- else if (arg.startsWith("-profile=")) {
- rslt = runOpts.addProfile(arg.substring(9));
- }
- else if (arg.startsWith("@")) {
- rslt = runOpts.addParam(arg.substring(1));
- }
- else if (arg.equals("-mode=test")) {
- mode = TEST_MODE;
- }
- else if (arg.equals("-mode=retest")) {
- mode = RETEST_MODE;
- }
- else if (arg.equals("-mode=resume")) {
- mode = RESUME_MODE;
- }
- else if (arg.equals("-mode=doc")) {
- mode = DOC_MODE;
- }
- else if (arg.equals("-mode=check")) {
- mode = CHECK_MODE;
- }
- else if (arg.equals("-mode=cache")) {
- mode = REDO_FROM_CACHE_MODE;
- }
- else if (arg.startsWith("-mode=")) {
- System.out.println("Error: Invalid mode.");
- return;
- }
- else if (arg.equals("-validate=no")) {
- setupOpts.setValidate(false);
- }
- else if ((arg.startsWith("-form="))) {
- rslt = runOpts.addRecordedForm(arg.substring(6));
- }
- else if (!arg.startsWith("-")) {
- if (mode == RETEST_MODE || mode == REDO_FROM_CACHE_MODE) {
- if (hasSessionArg) {
- if (arg.startsWith(session)) {
- rslt = runOpts.addTestPath(arg);
- }
- else {
- rslt = runOpts.addTestPath(session + "/" + arg);
- }
- }
- else {
- int slash = (arg).indexOf("/");
- if (slash >= 0) {
- if (session == null) {
- session = arg.substring(0, slash);
- }
- else if (!arg.substring(0, slash).equals(session)) {
- System.out.println("Each test path must be within the same session.");
- return;
- }
- rslt = runOpts.addTestPath(arg);
- }
- }
- }
- else {
- System.out.println("Unrecognized parameter \"" + arg + "\"");
- }
- }
- else {
- System.out.println("Unrecognized parameter \"" + arg + "\"");
- }
- }
-
- // Set mode
- rslt = runOpts.setMode(mode);
- rslt = runOpts.setSessionId(session);
-
- if (mode == RETEST_MODE || mode == RESUME_MODE || mode == REDO_FROM_CACHE_MODE) {
- if (logDir == null || session == null) {
- syntax(cmd);
- return;
- }
- if (setupOpts.getSources().isEmpty()) {
- loadSources();
- }
- }
-
- // Syntax checks
- if (setupOpts.getSources().isEmpty()) {
- System.out.println("Error: At least one -source parameter is required");
- return;
- }
- if (runOpts.getProfiles().size() > 0 && logDir == null) {
- System.out.println("Error: A -logdir parameter is required for testing profiles");
- return;
- }
-
- // Set session
- if (session == null) {
- session = System.getProperty("team.session");
- }
- // CMH - changed session format to UUID.
- // BPR - changed back to previous format
- if (session == null) {
- if (logDir == null) {
- session = "s0001";
- }
- else {
- session = LogUtils.generateSessionId(logDir);
- }
- rslt = runOpts.setSessionId(session);
- }
-
- Thread.currentThread().setName("TEAM Engine");
- Index masterIndex = new Index();
- File indexFile = null;
- if (logDir != null && session != null) {
- File dir = new File(logDir, runOpts.getSessionId());
- indexFile = new File(dir, "index.xml");
- }
-
- boolean regenerate = false;
-
- if (mode == TEST_MODE || mode == CHECK_MODE) {
- regenerate = true;
- }
- else if (mode == DOC_MODE) {
- masterIndex = Generator.generateDocXsl(setupOpts);
- }
- else {
- if (indexFile == null || !indexFile.canRead()) {
- System.out.println("Error: Can't read index file.");
- regenerate = true;
- }
- else {
- masterIndex = new Index(indexFile);
- if (masterIndex.outOfDate()) {
- System.out.println("Warning: Scripts have changed since this session was first executed.");
- if (mode == REDO_FROM_CACHE_MODE) {
- System.out.println("Regenerating masterIndex from source scripts");
- regenerate = true;
- }
- }
- }
- }
-
- if (regenerate) {
- masterIndex = Generator.generateXsl(setupOpts);
- if (indexFile != null) {
- masterIndex.persist(indexFile);
- }
- }
-
- if (mode == REDO_FROM_CACHE_MODE) {
- boolean hasCache = ViewLog.checkCache(logDir, session);
- if (!hasCache) {
- File dir = new File(logDir, runOpts.getSessionId());
- throw new Exception("Error: no cache for " + dir.getAbsolutePath());
- }
- }
-
- // Fortify Mod: Make sure masterIndex is not null
- // masterIndex.setElements(null);
- if (masterIndex != null) {
- masterIndex.setElements(null);
- }
- else {
- masterIndex = new Index();
- }
- List resourcesDirs = new ArrayList<>();
- for (File sourceFile : setupOpts.getSources()) {
- File resourcesDir = findResourcesDirectory(sourceFile);
- if (!resourcesDirs.contains(resourcesDir)) {
- resourcesDirs.add(resourcesDir);
- }
- }
- TEClassLoader cl = new TEClassLoader(resourcesDirs);
- Engine engine = new Engine(masterIndex, setupOpts.getSourcesName(), cl);
-
- if (setupOpts.isPreload() || mode == CHECK_MODE) {
- engine.preload(masterIndex, setupOpts.getSourcesName());
- }
-
- if (LOGR.isLoggable(Level.FINE)) {
- LOGR.fine(runOpts.toString());
- }
-
- if (mode == TEST_MODE) {
- saveSources();
- }
-
- if (mode != CHECK_MODE) {
- TECore core = new TECore(engine, masterIndex, runOpts);
- core.execute();
- }
-
- }
-
- /**
- * Seeks a "resources" directory by searching the file system from a starting location
- * and continuing upwards into ancestor directories.
- * @param sourceFile A File denoting a file system location (file or directory).
- * @return A File representing a directory named "resources", or {@code null} if one
- * cannot be found.
- */
- static File findResourcesDirectory(File sourceFile) {
- File parent = sourceFile.getParentFile();
- if (null == parent) {
- return null;
- }
- File[] resourceDirs = parent.listFiles(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return (name.equalsIgnoreCase("resources") && new File(dir, name).isDirectory());
- }
- });
- if (resourceDirs.length > 0) {
- return resourceDirs[0];
- }
- return findResourcesDirectory(parent);
- }
-
- /**
- * Displays startup command syntax.
- * @param cmd Name of the startup command (i.e. test.bat or test.sh)
- */
- static void syntax(String cmd) {
- System.out.println();
- System.out.println("Test mode:");
- System.out.println(" Use to start a test session.\n");
- System.out.println(" " + cmd + " [-mode=test] -source=ctlfile|dir ...");
- System.out.println(" [-logdir=dir] [-session=session] [-base=baseURI]");
- System.out.println(" -suite=qname [-profile=qname|*] ... | -test=qname [@param-name=value] ...\n");
- System.out.println(" qname=[namespace_uri,|prefix:]local_name\n");
- System.out.println("Resume mode:");
- System.out.println(" Use to resume a test session that was interrupted before completion.\n");
- System.out.println(" " + cmd + " -mode=resume [-logdir=dir] -session=session\n");
- System.out.println("Retest mode:");
- System.out.println(" Use to reexecute individual tests.\n");
- System.out.println(" " + cmd + " -mode=retest [-logdir=dir] testpath1 [testpath2] ...\n");
- System.out.println("Redo From Cache Mode:");
- System.out.println(" Use to rerun tests with cached server responses when the test has changed.\n");
- System.out.println(" " + cmd + "-mode=cache [-logdir=dir] [-session=session] [testpath1 [testpath2]]\n");
- System.out.println(" Warning: Test changes may make cached server responses invalid.\n");
- System.out.println("Check mode:");
- System.out.println(" Use to validate source files.\n");
- System.out.println(" " + cmd + " -mode=check -source=ctlfile|dir ...\n");
- System.out.println("Doc mode:");
- System.out.println(" Use to visit all subtests and generate log files without executing them.\n");
- System.out.println(" " + cmd + " -mode=doc -source=ctlfile|dir ... [-suite=qname]\n");
-
- /*
- * Doc mode once again behaves as it originally did in
- * https://sourceforge.net/p/teamengine/code/1 The entry point for the
- * PseudoCTLDocumentation generator (which was called with -mode=doc starting with
- * https://sourceforge.net/p/teamengine/code/459) is now the main method of
- * DocumentationHelper.
- */
-
- /*
- * The entry point for the PrettyPrintLogs functionality which was called with
- * -mode=pplogs is now in the main method of ViewLog and is activated with its
- * -html parameter.
- */
- }
-
- /**
- * Returns name of mode.
- * @param mode
- */
- public static String getModeName(int mode) {
- switch (mode) {
- case 0:
- return "Test Mode";
- case 1:
- return "Retest Mode";
- case 2:
- return "Resume Mode";
- case 3:
- return "Redo From Cache Mode";
- case 4:
- return "Doc Mode";
- case 5:
- return "Check Mode";
- default:
- return "Invalid Mode";
- }
- }
-
- private void saveSources() {
- if (runOpts.getLogDir() != null && runOpts.getSessionId() != null) {
- File sessionDir = new File(runOpts.getLogDir(), runOpts.getSessionId());
- File sourcesFile = new File(sessionDir, "sources.xml");
- try (PrintWriter writer = new PrintWriter(sourcesFile)) {
- writer.println("");
- for (File file : setupOpts.getSources()) {
- writer.println("" + file.getPath() + " ");
- }
- writer.println(" ");
- }
- catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
- }
-
- private void loadSources() {
- if (runOpts.getLogDir() != null && runOpts.getSessionId() != null) {
- File sessionDir = new File(runOpts.getLogDir(), runOpts.getSessionId());
- File sourcesFile = new File(sessionDir, "sources.xml");
- if (sourcesFile.exists()) {
- try {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setExpandEntityReferences(false);
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document doc = db.parse(sourcesFile);
- NodeList nl = doc.getElementsByTagName("source");
- for (int i = 0; i < nl.getLength(); i++) {
- String sourcePath = nl.item(i).getTextContent();
- File sourceFile = new File(sourcePath);
- setupOpts.addSourceWithValidation(sourceFile);
- }
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
-
-}
+/*
+
+ The Original Code is TEAM Engine.
+
+ The Initial Developer of the Original Code is Northrop Grumman Corporation
+ jointly with The National Technology Alliance. Portions created by
+ Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
+ Grumman Corporation. All Rights Reserved.
+
+ Contributor(s):
+ 2009 F. Vitale vitale@imaa.cnr.it
+ 2018 C. Heazel cheazel@wiscenterprisesl.com
+
+ Modifications:
+ 2/14/18
+ - Addressed path manipulation vulnerabilities and general cleanup.
+ - Identified Issues which need further discussion.
+
+ */
+
+package com.occamlab.te;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FilenameFilter;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.NodeList;
+
+import com.occamlab.te.index.Index;
+import com.occamlab.te.util.LogUtils;
+
+/**
+ *
+ * The main class for the TEAM Engine command line interface.
+ *
+ */
+public class Test {
+
+ private static final Logger LOGR = Logger.getLogger(Test.class.getName());
+
+ public static final int TEST_MODE = 0;
+
+ public static final int RETEST_MODE = 1;
+
+ public static final int RESUME_MODE = 2;
+
+ public static final int REDO_FROM_CACHE_MODE = 3;
+
+ public static final int DOC_MODE = 4;
+
+ public static final int CHECK_MODE = 5;
+
+ public static final String XSL_NS = "http://www.w3.org/1999/XSL/Transform";
+
+ public static final String TE_NS = "http://www.occamlab.com/te";
+
+ public static final String CTL_NS = "http://www.occamlab.com/ctl";
+
+ public static final String CTLP_NS = "http://www.occamlab.com/te/parsers";
+
+ SetupOptions setupOpts;
+
+ RuntimeOptions runOpts;
+
+ /**
+ * Constructs a test executor with default options.
+ */
+ public Test() {
+ this.setupOpts = new SetupOptions();
+ this.runOpts = new RuntimeOptions();
+ }
+
+ /**
+ * Replace the SetupOptions with a new copy
+ * @param setupOpts The new copy of the setup options
+ *
+ * ISSUE: SetupOptions are established when the Teamengin is initialized. they should
+ * be the same for all tests. Why do we allow them to be modified? ISSUE: when and how
+ * are the setup options validated? ANSWER: Delete this method since it is never
+ * called.
+ */
+ // void setSetupOptions(SetupOptions setupOpts) {
+ // this.setupOpts = setupOpts;
+ // }
+
+ /**
+ * Replace the RuntimeOptions with a new copy
+ * @param runOpts The new copy of the runtime options
+ *
+ * ISSUE: when and how are the runtime options validated? ANSWER: make RuntimeOptions
+ * self-validating.
+ */
+ void setRuntimeOptions(RuntimeOptions runOpts) {
+ this.runOpts = runOpts;
+ }
+
+ // This method does not appear to be used. Consider deleting it.
+ // Changed from public to private until we validate that is can be removed.
+
+ private void executeTest(String relativePathToMainCtl) throws Exception {
+ // File file =Misc.getResourceAsFile(relativePathToMainCtl);
+ String[] arguments = new String[1];
+ arguments[0] = "-source=" + relativePathToMainCtl;
+ execute(arguments);
+ }
+
+ /**
+ * Entry point from the command line. Creates a new test object then executes it.
+ * @param args An array of command line arguments
+ * @throws Exception
+ */
+ public static void main(String[] args) throws Exception {
+ Test test = new Test();
+ test.execute(args);
+ }
+
+ /**
+ * Executes a test suite.
+ * @param args Command line arguments
+ * @throws Exception
+ */
+ public void execute(String[] args) throws Exception {
+ @SuppressWarnings("unused")
+ boolean rslt;
+
+ // Copy work directory from setup options to runtime
+ File workDir = setupOpts.getWorkDir();
+ rslt = runOpts.setWorkDir(workDir);
+
+ // Initialize the rest of the test context
+ String cmd = "java com.occamlab.te.Test";
+ File logDir = runOpts.getLogDir();
+ String session = null;
+ boolean hasSessionArg = false;
+ int mode = TEST_MODE;
+
+ // Parse arguments from command-line
+ for (int i = 0; i < args.length; i++) {
+ String arg = args[i];
+ if (arg.startsWith("-cmd=")) {
+ cmd = arg.substring(5);
+ }
+ else if (arg.equals("-h") || arg.equals("-help") || arg.equals("-?")) {
+ syntax(cmd);
+ return;
+ // The path to the test script. If the file name is not an absolute
+ // path then it must be under the Scripts directory.
+ // Issue: should we restrict the range of valid paths for source files?
+ }
+ else if (arg.startsWith("-source=")) {
+ String sourcePath = arg.substring(8);
+ File sourceFile = new File(sourcePath);
+ if (!sourceFile.isAbsolute()) {
+ File scriptsDir = new File(SetupOptions.getBaseConfigDirectory(), "scripts");
+ sourceFile = new File(scriptsDir, sourcePath);
+ }
+ // Fortify Mod: Validate the sourceFile. It must both exist
+ // and pass validation by setupOptions
+ if (!sourceFile.exists() || !setupOpts.addSourceWithValidation(sourceFile)) {
+ System.out.println("Error: Cannot find CTL script(s) at " + sourceFile.getAbsolutePath());
+ return;
+ }
+ }
+ else if (args[i].startsWith("-logdir=")) {
+ String path = args[i].substring(8);
+ File file = new File(path);
+ if (file.isAbsolute()) {
+ logDir = file;
+ }
+ else {
+ logDir = new File(SetupOptions.getBaseConfigDirectory(), path);
+ }
+ if (!logDir.exists() || !runOpts.setLogDir(logDir)) {
+ System.out.println("Error: Cannot use logdir " + logDir.getAbsolutePath());
+ return;
+ }
+ }
+ else if (arg.startsWith("-session=")) {
+ // Issue: session is not validated but it is used as part of a file path.
+ hasSessionArg = true;
+ session = arg.substring(9);
+ }
+ else if (arg.startsWith("-base=")) {
+ rslt = runOpts.setBaseURI(arg.substring(6));
+ }
+ else if (arg.startsWith("-test=")) {
+ rslt = runOpts.setTestName(arg.substring(6));
+ }
+ else if (arg.startsWith("-suite=")) {
+ rslt = runOpts.setSuiteName(arg.substring(7));
+ }
+ else if (arg.startsWith("-profile=")) {
+ rslt = runOpts.addProfile(arg.substring(9));
+ }
+ else if (arg.startsWith("@")) {
+ rslt = runOpts.addParam(arg.substring(1));
+ }
+ else if (arg.equals("-mode=test")) {
+ mode = TEST_MODE;
+ }
+ else if (arg.equals("-mode=retest")) {
+ mode = RETEST_MODE;
+ }
+ else if (arg.equals("-mode=resume")) {
+ mode = RESUME_MODE;
+ }
+ else if (arg.equals("-mode=doc")) {
+ mode = DOC_MODE;
+ }
+ else if (arg.equals("-mode=check")) {
+ mode = CHECK_MODE;
+ }
+ else if (arg.equals("-mode=cache")) {
+ mode = REDO_FROM_CACHE_MODE;
+ }
+ else if (arg.startsWith("-mode=")) {
+ System.out.println("Error: Invalid mode.");
+ return;
+ }
+ else if (arg.equals("-validate=no")) {
+ setupOpts.setValidate(false);
+ }
+ else if ((arg.startsWith("-form="))) {
+ rslt = runOpts.addRecordedForm(arg.substring(6));
+ }
+ else if (!arg.startsWith("-")) {
+ if (mode == RETEST_MODE || mode == REDO_FROM_CACHE_MODE) {
+ if (hasSessionArg) {
+ if (arg.startsWith(session)) {
+ rslt = runOpts.addTestPath(arg);
+ }
+ else {
+ rslt = runOpts.addTestPath(session + "/" + arg);
+ }
+ }
+ else {
+ int slash = (arg).indexOf("/");
+ if (slash >= 0) {
+ if (session == null) {
+ session = arg.substring(0, slash);
+ }
+ else if (!arg.substring(0, slash).equals(session)) {
+ System.out.println("Each test path must be within the same session.");
+ return;
+ }
+ rslt = runOpts.addTestPath(arg);
+ }
+ }
+ }
+ else {
+ System.out.println("Unrecognized parameter \"" + arg + "\"");
+ }
+ }
+ else {
+ System.out.println("Unrecognized parameter \"" + arg + "\"");
+ }
+ }
+
+ // Set mode
+ rslt = runOpts.setMode(mode);
+ rslt = runOpts.setSessionId(session);
+
+ if (mode == RETEST_MODE || mode == RESUME_MODE || mode == REDO_FROM_CACHE_MODE) {
+ if (logDir == null || session == null) {
+ syntax(cmd);
+ return;
+ }
+ if (setupOpts.getSources().isEmpty()) {
+ loadSources();
+ }
+ }
+
+ // Syntax checks
+ if (setupOpts.getSources().isEmpty()) {
+ System.out.println("Error: At least one -source parameter is required");
+ return;
+ }
+ if (runOpts.getProfiles().size() > 0 && logDir == null) {
+ System.out.println("Error: A -logdir parameter is required for testing profiles");
+ return;
+ }
+
+ // Set session
+ if (session == null) {
+ session = System.getProperty("team.session");
+ }
+ // CMH - changed session format to UUID.
+ // BPR - changed back to previous format
+ if (session == null) {
+ if (logDir == null) {
+ session = "s0001";
+ }
+ else {
+ session = LogUtils.generateSessionId(logDir);
+ }
+ rslt = runOpts.setSessionId(session);
+ }
+
+ Thread.currentThread().setName("TEAM Engine");
+ Index masterIndex = new Index();
+ File indexFile = null;
+ if (logDir != null && session != null) {
+ File dir = new File(logDir, runOpts.getSessionId());
+ indexFile = new File(dir, "index.xml");
+ }
+
+ boolean regenerate = false;
+
+ if (mode == TEST_MODE || mode == CHECK_MODE) {
+ regenerate = true;
+ }
+ else if (mode == DOC_MODE) {
+ masterIndex = Generator.generateDocXsl(setupOpts);
+ }
+ else {
+ if (indexFile == null || !indexFile.canRead()) {
+ System.out.println("Error: Can't read index file.");
+ regenerate = true;
+ }
+ else {
+ masterIndex = new Index(indexFile);
+ if (masterIndex.outOfDate()) {
+ System.out.println("Warning: Scripts have changed since this session was first executed.");
+ if (mode == REDO_FROM_CACHE_MODE) {
+ System.out.println("Regenerating masterIndex from source scripts");
+ regenerate = true;
+ }
+ }
+ }
+ }
+
+ if (regenerate) {
+ masterIndex = Generator.generateXsl(setupOpts);
+ if (indexFile != null) {
+ masterIndex.persist(indexFile);
+ }
+ }
+
+ if (mode == REDO_FROM_CACHE_MODE) {
+ boolean hasCache = ViewLog.checkCache(logDir, session);
+ if (!hasCache) {
+ File dir = new File(logDir, runOpts.getSessionId());
+ throw new Exception("Error: no cache for " + dir.getAbsolutePath());
+ }
+ }
+
+ // Fortify Mod: Make sure masterIndex is not null
+ // masterIndex.setElements(null);
+ if (masterIndex != null) {
+ masterIndex.setElements(null);
+ }
+ else {
+ masterIndex = new Index();
+ }
+ List resourcesDirs = new ArrayList<>();
+ for (File sourceFile : setupOpts.getSources()) {
+ File resourcesDir = findResourcesDirectory(sourceFile);
+ if (!resourcesDirs.contains(resourcesDir)) {
+ resourcesDirs.add(resourcesDir);
+ }
+ }
+ TEClassLoader cl = new TEClassLoader(resourcesDirs);
+ Engine engine = new Engine(masterIndex, setupOpts.getSourcesName(), cl);
+
+ if (setupOpts.isPreload() || mode == CHECK_MODE) {
+ engine.preload(masterIndex, setupOpts.getSourcesName());
+ }
+
+ if (LOGR.isLoggable(Level.FINE)) {
+ LOGR.fine(runOpts.toString());
+ }
+
+ if (mode == TEST_MODE) {
+ saveSources();
+ }
+
+ if (mode != CHECK_MODE) {
+ TECore core = new TECore(engine, masterIndex, runOpts);
+ core.execute();
+ }
+
+ }
+
+ /**
+ * Seeks a "resources" directory by searching the file system from a starting location
+ * and continuing upwards into ancestor directories.
+ * @param sourceFile A File denoting a file system location (file or directory).
+ * @return A File representing a directory named "resources", or {@code null} if one
+ * cannot be found.
+ */
+ static File findResourcesDirectory(File sourceFile) {
+ File parent = sourceFile.getParentFile();
+ if (null == parent) {
+ return null;
+ }
+ File[] resourceDirs = parent.listFiles(new FilenameFilter() {
+ @Override
+ public boolean accept(File dir, String name) {
+ return (name.equalsIgnoreCase("resources") && new File(dir, name).isDirectory());
+ }
+ });
+ if (resourceDirs.length > 0) {
+ return resourceDirs[0];
+ }
+ return findResourcesDirectory(parent);
+ }
+
+ /**
+ * Displays startup command syntax.
+ * @param cmd Name of the startup command (i.e. test.bat or test.sh)
+ */
+ static void syntax(String cmd) {
+ System.out.println();
+ System.out.println("Test mode:");
+ System.out.println(" Use to start a test session.\n");
+ System.out.println(" " + cmd + " [-mode=test] -source=ctlfile|dir ...");
+ System.out.println(" [-logdir=dir] [-session=session] [-base=baseURI]");
+ System.out.println(" -suite=qname [-profile=qname|*] ... | -test=qname [@param-name=value] ...\n");
+ System.out.println(" qname=[namespace_uri,|prefix:]local_name\n");
+ System.out.println("Resume mode:");
+ System.out.println(" Use to resume a test session that was interrupted before completion.\n");
+ System.out.println(" " + cmd + " -mode=resume [-logdir=dir] -session=session\n");
+ System.out.println("Retest mode:");
+ System.out.println(" Use to reexecute individual tests.\n");
+ System.out.println(" " + cmd + " -mode=retest [-logdir=dir] testpath1 [testpath2] ...\n");
+ System.out.println("Redo From Cache Mode:");
+ System.out.println(" Use to rerun tests with cached server responses when the test has changed.\n");
+ System.out.println(" " + cmd + "-mode=cache [-logdir=dir] [-session=session] [testpath1 [testpath2]]\n");
+ System.out.println(" Warning: Test changes may make cached server responses invalid.\n");
+ System.out.println("Check mode:");
+ System.out.println(" Use to validate source files.\n");
+ System.out.println(" " + cmd + " -mode=check -source=ctlfile|dir ...\n");
+ System.out.println("Doc mode:");
+ System.out.println(" Use to visit all subtests and generate log files without executing them.\n");
+ System.out.println(" " + cmd + " -mode=doc -source=ctlfile|dir ... [-suite=qname]\n");
+
+ /*
+ * Doc mode once again behaves as it originally did in
+ * https://sourceforge.net/p/teamengine/code/1 The entry point for the
+ * PseudoCTLDocumentation generator (which was called with -mode=doc starting with
+ * https://sourceforge.net/p/teamengine/code/459) is now the main method of
+ * DocumentationHelper.
+ */
+
+ /*
+ * The entry point for the PrettyPrintLogs functionality which was called with
+ * -mode=pplogs is now in the main method of ViewLog and is activated with its
+ * -html parameter.
+ */
+ }
+
+ /**
+ * Returns name of mode.
+ * @param mode
+ */
+ public static String getModeName(int mode) {
+ switch (mode) {
+ case 0:
+ return "Test Mode";
+ case 1:
+ return "Retest Mode";
+ case 2:
+ return "Resume Mode";
+ case 3:
+ return "Redo From Cache Mode";
+ case 4:
+ return "Doc Mode";
+ case 5:
+ return "Check Mode";
+ default:
+ return "Invalid Mode";
+ }
+ }
+
+ private void saveSources() {
+ if (runOpts.getLogDir() != null && runOpts.getSessionId() != null) {
+ File sessionDir = new File(runOpts.getLogDir(), runOpts.getSessionId());
+ File sourcesFile = new File(sessionDir, "sources.xml");
+ try (PrintWriter writer = new PrintWriter(sourcesFile)) {
+ writer.println("");
+ for (File file : setupOpts.getSources()) {
+ writer.println("" + file.getPath() + " ");
+ }
+ writer.println(" ");
+ }
+ catch (FileNotFoundException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ private void loadSources() {
+ if (runOpts.getLogDir() != null && runOpts.getSessionId() != null) {
+ File sessionDir = new File(runOpts.getLogDir(), runOpts.getSessionId());
+ File sourcesFile = new File(sessionDir, "sources.xml");
+ if (sourcesFile.exists()) {
+ try {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setExpandEntityReferences(false);
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ Document doc = db.parse(sourcesFile);
+ NodeList nl = doc.getElementsByTagName("source");
+ for (int i = 0; i < nl.getLength(); i++) {
+ String sourcePath = nl.item(i).getTextContent();
+ File sourceFile = new File(sourcePath);
+ setupOpts.addSourceWithValidation(sourceFile);
+ }
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/ViewLog.java b/teamengine-core/src/main/java/com/occamlab/te/ViewLog.java
index c98435a23..232badf61 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/ViewLog.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/ViewLog.java
@@ -1,284 +1,304 @@
-/****************************************************************************
-
- The Original Code is TEAM Engine.
-
- The Initial Developer of the Original Code is Northrop Grumman Corporation
- jointly with The National Technology Alliance. Portions created by
- Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
- Grumman Corporation. All Rights Reserved.
-
- Contributor(s):
- Charles Heazel (WiSC): Modifications to address Fortify issues
-
- ****************************************************************************/
-package com.occamlab.te;
-
-import java.io.File;
-import java.io.InputStream;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.transform.Templates;
-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 org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-
-import com.occamlab.te.html.EarlToHtmlTransformation;
-import com.occamlab.te.util.DocumentationHelper;
-import com.occamlab.te.util.DomUtils;
-import com.occamlab.te.util.LogUtils;
-import com.occamlab.te.util.Misc;
-import com.occamlab.te.util.NullWriter;
-import com.occamlab.te.util.TEPath; // Fortify addition
-
-/**
- * Presents a test log for display.
- *
- */
-public class ViewLog {
-
- static public boolean hasCache = false;
- static String testName = " ";
-
- public static TransformerFactory transformerFactory = TransformerFactory.newInstance();
-
- public static boolean view_log(String suiteName, File logdir, String session, ArrayList tests,
- Templates templates, Writer out) throws Exception {
- return view_log(suiteName, logdir, session, tests, templates, out, 1);
- }
-
- public static boolean view_log(String suiteName, File logdir, String session, ArrayList tests,
- Templates templates, Writer out, int testnum) throws Exception {
- // Fortify mod: Validate logDir path
- TEPath tpath = new TEPath(logdir.getAbsolutePath());
- if (!tpath.isValid()) {
- System.out.println("ViewLog Error: Invalid log file name " + logdir);
- return false;
- }
- hasCache = false;
- Transformer t;
- if (templates == null) {
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- InputStream stream = cl.getResourceAsStream("com/occamlab/te/logstyles/default.xsl");
- t = transformerFactory.newTemplates(new StreamSource(stream)).newTransformer();
- }
- else {
- t = templates.newTransformer();
- }
- t.setParameter("sessionDir", session);
- t.setParameter("TESTNAME", suiteName);
- t.setParameter("logdir", logdir.getAbsolutePath());
- t.setParameter("testnum", Integer.toString(testnum));
- DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
-
- if (tests.isEmpty() && session == null) {
- Document doc = db.newDocument();
- Element sessions_e = doc.createElement("sessions");
- doc.appendChild(sessions_e);
- String[] children = logdir.list();
- for (int i = 0; i < children.length; i++) {
- if (new File(logdir, children[i]).isDirectory()) {
- Element session_e = doc.createElement("session");
- session_e.setAttribute("id", children[i]);
- sessions_e.appendChild(session_e);
- }
- }
- t.transform(new DOMSource(doc), new StreamResult(out));
- return true;
- }
- else if (tests.isEmpty()) {
- File session_dir = new File(logdir, session);
- if (!session_dir.isDirectory()) {
- System.out.println("Error: Directory " + session_dir.getAbsolutePath() + " does not exist.");
- return false;
- }
- Document doc = LogUtils.makeTestList(logdir, session);
- if (doc == null) {
- return false;
- }
- // increment_counts(doc.getDocumentElement());
- t.transform(new DOMSource(doc), new StreamResult(out));
- Element testElement = DomUtils.getElementByTagName(doc, "test");
- if (testElement == null) {
- return false;
- }
- else {
- setHasCache(testElement);
- return testElement.getAttribute("complete").equals("yes");
- }
- }
- else {
- boolean ret = true;
- for (String test : tests) {
- File f = new File(new File(logdir, test), "log.xml");
- if (f.exists()) {
- Document doc = LogUtils.makeTestList(logdir, test);
- if (doc == null) {
- return false;
- }
- Element testElement = DomUtils.getElementByTagName(doc, "test");
- if (testElement != null) {
- setHasCache(testElement);
- }
- t.setParameter("index", doc);
- Document log = LogUtils.readLog(logdir, test);
- t.transform(new DOMSource(log), new StreamResult(out));
- Element logElement = (Element) (log.getElementsByTagName("log").item(0));
- NodeList endtestlist = logElement.getElementsByTagName("endtest");
- ret = ret && (endtestlist.getLength() > 0);
- }
- else {
- System.out.println("Error: " + f.getAbsolutePath() + " does not exist.");
- ret = ret && false;
- }
- }
- return ret;
- }
- }
-
- static void setHasCache(Element testElement) {
- String hasCacheAttributeValue = testElement.getAttribute("hasCache");
- hasCache = (hasCacheAttributeValue == null) ? false : (hasCacheAttributeValue.equals("yes") ? true : false);
- }
-
- public static boolean hasCache() {
- return hasCache;
- }
-
- public static boolean checkCache(File logdir, String session) throws Exception {
- view_log(null, logdir, session, new ArrayList<>(), null, new NullWriter(), 1);
- return hasCache;
- }
-
- public static void main(String[] args) throws Exception {
- String testName = null;
- File logDir = (new RuntimeOptions()).getLogDir();
- String session = null;
- ArrayList tests = new ArrayList<>();
- String cmd = "java com.occamlab.te.ViewLog";
- String style = null;
- boolean listSessions = false;
- boolean ppLogs = false;
- boolean generateHtml = false;
-
- for (int i = 0; i < args.length; i++) {
- if (args[i].startsWith("-style=")) {
- style = args[i].substring(7);
- }
- else if (args[i].startsWith("-cmd=")) {
- cmd = args[i].substring(5);
- }
- else if (args[i].equals("-h") || args[i].equals("-help") || args[i].equals("-?")) {
- syntax(cmd);
- return;
- }
- else if (args[i].startsWith("-logdir=")) {
- String path = args[i].substring(8);
- File file = new File(path);
- if (file.isAbsolute()) {
- logDir = file;
- }
- else {
- logDir = new File(SetupOptions.getBaseConfigDirectory(), path);
- }
- }
- else if (args[i].equals("-sessions")) {
- listSessions = true;
- }
- else if (args[i].startsWith("-session=")) {
- session = args[i].substring(9);
- }
- else if (args[i].equals("-pp")) {
- ppLogs = true;
- }
- else if (args[i].equals("-html")) {
- generateHtml = true;
- }
- else if (!args[i].startsWith("-")) {
- tests.add(args[i]);
- }
- }
-
- if (ppLogs) {
- if (session == null) {
- syntax(cmd);
- return;
- }
- File sessionDir = new File(logDir, session);
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- DocumentationHelper docLogs = new DocumentationHelper(
- cl.getResource("com/occamlab/te/test_report_html.xsl"));
- File report = docLogs.prettyPrintsReport(sessionDir);
- if (report != null) {
- System.out.println("Generated " + report);
- }
- return;
- }
-
- if (generateHtml) {
- if (session == null) {
- syntax(cmd);
- return;
- }
- File sessionDir = new File(logDir, session);
- File testLog = new File(sessionDir, "report_logs.xml");
- RuntimeOptions opts = new RuntimeOptions();
- opts.setLogDir(logDir);
- opts.setSessionId(session);
- Map testInputMap = new HashMap<>();
- CtlEarlReporter reporter = new CtlEarlReporter();
- reporter.generateEarlReport(sessionDir, testLog, opts.getSourcesName(), testInputMap);
- EarlToHtmlTransformation earlToHtml = new EarlToHtmlTransformation();
- System.out.println("Generated EARL report " + earlToHtml.findEarlResultFile(sessionDir.getAbsolutePath()));
- File htmlResult = earlToHtml.earlHtmlReport(sessionDir.getAbsolutePath());
- System.out.println("Generated HTML report " + new File(htmlResult, "index.html"));
- return;
- }
-
- if (tests.isEmpty() && session == null && !listSessions) {
- syntax(cmd);
- return;
- }
-
- Templates templates = null;
- if (style != null) {
- File stylesheet = Misc.getResourceAsFile("com/occamlab/te/logstyles/default.xsl");
- stylesheet = new File(stylesheet.getParent(), style + ".xsl");
- if (!stylesheet.exists()) {
- System.out
- .println("Invalid style '" + style + "': " + stylesheet.getAbsolutePath() + " does not exist.");
- return;
- }
- templates = transformerFactory.newTemplates(new StreamSource(stylesheet));
- }
-
- Writer out = new OutputStreamWriter(System.out);
- view_log(testName, logDir, session, tests, templates, out);
- }
-
- static void syntax(String cmd) {
- System.out.println();
- System.out.println("To list user sessions:");
- System.out.println(" " + cmd + " [-logdir=dir] -sessions\n");
- System.out.println("To list tests in a session:");
- System.out.println(" " + cmd + " [-logdir=dir] -session=session\n");
- System.out.println("To view text results for individual tests:");
- System.out.println(" " + cmd + " [-logdir=dir] testpath1 [testpath2] ...\n");
- System.out.println("To \"Pretty Print\" the session results:");
- System.out.println(" " + cmd + " [-logdir=dir] -session=session -pp");
- System.out.println("To generate EARL and HTML reports of session results:");
- System.out.println(" " + cmd + " [-logdir=dir] -session=session -html");
- }
-
-}
+/****************************************************************************
+
+ The Original Code is TEAM Engine.
+
+ The Initial Developer of the Original Code is Northrop Grumman Corporation
+ jointly with The National Technology Alliance. Portions created by
+ Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
+ Grumman Corporation. All Rights Reserved.
+
+ Contributor(s):
+ Charles Heazel (WiSC): Modifications to address Fortify issues
+
+ ****************************************************************************/
+package com.occamlab.te;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.File;
+import java.io.InputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.Templates;
+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 org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import com.occamlab.te.html.EarlToHtmlTransformation;
+import com.occamlab.te.util.DocumentationHelper;
+import com.occamlab.te.util.DomUtils;
+import com.occamlab.te.util.LogUtils;
+import com.occamlab.te.util.Misc;
+import com.occamlab.te.util.NullWriter;
+import com.occamlab.te.util.TEPath; // Fortify addition
+
+/**
+ * Presents a test log for display.
+ *
+ */
+public class ViewLog {
+
+ static public boolean hasCache = false;
+ static String testName = " ";
+
+ public static TransformerFactory transformerFactory = TransformerFactory.newInstance();
+
+ public static boolean view_log(String suiteName, File logdir, String session, ArrayList tests,
+ Templates templates, Writer out) throws Exception {
+ return view_log(suiteName, logdir, session, tests, templates, out, 1);
+ }
+
+ public static boolean view_log(String suiteName, File logdir, String session, ArrayList tests,
+ Templates templates, Writer out, int testnum) throws Exception {
+ // Fortify mod: Validate logDir path
+ TEPath tpath = new TEPath(logdir.getAbsolutePath());
+ if (!tpath.isValid()) {
+ System.out.println("ViewLog Error: Invalid log file name " + logdir);
+ return false;
+ }
+ hasCache = false;
+ Transformer t;
+ if (templates == null) {
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ InputStream stream = cl.getResourceAsStream("com/occamlab/te/logstyles/default.xsl");
+ t = transformerFactory.newTemplates(new StreamSource(stream)).newTransformer();
+ }
+ else {
+ t = templates.newTransformer();
+ }
+ t.setParameter("sessionDir", session);
+ t.setParameter("TESTNAME", suiteName);
+ t.setParameter("logdir", logdir.getAbsolutePath());
+ t.setParameter("testnum", Integer.toString(testnum));
+ DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+
+ if (tests.isEmpty() && session == null) {
+ Document doc = db.newDocument();
+ Element sessions_e = doc.createElement("sessions");
+ doc.appendChild(sessions_e);
+ String[] children = logdir.list();
+ for (int i = 0; i < children.length; i++) {
+ if (new File(logdir, children[i]).isDirectory()) {
+ Element session_e = doc.createElement("session");
+ session_e.setAttribute("id", children[i]);
+ sessions_e.appendChild(session_e);
+ }
+ }
+ t.transform(new DOMSource(doc), new StreamResult(out));
+ return true;
+ }
+ else if (tests.isEmpty()) {
+ File session_dir = new File(logdir, session);
+ if (!session_dir.isDirectory()) {
+ System.out.println("Error: Directory " + session_dir.getAbsolutePath() + " does not exist.");
+ return false;
+ }
+ Document doc = LogUtils.makeTestList(logdir, session);
+ if (doc == null) {
+ return false;
+ }
+ // increment_counts(doc.getDocumentElement());
+ t.transform(new DOMSource(doc), new StreamResult(out));
+ Element testElement = DomUtils.getElementByTagName(doc, "test");
+ if (testElement == null) {
+ return false;
+ }
+ else {
+ setHasCache(testElement);
+ return testElement.getAttribute("complete").equals("yes");
+ }
+ }
+ else {
+ boolean ret = true;
+ for (String test : tests) {
+ File f = new File(new File(logdir, test), "log.xml");
+ if (f.exists()) {
+ Document doc = LogUtils.makeTestList(logdir, test);
+ if (doc == null) {
+ return false;
+ }
+ Element testElement = DomUtils.getElementByTagName(doc, "test");
+ if (testElement != null) {
+ setHasCache(testElement);
+ }
+ t.setParameter("index", doc);
+ Document log = LogUtils.readLog(logdir, test);
+ t.transform(new DOMSource(log), new StreamResult(out));
+ Element logElement = (Element) (log.getElementsByTagName("log").item(0));
+ NodeList endtestlist = logElement.getElementsByTagName("endtest");
+ ret = ret && (endtestlist.getLength() > 0);
+ }
+ else {
+ System.out.println("Error: " + f.getAbsolutePath() + " does not exist.");
+ ret = ret && false;
+ }
+ }
+ return ret;
+ }
+ }
+
+ static void setHasCache(Element testElement) {
+ String hasCacheAttributeValue = testElement.getAttribute("hasCache");
+ hasCache = (hasCacheAttributeValue == null) ? false : (hasCacheAttributeValue.equals("yes") ? true : false);
+ }
+
+ public static boolean hasCache() {
+ return hasCache;
+ }
+
+ public static boolean checkCache(File logdir, String session) throws Exception {
+ view_log(null, logdir, session, new ArrayList<>(), null, new NullWriter(), 1);
+ return hasCache;
+ }
+
+ public static void main(String[] args) throws Exception {
+ String testName = null;
+ File logDir = (new RuntimeOptions()).getLogDir();
+ String session = null;
+ ArrayList tests = new ArrayList<>();
+ String cmd = "java com.occamlab.te.ViewLog";
+ String style = null;
+ boolean listSessions = false;
+ boolean ppLogs = false;
+ boolean generateHtml = false;
+
+ for (int i = 0; i < args.length; i++) {
+ if (args[i].startsWith("-style=")) {
+ style = args[i].substring(7);
+ }
+ else if (args[i].startsWith("-cmd=")) {
+ cmd = args[i].substring(5);
+ }
+ else if (args[i].equals("-h") || args[i].equals("-help") || args[i].equals("-?")) {
+ syntax(cmd);
+ return;
+ }
+ else if (args[i].startsWith("-logdir=")) {
+ String path = args[i].substring(8);
+ File file = new File(path);
+ if (file.isAbsolute()) {
+ logDir = file;
+ }
+ else {
+ logDir = new File(SetupOptions.getBaseConfigDirectory(), path);
+ }
+ }
+ else if (args[i].equals("-sessions")) {
+ listSessions = true;
+ }
+ else if (args[i].startsWith("-session=")) {
+ session = args[i].substring(9);
+ }
+ else if (args[i].equals("-pp")) {
+ ppLogs = true;
+ }
+ else if (args[i].equals("-html")) {
+ generateHtml = true;
+ }
+ else if (!args[i].startsWith("-")) {
+ tests.add(args[i]);
+ }
+ }
+
+ if (ppLogs) {
+ if (session == null) {
+ syntax(cmd);
+ return;
+ }
+ File sessionDir = new File(logDir, session);
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ DocumentationHelper docLogs = new DocumentationHelper(
+ cl.getResource("com/occamlab/te/test_report_html.xsl"));
+ File report = docLogs.prettyPrintsReport(sessionDir);
+ if (report != null) {
+ System.out.println("Generated " + report);
+ }
+ return;
+ }
+
+ if (generateHtml) {
+ if (session == null) {
+ syntax(cmd);
+ return;
+ }
+ File sessionDir = new File(logDir, session);
+ File testLog = new File(sessionDir, "report_logs.xml");
+ RuntimeOptions opts = new RuntimeOptions();
+ opts.setLogDir(logDir);
+ opts.setSessionId(session);
+ Map testInputMap = new HashMap<>();
+ CtlEarlReporter reporter = new CtlEarlReporter();
+ reporter.generateEarlReport(sessionDir, testLog, opts.getSourcesName(), testInputMap);
+ EarlToHtmlTransformation earlToHtml = new EarlToHtmlTransformation();
+ System.out.println("Generated EARL report " + earlToHtml.findEarlResultFile(sessionDir.getAbsolutePath()));
+ File htmlResult = earlToHtml.earlHtmlReport(sessionDir.getAbsolutePath());
+ System.out.println("Generated HTML report " + new File(htmlResult, "index.html"));
+ return;
+ }
+
+ if (tests.isEmpty() && session == null && !listSessions) {
+ syntax(cmd);
+ return;
+ }
+
+ Templates templates = null;
+ if (style != null) {
+ File stylesheet = Misc.getResourceAsFile("com/occamlab/te/logstyles/default.xsl");
+ stylesheet = new File(stylesheet.getParent(), style + ".xsl");
+ if (!stylesheet.exists()) {
+ System.out
+ .println("Invalid style '" + style + "': " + stylesheet.getAbsolutePath() + " does not exist.");
+ return;
+ }
+ templates = transformerFactory.newTemplates(new StreamSource(stylesheet));
+ }
+
+ Writer out = new OutputStreamWriter(System.out);
+ view_log(testName, logDir, session, tests, templates, out);
+ }
+
+ static void syntax(String cmd) {
+ System.out.println();
+ System.out.println("To list user sessions:");
+ System.out.println(" " + cmd + " [-logdir=dir] -sessions\n");
+ System.out.println("To list tests in a session:");
+ System.out.println(" " + cmd + " [-logdir=dir] -session=session\n");
+ System.out.println("To view text results for individual tests:");
+ System.out.println(" " + cmd + " [-logdir=dir] testpath1 [testpath2] ...\n");
+ System.out.println("To \"Pretty Print\" the session results:");
+ System.out.println(" " + cmd + " [-logdir=dir] -session=session -pp");
+ System.out.println("To generate EARL and HTML reports of session results:");
+ System.out.println(" " + cmd + " [-logdir=dir] -session=session -html");
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/config/Config.java b/teamengine-core/src/main/java/com/occamlab/te/config/Config.java
index d750c85ab..850c35ef1 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/config/Config.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/config/Config.java
@@ -19,6 +19,26 @@ C. Heazel (WiSC): Added Fortify adjudication changes
****************************************************************************/
package com.occamlab.te.config;
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
diff --git a/teamengine-core/src/main/java/com/occamlab/te/config/ConfigComparator.java b/teamengine-core/src/main/java/com/occamlab/te/config/ConfigComparator.java
index cab27d8fb..e3dc9adea 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/config/ConfigComparator.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/config/ConfigComparator.java
@@ -1,37 +1,57 @@
-package com.occamlab.te.config;
-
-import java.util.Comparator;
-
-/**
- * Compares two ConfigEntry objects for order.
- *
- */
-public class ConfigComparator implements Comparator {
-
- private String denull(String s) {
- return s == null ? "" : s;
- }
-
- public int compare(ConfigEntry o1, ConfigEntry o2) {
- int i = o1.organization.compareTo(o2.organization);
- if (i != 0)
- return i;
- i = o1.standard.compareTo(o2.standard);
- if (i != 0)
- return i;
- i = o1.version.compareTo(o2.version);
- if (i != 0)
- return i;
- if (o1.suite != null && o2.suite != null) {
- return denull(o1.revision).compareTo(denull(o2.revision));
- }
- if (o1.suite == null && o2.suite != null) {
- return -1;
- }
- if (o1.suite != null && o2.suite == null) {
- return 1;
- }
- return 0;
- }
-
-}
+package com.occamlab.te.config;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.util.Comparator;
+
+/**
+ * Compares two ConfigEntry objects for order.
+ *
+ */
+public class ConfigComparator implements Comparator {
+
+ private String denull(String s) {
+ return s == null ? "" : s;
+ }
+
+ public int compare(ConfigEntry o1, ConfigEntry o2) {
+ int i = o1.organization.compareTo(o2.organization);
+ if (i != 0)
+ return i;
+ i = o1.standard.compareTo(o2.standard);
+ if (i != 0)
+ return i;
+ i = o1.version.compareTo(o2.version);
+ if (i != 0)
+ return i;
+ if (o1.suite != null && o2.suite != null) {
+ return denull(o1.revision).compareTo(denull(o2.revision));
+ }
+ if (o1.suite == null && o2.suite != null) {
+ return -1;
+ }
+ if (o1.suite != null && o2.suite == null) {
+ return 1;
+ }
+ return 0;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/config/ConfigEntry.java b/teamengine-core/src/main/java/com/occamlab/te/config/ConfigEntry.java
index 2e7060911..9b2eefce6 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/config/ConfigEntry.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/config/ConfigEntry.java
@@ -1,169 +1,189 @@
-/**
- * **************************************************************************
- *
- * Contributor(s):
- * C. Heazel (WiSC): Added Fortify adjudication changes
- *
- ***************************************************************************
- */
-package com.occamlab.te.config;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import javax.xml.namespace.QName;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-/* Used exclusively in ConfigFileBuilder and ConfigComparator */
-public final class ConfigEntry {
-
- public String organization = null;
-
- public String standard = null;
-
- public String version = null;
-
- public String revision = null;
-
- public QName suite = null;
-
- public String title = null;
-
- public String description = null;
-
- public String link = null;
-
- public String dataLink = null;
-
- public List profiles = new ArrayList<>();
-
- public List profileTitles = new ArrayList<>();
-
- public List profileDescriptions = new ArrayList<>();
-
- public List sources = new ArrayList<>();
-
- public File resources;
-
- public String webdir;
-
- ConfigEntry(File file) throws Exception {
- readConfigFile(file);
- }
-
- void readConfigFile(File file) throws Exception {
- // Fortify Mod: prevent external entity injection
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setExpandEntityReferences(false);
- DocumentBuilder db = dbf.newDocumentBuilder();
- // DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- Document doc = db.parse(file);
- Element config = doc.getDocumentElement();
- Element organizationEl = getElementByTagName(config, "organization");
- if (organizationEl != null) {
- organization = getElementByTagName(organizationEl, "name").getTextContent();
- }
- Element standardEl = getElementByTagName(config, "standard");
- if (standardEl != null) {
- standard = getElementByTagName(standardEl, "name").getTextContent();
- }
- Element versionEl = getElementByTagName(config, "version");
- if (versionEl != null) {
- version = getElementByTagName(versionEl, "name").getTextContent();
- }
- Element revisionEl = getElementByTagName(config, "revision");
- if (revisionEl != null) {
- revision = getElementByTagName(revisionEl, "name").getTextContent();
- }
- Element suiteEl = getElementByTagName(config, "suite");
- if (suiteEl != null) {
- String localName = getElementByTagName(suiteEl, "local-name").getTextContent();
- String namespaceUri = getElementByTagName(suiteEl, "namespace-uri").getTextContent();
- String prefix = getElementByTagName(suiteEl, "prefix").getTextContent();
- suite = new QName(namespaceUri, localName, prefix);
- Element titleEl = getElementByTagName(suiteEl, "title");
- if (titleEl != null) {
- title = titleEl.getTextContent();
- }
- Element descriptionEl = getElementByTagName(suiteEl, "description");
- if (descriptionEl != null) {
- description = descriptionEl.getTextContent();
- }
- NodeList linkNodes = suiteEl.getElementsByTagName("link");
- for (int i = 0; i < linkNodes.getLength(); i++) {
- Element linkEl = (Element) linkNodes.item(i);
- String value = linkEl.getTextContent();
- if ("data".equals(linkEl.getAttribute("linkType"))) {
- dataLink = file.getParentFile().getName() + "/" + value;
- }
- else if (value.startsWith("data/")) {
- dataLink = file.getParentFile().getName() + "/" + value;
- }
- else {
- link = value;
- }
- }
- }
- NodeList profileNodes = config.getElementsByTagName("profile");
- for (int i = 0; i < profileNodes.getLength(); i++) {
- Element profileEl = (Element) profileNodes.item(i);
- String localName = getElementByTagName(profileEl, "local-name").getTextContent();
- String namespaceUri = getElementByTagName(profileEl, "namespace-uri").getTextContent();
- String prefix = getElementByTagName(profileEl, "prefix").getTextContent();
- profiles.add(new QName(namespaceUri, localName, prefix));
- Element titleEl = getElementByTagName(profileEl, "title");
- profileTitles.add(titleEl == null ? "" : titleEl.getTextContent());
- Element descriptionEl = getElementByTagName(profileEl, "description");
- profileDescriptions.add(descriptionEl == null ? "" : descriptionEl.getTextContent());
- }
- NodeList sourceNodes = config.getElementsByTagName("source");
- for (int i = 0; i < sourceNodes.getLength(); i++) {
- Element sourceEl = (Element) sourceNodes.item(i);
- sources.add(new File(file.getParentFile(), sourceEl.getTextContent()));
- }
- Element resourcesEl = getElementByTagName(config, "resources");
- if (resourcesEl != null) {
- resources = new File(file.getParentFile(), resourcesEl.getTextContent());
- }
- webdir = file.getParentFile().getName();
- Element webEl = getElementByTagName(config, "web");
- if (webEl != null) {
- String dirname = webEl.getAttribute("dirname");
- if (dirname.length() > 0) {
- webdir = dirname;
- }
- }
- }
-
- void add(ConfigEntry config) {
- profiles.addAll(config.profiles);
- profileTitles.addAll(config.profileTitles);
- profileDescriptions.addAll(config.profileDescriptions);
- sources.addAll(config.sources);
- }
-
- Element getElementByTagName(Node node, String tagname) {
- NodeList nl;
- if (node.getNodeType() == Node.DOCUMENT_NODE) {
- nl = ((Document) node).getElementsByTagName(tagname);
- }
- else if (node.getNodeType() == Node.ELEMENT_NODE) {
- nl = ((Element) node).getElementsByTagName(tagname);
- }
- else {
- return null;
- }
- if (nl.getLength() >= 0) {
- return (Element) nl.item(0);
- }
- else {
- return null;
- }
- }
-
-}
+/**
+ * **************************************************************************
+ *
+ * Contributor(s):
+ * C. Heazel (WiSC): Added Fortify adjudication changes
+ *
+ ***************************************************************************
+ */
+package com.occamlab.te.config;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.namespace.QName;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/* Used exclusively in ConfigFileBuilder and ConfigComparator */
+public final class ConfigEntry {
+
+ public String organization = null;
+
+ public String standard = null;
+
+ public String version = null;
+
+ public String revision = null;
+
+ public QName suite = null;
+
+ public String title = null;
+
+ public String description = null;
+
+ public String link = null;
+
+ public String dataLink = null;
+
+ public List profiles = new ArrayList<>();
+
+ public List profileTitles = new ArrayList<>();
+
+ public List profileDescriptions = new ArrayList<>();
+
+ public List sources = new ArrayList<>();
+
+ public File resources;
+
+ public String webdir;
+
+ ConfigEntry(File file) throws Exception {
+ readConfigFile(file);
+ }
+
+ void readConfigFile(File file) throws Exception {
+ // Fortify Mod: prevent external entity injection
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setExpandEntityReferences(false);
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ // DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+ Document doc = db.parse(file);
+ Element config = doc.getDocumentElement();
+ Element organizationEl = getElementByTagName(config, "organization");
+ if (organizationEl != null) {
+ organization = getElementByTagName(organizationEl, "name").getTextContent();
+ }
+ Element standardEl = getElementByTagName(config, "standard");
+ if (standardEl != null) {
+ standard = getElementByTagName(standardEl, "name").getTextContent();
+ }
+ Element versionEl = getElementByTagName(config, "version");
+ if (versionEl != null) {
+ version = getElementByTagName(versionEl, "name").getTextContent();
+ }
+ Element revisionEl = getElementByTagName(config, "revision");
+ if (revisionEl != null) {
+ revision = getElementByTagName(revisionEl, "name").getTextContent();
+ }
+ Element suiteEl = getElementByTagName(config, "suite");
+ if (suiteEl != null) {
+ String localName = getElementByTagName(suiteEl, "local-name").getTextContent();
+ String namespaceUri = getElementByTagName(suiteEl, "namespace-uri").getTextContent();
+ String prefix = getElementByTagName(suiteEl, "prefix").getTextContent();
+ suite = new QName(namespaceUri, localName, prefix);
+ Element titleEl = getElementByTagName(suiteEl, "title");
+ if (titleEl != null) {
+ title = titleEl.getTextContent();
+ }
+ Element descriptionEl = getElementByTagName(suiteEl, "description");
+ if (descriptionEl != null) {
+ description = descriptionEl.getTextContent();
+ }
+ NodeList linkNodes = suiteEl.getElementsByTagName("link");
+ for (int i = 0; i < linkNodes.getLength(); i++) {
+ Element linkEl = (Element) linkNodes.item(i);
+ String value = linkEl.getTextContent();
+ if ("data".equals(linkEl.getAttribute("linkType"))) {
+ dataLink = file.getParentFile().getName() + "/" + value;
+ }
+ else if (value.startsWith("data/")) {
+ dataLink = file.getParentFile().getName() + "/" + value;
+ }
+ else {
+ link = value;
+ }
+ }
+ }
+ NodeList profileNodes = config.getElementsByTagName("profile");
+ for (int i = 0; i < profileNodes.getLength(); i++) {
+ Element profileEl = (Element) profileNodes.item(i);
+ String localName = getElementByTagName(profileEl, "local-name").getTextContent();
+ String namespaceUri = getElementByTagName(profileEl, "namespace-uri").getTextContent();
+ String prefix = getElementByTagName(profileEl, "prefix").getTextContent();
+ profiles.add(new QName(namespaceUri, localName, prefix));
+ Element titleEl = getElementByTagName(profileEl, "title");
+ profileTitles.add(titleEl == null ? "" : titleEl.getTextContent());
+ Element descriptionEl = getElementByTagName(profileEl, "description");
+ profileDescriptions.add(descriptionEl == null ? "" : descriptionEl.getTextContent());
+ }
+ NodeList sourceNodes = config.getElementsByTagName("source");
+ for (int i = 0; i < sourceNodes.getLength(); i++) {
+ Element sourceEl = (Element) sourceNodes.item(i);
+ sources.add(new File(file.getParentFile(), sourceEl.getTextContent()));
+ }
+ Element resourcesEl = getElementByTagName(config, "resources");
+ if (resourcesEl != null) {
+ resources = new File(file.getParentFile(), resourcesEl.getTextContent());
+ }
+ webdir = file.getParentFile().getName();
+ Element webEl = getElementByTagName(config, "web");
+ if (webEl != null) {
+ String dirname = webEl.getAttribute("dirname");
+ if (dirname.length() > 0) {
+ webdir = dirname;
+ }
+ }
+ }
+
+ void add(ConfigEntry config) {
+ profiles.addAll(config.profiles);
+ profileTitles.addAll(config.profileTitles);
+ profileDescriptions.addAll(config.profileDescriptions);
+ sources.addAll(config.sources);
+ }
+
+ Element getElementByTagName(Node node, String tagname) {
+ NodeList nl;
+ if (node.getNodeType() == Node.DOCUMENT_NODE) {
+ nl = ((Document) node).getElementsByTagName(tagname);
+ }
+ else if (node.getNodeType() == Node.ELEMENT_NODE) {
+ nl = ((Element) node).getElementsByTagName(tagname);
+ }
+ else {
+ return null;
+ }
+ if (nl.getLength() >= 0) {
+ return (Element) nl.item(0);
+ }
+ else {
+ return null;
+ }
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/config/ConfigFileBuilder.java b/teamengine-core/src/main/java/com/occamlab/te/config/ConfigFileBuilder.java
index d55f9e48d..dfc2db635 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/config/ConfigFileBuilder.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/config/ConfigFileBuilder.java
@@ -1,187 +1,207 @@
-package com.occamlab.te.config;
-
-import java.io.File;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.List;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import javax.xml.namespace.QName;
-
-public class ConfigFileBuilder {
-
- /*
- * Build an example master teamengine config file. To aggregate config files from
- * several ETSs into a master config file, use ConfigFileCreator instead.
- */
- public static void main(String[] args) throws Exception {
- String home = "";
- String scriptsDir = "webapps/teamengine/WEB-INF/scripts";
- String workDir = "webapps/teamengine/WEB-INF/work";
- String usersDir = "webapps/teamengine/WEB-INF/users";
- String resourcesDir = null;
- String defaultRevision = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
-
- // Parse arguments from command-line
- for (int i = 0; i < args.length; i++) {
- if (args[i].startsWith("-home=")) {
- home = args[i].substring(6);
- }
- else if (args[i].startsWith("-scriptsdir=")) {
- scriptsDir = args[i].substring(12);
- }
- else if (args[i].startsWith("-resourcesdir=")) {
- scriptsDir = args[i].substring(14);
- }
- else if (args[i].startsWith("-usersdir=")) {
- usersDir = args[i].substring(10);
- }
- else if (args[i].startsWith("-workdir=")) {
- workDir = args[i].substring(9);
- }
- else if (args[i].startsWith("-defaultrev=")) {
- defaultRevision = args[i].substring(12);
- }
- }
-
- if (resourcesDir == null) {
- resourcesDir = scriptsDir;
- }
-
- SortedSet configs = new TreeSet<>(new ConfigComparator());
-
- File[] scriptDirs = new File(".").listFiles();
- for (File dir : scriptDirs) {
- File file = new File(dir, "config.xml");
- if (file.canRead()) {
- ConfigEntry config = new ConfigEntry(file);
- File profilesDir = new File(dir, "profiles");
- if (profilesDir.isDirectory()) {
- File[] profileDirs = profilesDir.listFiles();
- for (File pdir : profileDirs) {
- File pfile = new File(pdir, "config.xml");
- if (pfile.canRead()) {
- config.add(new ConfigEntry(pfile));
- }
- }
- }
- configs.add(config);
- }
- }
-
- System.out.println("");
- System.out.println(" " + home + " ");
- System.out.println(" " + scriptsDir + " ");
- System.out.println(" " + resourcesDir + " ");
- System.out.println(" " + usersDir + " ");
- System.out.println(" " + workDir + " ");
- System.out.println(" ");
-
- Iterator it = configs.iterator();
- ConfigEntry config = it.hasNext() ? it.next() : null;
- while (config != null) {
- String organization = config.organization;
- System.out.println(" ");
- System.out.println(" " + organization + " ");
- while (config != null && config.organization.equals(organization)) {
- String standard = config.standard;
- System.out.println(" ");
- System.out.println(" " + standard + " ");
- while (config != null && config.organization.equals(organization) && config.standard.equals(standard)) {
- String version = config.version;
- System.out.println(" ");
- System.out.println(" " + version + " ");
- System.out.println(" ");
- System.out
- .println(" " + config.suite.getNamespaceURI() + " ");
- System.out.println(" " + config.suite.getPrefix() + " ");
- System.out.println(" " + config.suite.getLocalPart() + " ");
- String title = config.title;
- if (title == null) {
- title = organization + " " + standard + " " + version + " Test Suite";
- }
- System.out.println(" " + title + " ");
- if (config.description != null) {
- System.out.println(" " + config.description + " ");
- }
- if (config.link != null) {
- System.out.println(" " + config.link + "");
- }
- if (config.dataLink != null) {
- System.out.println(" " + config.dataLink + "");
- }
- System.out.println(" ");
- while (config != null && config.organization.equals(organization)
- && config.standard.equals(standard) && config.version.equals(version)) {
- List profiles = new ArrayList<>();
- List profileTitles = new ArrayList<>();
- List profileDescriptions = new ArrayList<>();
- List sources = new ArrayList<>();
- while (config != null && config.suite == null) {
- profiles.addAll(config.profiles);
- profileTitles.addAll(config.profileTitles);
- profileDescriptions.addAll(config.profileDescriptions);
- sources.addAll(config.sources);
- config = it.hasNext() ? it.next() : null;
- }
- if (config != null) {
- profiles.addAll(config.profiles);
- profileTitles.addAll(config.profileTitles);
- profileDescriptions.addAll(config.profileDescriptions);
- sources.addAll(config.sources);
- String revision = config.revision;
- if (revision == null) {
- revision = defaultRevision;
- }
- System.out.println(" ");
- System.out.println(" " + revision + " ");
- System.out.println(" ");
- for (File source : sources) {
- String path = source.getPath().substring(2).replace('\\', '/');
- System.out.println(" " + path + " ");
- }
- System.out.println(" ");
- if (config.resources != null) {
- String path = config.resources.getPath().substring(2).replace('\\', '/');
- System.out.println(" " + path + " ");
- }
- if (config.webdir != null) {
- System.out.println(" " + config.webdir + " ");
- }
- for (int i = 0; i < profiles.size(); i++) {
- System.out.println(" ");
- System.out.println(" " + profiles.get(i).getNamespaceURI()
- + " ");
- System.out
- .println(" " + profiles.get(i).getPrefix() + " ");
- System.out.println(" " + profiles.get(i).getLocalPart()
- + " ");
- String profileTitle = profileTitles.get(i);
- if (profileTitle == null)
- profileTitle = profiles.get(i).getLocalPart();
- System.out.println(" " + profileTitle + " ");
- String profileDescription = profileDescriptions.get(i);
- if (profileDescription != null) {
- System.out
- .println(" " + profileDescription + " ");
- }
- System.out.println(" ");
- }
- System.out.println(" ");
- config = it.hasNext() ? it.next() : null;
- }
- }
- System.out.println(" ");
- }
- System.out.println(" ");
- }
- System.out.println(" ");
- }
- System.out.println(" ");
- System.out.println(" ");
- }
-
-}
+package com.occamlab.te.config;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.File;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import javax.xml.namespace.QName;
+
+public class ConfigFileBuilder {
+
+ /*
+ * Build an example master teamengine config file. To aggregate config files from
+ * several ETSs into a master config file, use ConfigFileCreator instead.
+ */
+ public static void main(String[] args) throws Exception {
+ String home = "";
+ String scriptsDir = "webapps/teamengine/WEB-INF/scripts";
+ String workDir = "webapps/teamengine/WEB-INF/work";
+ String usersDir = "webapps/teamengine/WEB-INF/users";
+ String resourcesDir = null;
+ String defaultRevision = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
+
+ // Parse arguments from command-line
+ for (int i = 0; i < args.length; i++) {
+ if (args[i].startsWith("-home=")) {
+ home = args[i].substring(6);
+ }
+ else if (args[i].startsWith("-scriptsdir=")) {
+ scriptsDir = args[i].substring(12);
+ }
+ else if (args[i].startsWith("-resourcesdir=")) {
+ scriptsDir = args[i].substring(14);
+ }
+ else if (args[i].startsWith("-usersdir=")) {
+ usersDir = args[i].substring(10);
+ }
+ else if (args[i].startsWith("-workdir=")) {
+ workDir = args[i].substring(9);
+ }
+ else if (args[i].startsWith("-defaultrev=")) {
+ defaultRevision = args[i].substring(12);
+ }
+ }
+
+ if (resourcesDir == null) {
+ resourcesDir = scriptsDir;
+ }
+
+ SortedSet configs = new TreeSet<>(new ConfigComparator());
+
+ File[] scriptDirs = new File(".").listFiles();
+ for (File dir : scriptDirs) {
+ File file = new File(dir, "config.xml");
+ if (file.canRead()) {
+ ConfigEntry config = new ConfigEntry(file);
+ File profilesDir = new File(dir, "profiles");
+ if (profilesDir.isDirectory()) {
+ File[] profileDirs = profilesDir.listFiles();
+ for (File pdir : profileDirs) {
+ File pfile = new File(pdir, "config.xml");
+ if (pfile.canRead()) {
+ config.add(new ConfigEntry(pfile));
+ }
+ }
+ }
+ configs.add(config);
+ }
+ }
+
+ System.out.println("");
+ System.out.println(" " + home + " ");
+ System.out.println(" " + scriptsDir + " ");
+ System.out.println(" " + resourcesDir + " ");
+ System.out.println(" " + usersDir + " ");
+ System.out.println(" " + workDir + " ");
+ System.out.println(" ");
+
+ Iterator it = configs.iterator();
+ ConfigEntry config = it.hasNext() ? it.next() : null;
+ while (config != null) {
+ String organization = config.organization;
+ System.out.println(" ");
+ System.out.println(" " + organization + " ");
+ while (config != null && config.organization.equals(organization)) {
+ String standard = config.standard;
+ System.out.println(" ");
+ System.out.println(" " + standard + " ");
+ while (config != null && config.organization.equals(organization) && config.standard.equals(standard)) {
+ String version = config.version;
+ System.out.println(" ");
+ System.out.println(" " + version + " ");
+ System.out.println(" ");
+ System.out
+ .println(" " + config.suite.getNamespaceURI() + " ");
+ System.out.println(" " + config.suite.getPrefix() + " ");
+ System.out.println(" " + config.suite.getLocalPart() + " ");
+ String title = config.title;
+ if (title == null) {
+ title = organization + " " + standard + " " + version + " Test Suite";
+ }
+ System.out.println(" " + title + " ");
+ if (config.description != null) {
+ System.out.println(" " + config.description + " ");
+ }
+ if (config.link != null) {
+ System.out.println(" " + config.link + "");
+ }
+ if (config.dataLink != null) {
+ System.out.println(" " + config.dataLink + "");
+ }
+ System.out.println(" ");
+ while (config != null && config.organization.equals(organization)
+ && config.standard.equals(standard) && config.version.equals(version)) {
+ List profiles = new ArrayList<>();
+ List profileTitles = new ArrayList<>();
+ List profileDescriptions = new ArrayList<>();
+ List sources = new ArrayList<>();
+ while (config != null && config.suite == null) {
+ profiles.addAll(config.profiles);
+ profileTitles.addAll(config.profileTitles);
+ profileDescriptions.addAll(config.profileDescriptions);
+ sources.addAll(config.sources);
+ config = it.hasNext() ? it.next() : null;
+ }
+ if (config != null) {
+ profiles.addAll(config.profiles);
+ profileTitles.addAll(config.profileTitles);
+ profileDescriptions.addAll(config.profileDescriptions);
+ sources.addAll(config.sources);
+ String revision = config.revision;
+ if (revision == null) {
+ revision = defaultRevision;
+ }
+ System.out.println(" ");
+ System.out.println(" " + revision + " ");
+ System.out.println(" ");
+ for (File source : sources) {
+ String path = source.getPath().substring(2).replace('\\', '/');
+ System.out.println(" " + path + " ");
+ }
+ System.out.println(" ");
+ if (config.resources != null) {
+ String path = config.resources.getPath().substring(2).replace('\\', '/');
+ System.out.println(" " + path + " ");
+ }
+ if (config.webdir != null) {
+ System.out.println(" " + config.webdir + " ");
+ }
+ for (int i = 0; i < profiles.size(); i++) {
+ System.out.println(" ");
+ System.out.println(" " + profiles.get(i).getNamespaceURI()
+ + " ");
+ System.out
+ .println(" " + profiles.get(i).getPrefix() + " ");
+ System.out.println(" " + profiles.get(i).getLocalPart()
+ + " ");
+ String profileTitle = profileTitles.get(i);
+ if (profileTitle == null)
+ profileTitle = profiles.get(i).getLocalPart();
+ System.out.println(" " + profileTitle + " ");
+ String profileDescription = profileDescriptions.get(i);
+ if (profileDescription != null) {
+ System.out
+ .println(" " + profileDescription + " ");
+ }
+ System.out.println(" ");
+ }
+ System.out.println(" ");
+ config = it.hasNext() ? it.next() : null;
+ }
+ }
+ System.out.println(" ");
+ }
+ System.out.println(" ");
+ }
+ System.out.println(" ");
+ }
+ System.out.println(" ");
+ System.out.println(" ");
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/config/ConfigFileCreator.java b/teamengine-core/src/main/java/com/occamlab/te/config/ConfigFileCreator.java
index f72e881a8..c9ed9f915 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/config/ConfigFileCreator.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/config/ConfigFileCreator.java
@@ -14,6 +14,26 @@
*/
package com.occamlab.te.config;
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
diff --git a/teamengine-core/src/main/java/com/occamlab/te/config/TEBaseNotFoundException.java b/teamengine-core/src/main/java/com/occamlab/te/config/TEBaseNotFoundException.java
index 236fc6077..763523adb 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/config/TEBaseNotFoundException.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/config/TEBaseNotFoundException.java
@@ -7,6 +7,26 @@
*/
package com.occamlab.te.config;
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
/**
* Exception thrown when TE_BASE is not found.
*
diff --git a/teamengine-core/src/main/java/com/occamlab/te/config/TEConfigException.java b/teamengine-core/src/main/java/com/occamlab/te/config/TEConfigException.java
index bf925aa2a..1a513ea8c 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/config/TEConfigException.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/config/TEConfigException.java
@@ -7,6 +7,26 @@
*/
package com.occamlab.te.config;
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
public class TEConfigException extends RuntimeException {
/**
diff --git a/teamengine-core/src/main/java/com/occamlab/te/config/package-info.java b/teamengine-core/src/main/java/com/occamlab/te/config/package-info.java
index 2cc2bea6e..0028fc4b4 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/config/package-info.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/config/package-info.java
@@ -1,4 +1,23 @@
-/**
- * This package provides classes for building and reading configuration files.
- */
-package com.occamlab.te.config;
\ No newline at end of file
+/**
+ * This package provides classes for building and reading configuration files.
+ */
+package com.occamlab.te.config;
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
diff --git a/teamengine-core/src/main/java/com/occamlab/te/form/ImageHandler.java b/teamengine-core/src/main/java/com/occamlab/te/form/ImageHandler.java
index 3e7deed9a..92696eee3 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/form/ImageHandler.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/form/ImageHandler.java
@@ -1,5 +1,25 @@
package com.occamlab.te.form;
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
diff --git a/teamengine-core/src/main/java/com/occamlab/te/html/EarlToHtmlTransformation.java b/teamengine-core/src/main/java/com/occamlab/te/html/EarlToHtmlTransformation.java
index 8c02dee4f..5bbf2ccec 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/html/EarlToHtmlTransformation.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/html/EarlToHtmlTransformation.java
@@ -1,5 +1,25 @@
package com.occamlab.te.html;
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.SEVERE;
diff --git a/teamengine-core/src/main/java/com/occamlab/te/index/FunctionEntry.java b/teamengine-core/src/main/java/com/occamlab/te/index/FunctionEntry.java
index 27191df33..f84655019 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/index/FunctionEntry.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/index/FunctionEntry.java
@@ -1,195 +1,215 @@
-package com.occamlab.te.index;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-public class FunctionEntry extends TemplateEntry {
-
- boolean java;
-
- boolean initialized;
-
- String className;
-
- String method;
-
- int minArgs;
-
- int maxArgs;
-
- List classParams = null;
-
- FunctionEntry() {
- super();
- }
-
- // public void persistAttributes(PrintWriter out) {
- // super.persistAttributes(out);
- // out.print(" type=\"" + (java ? "java" : "xsl") + "\"");
- // }
- //
- // public void persistTags(PrintWriter out) {
- // super.persistTags(out);
- // if (minArgs != maxArgs) {
- // int min = minArgs;
- // int max = maxArgs;
- // if (getParams() != null) {
- // min -= getParams().size();
- // max -= getParams().size();
- // }
- // if (usesContext()) {
- // min--;
- // max--;
- // }
- // out.println(" ");
- // }
- // }
- //
- // public void persist(PrintWriter out) {
- // persist(out, "function");
- // }
-
- FunctionEntry(Element function) {
- super(function);
- // System.out.println(DomUtils.serializeNode(function));
- // try {
- String type = function.getAttribute("type");
- if (type.equals("xsl")) {
- setJava(false);
- // setTemplateFile(new File(new
- // URI(function.getAttribute("file"))));
- }
- else if (type.equals("java")) {
- // System.out.println(this.getId());
- setJava(true);
- }
- else {
- throw new RuntimeException("Invalid function type");
- }
- // NodeList nl = function.getElementsByTagName("param");
- // minArgs = nl.getLength();
- minArgs = 0;
- if (this.getParams() != null) {
- minArgs = this.getParams().size();
- }
- maxArgs = minArgs;
- // params = new ArrayList();
- // if (minArgs > 0) {
- // for (int i = 0; i < minArgs; i++) {
- // Element el = (Element)nl.item(i);
- // String prefix = el.getAttribute("prefix");
- // String namespaceUri = el.getAttribute("namespace-uri");
- // String localName = el.getAttribute("local-name");
- // params.add(new QName(namespaceUri, localName, prefix));
- // }
- // }
- NodeList nl = function.getElementsByTagName("var-params");
- if (nl.getLength() > 0) {
- Element varParams = (Element) nl.item(0);
- String min = varParams.getAttribute("min");
- if (min != null) {
- minArgs += Integer.parseInt(min);
- }
- String max = varParams.getAttribute("max");
- if (max != null) {
- maxArgs += Integer.parseInt(max);
- }
- }
- // setUsesContext(Boolean.parseBoolean(function.getAttribute("uses-context")));
- if (usesContext()) {
- minArgs++;
- maxArgs++;
- }
- Element e = (Element) function.getElementsByTagName("java").item(0);
- if (e != null) {
- setClassName(e.getAttribute("class"));
- setMethod(e.getAttribute("method"));
- setInitialized(Boolean.parseBoolean(e.getAttribute("initialized")));
- nl = e.getElementsByTagName("with-param");
- if (initialized && nl.getLength() > 0) {
- classParams = new ArrayList<>();
- for (int i = 0; i < nl.getLength(); i++) {
- Element el = (Element) nl.item(i);
- Node value = null;
- NodeList children = el.getChildNodes();
- for (int j = 0; j < children.getLength(); j++) {
- Node n = children.item(j);
- if (n.getNodeType() == Node.TEXT_NODE) {
- value = n;
- }
- if (n.getNodeType() == Node.ELEMENT_NODE) {
- value = n;
- break;
- }
- }
- classParams.add(value);
- }
- }
- }
- // } catch (URISyntaxException e) {
- // throw new RuntimeException(e);
- // }
- }
-
- public String getClassName() {
- return className;
- }
-
- public void setClassName(String className) {
- this.className = className;
- }
-
- public boolean isInitialized() {
- return initialized;
- }
-
- public void setInitialized(boolean initialized) {
- this.initialized = initialized;
- }
-
- public boolean isJava() {
- return java;
- }
-
- public void setJava(boolean java) {
- this.java = java;
- }
-
- public int getMaxArgs() {
- return maxArgs;
- }
-
- public void setMaxArgs(int maxArgs) {
- this.maxArgs = maxArgs;
- }
-
- public int getMinArgs() {
- return minArgs;
- }
-
- public void setMinArgs(int minArgs) {
- this.minArgs = minArgs;
- }
-
- public String getMethod() {
- return method;
- }
-
- public void setMethod(String method) {
- this.method = method;
- }
-
- public List getClassParams() {
- return classParams;
- }
-
- public void setClassParams(List classParams) {
- this.classParams = classParams;
- }
-
-}
+package com.occamlab.te.index;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+public class FunctionEntry extends TemplateEntry {
+
+ boolean java;
+
+ boolean initialized;
+
+ String className;
+
+ String method;
+
+ int minArgs;
+
+ int maxArgs;
+
+ List classParams = null;
+
+ FunctionEntry() {
+ super();
+ }
+
+ // public void persistAttributes(PrintWriter out) {
+ // super.persistAttributes(out);
+ // out.print(" type=\"" + (java ? "java" : "xsl") + "\"");
+ // }
+ //
+ // public void persistTags(PrintWriter out) {
+ // super.persistTags(out);
+ // if (minArgs != maxArgs) {
+ // int min = minArgs;
+ // int max = maxArgs;
+ // if (getParams() != null) {
+ // min -= getParams().size();
+ // max -= getParams().size();
+ // }
+ // if (usesContext()) {
+ // min--;
+ // max--;
+ // }
+ // out.println(" ");
+ // }
+ // }
+ //
+ // public void persist(PrintWriter out) {
+ // persist(out, "function");
+ // }
+
+ FunctionEntry(Element function) {
+ super(function);
+ // System.out.println(DomUtils.serializeNode(function));
+ // try {
+ String type = function.getAttribute("type");
+ if (type.equals("xsl")) {
+ setJava(false);
+ // setTemplateFile(new File(new
+ // URI(function.getAttribute("file"))));
+ }
+ else if (type.equals("java")) {
+ // System.out.println(this.getId());
+ setJava(true);
+ }
+ else {
+ throw new RuntimeException("Invalid function type");
+ }
+ // NodeList nl = function.getElementsByTagName("param");
+ // minArgs = nl.getLength();
+ minArgs = 0;
+ if (this.getParams() != null) {
+ minArgs = this.getParams().size();
+ }
+ maxArgs = minArgs;
+ // params = new ArrayList();
+ // if (minArgs > 0) {
+ // for (int i = 0; i < minArgs; i++) {
+ // Element el = (Element)nl.item(i);
+ // String prefix = el.getAttribute("prefix");
+ // String namespaceUri = el.getAttribute("namespace-uri");
+ // String localName = el.getAttribute("local-name");
+ // params.add(new QName(namespaceUri, localName, prefix));
+ // }
+ // }
+ NodeList nl = function.getElementsByTagName("var-params");
+ if (nl.getLength() > 0) {
+ Element varParams = (Element) nl.item(0);
+ String min = varParams.getAttribute("min");
+ if (min != null) {
+ minArgs += Integer.parseInt(min);
+ }
+ String max = varParams.getAttribute("max");
+ if (max != null) {
+ maxArgs += Integer.parseInt(max);
+ }
+ }
+ // setUsesContext(Boolean.parseBoolean(function.getAttribute("uses-context")));
+ if (usesContext()) {
+ minArgs++;
+ maxArgs++;
+ }
+ Element e = (Element) function.getElementsByTagName("java").item(0);
+ if (e != null) {
+ setClassName(e.getAttribute("class"));
+ setMethod(e.getAttribute("method"));
+ setInitialized(Boolean.parseBoolean(e.getAttribute("initialized")));
+ nl = e.getElementsByTagName("with-param");
+ if (initialized && nl.getLength() > 0) {
+ classParams = new ArrayList<>();
+ for (int i = 0; i < nl.getLength(); i++) {
+ Element el = (Element) nl.item(i);
+ Node value = null;
+ NodeList children = el.getChildNodes();
+ for (int j = 0; j < children.getLength(); j++) {
+ Node n = children.item(j);
+ if (n.getNodeType() == Node.TEXT_NODE) {
+ value = n;
+ }
+ if (n.getNodeType() == Node.ELEMENT_NODE) {
+ value = n;
+ break;
+ }
+ }
+ classParams.add(value);
+ }
+ }
+ }
+ // } catch (URISyntaxException e) {
+ // throw new RuntimeException(e);
+ // }
+ }
+
+ public String getClassName() {
+ return className;
+ }
+
+ public void setClassName(String className) {
+ this.className = className;
+ }
+
+ public boolean isInitialized() {
+ return initialized;
+ }
+
+ public void setInitialized(boolean initialized) {
+ this.initialized = initialized;
+ }
+
+ public boolean isJava() {
+ return java;
+ }
+
+ public void setJava(boolean java) {
+ this.java = java;
+ }
+
+ public int getMaxArgs() {
+ return maxArgs;
+ }
+
+ public void setMaxArgs(int maxArgs) {
+ this.maxArgs = maxArgs;
+ }
+
+ public int getMinArgs() {
+ return minArgs;
+ }
+
+ public void setMinArgs(int minArgs) {
+ this.minArgs = minArgs;
+ }
+
+ public String getMethod() {
+ return method;
+ }
+
+ public void setMethod(String method) {
+ this.method = method;
+ }
+
+ public List getClassParams() {
+ return classParams;
+ }
+
+ public void setClassParams(List classParams) {
+ this.classParams = classParams;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/index/Index.java b/teamengine-core/src/main/java/com/occamlab/te/index/Index.java
index cecfa235e..7bf027547 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/index/Index.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/index/Index.java
@@ -1,275 +1,295 @@
-/*
-
- The Original Code is TEAM Engine.
-
- The Initial Developer of the Original Code is Northrop Grumman Corporation
- jointly with The National Technology Alliance. Portions created by
- Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
- Grumman Corporation. All Rights Reserved.
-
- Contributor(s):
- C. Heazel (WiSC): Added Fortify adjudication changes
- C. Heazel (WiSC): Modified setElements() to correctly handle a null argumet
- */
-
-package com.occamlab.te.index;
-
-import java.io.File;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.xml.namespace.QName;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import com.occamlab.te.util.DomUtils;
-
-public class Index {
-
- File indexFile = null;
-
- List dependencies = new ArrayList<>();
-
- Map> functionsMap = new HashMap<>();
-
- Map parserMap = new HashMap<>();
-
- Map suiteMap = new HashMap<>();
-
- Map profileMap = new HashMap<>();
-
- Map testMap = new HashMap<>();
-
- List elements = new ArrayList<>();
-
- public Index() {
- }
-
- public Index(File indexFile) throws Exception {
- if (null == indexFile || !indexFile.exists()) {
- throw new IllegalArgumentException("indexFile is null or does not exist.");
- }
- this.indexFile = indexFile;
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setNamespaceAware(true);
- // Fortify Mod: prevent external entity injection
- dbf.setExpandEntityReferences(false);
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document doc = db.parse(indexFile);
- Element index = (Element) doc.getDocumentElement();
- NodeList nodes = index.getChildNodes();
- for (int i = 0; i < nodes.getLength(); i++) {
- Node node = nodes.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element el = (Element) node;
- elements.add(el);
- String name = el.getNodeName();
- if (name.equals("dependency")) {
- File file = new File(el.getAttribute("file").substring(5));
- dependencies.add(file);
- }
- else if (name.equals("suite")) {
- SuiteEntry se = new SuiteEntry(el);
- suiteMap.put(se.getId(), se);
- }
- else if (name.equals("profile")) {
- ProfileEntry pe = new ProfileEntry(el);
- profileMap.put(pe.getId(), pe);
- }
- else if (name.equals("test")) {
- TestEntry te = new TestEntry(el);
- testMap.put(te.getId(), te);
- }
- else if (name.equals("function")) {
- FunctionEntry fe = new FunctionEntry(el);
- List functions = functionsMap.get(fe.getId());
- if (functions == null) {
- functions = new ArrayList<>();
- functions.add(fe);
- functionsMap.put(fe.getId(), functions);
- }
- else {
- functions.add(fe);
- }
- }
- else if (name.equals("parser")) {
- ParserEntry pe = new ParserEntry(el);
- parserMap.put(pe.getId(), pe);
- }
- }
- }
- }
-
- public void persist(File file) throws Exception {
- file.getParentFile().mkdirs();
- PrintWriter out = new PrintWriter(file);
- out.println("");
- for (Element el : elements) {
- out.println(DomUtils.serializeNode(el));
- }
- out.println(" ");
- out.close();
- }
-
- public boolean outOfDate() {
- if (indexFile != null) {
- long indexDate = indexFile.lastModified();
- for (File file : dependencies) {
- if (file.lastModified() + 1000 > indexDate) {
- return true;
- }
- }
- }
- return false;
- }
-
- public void add(Index index) {
- elements.addAll(index.elements);
- dependencies.addAll(index.dependencies);
- functionsMap.putAll(index.functionsMap);
- suiteMap.putAll(index.suiteMap);
- profileMap.putAll(index.profileMap);
- testMap.putAll(index.testMap);
- parserMap.putAll(index.parserMap);
- }
-
- public List getFunctions(String name) {
- if (name.startsWith("{")) {
- return functionsMap.get(name);
- }
- throw new RuntimeException("Invalid function name");
- }
-
- public List getFunctions(QName qname) {
- return getFunctions("{" + qname.getNamespaceURI() + "}" + qname.getLocalPart());
- }
-
- public Set getFunctionKeys() {
- return functionsMap.keySet();
- }
-
- public ParserEntry getParser(String name) {
- return (ParserEntry) getEntry(parserMap, name);
- }
-
- public ParserEntry getParser(QName qname) {
- return (ParserEntry) getEntry(parserMap, qname);
- }
-
- public Set getParserKeys() {
- return parserMap.keySet();
- }
-
- public SuiteEntry getSuite(String name) {
- return (SuiteEntry) getEntry(suiteMap, name);
- }
-
- public SuiteEntry getSuite(QName qname) {
- return (SuiteEntry) getEntry(suiteMap, qname);
- }
-
- public Set getSuiteKeys() {
- return suiteMap.keySet();
- }
-
- public ProfileEntry getProfile(String name) {
- return (ProfileEntry) getEntry(profileMap, name);
- }
-
- public ProfileEntry getProfile(QName qname) {
- return (ProfileEntry) getEntry(profileMap, qname);
- }
-
- public Set getProfileKeys() {
- return profileMap.keySet();
- }
-
- public Collection getProfiles() {
- return profileMap.values();
- }
-
- public TestEntry getTest(String name) {
- return (TestEntry) getEntry(testMap, name);
- }
-
- public TestEntry getTest(QName qname) {
- return (TestEntry) getEntry(testMap, qname);
- }
-
- public Set getTestKeys() {
- return testMap.keySet();
- }
-
- private IndexEntry getEntry(Map map, QName qname) {
- return getEntry(map, "{" + qname.getNamespaceURI() + "}" + qname.getLocalPart());
- }
-
- private IndexEntry getEntry(Map map, String name) {
- if (name == null) {
- return map.values().iterator().next();
- }
-
- if (name.startsWith("{")) {
- return map.get(name);
- }
-
- int i = name.lastIndexOf(',');
- if (i >= 0) {
- String key = "{" + name.substring(0, i) + "}" + name.substring(i + 1);
- return map.get(key);
- }
-
- String prefix = null;
- String localName = name;
- i = name.indexOf(':');
- if (i >= 0) {
- prefix = name.substring(0, i);
- localName = name.substring(i + 1);
- }
-
- Iterator extends IndexEntry> it = map.values().iterator();
- while (it.hasNext()) {
- IndexEntry entry = it.next();
- if (entry.getLocalName().equals(localName)) {
- if (prefix == null) {
- return entry;
- }
- else {
- if (entry.getPrefix().equals(prefix)) {
- return entry;
- }
- }
- }
- }
-
- return null;
- }
-
- public void setElements(List elements) {
- // Mod to handle a null argument
- if (elements != null)
- this.elements = elements;
- else
- this.elements = new ArrayList<>();
- }
-
- public List getDependencies() {
- return dependencies;
- }
-
- public void setDependencies(List dependencies) {
- this.dependencies = dependencies;
- }
-
-}
+/*
+
+ The Original Code is TEAM Engine.
+
+ The Initial Developer of the Original Code is Northrop Grumman Corporation
+ jointly with The National Technology Alliance. Portions created by
+ Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
+ Grumman Corporation. All Rights Reserved.
+
+ Contributor(s):
+ C. Heazel (WiSC): Added Fortify adjudication changes
+ C. Heazel (WiSC): Modified setElements() to correctly handle a null argumet
+ */
+
+package com.occamlab.te.index;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.File;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.xml.namespace.QName;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import com.occamlab.te.util.DomUtils;
+
+public class Index {
+
+ File indexFile = null;
+
+ List dependencies = new ArrayList<>();
+
+ Map> functionsMap = new HashMap<>();
+
+ Map parserMap = new HashMap<>();
+
+ Map suiteMap = new HashMap<>();
+
+ Map profileMap = new HashMap<>();
+
+ Map testMap = new HashMap<>();
+
+ List elements = new ArrayList<>();
+
+ public Index() {
+ }
+
+ public Index(File indexFile) throws Exception {
+ if (null == indexFile || !indexFile.exists()) {
+ throw new IllegalArgumentException("indexFile is null or does not exist.");
+ }
+ this.indexFile = indexFile;
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setNamespaceAware(true);
+ // Fortify Mod: prevent external entity injection
+ dbf.setExpandEntityReferences(false);
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ Document doc = db.parse(indexFile);
+ Element index = (Element) doc.getDocumentElement();
+ NodeList nodes = index.getChildNodes();
+ for (int i = 0; i < nodes.getLength(); i++) {
+ Node node = nodes.item(i);
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ Element el = (Element) node;
+ elements.add(el);
+ String name = el.getNodeName();
+ if (name.equals("dependency")) {
+ File file = new File(el.getAttribute("file").substring(5));
+ dependencies.add(file);
+ }
+ else if (name.equals("suite")) {
+ SuiteEntry se = new SuiteEntry(el);
+ suiteMap.put(se.getId(), se);
+ }
+ else if (name.equals("profile")) {
+ ProfileEntry pe = new ProfileEntry(el);
+ profileMap.put(pe.getId(), pe);
+ }
+ else if (name.equals("test")) {
+ TestEntry te = new TestEntry(el);
+ testMap.put(te.getId(), te);
+ }
+ else if (name.equals("function")) {
+ FunctionEntry fe = new FunctionEntry(el);
+ List functions = functionsMap.get(fe.getId());
+ if (functions == null) {
+ functions = new ArrayList<>();
+ functions.add(fe);
+ functionsMap.put(fe.getId(), functions);
+ }
+ else {
+ functions.add(fe);
+ }
+ }
+ else if (name.equals("parser")) {
+ ParserEntry pe = new ParserEntry(el);
+ parserMap.put(pe.getId(), pe);
+ }
+ }
+ }
+ }
+
+ public void persist(File file) throws Exception {
+ file.getParentFile().mkdirs();
+ PrintWriter out = new PrintWriter(file);
+ out.println("");
+ for (Element el : elements) {
+ out.println(DomUtils.serializeNode(el));
+ }
+ out.println(" ");
+ out.close();
+ }
+
+ public boolean outOfDate() {
+ if (indexFile != null) {
+ long indexDate = indexFile.lastModified();
+ for (File file : dependencies) {
+ if (file.lastModified() + 1000 > indexDate) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public void add(Index index) {
+ elements.addAll(index.elements);
+ dependencies.addAll(index.dependencies);
+ functionsMap.putAll(index.functionsMap);
+ suiteMap.putAll(index.suiteMap);
+ profileMap.putAll(index.profileMap);
+ testMap.putAll(index.testMap);
+ parserMap.putAll(index.parserMap);
+ }
+
+ public List getFunctions(String name) {
+ if (name.startsWith("{")) {
+ return functionsMap.get(name);
+ }
+ throw new RuntimeException("Invalid function name");
+ }
+
+ public List getFunctions(QName qname) {
+ return getFunctions("{" + qname.getNamespaceURI() + "}" + qname.getLocalPart());
+ }
+
+ public Set getFunctionKeys() {
+ return functionsMap.keySet();
+ }
+
+ public ParserEntry getParser(String name) {
+ return (ParserEntry) getEntry(parserMap, name);
+ }
+
+ public ParserEntry getParser(QName qname) {
+ return (ParserEntry) getEntry(parserMap, qname);
+ }
+
+ public Set getParserKeys() {
+ return parserMap.keySet();
+ }
+
+ public SuiteEntry getSuite(String name) {
+ return (SuiteEntry) getEntry(suiteMap, name);
+ }
+
+ public SuiteEntry getSuite(QName qname) {
+ return (SuiteEntry) getEntry(suiteMap, qname);
+ }
+
+ public Set getSuiteKeys() {
+ return suiteMap.keySet();
+ }
+
+ public ProfileEntry getProfile(String name) {
+ return (ProfileEntry) getEntry(profileMap, name);
+ }
+
+ public ProfileEntry getProfile(QName qname) {
+ return (ProfileEntry) getEntry(profileMap, qname);
+ }
+
+ public Set getProfileKeys() {
+ return profileMap.keySet();
+ }
+
+ public Collection getProfiles() {
+ return profileMap.values();
+ }
+
+ public TestEntry getTest(String name) {
+ return (TestEntry) getEntry(testMap, name);
+ }
+
+ public TestEntry getTest(QName qname) {
+ return (TestEntry) getEntry(testMap, qname);
+ }
+
+ public Set getTestKeys() {
+ return testMap.keySet();
+ }
+
+ private IndexEntry getEntry(Map map, QName qname) {
+ return getEntry(map, "{" + qname.getNamespaceURI() + "}" + qname.getLocalPart());
+ }
+
+ private IndexEntry getEntry(Map map, String name) {
+ if (name == null) {
+ return map.values().iterator().next();
+ }
+
+ if (name.startsWith("{")) {
+ return map.get(name);
+ }
+
+ int i = name.lastIndexOf(',');
+ if (i >= 0) {
+ String key = "{" + name.substring(0, i) + "}" + name.substring(i + 1);
+ return map.get(key);
+ }
+
+ String prefix = null;
+ String localName = name;
+ i = name.indexOf(':');
+ if (i >= 0) {
+ prefix = name.substring(0, i);
+ localName = name.substring(i + 1);
+ }
+
+ Iterator extends IndexEntry> it = map.values().iterator();
+ while (it.hasNext()) {
+ IndexEntry entry = it.next();
+ if (entry.getLocalName().equals(localName)) {
+ if (prefix == null) {
+ return entry;
+ }
+ else {
+ if (entry.getPrefix().equals(prefix)) {
+ return entry;
+ }
+ }
+ }
+ }
+
+ return null;
+ }
+
+ public void setElements(List elements) {
+ // Mod to handle a null argument
+ if (elements != null)
+ this.elements = elements;
+ else
+ this.elements = new ArrayList<>();
+ }
+
+ public List getDependencies() {
+ return dependencies;
+ }
+
+ public void setDependencies(List dependencies) {
+ this.dependencies = dependencies;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/index/IndexEntry.java b/teamengine-core/src/main/java/com/occamlab/te/index/IndexEntry.java
index a485328fb..62974fd50 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/index/IndexEntry.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/index/IndexEntry.java
@@ -1,65 +1,85 @@
-package com.occamlab.te.index;
-
-import javax.xml.namespace.QName;
-
-import org.w3c.dom.Element;
-
-public class IndexEntry implements NamedEntry {
-
- QName qname = null;
-
- IndexEntry() {
- }
-
- IndexEntry(Element el) {
- String prefix = el.getAttribute("prefix");
- String namespaceUri = el.getAttribute("namespace-uri");
- String localName = el.getAttribute("local-name");
- setQName(new QName(namespaceUri, localName, prefix));
- }
-
- public String getName() {
- if (qname == null) {
- return null;
- }
- String prefix = qname.getPrefix();
- if (prefix == null) {
- return qname.getLocalPart();
- }
- else {
- return prefix + ":" + qname.getLocalPart();
- }
- }
-
- public String getLocalName() {
- return qname.getLocalPart();
- }
-
- public String getNamespaceURI() {
- return qname.getNamespaceURI();
- }
-
- public String getPrefix() {
- return qname.getPrefix();
- }
-
- public QName getQName() {
- return qname;
- }
-
- public void setQName(QName qname) {
- this.qname = qname;
- }
-
- public String getId() {
- return "{" + qname.getNamespaceURI() + "}" + qname.getLocalPart();
- }
-
- public String toString() {
- if (qname == null) {
- return super.toString();
- }
- return qname.toString();
- }
-
-}
+package com.occamlab.te.index;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import javax.xml.namespace.QName;
+
+import org.w3c.dom.Element;
+
+public class IndexEntry implements NamedEntry {
+
+ QName qname = null;
+
+ IndexEntry() {
+ }
+
+ IndexEntry(Element el) {
+ String prefix = el.getAttribute("prefix");
+ String namespaceUri = el.getAttribute("namespace-uri");
+ String localName = el.getAttribute("local-name");
+ setQName(new QName(namespaceUri, localName, prefix));
+ }
+
+ public String getName() {
+ if (qname == null) {
+ return null;
+ }
+ String prefix = qname.getPrefix();
+ if (prefix == null) {
+ return qname.getLocalPart();
+ }
+ else {
+ return prefix + ":" + qname.getLocalPart();
+ }
+ }
+
+ public String getLocalName() {
+ return qname.getLocalPart();
+ }
+
+ public String getNamespaceURI() {
+ return qname.getNamespaceURI();
+ }
+
+ public String getPrefix() {
+ return qname.getPrefix();
+ }
+
+ public QName getQName() {
+ return qname;
+ }
+
+ public void setQName(QName qname) {
+ this.qname = qname;
+ }
+
+ public String getId() {
+ return "{" + qname.getNamespaceURI() + "}" + qname.getLocalPart();
+ }
+
+ public String toString() {
+ if (qname == null) {
+ return super.toString();
+ }
+ return qname.toString();
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/index/NamedEntry.java b/teamengine-core/src/main/java/com/occamlab/te/index/NamedEntry.java
index 1c1cffc3a..312be5f45 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/index/NamedEntry.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/index/NamedEntry.java
@@ -1,21 +1,41 @@
-package com.occamlab.te.index;
-
-import javax.xml.namespace.QName;
-
-public interface NamedEntry {
-
- String getName();
-
- String getLocalName();
-
- String getNamespaceURI();
-
- String getPrefix();
-
- QName getQName();
-
- void setQName(QName qname);
-
- String getId();
-
-}
+package com.occamlab.te.index;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import javax.xml.namespace.QName;
+
+public interface NamedEntry {
+
+ String getName();
+
+ String getLocalName();
+
+ String getNamespaceURI();
+
+ String getPrefix();
+
+ QName getQName();
+
+ void setQName(QName qname);
+
+ String getId();
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/index/ParserEntry.java b/teamengine-core/src/main/java/com/occamlab/te/index/ParserEntry.java
index 213f48194..a62e07b59 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/index/ParserEntry.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/index/ParserEntry.java
@@ -1,90 +1,110 @@
-package com.occamlab.te.index;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import com.occamlab.te.util.DomUtils;
-
-public class ParserEntry extends IndexEntry {
-
- boolean initialized;
-
- String className;
-
- String method;
-
- List classParams = null;
-
- ParserEntry() {
- super();
- }
-
- ParserEntry(Element parser) throws Exception {
- super(parser);
- Element e = (Element) parser.getElementsByTagName("java").item(0);
- if (e != null) {
- setClassName(e.getAttribute("class"));
- setMethod(e.getAttribute("method"));
- setInitialized(Boolean.parseBoolean(e.getAttribute("initialized")));
- NodeList nl = e.getElementsByTagName("with-param");
- if (nl.getLength() > 0) {
- setInitialized(true);
- classParams = new ArrayList<>();
- for (int i = 0; i < nl.getLength(); i++) {
- Element el = (Element) nl.item(i);
- // System.out.println(DomUtils.serializeNode(el));
- Node value = null;
- NodeList children = el.getChildNodes();
- for (int j = 0; j < children.getLength(); j++) {
- Node n = children.item(j);
- if (n.getNodeType() == Node.TEXT_NODE) {
- value = n;
- }
- if (n.getNodeType() == Node.ELEMENT_NODE) {
- value = DomUtils.createDocument(n);
- break;
- }
- }
- classParams.add(value);
- }
- }
- }
- }
-
- public String getClassName() {
- return className;
- }
-
- public void setClassName(String className) {
- this.className = className;
- }
-
- public boolean isInitialized() {
- return initialized;
- }
-
- public void setInitialized(boolean initialized) {
- this.initialized = initialized;
- }
-
- public String getMethod() {
- return method;
- }
-
- public void setMethod(String method) {
- this.method = method;
- }
-
- public List getClassParams() {
- return classParams;
- }
-
- public void setClassParams(List classParams) {
- this.classParams = classParams;
- }
-
-}
+package com.occamlab.te.index;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import com.occamlab.te.util.DomUtils;
+
+public class ParserEntry extends IndexEntry {
+
+ boolean initialized;
+
+ String className;
+
+ String method;
+
+ List classParams = null;
+
+ ParserEntry() {
+ super();
+ }
+
+ ParserEntry(Element parser) throws Exception {
+ super(parser);
+ Element e = (Element) parser.getElementsByTagName("java").item(0);
+ if (e != null) {
+ setClassName(e.getAttribute("class"));
+ setMethod(e.getAttribute("method"));
+ setInitialized(Boolean.parseBoolean(e.getAttribute("initialized")));
+ NodeList nl = e.getElementsByTagName("with-param");
+ if (nl.getLength() > 0) {
+ setInitialized(true);
+ classParams = new ArrayList<>();
+ for (int i = 0; i < nl.getLength(); i++) {
+ Element el = (Element) nl.item(i);
+ // System.out.println(DomUtils.serializeNode(el));
+ Node value = null;
+ NodeList children = el.getChildNodes();
+ for (int j = 0; j < children.getLength(); j++) {
+ Node n = children.item(j);
+ if (n.getNodeType() == Node.TEXT_NODE) {
+ value = n;
+ }
+ if (n.getNodeType() == Node.ELEMENT_NODE) {
+ value = DomUtils.createDocument(n);
+ break;
+ }
+ }
+ classParams.add(value);
+ }
+ }
+ }
+ }
+
+ public String getClassName() {
+ return className;
+ }
+
+ public void setClassName(String className) {
+ this.className = className;
+ }
+
+ public boolean isInitialized() {
+ return initialized;
+ }
+
+ public void setInitialized(boolean initialized) {
+ this.initialized = initialized;
+ }
+
+ public String getMethod() {
+ return method;
+ }
+
+ public void setMethod(String method) {
+ this.method = method;
+ }
+
+ public List getClassParams() {
+ return classParams;
+ }
+
+ public void setClassParams(List classParams) {
+ this.classParams = classParams;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/index/ProfileEntry.java b/teamengine-core/src/main/java/com/occamlab/te/index/ProfileEntry.java
index 7cba0de78..e5917a1ff 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/index/ProfileEntry.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/index/ProfileEntry.java
@@ -1,119 +1,139 @@
-package com.occamlab.te.index;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.namespace.QName;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import com.occamlab.te.Test;
-import com.occamlab.te.util.DomUtils;
-
-public class ProfileEntry extends IndexEntry {
-
- String defaultResult = "Pass";
-
- QName baseSuite;
-
- List> excludes = new ArrayList<>();
-
- QName startingTest;
-
- Document form = null;
-
- String title = null;
-
- String description = null;
-
- public ProfileEntry() {
- super();
- }
-
- public ProfileEntry(Element profile) throws Exception {
- super(profile);
- title = DomUtils.getElementByTagName(profile, "title").getTextContent();
- description = DomUtils.getElementByTagName(profile, "description").getTextContent();
- Element base = DomUtils.getElementByTagName(profile, "base");
- baseSuite = getQName(base);
- for (Element exclude : DomUtils.getElementsByTagName(profile, "exclude")) {
- ArrayList list = new ArrayList<>();
- for (Element test : DomUtils.getElementsByTagName(exclude, "test")) {
- list.add(getQName(test));
- }
- excludes.add(list);
- }
- setDefaultResult(DomUtils.getElementByTagName(profile, "defaultResult").getTextContent());
- Element e = DomUtils.getElementByTagName(profile, "starting-test");
- startingTest = getQName(e);
- Element form_e = DomUtils.getElementByTagNameNS(profile, Test.CTL_NS, "form");
- if (form_e != null) {
- form = DomUtils.createDocument(form_e);
- }
- }
-
- public QName getStartingTest() {
- return startingTest;
- }
-
- public void setStartingTest(QName startingTest) {
- this.startingTest = startingTest;
- }
-
- public Document getForm() {
- return form;
- }
-
- public void setForm(Document form) {
- this.form = form;
- }
-
- public QName getBaseSuite() {
- return baseSuite;
- }
-
- public void setBaseSuite(QName baseSuite) {
- this.baseSuite = baseSuite;
- }
-
- public List> getExcludes() {
- return excludes;
- }
-
- public void setExcludes(List> excludes) {
- this.excludes = excludes;
- }
-
- QName getQName(Element e) {
- String prefix = e.getAttribute("prefix");
- String namespaceUri = e.getAttribute("namespace-uri");
- String localName = e.getAttribute("local-name");
- return new QName(namespaceUri, localName, prefix);
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getDefaultResult() {
- return defaultResult;
- }
-
- public void setDefaultResult(String defaultResult) {
- this.defaultResult = defaultResult;
- }
-
-}
+package com.occamlab.te.index;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.namespace.QName;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import com.occamlab.te.Test;
+import com.occamlab.te.util.DomUtils;
+
+public class ProfileEntry extends IndexEntry {
+
+ String defaultResult = "Pass";
+
+ QName baseSuite;
+
+ List> excludes = new ArrayList<>();
+
+ QName startingTest;
+
+ Document form = null;
+
+ String title = null;
+
+ String description = null;
+
+ public ProfileEntry() {
+ super();
+ }
+
+ public ProfileEntry(Element profile) throws Exception {
+ super(profile);
+ title = DomUtils.getElementByTagName(profile, "title").getTextContent();
+ description = DomUtils.getElementByTagName(profile, "description").getTextContent();
+ Element base = DomUtils.getElementByTagName(profile, "base");
+ baseSuite = getQName(base);
+ for (Element exclude : DomUtils.getElementsByTagName(profile, "exclude")) {
+ ArrayList list = new ArrayList<>();
+ for (Element test : DomUtils.getElementsByTagName(exclude, "test")) {
+ list.add(getQName(test));
+ }
+ excludes.add(list);
+ }
+ setDefaultResult(DomUtils.getElementByTagName(profile, "defaultResult").getTextContent());
+ Element e = DomUtils.getElementByTagName(profile, "starting-test");
+ startingTest = getQName(e);
+ Element form_e = DomUtils.getElementByTagNameNS(profile, Test.CTL_NS, "form");
+ if (form_e != null) {
+ form = DomUtils.createDocument(form_e);
+ }
+ }
+
+ public QName getStartingTest() {
+ return startingTest;
+ }
+
+ public void setStartingTest(QName startingTest) {
+ this.startingTest = startingTest;
+ }
+
+ public Document getForm() {
+ return form;
+ }
+
+ public void setForm(Document form) {
+ this.form = form;
+ }
+
+ public QName getBaseSuite() {
+ return baseSuite;
+ }
+
+ public void setBaseSuite(QName baseSuite) {
+ this.baseSuite = baseSuite;
+ }
+
+ public List> getExcludes() {
+ return excludes;
+ }
+
+ public void setExcludes(List> excludes) {
+ this.excludes = excludes;
+ }
+
+ QName getQName(Element e) {
+ String prefix = e.getAttribute("prefix");
+ String namespaceUri = e.getAttribute("namespace-uri");
+ String localName = e.getAttribute("local-name");
+ return new QName(namespaceUri, localName, prefix);
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getDefaultResult() {
+ return defaultResult;
+ }
+
+ public void setDefaultResult(String defaultResult) {
+ this.defaultResult = defaultResult;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/index/SuiteEntry.java b/teamengine-core/src/main/java/com/occamlab/te/index/SuiteEntry.java
index 69b65d0b2..f0d7b0b1a 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/index/SuiteEntry.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/index/SuiteEntry.java
@@ -1,103 +1,123 @@
-package com.occamlab.te.index;
-
-import javax.xml.namespace.QName;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import com.occamlab.te.Test;
-import com.occamlab.te.util.DomUtils;
-
-public class SuiteEntry extends IndexEntry {
-
- String defaultResult = "Pass";
-
- QName startingTest;
-
- Document form = null;
-
- String title = null;
-
- String description = null;
-
- String link;
-
- String dataLink;
-
- public SuiteEntry() {
- super();
- }
-
- SuiteEntry(Element suite) throws Exception {
- super(suite);
- title = DomUtils.getElementByTagName(suite, "title").getTextContent();
- description = DomUtils.getElementByTagName(suite, "description").getTextContent();
- Element e = DomUtils.getElementByTagName(suite, "starting-test");
- String prefix = e.getAttribute("prefix");
- String namespaceUri = e.getAttribute("namespace-uri");
- String localName = e.getAttribute("local-name");
- setDefaultResult(DomUtils.getElementByTagName(suite, "defaultResult").getTextContent());
- startingTest = new QName(namespaceUri, localName, prefix);
- Element form_e = DomUtils.getElementByTagNameNS(suite, Test.CTL_NS, "form");
- if (form_e != null) {
- form = DomUtils.createDocument(form_e);
- }
- }
-
- public QName getStartingTest() {
- return startingTest;
- }
-
- public void setStartingTest(QName startingTest) {
- this.startingTest = startingTest;
- }
-
- public Document getForm() {
- return form;
- }
-
- public void setForm(Document form) {
- this.form = form;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public String getDataLink() {
- return dataLink;
- }
-
- public void setDataLink(String dataLink) {
- this.dataLink = dataLink;
- }
-
- public String getLink() {
- return link;
- }
-
- public void setLink(String link) {
- this.link = link;
- }
-
- public String getDefaultResult() {
- return defaultResult;
- }
-
- public void setDefaultResult(String defaultResult) {
- this.defaultResult = defaultResult;
- }
-
-}
+package com.occamlab.te.index;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import javax.xml.namespace.QName;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import com.occamlab.te.Test;
+import com.occamlab.te.util.DomUtils;
+
+public class SuiteEntry extends IndexEntry {
+
+ String defaultResult = "Pass";
+
+ QName startingTest;
+
+ Document form = null;
+
+ String title = null;
+
+ String description = null;
+
+ String link;
+
+ String dataLink;
+
+ public SuiteEntry() {
+ super();
+ }
+
+ SuiteEntry(Element suite) throws Exception {
+ super(suite);
+ title = DomUtils.getElementByTagName(suite, "title").getTextContent();
+ description = DomUtils.getElementByTagName(suite, "description").getTextContent();
+ Element e = DomUtils.getElementByTagName(suite, "starting-test");
+ String prefix = e.getAttribute("prefix");
+ String namespaceUri = e.getAttribute("namespace-uri");
+ String localName = e.getAttribute("local-name");
+ setDefaultResult(DomUtils.getElementByTagName(suite, "defaultResult").getTextContent());
+ startingTest = new QName(namespaceUri, localName, prefix);
+ Element form_e = DomUtils.getElementByTagNameNS(suite, Test.CTL_NS, "form");
+ if (form_e != null) {
+ form = DomUtils.createDocument(form_e);
+ }
+ }
+
+ public QName getStartingTest() {
+ return startingTest;
+ }
+
+ public void setStartingTest(QName startingTest) {
+ this.startingTest = startingTest;
+ }
+
+ public Document getForm() {
+ return form;
+ }
+
+ public void setForm(Document form) {
+ this.form = form;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getDataLink() {
+ return dataLink;
+ }
+
+ public void setDataLink(String dataLink) {
+ this.dataLink = dataLink;
+ }
+
+ public String getLink() {
+ return link;
+ }
+
+ public void setLink(String link) {
+ this.link = link;
+ }
+
+ public String getDefaultResult() {
+ return defaultResult;
+ }
+
+ public void setDefaultResult(String defaultResult) {
+ this.defaultResult = defaultResult;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/index/TemplateEntry.java b/teamengine-core/src/main/java/com/occamlab/te/index/TemplateEntry.java
index 9978b4a59..4b8e5427a 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/index/TemplateEntry.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/index/TemplateEntry.java
@@ -1,132 +1,152 @@
-package com.occamlab.te.index;
-
-import java.io.File;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.namespace.QName;
-
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-
-public class TemplateEntry extends IndexEntry {
-
- File templateFile = null;
-
- boolean usesContext;
-
- List params = null;
-
- TemplateEntry() {
- super();
- }
-
- TemplateEntry(Element template) {
- super(template);
- try {
- String file = template.getAttribute("file");
- if (file != null && file.length() > 0) {
- setTemplateFile(new File(new URI(template.getAttribute("file"))));
- }
- NodeList nl = template.getElementsByTagName("param");
- params = new ArrayList<>();
- for (int i = 0; i < nl.getLength(); i++) {
- Element el = (Element) nl.item(i);
- String prefix = el.getAttribute("prefix");
- String namespaceUri = el.getAttribute("namespace-uri");
- String localName = el.getAttribute("local-name");
- params.add(new QName(namespaceUri, localName, prefix));
- }
- setUsesContext(Boolean.parseBoolean(template.getAttribute("uses-context")));
- }
- catch (URISyntaxException e) {
- throw new RuntimeException(e);
- }
- }
-
- // public void persistAttributes(PrintWriter out) {
- // super.persistAttributes(out);
- // try {
- // out.print(" file=\"" + templateFile.toURI().toURL().toString() + "\""
- // + " uses-context=\"" + Boolean.toString(usesContext) + "\"");
- // } catch (MalformedURLException e) {
- // throw new RuntimeException(e);
- // }
- // }
- //
- // public void persistTags(PrintWriter out) {
- // super.persistTags(out);
- // for (QName qname : params) {
- // out.println(" ");
- // }
- // }
-
- public File getTemplateFile() {
- return templateFile;
- }
-
- public void setTemplateFile(File templateFile) {
- this.templateFile = templateFile;
- }
-
- public List getParams() {
- return params;
- }
-
- public void setParams(List params) {
- this.params = params;
- }
-
- public boolean usesContext() {
- return usesContext;
- }
-
- public void setUsesContext(boolean usesContext) {
- this.usesContext = usesContext;
- }
-
- // static boolean freeExecutable() {
- // Set keys = Globals.loadedExecutables.keySet();
- // synchronized(Globals.loadedExecutables) {
- // Iterator it = keys.iterator();
- // if (it.hasNext()) {
- // Globals.loadedExecutables.remove(it.next());
- // return true;
- // }
- // }
- // return false;
- // }
- //
- // public XsltExecutable loadExecutable() throws SaxonApiException {
- // String key = getId();
- // XsltExecutable executable = Globals.loadedExecutables.get(key);
- // while (executable == null) {
- // try {
- // // System.out.println(template.getTemplateFile().getAbsolutePath());
- // Source source = new StreamSource(getTemplateFile());
- // executable = Globals.compiler.compile(source);
- // Globals.loadedExecutables.put(key, executable);
- // } catch (OutOfMemoryError e) {
- // boolean freed = freeExecutable();
- // if (!freed) {
- // throw e;
- // }
- // }
- // }
- //
- // Runtime rt = Runtime.getRuntime();
- // while (rt.totalMemory() - rt.freeMemory() > Globals.memThreshhold) {
- // boolean freed = freeExecutable();
- // if (!freed) {
- // break;
- // }
- // }
- //
- // return executable;
- // }
-
-}
+package com.occamlab.te.index;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.File;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.namespace.QName;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+public class TemplateEntry extends IndexEntry {
+
+ File templateFile = null;
+
+ boolean usesContext;
+
+ List params = null;
+
+ TemplateEntry() {
+ super();
+ }
+
+ TemplateEntry(Element template) {
+ super(template);
+ try {
+ String file = template.getAttribute("file");
+ if (file != null && file.length() > 0) {
+ setTemplateFile(new File(new URI(template.getAttribute("file"))));
+ }
+ NodeList nl = template.getElementsByTagName("param");
+ params = new ArrayList<>();
+ for (int i = 0; i < nl.getLength(); i++) {
+ Element el = (Element) nl.item(i);
+ String prefix = el.getAttribute("prefix");
+ String namespaceUri = el.getAttribute("namespace-uri");
+ String localName = el.getAttribute("local-name");
+ params.add(new QName(namespaceUri, localName, prefix));
+ }
+ setUsesContext(Boolean.parseBoolean(template.getAttribute("uses-context")));
+ }
+ catch (URISyntaxException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ // public void persistAttributes(PrintWriter out) {
+ // super.persistAttributes(out);
+ // try {
+ // out.print(" file=\"" + templateFile.toURI().toURL().toString() + "\""
+ // + " uses-context=\"" + Boolean.toString(usesContext) + "\"");
+ // } catch (MalformedURLException e) {
+ // throw new RuntimeException(e);
+ // }
+ // }
+ //
+ // public void persistTags(PrintWriter out) {
+ // super.persistTags(out);
+ // for (QName qname : params) {
+ // out.println(" ");
+ // }
+ // }
+
+ public File getTemplateFile() {
+ return templateFile;
+ }
+
+ public void setTemplateFile(File templateFile) {
+ this.templateFile = templateFile;
+ }
+
+ public List getParams() {
+ return params;
+ }
+
+ public void setParams(List params) {
+ this.params = params;
+ }
+
+ public boolean usesContext() {
+ return usesContext;
+ }
+
+ public void setUsesContext(boolean usesContext) {
+ this.usesContext = usesContext;
+ }
+
+ // static boolean freeExecutable() {
+ // Set keys = Globals.loadedExecutables.keySet();
+ // synchronized(Globals.loadedExecutables) {
+ // Iterator it = keys.iterator();
+ // if (it.hasNext()) {
+ // Globals.loadedExecutables.remove(it.next());
+ // return true;
+ // }
+ // }
+ // return false;
+ // }
+ //
+ // public XsltExecutable loadExecutable() throws SaxonApiException {
+ // String key = getId();
+ // XsltExecutable executable = Globals.loadedExecutables.get(key);
+ // while (executable == null) {
+ // try {
+ // // System.out.println(template.getTemplateFile().getAbsolutePath());
+ // Source source = new StreamSource(getTemplateFile());
+ // executable = Globals.compiler.compile(source);
+ // Globals.loadedExecutables.put(key, executable);
+ // } catch (OutOfMemoryError e) {
+ // boolean freed = freeExecutable();
+ // if (!freed) {
+ // throw e;
+ // }
+ // }
+ // }
+ //
+ // Runtime rt = Runtime.getRuntime();
+ // while (rt.totalMemory() - rt.freeMemory() > Globals.memThreshhold) {
+ // boolean freed = freeExecutable();
+ // if (!freed) {
+ // break;
+ // }
+ // }
+ //
+ // return executable;
+ // }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/index/TemplateEntryInterface.java b/teamengine-core/src/main/java/com/occamlab/te/index/TemplateEntryInterface.java
index d2eae62a2..06d1cb463 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/index/TemplateEntryInterface.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/index/TemplateEntryInterface.java
@@ -1,22 +1,42 @@
-package com.occamlab.te.index;
-
-import java.io.File;
-import java.util.List;
-
-import javax.xml.namespace.QName;
-
-public interface TemplateEntryInterface extends NamedEntry {
-
- File getTemplateFile();
-
- void setTemplateFile(File templateFile);
-
- List getParams();
-
- void setParams(List params);
-
- boolean usesContext();
-
- void setUsesContext(boolean usesContext);
-
-}
+package com.occamlab.te.index;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.File;
+import java.util.List;
+
+import javax.xml.namespace.QName;
+
+public interface TemplateEntryInterface extends NamedEntry {
+
+ File getTemplateFile();
+
+ void setTemplateFile(File templateFile);
+
+ List getParams();
+
+ void setParams(List params);
+
+ boolean usesContext();
+
+ void setUsesContext(boolean usesContext);
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/index/TestEntry.java b/teamengine-core/src/main/java/com/occamlab/te/index/TestEntry.java
index 0fd0dd2cf..c73109d6a 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/index/TestEntry.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/index/TestEntry.java
@@ -1,106 +1,126 @@
-package com.occamlab.te.index;
-
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.w3c.dom.Element;
-
-import com.occamlab.te.TECore;
-
-/**
- * Describes a test in a test suite. It corresponds to a <test> element in an index
- * file.
- */
-public class TestEntry extends TemplateEntry {
-
- private static final Logger LOGR = Logger.getLogger(TestEntry.class.getName());
-
- private int defaultResult = TECore.PASS;
-
- private int result = TECore.PASS;
-
- private String context;
-
- private String type;
-
- private String assertion;
-
- private boolean isConformanceClass;
-
- private boolean isBasic;
-
- public TestEntry() {
- super();
- }
-
- TestEntry(Element test) {
- super(test);
- if (usesContext()) {
- setContext(test.getElementsByTagName("context").item(0).getTextContent());
- }
- setType(test.getElementsByTagName("type").item(0).getTextContent());
- setAssertion(test.getElementsByTagName("assertion").item(0).getTextContent());
- String defaultResultName = test.getElementsByTagName("defaultResult").item(0).getTextContent();
- setDefaultResult(defaultResultName.equals("BestPractice") ? TECore.BEST_PRACTICE : TECore.PASS);
- setResult(getDefaultResult());
-
- this.isConformanceClass = Boolean.parseBoolean(test.getAttribute("isConformanceClass"));
- this.isBasic = Boolean.parseBoolean(test.getAttribute("isBasic"));
- }
-
- public boolean isConformanceClass() {
- return isConformanceClass;
- }
-
- public boolean isBasic() {
- return isBasic;
- }
-
- public int getDefaultResult() {
- return defaultResult;
- }
-
- public void setDefaultResult(int defaultResult) {
- this.defaultResult = defaultResult;
- }
-
- public int getResult() {
- return result;
- }
-
- public void setResult(int result) {
- if (LOGR.isLoggable(Level.FINE)) {
- LOGR.fine(String.format("Setting test result for %s: %d", getQName(), result));
- }
- this.result = result;
- }
-
- public String getContext() {
- return context;
- }
-
- public void setContext(String context) {
- this.context = context;
- }
-
- public String getType() {
- return type;
- }
-
- public void setType(String type) {
- this.type = type;
- }
-
- public String getAssertion() {
- return assertion;
- }
-
- public void setAssertion(String assertion) {
- this.assertion = assertion;
- }
-
- public String toString() {
- return super.toString() + "[result=" + this.result + "]";
- }
-
-}
+package com.occamlab.te.index;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.w3c.dom.Element;
+
+import com.occamlab.te.TECore;
+
+/**
+ * Describes a test in a test suite. It corresponds to a <test> element in an index
+ * file.
+ */
+public class TestEntry extends TemplateEntry {
+
+ private static final Logger LOGR = Logger.getLogger(TestEntry.class.getName());
+
+ private int defaultResult = TECore.PASS;
+
+ private int result = TECore.PASS;
+
+ private String context;
+
+ private String type;
+
+ private String assertion;
+
+ private boolean isConformanceClass;
+
+ private boolean isBasic;
+
+ public TestEntry() {
+ super();
+ }
+
+ TestEntry(Element test) {
+ super(test);
+ if (usesContext()) {
+ setContext(test.getElementsByTagName("context").item(0).getTextContent());
+ }
+ setType(test.getElementsByTagName("type").item(0).getTextContent());
+ setAssertion(test.getElementsByTagName("assertion").item(0).getTextContent());
+ String defaultResultName = test.getElementsByTagName("defaultResult").item(0).getTextContent();
+ setDefaultResult(defaultResultName.equals("BestPractice") ? TECore.BEST_PRACTICE : TECore.PASS);
+ setResult(getDefaultResult());
+
+ this.isConformanceClass = Boolean.parseBoolean(test.getAttribute("isConformanceClass"));
+ this.isBasic = Boolean.parseBoolean(test.getAttribute("isBasic"));
+ }
+
+ public boolean isConformanceClass() {
+ return isConformanceClass;
+ }
+
+ public boolean isBasic() {
+ return isBasic;
+ }
+
+ public int getDefaultResult() {
+ return defaultResult;
+ }
+
+ public void setDefaultResult(int defaultResult) {
+ this.defaultResult = defaultResult;
+ }
+
+ public int getResult() {
+ return result;
+ }
+
+ public void setResult(int result) {
+ if (LOGR.isLoggable(Level.FINE)) {
+ LOGR.fine(String.format("Setting test result for %s: %d", getQName(), result));
+ }
+ this.result = result;
+ }
+
+ public String getContext() {
+ return context;
+ }
+
+ public void setContext(String context) {
+ this.context = context;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getAssertion() {
+ return assertion;
+ }
+
+ public void setAssertion(String assertion) {
+ this.assertion = assertion;
+ }
+
+ public String toString() {
+ return super.toString() + "[result=" + this.result + "]";
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/parsers/BinaryPayloadParser.java b/teamengine-core/src/main/java/com/occamlab/te/parsers/BinaryPayloadParser.java
index 78d5c0d1d..0ea9d5811 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/parsers/BinaryPayloadParser.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/parsers/BinaryPayloadParser.java
@@ -1,42 +1,62 @@
-/**
- * **************************************************************************
- *
- * Contributor(s):
- * C. Heazel (WiSC): Added Fortify adjudication changes
- *
- ***************************************************************************
- */
-package com.occamlab.te.parsers;
-
-import java.io.PrintWriter;
-import java.net.URLConnection;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.XMLConstants; // Addition for Fortify modifications
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class BinaryPayloadParser {
-
- public Document parse(URLConnection uc, Element instruction, PrintWriter logger) throws Exception {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- // Fortify Mod: prevent external entity injection
- dbf.setExpandEntityReferences(false);
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document doc = db.newDocument();
- Element root = doc.createElement("payload");
-
- // Fortify Mod: prevent external entity injection
- TransformerFactory tf = TransformerFactory.newInstance();
- tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- Transformer t = tf.newTransformer();
- // Transformer t = TransformerFactory.newInstance().newTransformer();
-
- return doc;
- }
-
-}
+/**
+ * **************************************************************************
+ *
+ * Contributor(s):
+ * C. Heazel (WiSC): Added Fortify adjudication changes
+ *
+ ***************************************************************************
+ */
+package com.occamlab.te.parsers;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.PrintWriter;
+import java.net.URLConnection;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.XMLConstants; // Addition for Fortify modifications
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+public class BinaryPayloadParser {
+
+ public Document parse(URLConnection uc, Element instruction, PrintWriter logger) throws Exception {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ // Fortify Mod: prevent external entity injection
+ dbf.setExpandEntityReferences(false);
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ Document doc = db.newDocument();
+ Element root = doc.createElement("payload");
+
+ // Fortify Mod: prevent external entity injection
+ TransformerFactory tf = TransformerFactory.newInstance();
+ tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ Transformer t = tf.newTransformer();
+ // Transformer t = TransformerFactory.newInstance().newTransformer();
+
+ return doc;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/parsers/CDataParser.java b/teamengine-core/src/main/java/com/occamlab/te/parsers/CDataParser.java
index 655b7b022..daacedae4 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/parsers/CDataParser.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/parsers/CDataParser.java
@@ -1,52 +1,72 @@
-/****************************************************************************
-
- The Original Code is TEAM Engine.
-
- The Initial Developer of the Original Code is Northrop Grumman Corporation
- jointly with The National Technology Alliance. Portions created by
- Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
- Grumman Corporation. All Rights Reserved.
-
- Contributor(s):
- C. Heazel (WiSC) Fortify modifications
-
- ****************************************************************************/
-package com.occamlab.te.parsers;
-
-import java.io.InputStream;
-import java.io.PrintWriter;
-
-import java.net.URLConnection;
-
-import org.w3c.dom.Element;
-
-/**
- * Reads a response message and produces a String representation of its content.
- *
- */
-public class CDataParser {
-
- public static String parse(URLConnection uc, Element instruction, PrintWriter logger) throws Exception {
- // Fortify Mod: manage the input stream as a local variable so that it can be
- // closed.
- // return parse(uc.getInputStream(), instruction, logger);
- InputStream is = uc.getInputStream();
- String s = parse(is, instruction, logger);
- is.close();
- return s;
- }
-
- private static String parse(InputStream is, Element instruction, PrintWriter logger) throws Exception {
- byte[] buf = new byte[1024];
- int numread = is.read(buf);
- String s = new String(buf, 0, numread);
- while (numread >= 0) {
- numread = is.read(buf);
- if (numread > 0) {
- s += new String(buf, 0, numread);
- }
- }
- return s;
- }
-
-}
+/****************************************************************************
+
+ The Original Code is TEAM Engine.
+
+ The Initial Developer of the Original Code is Northrop Grumman Corporation
+ jointly with The National Technology Alliance. Portions created by
+ Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
+ Grumman Corporation. All Rights Reserved.
+
+ Contributor(s):
+ C. Heazel (WiSC) Fortify modifications
+
+ ****************************************************************************/
+package com.occamlab.te.parsers;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.InputStream;
+import java.io.PrintWriter;
+
+import java.net.URLConnection;
+
+import org.w3c.dom.Element;
+
+/**
+ * Reads a response message and produces a String representation of its content.
+ *
+ */
+public class CDataParser {
+
+ public static String parse(URLConnection uc, Element instruction, PrintWriter logger) throws Exception {
+ // Fortify Mod: manage the input stream as a local variable so that it can be
+ // closed.
+ // return parse(uc.getInputStream(), instruction, logger);
+ InputStream is = uc.getInputStream();
+ String s = parse(is, instruction, logger);
+ is.close();
+ return s;
+ }
+
+ private static String parse(InputStream is, Element instruction, PrintWriter logger) throws Exception {
+ byte[] buf = new byte[1024];
+ int numread = is.read(buf);
+ String s = new String(buf, 0, numread);
+ while (numread >= 0) {
+ numread = is.read(buf);
+ if (numread > 0) {
+ s += new String(buf, 0, numread);
+ }
+ }
+ return s;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/parsers/HTTPParser.java b/teamengine-core/src/main/java/com/occamlab/te/parsers/HTTPParser.java
index 4a4b2e9da..e9c1781f7 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/parsers/HTTPParser.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/parsers/HTTPParser.java
@@ -1,320 +1,340 @@
-/****************************************************************************
-
- The Original Code is TEAM Engine.
-
- The Initial Developer of the Original Code is Northrop Grumman Corporation
- jointly with The National Technology Alliance. Portions created by
- Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
- Grumman Corporation. All Rights Reserved.
-
- Contributor(s):
- C. Heazel (WiSC): Added Fortify adjudication changes
-
- ****************************************************************************/
-package com.occamlab.te.parsers;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.PrintWriter;
-import java.io.RandomAccessFile;
-import java.io.Reader;
-import java.net.URLConnection;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.net.ssl.SSLProtocolException;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMResult;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.XMLConstants; // Addition for Fortify modifications
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import com.occamlab.te.TECore;
-import com.occamlab.te.util.DomUtils;
-import com.occamlab.te.util.URLConnectionUtils;
-
-/**
- * Parses an HTTP response message and produces a DOM Document containing the message
- * content.
- *
- * HTTPParser returns HTTP status and header information. It uses other parser(s) to parse
- * the content; TECore by default if others are not specified. It supports multipart
- * messages. It returns a DOM Document representation of the message status, headers, and
- * content.
- */
-public class HTTPParser {
-
- private static final Logger LOGR = Logger.getLogger(HTTPParser.class.getName());
-
- public static final String PARSERS_NS = "http://www.occamlab.com/te/parsers";
-
- public static final String EOS_ERR = "Error in multipart stream. End of stream reached and with no closing boundary delimiter line";
-
- private static void append_headers(URLConnection uc, Element e) {
- Document doc = e.getOwnerDocument();
- Element headers = doc.createElement("headers");
- e.appendChild(headers);
-
- for (int i = 0;; i++) {
- String headerKey = uc.getHeaderFieldKey(i);
- String headerValue = uc.getHeaderField(i);
- if (headerKey == null) {
- if (headerValue == null)
- break;
- }
- else {
- Element header = doc.createElement("header");
- headers.appendChild(header);
- header.setAttribute("name", headerKey);
- header.appendChild(doc.createTextNode(headerValue));
- }
- }
- if (LOGR.isLoggable(Level.FINER)) {
- LOGR.finer(DomUtils.serializeNode(e));
- }
- }
-
- /**
- * Selects a parser for a message part based on the part number and MIME format type,
- * if supplied in instructions.
- * @param partnum An integer indicating the message part number.
- * @param mime A MIME media type.
- * @param instruction An Element representing parser instructions.
- * @return A Node containing parser info, or {@code null} if no matching parser is
- * found.
- */
- static Node select_parser(int partnum, String mime, Element instruction) {
- if (null == instruction)
- return null;
- NodeList instructions = instruction.getElementsByTagNameNS(PARSERS_NS, "parse");
- Node parserNode = null;
- instructionsLoop: for (int i = 0; i < instructions.getLength(); i++) {
- Element parse = (Element) instructions.item(i);
- if (partnum != 0) {
- String part_i = parse.getAttribute("part");
- if (part_i.length() > 0) {
- int n = Integer.parseInt(part_i);
- if (n != partnum) {
- continue;
- }
- }
- }
- if (mime != null) {
- String mime_i = parse.getAttribute("mime");
- if (mime_i.length() > 0) {
- String[] mime_parts = mime_i.split(";\\s*");
- if (!mime.startsWith(mime_parts[0])) {
- continue;
- }
- boolean ok = true;
- for (int j = 1; j < mime_parts.length; j++) {
- if (mime.indexOf(mime_parts[j]) < 0) {
- ok = false;
- break;
- }
- }
- if (!ok) {
- continue;
- }
- }
- }
- NodeList children = parse.getChildNodes();
- for (int j = 0; j < children.getLength(); j++) {
- if (children.item(j).getNodeType() == Node.ELEMENT_NODE) {
- parserNode = children.item(j);
- break instructionsLoop;
- }
- }
- }
- return parserNode;
- }
-
- private static boolean queue_equals(int[] queue, int qPos, int qLen, int[] value) {
- for (int i = 0; i < qLen; i++) {
- if (queue[(i + qPos) % qLen] != value[i]) {
- return false;
- }
- }
- return true;
- }
-
- private static File create_part_file(Reader in, String boundary) throws Exception {
- File temp = File.createTempFile("$te_", ".tmp");
- RandomAccessFile raf = new RandomAccessFile(temp, "rw");
- int qLen = boundary.length() + 2;
- int[] boundary_queue = new int[qLen];
- boundary_queue[0] = '-';
- boundary_queue[1] = '-';
- for (int i = 0; i < boundary.length(); i++) {
- boundary_queue[i + 2] = boundary.charAt(i);
- }
- int[] queue = new int[qLen];
- for (int i = 0; i < qLen; i++) {
- queue[i] = in.read();
- if (queue[i] == -1) {
- break;
- }
- }
- int qPos = 0;
- try {
- while (!queue_equals(queue, qPos, qLen, boundary_queue)) {
- raf.write(queue[qPos]);
- queue[qPos] = in.read();
- if (queue[qPos] == -1) {
- // Fortify Mod: Clean up the file first, then throw the exception.
- raf.close();
- throw new Exception(EOS_ERR);
- }
- qPos = (qPos + 1) % qLen;
- }
- }
- finally {
- raf.close();
- }
- return temp;
- }
-
- /**
- * Invocation point: Method called by TECore for request or soap-request.
- *
- * {@code }
- */
- public static Document parse(URLConnection uc, Element instruction, PrintWriter logger, TECore core)
- throws Throwable {
- try {
- uc.connect();
- }
- catch (SSLProtocolException sslep) {
- throw new SSLProtocolException(
- "[SSL ERROR] Failed to connect with the requested URL due to \"Invalid server_name\" found!! :"
- + uc.getURL() + ":" + sslep.getClass() + " : " + sslep.getMessage());
- }
- String mime = uc.getContentType();
- boolean multipart = (mime != null && mime.startsWith("multipart"));
-
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- // Fortify Mod: prevent external entity injection
- dbf.setExpandEntityReferences(false);
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document doc = db.newDocument();
- Element root = doc.createElement(multipart ? "multipart-response" : "response");
- if (uc.getHeaderFieldKey(0) == null) {
- Element status = doc.createElement("status");
- String status_line = uc.getHeaderField(0);
- if (status_line != null) {
- String[] status_array = status_line.split("\\s");
- if (status_array.length > 0) {
- status.setAttribute("protocol", status_array[0]);
- }
- if (status_array.length > 1) {
- status.setAttribute("code", status_array[1]);
- }
- if (status_array.length > 2) {
- StringBuilder sb = new StringBuilder();
- for (int i = 2; i < status_array.length; i++) {
- sb.append(status_array[i]);
- sb.append(" ");
- }
- status.appendChild(doc.createTextNode(sb.toString().trim()));
- }
- }
- root.appendChild(status);
- }
-
- append_headers(uc, root);
- // Fortify Mod: prevent external entity injection
- TransformerFactory tf = TransformerFactory.newInstance();
- tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- Transformer t = tf.newTransformer();
- // Transformer t = TransformerFactory.newInstance().newTransformer();
-
- if (multipart) {
- String mime2 = mime + ";";
- int start = mime2.indexOf("boundary=") + 9;
- char endchar = ';';
- if (mime2.charAt(start) == '"') {
- start++;
- endchar = '"';
- }
- int end = mime2.indexOf(endchar, start);
- String boundary = mime2.substring(start, end);
- InputStream is = URLConnectionUtils.getInputStream(uc);
- BufferedReader in = new BufferedReader(new InputStreamReader(is));
- File temp = create_part_file(in, boundary);
- temp.delete();
- String line = in.readLine();
- int num = 1;
- while (!line.endsWith("--")) {
- String contentType = "text/plain";
- Element part = doc.createElement("part");
- part.setAttribute("num", Integer.toString(num));
- Element headers = doc.createElement("headers");
- line = in.readLine();
- while (line.length() > 0) {
- Element header = doc.createElement("header");
- int colon = line.indexOf(":");
- String name = line.substring(0, colon);
- String value = line.substring(colon + 1).trim();
- if (name.toLowerCase().equals("content-type")) {
- contentType = value;
- }
- header.setAttribute("name", name);
- header.appendChild(doc.createTextNode(value));
- headers.appendChild(header);
- line = in.readLine();
- }
- part.appendChild(headers);
- temp = create_part_file(in, boundary);
- URLConnection pc = temp.toURI().toURL().openConnection();
- pc.setRequestProperty("Content-type", mime);
- Node parser = select_parser(num, contentType, instruction);
- // use TECore to invoke any subsidiary (chained) parsers
- Element response_e = core.parse(pc, parser);
- temp.delete();
- Element parser_e = (Element) (response_e.getElementsByTagName("parser").item(0));
- if (parser_e != null) {
- logger.print(parser_e.getTextContent());
- }
- Element content = (Element) (response_e.getElementsByTagName("content").item(0));
- if ((null != content) && content.hasChildNodes()) {
- t.transform(new DOMSource(content), new DOMResult(part));
- }
- root.appendChild(part);
- line = in.readLine();
- num++;
- }
- // Fortify Mod: Close the BufferedReader and release its resources
- in.close();
- }
- else {
- Node parser = select_parser(0, uc.getContentType(), instruction);
- // use TECore to invoke any chained (subsidiary) parsers
- if (LOGR.isLoggable(Level.FINER)) {
- String msg = String.format("Calling subsidiary parser for resource at %s:%n%s", uc.getURL(),
- DomUtils.serializeNode(parser));
- LOGR.finer(msg);
- }
- Element response_e = core.parse(uc, parser);
- Element parser_e = (Element) (response_e.getElementsByTagName("parser").item(0));
- if (parser_e != null) {
- logger.print(parser_e.getTextContent());
- }
- Element content = (Element) (response_e.getElementsByTagName("content").item(0));
- if (null != content) {
- root.appendChild(doc.importNode(content, true));
- }
- }
- doc.appendChild(root);
- return doc;
- }
-
-}
+/****************************************************************************
+
+ The Original Code is TEAM Engine.
+
+ The Initial Developer of the Original Code is Northrop Grumman Corporation
+ jointly with The National Technology Alliance. Portions created by
+ Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
+ Grumman Corporation. All Rights Reserved.
+
+ Contributor(s):
+ C. Heazel (WiSC): Added Fortify adjudication changes
+
+ ****************************************************************************/
+package com.occamlab.te.parsers;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.io.RandomAccessFile;
+import java.io.Reader;
+import java.net.URLConnection;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.net.ssl.SSLProtocolException;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMResult;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.XMLConstants; // Addition for Fortify modifications
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import com.occamlab.te.TECore;
+import com.occamlab.te.util.DomUtils;
+import com.occamlab.te.util.URLConnectionUtils;
+
+/**
+ * Parses an HTTP response message and produces a DOM Document containing the message
+ * content.
+ *
+ * HTTPParser returns HTTP status and header information. It uses other parser(s) to parse
+ * the content; TECore by default if others are not specified. It supports multipart
+ * messages. It returns a DOM Document representation of the message status, headers, and
+ * content.
+ */
+public class HTTPParser {
+
+ private static final Logger LOGR = Logger.getLogger(HTTPParser.class.getName());
+
+ public static final String PARSERS_NS = "http://www.occamlab.com/te/parsers";
+
+ public static final String EOS_ERR = "Error in multipart stream. End of stream reached and with no closing boundary delimiter line";
+
+ private static void append_headers(URLConnection uc, Element e) {
+ Document doc = e.getOwnerDocument();
+ Element headers = doc.createElement("headers");
+ e.appendChild(headers);
+
+ for (int i = 0;; i++) {
+ String headerKey = uc.getHeaderFieldKey(i);
+ String headerValue = uc.getHeaderField(i);
+ if (headerKey == null) {
+ if (headerValue == null)
+ break;
+ }
+ else {
+ Element header = doc.createElement("header");
+ headers.appendChild(header);
+ header.setAttribute("name", headerKey);
+ header.appendChild(doc.createTextNode(headerValue));
+ }
+ }
+ if (LOGR.isLoggable(Level.FINER)) {
+ LOGR.finer(DomUtils.serializeNode(e));
+ }
+ }
+
+ /**
+ * Selects a parser for a message part based on the part number and MIME format type,
+ * if supplied in instructions.
+ * @param partnum An integer indicating the message part number.
+ * @param mime A MIME media type.
+ * @param instruction An Element representing parser instructions.
+ * @return A Node containing parser info, or {@code null} if no matching parser is
+ * found.
+ */
+ static Node select_parser(int partnum, String mime, Element instruction) {
+ if (null == instruction)
+ return null;
+ NodeList instructions = instruction.getElementsByTagNameNS(PARSERS_NS, "parse");
+ Node parserNode = null;
+ instructionsLoop: for (int i = 0; i < instructions.getLength(); i++) {
+ Element parse = (Element) instructions.item(i);
+ if (partnum != 0) {
+ String part_i = parse.getAttribute("part");
+ if (part_i.length() > 0) {
+ int n = Integer.parseInt(part_i);
+ if (n != partnum) {
+ continue;
+ }
+ }
+ }
+ if (mime != null) {
+ String mime_i = parse.getAttribute("mime");
+ if (mime_i.length() > 0) {
+ String[] mime_parts = mime_i.split(";\\s*");
+ if (!mime.startsWith(mime_parts[0])) {
+ continue;
+ }
+ boolean ok = true;
+ for (int j = 1; j < mime_parts.length; j++) {
+ if (mime.indexOf(mime_parts[j]) < 0) {
+ ok = false;
+ break;
+ }
+ }
+ if (!ok) {
+ continue;
+ }
+ }
+ }
+ NodeList children = parse.getChildNodes();
+ for (int j = 0; j < children.getLength(); j++) {
+ if (children.item(j).getNodeType() == Node.ELEMENT_NODE) {
+ parserNode = children.item(j);
+ break instructionsLoop;
+ }
+ }
+ }
+ return parserNode;
+ }
+
+ private static boolean queue_equals(int[] queue, int qPos, int qLen, int[] value) {
+ for (int i = 0; i < qLen; i++) {
+ if (queue[(i + qPos) % qLen] != value[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static File create_part_file(Reader in, String boundary) throws Exception {
+ File temp = File.createTempFile("$te_", ".tmp");
+ RandomAccessFile raf = new RandomAccessFile(temp, "rw");
+ int qLen = boundary.length() + 2;
+ int[] boundary_queue = new int[qLen];
+ boundary_queue[0] = '-';
+ boundary_queue[1] = '-';
+ for (int i = 0; i < boundary.length(); i++) {
+ boundary_queue[i + 2] = boundary.charAt(i);
+ }
+ int[] queue = new int[qLen];
+ for (int i = 0; i < qLen; i++) {
+ queue[i] = in.read();
+ if (queue[i] == -1) {
+ break;
+ }
+ }
+ int qPos = 0;
+ try {
+ while (!queue_equals(queue, qPos, qLen, boundary_queue)) {
+ raf.write(queue[qPos]);
+ queue[qPos] = in.read();
+ if (queue[qPos] == -1) {
+ // Fortify Mod: Clean up the file first, then throw the exception.
+ raf.close();
+ throw new Exception(EOS_ERR);
+ }
+ qPos = (qPos + 1) % qLen;
+ }
+ }
+ finally {
+ raf.close();
+ }
+ return temp;
+ }
+
+ /**
+ * Invocation point: Method called by TECore for request or soap-request.
+ *
+ * {@code }
+ */
+ public static Document parse(URLConnection uc, Element instruction, PrintWriter logger, TECore core)
+ throws Throwable {
+ try {
+ uc.connect();
+ }
+ catch (SSLProtocolException sslep) {
+ throw new SSLProtocolException(
+ "[SSL ERROR] Failed to connect with the requested URL due to \"Invalid server_name\" found!! :"
+ + uc.getURL() + ":" + sslep.getClass() + " : " + sslep.getMessage());
+ }
+ String mime = uc.getContentType();
+ boolean multipart = (mime != null && mime.startsWith("multipart"));
+
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ // Fortify Mod: prevent external entity injection
+ dbf.setExpandEntityReferences(false);
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ Document doc = db.newDocument();
+ Element root = doc.createElement(multipart ? "multipart-response" : "response");
+ if (uc.getHeaderFieldKey(0) == null) {
+ Element status = doc.createElement("status");
+ String status_line = uc.getHeaderField(0);
+ if (status_line != null) {
+ String[] status_array = status_line.split("\\s");
+ if (status_array.length > 0) {
+ status.setAttribute("protocol", status_array[0]);
+ }
+ if (status_array.length > 1) {
+ status.setAttribute("code", status_array[1]);
+ }
+ if (status_array.length > 2) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 2; i < status_array.length; i++) {
+ sb.append(status_array[i]);
+ sb.append(" ");
+ }
+ status.appendChild(doc.createTextNode(sb.toString().trim()));
+ }
+ }
+ root.appendChild(status);
+ }
+
+ append_headers(uc, root);
+ // Fortify Mod: prevent external entity injection
+ TransformerFactory tf = TransformerFactory.newInstance();
+ tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ Transformer t = tf.newTransformer();
+ // Transformer t = TransformerFactory.newInstance().newTransformer();
+
+ if (multipart) {
+ String mime2 = mime + ";";
+ int start = mime2.indexOf("boundary=") + 9;
+ char endchar = ';';
+ if (mime2.charAt(start) == '"') {
+ start++;
+ endchar = '"';
+ }
+ int end = mime2.indexOf(endchar, start);
+ String boundary = mime2.substring(start, end);
+ InputStream is = URLConnectionUtils.getInputStream(uc);
+ BufferedReader in = new BufferedReader(new InputStreamReader(is));
+ File temp = create_part_file(in, boundary);
+ temp.delete();
+ String line = in.readLine();
+ int num = 1;
+ while (!line.endsWith("--")) {
+ String contentType = "text/plain";
+ Element part = doc.createElement("part");
+ part.setAttribute("num", Integer.toString(num));
+ Element headers = doc.createElement("headers");
+ line = in.readLine();
+ while (line.length() > 0) {
+ Element header = doc.createElement("header");
+ int colon = line.indexOf(":");
+ String name = line.substring(0, colon);
+ String value = line.substring(colon + 1).trim();
+ if (name.toLowerCase().equals("content-type")) {
+ contentType = value;
+ }
+ header.setAttribute("name", name);
+ header.appendChild(doc.createTextNode(value));
+ headers.appendChild(header);
+ line = in.readLine();
+ }
+ part.appendChild(headers);
+ temp = create_part_file(in, boundary);
+ URLConnection pc = temp.toURI().toURL().openConnection();
+ pc.setRequestProperty("Content-type", mime);
+ Node parser = select_parser(num, contentType, instruction);
+ // use TECore to invoke any subsidiary (chained) parsers
+ Element response_e = core.parse(pc, parser);
+ temp.delete();
+ Element parser_e = (Element) (response_e.getElementsByTagName("parser").item(0));
+ if (parser_e != null) {
+ logger.print(parser_e.getTextContent());
+ }
+ Element content = (Element) (response_e.getElementsByTagName("content").item(0));
+ if ((null != content) && content.hasChildNodes()) {
+ t.transform(new DOMSource(content), new DOMResult(part));
+ }
+ root.appendChild(part);
+ line = in.readLine();
+ num++;
+ }
+ // Fortify Mod: Close the BufferedReader and release its resources
+ in.close();
+ }
+ else {
+ Node parser = select_parser(0, uc.getContentType(), instruction);
+ // use TECore to invoke any chained (subsidiary) parsers
+ if (LOGR.isLoggable(Level.FINER)) {
+ String msg = String.format("Calling subsidiary parser for resource at %s:%n%s", uc.getURL(),
+ DomUtils.serializeNode(parser));
+ LOGR.finer(msg);
+ }
+ Element response_e = core.parse(uc, parser);
+ Element parser_e = (Element) (response_e.getElementsByTagName("parser").item(0));
+ if (parser_e != null) {
+ logger.print(parser_e.getTextContent());
+ }
+ Element content = (Element) (response_e.getElementsByTagName("content").item(0));
+ if (null != content) {
+ root.appendChild(doc.importNode(content, true));
+ }
+ }
+ doc.appendChild(root);
+ return doc;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/parsers/ImageParser.java b/teamengine-core/src/main/java/com/occamlab/te/parsers/ImageParser.java
index c38b96680..348ce1e6c 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/parsers/ImageParser.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/parsers/ImageParser.java
@@ -19,6 +19,26 @@ Paul Daisey (Image Matters LLC)
****************************************************************************/
package com.occamlab.te.parsers;
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
diff --git a/teamengine-core/src/main/java/com/occamlab/te/parsers/NullParser.java b/teamengine-core/src/main/java/com/occamlab/te/parsers/NullParser.java
index 95d2a916a..d41f7ec4b 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/parsers/NullParser.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/parsers/NullParser.java
@@ -1,31 +1,51 @@
-/****************************************************************************
-
- The Original Code is TEAM Engine.
-
- The Initial Developer of the Original Code is Northrop Grumman Corporation
- jointly with The National Technology Alliance. Portions created by
- Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
- Grumman Corporation. All Rights Reserved.
-
- Contributor(s): No additional contributors to date
-
- ****************************************************************************/
-package com.occamlab.te.parsers;
-
-import java.net.URLConnection;
-import java.io.PrintWriter;
-
-import org.w3c.dom.Element;
-
-/**
- * Ignores the request information and returns null. This request parser may
- * be used to skip a request for some reason.
- *
- */
-public class NullParser {
-
- public static String parse(URLConnection uc, Element instruction, PrintWriter logger) throws Exception {
- return null;
- }
-
-}
+/****************************************************************************
+
+ The Original Code is TEAM Engine.
+
+ The Initial Developer of the Original Code is Northrop Grumman Corporation
+ jointly with The National Technology Alliance. Portions created by
+ Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
+ Grumman Corporation. All Rights Reserved.
+
+ Contributor(s): No additional contributors to date
+
+ ****************************************************************************/
+package com.occamlab.te.parsers;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.net.URLConnection;
+import java.io.PrintWriter;
+
+import org.w3c.dom.Element;
+
+/**
+ * Ignores the request information and returns null. This request parser may
+ * be used to skip a request for some reason.
+ *
+ */
+public class NullParser {
+
+ public static String parse(URLConnection uc, Element instruction, PrintWriter logger) throws Exception {
+ return null;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/parsers/SchematronValidatingParser.java b/teamengine-core/src/main/java/com/occamlab/te/parsers/SchematronValidatingParser.java
index 4f0ea52b0..aaa686a8a 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/parsers/SchematronValidatingParser.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/parsers/SchematronValidatingParser.java
@@ -1,433 +1,453 @@
-/**
- * **************************************************************************
- *
- * Contributor(s):
- * C. Heazel (WiSC): Added Fortify adjudication changes
- *
- ***************************************************************************
- */
-
-package com.occamlab.te.parsers;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
-import java.io.PrintWriter;
-import java.net.URL;
-import java.net.URLConnection;
-import java.net.URLDecoder;
-import java.nio.charset.StandardCharsets;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-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.XMLConstants; // Addition for Fortify modifications
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-import com.occamlab.te.ErrorHandlerImpl;
-import com.thaiopensource.util.PropertyMap;
-import com.thaiopensource.util.PropertyMapBuilder;
-import com.thaiopensource.validate.SchemaReader;
-import com.thaiopensource.validate.SchemaReaderLoader;
-import com.thaiopensource.validate.ValidateProperty;
-import com.thaiopensource.validate.ValidationDriver;
-import com.thaiopensource.validate.prop.schematron.SchematronProperty;
-
-/**
- * Validates the given XML resource against the rules specified in a Schematron (v1.5)
- * file. Used in conjunction with standard XML Schema validator to provide more thorough
- * validation coverage.
- *
- * Diagnostic messages will be included if any are defined.
- *
- */
-public class SchematronValidatingParser {
-
- private static final Logger LOGR = Logger.getLogger(SchematronValidatingParser.class.getName());
-
- private PropertyMapBuilder configPropBuilder = null;
-
- private String schemaLocation = null;
-
- private File schemaFile = null;
-
- private String phase = null;
-
- private String type = null;
-
- private PrintWriter outputLogger = null;
-
- /** Namespace URI for the Schematron assertion language (v 1.5). */
- public static final String SCHEMATRON_NS_URI = "http://www.ascc.net/xml/schematron";
-
- /** Default constructor required for init */
- public SchematronValidatingParser() {
- }
-
- /** Overloaded constructor required for init */
- public SchematronValidatingParser(Document schema_link) throws Exception {
- getFileType(schema_link.getDocumentElement());
- }
-
- /**
- * Parses the parser element to get the schematron file location and type of resource
- * (from ctl file).
- * @param schema_links Gets the location of the schema (and type of resource) and
- * saves to global parameter
- * @return The type of resource (URL, File, Resource)
- */
- public String getFileType(Element schema_links) throws Exception {
- Document d = schema_links.getOwnerDocument();
- NodeList nodes = d.getElementsByTagNameNS("http://www.occamlab.com/te/parsers", "schema");
- String localType = null;
- for (int i = 0; i < nodes.getLength(); i++) {
- Element e = (Element) nodes.item(i);
- localType = e.getAttribute("type");
- this.type = e.getAttribute("type");
- this.phase = e.getAttribute("phase");
- this.schemaLocation = e.getTextContent().trim();
- }
- return localType;
- }
-
- /**
- * Converts an org.w3c.dom.Document element to an java.io.InputStream.
- * @param edoc The org.w3c.dom.Document to be converted
- * @return The InputStream value of the passed doument
- */
- public InputStream DocumentToInputStream(org.w3c.dom.Document edoc) throws IOException {
-
- final org.w3c.dom.Document doc = edoc;
- final PipedOutputStream pos = new PipedOutputStream();
- PipedInputStream pis = new PipedInputStream();
- pis.connect(pos);
-
- (new Thread(new Runnable() {
-
- public void run() {
- // Use the Transformer.transform() method to save the Document
- // to a StreamResult
- try {
- TransformerFactory tFactory = TransformerFactory.newInstance();
- // Fortify Mod: prevent external entity injection
- tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- Transformer transformer = tFactory.newTransformer();
- transformer.setOutputProperty("encoding", "ISO-8859-1");
- transformer.setOutputProperty("indent", "yes");
- transformer.transform(new DOMSource(doc), new StreamResult(pos));
- }
- catch (Exception _ex) {
- throw new RuntimeException("Failed to tranform org.w3c.dom.Document to PipedOutputStream", _ex);
- }
- finally {
- try {
- pos.close();
- }
- catch (IOException e) {
-
- }
- }
- }
- }, "MyClassName.convert(org.w3c.dom.Document edoc)")).start();
-
- return pis;
- }
-
- /**
- * Checks the given schematron phase for the XML file and returns the validation
- * status.
- * @param doc The XML file to validate (Document)
- * @param schemaFile The string path to the schematron file to use
- * @param phase The string phase name (contained in schematron file)
- * @return Whether there were validation errors or not (boolean)
- */
- public boolean checkSchematronRules(Document doc, String schemaFile, String phase) throws Exception {
-
- boolean isValid = false;
-
- if (doc == null || doc.getDocumentElement() == null)
- return isValid;
- try {
- ClassLoader loader = this.getClass().getClassLoader();
- URL url = loader.getResource(schemaFile);
- this.schemaFile = new File(URLDecoder.decode(url.getFile(), StandardCharsets.UTF_8));
- }
- catch (Exception e) {
- assert false : "Entity body not found. " + e.toString();
- }
- this.phase = phase;
- Document returnDoc = parse(doc, null, null);
- if (returnDoc != null) {
- isValid = true;
- }
- return isValid;
- }
-
- /**
- * Checks the given schematron phase for the XML file and returns the validation
- * status (takes schematron file, not string location). New and ADVANCED! (team engine
- * can't work with overloaded methods :P)
- * @param inputDoc The XML file to validate (Document)
- * @param schemaFile The file object of the schematron file to validate with
- * @param phase The string phase name (contained in schematron file)
- * @return Whether there were validation errors or not (boolean)
- */
- public boolean checkSchematronRulesAdv(InputSource inputDoc, File schemaFile, String phase) throws Exception {
-
- boolean isValid = false;
- if (inputDoc == null)
- return isValid;
- this.schemaFile = schemaFile;
- this.phase = phase;
-
- Document returnDoc = parse(inputDoc, null, null);
- if (returnDoc != null) {
- isValid = true;
- }
- return isValid;
- }
-
- /**
- * Runs the schematron file against the input source.
- */
- public boolean executeSchematronDriver(InputSource inputDoc, File schemaFile, String phase) {
-
- boolean isValid = false;
- ValidationDriver driver = createSchematronDriver(phase);
- assert null != driver : "Unable to create Schematron ValidationDriver";
- InputSource is = null;
- // Fortify Mod: move fis out so it can be closed on exit
- FileInputStream fis = null;
- try {
- // FileInputStream fis = new FileInputStream(schemaFile);
- fis = new FileInputStream(schemaFile);
- is = new InputSource(fis);
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- try {
- if (driver.loadSchema(is)) {
- isValid = driver.validate(inputDoc);
- fis.close(); // Fortify addition
- }
- else {
- assert false : ("Failed to load Schematron schema: " + schemaFile
- + "\nIs the schema valid? Is the phase defined?");
- }
- }
- catch (SAXException e) {
- assert false : e.toString();
- }
- catch (IOException e) {
- assert false : e.toString();
- }
- return isValid;
- }
-
- /**
- * Sets up the schematron reader with all the necessary parameters. Calls
- * initSchematronReader() to do further setup of the validation driver.
- * @param phase The string phase name (contained in schematron file)
- * @return The ValidationDriver to use in validating the XML document
- */
- ValidationDriver createSchematronDriver(String phase) {
- SchemaReaderLoader loader = new SchemaReaderLoader();
- SchemaReader schReader = loader.createSchemaReader(SCHEMATRON_NS_URI);
- this.configPropBuilder = new PropertyMapBuilder();
- SchematronProperty.DIAGNOSE.add(this.configPropBuilder);
-
- if (this.outputLogger == null) {
- this.outputLogger = new PrintWriter(System.out);
- }
- if (null != phase && !phase.isEmpty()) {
- this.configPropBuilder.put(SchematronProperty.PHASE, phase);
- }
- ErrorHandler eh = new ErrorHandlerImpl("Schematron", outputLogger);
- this.configPropBuilder.put(ValidateProperty.ERROR_HANDLER, eh);
- return new ValidationDriver(this.configPropBuilder.toPropertyMap(), schReader);
- }
-
- /**
- * Parses and validates a resource obtained by dereferencing a URI.
- * @param uc A URLConnection to access an XML resource.
- * @param instruction An element containing parser instructions.
- * @param logger The PrintWriter used for logging errors.
- * @return A Document node if parsing succeeds, or {@code null} if it fails.
- * @throws Exception
- */
- public Document parse(URLConnection uc, Element instruction, PrintWriter logger) throws Exception {
- return parse(uc.getInputStream(), instruction, logger);
- }
-
- Document parse(InputStream is, Element instruction, PrintWriter logger) throws Exception {
-
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setNamespaceAware(true);
- // Fortify Mod: Disable entity expansion to foil External Entity Injections
- dbf.setExpandEntityReferences(false);
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document doc = null;
- try {
- doc = db.parse(is);
- }
- catch (Exception e) {
- logger.println(e.getMessage());
- }
- return parse(doc, instruction, logger);
- }
-
- Document parse(InputSource is, Element instruction, PrintWriter logger) throws Exception {
-
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setNamespaceAware(true);
- // Fortify Mod: Disable entity expansion to foil External Entity Injections
- dbf.setExpandEntityReferences(false);
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document doc = null;
- try {
- doc = db.parse(is);
- }
- catch (Exception e) {
- logger.println(e.getMessage());
- }
- return parse(doc, instruction, logger);
- }
-
- /**
- * Checks the given Document against a Schematron schema. A schema reference is
- * conveyed by a DOM Element node as indicated below.
- *
- *
- * {@code
- *
- * /class/path/schema1.sch
- *
- * }
- *
- * @param doc The document to be validated.
- * @param instruction An Element containing schema information.
- * @param logger A Writer used for logging error messages.
- * @return The valid document, or {@code null} if any errors were detected.
- * @throws Exception
- */
- Document parse(Document doc, Element instruction, PrintWriter logger) throws Exception {
- this.outputLogger = logger;
- if (instruction != null) {
- getFileType(instruction);
- if (type.equals("url")) {
- URL schemaURL = new URL(this.schemaLocation);
- this.schemaFile = new File(schemaURL.toURI());
- }
- else if (type.equals("file")) {
- this.schemaFile = new File(this.schemaLocation);
- }
- else if (type.equals("resource")) {
- URL url = this.getClass().getResource(this.schemaLocation);
- this.schemaFile = new File(URLDecoder.decode(url.getFile(), StandardCharsets.UTF_8));
- }
- }
- boolean isValid = false;
- if (doc != null) {
- InputSource xmlInputSource = null;
- try {
- InputStream inputStream = DocumentToInputStream(doc);
- xmlInputSource = new InputSource(inputStream);
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- isValid = executeSchematronDriver(xmlInputSource, this.schemaFile, this.phase);
- }
- if (!isValid) {
- return null;
- }
- else {
- return doc;
- }
- }
-
- /**
- * Checks the content of an XML entity against the applicable rules defined in a
- * Schematron schema. The designated phase identifies the active patterns (rule sets);
- * if not specified, the default phase is executed.
- * @param xmlEntity A DOM Document representing the XML entity to validate.
- * @param schemaRef A (classpath) reference to a Schematron 1.5 schema.
- * @param phase The phase to execute.
- * @return A NodeList containing validation errors (it may be empty).
- */
- public NodeList validate(Document xmlEntity, String schemaRef, String phase) {
-
- if (xmlEntity == null || xmlEntity.getDocumentElement() == null)
- throw new IllegalArgumentException("No XML entity supplied (null).");
- InputSource xmlInputSource = null;
- try {
- InputStream inputStream = DocumentToInputStream(xmlEntity);
- xmlInputSource = new InputSource(inputStream);
- }
- catch (IOException e) {
- throw new RuntimeException(e);
- }
- PropertyMapBuilder builder = new PropertyMapBuilder();
- SchematronProperty.DIAGNOSE.add(builder);
- if (null != phase && !phase.isEmpty()) {
- builder.put(SchematronProperty.PHASE, phase);
- }
- XmlErrorHandler errHandler = new XmlErrorHandler();
- builder.put(ValidateProperty.ERROR_HANDLER, errHandler);
- ValidationDriver driver = createDriver(builder.toPropertyMap());
- InputStream schStream = this.getClass().getResourceAsStream(schemaRef.trim());
- try {
- InputSource input = new InputSource(schStream);
- try {
- boolean loaded = driver.loadSchema(input);
- if (!loaded) {
- throw new Exception("Failed to load schema at " + schemaRef.trim()
- + "\nIs the schema valid? Is the phase defined?");
- }
- }
- finally {
- schStream.close();
- }
- driver.validate(xmlInputSource);
- }
- catch (Exception e) {
- throw new RuntimeException("Schematron validation failed.", e);
- }
- NodeList errList = errHandler.toNodeList();
- if (LOGR.isLoggable(Level.FINER)) {
- LOGR.finer(String.format("Found %d Schematron rule violation(s):%n %s", errList.getLength(),
- errHandler.toString()));
- }
- return errList;
- }
-
- /**
- * Creates and initializes a ValidationDriver to perform Schematron validation. A
- * schema must be loaded before an instance can be validated.
- * @param configProps A PropertyMap containing properties to configure schema
- * construction and validation behavior; it typically includes
- * {@code SchematronProperty} and {@code ValidationProperty} items.
- * @return A ValidationDriver that is ready to load a Schematron schema.
- */
- ValidationDriver createDriver(PropertyMap configProps) {
- SchemaReaderLoader loader = new SchemaReaderLoader();
- SchemaReader schReader = loader.createSchemaReader(SCHEMATRON_NS_URI);
- return new ValidationDriver(configProps, schReader);
- }
-
-}
+/**
+ * **************************************************************************
+ *
+ * Contributor(s):
+ * C. Heazel (WiSC): Added Fortify adjudication changes
+ *
+ ***************************************************************************
+ */
+
+package com.occamlab.te.parsers;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.io.PrintWriter;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+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.XMLConstants; // Addition for Fortify modifications
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+import com.occamlab.te.ErrorHandlerImpl;
+import com.thaiopensource.util.PropertyMap;
+import com.thaiopensource.util.PropertyMapBuilder;
+import com.thaiopensource.validate.SchemaReader;
+import com.thaiopensource.validate.SchemaReaderLoader;
+import com.thaiopensource.validate.ValidateProperty;
+import com.thaiopensource.validate.ValidationDriver;
+import com.thaiopensource.validate.prop.schematron.SchematronProperty;
+
+/**
+ * Validates the given XML resource against the rules specified in a Schematron (v1.5)
+ * file. Used in conjunction with standard XML Schema validator to provide more thorough
+ * validation coverage.
+ *
+ * Diagnostic messages will be included if any are defined.
+ *
+ */
+public class SchematronValidatingParser {
+
+ private static final Logger LOGR = Logger.getLogger(SchematronValidatingParser.class.getName());
+
+ private PropertyMapBuilder configPropBuilder = null;
+
+ private String schemaLocation = null;
+
+ private File schemaFile = null;
+
+ private String phase = null;
+
+ private String type = null;
+
+ private PrintWriter outputLogger = null;
+
+ /** Namespace URI for the Schematron assertion language (v 1.5). */
+ public static final String SCHEMATRON_NS_URI = "http://www.ascc.net/xml/schematron";
+
+ /** Default constructor required for init */
+ public SchematronValidatingParser() {
+ }
+
+ /** Overloaded constructor required for init */
+ public SchematronValidatingParser(Document schema_link) throws Exception {
+ getFileType(schema_link.getDocumentElement());
+ }
+
+ /**
+ * Parses the parser element to get the schematron file location and type of resource
+ * (from ctl file).
+ * @param schema_links Gets the location of the schema (and type of resource) and
+ * saves to global parameter
+ * @return The type of resource (URL, File, Resource)
+ */
+ public String getFileType(Element schema_links) throws Exception {
+ Document d = schema_links.getOwnerDocument();
+ NodeList nodes = d.getElementsByTagNameNS("http://www.occamlab.com/te/parsers", "schema");
+ String localType = null;
+ for (int i = 0; i < nodes.getLength(); i++) {
+ Element e = (Element) nodes.item(i);
+ localType = e.getAttribute("type");
+ this.type = e.getAttribute("type");
+ this.phase = e.getAttribute("phase");
+ this.schemaLocation = e.getTextContent().trim();
+ }
+ return localType;
+ }
+
+ /**
+ * Converts an org.w3c.dom.Document element to an java.io.InputStream.
+ * @param edoc The org.w3c.dom.Document to be converted
+ * @return The InputStream value of the passed doument
+ */
+ public InputStream DocumentToInputStream(org.w3c.dom.Document edoc) throws IOException {
+
+ final org.w3c.dom.Document doc = edoc;
+ final PipedOutputStream pos = new PipedOutputStream();
+ PipedInputStream pis = new PipedInputStream();
+ pis.connect(pos);
+
+ (new Thread(new Runnable() {
+
+ public void run() {
+ // Use the Transformer.transform() method to save the Document
+ // to a StreamResult
+ try {
+ TransformerFactory tFactory = TransformerFactory.newInstance();
+ // Fortify Mod: prevent external entity injection
+ tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ Transformer transformer = tFactory.newTransformer();
+ transformer.setOutputProperty("encoding", "ISO-8859-1");
+ transformer.setOutputProperty("indent", "yes");
+ transformer.transform(new DOMSource(doc), new StreamResult(pos));
+ }
+ catch (Exception _ex) {
+ throw new RuntimeException("Failed to tranform org.w3c.dom.Document to PipedOutputStream", _ex);
+ }
+ finally {
+ try {
+ pos.close();
+ }
+ catch (IOException e) {
+
+ }
+ }
+ }
+ }, "MyClassName.convert(org.w3c.dom.Document edoc)")).start();
+
+ return pis;
+ }
+
+ /**
+ * Checks the given schematron phase for the XML file and returns the validation
+ * status.
+ * @param doc The XML file to validate (Document)
+ * @param schemaFile The string path to the schematron file to use
+ * @param phase The string phase name (contained in schematron file)
+ * @return Whether there were validation errors or not (boolean)
+ */
+ public boolean checkSchematronRules(Document doc, String schemaFile, String phase) throws Exception {
+
+ boolean isValid = false;
+
+ if (doc == null || doc.getDocumentElement() == null)
+ return isValid;
+ try {
+ ClassLoader loader = this.getClass().getClassLoader();
+ URL url = loader.getResource(schemaFile);
+ this.schemaFile = new File(URLDecoder.decode(url.getFile(), StandardCharsets.UTF_8));
+ }
+ catch (Exception e) {
+ assert false : "Entity body not found. " + e.toString();
+ }
+ this.phase = phase;
+ Document returnDoc = parse(doc, null, null);
+ if (returnDoc != null) {
+ isValid = true;
+ }
+ return isValid;
+ }
+
+ /**
+ * Checks the given schematron phase for the XML file and returns the validation
+ * status (takes schematron file, not string location). New and ADVANCED! (team engine
+ * can't work with overloaded methods :P)
+ * @param inputDoc The XML file to validate (Document)
+ * @param schemaFile The file object of the schematron file to validate with
+ * @param phase The string phase name (contained in schematron file)
+ * @return Whether there were validation errors or not (boolean)
+ */
+ public boolean checkSchematronRulesAdv(InputSource inputDoc, File schemaFile, String phase) throws Exception {
+
+ boolean isValid = false;
+ if (inputDoc == null)
+ return isValid;
+ this.schemaFile = schemaFile;
+ this.phase = phase;
+
+ Document returnDoc = parse(inputDoc, null, null);
+ if (returnDoc != null) {
+ isValid = true;
+ }
+ return isValid;
+ }
+
+ /**
+ * Runs the schematron file against the input source.
+ */
+ public boolean executeSchematronDriver(InputSource inputDoc, File schemaFile, String phase) {
+
+ boolean isValid = false;
+ ValidationDriver driver = createSchematronDriver(phase);
+ assert null != driver : "Unable to create Schematron ValidationDriver";
+ InputSource is = null;
+ // Fortify Mod: move fis out so it can be closed on exit
+ FileInputStream fis = null;
+ try {
+ // FileInputStream fis = new FileInputStream(schemaFile);
+ fis = new FileInputStream(schemaFile);
+ is = new InputSource(fis);
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ try {
+ if (driver.loadSchema(is)) {
+ isValid = driver.validate(inputDoc);
+ fis.close(); // Fortify addition
+ }
+ else {
+ assert false : ("Failed to load Schematron schema: " + schemaFile
+ + "\nIs the schema valid? Is the phase defined?");
+ }
+ }
+ catch (SAXException e) {
+ assert false : e.toString();
+ }
+ catch (IOException e) {
+ assert false : e.toString();
+ }
+ return isValid;
+ }
+
+ /**
+ * Sets up the schematron reader with all the necessary parameters. Calls
+ * initSchematronReader() to do further setup of the validation driver.
+ * @param phase The string phase name (contained in schematron file)
+ * @return The ValidationDriver to use in validating the XML document
+ */
+ ValidationDriver createSchematronDriver(String phase) {
+ SchemaReaderLoader loader = new SchemaReaderLoader();
+ SchemaReader schReader = loader.createSchemaReader(SCHEMATRON_NS_URI);
+ this.configPropBuilder = new PropertyMapBuilder();
+ SchematronProperty.DIAGNOSE.add(this.configPropBuilder);
+
+ if (this.outputLogger == null) {
+ this.outputLogger = new PrintWriter(System.out);
+ }
+ if (null != phase && !phase.isEmpty()) {
+ this.configPropBuilder.put(SchematronProperty.PHASE, phase);
+ }
+ ErrorHandler eh = new ErrorHandlerImpl("Schematron", outputLogger);
+ this.configPropBuilder.put(ValidateProperty.ERROR_HANDLER, eh);
+ return new ValidationDriver(this.configPropBuilder.toPropertyMap(), schReader);
+ }
+
+ /**
+ * Parses and validates a resource obtained by dereferencing a URI.
+ * @param uc A URLConnection to access an XML resource.
+ * @param instruction An element containing parser instructions.
+ * @param logger The PrintWriter used for logging errors.
+ * @return A Document node if parsing succeeds, or {@code null} if it fails.
+ * @throws Exception
+ */
+ public Document parse(URLConnection uc, Element instruction, PrintWriter logger) throws Exception {
+ return parse(uc.getInputStream(), instruction, logger);
+ }
+
+ Document parse(InputStream is, Element instruction, PrintWriter logger) throws Exception {
+
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setNamespaceAware(true);
+ // Fortify Mod: Disable entity expansion to foil External Entity Injections
+ dbf.setExpandEntityReferences(false);
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ Document doc = null;
+ try {
+ doc = db.parse(is);
+ }
+ catch (Exception e) {
+ logger.println(e.getMessage());
+ }
+ return parse(doc, instruction, logger);
+ }
+
+ Document parse(InputSource is, Element instruction, PrintWriter logger) throws Exception {
+
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setNamespaceAware(true);
+ // Fortify Mod: Disable entity expansion to foil External Entity Injections
+ dbf.setExpandEntityReferences(false);
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ Document doc = null;
+ try {
+ doc = db.parse(is);
+ }
+ catch (Exception e) {
+ logger.println(e.getMessage());
+ }
+ return parse(doc, instruction, logger);
+ }
+
+ /**
+ * Checks the given Document against a Schematron schema. A schema reference is
+ * conveyed by a DOM Element node as indicated below.
+ *
+ *
+ * {@code
+ *
+ * /class/path/schema1.sch
+ *
+ * }
+ *
+ * @param doc The document to be validated.
+ * @param instruction An Element containing schema information.
+ * @param logger A Writer used for logging error messages.
+ * @return The valid document, or {@code null} if any errors were detected.
+ * @throws Exception
+ */
+ Document parse(Document doc, Element instruction, PrintWriter logger) throws Exception {
+ this.outputLogger = logger;
+ if (instruction != null) {
+ getFileType(instruction);
+ if (type.equals("url")) {
+ URL schemaURL = new URL(this.schemaLocation);
+ this.schemaFile = new File(schemaURL.toURI());
+ }
+ else if (type.equals("file")) {
+ this.schemaFile = new File(this.schemaLocation);
+ }
+ else if (type.equals("resource")) {
+ URL url = this.getClass().getResource(this.schemaLocation);
+ this.schemaFile = new File(URLDecoder.decode(url.getFile(), StandardCharsets.UTF_8));
+ }
+ }
+ boolean isValid = false;
+ if (doc != null) {
+ InputSource xmlInputSource = null;
+ try {
+ InputStream inputStream = DocumentToInputStream(doc);
+ xmlInputSource = new InputSource(inputStream);
+ }
+ catch (IOException e) {
+ e.printStackTrace();
+ }
+ isValid = executeSchematronDriver(xmlInputSource, this.schemaFile, this.phase);
+ }
+ if (!isValid) {
+ return null;
+ }
+ else {
+ return doc;
+ }
+ }
+
+ /**
+ * Checks the content of an XML entity against the applicable rules defined in a
+ * Schematron schema. The designated phase identifies the active patterns (rule sets);
+ * if not specified, the default phase is executed.
+ * @param xmlEntity A DOM Document representing the XML entity to validate.
+ * @param schemaRef A (classpath) reference to a Schematron 1.5 schema.
+ * @param phase The phase to execute.
+ * @return A NodeList containing validation errors (it may be empty).
+ */
+ public NodeList validate(Document xmlEntity, String schemaRef, String phase) {
+
+ if (xmlEntity == null || xmlEntity.getDocumentElement() == null)
+ throw new IllegalArgumentException("No XML entity supplied (null).");
+ InputSource xmlInputSource = null;
+ try {
+ InputStream inputStream = DocumentToInputStream(xmlEntity);
+ xmlInputSource = new InputSource(inputStream);
+ }
+ catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ PropertyMapBuilder builder = new PropertyMapBuilder();
+ SchematronProperty.DIAGNOSE.add(builder);
+ if (null != phase && !phase.isEmpty()) {
+ builder.put(SchematronProperty.PHASE, phase);
+ }
+ XmlErrorHandler errHandler = new XmlErrorHandler();
+ builder.put(ValidateProperty.ERROR_HANDLER, errHandler);
+ ValidationDriver driver = createDriver(builder.toPropertyMap());
+ InputStream schStream = this.getClass().getResourceAsStream(schemaRef.trim());
+ try {
+ InputSource input = new InputSource(schStream);
+ try {
+ boolean loaded = driver.loadSchema(input);
+ if (!loaded) {
+ throw new Exception("Failed to load schema at " + schemaRef.trim()
+ + "\nIs the schema valid? Is the phase defined?");
+ }
+ }
+ finally {
+ schStream.close();
+ }
+ driver.validate(xmlInputSource);
+ }
+ catch (Exception e) {
+ throw new RuntimeException("Schematron validation failed.", e);
+ }
+ NodeList errList = errHandler.toNodeList();
+ if (LOGR.isLoggable(Level.FINER)) {
+ LOGR.finer(String.format("Found %d Schematron rule violation(s):%n %s", errList.getLength(),
+ errHandler.toString()));
+ }
+ return errList;
+ }
+
+ /**
+ * Creates and initializes a ValidationDriver to perform Schematron validation. A
+ * schema must be loaded before an instance can be validated.
+ * @param configProps A PropertyMap containing properties to configure schema
+ * construction and validation behavior; it typically includes
+ * {@code SchematronProperty} and {@code ValidationProperty} items.
+ * @return A ValidationDriver that is ready to load a Schematron schema.
+ */
+ ValidationDriver createDriver(PropertyMap configProps) {
+ SchemaReaderLoader loader = new SchemaReaderLoader();
+ SchemaReader schReader = loader.createSchemaReader(SCHEMATRON_NS_URI);
+ return new ValidationDriver(configProps, schReader);
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java b/teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java
index 7c74f5111..6eb239eb6 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java
@@ -11,6 +11,26 @@ Intecs SPA are Copyright (C) 2008-2009, Intecs SPA. All Rights Reserved.
package com.occamlab.te.parsers;
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.net.URLConnection;
diff --git a/teamengine-core/src/main/java/com/occamlab/te/parsers/ValidationError.java b/teamengine-core/src/main/java/com/occamlab/te/parsers/ValidationError.java
index b2d7fd2b6..e949fd93b 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/parsers/ValidationError.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/parsers/ValidationError.java
@@ -1,58 +1,78 @@
-package com.occamlab.te.parsers;
-
-/**
- * Encapsulates information pertaining to a validation error. Instances of this class are
- * immutable.
- *
- * @author rmartell
- * @version $Rev$
- */
-public class ValidationError {
-
- /**
- * A warning (e.g., a condition that does not cause the instance to be non-conforming.
- */
- public static final short WARNING = 1;
-
- /** An error (e.g., the instance is invalid). */
- public static final short ERROR = 2;
-
- /** A fatal error (e.g., the instance is not well-formed). */
- public static final short FATAL_ERROR = 3;
-
- /** The error message. */
- private String message;
-
- /** The severity level. */
- private short severity;
-
- /**
- * Constructs an immutable error object.
- * @param severity the severity level (Warning, Error, Fatal)
- * @param message a descriptive message
- */
- public ValidationError(short severity, String message) {
- if (null == message) {
- message = "No details available";
- }
- this.message = message;
- this.severity = severity;
- }
-
- /**
- * Returns the message describing this error.
- * @return the details about this error
- */
- public String getMessage() {
- return message;
- }
-
- /**
- * Returns the severity code (a short value) for this error.
- * @return the severity code for this error
- */
- public short getSeverity() {
- return severity;
- }
-
-}
+package com.occamlab.te.parsers;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+/**
+ * Encapsulates information pertaining to a validation error. Instances of this class are
+ * immutable.
+ *
+ * @author rmartell
+ * @version $Rev$
+ */
+public class ValidationError {
+
+ /**
+ * A warning (e.g., a condition that does not cause the instance to be non-conforming.
+ */
+ public static final short WARNING = 1;
+
+ /** An error (e.g., the instance is invalid). */
+ public static final short ERROR = 2;
+
+ /** A fatal error (e.g., the instance is not well-formed). */
+ public static final short FATAL_ERROR = 3;
+
+ /** The error message. */
+ private String message;
+
+ /** The severity level. */
+ private short severity;
+
+ /**
+ * Constructs an immutable error object.
+ * @param severity the severity level (Warning, Error, Fatal)
+ * @param message a descriptive message
+ */
+ public ValidationError(short severity, String message) {
+ if (null == message) {
+ message = "No details available";
+ }
+ this.message = message;
+ this.severity = severity;
+ }
+
+ /**
+ * Returns the message describing this error.
+ * @return the details about this error
+ */
+ public String getMessage() {
+ return message;
+ }
+
+ /**
+ * Returns the severity code (a short value) for this error.
+ * @return the severity code for this error
+ */
+ public short getSeverity() {
+ return severity;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java b/teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java
index 5d6a76790..fb6d8336a 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java
@@ -1,444 +1,464 @@
-/**
- * **************************************************************************
- *
- * Contributor(s):
- * C. Heazel (WiSC): Added Fortify adjudication changes
- *
- ***************************************************************************
- */
-package com.occamlab.te.parsers;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.CharArrayWriter;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintWriter;
-import java.net.URI;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.net.ssl.SSLProtocolException;
-import javax.xml.XMLConstants;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Result;
-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.validation.Schema;
-import javax.xml.validation.Validator;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.DocumentType;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.SAXException;
-
-import com.google.common.collect.ImmutableList;
-import com.occamlab.te.ErrorHandlerImpl;
-import com.occamlab.te.parsers.xml.CachingSchemaLoader;
-import com.occamlab.te.parsers.xml.InMemorySchemaSupplier;
-import com.occamlab.te.parsers.xml.XsdSchemaLoader;
-import com.occamlab.te.parsers.xml.SchemaSupplier;
-import com.occamlab.te.util.DomUtils;
-import com.occamlab.te.util.URLConnectionUtils;
-
-/**
- * Validates an XML resource against a set of W3C XML Schema or DTD schemas.
- *
- */
-public class XMLValidatingParser {
-
- static TransformerFactory TF = null;
- static DocumentBuilderFactory nonValidatingDBF = null;
- static DocumentBuilderFactory schemaValidatingDBF = null;
- static DocumentBuilderFactory dtdValidatingDBF = null;
-
- ArrayList schemaList = new ArrayList<>();
-
- ArrayList dtdList = new ArrayList<>();
-
- /*
- * For now we create a new cache per instance of XMLValidatingParser, which means a
- * new cache per test run. These schemas could be cached for a longer period than
- * that, but then the question because "how long?" Until the web app shuts down? Try
- * to obey the caching headers in the HTTP responses?
- *
- * This solution at least fixes the major performance issue.
- */
- private final CachingSchemaLoader schemaLoader = new CachingSchemaLoader(new XsdSchemaLoader());
-
- private static final Logger jlogger = Logger.getLogger("com.occamlab.te.parsers.XMLValidatingParser");
-
- private List loadSchemaList(Document schemaLinks, String schemaType) throws Exception {
- NodeList nodes = schemaLinks.getElementsByTagNameNS("http://www.occamlab.com/te/parsers", schemaType);
- if (nodes.getLength() == 0) {
- return Collections.emptyList();
- }
- final ArrayList schemas = new ArrayList<>();
- for (int i = 0; i < nodes.getLength(); i++) {
- Element e = (Element) nodes.item(i);
- Object schema = null;
- String type = e.getAttribute("type");
- // URL, File, or Resource
- if (type.equals("url")) {
- schema = new URL(e.getTextContent());
- }
- else if (type.equals("file")) {
- schema = new File(e.getTextContent());
- }
- else if (type.equals("resource")) {
- ClassLoader cl = getClass().getClassLoader();
- String resource = e.getTextContent();
- URL url = cl.getResource(resource);
- if (url == null) {
- String msg = "Can't find schema resource on classpath at " + resource;
- jlogger.warning(msg);
- throw new Exception(msg);
- }
- schema = url;
- }
- else {
- throw new Exception("Unknown schema resource type " + type);
- }
- jlogger.finer("Adding schema reference " + schema.toString());
- schemas.add(schema);
- }
- return schemas;
- }
-
- private void loadSchemaLists(Node schemaLinks, ArrayList schemas, ArrayList dtds)
- throws Exception {
- if (null == schemaLinks) {
- return;
- }
- jlogger.finer("Received schemaLinks\n" + DomUtils.serializeNode(schemaLinks));
- Document configDoc;
- if (schemaLinks instanceof Document) {
- configDoc = (Document) schemaLinks;
- }
- else {
- configDoc = schemaLinks.getOwnerDocument();
- }
-
- final ArrayList schemaSuppliers = new ArrayList<>();
- for (final Object schemaObj : loadSchemaList(configDoc, "schema")) {
- schemaSuppliers.add(SchemaSupplier.makeSupplier(schemaObj));
- }
- schemas.addAll(schemaSuppliers);
- dtds.addAll(loadSchemaList(configDoc, "dtd"));
-
- // If instruction body is an embedded xsd:schema, add it to the
- // ArrayList
- NodeList nodes = configDoc.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "schema");
- for (int i = 0; i < nodes.getLength(); i++) {
- Element e = (Element) nodes.item(i);
- CharArrayWriter caw = new CharArrayWriter();
- Transformer t = TF.newTransformer();
- t.transform(new DOMSource(e), new StreamResult(caw));
- schemas.add(new InMemorySchemaSupplier(caw.toCharArray()));
- }
- }
-
- public XMLValidatingParser() {
-
- if (nonValidatingDBF == null) {
- String property_name = "javax.xml.parsers.DocumentBuilderFactory";
- String oldprop = System.getProperty(property_name);
- System.setProperty(property_name, "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
- nonValidatingDBF = DocumentBuilderFactory.newInstance();
- // Fortify Mod: Disable entity expansion to foil External Entity Injections
- nonValidatingDBF.setExpandEntityReferences(false);
- nonValidatingDBF.setNamespaceAware(true);
- schemaValidatingDBF = DocumentBuilderFactory.newInstance();
- schemaValidatingDBF.setNamespaceAware(true);
- schemaValidatingDBF.setValidating(true);
- schemaValidatingDBF.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
- "http://www.w3.org/2001/XMLSchema");
- dtdValidatingDBF = DocumentBuilderFactory.newInstance();
- dtdValidatingDBF.setNamespaceAware(true);
- dtdValidatingDBF.setValidating(true);
- // Fortify Mod: Disable entity expansion to foil External Entity Injections
- dtdValidatingDBF.setExpandEntityReferences(false);
- if (oldprop == null) {
- System.clearProperty(property_name);
- }
- else {
- System.setProperty(property_name, oldprop);
- }
- }
-
- if (TF == null) {
- // Fortify Mod: prevent external entity injection
- // includes try block to capture exceptions to setFeature.
- TF = TransformerFactory.newInstance();
- try {
- TF.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- }
- catch (Exception e) {
- jlogger.warning("Failed to secure Transformer");
- }
- }
- }
-
- public XMLValidatingParser(Document schema_links) throws Exception {
- this();
- if (null != schema_links) {
- loadSchemaLists(schema_links, this.schemaList, this.dtdList);
- }
- }
-
- /**
- * Attempts to parse a resource read using the given connection to a URL.
- * @param uc A connection for reading from some URL.
- * @param instruction An Element node (ctlp:XMLValidatingParser) containing
- * instructions, usually schema references.
- * @param logger A log writer.
- * @return A Document, or null if the resource could not be parsed.
- * @throws SSLProtocolException
- */
- public Document parse(URLConnection uc, Element instruction, PrintWriter logger) throws SSLProtocolException {
- if (null == uc) {
- throw new NullPointerException("Unable to parse resource: URLConnection is null.");
- }
- jlogger.fine("Received URLConnection object for " + uc.getURL());
- Document doc = null;
- try (InputStream inStream = URLConnectionUtils.getInputStream(uc)) {
- doc = parse(inStream, instruction, logger);
- }
- catch (SSLProtocolException sslep) {
- throw new SSLProtocolException(
- "[SSL ERROR] Failed to connect with the requested URL due to \"Invalid server_name\" found!! :"
- + uc.getURL() + ":" + sslep.getClass() + " : " + sslep.getMessage());
- }
- catch (Exception e) {
- throw new RuntimeException(String.format("Failed to parse resource from %s", uc.getURL()), e);
- }
- return doc;
- }
-
- /**
- * Parses and validates an XML resource using the given schema references.
- * @param input The XML input to parse and validate. It must be either an InputStream
- * or a Document object.
- * @param parserConfig An Element
- * ({http://www.occamlab.com/te/parsers}XMLValidatingParser) containing configuration
- * info. If it is {@code null} or empty validation will be performed by using location
- * hints in the input document.
- * @param logger The PrintWriter to log all results to
- * @return {@code null} If any non-ignorable errors or warnings occurred; otherwise
- * the resulting Document.
- *
- */
- Document parse(Object input, Element parserConfig, PrintWriter logger) throws Exception {
- jlogger.finer("Received XML resource of type " + input.getClass().getName());
- Document resultDoc = null;
- ErrorHandlerImpl errHandler = new ErrorHandlerImpl("Parsing", logger);
-
- if (input instanceof InputStream) {
- DocumentBuilderFactory dbf = nonValidatingDBF;
- DocumentBuilder db = dbf.newDocumentBuilder();
- db.setErrorHandler(errHandler);
- try (InputStream xmlInput = (InputStream) input) {
- resultDoc = db.parse(xmlInput);
- }
- catch (Exception e) {
- jlogger.log(Level.INFO, "Error parsing InputStream", e);
- }
- }
- else if (input instanceof Document) {
- resultDoc = (Document) input;
- }
- else {
- throw new IllegalArgumentException("XML input must be an InputStream or a Document object.");
- }
- if (null == resultDoc) {
- throw new RuntimeException("Failed to parse input: " + input.getClass().getName());
- }
- errHandler.setRole("Validation");
- validate(resultDoc, parserConfig, errHandler);
- int error_count = errHandler.getErrorCount();
- int warning_count = errHandler.getWarningCount();
- if (error_count > 0 || warning_count > 0) {
- String msg = "";
- if (error_count > 0) {
- msg += error_count + " validation error" + (error_count == 1 ? "" : "s");
- if (warning_count > 0)
- msg += " and ";
- }
- if (warning_count > 0) {
- msg += warning_count + " warning" + (warning_count == 1 ? "" : "s");
- }
- msg += " detected.";
- logger.println(msg);
- }
-
- if (error_count > 0) {
- String s = (null != parserConfig) ? parserConfig.getAttribute("ignoreErrors") : "false";
- if (s.length() == 0 || !Boolean.parseBoolean(s)) {
- resultDoc = null;
- }
- }
-
- if (warning_count > 0) {
- String s = (null != parserConfig) ? parserConfig.getAttribute("ignoreWarnings") : "true";
- if (s.length() > 0 && !Boolean.parseBoolean(s)) {
- resultDoc = null;
- }
- }
- return resultDoc;
- }
-
- /**
- * A method to validate a pool of schemas outside of the request element.
- * @param doc doc The file document to validate
- * @param instruction instruction The xml encapsulated schema information (file
- * locations)
- * @return false if there were errors, true if none.
- *
- */
- public boolean checkXMLRules(Document doc, Document instruction) throws Exception {
-
- if (doc == null || doc.getDocumentElement() == null)
- return false;
- Element e = instruction.getDocumentElement();
- PrintWriter logger = new PrintWriter(System.out);
- Document parsedDoc = parse(doc, e, logger);
- return (parsedDoc != null);
- }
-
- /**
- * Validates the given document against the schema references supplied in the
- * accompanying instruction document.
- * @param doc The document to be validated.
- * @param instruction A document containing schema references; may be null, in which
- * case embedded schema references will be used instead.
- * @return A list of Element nodes ({@code }) containing error messages.
- * @throws Exception If any error occurs.
- */
- public NodeList validate(Document doc, Document instruction) throws Exception {
- return schemaValidation(doc, instruction).toNodeList();
- }
-
- public Element validateSingleResult(Document doc, Document instruction) throws Exception {
- return schemaValidation(doc, instruction).toRootElement();
- }
-
- XmlErrorHandler schemaValidation(Document doc, Document instruction) throws Exception {
- if (doc == null || doc.getDocumentElement() == null) {
- throw new NullPointerException("Input document is null.");
- }
- XmlErrorHandler errHandler = new XmlErrorHandler();
- validate(doc, instruction, errHandler);
- return errHandler;
- }
-
- /**
- * Validates the given XML {@link Document} per the given instructions, recording
- * errors in the given error handler.
- * @param doc must not be null
- * @param instruction may be null to signify no special instructions
- * @param errHandler errors will be recorded on this object
- */
- private void validate(final Document doc, final Node instruction, final ErrorHandler errHandler) throws Exception {
- ArrayList schemas = new ArrayList<>(schemaList);
- ArrayList dtds = new ArrayList<>(dtdList);
- loadSchemaLists(instruction, schemas, dtds);
- if (null == doc.getDoctype() && dtds.isEmpty()) {
- validateAgainstXMLSchemaList(doc, schemas, errHandler);
- }
- else {
- validateAgainstDTDList(doc, dtds, errHandler);
- }
- }
-
- /**
- * Validates an XML resource against a list of XML Schemas. Validation errors are
- * reported to the given handler.
- * @param doc The input Document node.
- * @param xsdList A list of XML schema references. Must be non-null, but if empty,
- * validation will be performed by using location hints found in the input document.
- * @param errHandler An ErrorHandler that collects validation errors.
- * @throws SAXException If a schema cannot be read for some reason.
- * @throws IOException If an I/O error occurs.
- */
- void validateAgainstXMLSchemaList(Document doc, List xsdList, ErrorHandler errHandler)
- throws SAXException, IOException {
- jlogger
- .fine("Validating XML resource from " + doc.getDocumentURI() + " with these specified schemas: " + xsdList);
- Schema schema;
- if (!xsdList.isEmpty()) {
- schema = schemaLoader.loadSchema(ImmutableList.copyOf(xsdList));
- }
- else {
- schema = schemaLoader.defaultSchema();
- }
- Validator validator = schema.newValidator();
- validator.setErrorHandler(errHandler);
- DOMSource source = new DOMSource(doc, doc.getBaseURI());
- validator.validate(source);
- }
-
- /**
- * Validates an XML resource against a list of DTD schemas or as indicated by a
- * DOCTYPE declaration. Validation errors are reported to the given handler. If no DTD
- * references are provided the external schema reference in the DOCTYPE declaration is
- * used (Note: an internal subset is ignored).
- * @param doc The input Document.
- * @param dtdList A list of DTD schema references. May be empty but not null.
- * @param errHandler An ErrorHandler that collects validation errors.
- * @throws Exception If any errors occur while attempting to validate the document.
- */
- private void validateAgainstDTDList(Document doc, ArrayList dtdList, ErrorHandler errHandler)
- throws Exception {
- jlogger.finer("Validating XML resource from " + doc.getDocumentURI());
- DocumentBuilder db = dtdValidatingDBF.newDocumentBuilder();
- db.setErrorHandler(errHandler);
- // Fortify Mod: prevent external entity injection
- // includes try block to capture exceptions to setFeature.
- TransformerFactory tf = TransformerFactory.newInstance();
- try {
- tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- }
- catch (Exception e) {
- jlogger.warning("Failed to secure Transformer");
- }
- // End Fortify Mod
- Transformer copier = tf.newTransformer();
- ByteArrayOutputStream content = new ByteArrayOutputStream();
- Result copy = new StreamResult(content);
- if (dtdList.isEmpty()) {
- DocumentType doctype = doc.getDoctype();
- if (null == doctype) {
- return;
- }
- URI systemId = URI.create(doctype.getSystemId());
- if (!systemId.isAbsolute() && null != doc.getBaseURI()) {
- systemId = URI.create(doc.getBaseURI()).resolve(systemId);
- }
- copier.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, systemId.toString());
- copier.transform(new DOMSource(doc), copy);
- db.parse(new ByteArrayInputStream(content.toByteArray()));
- }
- else {
- for (Object dtdRef : dtdList) {
- content.reset();
- copier.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dtdRef.toString());
- copier.transform(new DOMSource(doc), copy);
- db.parse(new ByteArrayInputStream(content.toByteArray()));
- }
- }
- }
-
-}
+/**
+ * **************************************************************************
+ *
+ * Contributor(s):
+ * C. Heazel (WiSC): Added Fortify adjudication changes
+ *
+ ***************************************************************************
+ */
+package com.occamlab.te.parsers;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.CharArrayWriter;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.net.URI;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.net.ssl.SSLProtocolException;
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Result;
+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.validation.Schema;
+import javax.xml.validation.Validator;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentType;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.SAXException;
+
+import com.google.common.collect.ImmutableList;
+import com.occamlab.te.ErrorHandlerImpl;
+import com.occamlab.te.parsers.xml.CachingSchemaLoader;
+import com.occamlab.te.parsers.xml.InMemorySchemaSupplier;
+import com.occamlab.te.parsers.xml.XsdSchemaLoader;
+import com.occamlab.te.parsers.xml.SchemaSupplier;
+import com.occamlab.te.util.DomUtils;
+import com.occamlab.te.util.URLConnectionUtils;
+
+/**
+ * Validates an XML resource against a set of W3C XML Schema or DTD schemas.
+ *
+ */
+public class XMLValidatingParser {
+
+ static TransformerFactory TF = null;
+ static DocumentBuilderFactory nonValidatingDBF = null;
+ static DocumentBuilderFactory schemaValidatingDBF = null;
+ static DocumentBuilderFactory dtdValidatingDBF = null;
+
+ ArrayList schemaList = new ArrayList<>();
+
+ ArrayList dtdList = new ArrayList<>();
+
+ /*
+ * For now we create a new cache per instance of XMLValidatingParser, which means a
+ * new cache per test run. These schemas could be cached for a longer period than
+ * that, but then the question because "how long?" Until the web app shuts down? Try
+ * to obey the caching headers in the HTTP responses?
+ *
+ * This solution at least fixes the major performance issue.
+ */
+ private final CachingSchemaLoader schemaLoader = new CachingSchemaLoader(new XsdSchemaLoader());
+
+ private static final Logger jlogger = Logger.getLogger("com.occamlab.te.parsers.XMLValidatingParser");
+
+ private List loadSchemaList(Document schemaLinks, String schemaType) throws Exception {
+ NodeList nodes = schemaLinks.getElementsByTagNameNS("http://www.occamlab.com/te/parsers", schemaType);
+ if (nodes.getLength() == 0) {
+ return Collections.emptyList();
+ }
+ final ArrayList schemas = new ArrayList<>();
+ for (int i = 0; i < nodes.getLength(); i++) {
+ Element e = (Element) nodes.item(i);
+ Object schema = null;
+ String type = e.getAttribute("type");
+ // URL, File, or Resource
+ if (type.equals("url")) {
+ schema = new URL(e.getTextContent());
+ }
+ else if (type.equals("file")) {
+ schema = new File(e.getTextContent());
+ }
+ else if (type.equals("resource")) {
+ ClassLoader cl = getClass().getClassLoader();
+ String resource = e.getTextContent();
+ URL url = cl.getResource(resource);
+ if (url == null) {
+ String msg = "Can't find schema resource on classpath at " + resource;
+ jlogger.warning(msg);
+ throw new Exception(msg);
+ }
+ schema = url;
+ }
+ else {
+ throw new Exception("Unknown schema resource type " + type);
+ }
+ jlogger.finer("Adding schema reference " + schema.toString());
+ schemas.add(schema);
+ }
+ return schemas;
+ }
+
+ private void loadSchemaLists(Node schemaLinks, ArrayList schemas, ArrayList dtds)
+ throws Exception {
+ if (null == schemaLinks) {
+ return;
+ }
+ jlogger.finer("Received schemaLinks\n" + DomUtils.serializeNode(schemaLinks));
+ Document configDoc;
+ if (schemaLinks instanceof Document) {
+ configDoc = (Document) schemaLinks;
+ }
+ else {
+ configDoc = schemaLinks.getOwnerDocument();
+ }
+
+ final ArrayList schemaSuppliers = new ArrayList<>();
+ for (final Object schemaObj : loadSchemaList(configDoc, "schema")) {
+ schemaSuppliers.add(SchemaSupplier.makeSupplier(schemaObj));
+ }
+ schemas.addAll(schemaSuppliers);
+ dtds.addAll(loadSchemaList(configDoc, "dtd"));
+
+ // If instruction body is an embedded xsd:schema, add it to the
+ // ArrayList
+ NodeList nodes = configDoc.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "schema");
+ for (int i = 0; i < nodes.getLength(); i++) {
+ Element e = (Element) nodes.item(i);
+ CharArrayWriter caw = new CharArrayWriter();
+ Transformer t = TF.newTransformer();
+ t.transform(new DOMSource(e), new StreamResult(caw));
+ schemas.add(new InMemorySchemaSupplier(caw.toCharArray()));
+ }
+ }
+
+ public XMLValidatingParser() {
+
+ if (nonValidatingDBF == null) {
+ String property_name = "javax.xml.parsers.DocumentBuilderFactory";
+ String oldprop = System.getProperty(property_name);
+ System.setProperty(property_name, "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
+ nonValidatingDBF = DocumentBuilderFactory.newInstance();
+ // Fortify Mod: Disable entity expansion to foil External Entity Injections
+ nonValidatingDBF.setExpandEntityReferences(false);
+ nonValidatingDBF.setNamespaceAware(true);
+ schemaValidatingDBF = DocumentBuilderFactory.newInstance();
+ schemaValidatingDBF.setNamespaceAware(true);
+ schemaValidatingDBF.setValidating(true);
+ schemaValidatingDBF.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
+ "http://www.w3.org/2001/XMLSchema");
+ dtdValidatingDBF = DocumentBuilderFactory.newInstance();
+ dtdValidatingDBF.setNamespaceAware(true);
+ dtdValidatingDBF.setValidating(true);
+ // Fortify Mod: Disable entity expansion to foil External Entity Injections
+ dtdValidatingDBF.setExpandEntityReferences(false);
+ if (oldprop == null) {
+ System.clearProperty(property_name);
+ }
+ else {
+ System.setProperty(property_name, oldprop);
+ }
+ }
+
+ if (TF == null) {
+ // Fortify Mod: prevent external entity injection
+ // includes try block to capture exceptions to setFeature.
+ TF = TransformerFactory.newInstance();
+ try {
+ TF.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ }
+ catch (Exception e) {
+ jlogger.warning("Failed to secure Transformer");
+ }
+ }
+ }
+
+ public XMLValidatingParser(Document schema_links) throws Exception {
+ this();
+ if (null != schema_links) {
+ loadSchemaLists(schema_links, this.schemaList, this.dtdList);
+ }
+ }
+
+ /**
+ * Attempts to parse a resource read using the given connection to a URL.
+ * @param uc A connection for reading from some URL.
+ * @param instruction An Element node (ctlp:XMLValidatingParser) containing
+ * instructions, usually schema references.
+ * @param logger A log writer.
+ * @return A Document, or null if the resource could not be parsed.
+ * @throws SSLProtocolException
+ */
+ public Document parse(URLConnection uc, Element instruction, PrintWriter logger) throws SSLProtocolException {
+ if (null == uc) {
+ throw new NullPointerException("Unable to parse resource: URLConnection is null.");
+ }
+ jlogger.fine("Received URLConnection object for " + uc.getURL());
+ Document doc = null;
+ try (InputStream inStream = URLConnectionUtils.getInputStream(uc)) {
+ doc = parse(inStream, instruction, logger);
+ }
+ catch (SSLProtocolException sslep) {
+ throw new SSLProtocolException(
+ "[SSL ERROR] Failed to connect with the requested URL due to \"Invalid server_name\" found!! :"
+ + uc.getURL() + ":" + sslep.getClass() + " : " + sslep.getMessage());
+ }
+ catch (Exception e) {
+ throw new RuntimeException(String.format("Failed to parse resource from %s", uc.getURL()), e);
+ }
+ return doc;
+ }
+
+ /**
+ * Parses and validates an XML resource using the given schema references.
+ * @param input The XML input to parse and validate. It must be either an InputStream
+ * or a Document object.
+ * @param parserConfig An Element
+ * ({http://www.occamlab.com/te/parsers}XMLValidatingParser) containing configuration
+ * info. If it is {@code null} or empty validation will be performed by using location
+ * hints in the input document.
+ * @param logger The PrintWriter to log all results to
+ * @return {@code null} If any non-ignorable errors or warnings occurred; otherwise
+ * the resulting Document.
+ *
+ */
+ Document parse(Object input, Element parserConfig, PrintWriter logger) throws Exception {
+ jlogger.finer("Received XML resource of type " + input.getClass().getName());
+ Document resultDoc = null;
+ ErrorHandlerImpl errHandler = new ErrorHandlerImpl("Parsing", logger);
+
+ if (input instanceof InputStream) {
+ DocumentBuilderFactory dbf = nonValidatingDBF;
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ db.setErrorHandler(errHandler);
+ try (InputStream xmlInput = (InputStream) input) {
+ resultDoc = db.parse(xmlInput);
+ }
+ catch (Exception e) {
+ jlogger.log(Level.INFO, "Error parsing InputStream", e);
+ }
+ }
+ else if (input instanceof Document) {
+ resultDoc = (Document) input;
+ }
+ else {
+ throw new IllegalArgumentException("XML input must be an InputStream or a Document object.");
+ }
+ if (null == resultDoc) {
+ throw new RuntimeException("Failed to parse input: " + input.getClass().getName());
+ }
+ errHandler.setRole("Validation");
+ validate(resultDoc, parserConfig, errHandler);
+ int error_count = errHandler.getErrorCount();
+ int warning_count = errHandler.getWarningCount();
+ if (error_count > 0 || warning_count > 0) {
+ String msg = "";
+ if (error_count > 0) {
+ msg += error_count + " validation error" + (error_count == 1 ? "" : "s");
+ if (warning_count > 0)
+ msg += " and ";
+ }
+ if (warning_count > 0) {
+ msg += warning_count + " warning" + (warning_count == 1 ? "" : "s");
+ }
+ msg += " detected.";
+ logger.println(msg);
+ }
+
+ if (error_count > 0) {
+ String s = (null != parserConfig) ? parserConfig.getAttribute("ignoreErrors") : "false";
+ if (s.length() == 0 || !Boolean.parseBoolean(s)) {
+ resultDoc = null;
+ }
+ }
+
+ if (warning_count > 0) {
+ String s = (null != parserConfig) ? parserConfig.getAttribute("ignoreWarnings") : "true";
+ if (s.length() > 0 && !Boolean.parseBoolean(s)) {
+ resultDoc = null;
+ }
+ }
+ return resultDoc;
+ }
+
+ /**
+ * A method to validate a pool of schemas outside of the request element.
+ * @param doc doc The file document to validate
+ * @param instruction instruction The xml encapsulated schema information (file
+ * locations)
+ * @return false if there were errors, true if none.
+ *
+ */
+ public boolean checkXMLRules(Document doc, Document instruction) throws Exception {
+
+ if (doc == null || doc.getDocumentElement() == null)
+ return false;
+ Element e = instruction.getDocumentElement();
+ PrintWriter logger = new PrintWriter(System.out);
+ Document parsedDoc = parse(doc, e, logger);
+ return (parsedDoc != null);
+ }
+
+ /**
+ * Validates the given document against the schema references supplied in the
+ * accompanying instruction document.
+ * @param doc The document to be validated.
+ * @param instruction A document containing schema references; may be null, in which
+ * case embedded schema references will be used instead.
+ * @return A list of Element nodes ({@code }) containing error messages.
+ * @throws Exception If any error occurs.
+ */
+ public NodeList validate(Document doc, Document instruction) throws Exception {
+ return schemaValidation(doc, instruction).toNodeList();
+ }
+
+ public Element validateSingleResult(Document doc, Document instruction) throws Exception {
+ return schemaValidation(doc, instruction).toRootElement();
+ }
+
+ XmlErrorHandler schemaValidation(Document doc, Document instruction) throws Exception {
+ if (doc == null || doc.getDocumentElement() == null) {
+ throw new NullPointerException("Input document is null.");
+ }
+ XmlErrorHandler errHandler = new XmlErrorHandler();
+ validate(doc, instruction, errHandler);
+ return errHandler;
+ }
+
+ /**
+ * Validates the given XML {@link Document} per the given instructions, recording
+ * errors in the given error handler.
+ * @param doc must not be null
+ * @param instruction may be null to signify no special instructions
+ * @param errHandler errors will be recorded on this object
+ */
+ private void validate(final Document doc, final Node instruction, final ErrorHandler errHandler) throws Exception {
+ ArrayList schemas = new ArrayList<>(schemaList);
+ ArrayList dtds = new ArrayList<>(dtdList);
+ loadSchemaLists(instruction, schemas, dtds);
+ if (null == doc.getDoctype() && dtds.isEmpty()) {
+ validateAgainstXMLSchemaList(doc, schemas, errHandler);
+ }
+ else {
+ validateAgainstDTDList(doc, dtds, errHandler);
+ }
+ }
+
+ /**
+ * Validates an XML resource against a list of XML Schemas. Validation errors are
+ * reported to the given handler.
+ * @param doc The input Document node.
+ * @param xsdList A list of XML schema references. Must be non-null, but if empty,
+ * validation will be performed by using location hints found in the input document.
+ * @param errHandler An ErrorHandler that collects validation errors.
+ * @throws SAXException If a schema cannot be read for some reason.
+ * @throws IOException If an I/O error occurs.
+ */
+ void validateAgainstXMLSchemaList(Document doc, List xsdList, ErrorHandler errHandler)
+ throws SAXException, IOException {
+ jlogger
+ .fine("Validating XML resource from " + doc.getDocumentURI() + " with these specified schemas: " + xsdList);
+ Schema schema;
+ if (!xsdList.isEmpty()) {
+ schema = schemaLoader.loadSchema(ImmutableList.copyOf(xsdList));
+ }
+ else {
+ schema = schemaLoader.defaultSchema();
+ }
+ Validator validator = schema.newValidator();
+ validator.setErrorHandler(errHandler);
+ DOMSource source = new DOMSource(doc, doc.getBaseURI());
+ validator.validate(source);
+ }
+
+ /**
+ * Validates an XML resource against a list of DTD schemas or as indicated by a
+ * DOCTYPE declaration. Validation errors are reported to the given handler. If no DTD
+ * references are provided the external schema reference in the DOCTYPE declaration is
+ * used (Note: an internal subset is ignored).
+ * @param doc The input Document.
+ * @param dtdList A list of DTD schema references. May be empty but not null.
+ * @param errHandler An ErrorHandler that collects validation errors.
+ * @throws Exception If any errors occur while attempting to validate the document.
+ */
+ private void validateAgainstDTDList(Document doc, ArrayList dtdList, ErrorHandler errHandler)
+ throws Exception {
+ jlogger.finer("Validating XML resource from " + doc.getDocumentURI());
+ DocumentBuilder db = dtdValidatingDBF.newDocumentBuilder();
+ db.setErrorHandler(errHandler);
+ // Fortify Mod: prevent external entity injection
+ // includes try block to capture exceptions to setFeature.
+ TransformerFactory tf = TransformerFactory.newInstance();
+ try {
+ tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ }
+ catch (Exception e) {
+ jlogger.warning("Failed to secure Transformer");
+ }
+ // End Fortify Mod
+ Transformer copier = tf.newTransformer();
+ ByteArrayOutputStream content = new ByteArrayOutputStream();
+ Result copy = new StreamResult(content);
+ if (dtdList.isEmpty()) {
+ DocumentType doctype = doc.getDoctype();
+ if (null == doctype) {
+ return;
+ }
+ URI systemId = URI.create(doctype.getSystemId());
+ if (!systemId.isAbsolute() && null != doc.getBaseURI()) {
+ systemId = URI.create(doc.getBaseURI()).resolve(systemId);
+ }
+ copier.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, systemId.toString());
+ copier.transform(new DOMSource(doc), copy);
+ db.parse(new ByteArrayInputStream(content.toByteArray()));
+ }
+ else {
+ for (Object dtdRef : dtdList) {
+ content.reset();
+ copier.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dtdRef.toString());
+ copier.transform(new DOMSource(doc), copy);
+ db.parse(new ByteArrayInputStream(content.toByteArray()));
+ }
+ }
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/parsers/XSLTransformationErrorHandler.java b/teamengine-core/src/main/java/com/occamlab/te/parsers/XSLTransformationErrorHandler.java
index eb3d5ccc0..7f98cc0c7 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/parsers/XSLTransformationErrorHandler.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/parsers/XSLTransformationErrorHandler.java
@@ -1,55 +1,75 @@
-package com.occamlab.te.parsers;
-
-import java.io.PrintWriter;
-
-import javax.xml.transform.ErrorListener;
-import javax.xml.transform.TransformerException;
-
-public class XSLTransformationErrorHandler implements ErrorListener {
-
- PrintWriter logger;
-
- boolean ignoreErrors;
-
- boolean ignoreWarnings;
-
- int errorCount;
-
- int warningCount;
-
- public XSLTransformationErrorHandler(PrintWriter logger, boolean ignoreErrors, boolean ignoreWarnings) {
- this.logger = logger;
- this.ignoreErrors = ignoreErrors;
- this.ignoreWarnings = ignoreWarnings;
- }
-
- @Override
- public void error(TransformerException e) throws TransformerException {
- if (!ignoreErrors) {
- logger.println("Error: " + e.getMessageAndLocation());
- }
- errorCount++;
- }
-
- @Override
- public void fatalError(TransformerException e) throws TransformerException {
- logger.println("Fatal Error: " + e.getMessageAndLocation());
- }
-
- @Override
- public void warning(TransformerException e) throws TransformerException {
- if (!ignoreWarnings) {
- logger.println("Warning: " + e.getMessageAndLocation());
- }
- warningCount++;
- }
-
- public int getErrorCount() {
- return errorCount;
- }
-
- public int getWarningCount() {
- return warningCount;
- }
-
-}
+package com.occamlab.te.parsers;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.PrintWriter;
+
+import javax.xml.transform.ErrorListener;
+import javax.xml.transform.TransformerException;
+
+public class XSLTransformationErrorHandler implements ErrorListener {
+
+ PrintWriter logger;
+
+ boolean ignoreErrors;
+
+ boolean ignoreWarnings;
+
+ int errorCount;
+
+ int warningCount;
+
+ public XSLTransformationErrorHandler(PrintWriter logger, boolean ignoreErrors, boolean ignoreWarnings) {
+ this.logger = logger;
+ this.ignoreErrors = ignoreErrors;
+ this.ignoreWarnings = ignoreWarnings;
+ }
+
+ @Override
+ public void error(TransformerException e) throws TransformerException {
+ if (!ignoreErrors) {
+ logger.println("Error: " + e.getMessageAndLocation());
+ }
+ errorCount++;
+ }
+
+ @Override
+ public void fatalError(TransformerException e) throws TransformerException {
+ logger.println("Fatal Error: " + e.getMessageAndLocation());
+ }
+
+ @Override
+ public void warning(TransformerException e) throws TransformerException {
+ if (!ignoreWarnings) {
+ logger.println("Warning: " + e.getMessageAndLocation());
+ }
+ warningCount++;
+ }
+
+ public int getErrorCount() {
+ return errorCount;
+ }
+
+ public int getWarningCount() {
+ return warningCount;
+ }
+
+}
diff --git a/teamengine-core/src/main/java/com/occamlab/te/parsers/XSLTransformationParser.java b/teamengine-core/src/main/java/com/occamlab/te/parsers/XSLTransformationParser.java
index bfbb23e85..3d1a985be 100644
--- a/teamengine-core/src/main/java/com/occamlab/te/parsers/XSLTransformationParser.java
+++ b/teamengine-core/src/main/java/com/occamlab/te/parsers/XSLTransformationParser.java
@@ -1,180 +1,200 @@
-package com.occamlab.te.parsers;
-
-import java.io.InputStream;
-import java.io.PrintWriter;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.transform.Source;
-import javax.xml.transform.Templates;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMResult;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamSource;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import com.occamlab.te.Test;
-import com.occamlab.te.util.DomUtils;
-import com.occamlab.te.util.URLConnectionUtils;
-
-import static java.lang.Boolean.FALSE;
-import static java.lang.Boolean.TRUE;
-
-public class XSLTransformationParser {
-
- private static final Logger LOGR = Logger.getLogger(XSLTransformationParser.class.getName());
-
- DocumentBuilder db = null;
-
- TransformerFactory tf = null;
-
- Templates defaultTemplates = null;
-
- HashMap defaultProperties = null;
-
- HashMap defaultParams = null;
-
- Boolean defaultIgnoreErrors;
-
- Boolean defaultIgnoreWarnings;
-
- public XSLTransformationParser() throws Exception {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setNamespaceAware(true);
- db = dbf.newDocumentBuilder();
- tf = TransformerFactory.newInstance();
- defaultProperties = new HashMap<>();
- defaultParams = new HashMap<>();
- defaultIgnoreErrors = FALSE;
- defaultIgnoreWarnings = TRUE;
- }
-
- public XSLTransformationParser(Node node) throws Exception {
- super();
- defaultTemplates = parseInstruction(DomUtils.getElement(node), defaultProperties, defaultParams,
- defaultIgnoreErrors, defaultIgnoreWarnings);
- }
-
- public XSLTransformationParser(String reftype, String ref) throws Exception {
- super();
- defaultTemplates = tf.newTemplates(getSource(reftype, ref));
- }
-
- private Source getSource(String reftype, String ref) throws Exception {
- if (reftype.equals("url")) {
- URL url = new URL(ref);
- return new StreamSource(url.openStream());
- }
- else if (reftype.equals("file")) {
- return new StreamSource(ref);
- }
- else if (reftype.equals("resource")) {
- ClassLoader cl = getClass().getClassLoader();
- return new StreamSource(cl.getResourceAsStream(ref));
- }
- return null;
- }
-
- private Templates parseInstruction(Element instruction, HashMap properties,
- HashMap params, Boolean ignoreErrors, Boolean ignoreWarnings) throws Exception {
- Templates templates = null;
- final String[] atts = { "url", "file", "resource" };
- for (String att : atts) {
- String val = instruction.getAttribute(att);
- if (val.length() > 0) {
- templates = tf.newTemplates(getSource(att, val));
- break;
- }
- }
- Element stylesheet = DomUtils.getElementByTagNameNS(instruction, Test.XSL_NS, "stylesheet");
- if (stylesheet == null) {
- stylesheet = DomUtils.getElementByTagNameNS(instruction, Test.XSL_NS, "transform");
- }
- if (stylesheet != null) {
- templates = tf.newTemplates(new DOMSource(stylesheet));
- }
- List children = DomUtils.getChildElements(instruction);
- for (Element e : children) {
- if (e.getLocalName().equals("property") && e.getNamespaceURI().equals(Test.CTLP_NS)) {
- properties.put(e.getAttribute("name"), e.getTextContent());
- }
- if (e.getLocalName().equals("with-param") && e.getNamespaceURI().equals(Test.CTLP_NS)) {
- params.put(e.getAttribute("name"), e.getTextContent());
- }
- }
- String ignoreErrorsAtt = instruction.getAttribute("ignoreErrors");
- if (ignoreErrorsAtt != null) {
- ignoreErrors = Boolean.parseBoolean(ignoreErrorsAtt);
- }
- String ignoreWarningsAtt = instruction.getAttribute("ignoreWarnings");
- if (ignoreWarningsAtt != null) {
- ignoreWarnings = Boolean.parseBoolean(ignoreWarningsAtt);
- }
- return templates;
- }
-
- public Document parse(URLConnection uc, Element instruction, PrintWriter logger) throws Exception {
- HashMap properties = new HashMap<>(defaultProperties);
- HashMap params = new HashMap<>(defaultParams);
- Boolean ignoreErrors = defaultIgnoreErrors;
- Boolean ignoreWarnings = defaultIgnoreWarnings;
- Templates templates = parseInstruction(instruction, properties, params, ignoreErrors, ignoreWarnings);
- Transformer t = null;
- if (templates != null) {
- t = templates.newTransformer();
- }
- else if (defaultTemplates != null) {
- t = defaultTemplates.newTransformer();
- }
- else {
- t = tf.newTransformer();
- }
- for (Entry prop : properties.entrySet()) {
- t.setOutputProperty(prop.getKey(), prop.getValue());
- }
- for (Entry param : params.entrySet()) {
- t.setParameter(param.getKey(), param.getValue());
- }
- XSLTransformationErrorHandler el = new XSLTransformationErrorHandler(logger, ignoreErrors, ignoreWarnings);
- t.setErrorListener(el);
- Document doc = db.newDocument();
- InputStream is = null;
- try {
- if (LOGR.isLoggable(Level.FINER)) {
- String msg = String.format("Attempting to transform source from %s using instruction set:%n %s",
- uc.getURL(), DomUtils.serializeNode(instruction));
- LOGR.finer(msg);
- }
- // may return error stream
- is = URLConnectionUtils.getInputStream(uc);
- t.transform(new StreamSource(is), new DOMResult(doc));
- }
- catch (TransformerException e) {
- el.error(e);
- }
- finally {
- if (null != is)
- is.close();
- }
- if (el.getErrorCount() > 0 && !ignoreErrors) {
- return null;
- }
- if (el.getWarningCount() > 0 && !ignoreWarnings) {
- return null;
- }
- return doc;
- }
-
-}
+package com.occamlab.te.parsers;
+
+/*-
+ * #%L
+ * TEAM Engine - Core Module
+ * %%
+ * Copyright (C) 2006 - 2024 Open Geospatial Consortium
+ * %%
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * #L%
+ */
+
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.Source;
+import javax.xml.transform.Templates;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMResult;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamSource;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+import com.occamlab.te.Test;
+import com.occamlab.te.util.DomUtils;
+import com.occamlab.te.util.URLConnectionUtils;
+
+import static java.lang.Boolean.FALSE;
+import static java.lang.Boolean.TRUE;
+
+public class XSLTransformationParser {
+
+ private static final Logger LOGR = Logger.getLogger(XSLTransformationParser.class.getName());
+
+ DocumentBuilder db = null;
+
+ TransformerFactory tf = null;
+
+ Templates defaultTemplates = null;
+
+ HashMap defaultProperties = null;
+
+ HashMap defaultParams = null;
+
+ Boolean defaultIgnoreErrors;
+
+ Boolean defaultIgnoreWarnings;
+
+ public XSLTransformationParser() throws Exception {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setNamespaceAware(true);
+ db = dbf.newDocumentBuilder();
+ tf = TransformerFactory.newInstance();
+ defaultProperties = new HashMap<>();
+ defaultParams = new HashMap<>();
+ defaultIgnoreErrors = FALSE;
+ defaultIgnoreWarnings = TRUE;
+ }
+
+ public XSLTransformationParser(Node node) throws Exception {
+ super();
+ defaultTemplates = parseInstruction(DomUtils.getElement(node), defaultProperties, defaultParams,
+ defaultIgnoreErrors, defaultIgnoreWarnings);
+ }
+
+ public XSLTransformationParser(String reftype, String ref) throws Exception {
+ super();
+ defaultTemplates = tf.newTemplates(getSource(reftype, ref));
+ }
+
+ private Source getSource(String reftype, String ref) throws Exception {
+ if (reftype.equals("url")) {
+ URL url = new URL(ref);
+ return new StreamSource(url.openStream());
+ }
+ else if (reftype.equals("file")) {
+ return new StreamSource(ref);
+ }
+ else if (reftype.equals("resource")) {
+ ClassLoader cl = getClass().getClassLoader();
+ return new StreamSource(cl.getResourceAsStream(ref));
+ }
+ return null;
+ }
+
+ private Templates parseInstruction(Element instruction, HashMap properties,
+ HashMap params, Boolean ignoreErrors, Boolean ignoreWarnings) throws Exception {
+ Templates templates = null;
+ final String[] atts = { "url", "file", "resource" };
+ for (String att : atts) {
+ String val = instruction.getAttribute(att);
+ if (val.length() > 0) {
+ templates = tf.newTemplates(getSource(att, val));
+ break;
+ }
+ }
+ Element stylesheet = DomUtils.getElementByTagNameNS(instruction, Test.XSL_NS, "stylesheet");
+ if (stylesheet == null) {
+ stylesheet = DomUtils.getElementByTagNameNS(instruction, Test.XSL_NS, "transform");
+ }
+ if (stylesheet != null) {
+ templates = tf.newTemplates(new DOMSource(stylesheet));
+ }
+ List children = DomUtils.getChildElements(instruction);
+ for (Element e : children) {
+ if (e.getLocalName().equals("property") && e.getNamespaceURI().equals(Test.CTLP_NS)) {
+ properties.put(e.getAttribute("name"), e.getTextContent());
+ }
+ if (e.getLocalName().equals("with-param") && e.getNamespaceURI().equals(Test.CTLP_NS)) {
+ params.put(e.getAttribute("name"), e.getTextContent());
+ }
+ }
+ String ignoreErrorsAtt = instruction.getAttribute("ignoreErrors");
+ if (ignoreErrorsAtt != null) {
+ ignoreErrors = Boolean.parseBoolean(ignoreErrorsAtt);
+ }
+ String ignoreWarningsAtt = instruction.getAttribute("ignoreWarnings");
+ if (ignoreWarningsAtt != null) {
+ ignoreWarnings = Boolean.parseBoolean(ignoreWarningsAtt);
+ }
+ return templates;
+ }
+
+ public Document parse(URLConnection uc, Element instruction, PrintWriter logger) throws Exception {
+ HashMap properties = new HashMap<>(defaultProperties);
+ HashMap