aboutsummaryrefslogtreecommitdiff
path: root/src/uk/ac/ox/cs/pagoda/util
diff options
context:
space:
mode:
authoryzhou <yujiao.zhou@gmail.com>2015-04-21 10:34:27 +0100
committeryzhou <yujiao.zhou@gmail.com>2015-04-21 10:34:27 +0100
commit9ce65c5a963b03ee97fe9cb6c5aa65a3c04a80a8 (patch)
tree47511c0fb89dccff0db4b5990522e04f294d795b /src/uk/ac/ox/cs/pagoda/util
parentb1ac207612ee8b045244253fb94b866104bc34f2 (diff)
downloadACQuA-9ce65c5a963b03ee97fe9cb6c5aa65a3c04a80a8.tar.gz
ACQuA-9ce65c5a963b03ee97fe9cb6c5aa65a3c04a80a8.zip
initial version
Diffstat (limited to 'src/uk/ac/ox/cs/pagoda/util')
-rw-r--r--src/uk/ac/ox/cs/pagoda/util/ConjunctiveQueryHelper.java70
-rw-r--r--src/uk/ac/ox/cs/pagoda/util/Namespace.java34
-rw-r--r--src/uk/ac/ox/cs/pagoda/util/Properties.java95
-rw-r--r--src/uk/ac/ox/cs/pagoda/util/Separator.java11
-rw-r--r--src/uk/ac/ox/cs/pagoda/util/SparqlHelper.java313
-rw-r--r--src/uk/ac/ox/cs/pagoda/util/Timer.java52
-rw-r--r--src/uk/ac/ox/cs/pagoda/util/TurtleHelper.java56
-rw-r--r--src/uk/ac/ox/cs/pagoda/util/UFS.java45
-rw-r--r--src/uk/ac/ox/cs/pagoda/util/Utility.java248
9 files changed, 924 insertions, 0 deletions
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 @@
1package uk.ac.ox.cs.pagoda.util;
2
3import java.util.Collection;
4import java.util.HashSet;
5import java.util.LinkedList;
6
7public class ConjunctiveQueryHelper {
8
9 public static String[][] getAnswerVariables(String queryText) {
10 Collection<String> disVars = new LinkedList<String>(), undisVars = new LinkedList<String>();
11 for (String var: getAllVariables(queryText))
12 if (var.startsWith("?")) disVars.add(var.substring(1));
13 else undisVars.add(var.substring(2));
14
15 String[] distinguishedVariables = disVars.toArray(new String[0]);
16 String[] undistinguishedVariables = undisVars.toArray(new String[0]);
17 String[] answerVariables = null;
18
19 String uppercase = queryText.toUpperCase();
20 int selectIndex = uppercase.indexOf("SELECT");
21 int whereIndex = uppercase.indexOf("WHERE");
22 String selectClause = queryText.substring(selectIndex + 6, whereIndex);
23 if (selectClause.contains("*")) answerVariables = distinguishedVariables;
24 else {
25 String[] terms = selectClause.split(" ");
26 int num = 0;
27 for (int i = 0; i < terms.length; ++i)
28 if (terms[i].startsWith("?")) ++num;
29 answerVariables = new String[num];
30 for (int i = 0, j = 0; i < terms.length; ++i)
31 if (terms[i].startsWith("?"))
32 answerVariables[j++] = terms[i].substring(1);
33 }
34
35 if (answerVariables != distinguishedVariables) {
36 int index = 0;
37 for (; index < answerVariables.length; ++index) {
38 distinguishedVariables[index] = answerVariables[index];
39 disVars.remove(answerVariables[index]);
40 }
41 for (String var: disVars)
42 distinguishedVariables[index++] = var;
43 }
44
45 return new String[][] { answerVariables, distinguishedVariables, undistinguishedVariables };
46 }
47
48 private static Collection<String> getAllVariables(String queryText) {
49 Collection<String> vars = new HashSet<String>();
50 int start, end = 0;
51 char ch;
52 while ((start = queryText.indexOf("?", end)) != -1) {
53 end = start + 1;
54 while (end + 1 < queryText.length() && (ch = queryText.charAt(end + 1)) != '\n' && ch != ' ')
55 ++end;
56 vars.add(queryText.substring(start, end + 1));
57 }
58
59 end = 0;
60 while ((start = queryText.indexOf("_:", end)) != -1) {
61 end = start + 1;
62 while (end + 1 < queryText.length() && (ch = queryText.charAt(end + 1)) != '\n' && ch != ' ')
63 ++end;
64 vars.add(queryText.substring(start, end + 1));
65 }
66
67 return vars;
68 }
69
70}
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 @@
1package uk.ac.ox.cs.pagoda.util;
2
3public class Namespace {
4
5 public static final String RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
6 public static final String RDFS_NS = "http://www.w3.org/2000/01/rdf-schema#";
7 public static final String OWL_NS = "http://www.w3.org/2002/07/owl#";
8 public static final String XSD_NS = "http://www.w3.org/2001/XMLSchema#";
9 public static final String SWRL_NS = "http://www.w3.org/2003/11/swrl#";
10 public static final String SWRLB_NS = "http://www.w3.org/2003/11/swrlb#";
11 public static final String SWRLX_NS = "http://www.w3.org/2003/11/swrlx#";
12 public static final String RULEML_NS = "http://www.w3.org/2003/11/ruleml#";
13
14 public static final String RDF_TYPE_QUOTED = "<" + RDF_NS + "type>";
15 public static final String RDF_TYPE = RDF_NS + "type";
16 public static final String RDF_TYPE_ABBR = "rdf:type";
17
18 public static final String EQUALITY = OWL_NS + "sameAs";
19 public static final String EQUALITY_QUOTED = "<" + EQUALITY + ">";
20 public static final String EQUALITY_ABBR = "owl:sameAs";
21
22 public static final String INEQUALITY = OWL_NS + "differentFrom";
23 public static final String INEQUALITY_ABBR = "owl:differentFrom";
24 public static final String INEQUALITY_QUOTED = "<" + INEQUALITY + ">";
25
26 public static final String RDF_PLAIN_LITERAL = RDF_NS + "PlainLiteral";
27 public static final String XSD_STRING = XSD_NS + "string";
28
29 public static final String PAGODA_ANONY = "http://www.cs.ox.ac.uk/PAGOdA/skolemised#";
30 public static final String PAGODA_AUX = "http://www.cs.ox.ac.uk/PAGOdA/auxiliary#";
31 public static final String KARMA_ANONY = "http://www.cs.ox.ac.uk/KARMA/anonymous";
32 public static final String PAGODA_ORIGINAL = PAGODA_AUX + "Original";
33
34}
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 @@
1package uk.ac.ox.cs.pagoda.util;
2
3import java.io.BufferedReader;
4import java.io.FileInputStream;
5import java.io.IOException;
6import java.io.InputStreamReader;
7import java.util.HashMap;
8
9public class Properties {
10
11 public static final String FILE_SEPARATOR = ";";
12
13// switches
14// public static final String reuseGapFile = "REUSE_GAP";
15 public static final String toTrackProofs = "TO_TRACK";
16 public static final String checkAnswers = "TO_CHECK_ANSWERS";
17 public static final String redirectSysOut = "TO_REDIRECT_SYS_OUT";
18 public static final String considerEqualities = "TO_CONSIDER_EQUALITIES";
19
20// parameters
21 public static final String testcase = "TEST_CASE";
22 public static final String typeOfLowerBounds = "TYPE_LOWER_BOUNDS";
23 public static final String FULL_REASONER = "OWLREASONER";
24
25// file locations
26 public static final String ontologyFile = "LOWER_T_FILE";
27 public static final String importedData = "IMPORT";
28 public static final String queryFile = "QUERY_FILE";
29
30// auxiliary files
31// public static final String auxiliaryDirectory = "AUXILIARY_DIRECTORY";
32// public static final String queryAnswerGapFile = "GAP_FILE";
33// public static final String lowerAnswerFile = "LOWER_ANSWER_FILE";
34// public static final String upperAnswerFile = "UPPER_ANSWER_FILE";
35// public static final String boundsGapFile = "BOUNDS_GAP_FILE";
36// public static final String fragmentFile = "FRAGMENT_FILE";
37
38 public static final String correspondence = "CORRESPONDENCE";
39
40 private HashMap<String, String> param = new HashMap<String, String>();
41
42 public static final String on = String.valueOf(true);
43 public static final String off = String.valueOf(false);
44
45 public void reset() {
46 param.clear();
47// param.put(reuseGapFile, on);
48 param.put(toTrackProofs, on);
49 param.put(checkAnswers, on);
50 param.put(redirectSysOut, off);
51 param.put(considerEqualities, off);
52 }
53
54 public Properties() {
55 reset();
56 }
57
58 public void addImportedFile(String additionalDataFile) {
59 if (additionalDataFile == null) return ;
60 String files = param.get(importedData);
61 StringBuilder sb = new StringBuilder();
62 if (files != null)
63 sb.append(files).append(FILE_SEPARATOR);
64 sb.append(additionalDataFile);
65 param.put(importedData, sb.toString());
66 }
67
68 public void load(String file) throws IOException {
69 BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
70 String line;
71 String tokens[];
72 while ((line = Utility.readLine(reader)) != null) {
73 if (line.isEmpty() || line.startsWith("#"))
74 continue;
75
76 tokens = line.split("=");
77 if (tokens[1].equals("on"))
78 set(tokens[0], String.valueOf(true));
79 else if (tokens[1].equals("off"))
80 set(tokens[0], String.valueOf(false));
81 else
82 set(tokens[0], tokens[1]);
83 }
84 reader.close();
85 }
86
87 public String get(String key) {
88 return param.get(key);
89 }
90
91 public void set(String key, String value) {
92 param.put(key, value);
93 }
94
95}
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 @@
1package uk.ac.ox.cs.pagoda.util;
2
3public class Separator {
4
5 public static final String FILE = System.getProperty("file.separator");
6 public static final String LINE = System.getProperty("line.separator");
7 public static final String INDIVIDUAL = "\t";
8 public static final String QUERY = "---------------------------------------------";
9
10
11}
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 @@
1package uk.ac.ox.cs.pagoda.util;
2
3import java.util.Collection;
4import java.util.HashSet;
5import java.util.Set;
6
7import org.semanticweb.HermiT.model.AnnotatedEquality;
8import org.semanticweb.HermiT.model.AtLeastConcept;
9import org.semanticweb.HermiT.model.Atom;
10import org.semanticweb.HermiT.model.AtomicConcept;
11import org.semanticweb.HermiT.model.AtomicDataRange;
12import org.semanticweb.HermiT.model.AtomicRole;
13import org.semanticweb.HermiT.model.Constant;
14import org.semanticweb.HermiT.model.DLPredicate;
15import org.semanticweb.HermiT.model.Equality;
16import org.semanticweb.HermiT.model.Individual;
17import org.semanticweb.HermiT.model.Inequality;
18import org.semanticweb.HermiT.model.Term;
19import org.semanticweb.HermiT.model.Variable;
20
21import uk.ac.ox.cs.pagoda.MyPrefixes;
22import uk.ac.ox.cs.pagoda.hermit.RuleHelper;
23
24import com.hp.hpl.jena.graph.Node;
25import com.hp.hpl.jena.query.Query;
26import com.hp.hpl.jena.query.QueryFactory;
27import com.hp.hpl.jena.sparql.core.TriplePath;
28import com.hp.hpl.jena.sparql.core.Var;
29import com.hp.hpl.jena.sparql.syntax.Element;
30import com.hp.hpl.jena.sparql.syntax.ElementAssign;
31import com.hp.hpl.jena.sparql.syntax.ElementBind;
32import com.hp.hpl.jena.sparql.syntax.ElementData;
33import com.hp.hpl.jena.sparql.syntax.ElementDataset;
34import com.hp.hpl.jena.sparql.syntax.ElementExists;
35import com.hp.hpl.jena.sparql.syntax.ElementFilter;
36import com.hp.hpl.jena.sparql.syntax.ElementGroup;
37import com.hp.hpl.jena.sparql.syntax.ElementMinus;
38import com.hp.hpl.jena.sparql.syntax.ElementNamedGraph;
39import com.hp.hpl.jena.sparql.syntax.ElementNotExists;
40import com.hp.hpl.jena.sparql.syntax.ElementOptional;
41import com.hp.hpl.jena.sparql.syntax.ElementPathBlock;
42import com.hp.hpl.jena.sparql.syntax.ElementService;
43import com.hp.hpl.jena.sparql.syntax.ElementSubQuery;
44import com.hp.hpl.jena.sparql.syntax.ElementTriplesBlock;
45import com.hp.hpl.jena.sparql.syntax.ElementUnion;
46import com.hp.hpl.jena.sparql.syntax.ElementVisitor;
47
48public class SparqlHelper {
49
50 public static String getSPARQLQuery(Atom[] atoms, String... vars) {
51 Set<Variable> undistinguishedVars = new HashSet<Variable>();
52 for (int i = 0; i < atoms.length; ++i) {
53 atoms[i].getVariables(undistinguishedVars);
54 }
55 int xIndex = 1;
56 while (undistinguishedVars.contains(Variable.create("X" + xIndex))) ++xIndex;
57
58 for (String var: vars)
59 if (var != null && !var.isEmpty())
60 undistinguishedVars.remove(Variable.create(var));
61
62 StringBuffer buffer = new StringBuffer();
63 if (vars.length > 0)
64 buffer.append("SELECT DISTINCT ");
65 else
66 buffer.append("SELECT *");
67 for (int i = 0; i < vars.length; ++i) {
68 if (vars[i] != null && !vars[i].isEmpty())
69 buffer.append("?").append(vars[i]).append(" ");
70 }
71 buffer.append( " WHERE {");
72 for (Atom atom: atoms)
73 if (atom.getDLPredicate() instanceof AtLeastConcept) {
74 AtLeastConcept atLeast = (AtLeastConcept) atom.getDLPredicate();
75 int number = atLeast.getNumber();
76 for (int i = 0; i < number; ++i) {
77 Variable newVar = Variable.create("X" + (xIndex + i));
78
79 Atom tAtom;
80 if (atLeast.getOnRole() instanceof AtomicRole)
81 tAtom = Atom.create(
82 (AtomicRole) atLeast.getOnRole(),
83 atom.getArgument(0),
84 newVar);
85 else
86 tAtom = Atom.create(
87 (AtomicRole) atLeast.getOnRole().getInverse(),
88 newVar,
89 atom.getArgument(0));
90 buffer.append(" ");
91 buffer.append(toSPARQLClause(tAtom, undistinguishedVars));
92 buffer.append(" .");
93
94 if (!atLeast.getToConcept().equals(AtomicConcept.THING)) {
95 if (atLeast.getToConcept() instanceof AtomicConcept);
96
97 tAtom = Atom.create((AtomicConcept) atLeast.getToConcept(), newVar);
98 buffer.append(" ");
99 buffer.append(toSPARQLClause(tAtom, undistinguishedVars));
100 buffer.append(" .");
101 }
102 }
103
104 for (int i = 0; i < number; ++i)
105 for (int j = i + 1; j < number; ++j) {
106 Atom tAtom = Atom.create(Inequality.INSTANCE, Variable.create("X" + (xIndex + i)), Variable.create("X" + (xIndex + j)));
107 buffer.append(" ");
108 buffer.append(toSPARQLClause(tAtom, undistinguishedVars));
109 buffer.append(" .");
110 }
111
112 xIndex += number;
113 }
114 else {
115 buffer.append(" ");
116 buffer.append(toSPARQLClause(atom, undistinguishedVars));
117 buffer.append(" .");
118 }
119 buffer.append(" ").append("}");
120 return buffer.toString();
121 }
122
123 private static String toSPARQLClause(Atom atom, Set<Variable> undisVars ) {
124 DLPredicate predicate = atom.getDLPredicate();
125 String r, a, b;
126
127 if (predicate instanceof Equality || predicate instanceof AnnotatedEquality)
128 atom = Atom.create(predicate = AtomicRole.create(Namespace.EQUALITY), atom.getArgument(0), atom.getArgument(1));
129 else if (predicate instanceof Inequality)
130 atom = Atom.create(predicate = AtomicRole.create(Namespace.INEQUALITY), atom.getArgument(0), atom.getArgument(1));
131
132 if (predicate instanceof AtomicConcept) {
133 r = Namespace.RDF_TYPE_QUOTED;
134 a = MyPrefixes.PAGOdAPrefixes.getQuotedIRI(getName(atom.getArgument(0), undisVars));
135 b = MyPrefixes.PAGOdAPrefixes.getQuotedIRI(RuleHelper.getText(predicate));
136 }
137 else if (predicate instanceof AtomicRole) {
138 r = MyPrefixes.PAGOdAPrefixes.getQuotedIRI(RuleHelper.getText(predicate));
139 a = MyPrefixes.PAGOdAPrefixes.getQuotedIRI(getName(atom.getArgument(0), undisVars));
140 b = MyPrefixes.PAGOdAPrefixes.getQuotedIRI(getName(atom.getArgument(1), undisVars));
141 }
142 else if (predicate instanceof AtomicDataRange) {
143 r = Namespace.RDF_TYPE_QUOTED;
144 a = MyPrefixes.PAGOdAPrefixes.getQuotedIRI(getName(atom.getArgument(0), undisVars));
145 b = MyPrefixes.PAGOdAPrefixes.getQuotedIRI(RuleHelper.getText(predicate));
146 }
147 else {
148 Utility.logError("error!!!!!!!!!!!");
149 return null;
150 }
151
152 return a + " " + r + " " + b;
153 }
154
155 private static String getName(Term t, Set<Variable> undisVars) {
156 if (t instanceof Variable)
157 if (undisVars.contains(t))
158 return "_:" + ((Variable) t).getName();
159 else return "?" + ((Variable) t).getName();
160 return MyPrefixes.PAGOdAPrefixes.abbreviateIRI(t.toString());
161 }
162
163 public static Query parse(String text, Collection<String> vars, Collection<Atom> atoms) {
164 Query query = QueryFactory.create(text);
165 if (vars != null) {
166 vars.clear();
167 for (Var var: query.getProjectVars())
168 vars.add(var.getName());
169 }
170 ElementVisitor visitor = new MySparqlElementVisitor(atoms);
171 query.getQueryPattern().visit(visitor);
172 return query;
173 }
174
175}
176
177class MySparqlElementVisitor implements ElementVisitor {
178
179 Collection<Atom> atoms;
180
181 public MySparqlElementVisitor(Collection<Atom> atoms) {
182 this.atoms = atoms;
183 }
184
185 @Override
186 public void visit(ElementSubQuery el) {
187 Utility.logError("ElmentSubQuery: " + el);
188 }
189
190 @Override
191 public void visit(ElementService el) {
192 // TODO Auto-generated method stub
193 Utility.logError("ElementService: " + el);
194 }
195
196 @Override
197 public void visit(ElementMinus el) {
198 // TODO Auto-generated method stub
199 Utility.logError("ElementMinus: " + el);
200 }
201
202 @Override
203 public void visit(ElementNotExists el) {
204 // TODO Auto-generated method stub
205 Utility.logError("ElementNotExists: " + el);
206 }
207
208 @Override
209 public void visit(ElementExists el) {
210 // TODO Auto-generated method stub
211 Utility.logError("ElementExists: " + el);
212 }
213
214 @Override
215 public void visit(ElementNamedGraph el) {
216 // TODO Auto-generated method stub
217 Utility.logError("ElementNamedGraph: " + el);
218 }
219
220 @Override
221 public void visit(ElementDataset el) {
222 // TODO Auto-generated method stub
223 Utility.logError("ElementDataset: " + el);
224 }
225
226 @Override
227 public void visit(ElementGroup el) {
228 // TODO Auto-generated method stub
229 for (Element e: el.getElements())
230 e.visit(this);
231 }
232
233 @Override
234 public void visit(ElementOptional el) {
235 // TODO Auto-generated method stub
236 Utility.logError("ElementOptional: " + el);
237 }
238
239 @Override
240 public void visit(ElementUnion el) {
241 // TODO Auto-generated method stub
242 Utility.logError("ElementUnion: " + el);
243 }
244
245 @Override
246 public void visit(ElementBind el) {
247 // TODO Auto-generated method stub
248 Utility.logError("ElementBind: " + el);
249 }
250
251 @Override
252 public void visit(ElementAssign el) {
253 // TODO Auto-generated method stub
254 Utility.logError("ElementAssign: " + el);
255 }
256
257 @Override
258 public void visit(ElementFilter el) {
259 // TODO Auto-generated method stub
260 Utility.logError("ElementFilter: " + el);
261 }
262
263 @Override
264 public void visit(ElementPathBlock el) {
265 // TODO Auto-generated method stub
266 for (TriplePath p: el.getPattern().getList()) {
267 if (p.getPredicate().isVariable()) {
268 AtomicRole r = AtomicRole.create("?" + p.getPredicate().getName());
269 Term a = getTerm(p.getSubject()), b = getTerm(p.getObject());
270 atoms.add(Atom.create(r, a, b));
271 }
272 else if (p.getPredicate().getURI().equals(Namespace.RDF_TYPE) && !p.getObject().isVariable()) {
273 AtomicConcept A = AtomicConcept.create(p.getObject().getURI());
274 Term c = getTerm(p.getSubject());
275 atoms.add(Atom.create(A, c));
276 }
277 else {
278 AtomicRole r = AtomicRole.create(p.getPredicate().getURI());
279 Term a = getTerm(p.getSubject()), b = getTerm(p.getObject());
280 atoms.add(Atom.create(r, a, b));
281 }
282 }
283 }
284
285 private Term getTerm(Node node) {
286 if (node.isVariable())
287 return Variable.create(node.getName());
288 if (node.isLiteral())
289 if (node.getLiteralDatatypeURI() == null)
290 return Constant.create(node.getLiteralLexicalForm(), Namespace.XSD_STRING);
291 else
292 return Constant.create(node.getLiteralLexicalForm(), node.getLiteralDatatypeURI());
293
294
295 if (node.isURI())
296 return Individual.create(node.getURI());
297 Utility.logError("unknown node: " + node);
298 return null;
299 }
300
301 @Override
302 public void visit(ElementTriplesBlock el) {
303 // TODO Auto-generated method stub
304
305 Utility.logError("ElementTriplesBlock: " + el);
306 }
307
308 @Override
309 public void visit(ElementData el) {
310 // TODO Auto-generated method stub
311
312 }
313} \ 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 @@
1package uk.ac.ox.cs.pagoda.util;
2
3public class Timer {
4
5 double pastTime = 0;
6 boolean active = false;
7
8 long startTime;
9
10 public Timer() {
11 resume();
12 }
13
14 public void resume() {
15 if (active) return;
16 startTime = System.currentTimeMillis();;
17 active = true;
18 }
19
20 public double duration() {
21 double time = pastTime;
22 if (active)
23 time += (System.currentTimeMillis() - startTime) / 1000.;
24 return time;
25 }
26
27 public void pause() {
28 if (!active) return ;
29 pastTime = duration();
30 active = false;
31 }
32
33 public double reset() {
34 double ret = duration();
35 pastTime = 0;
36 active = false;
37 resume();
38 return ret;
39 }
40
41 double timeout = -1;
42
43 public boolean timeOut() {
44 if (timeout < 0) return false;
45 return duration() > timeout;
46 }
47
48 public void setTimeout(double timeout) {
49 this.timeout = timeout;
50 }
51
52}
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 @@
1package uk.ac.ox.cs.pagoda.util;
2
3import java.io.*;
4
5public class TurtleHelper {
6
7 public static void simplify(String tempFile, String outputPath) throws IOException {
8 BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(tempFile)));
9 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputPath)));
10
11 String line, sub = null, pred = null, obj = null;
12 char lastSymbol = '.', symbol;
13 String[] seg;
14 while ((line = reader.readLine()) != null) {
15 if (line.trim().isEmpty() || line.startsWith("#") || line.startsWith("@base"))
16 continue;
17
18 if (line.startsWith("@")) {
19 writer.write(line);
20 writer.newLine();
21 continue;
22 }
23
24
25 symbol = line.charAt(line.length() - 1);
26
27 if (lastSymbol == '.') {
28 seg = line.split(" ");
29 sub = seg[0];
30 pred = seg[1];
31 obj = seg[2];
32 }
33 else if (lastSymbol == ';') {
34 line = line.substring(sub.length() + 1);
35 seg = line.split(" ");
36 pred = seg[0];
37 obj = seg[1];
38 }
39 else if (lastSymbol == ',') {
40 line = line.substring(sub.length() + pred.length() + 2);
41 obj = line.substring(0, line.lastIndexOf(' '));
42 }
43 else Utility.logError("ERROR");
44
45 lastSymbol = symbol;
46 if (pred.equals("rdf:type") && obj.startsWith("owl:"))
47 continue;
48
49 writer.write(sub + " " + pred + " " + obj + " .\n");
50 }
51
52 reader.close();
53 writer.close();
54 }
55
56}
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 @@
1package uk.ac.ox.cs.pagoda.util;
2
3import java.util.HashMap;
4import java.util.Map;
5import java.util.Set;
6
7public class UFS<T> {
8
9 private Map<T, T> groups = new HashMap<T, T>();
10
11 public boolean merge(T t1, T t2) {
12 t1 = find(t1); t2 = find(t2);
13 if (t1.equals(t2)) return false;
14 if (t2.toString().contains("cs.ox.ac.uk"))
15 groups.put(t2, t1);
16 else
17 groups.put(t1, t2);
18 return true;
19 }
20
21 public Set<T> keySet() {
22 return groups.keySet();
23 }
24
25 public T find(T u) {
26 T v, w = u;
27 while ((v = groups.get(u)) != null)
28 u = v;
29
30 while ((v = groups.get(w)) != null) {
31 groups.put(w, u);
32 w = v;
33 }
34
35 return u;
36 }
37
38 public void clear() {
39 groups.clear();
40 }
41
42 public boolean isEmpty() {
43 return groups.isEmpty();
44 }
45}
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 @@
1package uk.ac.ox.cs.pagoda.util;
2
3import java.io.BufferedReader;
4import java.io.BufferedWriter;
5import java.io.File;
6import java.io.FileInputStream;
7import java.io.FileNotFoundException;
8import java.io.FileOutputStream;
9import java.io.IOException;
10import java.io.InputStreamReader;
11import java.io.OutputStreamWriter;
12import java.io.PrintStream;
13import java.text.SimpleDateFormat;
14import java.util.Collection;
15import java.util.Date;
16import java.util.HashSet;
17import java.util.LinkedList;
18import java.util.Scanner;
19import java.util.Set;
20import java.util.Stack;
21
22import org.apache.log4j.Logger;
23import org.semanticweb.HermiT.model.Atom;
24
25public class Utility {
26
27 private static final Logger LOGS = Logger.getLogger("");
28
29 public static final String JAVA_FILE_SEPARATOR = "/";
30 public static final String FILE_SEPARATOR = System.getProperty("file.separator");
31 public static final String LINE_SEPARATOR = System.getProperty("line.separator");
32
33 public static final String TempDirectory = (new File("tmp")).getAbsolutePath() + FILE_SEPARATOR;
34
35 public static final int TEST = -1;
36 public static final int FLY = 0;
37 public static final int UOBM = 1;
38 public static final int LUBM = 2;
39 public static final int AEO = 3;
40 public static final int WINE = 4;
41
42 public static Set<Atom> toSet(Atom[] data)
43 {
44 HashSet<Atom> ret = new HashSet<Atom>();
45 for (Atom element: data)
46 ret.add(element);
47 return ret;
48 }
49
50 static Stack<PrintStream> outs = new Stack<PrintStream>();
51
52 static {
53 outs.push(System.out);
54 }
55
56 public static boolean redirectSystemOut()
57 {
58 String stamp = new SimpleDateFormat( "HH:mm:ss").format(new Date());
59 return redirectCurrentOut("./console" + stamp + ".txt");
60 }
61
62 public static boolean redirectCurrentOut(String fileName)
63 {
64 File file = new File(fileName);
65 PrintStream out;
66 try {
67 out = new PrintStream(new FileOutputStream(file));
68 } catch (FileNotFoundException e) {
69 e.printStackTrace();
70 return false;
71 }
72 outs.push(out);
73 System.setOut(out);
74 return true;
75 }
76
77 public static void closeCurrentOut() {
78 if (!outs.isEmpty())
79 outs.pop().close();
80
81 if (!outs.isEmpty())
82 System.setOut(outs.peek());
83 }
84
85 public static void sparql2expression(String input, String output) throws IOException {
86 BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
87 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
88 boolean first;
89 String line, query;
90 while ((line = reader.readLine()) != null) {
91 if (line.startsWith("^")) {
92 for (int i = 0; i < 4; ++i)
93 line = reader.readLine();
94 first = true;
95 query = "";
96 while ((line = reader.readLine()) != null && !line.startsWith("}"))
97 if (first) {
98 first = false;
99 query = expression(line.trim());
100 }
101 else query += ", " + expression(line.trim());
102 writer.write(query);
103 writer.newLine();
104 }
105 }
106 reader.close();
107 writer.close();
108 }
109
110 private static String expression(String line) {
111 String[] parts = line.split(" ");
112 if (parts[1].equals("rdf:type")) {
113 return parts[2] + "(?" + variableIndex(parts[0]) + ")";
114 }
115 else return parts[1] + "(?" + variableIndex(parts[0]) + ",?" + variableIndex(parts[2]) + ")";
116 }
117
118 private static int asciiX = (int)'X';
119
120 private static int variableIndex(String exp) {
121 char var = exp.charAt(1);
122 return (int)var - asciiX;
123 }
124
125 public static String readLine(BufferedReader reader) throws IOException {
126 String line = reader.readLine();
127 if (line == null)
128 return null;
129 return line.trim();
130 }
131
132 public static String getTextfromFile(String fileName) throws FileNotFoundException {
133 Scanner scanner = new Scanner(new File(fileName));
134 String program = scanner.useDelimiter("\\Z").next();
135 scanner.close();
136 return program;
137 }
138
139 public static String[] getPattern(BufferedReader answerReader) throws IOException {
140 String lastLine = readLine(answerReader), line;
141 while ((line = readLine(answerReader)) != null && !line.startsWith("---------"))
142 lastLine = line;
143 return lastLine.split(" ");
144 }
145
146 public static void removeRecursively(File file) {
147 if (!file.exists()) return;
148
149 if (file.isDirectory())
150 for (File tFile: file.listFiles())
151 removeRecursively(tFile);
152 file.delete();
153 }
154
155 public static void removeRecursively(String fileName) {
156 removeRecursively(new File(fileName));
157 }
158
159 public static Collection<String> getQueryTexts(String fileName) throws IOException {
160 BufferedReader queryReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
161 String line;
162 Collection<String> queryTexts = new LinkedList<String>();
163 while (true) {
164 while ((line = queryReader.readLine()) != null && ((line = line.trim()).isEmpty() || line.startsWith("#")));
165 if (line == null) {
166 queryReader.close();
167 return queryTexts;
168 }
169
170 StringBuffer query = new StringBuffer();
171 if (!line.startsWith("^["))
172 query.append(line).append(LINE_SEPARATOR);
173
174 while ((line = queryReader.readLine()) != null && !line.trim().endsWith("}"))
175 query.append(line).append(LINE_SEPARATOR);
176 query.append(line);
177 queryTexts.add(query.toString());
178 }
179 }
180
181 /**
182 *
183 * @param answerReader
184 * @return all lines before the next empty line
185 * @throws IOException
186 */
187 public static Collection<String> getLines(BufferedReader answerReader) throws IOException {
188 Collection<String> answerTuples = new LinkedList<String>();
189 String line;
190 while ((line = answerReader.readLine()) != null) {
191 line = line.trim();
192 if (line.isEmpty())
193 break;
194 answerTuples.add(line);
195 }
196 return answerTuples;
197 }
198
199 private static StringBuilder logMessage = new StringBuilder();
200
201 private static String getLogMessage(Object[] messages) {
202 if (messages.length == 1) return messages[0].toString();
203 else {
204 logMessage.setLength(0);
205 for (int i = 0; i < messages.length; ++i) {
206 if (logMessage.length() != 0)
207 logMessage.append(LINE_SEPARATOR);
208 logMessage.append(messages[i]);
209 }
210 return logMessage.toString();
211 }
212
213 }
214
215 public static void logInfo(Object... messages) {
216 LOGS.info(getLogMessage(messages));
217 }
218
219 public static void logTrace(Object... messages) {
220 LOGS.trace(getLogMessage(messages));
221 }
222
223 public static void logDebug(Object... messages) {
224 LOGS.debug(getLogMessage(messages));
225 }
226
227 public static void logError(Object... messages) {
228 LOGS.error(getLogMessage(messages));
229 }
230
231 public static void initialise() {
232 File tmp = new File(TempDirectory);
233 if (!tmp.exists()) tmp.mkdirs();
234 }
235
236 public static void cleanup() {
237 File tmp = new File(TempDirectory);
238 if (tmp.exists()) tmp.delete();
239 }
240
241 public static String toFileIRI(String path) {
242 String iri;
243 if (path.startsWith(FILE_SEPARATOR)) iri = "file:" + path;
244 else iri = "file:\\\\\\" + path;
245 return iri.replace(FILE_SEPARATOR, JAVA_FILE_SEPARATOR).replace(" ", "%20");
246 }
247
248}