From 9ce65c5a963b03ee97fe9cb6c5aa65a3c04a80a8 Mon Sep 17 00:00:00 2001 From: yzhou Date: Tue, 21 Apr 2015 10:34:27 +0100 Subject: initial version --- .../ox/cs/pagoda/util/ConjunctiveQueryHelper.java | 70 +++++ src/uk/ac/ox/cs/pagoda/util/Namespace.java | 34 +++ src/uk/ac/ox/cs/pagoda/util/Properties.java | 95 +++++++ src/uk/ac/ox/cs/pagoda/util/Separator.java | 11 + src/uk/ac/ox/cs/pagoda/util/SparqlHelper.java | 313 +++++++++++++++++++++ src/uk/ac/ox/cs/pagoda/util/Timer.java | 52 ++++ src/uk/ac/ox/cs/pagoda/util/TurtleHelper.java | 56 ++++ src/uk/ac/ox/cs/pagoda/util/UFS.java | 45 +++ src/uk/ac/ox/cs/pagoda/util/Utility.java | 248 ++++++++++++++++ 9 files changed, 924 insertions(+) create mode 100644 src/uk/ac/ox/cs/pagoda/util/ConjunctiveQueryHelper.java create mode 100644 src/uk/ac/ox/cs/pagoda/util/Namespace.java create mode 100644 src/uk/ac/ox/cs/pagoda/util/Properties.java create mode 100644 src/uk/ac/ox/cs/pagoda/util/Separator.java create mode 100644 src/uk/ac/ox/cs/pagoda/util/SparqlHelper.java create mode 100644 src/uk/ac/ox/cs/pagoda/util/Timer.java create mode 100644 src/uk/ac/ox/cs/pagoda/util/TurtleHelper.java create mode 100644 src/uk/ac/ox/cs/pagoda/util/UFS.java create mode 100644 src/uk/ac/ox/cs/pagoda/util/Utility.java (limited to 'src/uk/ac/ox/cs/pagoda/util') diff --git a/src/uk/ac/ox/cs/pagoda/util/ConjunctiveQueryHelper.java b/src/uk/ac/ox/cs/pagoda/util/ConjunctiveQueryHelper.java new file mode 100644 index 0000000..937c2c4 --- /dev/null +++ b/src/uk/ac/ox/cs/pagoda/util/ConjunctiveQueryHelper.java @@ -0,0 +1,70 @@ +package uk.ac.ox.cs.pagoda.util; + +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedList; + +public class ConjunctiveQueryHelper { + + public static String[][] getAnswerVariables(String queryText) { + Collection disVars = new LinkedList(), undisVars = new LinkedList(); + for (String var: getAllVariables(queryText)) + if (var.startsWith("?")) disVars.add(var.substring(1)); + else undisVars.add(var.substring(2)); + + String[] distinguishedVariables = disVars.toArray(new String[0]); + String[] undistinguishedVariables = undisVars.toArray(new String[0]); + String[] answerVariables = null; + + String uppercase = queryText.toUpperCase(); + int selectIndex = uppercase.indexOf("SELECT"); + int whereIndex = uppercase.indexOf("WHERE"); + String selectClause = queryText.substring(selectIndex + 6, whereIndex); + if (selectClause.contains("*")) answerVariables = distinguishedVariables; + else { + String[] terms = selectClause.split(" "); + int num = 0; + for (int i = 0; i < terms.length; ++i) + if (terms[i].startsWith("?")) ++num; + answerVariables = new String[num]; + for (int i = 0, j = 0; i < terms.length; ++i) + if (terms[i].startsWith("?")) + answerVariables[j++] = terms[i].substring(1); + } + + if (answerVariables != distinguishedVariables) { + int index = 0; + for (; index < answerVariables.length; ++index) { + distinguishedVariables[index] = answerVariables[index]; + disVars.remove(answerVariables[index]); + } + for (String var: disVars) + distinguishedVariables[index++] = var; + } + + return new String[][] { answerVariables, distinguishedVariables, undistinguishedVariables }; + } + + private static Collection getAllVariables(String queryText) { + Collection vars = new HashSet(); + int start, end = 0; + char ch; + while ((start = queryText.indexOf("?", end)) != -1) { + end = start + 1; + while (end + 1 < queryText.length() && (ch = queryText.charAt(end + 1)) != '\n' && ch != ' ') + ++end; + vars.add(queryText.substring(start, end + 1)); + } + + end = 0; + while ((start = queryText.indexOf("_:", end)) != -1) { + end = start + 1; + while (end + 1 < queryText.length() && (ch = queryText.charAt(end + 1)) != '\n' && ch != ' ') + ++end; + vars.add(queryText.substring(start, end + 1)); + } + + return vars; + } + +} diff --git a/src/uk/ac/ox/cs/pagoda/util/Namespace.java b/src/uk/ac/ox/cs/pagoda/util/Namespace.java new file mode 100644 index 0000000..07c8ebd --- /dev/null +++ b/src/uk/ac/ox/cs/pagoda/util/Namespace.java @@ -0,0 +1,34 @@ +package uk.ac.ox.cs.pagoda.util; + +public class Namespace { + + public static final String RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + public static final String RDFS_NS = "http://www.w3.org/2000/01/rdf-schema#"; + public static final String OWL_NS = "http://www.w3.org/2002/07/owl#"; + public static final String XSD_NS = "http://www.w3.org/2001/XMLSchema#"; + public static final String SWRL_NS = "http://www.w3.org/2003/11/swrl#"; + public static final String SWRLB_NS = "http://www.w3.org/2003/11/swrlb#"; + public static final String SWRLX_NS = "http://www.w3.org/2003/11/swrlx#"; + public static final String RULEML_NS = "http://www.w3.org/2003/11/ruleml#"; + + public static final String RDF_TYPE_QUOTED = "<" + RDF_NS + "type>"; + public static final String RDF_TYPE = RDF_NS + "type"; + public static final String RDF_TYPE_ABBR = "rdf:type"; + + public static final String EQUALITY = OWL_NS + "sameAs"; + public static final String EQUALITY_QUOTED = "<" + EQUALITY + ">"; + public static final String EQUALITY_ABBR = "owl:sameAs"; + + public static final String INEQUALITY = OWL_NS + "differentFrom"; + public static final String INEQUALITY_ABBR = "owl:differentFrom"; + public static final String INEQUALITY_QUOTED = "<" + INEQUALITY + ">"; + + public static final String RDF_PLAIN_LITERAL = RDF_NS + "PlainLiteral"; + public static final String XSD_STRING = XSD_NS + "string"; + + public static final String PAGODA_ANONY = "http://www.cs.ox.ac.uk/PAGOdA/skolemised#"; + public static final String PAGODA_AUX = "http://www.cs.ox.ac.uk/PAGOdA/auxiliary#"; + public static final String KARMA_ANONY = "http://www.cs.ox.ac.uk/KARMA/anonymous"; + public static final String PAGODA_ORIGINAL = PAGODA_AUX + "Original"; + +} diff --git a/src/uk/ac/ox/cs/pagoda/util/Properties.java b/src/uk/ac/ox/cs/pagoda/util/Properties.java new file mode 100644 index 0000000..551f94f --- /dev/null +++ b/src/uk/ac/ox/cs/pagoda/util/Properties.java @@ -0,0 +1,95 @@ +package uk.ac.ox.cs.pagoda.util; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.HashMap; + +public class Properties { + + public static final String FILE_SEPARATOR = ";"; + +// switches +// public static final String reuseGapFile = "REUSE_GAP"; + public static final String toTrackProofs = "TO_TRACK"; + public static final String checkAnswers = "TO_CHECK_ANSWERS"; + public static final String redirectSysOut = "TO_REDIRECT_SYS_OUT"; + public static final String considerEqualities = "TO_CONSIDER_EQUALITIES"; + +// parameters + public static final String testcase = "TEST_CASE"; + public static final String typeOfLowerBounds = "TYPE_LOWER_BOUNDS"; + public static final String FULL_REASONER = "OWLREASONER"; + +// file locations + public static final String ontologyFile = "LOWER_T_FILE"; + public static final String importedData = "IMPORT"; + public static final String queryFile = "QUERY_FILE"; + +// auxiliary files +// public static final String auxiliaryDirectory = "AUXILIARY_DIRECTORY"; +// public static final String queryAnswerGapFile = "GAP_FILE"; +// public static final String lowerAnswerFile = "LOWER_ANSWER_FILE"; +// public static final String upperAnswerFile = "UPPER_ANSWER_FILE"; +// public static final String boundsGapFile = "BOUNDS_GAP_FILE"; +// public static final String fragmentFile = "FRAGMENT_FILE"; + + public static final String correspondence = "CORRESPONDENCE"; + + private HashMap param = new HashMap(); + + public static final String on = String.valueOf(true); + public static final String off = String.valueOf(false); + + public void reset() { + param.clear(); +// param.put(reuseGapFile, on); + param.put(toTrackProofs, on); + param.put(checkAnswers, on); + param.put(redirectSysOut, off); + param.put(considerEqualities, off); + } + + public Properties() { + reset(); + } + + public void addImportedFile(String additionalDataFile) { + if (additionalDataFile == null) return ; + String files = param.get(importedData); + StringBuilder sb = new StringBuilder(); + if (files != null) + sb.append(files).append(FILE_SEPARATOR); + sb.append(additionalDataFile); + param.put(importedData, sb.toString()); + } + + public void load(String file) throws IOException { + BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); + String line; + String tokens[]; + while ((line = Utility.readLine(reader)) != null) { + if (line.isEmpty() || line.startsWith("#")) + continue; + + tokens = line.split("="); + if (tokens[1].equals("on")) + set(tokens[0], String.valueOf(true)); + else if (tokens[1].equals("off")) + set(tokens[0], String.valueOf(false)); + else + set(tokens[0], tokens[1]); + } + reader.close(); + } + + public String get(String key) { + return param.get(key); + } + + public void set(String key, String value) { + param.put(key, value); + } + +} diff --git a/src/uk/ac/ox/cs/pagoda/util/Separator.java b/src/uk/ac/ox/cs/pagoda/util/Separator.java new file mode 100644 index 0000000..1e6ad9c --- /dev/null +++ b/src/uk/ac/ox/cs/pagoda/util/Separator.java @@ -0,0 +1,11 @@ +package uk.ac.ox.cs.pagoda.util; + +public class Separator { + + public static final String FILE = System.getProperty("file.separator"); + public static final String LINE = System.getProperty("line.separator"); + public static final String INDIVIDUAL = "\t"; + public static final String QUERY = "---------------------------------------------"; + + +} diff --git a/src/uk/ac/ox/cs/pagoda/util/SparqlHelper.java b/src/uk/ac/ox/cs/pagoda/util/SparqlHelper.java new file mode 100644 index 0000000..31838bc --- /dev/null +++ b/src/uk/ac/ox/cs/pagoda/util/SparqlHelper.java @@ -0,0 +1,313 @@ +package uk.ac.ox.cs.pagoda.util; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import org.semanticweb.HermiT.model.AnnotatedEquality; +import org.semanticweb.HermiT.model.AtLeastConcept; +import org.semanticweb.HermiT.model.Atom; +import org.semanticweb.HermiT.model.AtomicConcept; +import org.semanticweb.HermiT.model.AtomicDataRange; +import org.semanticweb.HermiT.model.AtomicRole; +import org.semanticweb.HermiT.model.Constant; +import org.semanticweb.HermiT.model.DLPredicate; +import org.semanticweb.HermiT.model.Equality; +import org.semanticweb.HermiT.model.Individual; +import org.semanticweb.HermiT.model.Inequality; +import org.semanticweb.HermiT.model.Term; +import org.semanticweb.HermiT.model.Variable; + +import uk.ac.ox.cs.pagoda.MyPrefixes; +import uk.ac.ox.cs.pagoda.hermit.RuleHelper; + +import com.hp.hpl.jena.graph.Node; +import com.hp.hpl.jena.query.Query; +import com.hp.hpl.jena.query.QueryFactory; +import com.hp.hpl.jena.sparql.core.TriplePath; +import com.hp.hpl.jena.sparql.core.Var; +import com.hp.hpl.jena.sparql.syntax.Element; +import com.hp.hpl.jena.sparql.syntax.ElementAssign; +import com.hp.hpl.jena.sparql.syntax.ElementBind; +import com.hp.hpl.jena.sparql.syntax.ElementData; +import com.hp.hpl.jena.sparql.syntax.ElementDataset; +import com.hp.hpl.jena.sparql.syntax.ElementExists; +import com.hp.hpl.jena.sparql.syntax.ElementFilter; +import com.hp.hpl.jena.sparql.syntax.ElementGroup; +import com.hp.hpl.jena.sparql.syntax.ElementMinus; +import com.hp.hpl.jena.sparql.syntax.ElementNamedGraph; +import com.hp.hpl.jena.sparql.syntax.ElementNotExists; +import com.hp.hpl.jena.sparql.syntax.ElementOptional; +import com.hp.hpl.jena.sparql.syntax.ElementPathBlock; +import com.hp.hpl.jena.sparql.syntax.ElementService; +import com.hp.hpl.jena.sparql.syntax.ElementSubQuery; +import com.hp.hpl.jena.sparql.syntax.ElementTriplesBlock; +import com.hp.hpl.jena.sparql.syntax.ElementUnion; +import com.hp.hpl.jena.sparql.syntax.ElementVisitor; + +public class SparqlHelper { + + public static String getSPARQLQuery(Atom[] atoms, String... vars) { + Set undistinguishedVars = new HashSet(); + for (int i = 0; i < atoms.length; ++i) { + atoms[i].getVariables(undistinguishedVars); + } + int xIndex = 1; + while (undistinguishedVars.contains(Variable.create("X" + xIndex))) ++xIndex; + + for (String var: vars) + if (var != null && !var.isEmpty()) + undistinguishedVars.remove(Variable.create(var)); + + StringBuffer buffer = new StringBuffer(); + if (vars.length > 0) + buffer.append("SELECT DISTINCT "); + else + buffer.append("SELECT *"); + for (int i = 0; i < vars.length; ++i) { + if (vars[i] != null && !vars[i].isEmpty()) + buffer.append("?").append(vars[i]).append(" "); + } + buffer.append( " WHERE {"); + for (Atom atom: atoms) + if (atom.getDLPredicate() instanceof AtLeastConcept) { + AtLeastConcept atLeast = (AtLeastConcept) atom.getDLPredicate(); + int number = atLeast.getNumber(); + for (int i = 0; i < number; ++i) { + Variable newVar = Variable.create("X" + (xIndex + i)); + + Atom tAtom; + if (atLeast.getOnRole() instanceof AtomicRole) + tAtom = Atom.create( + (AtomicRole) atLeast.getOnRole(), + atom.getArgument(0), + newVar); + else + tAtom = Atom.create( + (AtomicRole) atLeast.getOnRole().getInverse(), + newVar, + atom.getArgument(0)); + buffer.append(" "); + buffer.append(toSPARQLClause(tAtom, undistinguishedVars)); + buffer.append(" ."); + + if (!atLeast.getToConcept().equals(AtomicConcept.THING)) { + if (atLeast.getToConcept() instanceof AtomicConcept); + + tAtom = Atom.create((AtomicConcept) atLeast.getToConcept(), newVar); + buffer.append(" "); + buffer.append(toSPARQLClause(tAtom, undistinguishedVars)); + buffer.append(" ."); + } + } + + for (int i = 0; i < number; ++i) + for (int j = i + 1; j < number; ++j) { + Atom tAtom = Atom.create(Inequality.INSTANCE, Variable.create("X" + (xIndex + i)), Variable.create("X" + (xIndex + j))); + buffer.append(" "); + buffer.append(toSPARQLClause(tAtom, undistinguishedVars)); + buffer.append(" ."); + } + + xIndex += number; + } + else { + buffer.append(" "); + buffer.append(toSPARQLClause(atom, undistinguishedVars)); + buffer.append(" ."); + } + buffer.append(" ").append("}"); + return buffer.toString(); + } + + private static String toSPARQLClause(Atom atom, Set undisVars ) { + DLPredicate predicate = atom.getDLPredicate(); + String r, a, b; + + if (predicate instanceof Equality || predicate instanceof AnnotatedEquality) + atom = Atom.create(predicate = AtomicRole.create(Namespace.EQUALITY), atom.getArgument(0), atom.getArgument(1)); + else if (predicate instanceof Inequality) + atom = Atom.create(predicate = AtomicRole.create(Namespace.INEQUALITY), atom.getArgument(0), atom.getArgument(1)); + + if (predicate instanceof AtomicConcept) { + r = Namespace.RDF_TYPE_QUOTED; + a = MyPrefixes.PAGOdAPrefixes.getQuotedIRI(getName(atom.getArgument(0), undisVars)); + b = MyPrefixes.PAGOdAPrefixes.getQuotedIRI(RuleHelper.getText(predicate)); + } + else if (predicate instanceof AtomicRole) { + r = MyPrefixes.PAGOdAPrefixes.getQuotedIRI(RuleHelper.getText(predicate)); + a = MyPrefixes.PAGOdAPrefixes.getQuotedIRI(getName(atom.getArgument(0), undisVars)); + b = MyPrefixes.PAGOdAPrefixes.getQuotedIRI(getName(atom.getArgument(1), undisVars)); + } + else if (predicate instanceof AtomicDataRange) { + r = Namespace.RDF_TYPE_QUOTED; + a = MyPrefixes.PAGOdAPrefixes.getQuotedIRI(getName(atom.getArgument(0), undisVars)); + b = MyPrefixes.PAGOdAPrefixes.getQuotedIRI(RuleHelper.getText(predicate)); + } + else { + Utility.logError("error!!!!!!!!!!!"); + return null; + } + + return a + " " + r + " " + b; + } + + private static String getName(Term t, Set undisVars) { + if (t instanceof Variable) + if (undisVars.contains(t)) + return "_:" + ((Variable) t).getName(); + else return "?" + ((Variable) t).getName(); + return MyPrefixes.PAGOdAPrefixes.abbreviateIRI(t.toString()); + } + + public static Query parse(String text, Collection vars, Collection atoms) { + Query query = QueryFactory.create(text); + if (vars != null) { + vars.clear(); + for (Var var: query.getProjectVars()) + vars.add(var.getName()); + } + ElementVisitor visitor = new MySparqlElementVisitor(atoms); + query.getQueryPattern().visit(visitor); + return query; + } + +} + +class MySparqlElementVisitor implements ElementVisitor { + + Collection atoms; + + public MySparqlElementVisitor(Collection atoms) { + this.atoms = atoms; + } + + @Override + public void visit(ElementSubQuery el) { + Utility.logError("ElmentSubQuery: " + el); + } + + @Override + public void visit(ElementService el) { + // TODO Auto-generated method stub + Utility.logError("ElementService: " + el); + } + + @Override + public void visit(ElementMinus el) { + // TODO Auto-generated method stub + Utility.logError("ElementMinus: " + el); + } + + @Override + public void visit(ElementNotExists el) { + // TODO Auto-generated method stub + Utility.logError("ElementNotExists: " + el); + } + + @Override + public void visit(ElementExists el) { + // TODO Auto-generated method stub + Utility.logError("ElementExists: " + el); + } + + @Override + public void visit(ElementNamedGraph el) { + // TODO Auto-generated method stub + Utility.logError("ElementNamedGraph: " + el); + } + + @Override + public void visit(ElementDataset el) { + // TODO Auto-generated method stub + Utility.logError("ElementDataset: " + el); + } + + @Override + public void visit(ElementGroup el) { + // TODO Auto-generated method stub + for (Element e: el.getElements()) + e.visit(this); + } + + @Override + public void visit(ElementOptional el) { + // TODO Auto-generated method stub + Utility.logError("ElementOptional: " + el); + } + + @Override + public void visit(ElementUnion el) { + // TODO Auto-generated method stub + Utility.logError("ElementUnion: " + el); + } + + @Override + public void visit(ElementBind el) { + // TODO Auto-generated method stub + Utility.logError("ElementBind: " + el); + } + + @Override + public void visit(ElementAssign el) { + // TODO Auto-generated method stub + Utility.logError("ElementAssign: " + el); + } + + @Override + public void visit(ElementFilter el) { + // TODO Auto-generated method stub + Utility.logError("ElementFilter: " + el); + } + + @Override + public void visit(ElementPathBlock el) { + // TODO Auto-generated method stub + for (TriplePath p: el.getPattern().getList()) { + if (p.getPredicate().isVariable()) { + AtomicRole r = AtomicRole.create("?" + p.getPredicate().getName()); + Term a = getTerm(p.getSubject()), b = getTerm(p.getObject()); + atoms.add(Atom.create(r, a, b)); + } + else if (p.getPredicate().getURI().equals(Namespace.RDF_TYPE) && !p.getObject().isVariable()) { + AtomicConcept A = AtomicConcept.create(p.getObject().getURI()); + Term c = getTerm(p.getSubject()); + atoms.add(Atom.create(A, c)); + } + else { + AtomicRole r = AtomicRole.create(p.getPredicate().getURI()); + Term a = getTerm(p.getSubject()), b = getTerm(p.getObject()); + atoms.add(Atom.create(r, a, b)); + } + } + } + + private Term getTerm(Node node) { + if (node.isVariable()) + return Variable.create(node.getName()); + if (node.isLiteral()) + if (node.getLiteralDatatypeURI() == null) + return Constant.create(node.getLiteralLexicalForm(), Namespace.XSD_STRING); + else + return Constant.create(node.getLiteralLexicalForm(), node.getLiteralDatatypeURI()); + + + if (node.isURI()) + return Individual.create(node.getURI()); + Utility.logError("unknown node: " + node); + return null; + } + + @Override + public void visit(ElementTriplesBlock el) { + // TODO Auto-generated method stub + + Utility.logError("ElementTriplesBlock: " + el); + } + + @Override + public void visit(ElementData el) { + // TODO Auto-generated method stub + + } +} \ No newline at end of file diff --git a/src/uk/ac/ox/cs/pagoda/util/Timer.java b/src/uk/ac/ox/cs/pagoda/util/Timer.java new file mode 100644 index 0000000..d1814a4 --- /dev/null +++ b/src/uk/ac/ox/cs/pagoda/util/Timer.java @@ -0,0 +1,52 @@ +package uk.ac.ox.cs.pagoda.util; + +public class Timer { + + double pastTime = 0; + boolean active = false; + + long startTime; + + public Timer() { + resume(); + } + + public void resume() { + if (active) return; + startTime = System.currentTimeMillis();; + active = true; + } + + public double duration() { + double time = pastTime; + if (active) + time += (System.currentTimeMillis() - startTime) / 1000.; + return time; + } + + public void pause() { + if (!active) return ; + pastTime = duration(); + active = false; + } + + public double reset() { + double ret = duration(); + pastTime = 0; + active = false; + resume(); + return ret; + } + + double timeout = -1; + + public boolean timeOut() { + if (timeout < 0) return false; + return duration() > timeout; + } + + public void setTimeout(double timeout) { + this.timeout = timeout; + } + +} diff --git a/src/uk/ac/ox/cs/pagoda/util/TurtleHelper.java b/src/uk/ac/ox/cs/pagoda/util/TurtleHelper.java new file mode 100644 index 0000000..6887b9f --- /dev/null +++ b/src/uk/ac/ox/cs/pagoda/util/TurtleHelper.java @@ -0,0 +1,56 @@ +package uk.ac.ox.cs.pagoda.util; + +import java.io.*; + +public class TurtleHelper { + + public static void simplify(String tempFile, String outputPath) throws IOException { + BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(tempFile))); + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputPath))); + + String line, sub = null, pred = null, obj = null; + char lastSymbol = '.', symbol; + String[] seg; + while ((line = reader.readLine()) != null) { + if (line.trim().isEmpty() || line.startsWith("#") || line.startsWith("@base")) + continue; + + if (line.startsWith("@")) { + writer.write(line); + writer.newLine(); + continue; + } + + + symbol = line.charAt(line.length() - 1); + + if (lastSymbol == '.') { + seg = line.split(" "); + sub = seg[0]; + pred = seg[1]; + obj = seg[2]; + } + else if (lastSymbol == ';') { + line = line.substring(sub.length() + 1); + seg = line.split(" "); + pred = seg[0]; + obj = seg[1]; + } + else if (lastSymbol == ',') { + line = line.substring(sub.length() + pred.length() + 2); + obj = line.substring(0, line.lastIndexOf(' ')); + } + else Utility.logError("ERROR"); + + lastSymbol = symbol; + if (pred.equals("rdf:type") && obj.startsWith("owl:")) + continue; + + writer.write(sub + " " + pred + " " + obj + " .\n"); + } + + reader.close(); + writer.close(); + } + +} diff --git a/src/uk/ac/ox/cs/pagoda/util/UFS.java b/src/uk/ac/ox/cs/pagoda/util/UFS.java new file mode 100644 index 0000000..0869fb7 --- /dev/null +++ b/src/uk/ac/ox/cs/pagoda/util/UFS.java @@ -0,0 +1,45 @@ +package uk.ac.ox.cs.pagoda.util; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class UFS { + + private Map groups = new HashMap(); + + public boolean merge(T t1, T t2) { + t1 = find(t1); t2 = find(t2); + if (t1.equals(t2)) return false; + if (t2.toString().contains("cs.ox.ac.uk")) + groups.put(t2, t1); + else + groups.put(t1, t2); + return true; + } + + public Set keySet() { + return groups.keySet(); + } + + public T find(T u) { + T v, w = u; + while ((v = groups.get(u)) != null) + u = v; + + while ((v = groups.get(w)) != null) { + groups.put(w, u); + w = v; + } + + return u; + } + + public void clear() { + groups.clear(); + } + + public boolean isEmpty() { + return groups.isEmpty(); + } +} diff --git a/src/uk/ac/ox/cs/pagoda/util/Utility.java b/src/uk/ac/ox/cs/pagoda/util/Utility.java new file mode 100644 index 0000000..120d463 --- /dev/null +++ b/src/uk/ac/ox/cs/pagoda/util/Utility.java @@ -0,0 +1,248 @@ +package uk.ac.ox.cs.pagoda.util; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.PrintStream; +import java.text.SimpleDateFormat; +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Scanner; +import java.util.Set; +import java.util.Stack; + +import org.apache.log4j.Logger; +import org.semanticweb.HermiT.model.Atom; + +public class Utility { + + private static final Logger LOGS = Logger.getLogger(""); + + public static final String JAVA_FILE_SEPARATOR = "/"; + public static final String FILE_SEPARATOR = System.getProperty("file.separator"); + public static final String LINE_SEPARATOR = System.getProperty("line.separator"); + + public static final String TempDirectory = (new File("tmp")).getAbsolutePath() + FILE_SEPARATOR; + + public static final int TEST = -1; + public static final int FLY = 0; + public static final int UOBM = 1; + public static final int LUBM = 2; + public static final int AEO = 3; + public static final int WINE = 4; + + public static Set toSet(Atom[] data) + { + HashSet ret = new HashSet(); + for (Atom element: data) + ret.add(element); + return ret; + } + + static Stack outs = new Stack(); + + static { + outs.push(System.out); + } + + public static boolean redirectSystemOut() + { + String stamp = new SimpleDateFormat( "HH:mm:ss").format(new Date()); + return redirectCurrentOut("./console" + stamp + ".txt"); + } + + public static boolean redirectCurrentOut(String fileName) + { + File file = new File(fileName); + PrintStream out; + try { + out = new PrintStream(new FileOutputStream(file)); + } catch (FileNotFoundException e) { + e.printStackTrace(); + return false; + } + outs.push(out); + System.setOut(out); + return true; + } + + public static void closeCurrentOut() { + if (!outs.isEmpty()) + outs.pop().close(); + + if (!outs.isEmpty()) + System.setOut(outs.peek()); + } + + public static void sparql2expression(String input, String output) throws IOException { + BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input))); + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output))); + boolean first; + String line, query; + while ((line = reader.readLine()) != null) { + if (line.startsWith("^")) { + for (int i = 0; i < 4; ++i) + line = reader.readLine(); + first = true; + query = ""; + while ((line = reader.readLine()) != null && !line.startsWith("}")) + if (first) { + first = false; + query = expression(line.trim()); + } + else query += ", " + expression(line.trim()); + writer.write(query); + writer.newLine(); + } + } + reader.close(); + writer.close(); + } + + private static String expression(String line) { + String[] parts = line.split(" "); + if (parts[1].equals("rdf:type")) { + return parts[2] + "(?" + variableIndex(parts[0]) + ")"; + } + else return parts[1] + "(?" + variableIndex(parts[0]) + ",?" + variableIndex(parts[2]) + ")"; + } + + private static int asciiX = (int)'X'; + + private static int variableIndex(String exp) { + char var = exp.charAt(1); + return (int)var - asciiX; + } + + public static String readLine(BufferedReader reader) throws IOException { + String line = reader.readLine(); + if (line == null) + return null; + return line.trim(); + } + + public static String getTextfromFile(String fileName) throws FileNotFoundException { + Scanner scanner = new Scanner(new File(fileName)); + String program = scanner.useDelimiter("\\Z").next(); + scanner.close(); + return program; + } + + public static String[] getPattern(BufferedReader answerReader) throws IOException { + String lastLine = readLine(answerReader), line; + while ((line = readLine(answerReader)) != null && !line.startsWith("---------")) + lastLine = line; + return lastLine.split(" "); + } + + public static void removeRecursively(File file) { + if (!file.exists()) return; + + if (file.isDirectory()) + for (File tFile: file.listFiles()) + removeRecursively(tFile); + file.delete(); + } + + public static void removeRecursively(String fileName) { + removeRecursively(new File(fileName)); + } + + public static Collection getQueryTexts(String fileName) throws IOException { + BufferedReader queryReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); + String line; + Collection queryTexts = new LinkedList(); + while (true) { + while ((line = queryReader.readLine()) != null && ((line = line.trim()).isEmpty() || line.startsWith("#"))); + if (line == null) { + queryReader.close(); + return queryTexts; + } + + StringBuffer query = new StringBuffer(); + if (!line.startsWith("^[")) + query.append(line).append(LINE_SEPARATOR); + + while ((line = queryReader.readLine()) != null && !line.trim().endsWith("}")) + query.append(line).append(LINE_SEPARATOR); + query.append(line); + queryTexts.add(query.toString()); + } + } + + /** + * + * @param answerReader + * @return all lines before the next empty line + * @throws IOException + */ + public static Collection getLines(BufferedReader answerReader) throws IOException { + Collection answerTuples = new LinkedList(); + String line; + while ((line = answerReader.readLine()) != null) { + line = line.trim(); + if (line.isEmpty()) + break; + answerTuples.add(line); + } + return answerTuples; + } + + private static StringBuilder logMessage = new StringBuilder(); + + private static String getLogMessage(Object[] messages) { + if (messages.length == 1) return messages[0].toString(); + else { + logMessage.setLength(0); + for (int i = 0; i < messages.length; ++i) { + if (logMessage.length() != 0) + logMessage.append(LINE_SEPARATOR); + logMessage.append(messages[i]); + } + return logMessage.toString(); + } + + } + + public static void logInfo(Object... messages) { + LOGS.info(getLogMessage(messages)); + } + + public static void logTrace(Object... messages) { + LOGS.trace(getLogMessage(messages)); + } + + public static void logDebug(Object... messages) { + LOGS.debug(getLogMessage(messages)); + } + + public static void logError(Object... messages) { + LOGS.error(getLogMessage(messages)); + } + + public static void initialise() { + File tmp = new File(TempDirectory); + if (!tmp.exists()) tmp.mkdirs(); + } + + public static void cleanup() { + File tmp = new File(TempDirectory); + if (tmp.exists()) tmp.delete(); + } + + public static String toFileIRI(String path) { + String iri; + if (path.startsWith(FILE_SEPARATOR)) iri = "file:" + path; + else iri = "file:\\\\\\" + path; + return iri.replace(FILE_SEPARATOR, JAVA_FILE_SEPARATOR).replace(" ", "%20"); + } + +} -- cgit v1.2.3