From 855788a1cb78dd6abf2167a29aa8fcd63c27c65a Mon Sep 17 00:00:00 2001 From: git Date: Wed, 8 Jan 2025 09:58:07 -0800 Subject: [PATCH 1/3] [Terry N.] more stringent check for a JDK installed --- build.xml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/build.xml b/build.xml index 4dd6ebf5..80836866 100644 --- a/build.xml +++ b/build.xml @@ -143,9 +143,15 @@ - + + + + + @@ -159,6 +165,7 @@ + From 89c6c77c59d5f3ad2875ac2f30912d3a50a326b0 Mon Sep 17 00:00:00 2001 From: git Date: Wed, 8 Jan 2025 12:33:51 -0800 Subject: [PATCH 2/3] [Terry N.] restore previous work from Git clash over the holiday period. --- .github/workflows/ant.yml | 4 +- INSTALL.MacOS | 4 +- build.xml | 46 +- config.xml | 2 +- docker/sigma-ci/Dockerfile | 4 +- docker/sigmakee/Dockerfile | 2 +- docker/sigmakee2023/Dockerfile | 2 +- docker/sumo-ci/Dockerfile | 2 +- nbproject/project.xml | 2 +- src/java/com/articulate/sigma/Formula.java | 76 +-- .../articulate/sigma/InferenceTestSuite.java | 16 +- src/java/com/articulate/sigma/KB.java | 2 +- .../com/articulate/sigma/KButilities.java | 509 +++++++++--------- src/java/com/articulate/sigma/KIF.java | 9 +- src/java/com/articulate/sigma/KIFAST.java | 261 +++++---- .../com/articulate/sigma/ProofProcessor.java | 4 +- .../sigma/KBmanagerInitIntegrationTest.java | 2 +- 17 files changed, 476 insertions(+), 471 deletions(-) diff --git a/.github/workflows/ant.yml b/.github/workflows/ant.yml index 12fdc203..7c2bb5ff 100644 --- a/.github/workflows/ant.yml +++ b/.github/workflows/ant.yml @@ -60,10 +60,10 @@ jobs: sed -i "s|/home/theuser/workspace/sumo|$ONTOLOGYPORTAL_GIT/sumo|g" $SIGMA_HOME/KBs/config.xml sed -i "s|/home/theuser/E/bin/e_ltb_runner|/usr/local/bin/e_ltb_runner|g" $SIGMA_HOME/KBs/config.xml - - name: Set up JDK 11 for x64 + - name: Set up JDK 21 for x64 uses: actions/setup-java@v4 with: - java-version: '11' + java-version: '21' distribution: 'temurin' - name: Build with Ant diff --git a/INSTALL.MacOS b/INSTALL.MacOS index a8454e3c..0076fa0a 100644 --- a/INSTALL.MacOS +++ b/INSTALL.MacOS @@ -49,7 +49,7 @@ these variables created before the next step, and replace Next, execute step-by-step the commands below (tested on MacOS 10.14.5 to Sonoma 14.5): -You will need at least Java 11+ (avoid JDK 17) to compile SigmaKEE and to run +You will need at least Java 21+ (avoid JDK 17) to compile SigmaKEE and to run Apache Tomcat. ! For ARM processors download it from here: https://jdk.java.net/archive/ @@ -66,7 +66,7 @@ Apache Tomcat. export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-23.jdk/Contents/Home export PATH=$JAVA_HOME/bin:$PATH -Install (ensure the above preparation have been performed) +Install (ensure the above preparations have been performed) > ant install *** Legacy install steps now taken care of by the above command "ant install" diff --git a/build.xml b/build.xml index 71e27468..e0a217d9 100644 --- a/build.xml +++ b/build.xml @@ -115,7 +115,7 @@ - + @@ -368,7 +368,12 @@ - + + + + + + @@ -379,7 +384,7 @@ - + @@ -397,10 +402,6 @@ - - - - @@ -431,7 +432,8 @@ - + + @@ -441,7 +443,8 @@ - + + @@ -451,7 +454,8 @@ - + + @@ -479,6 +483,14 @@ + + + + + + + + @@ -538,9 +550,14 @@ + + + + + + - # For SIGMA export SIGMA_HOME=${user.home}/.${app.name} export ONTOLOGYPORTAL_GIT=${workspace.dir} @@ -548,12 +565,12 @@ export SIGMA_SRC=$ONTOLOGYPORTAL_GIT/${app.name} export CATALINA_OPTS="$CATALINA_OPTS ${run.jvmargs}" export CATALINA_HOME=${programs.dir}/apache-tomcat-${tomcat.version} export PATH=$CATALINA_HOME/bin:$PATH -export SIGMA_CP=$SIGMA_SRC/build/${app.name}.jar:$SIGMA_SRC/lib/* +export SIGMA_CP=$SIGMA_SRC/build/${app.name}.jar:$SIGMA_SRC/lib/* + - # For SIGMA export SIGMA_HOME=${user.home}/.${app.name} export ONTOLOGYPORTAL_GIT=${workspace.dir} @@ -561,7 +578,8 @@ export SIGMA_SRC=$ONTOLOGYPORTAL_GIT/${app.name} export CATALINA_OPTS="$CATALINA_OPTS ${run.jvmargs}" export CATALINA_HOME=${programs.dir}/apache-tomcat-${tomcat.version} export PATH=$CATALINA_HOME/bin:$PATH -export SIGMA_CP=$SIGMA_SRC/build/${app.name}.jar:$SIGMA_SRC/lib/* +export SIGMA_CP=$SIGMA_SRC/build/${app.name}.jar:$SIGMA_SRC/lib/* + diff --git a/config.xml b/config.xml index 8080ec39..b098d15a 100644 --- a/config.xml +++ b/config.xml @@ -25,7 +25,7 @@ - + diff --git a/docker/sigma-ci/Dockerfile b/docker/sigma-ci/Dockerfile index c912d10c..2e025faa 100644 --- a/docker/sigma-ci/Dockerfile +++ b/docker/sigma-ci/Dockerfile @@ -1,4 +1,4 @@ -FROM tomcat:9.0.96-jdk11-temurin-jammy AS builder +FROM tomcat:9.0.97-jdk21-temurin-jammy AS builder # Followed instructions from: https://github.com/vprover/vampire/wiki/Source-Build-for-Users # for buildling latest vampire w/ latest Z3 @@ -33,7 +33,7 @@ RUN apt update; \ ################################################# # runtime image. -FROM tomcat:9.0.96-jdk11-temurin-jammy AS runtime +FROM tomcat:9.0.97-jdk21-temurin-jammy AS runtime COPY --from=builder \ /usr/local/tomcat/E/PROVER/e_ltb_runner /usr/local/bin/e_ltb_runner diff --git a/docker/sigmakee/Dockerfile b/docker/sigmakee/Dockerfile index 8977b6c3..07fb90d0 100644 --- a/docker/sigmakee/Dockerfile +++ b/docker/sigmakee/Dockerfile @@ -3,7 +3,7 @@ FROM $IMAGE_ACCOUNT/sigma-ci:latest AS builder ################################################# # runtime image. -FROM tomcat:9.0.96-jdk11-temurin-jammy AS runtime +FROM tomcat:9.0.97-jdk21-temurin-jammy AS runtime RUN apt update; \ apt-get install -y --no-install-recommends \ diff --git a/docker/sigmakee2023/Dockerfile b/docker/sigmakee2023/Dockerfile index dd9029e7..9a7fe05a 100644 --- a/docker/sigmakee2023/Dockerfile +++ b/docker/sigmakee2023/Dockerfile @@ -34,7 +34,7 @@ RUN cd /root \ && echo "export SIGMA_SRC=/root/workspace/sigmakee" >> .bashrc \ && echo "export ONTOLOGYPORTAL_GIT=/root/workspace" >> .bashrc \ && echo 'export CATALINA_OPTS="$CATALINA_OPTS -Xmx10g -Xss1m"' >> .bashrc \ - && echo "export CATALINA_HOME=/root/Programs/apache-tomcat-9.0.96" >> .bashrc \ + && echo "export CATALINA_HOME=/root/Programs/apache-tomcat-9.0.97" >> .bashrc \ && source .bashrc # Setup Vampire diff --git a/docker/sumo-ci/Dockerfile b/docker/sumo-ci/Dockerfile index 863d2877..db9ad6b9 100644 --- a/docker/sumo-ci/Dockerfile +++ b/docker/sumo-ci/Dockerfile @@ -3,7 +3,7 @@ FROM $IMAGE_ACCOUNT/sigma-ci:latest AS builder ################################################# # runtime image. -FROM tomcat:9.0.96-jdk11-temurin-jammy AS runtime +FROM tomcat:9.0.97-jdk21-temurin-jammy AS runtime RUN apt update; \ apt-get install -y --no-install-recommends \ diff --git a/nbproject/project.xml b/nbproject/project.xml index 0d8eabe6..649de4cc 100644 --- a/nbproject/project.xml +++ b/nbproject/project.xml @@ -272,7 +272,7 @@ auxiliary.show.customizer.message= folder - build/test/classes + build/WEB-INF/classes dist diff --git a/src/java/com/articulate/sigma/Formula.java b/src/java/com/articulate/sigma/Formula.java index 19acd757..87abf174 100644 --- a/src/java/com/articulate/sigma/Formula.java +++ b/src/java/com/articulate/sigma/Formula.java @@ -23,6 +23,7 @@ portions copyright Teknowledge (c) 2003 and reused under the terms of package com.articulate.sigma; import com.articulate.sigma.utils.StringUtil; + import org.apache.commons.lang3.StringUtils; import java.io.*; @@ -409,7 +410,7 @@ public void read(String s) { theFormula = s; allVarsCache = new HashSet<>(); - allVarsPairCache = new ArrayList>(); + allVarsPairCache = new ArrayList<>(); quantVarsCache = new HashSet<>(); unquantVarsCache = new HashSet<>(); existVarsCache = new HashSet<>(); @@ -429,7 +430,7 @@ public String createID() { if (!StringUtil.emptyString(fname) && fname.lastIndexOf(File.separator) > -1) fname = fname.substring(fname.lastIndexOf(File.separator) + 1); int hc = theFormula.hashCode(); - String result = null; + String result; if (hc < 0) result = "N" + (Integer.valueOf(hc)).toString().substring(1) + fname; else @@ -702,7 +703,7 @@ public Formula cons(String obj) { Formula ans = this; String fStr = this.theFormula; if (!StringUtil.emptyString(obj) && !StringUtil.emptyString(fStr)) { - String theNewFormula = null; + String theNewFormula; if (this.listP()) { if (this.empty()) theNewFormula = ("(" + obj + ")"); @@ -838,7 +839,7 @@ public Formula append(Formula f) { System.out.println("Error in KB.append(): attempt to append to non-list: " + theFormula); return this; } - if (f == null || f.theFormula == null || f.theFormula == "" || f.theFormula.equals("()")) + if (f == null || f.theFormula == null || "".equals(f.theFormula) || f.theFormula.equals("()")) return newFormula; f.theFormula = f.theFormula.trim(); if (!f.atom()) @@ -916,20 +917,22 @@ public static boolean listP(String s) { */ private String validArgsRecurse(Formula f, String filename, Integer lineNo) { - if (f.theFormula == "" || !f.listP() || f.atom() || f.empty()) + if ("".equals(f.theFormula) || !f.listP() || f.atom() || f.empty()) return ""; String pred = f.car(); String rest = f.cdr(); Formula restF = new Formula(); restF.read(rest); int argCount = 0; + String arg, result; + Formula argF; while (!restF.empty()) { argCount++; - String arg = restF.car(); - Formula argF = new Formula(); + arg = restF.car(); + argF = new Formula(); argF.read(arg); - String result = validArgsRecurse(argF, filename, lineNo); - if (result != "") + result = validArgsRecurse(argF, filename, lineNo); + if (!"".equals(result)) return result; restF.theFormula = restF.cdr(); } @@ -1002,7 +1005,7 @@ else if (!(isVariable(pred)) && (argCount > (MAX_PREDICATE_ARITY + 1))) { */ public String validArgs(String filename, Integer lineNo) { - if (theFormula == null || theFormula == "") + if (theFormula == null || "".equals(theFormula)) return ""; Formula f = new Formula(); f.read(theFormula); @@ -1049,10 +1052,12 @@ private ArrayList parseList(String s) { f.read("(" + s + ")"); if (f.empty()) return result; + String car; + Formula newForm; while (!f.empty()) { - String car = f.car(); + car = f.car(); f.read(f.cdr()); - Formula newForm = new Formula(); + newForm = new Formula(); newForm.read(car); result.add(newForm); } @@ -1346,12 +1351,14 @@ else if (f1.atom() || f2.atom()) { if (!Formula.isCommutative(head1.theFormula) && !(kb != null && kb.isInstanceOf(head1.theFormula, "SymmetricRelation"))) { //non commutative relation; comparing parameters in order List> runningMaps = headMaps; + List> parameterMaps; + Formula parameter1, parameter2; for (int i = 0; i < args1.size(); i++) { - Formula parameter1 = new Formula(); + parameter1 = new Formula(); parameter1.read(args1.get(i)); - Formula parameter2 = new Formula(); + parameter2 = new Formula(); parameter2.read(args2.get(i)); - List> parameterMaps = mapFormulaVariables(parameter1, parameter2, kb, memoMap); + parameterMaps = mapFormulaVariables(parameter1, parameter2, kb, memoMap); memoMap.put(FormulaUtil.createFormulaMatchMemoMapKey(parameter1.theFormula, parameter2.theFormula), parameterMaps); runningMaps = VariableMapping.intersect(runningMaps, parameterMaps); if (runningMaps == null) { @@ -1781,8 +1788,9 @@ public void collectQuantifiedUnquantifiedVariablesRecurse(Formula f, HashMap thisCol, Collection arg) { @@ -1850,25 +1856,27 @@ public Set collectAllVariables() { if (!allVarsCache.isEmpty()) return allVarsCache; + //ArrayList result = new ArrayList(); HashSet resultSet = new HashSet<>(); + if (listLength() < 1) return resultSet; Formula fcar = new Formula(); fcar.read(this.car()); if (fcar.isVariable()) - resultSet.add(fcar.theFormula); + resultSet.add(fcar.theFormula); else { - if (fcar.listP()) - resultSet.addAll(fcar.collectAllVariables()); + if (fcar.listP()) + resultSet.addAll(fcar.collectAllVariables()); } Formula fcdr = new Formula(); fcdr.read(this.cdr()); if (fcdr.isVariable()) - resultSet.add(fcdr.theFormula); + resultSet.add(fcdr.theFormula); else { - if (fcdr.listP()) - resultSet.addAll(fcdr.collectAllVariables()); + if (fcdr.listP()) + resultSet.addAll(fcdr.collectAllVariables()); } //result.addAll(resultSet); allVarsCache.addAll(resultSet); @@ -1962,10 +1970,6 @@ public Set collectQuantifiedVariables() { return resultSet; Formula fcar = new Formula(); fcar.read(this.car()); - if (fcar.empty()) - return resultSet; - if (debug) - System.out.println("Formula.collectQuantifiedVariables(): car: " + fcar); if (fcar.theFormula.equals(UQUANT) || fcar.theFormula.equals(EQUANT)) { Formula remainder = new Formula(); remainder.read(this.cdr()); @@ -2001,7 +2005,7 @@ public Set collectTerms() { HashSet resultSet = new HashSet<>(); - if (this.theFormula == null || this.theFormula == "") { + if (this.theFormula == null || "".equals(this.theFormula)) { System.out.println("Error in Formula.collectTerms(): " + "No formula to collect terms from: " + this); return null; @@ -2113,7 +2117,7 @@ public Formula renameVariableArityRelations(KB kb, TreeMap relati f.read(this.theFormula); int flen = f.listLength(); String suffix = ("__" + (flen - 1)); - String arg = null; + String arg; sb.append("("); for (int i = 0 ; i < flen ; i++) { arg = f.getStringArgument(i); @@ -2421,7 +2425,7 @@ public boolean isSimpleClause(KB kb) { return false; if (!atom(this.car())) return false; - String arg = null; + String arg; int argnum = 1; do { arg = this.getStringArgument(argnum); @@ -2787,7 +2791,7 @@ public Formula replaceQuantifierVars(String quantifier, List vars) throw */ public static boolean isQuery(String query, String formula) { - boolean result = false; + boolean result; Formula f = new Formula(); f.read(formula); @@ -2857,7 +2861,7 @@ public String format(String hyperlink, String indentChars, String eolChars) { int flen = this.theFormula.length(); char pch = '0'; // char at (i-1) - char ch = '0'; // char at i + char ch; // char at i for (int i = 0; i < flen; i++) { // logger.finest("formatted string = " + formatted.toString()); ch = this.theFormula.charAt(i); @@ -2970,6 +2974,7 @@ public static String textFormat(String input) { /** *************************************************************** * Format a formula for text presentation. */ + @Override public String toString() { return format("", " ", Character.valueOf((char) 10).toString()); @@ -2997,7 +3002,7 @@ public String htmlFormat(String html) { */ public String htmlFormat(KB kb, String href) { - String fKbHref = ""; + String fKbHref; String kbHref = (href + "/sigma/Browse.jsp?kb=" + kb.name); fKbHref = format(kbHref,"    ","
\n"); return fKbHref; @@ -3131,7 +3136,7 @@ public static void testClausifier(String[] args) { long dur = (System.currentTimeMillis() - t1); } catch (Exception ex) { - System.out.println(ex.getMessage()); + System.err.println(ex.getMessage()); ex.printStackTrace(); } finally { @@ -3300,4 +3305,3 @@ else if (args != null && args.length > 1 && args[0].contains("x")) { } } } - diff --git a/src/java/com/articulate/sigma/InferenceTestSuite.java b/src/java/com/articulate/sigma/InferenceTestSuite.java index b7efc712..e7c46028 100644 --- a/src/java/com/articulate/sigma/InferenceTestSuite.java +++ b/src/java/com/articulate/sigma/InferenceTestSuite.java @@ -450,10 +450,8 @@ public String test(KB inputKB, int defaultTimeout, String TPTPlocation) System.out.println("INFO in InferenceTestSuite.test(): Note that any prior user assertions will be deleted."); System.out.println("INFO in InferenceTestSuite.test(): Prover: " + KBmanager.getMgr().prover); StringBuilder result = new StringBuilder(); - FileWriter fw = null; int fail = 0; int pass = 0; - PrintWriter pw = null; String proof = null; String language = "EnglishLanguage"; @@ -537,9 +535,8 @@ public String test(KB inputKB, int defaultTimeout, String TPTPlocation) resultsFilename = rfn.substring(0,rfn.length()-3) + "-res.html"; resultsFile = new File(outputDir, resultsFilename); tpp = new TPTP3ProofProcessor(); - try { - fw = new FileWriter(resultsFile); - pw = new PrintWriter(fw); + try (FileWriter fw = new FileWriter(resultsFile); PrintWriter pw = new PrintWriter(fw)) { + tpp.parseProofOutput(proof, kb); System.out.println("InferenceTestSuite.test() proof status: " + tpp.status + " for " + itd.note); itd.SZSstatus = tpp.status; @@ -554,15 +551,6 @@ public String test(KB inputKB, int defaultTimeout, String TPTPlocation) catch (IOException e) { throw new IOException("Error writing file " + resultsFile.getCanonicalPath()); } - finally { - try { - if (pw != null) { pw.close(); } - if (fw != null) { fw.close(); } - } - catch (IOException ex) { - ex.printStackTrace(); - } - } if (tpp.inconsistency) { result.append("

InferenceTestSuite.inferenceUnitTest(): Danger! possible inconsistency!

"); itd.inconsistent = true; diff --git a/src/java/com/articulate/sigma/KB.java b/src/java/com/articulate/sigma/KB.java index 66b3269f..347a4953 100644 --- a/src/java/com/articulate/sigma/KB.java +++ b/src/java/com/articulate/sigma/KB.java @@ -1121,7 +1121,7 @@ private ArrayList stringsToFormulas(ArrayList strings) { */ public ArrayList ask(String kind, int argnum, String term) { - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList<>(); String msg; if (StringUtil.emptyString(term)) { msg = ("Error in KB.ask(\"" + kind + "\", " + argnum + ", \"" + term + "\"), " diff --git a/src/java/com/articulate/sigma/KButilities.java b/src/java/com/articulate/sigma/KButilities.java index a710edc9..053a5594 100755 --- a/src/java/com/articulate/sigma/KButilities.java +++ b/src/java/com/articulate/sigma/KButilities.java @@ -15,6 +15,7 @@ portions copyright Teknowledge (c) 2003 and reused under the termsof the GNU /*************************************************************************************************/ package com.articulate.sigma; + import java.io.*; import java.net.HttpURLConnection; import java.net.URL; @@ -23,14 +24,15 @@ portions copyright Teknowledge (c) 2003 and reused under the termsof the GNU import java.util.regex.Pattern; import com.articulate.sigma.dataProc.Infrastructure; -import com.articulate.sigma.nlg.LanguageFormatter; import com.articulate.sigma.nlg.NLGUtils; import com.articulate.sigma.trans.SUMOtoTFAform; import com.articulate.sigma.utils.FileUtil; import com.articulate.sigma.utils.MapUtils; import com.articulate.sigma.utils.StringUtil; import com.articulate.sigma.wordNet.WordNet; + import com.google.common.collect.Sets; + import org.json.simple.JSONAware; import org.json.simple.JSONValue; @@ -42,7 +44,7 @@ public class KButilities { public static boolean debug = false; /** Errors found during processing formulas */ - public static TreeSet errors = new TreeSet(); + public static TreeSet errors = new TreeSet<>(); /** Warnings found during processing formulas */ public static TreeSet warnings = new TreeSet(); @@ -82,14 +84,15 @@ public static boolean hasCorrectTypes(KB kb, Formula f) { Map> explicit = SUMOtoTFAform.fp.findExplicitTypes(kb, f); if (debug) System.out.println("hasCorrectTypes() explicit: " + explicit); KButilities.mergeToMap(SUMOtoTFAform.varmap,explicit,kb); + String error; if (SUMOtoTFAform.inconsistentVarTypes()) { - String error = "inconsistent types in " + SUMOtoTFAform.varmap; + error = "inconsistent types in " + SUMOtoTFAform.varmap; System.out.println("hasCorrectTypes(): " + SUMOtoTFAform.errors); errors.addAll(SUMOtoTFAform.errors); return false; } if (SUMOtoTFAform.typeConflict(f)) { - String error = "Type conflict: " + SUMOtoTFAform.errors; + error = "Type conflict: " + SUMOtoTFAform.errors; System.out.println("hasCorrectTypes(): " + SUMOtoTFAform.errors); errors.addAll(SUMOtoTFAform.errors); return false; @@ -103,7 +106,7 @@ public static boolean hasCorrectTypes(KB kb, Formula f) { public static boolean isValidFormula(KB kb, String form) { SUMOtoTFAform.initOnce(); - String result = ""; + String result; KIF kif = new KIF(); try { result = kif.parseStatement(form); @@ -158,7 +161,7 @@ public static boolean isVariableArity(KB kb, String term) { public static String getDocumentation(KB kb, String term) { ArrayList forms = kb.askWithRestriction(0,"documentation",1,term); - if (forms == null || forms.size() == 0) + if (forms == null || forms.isEmpty()) return null; Formula form = forms.get(0); if (form == null) @@ -186,8 +189,9 @@ public static int getCountUniqueTermFormats(KB kb, String lang) { ArrayList forms = kb.askWithRestriction(0,"termFormat",1,lang); HashSet terms = new HashSet<>(); + String s; for (Formula f : forms) { - String s = f.getStringArgument(2); + s = f.getStringArgument(2); terms.add(s); } return terms.size(); @@ -239,9 +243,10 @@ public static void genSynLinks(String fname) { int termcol = 0; ArrayList> spread = new ArrayList<>(); spread = DB.readSpreadsheet(fname,null,false,'\t'); + String label; for (ArrayList row : spread) { if (row != null && row.size() > 1) { - String label = row.get(termcol); + label = row.get(termcol); System.out.println("(synonymousExternalConcept \"" + label + "\" Entity Taxonomy)"); } } @@ -269,23 +274,24 @@ public static ArrayList termIntersection(KB kb, String term1, String te ArrayList ant2 = kb.ask("ant",0,term2); ArrayList cons1 = kb.ask("cons",0,term1); ArrayList cons2 = kb.ask("cons",0,term2); - HashSet hrule1 = new HashSet(); + HashSet hrule1 = new HashSet<>(); hrule1.addAll(ant1); hrule1.addAll(cons1); - HashSet hrule2 = new HashSet(); + HashSet hrule2 = new HashSet<>(); hrule2.addAll(ant2); hrule2.addAll(cons2); - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList<>(); result.addAll(hrule1); result.retainAll(hrule2); ArrayList stmt1 = kb.ask("stmt",0,term1); ArrayList stmt2 = kb.ask("stmt",0,term2); stmt1.retainAll(stmt2); result.addAll(stmt1); + ArrayList stmt; for (int i = 0; i < 7; i++) { for (int j = 0; j < 7; j++) { if (j != i) { - ArrayList stmt = kb.askWithRestriction(i,term1,j,term2); + stmt = kb.askWithRestriction(i,term1,j,term2); result.addAll(stmt); } } @@ -299,10 +305,12 @@ public static void countRelations(KB kb) { System.out.println("Relations: " + kb.getCountRelations()); Iterator it = kb.terms.iterator(); + String term; + ArrayList al; while (it.hasNext()) { - String term = (String) it.next(); - ArrayList al = kb.ask("arg",0,term); - if (al != null && al.size() > 0) { + term = (String) it.next(); + al = kb.ask("arg",0,term); + if (al != null && !al.isEmpty()) { System.out.println(term + " " + al.size()); } } @@ -314,10 +322,7 @@ public static boolean isCacheFile(String filename) { if (StringUtil.emptyString(filename)) return false; - if (filename.endsWith("_Cache.kif")) - return true; - else - return false; + return filename.endsWith("_Cache.kif"); } /** ************************************************************* @@ -326,9 +331,7 @@ public static void countProcesses(KB kb) { int count = 0; int wncount = 0; - Iterator it = kb.terms.iterator(); - while (it.hasNext()) { - String term = (String) it.next(); + for (String term : kb.terms) { if (kb.isSubclass(term,"Process")) { count++; if (WordNet.wn.SUMOHash.containsKey(term)) @@ -351,7 +354,7 @@ private static boolean uRLexists(String URLName){ (HttpURLConnection) new URL(URLName).openConnection(); con.setRequestMethod("HEAD"); return(con.getResponseCode() == HttpURLConnection.HTTP_OK); - } catch (Exception e) { + } catch (IOException e) { e.printStackTrace(); return false; } @@ -363,9 +366,11 @@ public static void checkURLs(KB kb) { URL u = null; ArrayList results = kb.ask("arg",0,"externalImage"); + Formula f; + String url; for (int i = 0; i < results.size(); i++) { - Formula f = (Formula) results.get(i); - String url = StringUtil.removeEnclosingQuotes(f.getStringArgument(2)); + f = (Formula) results.get(i); + url = StringUtil.removeEnclosingQuotes(f.getStringArgument(2)); if (!uRLexists(url)) System.out.println(f + " doesn't exist"); } @@ -383,19 +388,16 @@ public static void validatePictureList() { // http://upload.wikimedia.org/wikipedia/commons/3/33/Reef.jpg // URL u = null; - String line = null; + String line; - FileReader fr = null; - LineNumberReader lr = null; - - try { - fr = new FileReader("pictureList.kif"); - lr = new LineNumberReader(fr); + try (FileReader fr = new FileReader("pictureList.kif"); LineNumberReader lr = new LineNumberReader(fr)) { Pattern p = Pattern.compile("([^ ]+) ([^ ]+) \"([^\"]+)\"\\)"); + Matcher m; + String url; while ((line = lr.readLine()) != null) { - Matcher m = p.matcher(line); + m = p.matcher(line); if (m.matches()) { - String url = StringUtil.removeEnclosingQuotes(m.group(3)); + url = StringUtil.removeEnclosingQuotes(m.group(3)); //System.out.println("the url: " + url); if (!uRLexists(url)) System.out.println(";; " + line); @@ -406,18 +408,8 @@ public static void validatePictureList() { System.out.println(line); } } - catch (java.io.IOException e) { - System.out.println("Error reading pictureList.kif\n" + e.getMessage()); - } - finally { - try { - if (lr != null) - lr.close(); - if (fr != null) - fr.close(); - } - catch (Exception ex) { - } + catch (IOException e) { + System.err.println("Error reading pictureList.kif\n" + e.getMessage()); } } @@ -434,6 +426,7 @@ public GraphArc(String s, String r, String t) { public String rel = ""; public String target = ""; + @Override public int compareTo(Object o) { if (o.getClass().toString().endsWith("GraphArc")) { @@ -447,6 +440,7 @@ public int compareTo(Object o) { } } + @Override public boolean equals(Object o) { if (o.getClass().toString().endsWith("GraphArc")) { GraphArc ga2 = (GraphArc) o; @@ -457,13 +451,15 @@ public boolean equals(Object o) { else throw new ClassCastException(); } + @Override public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("{\"source\":\"" + source + "\",\"rel\":\"" + rel + "\",\"target\":\"" + target + "\"}"); + StringBuilder sb = new StringBuilder(); + sb.append("{\"source\":\"").append(source).append("\",\"rel\":\"").append(rel).append("\",\"target\":\"").append(target).append("\"}"); return sb.toString(); } + @Override public String toJSONString() { return toString(); } @@ -480,7 +476,7 @@ public String semnetAsJSON3(KB kb, boolean cached, boolean strings) { GraphArc ga = this.new GraphArc(sp[0],sp[1],sp[2]); al.add(ga); } - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append(JSONValue.toJSONString(al)); return sb.toString(); } @@ -492,6 +488,10 @@ public Set generateSemNetNeighbors(KB kb, boolean cached, boolean stri if (debug) System.out.println("generateSemNetNeighbors(): term: " + term + " count: " + count); TreeSet resultSet = new TreeSet<>(); TreeSet targets = new TreeSet<>(); + Set terms; + GraphArc ga; + String predicate, arg1, arg2; + ArrayList args; for (Formula f : kb.formulaMap.values()) { // look at all formulas in the KB //if (debug) System.out.println("generateSemNetNeighbors(): check formula: " + f); if (isCacheFile(f.sourceFile) && !cached) { @@ -500,7 +500,7 @@ public Set generateSemNetNeighbors(KB kb, boolean cached, boolean stri } if ((!f.isSimpleClause(kb) || !f.isGround()) && links) { if (debug) System.out.println("generateSemNetNeighbors(): not simple"); - Set terms = f.collectTerms(); + terms = f.collectTerms(); for (String term1 : terms) { if (!term1.equals(term)) continue; @@ -510,31 +510,31 @@ public Set generateSemNetNeighbors(KB kb, boolean cached, boolean stri if (Formula.isLogicalOperator(term2) || Formula.isVariable(term2) || (!strings && StringUtil.isQuotedString(term2))) continue; if (!term1.equals(term2)) { - GraphArc ga = new GraphArc(term1,"link",term2); + ga = new GraphArc(term1,"link",term2); resultSet.add(ga); targets.add(term2); } } - GraphArc ga = new GraphArc(term1,"inAxiom", "\"" + f.getFormula() + "\""); + ga = new GraphArc(term1,"inAxiom", "\"" + f.getFormula() + "\""); resultSet.add(ga); } } else { - String predicate = f.getStringArgument(0); + predicate = f.getStringArgument(0); if (debug) System.out.println("generateSemNetNeighbors(): simple"); - ArrayList args = f.argumentsToArrayListString(0); + args = f.argumentsToArrayListString(0); if ((args != null && args.size() == 3) || args.get(0).equals("documentation")) { // could have a function which would return null - String arg1 = f.getStringArgument(1); + arg1 = f.getStringArgument(1); if (arg1.equals(term)) { if (debug) System.out.println("generateSemNetNeighbors(): check ground formula: " + f); - String arg2 = f.getStringArgument(2); + arg2 = f.getStringArgument(2); if (args.get(0).equals("documentation")) arg2 = f.getStringArgument(3); if (!Formula.isVariable(arg1) && !Formula.isVariable(arg2) && (strings || !StringUtil.isQuotedString(arg1)) && (strings || !StringUtil.isQuotedString(arg2))) { if (StringUtil.isQuotedString(arg2)) arg2 = StringUtil.removeEnclosingQuotes(arg2); - GraphArc ga = new GraphArc(arg1, predicate, arg2); + ga = new GraphArc(arg1, predicate, arg2); resultSet.add(ga); targets.add(arg2); } @@ -542,12 +542,12 @@ public Set generateSemNetNeighbors(KB kb, boolean cached, boolean stri arg1 = f.getStringArgument(2); if (arg1.equals(term)) { if (debug) System.out.println("generateSemNetNeighbors(): check ground formula: " + f); - String arg2 = f.getStringArgument(1); + arg2 = f.getStringArgument(1); if (!Formula.isVariable(arg1) && !Formula.isVariable(arg2) && (strings || !StringUtil.isQuotedString(arg1)) && (strings || !StringUtil.isQuotedString(arg2))) { if (StringUtil.isQuotedString(arg1)) arg2 = StringUtil.removeEnclosingQuotes(arg1); - GraphArc ga = new GraphArc(arg2, predicate, arg1); + ga = new GraphArc(arg2, predicate, arg1); resultSet.add(ga); targets.add(arg2); } @@ -577,12 +577,15 @@ public Set generateSemNetNeighbors(KB kb, boolean cached, boolean stri */ private static Set generateSemanticNetwork(KB kb, boolean cached, boolean strings) { - TreeSet resultSet = new TreeSet(); + TreeSet resultSet = new TreeSet<>(); + Set terms; + String predicate, arg1, arg2; + ArrayList args; for (Formula f : kb.formulaMap.values()) { // look at all formulas in the KB if (isCacheFile(f.sourceFile)) continue; if (!f.isSimpleClause(kb) || !f.isGround()) { - Set terms = f.collectTerms(); + terms = f.collectTerms(); for (String term1 : terms) { if (Formula.isLogicalOperator(term1) || Formula.isVariable(term1) || (!strings && StringUtil.isQuotedString(term1))) continue; @@ -599,11 +602,11 @@ private static Set generateSemanticNetwork(KB kb, boolean cached, boolea } } else { - String predicate = f.getStringArgument(0); - ArrayList args = f.argumentsToArrayListString(1); + predicate = f.getStringArgument(0); + args = f.argumentsToArrayListString(1); if (args != null && args.size() == 2) { // could have a function which would return null - String arg1 = f.getStringArgument(1); - String arg2 = f.getStringArgument(2); + arg1 = f.getStringArgument(1); + arg2 = f.getStringArgument(2); if (arg1.contains("(") || arg1.contains(")") || arg2.contains("(") || arg2.contains(")")) System.out.println("error in generateSemanticNetwork(): for formula: " + f); else if (!Formula.isLogicalOperator(arg1) && !Formula.isLogicalOperator(arg2) && @@ -620,11 +623,12 @@ else if (!Formula.isLogicalOperator(arg1) && !Formula.isLogicalOperator(arg2) && */ private static String semnetAsDot(Set triples) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("graph G {"); + String[] tuple; for (String s : triples) { - String[] tuple = s.split(" "); - sb.append(" \"" + tuple[0] + "\" -- \"" + tuple[2] + "\" [ label=\"" + tuple[1] + "\" ];\n"); + tuple = s.split(" "); + sb.append(" \"").append(tuple[0]).append("\" -- \"").append(tuple[2]).append("\" [ label=\"").append(tuple[1]).append("\" ];\n"); } sb.append("}"); return sb.toString(); @@ -637,22 +641,25 @@ private static String semnetAsJSON(Set triples, KB kb,String language) { if (StringUtil.emptyString(language)) language = "EnglishLanguage"; - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("{\n"); sb.append(" \"graphs\" : [ \n"); sb.append(" {\n"); - sb.append(" \"id\": \"" + kb.name + "\",\n"); + sb.append(" \"id\": \"").append(kb.name).append("\",\n"); sb.append(" \"type\": \"SUMO-graph\",\n"); - sb.append(" \"label\": \"" + kb.name + "\",\n"); + sb.append(" \"label\": \"").append(kb.name).append("\",\n"); sb.append(" \"nodes\": {\n"); + ArrayList forms; + String formStr; + Formula form; for (String s : kb.getTerms()) { if (Formula.isLogicalOperator(s)) continue; - sb.append(" \"" + s + "\": {\n"); - ArrayList forms = kb.askWithTwoRestrictions(0,"termFormat",1,language,2,s); - String formStr = ""; - if (forms != null && forms.size() > 0) { - Formula form = forms.iterator().next().getArgument(3); + sb.append(" \"").append(s).append("\": {\n"); + forms = kb.askWithTwoRestrictions(0,"termFormat",1,language,2,s); + formStr = ""; + if (forms != null && !forms.isEmpty()) { + form = forms.iterator().next().getArgument(3); if (form != null && form.atom()) formStr = form.getFormula(); if (!StringUtil.emptyString(formStr)) @@ -660,18 +667,19 @@ private static String semnetAsJSON(Set triples, KB kb,String language) { } else formStr = s; - sb.append(" \"label\" : \"" + formStr + "\"\n"); + sb.append(" \"label\" : \"").append(formStr).append("\"\n"); sb.append(" },\n"); } sb.deleteCharAt(sb.length()-2); sb.append(" },\n"); sb.append(" \"edges\": [\n"); + String[] tuple; for (String s : triples) { - String[] tuple = s.split(" "); + tuple = s.split(" "); sb.append(" {\n"); - sb.append(" \"source\": \"" + tuple[0] + "\",\n"); - sb.append(" \"relation\": \"" + tuple[1] + "\",\n"); - sb.append(" \"target\": \"" + tuple[2] + "\"\n"); + sb.append(" \"source\": \"").append(tuple[0]).append("\",\n"); + sb.append(" \"relation\": \"").append(tuple[1]).append("\",\n"); + sb.append(" \"target\": \"").append(tuple[2]).append("\"\n"); sb.append(" },\n"); } sb.deleteCharAt(sb.length()-2); @@ -692,21 +700,20 @@ private static void semnetAsJSON2(Set triples, KB kb,String language) { String edgeFileStr = kbDir + File.separator + "edges.json"; if (StringUtil.emptyString(language)) language = "EnglishLanguage"; - StringBuffer sb = new StringBuffer(); - PrintWriter nodepw = null; - PrintWriter edgepw = null; - try { - nodepw = new PrintWriter(new FileWriter(nodeFileStr, false)); - edgepw = new PrintWriter(new FileWriter(edgeFileStr, false)); + StringBuilder sb = new StringBuilder(); + ArrayList forms; + String formStr; + Formula form; + try (PrintWriter nodepw = new PrintWriter(new FileWriter(nodeFileStr, false)); PrintWriter edgepw = new PrintWriter(new FileWriter(edgeFileStr, false))) { sb.append("[\n"); for (String s : kb.getTerms()) { if (Formula.isLogicalOperator(s)) continue; - sb.append(" { \"id\" : \"" + s + "\",\n"); - ArrayList forms = kb.askWithTwoRestrictions(0, "termFormat", 1, language, 2, s); - String formStr = ""; - if (forms != null && forms.size() > 0) { - Formula form = forms.iterator().next().getArgument(3); + sb.append(" { \"id\" : \"").append(s).append("\",\n"); + forms = kb.askWithTwoRestrictions(0, "termFormat", 1, language, 2, s); + formStr = ""; + if (forms != null && !forms.isEmpty()) { + form = forms.iterator().next().getArgument(3); if (form != null && form.atom()) formStr = form.getFormula(); if (!StringUtil.emptyString(formStr)) @@ -714,37 +721,32 @@ private static void semnetAsJSON2(Set triples, KB kb,String language) { } else formStr = s; - sb.append(" \"label\" : \"" + formStr + "\"\n"); + sb.append(" \"label\" : \"").append(formStr).append("\"\n"); sb.append(" },\n"); } sb.deleteCharAt(sb.length() - 2); sb.append("]\n"); nodepw.print(sb.toString()); - sb = new StringBuffer(); + sb = new StringBuilder(); sb.append("[\n"); + String[] tuple; for (String s : triples) { - String[] tuple = s.split(" "); + tuple = s.split(" "); sb.append(" {\n"); - sb.append(" \"source\" : \"" + tuple[0] + "\",\n"); - sb.append(" \"relation\" : \"" + tuple[1] + "\",\n"); - sb.append(" \"target\" : \"" + tuple[2] + "\"\n"); + sb.append(" \"source\" : \"").append(tuple[0]).append("\",\n"); + sb.append(" \"relation\" : \"").append(tuple[1]).append("\",\n"); + sb.append(" \"target\" : \"").append(tuple[2]).append("\"\n"); sb.append(" },\n"); } sb.deleteCharAt(sb.length() - 2); sb.append("]\n"); edgepw.print(sb.toString()); } - catch (Exception e) { - System.out.println(e.getMessage()); + catch (IOException e) { + System.err.println(e.getMessage()); e.printStackTrace(); } - finally { - if (nodepw != null) - nodepw.close(); - if (edgepw != null) - edgepw.close(); - } } /** ************************************************************* @@ -756,17 +758,18 @@ private static void semnetAsTriples(Set triples, KB kb,String language) String fileStr = kbDir + File.separator + "triples.txt"; if (StringUtil.emptyString(language)) language = "EnglishLanguage"; - StringBuffer sb = new StringBuffer(); - PrintWriter pw = null; - try { - pw = new PrintWriter(new FileWriter(fileStr, false)); + String formStr, doc; + ArrayList forms; + Formula form; + String[] tuple; + try (PrintWriter pw = new PrintWriter(new FileWriter(fileStr, false))) { for (String s : kb.getTerms()) { if (Formula.isLogicalOperator(s)) continue; - ArrayList forms = kb.askWithTwoRestrictions(0, "termFormat", 1, language, 2, s); - String formStr = ""; - if (forms != null && forms.size() > 0) { - Formula form = forms.iterator().next().getArgument(3); + forms = kb.askWithTwoRestrictions(0, "termFormat", 1, language, 2, s); + formStr = ""; + if (forms != null && !forms.isEmpty()) { + form = forms.iterator().next().getArgument(3); if (form != null && form.atom()) formStr = form.getFormula(); if (!StringUtil.emptyString(formStr)) @@ -775,23 +778,19 @@ private static void semnetAsTriples(Set triples, KB kb,String language) else formStr = s; pw.println(s + "|" + formStr); - String doc = KButilities.getDocumentation(kb,s); + doc = KButilities.getDocumentation(kb,s); if (!StringUtil.emptyString(doc)) pw.println(s + "|documentation|" + doc); } for (String s : triples) { - String[] tuple = s.split(" "); + tuple = s.split(" "); pw.println(tuple[0] + "|" + tuple[1] + "|" + tuple[2]); } } catch (Exception e) { - System.out.println(e.getMessage()); + System.err.println(e.getMessage()); e.printStackTrace(); } - finally { - if (pw != null) - pw.close(); - } } /** ************************************************************* @@ -804,20 +803,20 @@ private static void semnetAsSQLGraph(Set triples, KB kb,String language) String edgeFileStr = kbDir + File.separator + "edges.sql"; if (StringUtil.emptyString(language)) language = "EnglishLanguage"; - StringBuffer sb = new StringBuffer(); - PrintWriter nodepw = null; - PrintWriter edgepw = null; - try { - nodepw = new PrintWriter(new FileWriter(nodeFileStr, false)); - edgepw = new PrintWriter(new FileWriter(edgeFileStr, false)); + StringBuilder sb = new StringBuilder(); + ArrayList forms; + String formStr; + Formula form; + String[] tuple; + try (PrintWriter nodepw = new PrintWriter(new FileWriter(nodeFileStr, false)); PrintWriter edgepw = new PrintWriter(new FileWriter(edgeFileStr, false))) { for (String s : kb.getTerms()) { if (Formula.isLogicalOperator(s)) continue; - sb.append("INSERT INTO nodes (id, label) values ('" + s + "',"); - ArrayList forms = kb.askWithTwoRestrictions(0, "termFormat", 1, language, 2, s); - String formStr = ""; - if (forms != null && forms.size() > 0) { - Formula form = forms.iterator().next().getArgument(3); + sb.append("INSERT INTO nodes (id, label) values ('").append(s).append("',"); + forms = kb.askWithTwoRestrictions(0, "termFormat", 1, language, 2, s); + formStr = ""; + if (forms != null && !forms.isEmpty()) { + form = forms.iterator().next().getArgument(3); if (form != null && form.atom()) formStr = form.getFormula(); if (!StringUtil.emptyString(formStr)) @@ -825,28 +824,22 @@ private static void semnetAsSQLGraph(Set triples, KB kb,String language) } else formStr = s; - sb.append("'" + formStr + "');\n"); + sb.append("'").append(formStr).append("');\n"); } nodepw.print(sb.toString()); - sb = new StringBuffer(); + sb = new StringBuilder(); for (String s : triples) { - String[] tuple = s.split(" "); - sb.append(" INSERT INTO edges (source, rel, target) values ('" + tuple[0] + "'"); - sb.append(", '" + tuple[1] + "', '" + tuple[2] + "');\n"); + tuple = s.split(" "); + sb.append(" INSERT INTO edges (source, rel, target) values ('").append(tuple[0]).append("'"); + sb.append(", '").append(tuple[1]).append("', '").append(tuple[2]).append("');\n"); } edgepw.print(sb.toString()); } - catch (Exception e) { - System.out.println(e.getMessage()); + catch (IOException e) { + System.err.println(e.getMessage()); e.printStackTrace(); } - finally { - if (nodepw != null) - nodepw.close(); - if (edgepw != null) - edgepw.close(); - } } /** ************************************************************* @@ -854,11 +847,11 @@ private static void semnetAsSQLGraph(Set triples, KB kb,String language) */ public static String generateAllNL(KB kb) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); for (String f : kb.formulaMap.keySet()) { if (!f.startsWith("(documentation") && !f.startsWith("(format") && !f.startsWith("(termFormat")) - result.append(f + "\n" + StringUtil.filterHtml(NLGUtils.htmlParaphrase("", f, - kb.getFormatMap("EnglishLanguage"), kb.getTermFormatMap("EnglishLanguage"), kb, "EnglishLanguage")) + "\n"); + result.append(f).append("\n").append(StringUtil.filterHtml(NLGUtils.htmlParaphrase("", f, + kb.getFormatMap("EnglishLanguage"), kb.getTermFormatMap("EnglishLanguage"), kb, "EnglishLanguage"))).append("\n"); } return result.toString(); } @@ -872,23 +865,26 @@ public static String generateAllNL(KB kb) { public static boolean instanceOfInstanceP(KB kb) { boolean result = false; + ArrayList al, al2, al3; + Formula f, f2, f3; + String term2, term3, term4; for (String term : kb.terms) { - ArrayList al = kb.askWithRestriction(0,"instance",1,term); + al = kb.askWithRestriction(0,"instance",1,term); for (int i = 0; i < al.size(); i++) { - Formula f = (Formula) al.get(i); - String term2 = f.getStringArgument(2); + f = (Formula) al.get(i); + term2 = f.getStringArgument(2); if (Formula.atom(term2)) { - ArrayList al2 = kb.askWithRestriction(0,"instance",1,term2); - if (al2.size() > 0) + al2 = kb.askWithRestriction(0,"instance",1,term2); + if (!al2.isEmpty()) result = true; for (int j = 0; j < al2.size(); j++) { - Formula f2 = (Formula) al2.get(j); - String term3 = f2.getStringArgument(2); + f2 = (Formula) al2.get(j); + term3 = f2.getStringArgument(2); if (Formula.atom(term3)) { - ArrayList al3 = kb.askWithRestriction(0,"instance",1,term3); + al3 = kb.askWithRestriction(0,"instance",1,term3); for (int k = 0; k < al3.size(); k++) { - Formula f3 = (Formula) al3.get(k); - String term4 = f3.getStringArgument(2); + f3 = (Formula) al3.get(k); + term4 = f3.getStringArgument(2); } } } @@ -903,48 +899,52 @@ public static boolean instanceOfInstanceP(KB kb) { public static void writeDisplayText(KB kb, String displayFormatPredicate, String displayTermPredicate, String language, String fname) throws IOException { - PrintWriter pr = null; - try { - pr = new PrintWriter(new FileWriter(fname, false)); + try (PrintWriter pr = new PrintWriter(new FileWriter(fname, false))) { //get all formulas that have the display predicate as the predicate ArrayList formats = kb.askWithRestriction(0, displayFormatPredicate, 1, language); ArrayList terms = kb.askWithRestriction(0, displayTermPredicate, 1, language); - HashMap termMap = new HashMap(); + HashMap termMap = new HashMap<>(); + Formula term; + String key, value, argName, argNum; for (int i = 0; i < terms.size(); i++) { - Formula term = terms.get(i); - String key = term.getStringArgument(2); - String value = term.getStringArgument(3); - if (key != "" && value != "") + term = terms.get(i); + key = term.getStringArgument(2); + value = term.getStringArgument(3); + if (!"".equals(key) && !"".equals(value)) termMap.put(key, value); } + Formula format, f; + String sTerm, displayText; + StringBuilder sb; + ArrayList predInstances, arguments; for (int i = 0; i < formats.size(); i++) { - Formula format = formats.get(i); + format = formats.get(i); // This is the current predicate whose format we are keeping track of. - String key = format.getStringArgument(2); - String value = format.getStringArgument(3); - if (key != "" && value != "") { + key = format.getStringArgument(2); + value = format.getStringArgument(3); + if (!"".equals(key) && !"".equals(value)) { // This basically gets all statements that use the current predicate in the 0 position - ArrayList predInstances = kb.ask("arg", 0, key); + predInstances = kb.ask("arg", 0, key); for(int j=0; j < predInstances.size(); j++) { - StringBuilder sb = new StringBuilder(); - String displayText = String.copyValueOf(value.toCharArray()); - Formula f = predInstances.get(j); - ArrayList arguments = f.complexArgumentsToArrayList(0); + sb = new StringBuilder(); + displayText = String.copyValueOf(value.toCharArray()); + f = predInstances.get(j); + arguments = f.complexArgumentsToArrayList(0); sb.append(key); sb.append(","); // check if each of the arguments for the statements is to be replaced in its // format statement. for (int k = 1; k < arguments.size(); k++) { - String argName = f.getStringArgument(k); - String term = (String) termMap.get(argName); - term = StringUtil.removeEnclosingQuotes(term); - String argNum = "%" + String.valueOf(k); + argName = f.getStringArgument(k); + sTerm = (String) termMap.get(argName); + sTerm = StringUtil.removeEnclosingQuotes(sTerm); + argNum = "%" + String.valueOf(k); // also, add the SUMO Concept that is replaced in the format if (displayText.contains(argNum)) { sb.append(argName); sb.append(","); - displayText = displayText.replace(argNum, term); + displayText = displayText.replace(argNum, sTerm); } } sb.append(displayText); @@ -956,20 +956,11 @@ public static void writeDisplayText(KB kb, String displayFormatPredicate, String } } } - - } - catch (java.io.IOException e) { - System.out.println(e.getMessage()); - e.printStackTrace(); } - catch (Exception e) { - System.out.println(e.getMessage()); + catch (IOException e) { + System.err.println(e.getMessage()); e.printStackTrace(); } - finally { - if (pr != null) - pr.close(); - } } /** ************************************************************* @@ -982,6 +973,7 @@ public static void generateTPTPTestAssertions() { KBmanager.getMgr().initializeOnce(); KB kb = KBmanager.getMgr().getKB(KBmanager.getMgr().getPref("sumokbname")); System.out.println("INFO in KB.generateTPTPTestAssertions(): printing predicates"); + String argType1, argType2; for (String term : kb.terms) { if (Character.isLowerCase(term.charAt(0)) && kb.kbCache.valences.get(term) <= 2) { /* @@ -995,8 +987,8 @@ public static void generateTPTPTestAssertions() { System.out.print("(instance Bar " + type + ")"); } */ - String argType1 = kb.getArgType(term,1); - String argType2 = kb.getArgType(term,2); + argType1 = kb.getArgType(term,1); + argType2 = kb.getArgType(term,2); if (argType1 != null && argType2 != null) { System.out.print("fof(local_" + counter++ + ",axiom,(s__" + term + "(s__Foo,s__Bar))).|"); System.out.print("fof(local_" + counter++ + ",axiom,(s__instance(s__Foo,s__" + argType1 + "))).|"); @@ -1006,7 +998,7 @@ public static void generateTPTPTestAssertions() { } } catch (Exception e) { - System.out.println(e.getMessage()); + System.err.println(e.getMessage()); } } @@ -1026,7 +1018,7 @@ public static void generateRelationList() { } } catch (Exception e) { - System.out.println(e.getMessage()); + System.err.println(e.getMessage()); } } @@ -1042,7 +1034,7 @@ public static int getCountNonLinguisticAxioms(KB kb) { HashSet forms = new HashSet<>(); forms.addAll(kb.formulaMap.values()); for (Formula f : forms) { - if (!rels.contains(f.getArgument(0))) + if (!rels.contains(f.getArgument(0).toString())) counter++; } return counter; @@ -1055,15 +1047,18 @@ public static void countStringWords(KB kb) { int total = 0; System.out.println("INFO in KB.countStringWords(): counting words"); - Iterator it = kb.formulas.keySet().iterator(); - while (it.hasNext()) { - String s = it.next(); - Pattern p = Pattern.compile("\"(.+)\""); - Matcher m = p.matcher(s); - boolean b = m.find(); + Pattern p; + Matcher m; + boolean b; + String quoted; + String[] ar; + for (String s : kb.formulas.keySet()) { + p = Pattern.compile("\"(.+)\""); + m = p.matcher(s); + b = m.find(); if (b) { - String quoted = m.group(1); - String[] ar = quoted.split(" "); + quoted = m.group(1); + ar = quoted.split(" "); for (int i = 0; i < ar.length-1; i++) { if (ar[i].matches("\\w+")) total++; @@ -1080,31 +1075,33 @@ public static void countStringWords(KB kb) { */ public static Set getAllFormulasOfTerm(KB kb, String term) { - HashSet result = new HashSet<>(); - Pattern pattern = Pattern.compile("(\\s|\\()" + term + "(\\s|\\))"); - for (String f : kb.formulaMap.keySet()){ - Matcher matcher = pattern.matcher(f); - if (matcher.find()) { - result.add(kb.formulaMap.get(f)); - } - } - return result; - } + HashSet result = new HashSet<>(); + Pattern pattern = Pattern.compile("(\\s|\\()" + term + "(\\s|\\))"); + for (String f : kb.formulaMap.keySet()){ + Matcher matcher = pattern.matcher(f); + if (matcher.find()) { + result.add(kb.formulaMap.get(f)); + } + } + return result; + } /** ************************************************************* * Find all formulas in which the SUMO term is involved. */ public static String generateFormulasAndDoc(KB kb) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); + String doc; + Set allForms; for (String t : kb.terms) { - String doc = getDocumentation(kb,t); + doc = getDocumentation(kb,t); if (!StringUtil.emptyString(doc)) { - Set allForms = getAllFormulasOfTerm(kb,t); - sb.append("!!doc " + doc + "\n"); + allForms = getAllFormulasOfTerm(kb,t); + sb.append("!!doc ").append(doc).append("\n"); for (Formula f : allForms) { if (!FormulaUtil.isDoc(f)) - sb.append(f.toString() + "\n"); + sb.append(f.toString()).append("\n"); } } } @@ -1116,13 +1113,14 @@ public static String generateFormulasAndDoc(KB kb) { */ public static String termFormatIndex(KB kb) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); ArrayList forms = kb.ask("arg", 0, "termFormat"); + String term, str; for (Formula f : forms) { - String term = f.getStringArgument(2); - String str = f.getStringArgument(3); + term = f.getStringArgument(2); + str = f.getStringArgument(3); if (!StringUtil.emptyString(term) && ! StringUtil.emptyString((str))) - sb.append(term + "\t" + str + "\n"); + sb.append(term).append("\t").append(str).append("\n"); } return sb.toString(); } @@ -1133,12 +1131,11 @@ public static String termFormatIndex(KB kb) { */ public static void genAllDoc(KB kb, String fname) { - PrintWriter pr = null; ArrayList al = kb.ask("arg",0,"documentation"); - try { - pr = new PrintWriter(new FileWriter(fname, false)); + try (PrintWriter pr = new PrintWriter(new FileWriter(fname, false))) { + String arg; for (Formula form : al) { - String arg = form.getArgument(3).toString(); + arg = form.getArgument(3).toString(); arg = arg.replace("&%", ""); pr.println(form.getArgument(1) + "\t" + arg); } @@ -1157,8 +1154,9 @@ public static void genDoc(KB kb, String fname) { System.out.println(genDocHeader(true)); ArrayList al = kb.ask("arg",0,"documentation"); for (Formula form : al) { + String arg; if (form.sourceFile.endsWith(fname)) { - String arg = form.getArgument(3).toString(); + arg = form.getArgument(3).toString(); arg = arg.replace("&%",""); System.out.println(form.getArgument(1) + "\t" + arg); } @@ -1181,16 +1179,16 @@ private static ArrayList genAscii() { */ private static String genDocHeader(boolean onePage) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("

Data Dictionary

"); ArrayList ascii = genAscii(); if (onePage) { for (String s : ascii) - sb.append("" + s + "  "); + sb.append("").append(s).append("  "); } else for (String s : ascii) { - sb.append("" + s + "  "); + sb.append("").append(s).append("  "); } sb.append("

\n"); sb.append("\n"); @@ -1204,17 +1202,13 @@ private static TreeMap genHTMLDocFiles(KB kb) { String head = genDocHeader(false); TreeMap files = new TreeMap<>(); ArrayList ascii = genAscii(); - FileWriter fw = null; - PrintWriter pw = null; for (String s : ascii) { - try { - fw = new FileWriter(s + "dict.html"); - pw = new PrintWriter(fw); + try (FileWriter fw = new FileWriter(s + "dict.html"); PrintWriter pw = new PrintWriter(fw)) { pw.println(head + "\n"); files.put(s,pw); } catch (Exception e) { - System.out.println(e.getMessage()); + System.err.println(e.getMessage()); e.printStackTrace(); } } @@ -1228,9 +1222,10 @@ private static TreeMap genDocList(KB kb) { ArrayList al = kb.ask("arg",0,"documentation"); TreeMap map = new TreeMap<>(); + String arg2; for (Formula form : al) { if (form.getArgument(2).toString().equals("EnglishLanguage")) { - String arg2 = form.getArgument(3).toString(); + arg2 = form.getArgument(3).toString(); //arg = arg.replace("&%",""); String arg1 = form.getArgument(1).toString(); arg2 = StringUtil.removeEnclosingQuotes(kb.formatStaticDocumentation(arg2, "EnglishLanguage", true)); @@ -1247,10 +1242,9 @@ private static TreeMap genDocList(KB kb) { private static void closeDocList(TreeMap files) { for (String term : files.keySet()) { - PrintWriter pw = files.get(term); - pw.println("
TermDoc
\n"); - pw.flush(); - pw.close(); + try (PrintWriter pw = files.get(term)) { + pw.println("\n"); + } } } @@ -1273,10 +1267,10 @@ public static List getLabelsForTerm(KB kb, String term, String lang) { private static String htmlForDoc(KB kb, String term, String lang, String doc, boolean noSUMO, boolean coreTerm) { List labels = getLabelsForTerm(kb,term,lang); - StringBuffer sb = new StringBuffer(); - sb.append("" + term + ""); + StringBuilder sb = new StringBuilder(); + sb.append("").append(term).append(""); for (String s : labels) - sb.append(s + ", "); + sb.append(s).append(", "); sb.delete(sb.length()-2,sb.length()); sb.append(""); if (coreTerm) @@ -1287,7 +1281,7 @@ private static String htmlForDoc(KB kb, String term, String lang, String doc, bo sb.append(doc); if (!noSUMO) { sb.append("[and full SUMO definition]"); + sb.append(term).append("\">full SUMO definition]"); } sb.append("\n"); return sb.toString(); @@ -1298,7 +1292,7 @@ private static String htmlForDoc(KB kb, String term, String lang, String doc, bo */ private static String genDocLine(boolean shade, KB kb, String term, String lang, String doc, boolean noSUMO, boolean coreTerm) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); if (shade) sb.append(""); else @@ -1336,15 +1330,16 @@ public static void genAllHTMLDoc(KB kb) { System.out.println("\n"); TreeMap map = genDocList(kb); boolean shade = false; + String arg2; for (String term : map.keySet()) { - String arg2 = map.get(term); + arg2 = map.get(term); if (shade) System.out.println("
TermDoc
"); else System.out.println("
"); // (KB kb, String term, String lang, String doc, boolean noSUMO, boolean coreTerm) System.out.println(htmlForDoc(kb,term,"EnglishLanguage",arg2,false,false)); - shade = ! shade; + shade = !shade; } System.out.println("
\n"); } @@ -1370,18 +1365,20 @@ public static void genSpecificTermDoc(KB kb, String file, String lang) { System.out.println("\n"); TreeMap map = genDocList(kb); boolean shade = false; + List links; + String arg2; for (String term : map.keySet()) { if (!lines.contains(term)) continue; - List links = getLinkedTermsInDoc(kb,term); // empty list if none + links = getLinkedTermsInDoc(kb,term); // empty list if none aux.addAll(links); - String arg2 = map.get(term); + arg2 = map.get(term); if (shade) System.out.println("
Termlabelin List or AuxDoc
"); else System.out.println("
"); System.out.println(htmlForDoc(kb,term,"EnglishLanguage",arg2,false,true)); - shade = ! shade; + shade = !shade; } System.out.println("
\n"); } @@ -1395,9 +1392,9 @@ public static Map> mergeToMap(Map> map1, Map> map2, KB kb) { Map> result = new HashMap<>(map1); - + Set value; for (String key : map2.keySet()) { - Set value = new HashSet(); + value = new HashSet<>(); if (result.containsKey(key)) { value = result.get(key); } @@ -1510,9 +1507,9 @@ else if (args != null && args.length > 1 && args[0].equals("-v")) { else if (args != null && args.length > 1 && args[0].equals("-a")) { SUMOtoTFAform.initOnce(); Formula f = new Formula(StringUtil.removeEnclosingQuotes(args[1])); - f.debug = true; + Formula.debug = true; System.out.println("higherOrder : " + f.isHigherOrder(kb)); - f.debug = false; + Formula.debug = false; System.out.println("isFunctional : " + f.isFunctional); System.out.println("isGround : " + f.isGround); System.out.println("termCache : " + f.termCache); diff --git a/src/java/com/articulate/sigma/KIF.java b/src/java/com/articulate/sigma/KIF.java index 0b5cfc01..d5a35867 100644 --- a/src/java/com/articulate/sigma/KIF.java +++ b/src/java/com/articulate/sigma/KIF.java @@ -112,7 +112,7 @@ public long getKIFFileSize(String filename) { try { File f = new File(filename); if (!f.exists()) { - System.out.println("KIF.getKIFFileSize(): error file " + filename + " does not exist"); + System.err.println("KIF.getKIFFileSize(): error file " + filename + " does not exist"); return 0; } return f.length(); @@ -137,7 +137,6 @@ public int getParseMode() { * * @param mode * An integer value denoting a parsing mode. - * @return void */ public void setParseMode(int mode) { @@ -235,7 +234,7 @@ public TreeSet parse(Reader r) { // int lineStart = 0; boolean isEOL = false; ArrayList list; - String key, fstr; + String key, fstr, validArgs; do { lastVal = st.ttype; st.nextToken(); @@ -300,7 +299,7 @@ else if (st.ttype == 41) { // ) - close paren duplicateCount++; } if (mode == NORMAL_PARSE_MODE) { // Check arg validity ONLY in NORMAL_PARSE_MODE - String validArgs = f.validArgs((file != null ? file.getName() : null), + validArgs = f.validArgs((file != null ? file.getName() : null), (file != null ? f.startLine : null)); if (StringUtil.emptyString(validArgs)) validArgs = f.badQuantification(); @@ -532,7 +531,7 @@ public void writeFile(String fname) { pr.println(it.next().getFormula()); } catch (Exception ex) { - System.out.println(ex.getMessage()); + System.err.println(ex.getMessage()); ex.printStackTrace(); } } diff --git a/src/java/com/articulate/sigma/KIFAST.java b/src/java/com/articulate/sigma/KIFAST.java index aa5a25b6..b7b12259 100644 --- a/src/java/com/articulate/sigma/KIFAST.java +++ b/src/java/com/articulate/sigma/KIFAST.java @@ -15,10 +15,10 @@ public class KIFAST { public static int count = 0; /** The set of all terms in the knowledge base. This is a set of Strings. */ - public TreeSet terms = new TreeSet(); + public TreeSet terms = new TreeSet<>(); /** A hashMap to store term frequencies for each term in knowledge base */ - public Map termFrequency = new HashMap(); + public Map termFrequency = new HashMap<>(); /** * A HashMap of ArrayLists of Formulas. Each String key points to a list of @@ -35,16 +35,16 @@ public class KIFAST { * Formula that is that string, along with information about at what line * number and in what file it appears. */ - public HashMap formulaMap = new HashMap(); + public HashMap formulaMap = new HashMap<>(); public String filename; private File file; private int totalLinesForComments = 0; /** warnings generated during parsing */ - public TreeSet warningSet = new TreeSet(); + public TreeSet warningSet = new TreeSet<>(); /** errors generated during parsing */ - public TreeSet errorSet = new TreeSet(); + public TreeSet errorSet = new TreeSet<>(); /**************************************************************** * Read a KIF file. @@ -54,20 +54,18 @@ public class KIFAST { public TreeSet readFile(String fname) throws Exception { TreeSet warnings = new TreeSet<>(); - FileReader fr = null; Exception exThr = null; - try { - this.file = new File(fname); - if (!this.file.exists()) { - String errString = " error file " + fname + "does not exist"; - KBmanager.getMgr() - .setError(KBmanager.getMgr().getError() + "\n
" + errString + "\n
"); - System.out.println("Error in KIF.readFile(): " + errString); - return null; - } - this.filename = file.getCanonicalPath(); - fr = new FileReader(file); - BufferedReader br = new BufferedReader(fr); + this.file = new File(fname); + if (!this.file.exists()) { + String errString = " error file " + fname + "does not exist"; + KBmanager.getMgr() + .setError(KBmanager.getMgr().getError() + "\n
" + errString + "\n
"); + System.out.println("Error in KIF.readFile(): " + errString); + return null; + } + this.filename = file.getCanonicalPath(); + try (FileReader fr = new FileReader(file); + BufferedReader br = new BufferedReader(fr)) { if (br == null) { String errStr = "No Input Reader Specified"; warningSet.add(errStr); @@ -86,15 +84,6 @@ public TreeSet readFile(String fname) throws Exception { KBmanager.getMgr() .setError(KBmanager.getMgr().getError() + "\n
" + er + " in file " + fname + "\n
"); } - finally { - if (fr != null) { - try { - fr.close(); - } - catch (Exception ex2) { - } - } - } if (exThr != null) throw exThr; return warnings; @@ -107,11 +96,11 @@ public TreeSet readFile(String fname) throws Exception { public TreeSet parseBody(String s, int startLine, int endLine) { int lastVal; - String errStr = null; + String errStr; int parenLevel = 0; String errStart = "Parsing error in " + filename; StringBuffer sb = new StringBuffer(); - FormulaAST fast = new FormulaAST(); +// FormulaAST fast = new FormulaAST(); System.out.println("parseBody: " + s); Reader r = new StringReader(s); StreamTokenizer_s st = new StreamTokenizer_s(r); @@ -120,52 +109,57 @@ public TreeSet parseBody(String s, int startLine, int endLine) { do { lastVal = st.ttype; st.nextToken(); - if (st.ttype == 40) { // Open paren - parenLevel++; - if ((parenLevel != 0) && (lastVal != 40) && (sb.length() > 0)) - sb.append(" "); // add back whitespace that ST removes - sb.append("("); - } - else if (st.ttype == 41) { // ) - close paren - parenLevel--; - sb.append(")"); - if (parenLevel == 0) { // The end of the statement... - if (formulaMap.keySet().contains(sb.toString()) && !KBmanager.getMgr().getPref("reportDup").equals("no")) { - String warning = ("Duplicate axiom at line: " + startLine + " of " + filename + ": " + sb); - warningSet.add(warning); - System.out.println(warning); + switch (st.ttype) { + case 40: + // Open paren + parenLevel++; + if ((parenLevel != 0) && (lastVal != 40) && (sb.length() > 0)) + sb.append(" "); // add back whitespace that ST removes + sb.append("("); + break; + case 41: + // ) - close paren + parenLevel--; + sb.append(")"); + if (parenLevel == 0) { // The end of the statement... + if (formulaMap.keySet().contains(sb.toString()) && !KBmanager.getMgr().getPref("reportDup").equals("no")) { + String warning = ("Duplicate axiom at line: " + startLine + " of " + filename + ": " + sb); + warningSet.add(warning); + System.out.println(warning); + } + warningSet.addAll(parseBody(sb.toString(),startLine,endLine)); // <--- call parseBody() + sb = new StringBuffer(); } - warningSet.addAll(parseBody(sb.toString(),startLine,endLine)); // <--- call parseBody() - sb = new StringBuffer(); - } - else if (parenLevel < 0) { - errStr = (errStart + ": Extra closing parenthesis found near line: " + startLine); - errorSet.add(errStr); - throw new ParseException(errStr, startLine); - } - } - else if (st.ttype == 34) { // " - it's a string - st.sval = StringUtil.escapeQuoteChars(st.sval); - if (lastVal != 40) // add back whitespace that ST removes - sb.append(" "); - sb.append("\""); - String com = st.sval; - sb.append(com); - sb.append("\""); - } - else { - if (lastVal != 40) // add back whitespace that ST removes - sb.append(" "); - sb.append(st.sval); + else if (parenLevel < 0) { + errStr = (errStart + ": Extra closing parenthesis found near line: " + startLine); + errorSet.add(errStr); + throw new ParseException(errStr, startLine); + } + break; + case 34: + // " - it's a string + st.sval = StringUtil.escapeQuoteChars(st.sval); + if (lastVal != 40) // add back whitespace that ST removes + sb.append(" "); + sb.append("\""); + String com = st.sval; + sb.append(com); + sb.append("\""); + break; + default: + if (lastVal != 40) // add back whitespace that ST removes + sb.append(" "); + sb.append(st.sval); + break; } } while (st.ttype != StreamTokenizer.TT_EOF); } - catch (Exception ex) { - String message = ex.getMessage().replaceAll(":", "&58;"); // HTMLformatter.formatErrors depends on : + catch (IOException | ParseException ex) { + String message = ex.getMessage().replaceAll(":", ":"); // HTMLformatter.formatErrors depends on : warningSet.add("Warning in KIFAST.parseBody() " + message); ex.printStackTrace(); } - return new TreeSet(); + return new TreeSet<>(); } /***************************************************************** @@ -178,12 +172,12 @@ public TreeSet parseNew(StreamTokenizer_s st) { String errStr = null; TreeSet warnings = new TreeSet<>(); - char ch; +// char ch; boolean isEOL = false; int lastVal; - int lineNum = 0; +// int lineNum = 0; int startLine = 0; - int endLine = 0; + int endLine; int parenLevel = 0; int duplicateCount = 0; String errStart = "Parsing error in " + filename; @@ -211,53 +205,58 @@ public TreeSet parseNew(StreamTokenizer_s st) { } else if (isEOL) isEOL = false; // Turn off isEOL if a non-EOL token encountered - if (st.ttype == 40) { // Open paren - if (parenLevel == 0) - startLine = st.lineno(); - parenLevel++; - if ((parenLevel != 0) && (lastVal != 40) && (sb.length() > 0)) - sb.append(" "); // add back whitespace that ST removes - sb.append("("); - } - else if (st.ttype == 41) { // ) - close paren - parenLevel--; - sb.append(")"); - if (parenLevel == 0) { // The end of the statement... - if (formulaMap.keySet().contains(sb.toString()) && !KBmanager.getMgr().getPref("reportDup").equals("no")) { - String warning = ("Duplicate axiom at line: " + startLine + " of " + filename + ": " + sb); - warningSet.add(warning); - System.out.println(warning); - duplicateCount++; + switch (st.ttype) { + case 40: + // Open paren + if (parenLevel == 0) + startLine = st.lineno(); + parenLevel++; + if ((parenLevel != 0) && (lastVal != 40) && (sb.length() > 0)) + sb.append(" "); // add back whitespace that ST removes + sb.append("("); + break; + case 41: + // ) - close paren + parenLevel--; + sb.append(")"); + if (parenLevel == 0) { // The end of the statement... + if (formulaMap.keySet().contains(sb.toString()) && !KBmanager.getMgr().getPref("reportDup").equals("no")) { + String warning = ("Duplicate axiom at line: " + startLine + " of " + filename + ": " + sb); + warningSet.add(warning); + System.out.println(warning); + duplicateCount++; + } + endLine = st.lineno() + totalLinesForComments; + warningSet.addAll(parseBody(sb.toString(),startLine,endLine)); // <--- call parseBody() + sb = new StringBuffer(); } - endLine = st.lineno() + totalLinesForComments; - warningSet.addAll(parseBody(sb.toString(),startLine,endLine)); // <--- call parseBody() - sb = new StringBuffer(); - } - else if (parenLevel < 0) { - errStr = (errStart + ": Extra closing parenthesis found near line: " + startLine); - errorSet.add(errStr); - throw new ParseException(errStr, startLine); - } - } - else if (st.ttype == 34) { // " - it's a string - st.sval = StringUtil.escapeQuoteChars(st.sval); - if (lastVal != 40) // add back whitespace that ST removes - sb.append(" "); - sb.append("\""); - String com = st.sval; - totalLinesForComments += StringUtil.countChar(com, (char) 0X0A); - sb.append(com); - sb.append("\""); - } - else { - if (lastVal != 40) // add back whitespace that ST removes - sb.append(" "); - sb.append(st.sval); + else if (parenLevel < 0) { + errStr = (errStart + ": Extra closing parenthesis found near line: " + startLine); + errorSet.add(errStr); + throw new ParseException(errStr, startLine); + } + break; + case 34: + // " - it's a string + st.sval = StringUtil.escapeQuoteChars(st.sval); + if (lastVal != 40) // add back whitespace that ST removes + sb.append(" "); + sb.append("\""); + String com = st.sval; + totalLinesForComments += StringUtil.countChar(com, (char) 0X0A); + sb.append(com); + sb.append("\""); + break; + default: + if (lastVal != 40) // add back whitespace that ST removes + sb.append(" "); + sb.append(st.sval); + break; } } while (st.ttype != StreamTokenizer.TT_EOF); } - catch (Exception ex) { - String message = ex.getMessage().replaceAll(":", "&58;"); // HTMLformatter.formatErrors depends on : + catch (IOException | ParseException ex) { + String message = ex.getMessage().replaceAll(":", ":"); // HTMLformatter.formatErrors depends on : warningSet.add("Warning in KIFAST.parse() " + message); ex.printStackTrace(); } @@ -281,7 +280,7 @@ else if (st.ttype == 34) { // " - it's a string */ public TreeSet parse(Reader r) { - Stack stack = new Stack<>(); +// Stack stack = new Stack<>(); StringBuilder expression = new StringBuilder(); int lastVal; FormulaAST f = new FormulaAST(); @@ -304,9 +303,11 @@ public TreeSet parse(Reader r) { int argumentNum = -1; boolean inAntecedent = false; boolean inConsequent = false; - HashSet keySet = new HashSet(); + HashSet keySet = new HashSet<>(); // int lineStart = 0; boolean isEOL = false; + String fstr, warning, validArgs; + ArrayList list; do { lastVal = st.ttype; st.nextToken(); @@ -358,17 +359,17 @@ else if (st.ttype == 41) { // ) - close paren parenLevel--; expression.append(")"); if (parenLevel == 0) { // The end of the statement... - String fstr = StringUtil.normalizeSpaceChars(expression.toString()); + fstr = StringUtil.normalizeSpaceChars(expression.toString()); f.read(fstr.intern()); if (formulaMap.keySet().contains(f.toString()) && !KBmanager.getMgr().getPref("reportDup").equals("no")) { - String warning = ("Duplicate axiom at line: " + f.startLine + " of " + f.sourceFile + ": " + warning = ("Duplicate axiom at line: " + f.startLine + " of " + f.sourceFile + ": " + expression); warningSet.add(warning); - System.out.println(warning); + System.err.println(warning); duplicateCount++; } - String validArgs = f.validArgs((file != null ? file.getName() : null), - (file != null ? Integer.valueOf(f.startLine) : null)); + validArgs = f.validArgs((file != null ? file.getName() : null), + (file != null ? f.startLine : null)); if (StringUtil.emptyString(validArgs)) validArgs = f.badQuantification(); if (StringUtil.isNonEmptyString(validArgs)) { @@ -380,23 +381,21 @@ else if (st.ttype == 41) { // ) - close paren keySet.add(f.toString()); // Make the formula itself a key keySet.add(f.createID()); f.endLine = st.lineno() + totalLinesForComments; - Iterator it = keySet.iterator(); - while (it.hasNext()) { // Add the expression but ... - String fkey = it.next(); + for (String fkey : keySet) { + // Add the expression but ... if (formulas.containsKey(fkey)) { if (!formulaMap.keySet().contains(f.toString())) { // don't add keys if formula is already present - ArrayList list = formulas.get(fkey); + list = formulas.get(fkey); if (StringUtil.emptyString(f.toString())) { System.out.println("Error in KIF.parse(): Storing empty formula from line: " + f.startLine); errorSet.add(errStr); } - else if (!list.contains(f.toString())) + else if (!list.contains(f)) list.add(f); } - } - else { - ArrayList list = new ArrayList<>(); + } else { + list = new ArrayList<>(); if (StringUtil.emptyString(f.toString())) { System.out.println( "Error in KIF.parse(): Storing empty formula from line: " + f.startLine); @@ -485,8 +484,8 @@ else if (st.ttype != StreamTokenizer.TT_EOF) { throw new ParseException(errStr, f.startLine); } } - catch (Exception ex) { - String message = ex.getMessage().replaceAll(":", "&58;"); // HTMLformatter.formatErrors depends on : + catch (IOException | ParseException ex) { + String message = ex.getMessage().replaceAll(":", ":"); // HTMLformatter.formatErrors depends on : warningSet.add("Warning in KIF.parse() " + message); ex.printStackTrace(); } diff --git a/src/java/com/articulate/sigma/ProofProcessor.java b/src/java/com/articulate/sigma/ProofProcessor.java index dd8ff43b..00ae2328 100644 --- a/src/java/com/articulate/sigma/ProofProcessor.java +++ b/src/java/com/articulate/sigma/ProofProcessor.java @@ -41,7 +41,7 @@ public class ProofProcessor { */ public ProofProcessor(ArrayList xmlInput) { - xml = new ArrayList(xmlInput); + xml = new ArrayList<>(xmlInput); } /** *************************************************************** @@ -51,7 +51,7 @@ public ProofProcessor(ArrayList xmlInput) { */ public boolean equalsAnswer(int answerNum, String expectedAnswer) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); ArrayList queryResponseElements = ((BasicXMLelement) xml.get(0)).subelements; BasicXMLelement answer = queryResponseElements.get(answerNum); if (((String) answer.attributes.get("result")).equalsIgnoreCase("no")) diff --git a/test/integration/java/com/articulate/sigma/KBmanagerInitIntegrationTest.java b/test/integration/java/com/articulate/sigma/KBmanagerInitIntegrationTest.java index 6dbb2a7b..aab0aa09 100644 --- a/test/integration/java/com/articulate/sigma/KBmanagerInitIntegrationTest.java +++ b/test/integration/java/com/articulate/sigma/KBmanagerInitIntegrationTest.java @@ -107,7 +107,7 @@ else if (fileName.startsWith("SUMO_")) { @Test public void testInitializationTime() { - assertTrue("Actual time = " + IntegrationTestBase.totalKbMgrInitTime, IntegrationTestBase.totalKbMgrInitTime < 110000); + assertTrue("Actual time = " + IntegrationTestBase.totalKbMgrInitTime, IntegrationTestBase.totalKbMgrInitTime < 120000); // Just in case something whacky is going on, make sure it's greater than some minimum, too. assertTrue("Actual time = " + IntegrationTestBase.totalKbMgrInitTime, IntegrationTestBase.totalKbMgrInitTime > 10000); } From cf9e4278732988fec2dfcdfa99dc73fab5201ee0 Mon Sep 17 00:00:00 2001 From: git Date: Wed, 8 Jan 2025 12:45:26 -0800 Subject: [PATCH 3/3] [Terry N.] restore previous work from Git clash over the holiday period. --- src/java/com/articulate/sigma/Formula.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/java/com/articulate/sigma/Formula.java b/src/java/com/articulate/sigma/Formula.java index 87abf174..fec1785c 100644 --- a/src/java/com/articulate/sigma/Formula.java +++ b/src/java/com/articulate/sigma/Formula.java @@ -1970,6 +1970,10 @@ public Set collectQuantifiedVariables() { return resultSet; Formula fcar = new Formula(); fcar.read(this.car()); + if (fcar.empty()) + return resultSet; + if (debug) + System.out.println("Formula.collectQuantifiedVariables(): car: " + fcar); if (fcar.theFormula.equals(UQUANT) || fcar.theFormula.equals(EQUANT)) { Formula remainder = new Formula(); remainder.read(this.cdr());