├── .gitignore
├── LICENSE
├── README.md
├── pom.xml
└── src
├── main
└── java
│ └── de
│ └── derivo
│ └── sparqldlapi
│ ├── Query.java
│ ├── QueryArgument.java
│ ├── QueryAtom.java
│ ├── QueryAtomGroup.java
│ ├── QueryBinding.java
│ ├── QueryEngine.java
│ ├── QueryParser.java
│ ├── QueryResult.java
│ ├── QueryToken.java
│ ├── QueryTokenizer.java
│ ├── Var.java
│ ├── examples
│ ├── Example_Basic.java
│ ├── Example_Extended.java
│ └── Example_XML_JSON.java
│ ├── exceptions
│ ├── QueryEngineException.java
│ └── QueryParserException.java
│ ├── impl
│ ├── LiteralTranslator.java
│ ├── QueryAtomGroupImpl.java
│ ├── QueryBindingImpl.java
│ ├── QueryEngineImpl.java
│ ├── QueryImpl.java
│ ├── QueryParserImpl.java
│ ├── QueryResultImpl.java
│ └── QueryTokenizerImpl.java
│ └── types
│ ├── QueryArgumentType.java
│ ├── QueryAtomType.java
│ └── QueryType.java
└── test
└── java
└── de
└── derivo
└── sparqldlapi
└── tests
├── AllTests.java
├── LiteralTranslator_TestCase.java
├── QueryArgumentTest.java
├── QueryAtomTest.java
├── QueryBindingTest.java
├── QueryEngineStrictModeTest.java
├── QueryParserTest.java
├── QueryResultTest.java
├── QueryTest.java
├── QueryTokenTest.java
└── QueryTokenizerTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 |
3 | # Mobile Tools for Java (J2ME)
4 | .mtj.tmp/
5 |
6 | # Package Files #
7 | *.jar
8 | *.war
9 | *.ear
10 |
11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
12 | hs_err_pid*
13 |
14 | # Eclipse
15 | .classpath
16 | .project
17 | .settings/
18 | META-INF/
19 |
20 | #intelliJ
21 | *.iws
22 | *.ipr
23 | .idea
24 | *.iml
25 | build/
26 |
27 | target
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
166 |
167 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # sparq-dl-api
2 | A query engine for SPARQL-DL. Originally written by Derivo Systems
3 |
4 | http://www.derivo.de/en/resources/sparql-dl-api.html
5 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 |
6 | org.sonatype.oss
7 | oss-parent
8 | 7
9 |
10 |
11 |
12 | edu.stanford.protege
13 | de-derivo-sparqldlapi
14 | 3.0.0
15 | jar
16 |
17 |
18 |
19 | GNU LGPL Version 3.0
20 | http://www.gnu.org/licenses/lgpl.txt
21 | repo
22 |
23 |
24 |
25 | SPARQL-DL API
26 | This library was originally developed by Mario Volke and Derivo Systems.
27 | http://www.derivo.de/en/resources/sparql-dl-api.html
28 |
29 |
30 |
31 | matthewhorridge
32 | Matthew Horridge
33 | matthew.horridge@stanford.edu
34 |
35 |
36 |
37 |
38 |
39 | Mario Volke
40 |
41 |
42 | Olaf Noppens
43 |
44 |
45 | Thorsten Liebig
46 |
47 |
48 |
49 |
50 |
51 | ossrh
52 | https://oss.sonatype.org/content/repositories/snapshots
53 |
54 |
55 | ossrh
56 | https://oss.sonatype.org/service/local/staging/deploy/maven2/
57 |
58 |
59 |
60 |
61 | scm:git:git@github.com:protegeproject/sparql-dl-api.git
62 | scm:git:git@github.com:protegeproject/sparql-dl-api.git
63 | https://github.com/protegeproject/sparql-dl-api
64 |
65 |
66 |
67 |
68 | net.sourceforge.owlapi
69 | owlapi-distribution
70 | 4.2.8
71 |
72 |
73 | org.jdom
74 | jdom-legacy
75 | 1.1.3
76 |
77 |
78 | edu.stanford.protege
79 | jpaul
80 | 2.5.1
81 |
82 |
83 | junit
84 | junit
85 | 4.12
86 | test
87 |
88 |
89 | org.mockito
90 | mockito-core
91 | 2.0.5-beta
92 | test
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 | org.apache.maven.plugins
101 | maven-compiler-plugin
102 | 3.0
103 |
104 | 1.8
105 | 1.8
106 |
107 |
108 |
109 |
110 | org.apache.maven.plugins
111 | maven-source-plugin
112 | 2.2.1
113 |
114 |
115 | attach-sources
116 |
117 | jar
118 |
119 |
120 |
121 |
122 |
123 |
124 | org.apache.maven.plugins
125 | maven-javadoc-plugin
126 | 2.9.1
127 |
128 |
129 | attach-javadocs
130 |
131 | jar
132 |
133 |
134 | -Xdoclint:none
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/Query.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi;
6 |
7 | import java.util.List;
8 | import java.util.Set;
9 |
10 | import de.derivo.sparqldlapi.exceptions.QueryParserException;
11 | import de.derivo.sparqldlapi.impl.QueryParserImpl;
12 | import de.derivo.sparqldlapi.impl.QueryTokenizerImpl;
13 | import de.derivo.sparqldlapi.types.QueryType;
14 |
15 | /**
16 | * The Query class represents a SPARQL-DL query
17 | * and mainly contains query atoms.
18 | *
19 | * @author Mario Volke
20 | */
21 | public abstract class Query
22 | {
23 | /**
24 | * Check whether there are any atoms in the query.
25 | *
26 | * @return True if there are no atoms at all.
27 | */
28 | abstract public boolean isEmpty();
29 |
30 | /**
31 | * Get the type of the query.
32 | *
33 | * @return
34 | */
35 | abstract public QueryType getType();
36 |
37 | /**
38 | * Check whether the given query argument is a result variable.
39 | *
40 | * @return True if the query argument is a result variable, false otherwise.
41 | */
42 | abstract public boolean isResultVar(QueryArgument arg);
43 |
44 | /**
45 | * Get the number of result variables.
46 | *
47 | * @return
48 | */
49 | abstract public int numResultVars();
50 |
51 | /**
52 | * Get an unodifiable set of all result variables.
53 | *
54 | * @return
55 | */
56 | abstract public Set getResultVars();
57 |
58 | /**
59 | * Get an unodifiable list of all query atom groups.
60 | *
61 | * @return
62 | */
63 | abstract public List getAtomGroups();
64 |
65 | /**
66 | * Check whether the query is of type ASK
67 | *
68 | * @return
69 | */
70 | abstract public boolean isAsk();
71 |
72 | /**
73 | * Check whether the query is of type SELECT.
74 | *
75 | * @return
76 | */
77 | abstract public boolean isSelect();
78 |
79 | /**
80 | * Check whether the query is of type SELECT DISTINCT.
81 | *
82 | * @return
83 | */
84 | abstract public boolean isSelectDistinct();
85 |
86 | /**
87 | * Print the SPARQL-DL query as string.
88 | *
89 | * @return String containing valid SPARQL-DL query.
90 | */
91 | abstract public String toString();
92 |
93 | /**
94 | * A factory method to create a query from string.
95 | *
96 | * @param query
97 | * @return
98 | * @throws QueryParserException
99 | */
100 | public static Query create(String query)
101 | throws QueryParserException
102 | {
103 | QueryTokenizer tokenizer = new QueryTokenizerImpl();
104 | QueryParser parser = new QueryParserImpl();
105 |
106 | return parser.parse(tokenizer.tokenize(query));
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/QueryArgument.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi;
6 |
7 | import de.derivo.sparqldlapi.types.QueryArgumentType;
8 | import org.semanticweb.owlapi.model.IRI;
9 | import org.semanticweb.owlapi.model.OWLAnonymousIndividual;
10 | import org.semanticweb.owlapi.model.OWLLiteral;
11 |
12 | /**
13 | * This class represents a query argument (e.g. an URI or a variable).
14 | *
15 | * @author Mario Volke
16 | */
17 | public class QueryArgument {
18 |
19 | private Object value;
20 |
21 | // private String value;
22 |
23 |
24 | private QueryArgumentType type;
25 |
26 | public QueryArgument(IRI value) {
27 | this.type = QueryArgumentType.URI;
28 | this.value = value;
29 | }
30 |
31 |
32 | public QueryArgument(OWLLiteral value) {
33 | this.type = QueryArgumentType.LITERAL;
34 | this.value = value;
35 | }
36 |
37 |
38 | public QueryArgument(OWLAnonymousIndividual value) {
39 | this.type = QueryArgumentType.BNODE;
40 | this.value = value;
41 | }
42 |
43 | public QueryArgument(Var value) {
44 | this.type = QueryArgumentType.VAR;
45 | this.value = value;
46 | }
47 |
48 | /**
49 | * Factory method to create a QueryArgument instance with type URI by IRI.
50 | *
51 | * @param value
52 | * @return
53 | */
54 | public static QueryArgument newURI(IRI value) {
55 | return new QueryArgument(value);
56 | }
57 |
58 | // /**
59 | // * Factory method to create a QueryArgument instance with type URI by string.
60 | // *
61 | // * @param value
62 | // * @return
63 | // */
64 | // public static QueryArgument newURI(String value)
65 | // {
66 | // return new QueryArgument(QueryArgumentType.URI, value);
67 | // }
68 |
69 | /**
70 | * Factory method to create a QueryArgument instance with type VAR by string.
71 | *
72 | * @param value
73 | * @return
74 | */
75 | public static QueryArgument newVar(Var value) {
76 | return new QueryArgument(value);
77 | }
78 |
79 | /**
80 | * Factory method to create a QueryArgument instance with type BNODE by string.
81 | *
82 | * @param value
83 | * @return
84 | */
85 | public static QueryArgument newBnode(OWLAnonymousIndividual value) {
86 | return new QueryArgument(value);
87 | }
88 |
89 | /**
90 | * Factory method to create a QueryArgument instance with type LITERAL by string.
91 | *
92 | * @return
93 | */
94 | // public static QueryArgument newLiteral(String value, String datatype, String lang)
95 | public static QueryArgument newLiteral(OWLLiteral literal) {
96 | return new QueryArgument(literal);
97 | }
98 |
99 |
100 | // /**
101 | // * Get the value of the query argument.
102 | // *
103 | // * @return
104 | // */
105 | // public Object getValue()
106 | // {
107 | // return value;
108 | // }
109 |
110 | public IRI getValueAsIRI() {
111 | return (IRI) value;
112 | }
113 |
114 | public OWLLiteral getValueAsLiteral() {
115 | return (OWLLiteral) value;
116 | }
117 |
118 | public Var getValueAsVar() {
119 | return (Var) value;
120 | }
121 |
122 | public OWLAnonymousIndividual getValueAsBNode() {
123 | return (OWLAnonymousIndividual) value;
124 | }
125 |
126 | public String getValueAsString() {
127 | if (value instanceof IRI) {
128 | return value.toString();
129 | }
130 | else if (value instanceof OWLLiteral) {
131 | return ((OWLLiteral) value).getLiteral();
132 | }
133 | else if (value instanceof OWLAnonymousIndividual) {
134 | return ((OWLAnonymousIndividual) value).getID().toString();
135 | }
136 | else if (value instanceof Var) {
137 | return ((Var) value).getName();
138 | }
139 | else {
140 | return value.toString();
141 | }
142 | }
143 |
144 | /**
145 | * Get the type of the query argument.
146 | *
147 | * @return
148 | */
149 | public QueryArgumentType getType() {
150 | return type;
151 | }
152 |
153 | /**
154 | * Check whether the query argument has a special type.
155 | *
156 | * @param type
157 | * @return True if the query argument has this type.
158 | */
159 | public boolean hasType(QueryArgumentType type) {
160 | return this.type == type;
161 | }
162 |
163 | /**
164 | * Check whether the query argument is an URI.
165 | *
166 | * @return True if the query argument is an URI.
167 | */
168 | public boolean isURI() {
169 | return hasType(QueryArgumentType.URI);
170 | }
171 |
172 | /**
173 | * Check whether the query argument is a variable.
174 | *
175 | * @return True if the query argument is a variable.
176 | */
177 | public boolean isVar() {
178 | return hasType(QueryArgumentType.VAR);
179 | }
180 |
181 | /**
182 | * Check whether the query argument is a literal.
183 | *
184 | * @return True if the query argument is a literal.
185 | */
186 | public boolean isLiteral() {
187 | return hasType(QueryArgumentType.LITERAL);
188 | }
189 |
190 | /**
191 | * Check whether the query argument is a bnode.
192 | *
193 | * @return True if the query argument is a bnode.
194 | */
195 | public boolean isBnode() {
196 | return hasType(QueryArgumentType.BNODE);
197 | }
198 |
199 | @Override
200 | public boolean equals(Object obj) {
201 | QueryArgument arg = (QueryArgument) obj;
202 | return value.equals(arg.value) && this.type == arg.type;
203 | }
204 |
205 | @Override
206 | public int hashCode() {
207 | int hash = 7;
208 | hash = 31 * type.hashCode() + hash;
209 | hash = 31 * value.hashCode() + hash;
210 | return hash;
211 | }
212 |
213 | /**
214 | * Print the query argument as string.
215 | * Output depends on the type of the argument.
216 | */
217 | public String toString() {
218 | StringBuffer sb;
219 |
220 | switch (type) {
221 | case LITERAL:
222 | sb = new StringBuffer();
223 | sb.append(value);
224 | // sb.append('"');
225 | // char c;
226 | // int pos = 0;
227 | // while(pos < value.length()) {
228 | // c = value.charAt(pos);
229 | // if(c == '"' || c == '\\') {
230 | // sb.append('\\');
231 | // }
232 | // sb.append(c);
233 | // pos++;
234 | // }
235 | // sb.append('"');
236 | // return sb.toString();
237 | case VAR:
238 | sb = new StringBuffer();
239 | sb.append('?');
240 | sb.append(value);
241 | return sb.toString();
242 | case URI:
243 | sb = new StringBuffer();
244 | sb.append('<');
245 | sb.append(value);
246 | sb.append('>');
247 | default:
248 | return value.toString();
249 | }
250 | }
251 | }
252 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/QueryAtom.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi;
6 |
7 | import java.util.ArrayList;
8 | import java.util.Arrays;
9 | import java.util.List;
10 |
11 | import de.derivo.sparqldlapi.types.QueryAtomType;
12 |
13 | /**
14 | * This class represents a query atom.
15 | *
16 | * @author Mario Volke
17 | */
18 | public class QueryAtom
19 | {
20 | protected final QueryAtomType type;
21 | protected final List args;
22 | protected boolean bound;
23 |
24 | public QueryAtom(final QueryAtomType type, final QueryArgument ... args)
25 | {
26 | this(type, Arrays.asList(args));
27 | }
28 |
29 | public QueryAtom(final QueryAtomType type, final List args)
30 | {
31 | this.type = type;
32 | this.args = args;
33 |
34 | // check if atom is bound
35 | bound = true;
36 | for(QueryArgument arg : args) {
37 | if(arg.isVar() || arg.isBnode()) {
38 | bound = false;
39 | break;
40 | }
41 | }
42 | }
43 |
44 | /**
45 | * Check whether the atom contains any variables or not.
46 | *
47 | * @return True if there are no variables left.
48 | */
49 | public boolean isBound()
50 | {
51 | return bound;
52 | }
53 |
54 | /**
55 | * Get the exact type of the atom.
56 | *
57 | * @return The query atom type.
58 | */
59 | public QueryAtomType getType()
60 | {
61 | return type;
62 | }
63 |
64 | /**
65 | * Check whether this atom has a concrete type.
66 | *
67 | * @param type
68 | * @return True if the atom has this type.
69 | */
70 | public boolean hasType(QueryAtomType type)
71 | {
72 | return this.type == type;
73 | }
74 |
75 | /**
76 | * Get the arguments of the atom.
77 | *
78 | * @return
79 | */
80 | public List getArguments()
81 | {
82 | return args;
83 | }
84 |
85 | /**
86 | * A convenience method to clone the QueryAtom instance while
87 | * inserting a new binding.
88 | *
89 | * @param binding
90 | * @return
91 | */
92 | public QueryAtom bind(QueryBinding binding)
93 | {
94 | List args = new ArrayList();
95 | for(QueryArgument arg : this.args) {
96 | if(binding.isBound(arg)) {
97 | args.add(binding.get(arg));
98 | }
99 | else {
100 | args.add(arg);
101 | }
102 | }
103 |
104 | return new QueryAtom(type, args);
105 | }
106 |
107 | /**
108 | * Get the atom as string.
109 | *
110 | * @return String containing valid SPARQL-DL atom format.
111 | */
112 | public String toString()
113 | {
114 | StringBuffer sb = new StringBuffer();
115 | sb.append(type);
116 | sb.append('(');
117 | boolean first = true;
118 | for(QueryArgument arg : args) {
119 | if(first) {
120 | first = false;
121 | }
122 | else {
123 | sb.append(',');
124 | sb.append(' ');
125 | }
126 | sb.append(arg);
127 | }
128 | sb.append(')');
129 | return sb.toString();
130 | }
131 |
132 | @Override
133 | public boolean equals(Object obj)
134 | {
135 | QueryAtom atom = (QueryAtom)obj;
136 | if(!type.equals(atom.type)) {
137 | return false;
138 | }
139 |
140 | if(!args.equals(atom.args)) {
141 | return false;
142 | }
143 |
144 | return true;
145 | }
146 |
147 | @Override
148 | public int hashCode()
149 | {
150 | int hash = 7;
151 | hash = 31 * type.hashCode() + hash;
152 | hash = 31 * args.hashCode() + hash;
153 | return hash;
154 | }
155 | }
156 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/QueryAtomGroup.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi;
6 |
7 | import java.util.List;
8 |
9 | /**
10 | * The QueryAtomGroup class contains a group of atoms of a WHERE {} or UNION {} statement.
11 | *
12 | * @author Mario Volke
13 | */
14 | public interface QueryAtomGroup
15 | {
16 | /**
17 | * Check whether there are any atoms in the group.
18 | * @return True if there are no atoms at all.
19 | */
20 | boolean isEmpty();
21 |
22 | /**
23 | * Get an unodifiable list of all query atoms in the group.
24 | */
25 | List getAtoms();
26 |
27 | /**
28 | * Print the group as string.*
29 | * @return a string
30 | */
31 | String toString();
32 |
33 | @Override
34 | boolean equals(Object obj);
35 |
36 | @Override
37 | int hashCode();
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/QueryBinding.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi;
6 |
7 | import java.util.Set;
8 |
9 | /**
10 | * A QueryBinding is one single entry in the result set of an executed query.
11 | * A binding consists of a mapping from variables to concrete values (e.g. URIs or literals).
12 | *
13 | * @author Mario Volke
14 | */
15 | public interface QueryBinding extends Cloneable
16 | {
17 | /**
18 | * Get the binding of a query argument.
19 | *
20 | * @param arg
21 | * @return Null if argument is not bound, yet, or the binding otherwise.
22 | */
23 | public QueryArgument get(QueryArgument arg);
24 |
25 | /**
26 | * Get all bound arguments.
27 | *
28 | * @return A set of bound arguments (contains usually only variables).
29 | */
30 | public Set getBoundArgs();
31 |
32 | /**
33 | * Check whether an argument is bound.
34 | *
35 | * @param arg
36 | * @return True if the argument is bound.
37 | */
38 | public boolean isBound(QueryArgument arg);
39 |
40 | /**
41 | * Get the number of bound arguments.
42 | *
43 | * @return The number of bound arguments.
44 | */
45 | public int size();
46 |
47 | /**
48 | * Check whether there are any bindings.
49 | *
50 | * @return True if there are no bindings at all.
51 | */
52 | public boolean isEmpty();
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/QueryEngine.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi;
6 |
7 | import org.semanticweb.owlapi.model.OWLOntologyManager;
8 | import org.semanticweb.owlapi.reasoner.OWLReasoner;
9 |
10 | import de.derivo.sparqldlapi.exceptions.QueryEngineException;
11 | import de.derivo.sparqldlapi.impl.QueryEngineImpl;
12 |
13 | /**
14 | * The query engine that executes a query and generates the appropriate result set.
15 | *
16 | * @author Mario Volke
17 | */
18 | public abstract class QueryEngine
19 | {
20 | /**
21 | * Factory method to create a QueryEngine instance.
22 | *
23 | * @param manager An OWLOntologyManager instance of OWLAPI v3
24 | * @param reasoner An OWLReasoner instance.
25 | * @return an instance of QueryEngine
26 | */
27 | public static QueryEngine create(OWLOntologyManager manager, OWLReasoner reasoner)
28 | {
29 | return new QueryEngineImpl(manager, reasoner);
30 | }
31 |
32 | /**
33 | * Factory method to create a QueryEngine instance.
34 | *
35 | * @param manager An OWLOntologyManager instance of OWLAPI v3
36 | * @param reasoner An OWLReasoner instance.
37 | * @param strictMode If strict mode is enabled the query engine will throw a QueryEngineException if data types withing the query are not correct (e.g. Class(URI_OF_AN_INDIVIDUAL))
38 | * @return an instance of QueryEngine
39 | */
40 | public static QueryEngine create(OWLOntologyManager manager, OWLReasoner reasoner, boolean strict)
41 | {
42 | return new QueryEngineImpl(manager, reasoner, strict);
43 | }
44 |
45 | /**
46 | * Execute a sparql-dl query and generate the result set.
47 | *
48 | * @param query
49 | * @return The query result set.
50 | */
51 | public abstract QueryResult execute(Query query)
52 | throws QueryEngineException;
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/QueryParser.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi;
6 |
7 | import java.util.List;
8 |
9 | import de.derivo.sparqldlapi.exceptions.QueryParserException;
10 |
11 | /**
12 | * The SPARQL-DL query parser.
13 | *
14 | * @author Mario Volke
15 | */
16 | public interface QueryParser
17 | {
18 | /**
19 | * Parse the query.
20 | * @param tokens The tokens that you got from the QueryTokenizer.
21 | * @return A Query instance.
22 | * @throws QueryParserException
23 | */
24 | public Query parse(List tokens)
25 | throws QueryParserException;
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/QueryResult.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi;
6 |
7 | import java.util.Iterator;
8 |
9 | import org.jdom.Document;
10 |
11 | /**
12 | * QueryResult contains the result set of an executed query
13 | * with all bindings. This class also provides some methods
14 | * to export the result set in different formats like SPARQL-XML or JSON.
15 | *
16 | * @author Mario Volke
17 | */
18 | public interface QueryResult extends Iterable
19 | {
20 | /**
21 | * Get the query that belongs to this result.
22 | *
23 | * @return
24 | */
25 | public Query getQuery();
26 |
27 | /**
28 | * An iterator over the result set.
29 | *
30 | * @return
31 | */
32 | public Iterator iterator();
33 |
34 | /**
35 | * Returns the QueryBinding at the specified position of the result.
36 | *
37 | * @param index
38 | * @return The QueryBinding at the specified position.
39 | */
40 | public QueryBinding get(int index);
41 |
42 | /**
43 | * Get the size of the result set.
44 | *
45 | * @return The size of the result set.
46 | */
47 | public int size();
48 |
49 | /**
50 | * Check whether the result set is empty.
51 | *
52 | * @return True if the result set is empty.
53 | */
54 | public boolean isEmpty();
55 |
56 | /**
57 | * Ask if the query had a solution.
58 | * This is the only result you get if the query was of type ASK.
59 | * This could also be true if the result set is empty.
60 | *
61 | * @return True if the query had a solution.
62 | */
63 | public boolean ask();
64 |
65 | /**
66 | * Output query results as JDOM XML document containing the standard
67 | * SPARQL query results XML format (http://www.w3.org/TR/rdf-sparql-XMLres/).
68 | * Supports both: Variable binding results and Boolean results.
69 | *
70 | * @return A JDOM XML document.
71 | */
72 | public Document toXML();
73 |
74 | /**
75 | * Output query results in JSON format as standardized in http://www.w3.org/TR/rdf-sparql-json-res/.
76 | * Supports both: Variable binding results and Boolean results.
77 | *
78 | * @return The JSON result as string.
79 | */
80 | public String toJSON();
81 |
82 | /**
83 | * Use this method for debugging purposes.
84 | * This is no standard format like SPARQL-XML or JSON.
85 | *
86 | * @return A nicely formatted string containing the results and bindings.
87 | */
88 | public String toString();
89 | }
90 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/QueryToken.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi;
6 |
7 | /**
8 | * The SPARQL-DL query token.
9 | *
10 | * This tokenizer is heavily influenced by org.coode.manchesterowlsyntax.ManchesterOWLSyntaxTokenizer
11 | * of the OWL-API.
12 | *
13 | * @author Mario Volke
14 | */
15 | public class QueryToken
16 | {
17 | private String token;
18 | private int pos;
19 | private int col;
20 | private int row;
21 |
22 | public QueryToken(String token, int pos, int col, int row)
23 | {
24 | this.token = token;
25 | this.pos = pos;
26 | this.col = col;
27 | this.row = row;
28 | }
29 |
30 | public String getToken()
31 | {
32 | return token;
33 | }
34 |
35 | public int getPos()
36 | {
37 | return pos;
38 | }
39 |
40 | public int getCol()
41 | {
42 | return col;
43 | }
44 |
45 | public int getRow()
46 | {
47 | return row;
48 | }
49 |
50 | public String toString()
51 | {
52 | StringBuilder sb = new StringBuilder();
53 | sb.append(token);
54 | sb.append(" [");
55 | sb.append(pos);
56 | sb.append(", ");
57 | sb.append(col);
58 | sb.append(", ");
59 | sb.append(row);
60 | sb.append("]");
61 | return sb.toString();
62 | }
63 |
64 | @Override
65 | public boolean equals(Object obj)
66 | {
67 | QueryToken t = (QueryToken)obj;
68 | return token.equals(t.token) && pos == t.pos && col == t.col && row == t.row;
69 | }
70 |
71 | @Override
72 | public int hashCode()
73 | {
74 | int hash = 7;
75 | hash = 31 * token.hashCode() + hash;
76 | hash = 31 * pos + hash;
77 | hash = 31 * col + hash;
78 | hash = 31 * row + hash;
79 | return hash;
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/QueryTokenizer.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi;
6 |
7 | import java.util.List;
8 |
9 | /**
10 | * The SPARQL-DL query tokenizer.
11 | *
12 | * This tokenizer is heavily influenced by org.coode.manchesterowlsyntax.ManchesterOWLSyntaxTokenizer
13 | * of the OWL-API.
14 | *
15 | * @author Mario Volke
16 | */
17 | public interface QueryTokenizer
18 | {
19 | /**
20 | * Tokenize a SPARQL-DL query string.
21 | * @param buffer
22 | * @return A list of tokens.
23 | */
24 | public List tokenize(String buffer);
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/Var.java:
--------------------------------------------------------------------------------
1 | package de.derivo.sparqldlapi;
2 |
3 | /**
4 | * Matthew Horridge
5 | * Stanford Center for Biomedical Informatics Research
6 | * 11/06/15
7 | */
8 | public class Var {
9 |
10 | private String name;
11 |
12 | public Var(String name) {
13 | this.name = name;
14 | }
15 |
16 | public String getName() {
17 | return name;
18 | }
19 |
20 | @Override
21 | public int hashCode() {
22 | return name.hashCode();
23 | }
24 |
25 | @Override
26 | public boolean equals(Object obj) {
27 | if (obj == this) {
28 | return true;
29 | }
30 | if (!(obj instanceof Var)) {
31 | return false;
32 | }
33 | Var other = (Var) obj;
34 | return this.name.equals(other.name);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/examples/Example_Basic.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.examples;
6 |
7 | import de.derivo.sparqldlapi.Query;
8 | import de.derivo.sparqldlapi.QueryEngine;
9 | import de.derivo.sparqldlapi.QueryResult;
10 | import de.derivo.sparqldlapi.exceptions.QueryEngineException;
11 | import de.derivo.sparqldlapi.exceptions.QueryParserException;
12 |
13 | import org.semanticweb.owlapi.apibinding.OWLManager;
14 | import org.semanticweb.owlapi.model.IRI;
15 | import org.semanticweb.owlapi.model.OWLOntology;
16 | import org.semanticweb.owlapi.model.OWLOntologyCreationException;
17 | import org.semanticweb.owlapi.model.OWLOntologyManager;
18 | import org.semanticweb.owlapi.reasoner.InferenceType;
19 | import org.semanticweb.owlapi.reasoner.OWLReasoner;
20 | import org.semanticweb.owlapi.reasoner.structural.StructuralReasonerFactory;
21 |
22 |
23 | /**
24 | * This basic examples show how to load an ontology, to initialize the SPARQL-DL query engine
25 | * as well as to execute some simple queries.
26 | * We use the OWL wine ontology for demonstration and the built-in StructuralReasoner as sample
27 | * reasoning system.
28 | * In case you use any other reasoning engine make sure you have the respective jars within your
29 | * classpath (note that you have to provide the resp. ReasonerFactory in this case).
30 | *
31 | * @author Mario Volke
32 | * @author Thorsten Liebig
33 | */
34 | public class Example_Basic
35 | {
36 | private static QueryEngine engine;
37 |
38 | /**
39 | * @param args
40 | */
41 | public static void main(String[] args)
42 | {
43 | try {
44 | // Create an ontology manager
45 | OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
46 |
47 | // Load the wine ontology from the web.
48 | OWLOntology ont = manager.loadOntologyFromOntologyDocument(IRI.create("http://www.w3.org/TR/owl-guide/wine.rdf"));
49 |
50 | // Create an instance of an OWL API reasoner (we use the OWL API built-in StructuralReasoner for the purpose of demonstration here)
51 | StructuralReasonerFactory factory = new StructuralReasonerFactory();
52 | OWLReasoner reasoner = factory.createReasoner(ont);
53 | // Optionally let the reasoner compute the most relevant inferences in advance
54 | reasoner.precomputeInferences(InferenceType.CLASS_ASSERTIONS,InferenceType.OBJECT_PROPERTY_ASSERTIONS);
55 |
56 | // Create an instance of the SPARQL-DL query engine
57 | engine = QueryEngine.create(manager, reasoner, true);
58 |
59 | // Some queries which cover important basic language constructs of SPARQL-DL
60 |
61 | // All white wines (all individuals of the class WhiteWine and sub classes thereof)
62 | processQuery(
63 | "SELECT * WHERE {\n" +
64 | "Type(?x, )" +
65 | "}"
66 | );
67 |
68 | // The white wines (the individuals of WhiteWine but not of it's sub classes)
69 | processQuery(
70 | "SELECT * WHERE {\n" +
71 | "DirectType(?x, )" +
72 | "}"
73 | );
74 |
75 | // Is PinotBlanc a sub class of Wine?
76 | processQuery(
77 | "PREFIX wine: \n" +
78 | "ASK {\n" +
79 | "SubClassOf(wine:PinotBlanc, wine:Wine)" +
80 | "}"
81 | );
82 |
83 | // The direct sub classes of FrenchWine
84 | processQuery(
85 | "PREFIX wine: \n" +
86 | "SELECT ?x WHERE {\n" +
87 | "DirectSubClassOf(?x, wine:FrenchWine)" +
88 | "}"
89 | );
90 |
91 | // All individuals
92 | processQuery(
93 | "PREFIX wine: \n" +
94 | "SELECT * WHERE {\n" +
95 | "Individual(?x)" +
96 | "}"
97 | );
98 |
99 | // All functional ObjectProperties
100 | processQuery(
101 | "PREFIX wine: \n" +
102 | "SELECT * WHERE {\n" +
103 | "ObjectProperty(?x), " +
104 | "Functional(?x)" +
105 | "}"
106 | );
107 |
108 | // The strict sub classes of DryWhiteWine (sub classes with are not equivalent to DryWhiteWine)
109 | processQuery(
110 | "PREFIX wine: \n" +
111 | "SELECT ?x WHERE {\n" +
112 | "StrictSubClassOf(?x, wine:DryWhiteWine)" +
113 | "}"
114 | );
115 |
116 | // All the grapes from which RedTableWines are made from (without duplicates)
117 | processQuery(
118 | "PREFIX wine: \n" +
119 | "SELECT DISTINCT ?v WHERE {\n" +
120 | "Type(?i, wine:RedTableWine),\n" +
121 | "PropertyValue(?i, wine:madeFromGrape, ?v)" +
122 | "}"
123 | );
124 |
125 | }
126 | catch(UnsupportedOperationException exception) {
127 | System.out.println("Unsupported reasoner operation.");
128 | }
129 | catch(OWLOntologyCreationException e) {
130 | System.out.println("Could not load the wine ontology: " + e.getMessage());
131 | }
132 | }
133 |
134 | public static void processQuery(String q)
135 | {
136 | try {
137 | long startTime = System.currentTimeMillis();
138 |
139 | // Create a query object from it's string representation
140 | Query query = Query.create(q);
141 |
142 | System.out.println("Excecute the query:");
143 | System.out.println(q);
144 | System.out.println("-------------------------------------------------");
145 |
146 | // Execute the query and generate the result set
147 | QueryResult result = engine.execute(query);
148 |
149 | if(query.isAsk()) {
150 | System.out.print("Result: ");
151 | if(result.ask()) {
152 | System.out.println("yes");
153 | }
154 | else {
155 | System.out.println("no");
156 | }
157 | }
158 | else {
159 | if(!result.ask()) {
160 | System.out.println("Query has no solution.\n");
161 | }
162 | else {
163 | System.out.println("Results:");
164 | System.out.print(result);
165 | System.out.println("-------------------------------------------------");
166 | System.out.println("Size of result set: " + result.size());
167 | }
168 | }
169 |
170 | System.out.println("-------------------------------------------------");
171 | System.out.println("Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + "s\n");
172 | }
173 | catch(QueryParserException e) {
174 | System.out.println("Query parser error: " + e);
175 | }
176 | catch(QueryEngineException e) {
177 | System.out.println("Query engine error: " + e);
178 | }
179 | }
180 | }
181 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/examples/Example_Extended.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.examples;
6 |
7 | import org.semanticweb.owlapi.apibinding.OWLManager;
8 | import org.semanticweb.owlapi.model.IRI;
9 | import org.semanticweb.owlapi.model.OWLOntology;
10 | import org.semanticweb.owlapi.model.OWLOntologyCreationException;
11 | import org.semanticweb.owlapi.model.OWLOntologyManager;
12 | import org.semanticweb.owlapi.reasoner.InferenceType;
13 | import org.semanticweb.owlapi.reasoner.OWLReasoner;
14 |
15 | import de.derivo.sparqldlapi.Query;
16 | import de.derivo.sparqldlapi.QueryEngine;
17 | import de.derivo.sparqldlapi.QueryResult;
18 | import de.derivo.sparqldlapi.exceptions.QueryEngineException;
19 | import de.derivo.sparqldlapi.exceptions.QueryParserException;
20 | import org.semanticweb.owlapi.reasoner.structural.StructuralReasonerFactory;
21 |
22 | /**
23 | * This examples show some extra queries and most notably the "OR WHERE" clause which
24 | * is useful to concatenate two conjunctive queries.
25 | * We use the OWL wine ontology for demonstration and the built-in StructuralReasoner as sample
26 | * reasoning system.
27 | * In case you use any other reasoning engine make sure you have the respective jars within your
28 | * classpath (note that you have to provide the resp. ReasonerFactory in this case).
29 | *
30 | * @author Mario Volke
31 | * @author Thorsten Liebig
32 | */
33 | public class Example_Extended
34 | {
35 | private static QueryEngine engine;
36 |
37 | /**
38 | * @param args
39 | */
40 | public static void main(String[] args)
41 | {
42 | try {
43 | // Create our ontology manager in the usual way.
44 | OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
45 |
46 | // Load a copy of the wine ontology. We'll load the ontology from the web.
47 | OWLOntology ont = manager.loadOntologyFromOntologyDocument(IRI.create("http://www.w3.org/TR/owl-guide/wine.rdf"));
48 |
49 | // Create an instance of an OWL API reasoner (we use the OWL API built-in StructuralReasoner for the purpose of demonstration here)
50 | StructuralReasonerFactory factory = new StructuralReasonerFactory();
51 | OWLReasoner reasoner = factory.createReasoner(ont);
52 | // Optionally let the reasoner compute the most relevant inferences in advance
53 | reasoner.precomputeInferences(InferenceType.CLASS_ASSERTIONS,InferenceType.OBJECT_PROPERTY_ASSERTIONS);
54 |
55 | // Create an instance of the SPARQL-DL query engine
56 | engine = QueryEngine.create(manager, reasoner);
57 |
58 | // Some queries which demonstrate more sophisticated language constructs of SPARQL-DL
59 |
60 | // The empty ASK is true by default
61 | processQuery(
62 | "ASK {}"
63 | );
64 |
65 | // The response to an empty SELECT is an empty response
66 | processQuery(
67 | "SELECT * WHERE {}"
68 | );
69 |
70 | // There can't be an instance of owl:Nothing. Therefore this query has no solutions.
71 | processQuery(
72 | "PREFIX owl: \n" +
73 | "SELECT * WHERE { Type(?x,owl:Nothing) }"
74 | );
75 |
76 | // A complicated way to retrieve all individuals. Note that the WHERE keyword is optional.
77 | processQuery(
78 | "PREFIX owl: \n" +
79 | "SELECT DISTINCT ?x { Type(?x,?y), ComplementOf(owl:Nothing,?y) }"
80 | );
81 |
82 | // All wines which are OffDry
83 | processQuery(
84 | "PREFIX wine: \n" +
85 | "PREFIX food: \n" +
86 | "SELECT DISTINCT ?w WHERE { PropertyValue(?w, wine:hasWineDescriptor, food:OffDry) }"
87 | );
88 |
89 | // A query returning pairs of results, namely all sources and fillers of yearValue
90 | processQuery(
91 | "PREFIX wine: \n" +
92 | "SELECT DISTINCT ?w ?g WHERE { PropertyValue(?w, wine:yearValue, ?g)" +
93 | "}"
94 | );
95 |
96 | // The most specific types of wines of all wineries
97 | processQuery(
98 | "PREFIX wine: \n" +
99 | "SELECT DISTINCT ?x ?y WHERE {\n" +
100 | "Type(?x, wine:Winery), \n" +
101 | "DirectType(?z, ?y), \n" +
102 | "PropertyValue(?x, wine:producesWine, ?z)" +
103 | "}"
104 | );
105 |
106 | // All entities which are either object properties or classes
107 | processQuery(
108 | "SELECT ?i WHERE {" +
109 | "ObjectProperty(?i) " +
110 | "} OR WHERE {" +
111 | "Class(?i)" +
112 | "}"
113 | );
114 |
115 | // Equivalent query to the one above
116 | processQuery(
117 | "SELECT * WHERE {" +
118 | "ObjectProperty(?i) " +
119 | "} OR WHERE {" +
120 | "Class(?j)" +
121 | "}"
122 | );
123 |
124 | }
125 | catch(UnsupportedOperationException exception) {
126 | System.out.println("Unsupported reasoner operation.");
127 | }
128 | catch(OWLOntologyCreationException e) {
129 | System.out.println("Could not load the pizza ontology: " + e.getMessage());
130 | }
131 | }
132 |
133 | public static void processQuery(String q)
134 | {
135 | try {
136 | long startTime = System.currentTimeMillis();
137 |
138 | // Create a SPARQL-DL query
139 | Query query = Query.create(q);
140 |
141 | System.out.println("Excecute query:");
142 | System.out.println(q);
143 | System.out.println("-------------------------------------------------");
144 |
145 | // Execute the query and generate the result set
146 | QueryResult result = engine.execute(query);
147 | if(query.isAsk()) {
148 | System.out.print("Result: ");
149 | if(result.ask()) {
150 | System.out.println("yes");
151 | }
152 | else {
153 | System.out.println("no");
154 | }
155 | }
156 | else {
157 | if(!result.ask()) {
158 | System.out.println("Query has no solution.\n");
159 | }
160 | else {
161 | System.out.println("Results:");
162 | System.out.print(result);
163 | System.out.println("-------------------------------------------------");
164 | System.out.println("Size of result set: " + result.size());
165 | }
166 | }
167 |
168 | System.out.println("-------------------------------------------------");
169 | System.out.println("Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + "s\n");
170 | }
171 | catch(QueryParserException e) {
172 | System.out.println("Query parser error: " + e);
173 | }
174 | catch(QueryEngineException e) {
175 | System.out.println("Query engine error: " + e);
176 | }
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/examples/Example_XML_JSON.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.examples;
6 |
7 | import java.io.IOException;
8 |
9 | import de.derivo.sparqldlapi.Query;
10 | import de.derivo.sparqldlapi.QueryEngine;
11 | import de.derivo.sparqldlapi.QueryResult;
12 | import de.derivo.sparqldlapi.exceptions.QueryEngineException;
13 | import de.derivo.sparqldlapi.exceptions.QueryParserException;
14 |
15 | import org.jdom.output.XMLOutputter;
16 |
17 | import org.semanticweb.owlapi.apibinding.OWLManager;
18 | import org.semanticweb.owlapi.model.IRI;
19 | import org.semanticweb.owlapi.model.OWLOntology;
20 | import org.semanticweb.owlapi.model.OWLOntologyCreationException;
21 | import org.semanticweb.owlapi.model.OWLOntologyManager;
22 | import org.semanticweb.owlapi.reasoner.InferenceType;
23 | import org.semanticweb.owlapi.reasoner.OWLReasoner;
24 | import org.semanticweb.owlapi.reasoner.structural.StructuralReasonerFactory;
25 |
26 |
27 | /**
28 | * This example shows how to export a query result as a standard SPARQL-XML-result or JSON.
29 | * We use the OWL wine ontology for demonstration and the built-in StructuralReasoner as sample
30 | * reasoning system.
31 | * In case you use any other reasoning engine make sure you have the respective jars within your
32 | * classpath (note that you have to provide the resp. ReasonerFactory in this case).
33 | *
34 | * @author Mario Volke
35 | */
36 | public class Example_XML_JSON
37 | {
38 | private static QueryEngine engine;
39 |
40 | /**
41 | * @param args
42 | */
43 | public static void main(String[] args)
44 | {
45 | try {
46 | // Create an ontology manager in the usual way.
47 | OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
48 |
49 | // Load the wine ontology from the web.
50 | OWLOntology ont = manager.loadOntologyFromOntologyDocument(IRI.create("http://www.w3.org/TR/owl-guide/wine.rdf"));
51 |
52 | // Create an instance of an OWL API reasoner (we use the OWL API built-in StructuralReasoner for the purpose of demonstration here)
53 | StructuralReasonerFactory factory = new StructuralReasonerFactory();
54 | OWLReasoner reasoner = factory.createReasoner(ont);
55 | // Optionally let the reasoner compute the most relevant inferences in advance
56 | reasoner.precomputeInferences(InferenceType.CLASS_ASSERTIONS,InferenceType.OBJECT_PROPERTY_ASSERTIONS);
57 |
58 | // Create an instance of the SPARQL-DL query engine
59 | engine = QueryEngine.create(manager, reasoner);
60 |
61 | processQuery(
62 | "PREFIX wine: \n" +
63 | "SELECT * WHERE {\n" +
64 | "SubClassOf(wine:PinotBlanc, ?x),\n" +
65 | "SubClassOf(?x, wine:Wine)\n" +
66 | "}"
67 | );
68 |
69 | processQuery(
70 | "PREFIX wine: \n" +
71 | "ASK {\n" +
72 | "SubClassOf(wine:PinotBlanc, wine:Wine)\n" +
73 | "}"
74 | );
75 | }
76 | catch(UnsupportedOperationException exception) {
77 | System.out.println("Unsupported reasoner operation.");
78 | }
79 | catch(OWLOntologyCreationException e) {
80 | System.out.println("Could not load the ontology: " + e.getMessage());
81 | }
82 | }
83 |
84 | public static void processQuery(String q)
85 | {
86 | try {
87 | long startTime = System.currentTimeMillis();
88 |
89 | // Create the SPARQL-DL query
90 | Query query = Query.create(q);
91 |
92 | System.out.println("Excecute query:");
93 | System.out.println(q);
94 | System.out.println("-------------------------------------------------");
95 |
96 | // Execute the query and generate the result set
97 | QueryResult result = engine.execute(query);
98 |
99 | // print as XML
100 | try {
101 | XMLOutputter out = new XMLOutputter();
102 | out.output(result.toXML(), System.out);
103 | }
104 | catch(IOException e) {
105 | // ok, this should not happen
106 | }
107 |
108 | System.out.println("-------------------------------------------------");
109 |
110 | // print as JSON
111 | System.out.print(result.toJSON());
112 |
113 | System.out.println("-------------------------------------------------");
114 | System.out.println("Size of result set: " + result.size());
115 | System.out.println("Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + "s\n");
116 | }
117 | catch(QueryParserException e) {
118 | System.out.println("Query parser error: " + e);
119 | }
120 | catch(QueryEngineException e) {
121 | System.out.println("Query engine error: " + e);
122 | }
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/exceptions/QueryEngineException.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.exceptions;
6 |
7 | public class QueryEngineException extends Exception
8 | {
9 | private static final long serialVersionUID = 1L;
10 |
11 | public QueryEngineException(String message)
12 | {
13 | super(message);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/exceptions/QueryParserException.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.exceptions;
6 |
7 | import de.derivo.sparqldlapi.QueryToken;
8 |
9 | public class QueryParserException extends Exception
10 | {
11 | private static final long serialVersionUID = 1L;
12 |
13 | QueryToken token;
14 |
15 | public QueryParserException(String message)
16 | {
17 | super(message);
18 | token = null;
19 | }
20 |
21 | public QueryParserException(String message, QueryToken token)
22 | {
23 | super(message);
24 | this.token = token;
25 | }
26 |
27 | public String toString()
28 | {
29 | String s = this.getMessage();
30 | if(token != null) {
31 | s += " (near \"" + token.getToken() + "\", pos: " + token.getPos() + ", col: " + token.getCol() + ", row: " + token.getRow() + ")";
32 | }
33 | return s;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/impl/LiteralTranslator.java:
--------------------------------------------------------------------------------
1 | package de.derivo.sparqldlapi.impl;
2 |
3 | import de.derivo.sparqldlapi.QueryArgument;
4 | import de.derivo.sparqldlapi.types.QueryArgumentType;
5 | import org.semanticweb.owlapi.model.IRI;
6 | import org.semanticweb.owlapi.model.OWLDataFactory;
7 | import org.semanticweb.owlapi.model.OWLDatatype;
8 | import org.semanticweb.owlapi.model.OWLLiteral;
9 | import org.semanticweb.owlapi.vocab.OWL2Datatype;
10 | import org.semanticweb.owlapi.vocab.XSDVocabulary;
11 |
12 | import java.util.regex.Matcher;
13 | import java.util.regex.Pattern;
14 |
15 | /**
16 | * Matthew Horridge
17 | * Stanford Center for Biomedical Informatics Research
18 | * 10/03/15
19 | */
20 | public class LiteralTranslator {
21 |
22 | private final static Pattern LITERAL_PATTERN_IRI_QUOTED = Pattern.compile("\"([^@\"]+)(@([^\"]+))?\"(\\^\\^<([^>]+)>)?");
23 | private final static Pattern LITERAL_PATTERN = Pattern.compile("\"([^@\"]+)(@([^\"]+))?\"(\\^\\^(.+))?");
24 |
25 | private OWLDataFactory dataFactory;
26 |
27 | private final OWLDatatype STRING_DATATYPE;
28 |
29 | public LiteralTranslator(OWLDataFactory dataFactory) {
30 | this.dataFactory = dataFactory;
31 | STRING_DATATYPE = dataFactory.getOWLDatatype(XSDVocabulary.STRING.getIRI());
32 | }
33 |
34 | public OWLLiteral toOWLLiteral(QueryArgument argument) {
35 | return argument.getValueAsLiteral();
36 | // Matcher matcher = LITERAL_PATTERN.matcher(argument.getValue());
37 | // if(matcher.matches()) {
38 | // String literal = matcher.group(1);
39 | // String lang = matcher.group(3);
40 | // String datatypeIRI = matcher.group(5);
41 | // if (lang != null) {
42 | // return dataFactory.getOWLLiteral(literal, lang);
43 | // }
44 | // else if (datatypeIRI != null) {
45 | // OWLDatatype datatype;
46 | // if(datatypeIRI.equals("http://www.w3.org/2001/XMLSchema#string")) {
47 | // datatype = STRING_DATATYPE;
48 | // }
49 | // else {
50 | // datatype = dataFactory.getOWLDatatype(IRI.create(datatypeIRI));
51 | // }
52 | // return dataFactory.getOWLLiteral(literal, datatype);
53 | // }
54 | // }
55 | // return dataFactory.getOWLLiteral(argument.getValue(), dataFactory.getRDFPlainLiteral());
56 | }
57 |
58 | public static QueryArgument toQueryArgument(OWLLiteral literal) {
59 | return QueryArgument.newLiteral(literal);
60 | // return toQueryArgument(literal.getLiteral(), literal.getLang(), literal.getDatatype().getIRI().toString());
61 | }
62 |
63 | // public static QueryArgument toQueryArgument(String literal, String lang, String datatypeIRI) {
64 | // StringBuilder sb = new StringBuilder();
65 | // sb.append("\"");
66 | // sb.append(literal);
67 | // if(!lang.isEmpty()) {
68 | // sb.append("@");
69 | // sb.append(lang);
70 | // }
71 | // sb.append("\"^^");
72 | // sb.append(datatypeIRI);
73 | // return new QueryArgument(QueryArgumentType.LITERAL, sb.toString());
74 | // }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/impl/QueryAtomGroupImpl.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.impl;
6 |
7 | import de.derivo.sparqldlapi.QueryAtom;
8 | import de.derivo.sparqldlapi.QueryAtomGroup;
9 | import de.derivo.sparqldlapi.QueryBinding;
10 |
11 | import java.util.Collections;
12 | import java.util.LinkedList;
13 | import java.util.List;
14 |
15 | import static com.google.common.base.Preconditions.checkNotNull;
16 |
17 | /**
18 | * Concrete implementation of the abstract Query class.
19 | *
20 | * @author Mario Volke
21 | */
22 | public class QueryAtomGroupImpl implements QueryAtomGroup {
23 |
24 | private final List atoms = new LinkedList();
25 |
26 | public QueryAtomGroupImpl() {
27 | }
28 |
29 | /**
30 | * Add an atom to the group.
31 | * This means intersection in a logical sense.
32 | */
33 | public void addAtom(QueryAtom atom) {
34 | atoms.add(checkNotNull(atom));
35 | }
36 |
37 | /**
38 | * Remove an atom from the group.
39 | */
40 | public boolean removeAtom(QueryAtom atom) {
41 | return atoms.remove(checkNotNull(atom));
42 | }
43 |
44 | /**
45 | * Check whether there are any atoms in the group.
46 | * @return True if there are no atoms at all.
47 | */
48 | public boolean isEmpty() {
49 | return atoms.isEmpty();
50 | }
51 |
52 | /**
53 | * Get the next atom to process.
54 | */
55 | public QueryAtom nextAtom() {
56 | if (isEmpty()) {
57 | return null;
58 | }
59 | return atoms.get(0);
60 | }
61 |
62 | /**
63 | * Get an unodifiable list of all query atoms.
64 | */
65 | public List getAtoms() {
66 | return Collections.unmodifiableList(atoms);
67 | }
68 |
69 | /**
70 | * A convenience method to clone the atom group instance and pop the first atom.
71 | * Only the instance itself will be cloned not the atoms.
72 | * @return A new query instance with the first atom removed.
73 | */
74 | public QueryAtomGroupImpl pop() {
75 | QueryAtomGroupImpl group = new QueryAtomGroupImpl();
76 | boolean first = true;
77 | for (QueryAtom atom : atoms) {
78 | if (first) {
79 | first = false;
80 | }
81 | else {
82 | group.addAtom(atom);
83 | }
84 | }
85 | return group;
86 | }
87 |
88 | /**
89 | * A convenience method to clone the atom group instance while inserting a new binding
90 | * to all atoms of the group.
91 | * The instance and the atoms will be cloned.
92 | */
93 | public QueryAtomGroupImpl bind(QueryBinding binding) {
94 | QueryAtomGroupImpl group = new QueryAtomGroupImpl();
95 | for (QueryAtom atom : atoms) {
96 | group.addAtom(atom.bind(binding));
97 | }
98 | return group;
99 | }
100 |
101 | /**
102 | * Print the group as string.
103 | */
104 | public String toString() {
105 | StringBuffer sb = new StringBuffer();
106 | boolean first = true;
107 | for (QueryAtom atom : atoms) {
108 | if (first) {
109 | first = false;
110 | }
111 | else {
112 | sb.append(',');
113 | sb.append(' ');
114 | }
115 | sb.append(atom);
116 | }
117 | return sb.toString();
118 | }
119 |
120 | @Override
121 | public boolean equals(Object obj) {
122 | QueryAtomGroupImpl group = (QueryAtomGroupImpl) obj;
123 | return atoms.equals(group.atoms);
124 |
125 | }
126 |
127 | @Override
128 | public int hashCode() {
129 | int hash = 7;
130 | hash = 31 * atoms.hashCode() + hash;
131 | return hash;
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/impl/QueryBindingImpl.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.impl;
6 |
7 | import java.util.HashMap;
8 | import java.util.Map;
9 | import java.util.Set;
10 |
11 | import de.derivo.sparqldlapi.QueryArgument;
12 | import de.derivo.sparqldlapi.QueryBinding;
13 |
14 | /**
15 | * Concrete implementation of the QueryBinding interface.
16 | *
17 | * @author mvolke
18 | */
19 | public class QueryBindingImpl implements QueryBinding
20 | {
21 | private Map bindingMap = new HashMap();
22 |
23 | public QueryBindingImpl()
24 | {}
25 |
26 | public QueryBindingImpl(Map bindings)
27 | {
28 | bindingMap.putAll(bindings);
29 | }
30 |
31 | /**
32 | * Get the binding of a query argument.
33 | *
34 | * @param arg
35 | * @return Null if argument is not bound, yet, or the binding otherwise.
36 | */
37 | public QueryArgument get(QueryArgument arg)
38 | {
39 | return bindingMap.get(arg);
40 | }
41 |
42 | /**
43 | * Set a binding.
44 | * Usually a binding should map from a variable to an URI or literal.
45 | * Already specified bindings will be overwritten.
46 | *
47 | * @param arg
48 | * @param binding
49 | */
50 | public void set(QueryArgument arg, QueryArgument binding)
51 | {
52 | bindingMap.put(arg, binding);
53 | }
54 |
55 | /**
56 | * Set multiple bindings at once.
57 | *
58 | * @param bindings
59 | */
60 | public void set(Map bindings)
61 | {
62 | bindingMap.putAll(bindings);
63 | }
64 |
65 | /**
66 | * Set all bindings that are already set in query binding b.
67 | *
68 | * @param b
69 | */
70 | public void set(QueryBindingImpl b)
71 | {
72 | bindingMap.putAll(b.bindingMap);
73 | }
74 |
75 | /**
76 | * Get all bound arguments.
77 | *
78 | * @return A set of bound arguments (contains usually only variables).
79 | */
80 | public Set getBoundArgs()
81 | {
82 | return bindingMap.keySet();
83 | }
84 |
85 | /**
86 | * Check whether an argument is bound.
87 | *
88 | * @param arg
89 | * @return True if the argument is bound.
90 | */
91 | public boolean isBound(QueryArgument arg)
92 | {
93 | return bindingMap.containsKey(arg);
94 | }
95 |
96 | /**
97 | * Get the number of bound arguments.
98 | *
99 | * @return The number of bound arguments.
100 | */
101 | public int size()
102 | {
103 | return bindingMap.size();
104 | }
105 |
106 | /**
107 | * Check whether there are any bindings.
108 | *
109 | * @return True if there are no bindings at all.
110 | */
111 | public boolean isEmpty()
112 | {
113 | return bindingMap.isEmpty();
114 | }
115 |
116 | /**
117 | * Clone this instance of QueryBinding.
118 | * Only the QueryBinding class itself will be cloned,
119 | * but not the query arguments.
120 | *
121 | * @return
122 | */
123 | public QueryBindingImpl clone()
124 | {
125 | return new QueryBindingImpl(bindingMap);
126 | }
127 |
128 | /**
129 | * Clone this instance of QueryBinding and filter the binding map given by args.
130 | * Only query arguments within the set of args will be available in the result.
131 | * Only the QueryBinding class itself will be cloned,
132 | * but not the query arguments.
133 | *
134 | * @return
135 | */
136 | public QueryBindingImpl cloneAndFilter(Set args)
137 | {
138 | QueryBindingImpl binding = new QueryBindingImpl();
139 | for(QueryArgument arg : getBoundArgs()) {
140 | if(args.contains(arg)) {
141 | binding.set(arg, bindingMap.get(arg));
142 | }
143 | }
144 | return binding;
145 | }
146 |
147 | @Override
148 | public boolean equals(Object obj)
149 | {
150 | QueryBindingImpl arg = (QueryBindingImpl)obj;
151 | return bindingMap.equals(arg.bindingMap);
152 | }
153 |
154 | @Override
155 | public int hashCode()
156 | {
157 | return bindingMap.hashCode();
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/impl/QueryImpl.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.impl;
6 |
7 | import java.util.ArrayList;
8 | import java.util.Collections;
9 | import java.util.HashSet;
10 | import java.util.List;
11 | import java.util.Set;
12 |
13 | import de.derivo.sparqldlapi.Query;
14 | import de.derivo.sparqldlapi.QueryArgument;
15 | import de.derivo.sparqldlapi.QueryAtomGroup;
16 | import de.derivo.sparqldlapi.types.QueryArgumentType;
17 | import de.derivo.sparqldlapi.types.QueryType;
18 |
19 | /**
20 | * Concrete implementation of the abstract Query class.
21 | *
22 | * @author Mario Volke
23 | */
24 | public class QueryImpl extends Query
25 | {
26 | private QueryType type;
27 | private List groups;
28 | private Set resultVars;
29 |
30 | public QueryImpl(QueryType type)
31 | {
32 | this.type = type;
33 | groups = new ArrayList();
34 | resultVars = new HashSet();
35 | }
36 |
37 | /**
38 | * Get the type of the query.
39 | *
40 | * @return
41 | */
42 | public QueryType getType()
43 | {
44 | return type;
45 | }
46 |
47 | /**
48 | * Add a result variable to the query.
49 | *
50 | * @param arg QueryArgument has to be a variable.
51 | */
52 | public void addResultVar(QueryArgument arg)
53 | {
54 | if(arg.getType() == QueryArgumentType.VAR) {
55 | resultVars.add(arg);
56 | }
57 | }
58 |
59 | /**
60 | * Remove a result variable from the query.
61 | *
62 | * @param atom
63 | * @return
64 | */
65 | public boolean removeResultVar(QueryArgument arg)
66 | {
67 | return resultVars.remove(arg);
68 | }
69 |
70 | /**
71 | * Check whether the given query argument is a result variable.
72 | *
73 | * @return True if the query argument is a result variable, false otherwise.
74 | */
75 | public boolean isResultVar(QueryArgument arg)
76 | {
77 | return resultVars.contains(arg);
78 | }
79 |
80 | /**
81 | * Get the number of result variables.
82 | *
83 | * @return
84 | */
85 | public int numResultVars()
86 | {
87 | return resultVars.size();
88 | }
89 |
90 | /**
91 | * Add an atom group to the query.
92 | * This means union in a logical sense.
93 | *
94 | * @param group
95 | */
96 | public void addAtomGroup(QueryAtomGroup group)
97 | {
98 | groups.add(group);
99 | }
100 |
101 | /**
102 | * Remove an atom group from the query.
103 | *
104 | * @param group
105 | * @return
106 | */
107 | public boolean removeAtomGroup(QueryAtomGroup group)
108 | {
109 | return groups.remove(group);
110 | }
111 |
112 | /**
113 | * Check whether there are any groups in the query.
114 | *
115 | * @return True if there are no atoms at all.
116 | */
117 | public boolean isEmpty()
118 | {
119 | return groups.isEmpty();
120 | }
121 |
122 | /**
123 | * Get the next group to process.
124 | *
125 | * @return
126 | */
127 | public QueryAtomGroup nextAtomGroup()
128 | {
129 | if(isEmpty()) {
130 | return null;
131 | }
132 | return groups.get(0);
133 | }
134 |
135 | /**
136 | * Get an unodifiable list of all query atom groups.
137 | *
138 | * @return
139 | */
140 | public List getAtomGroups()
141 | {
142 | return Collections.unmodifiableList(groups);
143 | }
144 |
145 | /**
146 | * Get an unodifiable set of all result variables.
147 | *
148 | * @return
149 | */
150 | public Set getResultVars()
151 | {
152 | return Collections.unmodifiableSet(resultVars);
153 | }
154 |
155 | /**
156 | * Check whether the query is of type ASK
157 | *
158 | * @return
159 | */
160 | public boolean isAsk()
161 | {
162 | return type == QueryType.ASK;
163 | }
164 |
165 | /**
166 | * Check whether the query is of type SELECT.
167 | *
168 | * @return
169 | */
170 | public boolean isSelect()
171 | {
172 | return type == QueryType.SELECT;
173 | }
174 |
175 | /**
176 | * Check whether the query is of type SELECT DISTINCT.
177 | *
178 | * @return
179 | */
180 | public boolean isSelectDistinct()
181 | {
182 | return type == QueryType.SELECT_DISTINCT;
183 | }
184 |
185 | /**
186 | * Print the SPARQL-DL query as string.
187 | *
188 | * @return String containing valid SPARQL-DL query.
189 | */
190 | public String toString()
191 | {
192 | StringBuffer sb = new StringBuffer();
193 |
194 | switch(type) {
195 | case ASK:
196 | sb.append("ASK");
197 | break;
198 | case SELECT:
199 | sb.append("SELECT");
200 | break;
201 | case SELECT_DISTINCT:
202 | sb.append("SELECT_DISTINCT");
203 | break;
204 | }
205 |
206 | for(QueryArgument arg : resultVars) {
207 | sb.append(' ');
208 | sb.append(arg.toString());
209 | }
210 |
211 | sb.append('\n');
212 |
213 | boolean first = true;
214 | for(QueryAtomGroup group : groups) {
215 | if(first) {
216 | first = false;
217 | sb.append("WHERE ");
218 | }
219 | else {
220 | sb.append("UNION ");
221 | }
222 | sb.append("{ ");
223 | sb.append(group);
224 | sb.append(" }\n");
225 | }
226 | return sb.toString();
227 | }
228 | }
229 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/impl/QueryParserImpl.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.impl;
6 |
7 | import java.util.ArrayList;
8 | import java.util.HashMap;
9 | import java.util.List;
10 | import java.util.Map;
11 |
12 | import de.derivo.sparqldlapi.*;
13 | import de.derivo.sparqldlapi.exceptions.QueryParserException;
14 | import de.derivo.sparqldlapi.impl.QueryImpl;
15 | import de.derivo.sparqldlapi.types.QueryAtomType;
16 | import de.derivo.sparqldlapi.types.QueryType;
17 | import org.semanticweb.owlapi.model.IRI;
18 | import org.semanticweb.owlapi.model.NodeID;
19 | import org.semanticweb.owlapi.model.OWLDataFactory;
20 | import org.semanticweb.owlapi.model.OWLLiteral;
21 | import org.semanticweb.owlapi.vocab.OWL2Datatype;
22 | import uk.ac.manchester.cs.owl.owlapi.OWLDataFactoryImpl;
23 |
24 | /**
25 | * Concrete implementation of the QueryParser interface.
26 | *
27 | * @author Mario Volke
28 | */
29 | public class QueryParserImpl implements QueryParser
30 | {
31 | private List tokens;
32 | private int pos;
33 | private QueryImpl query;
34 | private QueryAtomGroupImpl currentAtomGroup;
35 | private QueryAtomType currentAtomType;
36 | private List currentArgs;
37 | private Map prefixes;
38 | private final OWLDataFactory df;
39 |
40 | public QueryParserImpl() {
41 | df = new OWLDataFactoryImpl();
42 | }
43 |
44 | private void reset()
45 | {
46 | pos = 0;
47 | currentAtomType = null;
48 | currentArgs = null;
49 | tokens = null;
50 | query = null;
51 |
52 | // add standard prefixes
53 | prefixes = new HashMap();
54 | prefixes.put("rdf:", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
55 | prefixes.put("rdfs:", "http://www.w3.org/2000/01/rdf-schema#");
56 | prefixes.put("xsd:", "http://www.w3.org/2001/XMLSchema#");
57 | prefixes.put("fn:", "http://www.w3.org/2005/xpath-functions#");
58 | prefixes.put("owl:", "http://www.w3.org/2002/07/owl#");
59 | }
60 |
61 | public Query parse(List tokens)
62 | throws QueryParserException
63 | {
64 | reset();
65 |
66 | this.tokens = tokens;
67 |
68 | parsePrefixes();
69 | parseQueryHead();
70 |
71 | return query;
72 | }
73 |
74 | private void parsePrefixes()
75 | throws QueryParserException
76 | {
77 | while(tokens.get(pos).getToken().equalsIgnoreCase("PREFIX")) {
78 |
79 | if(tokens.size() < pos + 3) {
80 | throw new QueryParserException("PREFIX syntax error.", tokens.get(pos));
81 | }
82 |
83 | String uri = tokens.get(pos + 2).getToken();
84 | if(!isURI(uri)) {
85 | throw new QueryParserException("PREFIX syntax error.", tokens.get(pos + 2));
86 | }
87 |
88 | prefixes.put(tokens.get(pos + 1).getToken(), uri.substring(1, uri.length() - 1));
89 |
90 | pos += 3;
91 | }
92 | }
93 |
94 | private void parseQueryHead()
95 | throws QueryParserException
96 | {
97 | QueryToken typeToken = tokens.get(pos);
98 | QueryToken nextToken = tokens.get(pos + 1);
99 | QueryType type;
100 | if(typeToken.getToken().equalsIgnoreCase("select") && nextToken.getToken().equalsIgnoreCase("distinct")) {
101 | type = QueryType.SELECT_DISTINCT;
102 | pos++;
103 | }
104 | else {
105 | type = QueryType.fromString(typeToken.getToken());
106 | }
107 |
108 | pos++;
109 |
110 | switch(type) {
111 | case SELECT:
112 | query = new QueryImpl(QueryType.SELECT);
113 | parseSelect();
114 | break;
115 | case SELECT_DISTINCT:
116 | query = new QueryImpl(QueryType.SELECT_DISTINCT);
117 | parseSelect();
118 | break;
119 | case ASK:
120 | query = new QueryImpl(QueryType.ASK);
121 | parseAsk();
122 | break;
123 | default:
124 | throw new QueryParserException("Unknown query type.", typeToken);
125 | }
126 | }
127 |
128 | private void parseSelect()
129 | throws QueryParserException
130 | {
131 | parseResultVars();
132 |
133 | // if result var list is empty here then
134 | // we parsed "*" and we have to fetch all variables after parsing all atoms.
135 | boolean fetchResultVars = false;
136 | if(query.numResultVars() == 0) {
137 | fetchResultVars = true;
138 | }
139 |
140 | // parse first where group
141 | parseWhere();
142 |
143 | // parse optional union groups
144 | parseOrWheres();
145 |
146 | if(fetchResultVars) {
147 | for(QueryAtomGroup group : query.getAtomGroups()) {
148 | for(QueryAtom atom : group.getAtoms()) {
149 | for(QueryArgument arg : atom.getArguments()) {
150 | if(arg.isVar()) {
151 | query.addResultVar(arg);
152 | }
153 | }
154 | }
155 | }
156 | }
157 | }
158 |
159 | private void parseResultVars()
160 | throws QueryParserException
161 | {
162 | QueryToken token = tokens.get(pos);
163 |
164 | if("*".equals(token.getToken())) {
165 | pos++;
166 | return;
167 | }
168 |
169 | while(isVar(token.getToken())){
170 | query.addResultVar(QueryArgument.newVar(new Var(token.getToken().substring(1))));
171 |
172 | pos++;
173 | token = tokens.get(pos);
174 | };
175 |
176 | if(query.numResultVars() == 0) {
177 | throw new QueryParserException("Minimum one variable in result list is needed.", token);
178 | }
179 | }
180 |
181 | private void parseAsk()
182 | throws QueryParserException
183 | {
184 | parseWhere();
185 | }
186 |
187 | private void parseWhere()
188 | throws QueryParserException
189 | {
190 | currentAtomGroup = new QueryAtomGroupImpl();
191 |
192 | parseOptionalWhere();
193 | parseGroupBegin();
194 | parseAtoms();
195 | parseGroupEnd();
196 |
197 | query.addAtomGroup(currentAtomGroup);
198 | currentAtomGroup = null;
199 | }
200 |
201 | private void parseOptionalWhere()
202 | {
203 | QueryToken where = tokens.get(pos);
204 | if("where".equalsIgnoreCase(where.getToken())) {
205 | pos++;
206 | }
207 | }
208 |
209 | private void parseGroupBegin()
210 | throws QueryParserException
211 | {
212 | QueryToken grp = tokens.get(pos);
213 | if(!"{".equals(grp.getToken())) {
214 | throw new QueryParserException("Character \"{\" awaited in SPARQL-DL query.", grp);
215 | }
216 | pos++;
217 | }
218 |
219 | private void parseGroupEnd()
220 | throws QueryParserException
221 | {
222 | QueryToken grp = tokens.get(pos);
223 | if(!"}".equals(grp.getToken())) {
224 | throw new QueryParserException("Character \"}\" awaited in SPARQL-DL query.", grp);
225 | }
226 | pos++;
227 | }
228 |
229 | private void parseOrWheres()
230 | throws QueryParserException
231 | {
232 | while(pos < tokens.size()) {
233 | QueryToken or = tokens.get(pos);
234 | if(!"or".equalsIgnoreCase(or.getToken())) {
235 | break;
236 | }
237 |
238 | pos++;
239 |
240 | QueryToken where = tokens.get(pos);
241 | if(!"where".equalsIgnoreCase(where.getToken())) {
242 | throw new QueryParserException("\"WHERE\" awaited in SPARQL-DL query.", where);
243 | }
244 |
245 | pos++;
246 |
247 | currentAtomGroup = new QueryAtomGroupImpl();
248 |
249 | parseGroupBegin();
250 | parseAtoms();
251 | parseGroupEnd();
252 |
253 | // consume group
254 | query.addAtomGroup(currentAtomGroup);
255 | currentAtomGroup = null;
256 | }
257 | }
258 |
259 | private void parseAtoms()
260 | throws QueryParserException
261 | {
262 | // there could also be no atom at all
263 | // of course this doesn't make sense
264 | if("}".equals(tokens.get(pos).getToken())) {
265 | return;
266 | }
267 |
268 | while(pos < tokens.size()) {
269 | parseAtom();
270 |
271 | QueryToken delim = tokens.get(pos);
272 | if("}".equals(delim.getToken())) {
273 | break;
274 | }
275 |
276 | parseCommaDelim();
277 | }
278 | }
279 |
280 | private void parseCommaDelim()
281 | throws QueryParserException
282 | {
283 | QueryToken delim = tokens.get(pos);
284 | if(!",".equals(delim.getToken())) {
285 | throw new QueryParserException("Character \",\" awaited in SPARQL-DL query.", delim);
286 | }
287 | pos++;
288 | }
289 |
290 | private void parseAtom()
291 | throws QueryParserException
292 | {
293 | QueryToken atomNameToken = tokens.get(pos);
294 | String atomName = atomNameToken.getToken();
295 | pos++;
296 |
297 | currentAtomType = QueryAtomType.fromString(atomName);
298 | currentArgs = new ArrayList();
299 |
300 | switch(currentAtomType) {
301 | case TYPE:
302 | case DIRECT_TYPE:
303 | parseParamsListOpen();
304 | parseVariableBlankURI();
305 | parseCommaDelim();
306 | parseVariableURI();
307 | parseParamsListClose();
308 | break;
309 | case PROPERTY_VALUE:
310 | case ANNOTATION:
311 | parseParamsListOpen();
312 | parseVariableBlankURI();
313 | parseCommaDelim();
314 | parseVariableURI();
315 | parseCommaDelim();
316 | parseVariableBlankURILiteral();
317 | parseParamsListClose();
318 | break;
319 | case SAME_AS:
320 | case DIFFERENT_FROM:
321 | parseParamsListOpen();
322 | parseVariableBlankURI();
323 | parseCommaDelim();
324 | parseVariableBlankURI();
325 | parseParamsListClose();
326 | break;
327 | case EQUIVALENT_CLASS:
328 | case SUB_CLASS_OF:
329 | case DISJOINT_WITH:
330 | case COMPLEMENT_OF:
331 | case EQUIVALENT_PROPERTY:
332 | case SUB_PROPERTY_OF:
333 | case INVERSE_OF:
334 | case DOMAIN:
335 | case RANGE:
336 | case STRICT_SUB_CLASS_OF:
337 | case DIRECT_SUB_CLASS_OF:
338 | case STRICT_SUB_PROPERTY_OF:
339 | case DIRECT_SUB_PROPERTY_OF:
340 | parseParamsListOpen();
341 | parseVariableURI();
342 | parseCommaDelim();
343 | parseVariableURI();
344 | parseParamsListClose();
345 | break;
346 | case CLASS:
347 | case INDIVIDUAL:
348 | case PROPERTY:
349 | case OBJECT_PROPERTY:
350 | case DATA_PROPERTY:
351 | case FUNCTIONAL:
352 | case INVERSE_FUNCTIONAL:
353 | case TRANSITIVE:
354 | case SYMMETRIC:
355 | case REFLEXIVE:
356 | case IRREFLEXIVE:
357 | parseParamsListOpen();
358 | parseVariableURI();
359 | parseParamsListClose();
360 | break;
361 | default:
362 | throw new QueryParserException("Unknown atom in SPARQL-DL query.", atomNameToken);
363 | }
364 |
365 | // consume atom
366 | currentAtomGroup.addAtom(new QueryAtom(currentAtomType, currentArgs));
367 | currentAtomType = null;
368 | currentArgs = null;
369 | }
370 |
371 | private void parseParamsListOpen()
372 | throws QueryParserException
373 | {
374 | QueryToken token = tokens.get(pos);
375 | pos++;
376 |
377 | if(!"(".equals(token.getToken())) {
378 | throw new QueryParserException("Character \"(\" awaited in SPARQL-DL query.", token);
379 | }
380 | }
381 |
382 | private void parseParamsListClose()
383 | throws QueryParserException
384 | {
385 | QueryToken token = tokens.get(pos);
386 | pos++;
387 |
388 | if(!")".equals(token.getToken())) {
389 | throw new QueryParserException("Character \")\" awaited in SPARQL-DL query.", token);
390 | }
391 | }
392 |
393 | private void parseVariableBlankURI()
394 | throws QueryParserException
395 | {
396 | QueryToken token = tokens.get(pos);
397 | String tokenString = token.getToken();
398 | if(isPrefixURI(tokenString, prefixes)) {
399 | appendPrefixURI(tokenString);
400 | }
401 | else if(isBnode(tokenString)) {
402 | appendBnode(tokenString);
403 | }
404 | else if(isVar(tokenString)) {
405 | appendVar(tokenString);
406 | }
407 | else if(isURI(tokenString)) {
408 | appendURI(tokenString);
409 | }
410 | else {
411 | throw new QueryParserException("Variable, blank node or URI awaited as parameter in SPARQL-DL query.", token);
412 | }
413 | pos++;
414 | }
415 |
416 | private void parseVariableURI()
417 | throws QueryParserException
418 | {
419 | QueryToken token = tokens.get(pos);
420 | String tokenString = token.getToken();
421 | if(isPrefixURI(tokenString, prefixes)) {
422 | appendPrefixURI(tokenString);
423 | }
424 | else if(isVar(tokenString)) {
425 | appendVar(tokenString);
426 | }
427 | else if(isURI(tokenString)) {
428 | appendURI(tokenString);
429 | }
430 | else {
431 | throw new QueryParserException("Variable or URI awaited as parameter in SPARQL-DL query.", token);
432 | }
433 | pos++;
434 | }
435 |
436 | private void parseVariableBlankURILiteral()
437 | throws QueryParserException
438 | {
439 | QueryToken token = tokens.get(pos);
440 | String tokenString = token.getToken();
441 | if(isPrefixURI(tokenString, prefixes)) {
442 | appendPrefixURI(tokenString);
443 | }
444 | else if(isBnode(tokenString)) {
445 | appendLiteral(tokenString);
446 | }
447 | else if(isVar(tokenString)) {
448 | appendVar(tokenString);
449 | }
450 | else if(isURI(tokenString)) {
451 | appendURI(tokenString);
452 | }
453 | else if(isLiteral(tokenString)) {
454 | appendLiteral(tokenString);
455 | }
456 | else {
457 | throw new QueryParserException("Variable, blank node, URI or literal awaited as parameter in SPARQL-DL query.", token);
458 | }
459 | pos++;
460 | }
461 |
462 | @SuppressWarnings("unused")
463 | private void parseURI()
464 | throws QueryParserException
465 | {
466 | QueryToken token = tokens.get(pos);
467 | String tokenString = token.getToken();
468 | if(isPrefixURI(tokenString, prefixes)) {
469 | appendPrefixURI(tokenString);
470 | }
471 | else if(isURI(tokenString)) {
472 | appendURI(tokenString);
473 | }
474 | else {
475 | throw new QueryParserException("URI awaited as parameter in SPARQL-DL query.", token);
476 | }
477 | pos++;
478 | }
479 |
480 | @SuppressWarnings("unused")
481 | private void parseURILiteral()
482 | throws QueryParserException
483 | {
484 | QueryToken token = tokens.get(pos);
485 | String tokenString = token.getToken();
486 | if(isPrefixURI(tokenString, prefixes)) {
487 | appendPrefixURI(tokenString);
488 | }
489 | else if(isURI(tokenString)) {
490 | appendURI(tokenString);
491 | }
492 | else if(isLiteral(tokenString)) {
493 | appendLiteral(tokenString);
494 | }
495 | else {
496 | throw new QueryParserException("URI or literal awaited as parameter in SPARQL-DL query.", token);
497 | }
498 | pos++;
499 | }
500 |
501 | private void appendURI(String s)
502 | {
503 | currentArgs.add(QueryArgument.newURI(IRI.create(s.substring(1, s.length() - 1))));
504 | }
505 |
506 | private void appendPrefixURI(String s)
507 | {
508 | currentArgs.add(QueryArgument.newURI(IRI.create(uriWithPrefix(s))));
509 | }
510 |
511 | private void appendBnode(String s)
512 | {
513 | currentArgs.add(QueryArgument.newBnode(df.getOWLAnonymousIndividual(s)));
514 | }
515 |
516 | private void appendLiteral(String s)
517 | {
518 | String strippedString;
519 | if(s.startsWith("\"") && s.endsWith("\"")) {
520 | strippedString = s.substring(1, s.length() - 1);
521 | }
522 | else {
523 | strippedString = s;
524 | }
525 | OWLLiteral literal = df.getOWLLiteral(strippedString, df.getRDFPlainLiteral());
526 | currentArgs.add(QueryArgument.newLiteral(literal));
527 | }
528 |
529 | private void appendVar(String s)
530 | {
531 | currentArgs.add(QueryArgument.newVar(new Var(s.substring(1))));
532 | }
533 |
534 | private String uriWithPrefix(String s)
535 | {
536 | for(String p : prefixes.keySet()) {
537 | if(s.startsWith(p)) {
538 | return prefixes.get(p) + s.substring(p.length());
539 | }
540 | }
541 |
542 | return s;
543 | }
544 |
545 | /* static helpers */
546 |
547 | private static boolean isLiteral(String s)
548 | {
549 | return (s.length() >= 2 && s.charAt(0) == '\"' && s.charAt(s.length() - 1) == '\"');
550 | }
551 |
552 | private static boolean isBnode(String s)
553 | {
554 | return (s.length() > 2 && s.charAt(0) == '_' && s.charAt(1) == ':');
555 | }
556 |
557 | private static boolean isVar(String s)
558 | {
559 | return (s.length() > 1 && (s.charAt(0) == '?' || s.charAt(0) == '$'));
560 | }
561 |
562 | private static boolean isURI(String s)
563 | {
564 | return (s.length() >= 2 && s.charAt(0) == '<' && s.charAt(s.length() - 1) == '>');
565 | }
566 |
567 | private static boolean isPrefixURI(String s, Map prefixes)
568 | {
569 | for(String p : prefixes.keySet()) {
570 | if(s.startsWith(p)) {
571 | return true;
572 | }
573 | }
574 |
575 | return false;
576 | }
577 | }
578 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/impl/QueryResultImpl.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.impl;
6 |
7 | import java.util.ArrayList;
8 | import java.util.Iterator;
9 | import java.util.List;
10 | import java.util.Set;
11 |
12 | import org.jdom.Document;
13 | import org.jdom.Element;
14 | import org.jdom.Namespace;
15 |
16 | import de.derivo.sparqldlapi.Query;
17 | import de.derivo.sparqldlapi.QueryArgument;
18 | import de.derivo.sparqldlapi.QueryBinding;
19 | import de.derivo.sparqldlapi.QueryResult;
20 |
21 | /**
22 | * Concrete implementation of the QueryResult interface.
23 | *
24 | * @author Mario Volke
25 | */
26 | public class QueryResultImpl implements QueryResult
27 | {
28 | private List bindings;
29 | private boolean ask;
30 | private Query query;
31 |
32 | public QueryResultImpl(Query query)
33 | {
34 | bindings = new ArrayList();
35 | ask = true;
36 | this.query = query;
37 | }
38 |
39 | /**
40 | * Get the query that belongs to this result.
41 | *
42 | * @return
43 | */
44 | public Query getQuery()
45 | {
46 | return query;
47 | }
48 |
49 | /**
50 | * Add a binding to the result set.
51 | *
52 | * @param binding
53 | */
54 | public void add(QueryBindingImpl binding)
55 | {
56 | ask = true;
57 | bindings.add(binding);
58 | }
59 |
60 | /**
61 | * Set whether the query has a solution or not.
62 | *
63 | * @param s
64 | */
65 | public void setAsk(boolean s)
66 | {
67 | ask = s;
68 | }
69 |
70 | /**
71 | * Ask if the query had a solution.
72 | * This is the only result you get if the query was of type ASK.
73 | * This could also be true if the result set is empty.
74 | *
75 | * @return True if the query had a solution.
76 | */
77 | public boolean ask()
78 | {
79 | return ask;
80 | }
81 |
82 | /**
83 | * An iterator over the result set.
84 | *
85 | * @return
86 | */
87 | public Iterator iterator()
88 | {
89 | List iBindings = new ArrayList();
90 | for(QueryBindingImpl b : bindings) {
91 | iBindings.add(b);
92 | }
93 | return iBindings.iterator();
94 | }
95 |
96 | public List getBindings()
97 | {
98 | return bindings;
99 | }
100 |
101 | /**
102 | * Get the size of the result set.
103 | *
104 | * @return The size of the result set.
105 | */
106 | public int size()
107 | {
108 | return bindings.size();
109 | }
110 |
111 | /**
112 | * Returns the QueryBinding at the specified position of the result.
113 | *
114 | * @param index
115 | * @return The QueryBinding at the specified position.
116 | */
117 | public QueryBinding get(int index)
118 | {
119 | return (QueryBinding)bindings.get(index);
120 | }
121 |
122 | /**
123 | * Check whether the result set is empty.
124 | *
125 | * @return True if the result set is empty.
126 | */
127 | public boolean isEmpty()
128 | {
129 | return bindings.isEmpty();
130 | }
131 |
132 | /**
133 | * Output query results as JDOM XML document containing the standard
134 | * SPARQL query results XML format (http://www.w3.org/TR/rdf-sparql-XMLres/).
135 | * Supports both: Variable binding results and Boolean results.
136 | *
137 | * @return A JDOM XML document.
138 | */
139 | public Document toXML()
140 | {
141 | Element sparql = new Element("sparql");
142 | sparql.setNamespace(Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"));
143 |
144 | // generate head
145 | Element head = new Element("head");
146 | if(!bindings.isEmpty()) {
147 | QueryBinding top = bindings.get(0);
148 | for(QueryArgument arg : top.getBoundArgs()) {
149 | if(arg.isVar()) {
150 | Element var = new Element("variable");
151 | var.setAttribute("name", arg.getValueAsString());
152 | head.addContent(var);
153 | }
154 | }
155 | }
156 | sparql.addContent(head);
157 |
158 | if(query.isAsk()) {
159 | Element booleanElement = new Element("boolean");
160 | if(ask) {
161 | booleanElement.setText("true");
162 | }
163 | else {
164 | booleanElement.setText("false");
165 | }
166 | sparql.addContent(booleanElement);
167 | }
168 | else {
169 | // otherwise generate results
170 | Element results = new Element("results");
171 | for(QueryBinding binding : bindings) {
172 | Element result = new Element("result");
173 | for(QueryArgument key : binding.getBoundArgs()) {
174 | if(key.isVar()) {
175 | Element b = new Element("binding");
176 | b.setAttribute("name", key.getValueAsString());
177 | QueryArgument value = binding.get(key);
178 | switch(value.getType()) {
179 | case URI:
180 | Element uri = new Element("uri");
181 | uri.setText(value.getValueAsIRI().toString());
182 | b.addContent(uri);
183 | break;
184 | case LITERAL:
185 | Element literal = new Element("literal");
186 | literal.setText(value.getValueAsLiteral().getLiteral());
187 | b.addContent(literal);
188 | break;
189 | case BNODE:
190 | Element bnode = new Element("bnode");
191 | bnode.setText(value.getValueAsBNode().getID().toString());
192 | b.addContent(bnode);
193 | break;
194 | default:
195 | }
196 | result.addContent(b);
197 | }
198 | }
199 | results.addContent(result);
200 | }
201 | sparql.addContent(results);
202 | }
203 |
204 | return new Document(sparql);
205 | }
206 |
207 | /**
208 | * Output query results in JSON format as standardized in http://www.w3.org/TR/rdf-sparql-json-res/.
209 | * Supports both: Variable binding results and Boolean results.
210 | *
211 | * @return The JSON result as string.
212 | */
213 | public String toJSON()
214 | {
215 | StringBuffer sb = new StringBuffer();
216 | sb.append("{\n");
217 |
218 | // generate head
219 | sb.append("\t\"head\": {\n");
220 | if(!bindings.isEmpty()) {
221 | sb.append("\t\t\"vars\": [\n");
222 | QueryBinding top = bindings.get(0);
223 | boolean first = true;
224 | for(QueryArgument arg : top.getBoundArgs()) {
225 | if(arg.isVar()) {
226 | if(first) {
227 | first = false;
228 | }
229 | else {
230 | sb.append(",\n");
231 | }
232 | sb.append("\t\t\t\"");
233 | sb.append(arg.getValueAsString());
234 | sb.append("\"");
235 | }
236 | }
237 | sb.append("\n\t\t]\n");
238 | }
239 | sb.append("\t},\n");
240 |
241 | if(query.isAsk()) {
242 | if(ask) {
243 | sb.append("\t\"boolean\": true\n");
244 | }
245 | else {
246 | sb.append("\t\"boolean\": false\n");
247 | }
248 | }
249 | else {
250 | // otherwise generate results
251 | sb.append("\t\"results\": {\n");
252 | sb.append("\t\t\"bindings\": [\n");
253 | boolean firstBinding = true;
254 | for(QueryBinding binding : bindings) {
255 | if(firstBinding) {
256 | firstBinding = false;
257 | }
258 | else {
259 | sb.append(",\n");
260 | }
261 | sb.append("\t\t\t{\n");
262 | boolean firstVar = true;
263 | for(QueryArgument key : binding.getBoundArgs()) {
264 | if(key.isVar()) {
265 | if(firstVar) {
266 | firstVar = false;
267 | }
268 | else {
269 | sb.append(",\n");
270 | }
271 | sb.append("\t\t\t\t\"");
272 | sb.append(key.getValueAsString());
273 | sb.append("\": {\n");
274 | QueryArgument value = binding.get(key);
275 | switch(value.getType()) {
276 | case URI:
277 | sb.append("\t\t\t\t\t\"type\": \"uri\",\n");
278 | sb.append("\t\t\t\t\t\"value\": \"");
279 | sb.append(value.getValueAsIRI().toString().replaceAll("\"", "\\\\\""));
280 | sb.append("\"\n");
281 | break;
282 | case LITERAL:
283 | sb.append("\t\t\t\t\t\"type\": \"literal\",\n");
284 | sb.append("\t\t\t\t\t\"value\": \"");
285 | sb.append(value.getValueAsLiteral().getLiteral().replaceAll("\"", "\\\\\""));
286 | sb.append("\"\n");
287 | break;
288 | case BNODE:
289 | sb.append("\t\t\t\t\t\"type\": \"bnode\",\n");
290 | sb.append("\t\t\t\t\t\"value\": \"");
291 | sb.append(value.getValueAsBNode().getID().toString().replaceAll("\"", "\\\\\""));
292 | sb.append("\"\n");
293 | break;
294 | default:
295 | }
296 | sb.append("\t\t\t\t}");
297 | }
298 | }
299 | sb.append("\n\t\t\t}");
300 | }
301 | sb.append("\n\t\t]\n\t}\n");
302 | }
303 | sb.append("}\n");
304 |
305 | return sb.toString();
306 | }
307 |
308 | /**
309 | * Use this method for debugging purposes.
310 | * This is no standard format like SPARQL-XML or JSON.
311 | *
312 | * @return A nicely formatted string containing the results and bindings.
313 | */
314 | public String toString()
315 | {
316 | StringBuffer sb = new StringBuffer();
317 | for(QueryBinding binding : bindings) {
318 | Set keys = binding.getBoundArgs();
319 | boolean first = true;
320 | for(QueryArgument key : keys) {
321 | if(first) {
322 | first = false;
323 | }
324 | else {
325 | sb.append(',');
326 | sb.append(' ');
327 | }
328 | sb.append(key.toString());
329 | sb.append(' ');
330 | sb.append('=');
331 | sb.append(' ');
332 | sb.append(binding.get(key).toString());
333 | }
334 | sb.append('\n');
335 | }
336 | return sb.toString();
337 | }
338 | }
339 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/impl/QueryTokenizerImpl.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.impl;
6 |
7 | import java.util.ArrayList;
8 | import java.util.HashSet;
9 | import java.util.List;
10 | import java.util.Set;
11 |
12 | import de.derivo.sparqldlapi.QueryToken;
13 | import de.derivo.sparqldlapi.QueryTokenizer;
14 |
15 | /**
16 | * Concrete implementation of the QueryTokenizer interface.
17 | *
18 | * This tokenizer is heavily influenced by org.coode.manchesterowlsyntax.ManchesterOWLSyntaxTokenizer
19 | * of the OWL-API.
20 | *
21 | * @author Mario Volke
22 | */
23 | public class QueryTokenizerImpl implements QueryTokenizer
24 | {
25 | public static final String EOF = "";
26 | public static final char LITERAL_ESCAPE_CHAR = '\\';
27 | private Set skip = new HashSet();
28 | private Set delims = new HashSet();
29 | private String buffer;
30 | private List tokens = new ArrayList();
31 | private int pos;
32 | private int col;
33 | private int row;
34 | private int startPos;
35 | private int startCol;
36 | private int startRow;
37 | private StringBuilder sb;
38 |
39 | public QueryTokenizerImpl()
40 | {
41 | skip.add(' ');
42 | skip.add('\n');
43 | skip.add('\r');
44 | skip.add('\t');
45 | delims.add(',');
46 | delims.add('(');
47 | delims.add(')');
48 | delims.add('{');
49 | delims.add('}');
50 | }
51 |
52 | private void reset()
53 | {
54 | sb = new StringBuilder();
55 | tokens.clear();
56 | pos = 0;
57 | col = 1;
58 | row = 1;
59 | startPos = 0;
60 | startCol = 1;
61 | startRow = 1;
62 | buffer = null;
63 | }
64 |
65 | public List tokenize(String buffer)
66 | {
67 | reset();
68 |
69 | this.buffer = buffer;
70 |
71 | while(pos < buffer.length()) {
72 | char ch = readChar();
73 | if(ch == '\"') {
74 | readLiteral();
75 | }
76 | else if(skip.contains(ch)) {
77 | consumeToken();
78 | }
79 | else if(delims.contains(ch)) {
80 | consumeToken();
81 | sb.append(ch);
82 | consumeToken();
83 | }
84 | else {
85 | sb.append(ch);
86 | }
87 | }
88 | consumeToken();
89 | tokens.add(new QueryToken(EOF, pos, col, row));
90 |
91 | return tokens;
92 | }
93 |
94 | private void readLiteral()
95 | {
96 | sb.append('\"');
97 | while(pos < buffer.length()) {
98 | char ch = readChar();
99 | if(ch == LITERAL_ESCAPE_CHAR) {
100 | if(pos + 1 < buffer.length()) {
101 | char escapedChar = readChar();
102 | if(escapedChar == '"' || escapedChar == '\\') {
103 | sb.append(escapedChar);
104 | }
105 | else {
106 | sb.append(ch);
107 | sb.append(escapedChar);
108 | }
109 | }
110 | else {
111 | sb.append(ch);
112 | }
113 | }
114 | else if(ch == '\"') {
115 | sb.append(ch);
116 | break;
117 | }
118 | else {
119 | sb.append(ch);
120 | }
121 | }
122 |
123 | consumeToken();
124 | }
125 |
126 | private void consumeToken()
127 | {
128 | if(sb.length() > 0) {
129 | tokens.add(new QueryToken(sb.toString(), startPos, startCol, startRow));
130 | sb = new StringBuilder();
131 | }
132 | startPos = pos;
133 | startCol = col;
134 | startRow = row;
135 | }
136 |
137 | private char readChar()
138 | {
139 | char ch = buffer.charAt(pos);
140 | pos++;
141 | col++;
142 | if(ch == '\n') {
143 | row++;
144 | col = 0;
145 | }
146 | return ch;
147 | }
148 |
149 | public static void main(String[] args)
150 | {
151 | QueryTokenizerImpl tokenizer = new QueryTokenizerImpl();
152 | List tokens = tokenizer.tokenize("SELECT ?i ?p WHERE { Type(?i, VintageYear), Property(?i, ?p, \">?, oha \\\"\") }");
153 | for(QueryToken t : tokens) {
154 | System.out.println(t.toString());
155 | }
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/types/QueryArgumentType.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.types;
6 |
7 | /**
8 | * All possible query argument types.
9 | *
10 | * @author Mario Volke
11 | */
12 | public enum QueryArgumentType
13 | {
14 | VAR, BNODE, LITERAL, URI
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/types/QueryAtomType.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.types;
6 |
7 | /**
8 | * All possible query atoms types.
9 | *
10 | * @author Mario Volke
11 | */
12 | public enum QueryAtomType {
13 | CLASS("Class"), PROPERTY("Property"), INDIVIDUAL("Individual"),
14 | TYPE("Type"), PROPERTY_VALUE("PropertyValue"), EQUIVALENT_CLASS("EquivalentClass"),
15 | SUB_CLASS_OF("SubClassOf"), EQUIVALENT_PROPERTY("EquivalentProperty"),
16 | SUB_PROPERTY_OF("SubPropertyOf"), INVERSE_OF("InverseOf"),
17 | OBJECT_PROPERTY("ObjectProperty"), DATA_PROPERTY("DataProperty"), ANNOTATION_PROPERTY("AnnotationProperty"),
18 | FUNCTIONAL("Functional"), INVERSE_FUNCTIONAL("InverseFunctional"),
19 | TRANSITIVE("Transitive"), SYMMETRIC("Symmetric"), IRREFLEXIVE("Irreflexive"), REFLEXIVE("Reflexive"),
20 | SAME_AS("SameAs"), DISJOINT_WITH("DisjointWith"), DIFFERENT_FROM("DifferentFrom"),
21 | COMPLEMENT_OF("ComplementOf"), ANNOTATION("Annotation"), DOMAIN("Domain"), RANGE("Range"),
22 |
23 | /* class/property-hierarchy extension */
24 | STRICT_SUB_CLASS_OF("StrictSubClassOf"), DIRECT_SUB_CLASS_OF("DirectSubClassOf"),
25 | DIRECT_TYPE("DirectType"),
26 | STRICT_SUB_PROPERTY_OF("StrictSubPropertyOf"), DIRECT_SUB_PROPERTY_OF("DirectSubPropertyOf"),
27 |
28 | UKNOWN;
29 |
30 | private final String syntax;
31 |
32 | private QueryAtomType() {
33 | this(null);
34 | }
35 |
36 | private QueryAtomType(String syntax) {
37 | this.syntax = syntax;
38 | }
39 |
40 | public static QueryAtomType fromString(String str) {
41 | for (QueryAtomType value : values()) {
42 | if (value.syntax != null && value.syntax.equalsIgnoreCase(str)) {
43 | return value;
44 | }
45 | }
46 |
47 | return QueryAtomType.UKNOWN;
48 | }
49 |
50 | public String toString() {
51 | return syntax;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/de/derivo/sparqldlapi/types/QueryType.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.types;
6 |
7 | /**
8 | * All possible query types.
9 | *
10 | * @author Mario Volke
11 | */
12 | public enum QueryType
13 | {
14 | SELECT("select"), SELECT_DISTINCT("select distinct"), ASK("ask"),
15 |
16 | UNKNOWN;
17 |
18 | private final String syntax;
19 |
20 | private QueryType()
21 | {
22 | this(null);
23 | }
24 |
25 | private QueryType(String syntax)
26 | {
27 | this.syntax = syntax;
28 | }
29 |
30 | public static QueryType fromString(String str)
31 | {
32 | for(QueryType value : values()) {
33 | if(value.syntax != null && value.syntax.equalsIgnoreCase(str)) {
34 | return value;
35 | }
36 | }
37 |
38 | return QueryType.UNKNOWN;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/test/java/de/derivo/sparqldlapi/tests/AllTests.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.tests;
6 |
7 | import org.junit.runner.RunWith;
8 | import org.junit.runners.Suite;
9 | import org.junit.runners.Suite.SuiteClasses;
10 |
11 | @RunWith(Suite.class)
12 | @SuiteClasses({
13 | QueryArgumentTest.class,
14 | QueryAtomTest.class,
15 | QueryTest.class,
16 | QueryTokenTest.class,
17 | QueryTokenizerTest.class,
18 | QueryParserTest.class,
19 | QueryBindingTest.class,
20 | QueryResultTest.class,
21 | QueryEngineStrictModeTest.class
22 | })
23 | public class AllTests
24 | {}
25 |
--------------------------------------------------------------------------------
/src/test/java/de/derivo/sparqldlapi/tests/LiteralTranslator_TestCase.java:
--------------------------------------------------------------------------------
1 | package de.derivo.sparqldlapi.tests;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Matthew Horridge
7 | * Stanford Center for Biomedical Informatics Research
8 | * 10/03/15
9 | */
10 | public class LiteralTranslator_TestCase {
11 |
12 | @Test
13 | public void shouldRenderLiteral() {
14 |
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/test/java/de/derivo/sparqldlapi/tests/QueryArgumentTest.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.tests;
6 |
7 | import static org.junit.Assert.*;
8 | import static org.mockito.Mockito.mock;
9 |
10 | import de.derivo.sparqldlapi.Var;
11 | import org.junit.Test;
12 |
13 | import de.derivo.sparqldlapi.QueryArgument;
14 | import de.derivo.sparqldlapi.types.QueryArgumentType;
15 | import org.junit.runner.RunWith;
16 | import org.mockito.runners.MockitoJUnitRunner;
17 | import org.semanticweb.owlapi.model.IRI;
18 | import org.semanticweb.owlapi.model.OWLAnonymousIndividual;
19 | import org.semanticweb.owlapi.model.OWLLiteral;
20 | import uk.ac.manchester.cs.owl.owlapi.OWLLiteralImpl;
21 |
22 | /**
23 | * A jUnit 4.0 test class to test QueryArgument
24 | *
25 | * @author Mario Volke
26 | */
27 | @RunWith(MockitoJUnitRunner.class)
28 | public class QueryArgumentTest
29 | {
30 | @Test
31 | public void testGetValue()
32 | {
33 | QueryArgument arg = new QueryArgument(IRI.create("http://example.com"));
34 | assertEquals(arg.getValueAsIRI(), IRI.create("http://example.com"));
35 | }
36 |
37 | @Test
38 | public void testGetType()
39 | {
40 | QueryArgument arg = new QueryArgument(IRI.create("http://example.com"));
41 | assertEquals(arg.getType(), QueryArgumentType.URI);
42 | }
43 |
44 | @Test
45 | public void testHasType()
46 | {
47 | QueryArgument arg = new QueryArgument(IRI.create("http://example.com"));
48 | assertTrue(arg.hasType(QueryArgumentType.URI));
49 | assertFalse(arg.hasType(QueryArgumentType.VAR));
50 | }
51 |
52 | @Test
53 | public void testIsURI()
54 | {
55 | QueryArgument arg = new QueryArgument(IRI.create("http://example.com"));
56 | assertTrue(arg.isURI());
57 | QueryArgument arg2 = new QueryArgument(new Var("x"));
58 | assertFalse(arg2.isURI());
59 | }
60 |
61 | @Test
62 | public void testIsVar()
63 | {
64 | QueryArgument arg = new QueryArgument(new Var("x"));
65 | assertTrue(arg.isVar());
66 | QueryArgument arg2 = new QueryArgument(IRI.create("http://example.com"));
67 | assertFalse(arg2.isVar());
68 | }
69 |
70 | @Test
71 | public void testIsLiteral()
72 | {
73 | QueryArgument arg = new QueryArgument(mock(OWLLiteral.class));
74 | assertTrue(arg.isLiteral());
75 | QueryArgument arg2 = new QueryArgument(new Var("x"));
76 | assertFalse(arg2.isLiteral());
77 | }
78 |
79 | @Test
80 | public void testIsBnode()
81 | {
82 | QueryArgument arg = new QueryArgument(mock(OWLAnonymousIndividual.class));
83 | assertTrue(arg.isBnode());
84 | QueryArgument arg2 = new QueryArgument(new Var("x"));
85 | assertFalse(arg2.isBnode());
86 | }
87 |
88 | @Test
89 | public void testEqualsTrue()
90 | {
91 | QueryArgument arg1 = new QueryArgument(new Var("x"));
92 | QueryArgument arg2 = new QueryArgument(new Var("x"));
93 | assertTrue(arg1.equals(arg2));
94 | }
95 |
96 | @Test
97 | public void testEqualsFalse()
98 | {
99 | QueryArgument arg1 = new QueryArgument(new Var("x"));
100 | QueryArgument arg2 = new QueryArgument(mock(OWLLiteral.class));
101 | assertFalse(arg1.equals(arg2));
102 | }
103 |
104 |
105 | @Test
106 | public void testHashCodeEqualsTrue()
107 | {
108 | QueryArgument arg1 = new QueryArgument(new Var("x"));
109 | QueryArgument arg2 = new QueryArgument(new Var("x"));
110 | assertEquals(arg1.hashCode(), arg2.hashCode());
111 | }
112 |
113 | @Test
114 | public void testHashCodeEqualsFalse()
115 | {
116 | QueryArgument arg1 = new QueryArgument(new Var("x"));
117 | QueryArgument arg2 = new QueryArgument(mock(OWLLiteral.class));
118 | assertFalse(arg1.hashCode() == arg2.hashCode());
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/src/test/java/de/derivo/sparqldlapi/tests/QueryAtomTest.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.tests;
6 |
7 | import static org.junit.Assert.*;
8 |
9 | import java.util.LinkedList;
10 | import java.util.List;
11 |
12 | import de.derivo.sparqldlapi.Var;
13 | import org.junit.Test;
14 |
15 | import de.derivo.sparqldlapi.QueryArgument;
16 | import de.derivo.sparqldlapi.QueryAtom;
17 | import de.derivo.sparqldlapi.impl.QueryBindingImpl;
18 | import de.derivo.sparqldlapi.types.QueryArgumentType;
19 | import de.derivo.sparqldlapi.types.QueryAtomType;
20 | import org.semanticweb.owlapi.model.IRI;
21 |
22 | /**
23 | * A jUnit 4.0 test class to test QueryAtom
24 | *
25 | * @author Mario Volke
26 | */
27 | public class QueryAtomTest
28 | {
29 | @Test
30 | public void testIsBound()
31 | {
32 | QueryArgument arg = new QueryArgument(IRI.create("http://example.com"));
33 | QueryAtom atom = new QueryAtom(QueryAtomType.CLASS, arg);
34 | assertTrue(atom.isBound());
35 |
36 | QueryArgument arg2 = new QueryArgument(new Var("x"));
37 | QueryAtom atom2 = new QueryAtom(QueryAtomType.CLASS, arg2);
38 | assertFalse(atom2.isBound());
39 | }
40 |
41 | @Test
42 | public void testGetType()
43 | {
44 | QueryArgument arg = new QueryArgument(IRI.create("http://example.com"));
45 | QueryAtom atom = new QueryAtom(QueryAtomType.CLASS, arg);
46 | assertEquals(atom.getType(), QueryAtomType.CLASS);
47 | }
48 |
49 | @Test
50 | public void testHasType()
51 | {
52 | QueryArgument arg = new QueryArgument(IRI.create("http://example.com"));
53 | QueryAtom atom = new QueryAtom(QueryAtomType.CLASS, arg);
54 | assertTrue(atom.hasType(QueryAtomType.CLASS));
55 | assertFalse(atom.hasType(QueryAtomType.DATA_PROPERTY));
56 | }
57 |
58 | @Test
59 | public void testGetArguments()
60 | {
61 | QueryArgument arg = new QueryArgument(IRI.create("http://example.com"));
62 | QueryAtom atom = new QueryAtom(QueryAtomType.CLASS, arg);
63 |
64 | List args = new LinkedList();
65 | args.add(arg);
66 | assertEquals(atom.getArguments(), args);
67 | }
68 |
69 | @Test
70 | public void testBind()
71 | {
72 | QueryArgument arg = new QueryArgument(new Var("x"));
73 | QueryArgument arg2 = new QueryArgument(IRI.create("http://example.com"));
74 | QueryAtom atom = new QueryAtom(QueryAtomType.CLASS, arg);
75 | QueryBindingImpl binding = new QueryBindingImpl();
76 | binding.set(arg, arg2);
77 | QueryAtom boundAtom = new QueryAtom(QueryAtomType.CLASS, arg2);
78 | assertEquals(atom.bind(binding), boundAtom);
79 | }
80 |
81 | @Test
82 | public void testEqualsTrue()
83 | {
84 | QueryArgument arg1 = new QueryArgument(new Var("x"));
85 | QueryArgument arg2 = new QueryArgument(new Var("x"));
86 | QueryAtom atom1 = new QueryAtom(QueryAtomType.CLASS, arg1);
87 | QueryAtom atom2 = new QueryAtom(QueryAtomType.CLASS, arg2);
88 | assertTrue(atom1.equals(atom2));
89 | }
90 |
91 | @Test
92 | public void testEqualsFalse()
93 | {
94 | QueryArgument arg1 = new QueryArgument(new Var("x"));
95 | QueryArgument arg2 = new QueryArgument(new Var("x"));
96 | QueryAtom atom1 = new QueryAtom(QueryAtomType.CLASS, arg1);
97 | QueryAtom atom2 = new QueryAtom(QueryAtomType.DATA_PROPERTY, arg2);
98 | assertFalse(atom1.equals(atom2));
99 | }
100 |
101 |
102 | @Test
103 | public void testHashCodeEqualsTrue()
104 | {
105 | QueryArgument arg1 = new QueryArgument(new Var("x"));
106 | QueryArgument arg2 = new QueryArgument(new Var("x"));
107 | QueryAtom atom1 = new QueryAtom(QueryAtomType.CLASS, arg1);
108 | QueryAtom atom2 = new QueryAtom(QueryAtomType.CLASS, arg2);
109 | assertEquals(atom1.hashCode(), atom2.hashCode());
110 | }
111 |
112 | @Test
113 | public void testHashCodeEqualsFalse()
114 | {
115 | QueryArgument arg1 = new QueryArgument(new Var("x"));
116 | QueryArgument arg2 = new QueryArgument(new Var("x"));
117 | QueryAtom atom1 = new QueryAtom(QueryAtomType.CLASS, arg1);
118 | QueryAtom atom2 = new QueryAtom(QueryAtomType.DATA_PROPERTY, arg2);
119 | assertFalse(atom1.hashCode() == atom2.hashCode());
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/src/test/java/de/derivo/sparqldlapi/tests/QueryBindingTest.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.tests;
6 |
7 | import static org.junit.Assert.*;
8 |
9 | import java.util.HashSet;
10 | import java.util.Set;
11 |
12 | import de.derivo.sparqldlapi.Var;
13 | import org.junit.After;
14 | import org.junit.Before;
15 | import org.junit.Test;
16 |
17 | import de.derivo.sparqldlapi.QueryArgument;
18 | import de.derivo.sparqldlapi.QueryBinding;
19 | import de.derivo.sparqldlapi.impl.QueryBindingImpl;
20 | import de.derivo.sparqldlapi.types.QueryArgumentType;
21 |
22 | /**
23 | * A jUnit 4.0 test class to test the implementation of QueryBinding
24 | *
25 | * @author Mario Volke
26 | */
27 | public class QueryBindingTest
28 | {
29 | private QueryArgument varArg;
30 | private QueryArgument uriArg;
31 | private QueryArgument varArg2;
32 | private QueryArgument uriArg2;
33 |
34 | @Before
35 | public void setUp()
36 | {
37 | varArg = new QueryArgument(new Var("x"));
38 | uriArg = new QueryArgument(new Var("test"));
39 | varArg2 = new QueryArgument(new Var("y"));
40 | uriArg2 = new QueryArgument(new Var("test2"));
41 | }
42 |
43 | @After
44 | public void tearDown()
45 | {
46 | varArg = null;
47 | uriArg = null;
48 | varArg2 = null;
49 | uriArg2 = null;
50 | }
51 |
52 | @Test
53 | public void testGet()
54 | {
55 | QueryBindingImpl binding = new QueryBindingImpl();
56 | binding.set(varArg, uriArg);
57 | assertEquals(binding.get(varArg), uriArg);
58 | }
59 |
60 | @Test
61 | public void testGetNull()
62 | {
63 | QueryBindingImpl binding = new QueryBindingImpl();
64 | binding.set(varArg, uriArg);
65 | assertTrue(binding.get(uriArg) == null);
66 | }
67 |
68 | @Test
69 | public void testGetBoundArgs()
70 | {
71 | QueryBindingImpl binding = new QueryBindingImpl();
72 | binding.set(varArg, uriArg);
73 | Set boundArgs = new HashSet();
74 | boundArgs.add(varArg);
75 | assertEquals(binding.getBoundArgs(), boundArgs);
76 | }
77 |
78 | @Test
79 | public void testIsBound()
80 | {
81 | QueryBindingImpl binding = new QueryBindingImpl();
82 | binding.set(varArg, uriArg);
83 | assertTrue(binding.isBound(varArg));
84 | assertFalse(binding.isBound(uriArg));
85 | }
86 |
87 | @Test
88 | public void testSize()
89 | {
90 | QueryBindingImpl binding = new QueryBindingImpl();
91 | assertTrue(binding.size() == 0);
92 | binding.set(varArg, uriArg);
93 | assertTrue(binding.size() == 1);
94 | // no duplicate entries
95 | binding.set(varArg, uriArg);
96 | assertTrue(binding.size() == 1);
97 | binding.set(varArg2, uriArg2);
98 | assertTrue(binding.size() == 2);
99 | }
100 |
101 | @Test
102 | public void testIsEmpty()
103 | {
104 | QueryBindingImpl binding = new QueryBindingImpl();
105 | assertTrue(binding.isEmpty());
106 | binding.set(varArg, uriArg);
107 | assertFalse(binding.isEmpty());
108 | }
109 |
110 | @Test
111 | public void testEqualsTrue()
112 | {
113 | QueryBindingImpl binding1 = new QueryBindingImpl();
114 | QueryBindingImpl binding2 = new QueryBindingImpl();
115 | binding1.set(varArg, uriArg);
116 | binding2.set(varArg, uriArg);
117 | assertTrue(((QueryBinding)binding1).equals((QueryBinding)binding2));
118 | }
119 |
120 | @Test
121 | public void testEqualsFalse()
122 | {
123 | QueryBindingImpl binding1 = new QueryBindingImpl();
124 | QueryBindingImpl binding2 = new QueryBindingImpl();
125 | binding1.set(varArg, uriArg);
126 | binding2.set(varArg, uriArg2);
127 | assertFalse(((QueryBinding)binding1).equals((QueryBinding)binding2));
128 | }
129 |
130 |
131 | @Test
132 | public void testHashCodeEqualsTrue()
133 | {
134 | QueryBindingImpl binding1 = new QueryBindingImpl();
135 | QueryBindingImpl binding2 = new QueryBindingImpl();
136 | binding1.set(varArg, uriArg);
137 | binding2.set(varArg, uriArg);
138 | assertEquals(((QueryBinding)binding1).hashCode(), ((QueryBinding)binding2).hashCode());
139 | }
140 |
141 | @Test
142 | public void testHashCodeEqualsFalse()
143 | {
144 | QueryBindingImpl binding1 = new QueryBindingImpl();
145 | QueryBindingImpl binding2 = new QueryBindingImpl();
146 | binding1.set(varArg, uriArg);
147 | binding2.set(varArg, uriArg2);
148 | assertFalse(((QueryBinding)binding1).hashCode() == ((QueryBinding)binding2).hashCode());
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/src/test/java/de/derivo/sparqldlapi/tests/QueryEngineStrictModeTest.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.tests;
6 |
7 | import org.junit.After;
8 | import org.junit.Before;
9 | import org.junit.BeforeClass;
10 | import org.junit.Test;
11 | import org.semanticweb.owlapi.apibinding.OWLManager;
12 | import org.semanticweb.owlapi.model.IRI;
13 | import org.semanticweb.owlapi.model.OWLOntology;
14 | import org.semanticweb.owlapi.model.OWLOntologyCreationException;
15 | import org.semanticweb.owlapi.model.OWLOntologyManager;
16 | import org.semanticweb.owlapi.reasoner.OWLReasoner;
17 | import org.semanticweb.owlapi.reasoner.structural.StructuralReasonerFactory;
18 |
19 | import de.derivo.sparqldlapi.Query;
20 | import de.derivo.sparqldlapi.QueryEngine;
21 | import de.derivo.sparqldlapi.exceptions.QueryEngineException;
22 | import de.derivo.sparqldlapi.exceptions.QueryParserException;
23 |
24 | /**
25 | * Test for exceptions thrown in QueryEngine strict mode
26 | *
27 | * @author Mario Volke
28 | */
29 | public class QueryEngineStrictModeTest
30 | {
31 | private static final String ONTOLOGY_PREFIX = "http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#";
32 | private static OWLOntologyManager manager;
33 | private static OWLReasoner reasoner;
34 | private QueryEngine engine;
35 |
36 | @BeforeClass
37 | public static void oneTimeSetUp()
38 | {
39 | try {
40 | // Create our ontology manager in the usual way.
41 | manager = OWLManager.createOWLOntologyManager();
42 |
43 | OWLOntology ont = manager.loadOntologyFromOntologyDocument(IRI.create("http://www.w3.org/TR/owl-guide/wine.rdf"));
44 |
45 | // We need to create an instance of Reasoner.
46 | StructuralReasonerFactory factory = new StructuralReasonerFactory();
47 | reasoner = factory.createReasoner(ont);
48 | reasoner.precomputeInferences();
49 | }
50 | catch(UnsupportedOperationException exception) {
51 | System.out.println("Unsupported reasoner operation.");
52 | }
53 | catch(OWLOntologyCreationException e) {
54 | System.out.println("Could not load the wine ontology: " + e.getMessage());
55 | }
56 | }
57 |
58 | @Before
59 | public void setUp()
60 | {
61 | engine = QueryEngine.create(manager, reasoner, true);
62 | }
63 |
64 | @After
65 | public void tearDown()
66 | {
67 | engine = null;
68 | }
69 |
70 | // Class atom
71 |
72 | @Test(expected = QueryEngineException.class)
73 | public void testClassUndeclared()
74 | throws QueryParserException, QueryEngineException
75 | {
76 | Query query = Query.create("SELECT * WHERE { Class() }");
77 | engine.execute(query);
78 | }
79 |
80 | @Test(expected = QueryEngineException.class)
81 | public void testClassNotClass()
82 | throws QueryParserException, QueryEngineException
83 | {
84 | Query query = Query.create("SELECT * WHERE { Class(<" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>) }");
85 | engine.execute(query);
86 | }
87 |
88 | // Individual atom
89 |
90 | @Test(expected = QueryEngineException.class)
91 | public void testIndividualUndeclared()
92 | throws QueryParserException, QueryEngineException
93 | {
94 | Query query = Query.create("SELECT * WHERE { Individual() }");
95 | engine.execute(query);
96 | }
97 |
98 | @Test(expected = QueryEngineException.class)
99 | public void testIndividualNotIndividual()
100 | throws QueryParserException, QueryEngineException
101 | {
102 | Query query = Query.create("SELECT * WHERE { Individual(<" + ONTOLOGY_PREFIX + "Riesling>) }");
103 | engine.execute(query);
104 | }
105 |
106 | // Type atom
107 |
108 | @Test(expected = QueryEngineException.class)
109 | public void testTypeClassUndeclared()
110 | throws QueryParserException, QueryEngineException
111 | {
112 | Query query = Query.create("SELECT * WHERE { Type(?x, ) }");
113 | engine.execute(query);
114 | }
115 |
116 | @Test(expected = QueryEngineException.class)
117 | public void testTypeNotClass()
118 | throws QueryParserException, QueryEngineException
119 | {
120 | Query query = Query.create("SELECT * WHERE { Type(?x, <" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>) }");
121 | engine.execute(query);
122 | }
123 |
124 | @Test(expected = QueryEngineException.class)
125 | public void testTypeIndividualUndeclared()
126 | throws QueryParserException, QueryEngineException
127 | {
128 | Query query = Query.create("SELECT * WHERE { Type(, ?x) }");
129 | engine.execute(query);
130 | }
131 |
132 | @Test(expected = QueryEngineException.class)
133 | public void testTypeNotIndividual()
134 | throws QueryParserException, QueryEngineException
135 | {
136 | Query query = Query.create("SELECT * WHERE { Type(<" + ONTOLOGY_PREFIX + "Riesling>, ?x) }");
137 | engine.execute(query);
138 | }
139 |
140 | // DirectType atom
141 |
142 | @Test(expected = QueryEngineException.class)
143 | public void testDirectTypeClassUndeclared()
144 | throws QueryParserException, QueryEngineException
145 | {
146 | Query query = Query.create("SELECT * WHERE { DirectType(?x, ) }");
147 | engine.execute(query);
148 | }
149 |
150 | @Test(expected = QueryEngineException.class)
151 | public void testDirectTypeNotClass()
152 | throws QueryParserException, QueryEngineException
153 | {
154 | Query query = Query.create("SELECT * WHERE { DirectType(?x, <" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>) }");
155 | engine.execute(query);
156 | }
157 |
158 | @Test(expected = QueryEngineException.class)
159 | public void testDirectTypeIndividualUndeclared()
160 | throws QueryParserException, QueryEngineException
161 | {
162 | Query query = Query.create("SELECT * WHERE { DirectType(, ?x) }");
163 | engine.execute(query);
164 | }
165 |
166 | @Test(expected = QueryEngineException.class)
167 | public void testDirectTypeNotIndividual()
168 | throws QueryParserException, QueryEngineException
169 | {
170 | Query query = Query.create("SELECT * WHERE { DirectType(<" + ONTOLOGY_PREFIX + "Riesling>, ?x) }");
171 | engine.execute(query);
172 | }
173 |
174 | // PropertyValue atom
175 |
176 | @Test(expected = QueryEngineException.class)
177 | public void testPropertyValueIndividualUndeclared()
178 | throws QueryParserException, QueryEngineException
179 | {
180 | Query query = Query.create("SELECT * WHERE { PropertyValue(, ?x, ?y) }");
181 | engine.execute(query);
182 | }
183 |
184 | @Test(expected = QueryEngineException.class)
185 | public void testPropertyValueNotIndividual()
186 | throws QueryParserException, QueryEngineException
187 | {
188 | Query query = Query.create("SELECT * WHERE { PropertyValue(<" + ONTOLOGY_PREFIX + "Riesling>, ?x, ?y) }");
189 | engine.execute(query);
190 | }
191 |
192 | @Test(expected = QueryEngineException.class)
193 | public void testPropertyValuePropertyUndeclared()
194 | throws QueryParserException, QueryEngineException
195 | {
196 | Query query = Query.create("SELECT * WHERE { PropertyValue(?x, , ?y) }");
197 | engine.execute(query);
198 | }
199 |
200 | @Test(expected = QueryEngineException.class)
201 | public void testPropertyValueNotProperty()
202 | throws QueryParserException, QueryEngineException
203 | {
204 | Query query = Query.create("SELECT * WHERE { PropertyValue(?x, <" + ONTOLOGY_PREFIX + "Riesling>, ?y) }");
205 | engine.execute(query);
206 | }
207 |
208 | @Test(expected = QueryEngineException.class)
209 | public void testPropertyValueNotLiteral()
210 | throws QueryParserException, QueryEngineException
211 | {
212 | Query query = Query.create("SELECT * WHERE { PropertyValue(?x, <" + ONTOLOGY_PREFIX + "yearValue>, ) }");
213 | engine.execute(query);
214 | }
215 |
216 | @Test(expected = QueryEngineException.class)
217 | public void testPropertyValueNotUri()
218 | throws QueryParserException, QueryEngineException
219 | {
220 | Query query = Query.create("SELECT * WHERE { PropertyValue(?x, <" + ONTOLOGY_PREFIX + "locatedIn>, \"literal\") }");
221 | engine.execute(query);
222 | }
223 |
224 | @Test(expected = QueryEngineException.class)
225 | public void testPropertyValueIndividualUndeclared2()
226 | throws QueryParserException, QueryEngineException
227 | {
228 | Query query = Query.create("SELECT * WHERE { PropertyValue(?x, <" + ONTOLOGY_PREFIX + "locatedIn>, ) }");
229 | engine.execute(query);
230 | }
231 |
232 | @Test(expected = QueryEngineException.class)
233 | public void testPropertyValueNotIndividual2()
234 | throws QueryParserException, QueryEngineException
235 | {
236 | Query query = Query.create("SELECT * WHERE { PropertyValue(?x, <" + ONTOLOGY_PREFIX + "locatedIn>, <" + ONTOLOGY_PREFIX + "Riesling>) }");
237 | engine.execute(query);
238 | }
239 |
240 | // SameAs atom
241 |
242 | @Test(expected = QueryEngineException.class)
243 | public void testSameAsIndividualUndeclared()
244 | throws QueryParserException, QueryEngineException
245 | {
246 | Query query = Query.create("SELECT * WHERE { SameAs(, ?x) }");
247 | engine.execute(query);
248 | }
249 |
250 | @Test(expected = QueryEngineException.class)
251 | public void testSameAsNotIndividual()
252 | throws QueryParserException, QueryEngineException
253 | {
254 | Query query = Query.create("SELECT * WHERE { SameAs(<" + ONTOLOGY_PREFIX + "Riesling>, ?x) }");
255 | engine.execute(query);
256 | }
257 |
258 | @Test(expected = QueryEngineException.class)
259 | public void testSameAsIndividualUndeclared2()
260 | throws QueryParserException, QueryEngineException
261 | {
262 | Query query = Query.create("SELECT * WHERE { SameAs(?x, ) }");
263 | engine.execute(query);
264 | }
265 |
266 | @Test(expected = QueryEngineException.class)
267 | public void testSameAsNotIndividual2()
268 | throws QueryParserException, QueryEngineException
269 | {
270 | Query query = Query.create("SELECT * WHERE { SameAs(?x, <" + ONTOLOGY_PREFIX + "Riesling>) }");
271 | engine.execute(query);
272 | }
273 |
274 | // DifferentFrom atom
275 |
276 | @Test(expected = QueryEngineException.class)
277 | public void testDifferentFromIndividualUndeclared()
278 | throws QueryParserException, QueryEngineException
279 | {
280 | Query query = Query.create("SELECT * WHERE { DifferentFrom(, ?x) }");
281 | engine.execute(query);
282 | }
283 |
284 | @Test(expected = QueryEngineException.class)
285 | public void testDifferentFromNotIndividual()
286 | throws QueryParserException, QueryEngineException
287 | {
288 | Query query = Query.create("SELECT * WHERE { DifferentFrom(<" + ONTOLOGY_PREFIX + "Riesling>, ?x) }");
289 | engine.execute(query);
290 | }
291 |
292 | @Test(expected = QueryEngineException.class)
293 | public void testDifferentFromIndividualUndeclared2()
294 | throws QueryParserException, QueryEngineException
295 | {
296 | Query query = Query.create("SELECT * WHERE { DifferentFrom(?x, ) }");
297 | engine.execute(query);
298 | }
299 |
300 | @Test(expected = QueryEngineException.class)
301 | public void testDifferentFromNotIndividual2()
302 | throws QueryParserException, QueryEngineException
303 | {
304 | Query query = Query.create("SELECT * WHERE { DifferentFrom(?x, <" + ONTOLOGY_PREFIX + "Riesling>) }");
305 | engine.execute(query);
306 | }
307 |
308 | // SubClassOf atom
309 |
310 | @Test(expected = QueryEngineException.class)
311 | public void testSubClassOfClassUndeclared()
312 | throws QueryParserException, QueryEngineException
313 | {
314 | Query query = Query.create("SELECT * WHERE { SubClassOf(, ?x) }");
315 | engine.execute(query);
316 | }
317 |
318 | @Test(expected = QueryEngineException.class)
319 | public void testSubClassOfNotClass()
320 | throws QueryParserException, QueryEngineException
321 | {
322 | Query query = Query.create("SELECT * WHERE { SubClassOf(<" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>, ?x) }");
323 | engine.execute(query);
324 | }
325 |
326 | @Test(expected = QueryEngineException.class)
327 | public void testSubClassOfClassUndeclared2()
328 | throws QueryParserException, QueryEngineException
329 | {
330 | Query query = Query.create("SELECT * WHERE { SubClassOf(?x, ) }");
331 | engine.execute(query);
332 | }
333 |
334 | @Test(expected = QueryEngineException.class)
335 | public void testSubClassOfNotClass2()
336 | throws QueryParserException, QueryEngineException
337 | {
338 | Query query = Query.create("SELECT * WHERE { SubClassOf(?x, <" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>) }");
339 | engine.execute(query);
340 | }
341 |
342 | // DirectSubClassOf atom
343 |
344 | @Test(expected = QueryEngineException.class)
345 | public void testDirectSubClassOfClassUndeclared()
346 | throws QueryParserException, QueryEngineException
347 | {
348 | Query query = Query.create("SELECT * WHERE { DirectSubClassOf(, ?x) }");
349 | engine.execute(query);
350 | }
351 |
352 | @Test(expected = QueryEngineException.class)
353 | public void testDirectSubClassOfNotClass()
354 | throws QueryParserException, QueryEngineException
355 | {
356 | Query query = Query.create("SELECT * WHERE { DirectSubClassOf(<" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>, ?x) }");
357 | engine.execute(query);
358 | }
359 |
360 | @Test(expected = QueryEngineException.class)
361 | public void testDirectSubClassOfClassUndeclared2()
362 | throws QueryParserException, QueryEngineException
363 | {
364 | Query query = Query.create("SELECT * WHERE { DirectSubClassOf(?x, ) }");
365 | engine.execute(query);
366 | }
367 |
368 | @Test(expected = QueryEngineException.class)
369 | public void testDirectSubClassOfNotClass2()
370 | throws QueryParserException, QueryEngineException
371 | {
372 | Query query = Query.create("SELECT * WHERE { DirectSubClassOf(?x, <" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>) }");
373 | engine.execute(query);
374 | }
375 |
376 | // StrictSubClassOf atom
377 |
378 | @Test(expected = QueryEngineException.class)
379 | public void testStrictSubClassOfClassUndeclared()
380 | throws QueryParserException, QueryEngineException
381 | {
382 | Query query = Query.create("SELECT * WHERE { StrictSubClassOf(, ?x) }");
383 | engine.execute(query);
384 | }
385 |
386 | @Test(expected = QueryEngineException.class)
387 | public void testStrictSubClassOfNotClass()
388 | throws QueryParserException, QueryEngineException
389 | {
390 | Query query = Query.create("SELECT * WHERE { StrictSubClassOf(<" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>, ?x) }");
391 | engine.execute(query);
392 | }
393 |
394 | @Test(expected = QueryEngineException.class)
395 | public void testStrictSubClassOfClassUndeclared2()
396 | throws QueryParserException, QueryEngineException
397 | {
398 | Query query = Query.create("SELECT * WHERE { StrictSubClassOf(?x, ) }");
399 | engine.execute(query);
400 | }
401 |
402 | @Test(expected = QueryEngineException.class)
403 | public void testStrictSubClassOfNotClass2()
404 | throws QueryParserException, QueryEngineException
405 | {
406 | Query query = Query.create("SELECT * WHERE { StrictSubClassOf(?x, <" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>) }");
407 | engine.execute(query);
408 | }
409 |
410 | // EquivalentClass atom
411 |
412 | @Test(expected = QueryEngineException.class)
413 | public void testEquivalentClassClassUndeclared()
414 | throws QueryParserException, QueryEngineException
415 | {
416 | Query query = Query.create("SELECT * WHERE { EquivalentClass(, ?x) }");
417 | engine.execute(query);
418 | }
419 |
420 | @Test(expected = QueryEngineException.class)
421 | public void testEquivalentClassNotClass()
422 | throws QueryParserException, QueryEngineException
423 | {
424 | Query query = Query.create("SELECT * WHERE { EquivalentClass(<" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>, ?x) }");
425 | engine.execute(query);
426 | }
427 |
428 | @Test(expected = QueryEngineException.class)
429 | public void testEquivalentClassClassUndeclared2()
430 | throws QueryParserException, QueryEngineException
431 | {
432 | Query query = Query.create("SELECT * WHERE { EquivalentClass(?x, ) }");
433 | engine.execute(query);
434 | }
435 |
436 | @Test(expected = QueryEngineException.class)
437 | public void testEquivalentClassNotClass2()
438 | throws QueryParserException, QueryEngineException
439 | {
440 | Query query = Query.create("SELECT * WHERE { EquivalentClass(?x, <" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>) }");
441 | engine.execute(query);
442 | }
443 |
444 | // DisjointWith atom
445 |
446 | @Test(expected = QueryEngineException.class)
447 | public void testDisjointWithClassUndeclared()
448 | throws QueryParserException, QueryEngineException
449 | {
450 | Query query = Query.create("SELECT * WHERE { DisjointWith(, ?x) }");
451 | engine.execute(query);
452 | }
453 |
454 | @Test(expected = QueryEngineException.class)
455 | public void testDisjointWithNotClass()
456 | throws QueryParserException, QueryEngineException
457 | {
458 | Query query = Query.create("SELECT * WHERE { DisjointWith(<" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>, ?x) }");
459 | engine.execute(query);
460 | }
461 |
462 | @Test(expected = QueryEngineException.class)
463 | public void testDisjointWithClassUndeclared2()
464 | throws QueryParserException, QueryEngineException
465 | {
466 | Query query = Query.create("SELECT * WHERE { DisjointWith(?x, ) }");
467 | engine.execute(query);
468 | }
469 |
470 | @Test(expected = QueryEngineException.class)
471 | public void testDisjointWithNotClass2()
472 | throws QueryParserException, QueryEngineException
473 | {
474 | Query query = Query.create("SELECT * WHERE { DisjointWith(?x, <" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>) }");
475 | engine.execute(query);
476 | }
477 |
478 | // ComplementOf atom
479 |
480 | @Test(expected = QueryEngineException.class)
481 | public void testComplementOfClassUndeclared()
482 | throws QueryParserException, QueryEngineException
483 | {
484 | Query query = Query.create("SELECT * WHERE { ComplementOf(, ?x) }");
485 | engine.execute(query);
486 | }
487 |
488 | @Test(expected = QueryEngineException.class)
489 | public void testComplementOfNotClass()
490 | throws QueryParserException, QueryEngineException
491 | {
492 | Query query = Query.create("SELECT * WHERE { ComplementOf(<" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>, ?x) }");
493 | engine.execute(query);
494 | }
495 |
496 | @Test(expected = QueryEngineException.class)
497 | public void testComplementOfClassUndeclared2()
498 | throws QueryParserException, QueryEngineException
499 | {
500 | Query query = Query.create("SELECT * WHERE { ComplementOf(?x, ) }");
501 | engine.execute(query);
502 | }
503 |
504 | @Test(expected = QueryEngineException.class)
505 | public void testComplementOfNotClass2()
506 | throws QueryParserException, QueryEngineException
507 | {
508 | Query query = Query.create("SELECT * WHERE { ComplementOf(?x, <" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>) }");
509 | engine.execute(query);
510 | }
511 |
512 | // SubPropertyOf atom
513 |
514 | @Test(expected = QueryEngineException.class)
515 | public void testSubPropertyOfPropertyUndeclared()
516 | throws QueryParserException, QueryEngineException
517 | {
518 | Query query = Query.create("SELECT * WHERE { SubPropertyOf(, ?x) }");
519 | engine.execute(query);
520 | }
521 |
522 | @Test(expected = QueryEngineException.class)
523 | public void testSubPropertyOfNotProperty()
524 | throws QueryParserException, QueryEngineException
525 | {
526 | Query query = Query.create("SELECT * WHERE { SubPropertyOf(<" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>, ?x) }");
527 | engine.execute(query);
528 | }
529 |
530 | @Test(expected = QueryEngineException.class)
531 | public void testSubPropertyOfPropertyUndeclared2()
532 | throws QueryParserException, QueryEngineException
533 | {
534 | Query query = Query.create("SELECT * WHERE { SubPropertyOf(?x, ) }");
535 | engine.execute(query);
536 | }
537 |
538 | @Test(expected = QueryEngineException.class)
539 | public void testSubPropertyOfNotProperty2()
540 | throws QueryParserException, QueryEngineException
541 | {
542 | Query query = Query.create("SELECT * WHERE { SubPropertyOf(?x, <" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>) }");
543 | engine.execute(query);
544 | }
545 |
546 | // DirectSubPropertyOf atom
547 |
548 | @Test(expected = QueryEngineException.class)
549 | public void testDirectSubPropertyOfPropertyUndeclared()
550 | throws QueryParserException, QueryEngineException
551 | {
552 | Query query = Query.create("SELECT * WHERE { DirectSubPropertyOf(, ?x) }");
553 | engine.execute(query);
554 | }
555 |
556 | @Test(expected = QueryEngineException.class)
557 | public void testDirectSubPropertyOfNotProperty()
558 | throws QueryParserException, QueryEngineException
559 | {
560 | Query query = Query.create("SELECT * WHERE { DirectSubPropertyOf(<" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>, ?x) }");
561 | engine.execute(query);
562 | }
563 |
564 | @Test(expected = QueryEngineException.class)
565 | public void testDirectSubPropertyOfPropertyUndeclared2()
566 | throws QueryParserException, QueryEngineException
567 | {
568 | Query query = Query.create("SELECT * WHERE { DirectSubPropertyOf(?x, ) }");
569 | engine.execute(query);
570 | }
571 |
572 | @Test(expected = QueryEngineException.class)
573 | public void testDirectSubPropertyOfNotProperty2()
574 | throws QueryParserException, QueryEngineException
575 | {
576 | Query query = Query.create("SELECT * WHERE { DirectSubPropertyOf(?x, <" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>) }");
577 | engine.execute(query);
578 | }
579 |
580 | // StrictSubPropertyOf atom
581 |
582 | @Test(expected = QueryEngineException.class)
583 | public void testStrictSubPropertyOfPropertyUndeclared()
584 | throws QueryParserException, QueryEngineException
585 | {
586 | Query query = Query.create("SELECT * WHERE { StrictSubPropertyOf(, ?x) }");
587 | engine.execute(query);
588 | }
589 |
590 | @Test(expected = QueryEngineException.class)
591 | public void testStrictSubPropertyOfNotProperty()
592 | throws QueryParserException, QueryEngineException
593 | {
594 | Query query = Query.create("SELECT * WHERE { StrictSubPropertyOf(<" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>, ?x) }");
595 | engine.execute(query);
596 | }
597 |
598 | @Test(expected = QueryEngineException.class)
599 | public void testStrictSubPropertyOfPropertyUndeclared2()
600 | throws QueryParserException, QueryEngineException
601 | {
602 | Query query = Query.create("SELECT * WHERE { StrictSubPropertyOf(?x, ) }");
603 | engine.execute(query);
604 | }
605 |
606 | @Test(expected = QueryEngineException.class)
607 | public void testStrictSubPropertyOfNotProperty2()
608 | throws QueryParserException, QueryEngineException
609 | {
610 | Query query = Query.create("SELECT * WHERE { StrictSubPropertyOf(?x, <" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>) }");
611 | engine.execute(query);
612 | }
613 |
614 | // EquivalentProperty atom
615 |
616 | @Test(expected = QueryEngineException.class)
617 | public void testEquivalentPropertyPropertyUndeclared()
618 | throws QueryParserException, QueryEngineException
619 | {
620 | Query query = Query.create("SELECT * WHERE { EquivalentProperty(, ?x) }");
621 | engine.execute(query);
622 | }
623 |
624 | @Test(expected = QueryEngineException.class)
625 | public void testEquivalentPropertyNotProperty()
626 | throws QueryParserException, QueryEngineException
627 | {
628 | Query query = Query.create("SELECT * WHERE { EquivalentProperty(<" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>, ?x) }");
629 | engine.execute(query);
630 | }
631 |
632 | @Test(expected = QueryEngineException.class)
633 | public void testEquivalentPropertyPropertyUndeclared2()
634 | throws QueryParserException, QueryEngineException
635 | {
636 | Query query = Query.create("SELECT * WHERE { EquivalentProperty(?x, ) }");
637 | engine.execute(query);
638 | }
639 |
640 | @Test(expected = QueryEngineException.class)
641 | public void testEquivalentPropertyNotProperty2()
642 | throws QueryParserException, QueryEngineException
643 | {
644 | Query query = Query.create("SELECT * WHERE { EquivalentProperty(?x, <" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>) }");
645 | engine.execute(query);
646 | }
647 |
648 | // InverseOf atom
649 |
650 | @Test(expected = QueryEngineException.class)
651 | public void testInverseOfPropertyUndeclared()
652 | throws QueryParserException, QueryEngineException
653 | {
654 | Query query = Query.create("SELECT * WHERE { InverseOf(, ?x) }");
655 | engine.execute(query);
656 | }
657 |
658 | @Test(expected = QueryEngineException.class)
659 | public void testInverseOfNotProperty()
660 | throws QueryParserException, QueryEngineException
661 | {
662 | Query query = Query.create("SELECT * WHERE { InverseOf(<" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>, ?x) }");
663 | engine.execute(query);
664 | }
665 |
666 | @Test(expected = QueryEngineException.class)
667 | public void testInverseOfPropertyUndeclared2()
668 | throws QueryParserException, QueryEngineException
669 | {
670 | Query query = Query.create("SELECT * WHERE { InverseOf(?x, ) }");
671 | engine.execute(query);
672 | }
673 |
674 | @Test(expected = QueryEngineException.class)
675 | public void testInverseOfNotProperty2()
676 | throws QueryParserException, QueryEngineException
677 | {
678 | Query query = Query.create("SELECT * WHERE { InverseOf(?x, <" + ONTOLOGY_PREFIX + "StonleighSauvignonBlanc>) }");
679 | engine.execute(query);
680 | }
681 |
682 | // ObjectProperty atom
683 |
684 | @Test(expected = QueryEngineException.class)
685 | public void testObjectPropertyPropertyUndeclared()
686 | throws QueryParserException, QueryEngineException
687 | {
688 | Query query = Query.create("SELECT * WHERE { ObjectProperty() }");
689 | engine.execute(query);
690 | }
691 |
692 | @Test(expected = QueryEngineException.class)
693 | public void testObjectPropertyNotProperty()
694 | throws QueryParserException, QueryEngineException
695 | {
696 | Query query = Query.create("SELECT * WHERE { ObjectProperty(<" + ONTOLOGY_PREFIX + "yearValue>) }");
697 | engine.execute(query);
698 | }
699 |
700 | // InverseFunctional atom
701 |
702 | @Test(expected = QueryEngineException.class)
703 | public void testInverseFunctionalPropertyUndeclared()
704 | throws QueryParserException, QueryEngineException
705 | {
706 | Query query = Query.create("SELECT * WHERE { InverseFunctional() }");
707 | engine.execute(query);
708 | }
709 |
710 | @Test(expected = QueryEngineException.class)
711 | public void testInverseFunctionalNotProperty()
712 | throws QueryParserException, QueryEngineException
713 | {
714 | Query query = Query.create("SELECT * WHERE { InverseFunctional(<" + ONTOLOGY_PREFIX + "yearValue>) }");
715 | engine.execute(query);
716 | }
717 |
718 | // Symmetric atom
719 |
720 | @Test(expected = QueryEngineException.class)
721 | public void testSymmetricPropertyUndeclared()
722 | throws QueryParserException, QueryEngineException
723 | {
724 | Query query = Query.create("SELECT * WHERE { Symmetric() }");
725 | engine.execute(query);
726 | }
727 |
728 | @Test(expected = QueryEngineException.class)
729 | public void testSymmetricNotProperty()
730 | throws QueryParserException, QueryEngineException
731 | {
732 | Query query = Query.create("SELECT * WHERE { Symmetric(<" + ONTOLOGY_PREFIX + "yearValue>) }");
733 | engine.execute(query);
734 | }
735 |
736 | // Transitive atom
737 |
738 | @Test(expected = QueryEngineException.class)
739 | public void testTransitivePropertyUndeclared()
740 | throws QueryParserException, QueryEngineException
741 | {
742 | Query query = Query.create("SELECT * WHERE { Transitive() }");
743 | engine.execute(query);
744 | }
745 |
746 | @Test(expected = QueryEngineException.class)
747 | public void testTransitiveNotProperty()
748 | throws QueryParserException, QueryEngineException
749 | {
750 | Query query = Query.create("SELECT * WHERE { Transitive(<" + ONTOLOGY_PREFIX + "yearValue>) }");
751 | engine.execute(query);
752 | }
753 |
754 | // Irreflexive atom
755 |
756 | @Test(expected = QueryEngineException.class)
757 | public void testIrreflexivePropertyUndeclared()
758 | throws QueryParserException, QueryEngineException
759 | {
760 | Query query = Query.create("SELECT * WHERE { Irreflexive() }");
761 | engine.execute(query);
762 | }
763 |
764 | @Test(expected = QueryEngineException.class)
765 | public void testIrreflexiveNotProperty()
766 | throws QueryParserException, QueryEngineException
767 | {
768 | Query query = Query.create("SELECT * WHERE { Irreflexive(<" + ONTOLOGY_PREFIX + "yearValue>) }");
769 | engine.execute(query);
770 | }
771 |
772 | // DataProperty atom
773 |
774 | @Test(expected = QueryEngineException.class)
775 | public void testDataPropertyPropertyUndeclared()
776 | throws QueryParserException, QueryEngineException
777 | {
778 | Query query = Query.create("SELECT * WHERE { DataProperty() }");
779 | engine.execute(query);
780 | }
781 |
782 | @Test(expected = QueryEngineException.class)
783 | public void testDataPropertyNotProperty()
784 | throws QueryParserException, QueryEngineException
785 | {
786 | Query query = Query.create("SELECT * WHERE { DataProperty(<" + ONTOLOGY_PREFIX + "locatedIn>) }");
787 | engine.execute(query);
788 | }
789 |
790 | // Property atom
791 |
792 | @Test(expected = QueryEngineException.class)
793 | public void testPropertyPropertyUndeclared()
794 | throws QueryParserException, QueryEngineException
795 | {
796 | Query query = Query.create("SELECT * WHERE { Property() }");
797 | engine.execute(query);
798 | }
799 |
800 | @Test(expected = QueryEngineException.class)
801 | public void testPropertyNotProperty()
802 | throws QueryParserException, QueryEngineException
803 | {
804 | Query query = Query.create("SELECT * WHERE { Property(<" + ONTOLOGY_PREFIX + "Riesling>) }");
805 | engine.execute(query);
806 | }
807 |
808 | // Functional atom
809 |
810 | @Test(expected = QueryEngineException.class)
811 | public void testFunctionalPropertyUndeclared()
812 | throws QueryParserException, QueryEngineException
813 | {
814 | Query query = Query.create("SELECT * WHERE { Functional() }");
815 | engine.execute(query);
816 | }
817 |
818 | @Test(expected = QueryEngineException.class)
819 | public void testFunctionalNotProperty()
820 | throws QueryParserException, QueryEngineException
821 | {
822 | Query query = Query.create("SELECT * WHERE { Functional(<" + ONTOLOGY_PREFIX + "Riesling>) }");
823 | engine.execute(query);
824 | }
825 |
826 | // Annotation atom
827 |
828 | @Test(expected = QueryEngineException.class)
829 | public void testAnnotationUndeclared()
830 | throws QueryParserException, QueryEngineException
831 | {
832 | Query query = Query.create("SELECT * WHERE { Annotation(, ?x, ?y) }");
833 | engine.execute(query);
834 | }
835 |
836 | @Test(expected = QueryEngineException.class)
837 | public void testAnnotationUndeclared2()
838 | throws QueryParserException, QueryEngineException
839 | {
840 | Query query = Query.create("SELECT * WHERE { Annotation(?x, , ?y) }");
841 | engine.execute(query);
842 | }
843 |
844 | @Test(expected = QueryEngineException.class)
845 | public void testAnnotationNotAnnotation()
846 | throws QueryParserException, QueryEngineException
847 | {
848 | Query query = Query.create("SELECT * WHERE { Annotation(?x, <" + ONTOLOGY_PREFIX + "Riesling>, ?y) }");
849 | engine.execute(query);
850 | }
851 | }
852 |
--------------------------------------------------------------------------------
/src/test/java/de/derivo/sparqldlapi/tests/QueryParserTest.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.tests;
6 |
7 | import static org.junit.Assert.*;
8 |
9 | import java.util.HashSet;
10 | import java.util.LinkedList;
11 | import java.util.List;
12 | import java.util.Set;
13 |
14 | import de.derivo.sparqldlapi.*;
15 | import org.junit.Test;
16 |
17 | import de.derivo.sparqldlapi.exceptions.QueryParserException;
18 | import de.derivo.sparqldlapi.impl.QueryParserImpl;
19 | import de.derivo.sparqldlapi.impl.QueryTokenizerImpl;
20 | import de.derivo.sparqldlapi.types.QueryArgumentType;
21 | import de.derivo.sparqldlapi.types.QueryAtomType;
22 | import de.derivo.sparqldlapi.types.QueryType;
23 | import org.semanticweb.owlapi.model.IRI;
24 |
25 | /**
26 | * A jUnit 4.0 test class to test the implementation of QueryParser
27 | *
28 | * @author Mario Volke
29 | */
30 | public class QueryParserTest
31 | {
32 | @Test
33 | public void testParseSelect()
34 | throws QueryParserException
35 | {
36 | QueryTokenizer tokenizer = new QueryTokenizerImpl();
37 | List tokens = tokenizer.tokenize(
38 | "PREFIX wine: \n" +
39 | "PREFIX foaf: \n" +
40 | "SELECT * WHERE { PropertyValue(?i, wine:hasColor, ?v), PropertyValue(?p, foaf:name, \"foo \\\" bar\") }"
41 | );
42 |
43 | QueryParser parser = new QueryParserImpl();
44 | Query query = parser.parse(tokens);
45 |
46 | Set resultVars = new HashSet();
47 | resultVars.add(new QueryArgument(new Var("i")));
48 | resultVars.add(new QueryArgument(new Var("v")));
49 | resultVars.add(new QueryArgument(new Var("p")));
50 |
51 | List atoms = new LinkedList();
52 | atoms.add(new QueryAtom(
53 | QueryAtomType.PROPERTY_VALUE,
54 | new QueryArgument(new Var("i")),
55 | new QueryArgument(IRI.create("http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#hasColor")),
56 | new QueryArgument(new Var("v"))
57 | ));
58 | atoms.add(new QueryAtom(
59 | QueryAtomType.PROPERTY_VALUE,
60 | new QueryArgument(new Var("p")),
61 | new QueryArgument(IRI.create("http://xmlns.com/foaf/0.1/name")),
62 | new QueryArgument(IRI.create("\"foo \" bar\"^^http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral"))
63 | ));
64 |
65 | assertEquals(query.getType(), QueryType.SELECT);
66 | assertEquals(query.getResultVars(), resultVars);
67 | // assertEquals(query.getAtomGroups().get(0).getAtoms(), atoms);
68 | }
69 |
70 | @Test(expected = QueryParserException.class)
71 | public void testParseSelectWithException()
72 | throws QueryParserException
73 | {
74 | QueryTokenizer tokenizer = new QueryTokenizerImpl();
75 | List tokens = tokenizer.tokenize(
76 | "SELECT * WHERE { PropertyValue(?i, wine:hasColor, ?v)"
77 | );
78 |
79 | QueryParser parser = new QueryParserImpl();
80 | parser.parse(tokens);
81 | }
82 |
83 | @Test
84 | public void testParseSelectDistinct()
85 | throws QueryParserException
86 | {
87 | QueryTokenizer tokenizer = new QueryTokenizerImpl();
88 | List tokens = tokenizer.tokenize(
89 | "PREFIX wine: \n" +
90 | "PREFIX foaf: \n" +
91 | "SELECT DISTINCT * WHERE { PropertyValue(?i, wine:hasColor, ?v), PropertyValue(?p, foaf:name, \"foo \\\" bar\") }"
92 | );
93 |
94 | QueryParser parser = new QueryParserImpl();
95 | Query query = parser.parse(tokens);
96 |
97 | Set resultVars = new HashSet();
98 | resultVars.add(new QueryArgument(new Var("i")));
99 | resultVars.add(new QueryArgument(new Var("v")));
100 | resultVars.add(new QueryArgument(new Var("p")));
101 |
102 | List atoms = new LinkedList();
103 | atoms.add(new QueryAtom(
104 | QueryAtomType.PROPERTY_VALUE,
105 | new QueryArgument(new Var("i")),
106 | new QueryArgument(IRI.create("http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#hasColor")),
107 | new QueryArgument(new Var("v"))
108 | ));
109 | atoms.add(new QueryAtom(
110 | QueryAtomType.PROPERTY_VALUE,
111 | new QueryArgument(new Var("p")),
112 | new QueryArgument(IRI.create("http://xmlns.com/foaf/0.1/name")),
113 | new QueryArgument(IRI.create("foo \" bar^^http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral"))
114 | ));
115 |
116 | assertEquals(query.getType(), QueryType.SELECT_DISTINCT);
117 | assertEquals(query.getResultVars(), resultVars);
118 | // assertEquals(query.getAtomGroups().get(0).getAtoms(), atoms);
119 | }
120 |
121 |
122 | @Test
123 | public void testParseAsk()
124 | throws QueryParserException
125 | {
126 | QueryTokenizer tokenizer = new QueryTokenizerImpl();
127 | List tokens = tokenizer.tokenize(
128 | "PREFIX wine: \n" +
129 | "ASK { PropertyValue(?i, wine:hasColor, ?v) }"
130 | );
131 |
132 | QueryParser parser = new QueryParserImpl();
133 | Query query = parser.parse(tokens);
134 |
135 | Set resultVars = new HashSet();
136 |
137 | List atoms = new LinkedList();
138 | atoms.add(new QueryAtom(
139 | QueryAtomType.PROPERTY_VALUE,
140 | new QueryArgument(new Var("i")),
141 | new QueryArgument(IRI.create("http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#hasColor")),
142 | new QueryArgument(new Var("v"))
143 | ));
144 |
145 | assertEquals(query.getType(), QueryType.ASK);
146 | assertEquals(query.getResultVars(), resultVars);
147 | assertEquals(query.getAtomGroups().get(0).getAtoms(), atoms);
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/src/test/java/de/derivo/sparqldlapi/tests/QueryResultTest.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.tests;
6 |
7 | import static org.junit.Assert.*;
8 | import static org.mockito.Mockito.mock;
9 |
10 | import de.derivo.sparqldlapi.*;
11 | import org.junit.After;
12 | import org.junit.Before;
13 | import org.junit.Test;
14 |
15 | import de.derivo.sparqldlapi.impl.QueryAtomGroupImpl;
16 | import de.derivo.sparqldlapi.impl.QueryBindingImpl;
17 | import de.derivo.sparqldlapi.impl.QueryImpl;
18 | import de.derivo.sparqldlapi.impl.QueryResultImpl;
19 | import de.derivo.sparqldlapi.types.QueryArgumentType;
20 | import de.derivo.sparqldlapi.types.QueryAtomType;
21 | import de.derivo.sparqldlapi.types.QueryType;
22 | import org.semanticweb.owlapi.model.IRI;
23 | import org.semanticweb.owlapi.model.OWLLiteral;
24 |
25 | /**
26 | * A jUnit 4.0 test class to test the implementation of QueryResult
27 | *
28 | * @author Mario Volke
29 | */
30 | public class QueryResultTest
31 | {
32 | private Query query;
33 | private QueryAtomGroup group;
34 | private QueryAtom atom;
35 | private QueryArgument arg1, arg2, arg3;
36 |
37 | @Before
38 | public void setUp()
39 | {
40 | arg1 = new QueryArgument(new Var("x"));
41 | arg2 = new QueryArgument(IRI.create("http://xmlns.com/foaf/0.1/name"));
42 | arg3 = new QueryArgument(mock(OWLLiteral.class));
43 |
44 | atom = new QueryAtom(QueryAtomType.PROPERTY_VALUE, arg1, arg2, arg3);
45 |
46 | QueryAtomGroupImpl groupImpl = new QueryAtomGroupImpl();
47 | groupImpl.addAtom(atom);
48 | group = groupImpl;
49 |
50 | QueryImpl queryImpl = new QueryImpl(QueryType.SELECT);
51 | queryImpl.addAtomGroup(group);
52 | queryImpl.addResultVar(arg1);
53 | query = queryImpl;
54 | }
55 |
56 | @After
57 | public void tearDown()
58 | {
59 | arg1 = null;
60 | arg2 = null;
61 | arg3 = null;
62 | group = null;
63 | atom = null;
64 | query = null;
65 | }
66 |
67 | @Test
68 | public void testGetQuery()
69 | {
70 | QueryResult result = new QueryResultImpl(query);
71 | assertSame(result.getQuery(), query);
72 | }
73 |
74 | @Test
75 | public void testSize()
76 | {
77 | QueryResultImpl result = new QueryResultImpl(query);
78 | assertTrue(result.size() == 0);
79 |
80 | QueryArgument boundArg = new QueryArgument(IRI.create("http://example.com"));
81 | QueryBindingImpl binding = new QueryBindingImpl();
82 | binding.set(arg1, boundArg);
83 | result.add(binding);
84 | assertTrue(result.size() == 1);
85 | }
86 |
87 | @Test
88 | public void testGet()
89 | {
90 | QueryResultImpl result = new QueryResultImpl(query);
91 | QueryArgument boundArg = new QueryArgument(IRI.create("http://example.com"));
92 | QueryBindingImpl binding = new QueryBindingImpl();
93 | binding.set(arg1, boundArg);
94 | result.add(binding);
95 | assertEquals(result.get(0), binding);
96 | }
97 |
98 | @Test(expected = IndexOutOfBoundsException.class)
99 | public void testGetWithException()
100 | {
101 | QueryResult result = new QueryResultImpl(query);
102 | result.get(0);
103 | }
104 |
105 | @Test
106 | public void testIsEmpty()
107 | {
108 | QueryResultImpl result = new QueryResultImpl(query);
109 | assertTrue(result.isEmpty());
110 |
111 | QueryArgument boundArg = new QueryArgument(IRI.create("http://example.com"));
112 | QueryBindingImpl binding = new QueryBindingImpl();
113 | binding.set(arg1, boundArg);
114 | result.add(binding);
115 | assertFalse(result.isEmpty());
116 | }
117 |
118 | @Test
119 | public void testAsk()
120 | {
121 | QueryResultImpl result = new QueryResultImpl(query);
122 | result.setAsk(true);
123 | assertTrue(result.ask());
124 | result.setAsk(false);
125 | assertFalse(result.ask());
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/src/test/java/de/derivo/sparqldlapi/tests/QueryTest.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.tests;
6 |
7 | import static org.junit.Assert.*;
8 |
9 | import java.util.HashSet;
10 | import java.util.LinkedList;
11 | import java.util.List;
12 | import java.util.Set;
13 |
14 | import de.derivo.sparqldlapi.Var;
15 | import org.junit.Test;
16 |
17 | import de.derivo.sparqldlapi.Query;
18 | import de.derivo.sparqldlapi.QueryArgument;
19 | import de.derivo.sparqldlapi.QueryAtomGroup;
20 | import de.derivo.sparqldlapi.impl.QueryAtomGroupImpl;
21 | import de.derivo.sparqldlapi.impl.QueryImpl;
22 | import de.derivo.sparqldlapi.types.QueryArgumentType;
23 | import de.derivo.sparqldlapi.types.QueryType;
24 | import org.semanticweb.owlapi.model.IRI;
25 |
26 | /**
27 | * A jUnit 4.0 test class to test the implementation of Query
28 | *
29 | * @author Mario Volke
30 | */
31 | public class QueryTest
32 | {
33 | @Test
34 | public void testIsEmpty()
35 | {
36 | QueryImpl query = new QueryImpl(QueryType.ASK);
37 | assertTrue(query.isEmpty());
38 | query.addAtomGroup(new QueryAtomGroupImpl());
39 | assertFalse(query.isEmpty());
40 | }
41 |
42 | @Test
43 | public void testGetType()
44 | {
45 | Query query = new QueryImpl(QueryType.ASK);
46 | assertEquals(query.getType(), QueryType.ASK);
47 | }
48 |
49 | @Test
50 | public void testIsResultVariable()
51 | {
52 | QueryImpl query = new QueryImpl(QueryType.SELECT);
53 | QueryArgument arg = new QueryArgument(new Var("x"));
54 |
55 | assertFalse(query.isResultVar(arg));
56 |
57 | query.addResultVar(arg);
58 | assertTrue(query.isResultVar(arg));
59 | }
60 |
61 | @Test
62 | public void testNumResultVars()
63 | {
64 | QueryImpl query = new QueryImpl(QueryType.SELECT);
65 | QueryArgument arg = new QueryArgument(new Var("x"));
66 |
67 | assertEquals(query.numResultVars(), 0);
68 |
69 | query.addResultVar(arg);
70 | assertEquals(query.numResultVars(), 1);
71 |
72 | // no duplicate entries
73 | query.addResultVar(arg);
74 | assertEquals(query.numResultVars(), 1);
75 |
76 | // no other entries than variables
77 | QueryArgument arg2 = new QueryArgument(IRI.create("http://example.com"));
78 | query.addResultVar(arg2);
79 | assertEquals(query.numResultVars(), 1);
80 | }
81 |
82 | @Test
83 | public void testGetResultVars()
84 | {
85 | QueryImpl query = new QueryImpl(QueryType.SELECT);
86 | QueryArgument arg = new QueryArgument(new Var("x"));
87 | query.addResultVar(arg);
88 |
89 | // no duplicate entries
90 | query.addResultVar(arg);
91 |
92 | // no other entries than variables
93 | QueryArgument arg2 = new QueryArgument(IRI.create("http://example.com"));
94 | query.addResultVar(arg2);
95 |
96 | Set resultVars = new HashSet();
97 | resultVars.add(arg);
98 | assertEquals(query.getResultVars(), resultVars);
99 | }
100 |
101 | @Test
102 | public void testGetAtomGroups()
103 | {
104 | QueryImpl query = new QueryImpl(QueryType.SELECT);
105 | QueryAtomGroup group = new QueryAtomGroupImpl();
106 | query.addAtomGroup(group);
107 |
108 | List groups = new LinkedList();
109 | groups.add(group);
110 | assertEquals(query.getAtomGroups(), groups);
111 | }
112 |
113 |
114 | @Test
115 | public void testIsAsk()
116 | {
117 | Query query = new QueryImpl(QueryType.SELECT);
118 | assertFalse(query.isAsk());
119 | Query query2 = new QueryImpl(QueryType.ASK);
120 | assertTrue(query2.isAsk());
121 | }
122 |
123 | @Test
124 | public void testIsSelect()
125 | {
126 | Query query = new QueryImpl(QueryType.SELECT);
127 | assertTrue(query.isSelect());
128 | Query query2 = new QueryImpl(QueryType.ASK);
129 | assertFalse(query2.isSelect());
130 | }
131 |
132 | @Test
133 | public void testIsSelectDistinct()
134 | {
135 | Query query = new QueryImpl(QueryType.SELECT_DISTINCT);
136 | assertTrue(query.isSelectDistinct());
137 | Query query2 = new QueryImpl(QueryType.ASK);
138 | assertFalse(query2.isSelectDistinct());
139 | }
140 | }
141 |
--------------------------------------------------------------------------------
/src/test/java/de/derivo/sparqldlapi/tests/QueryTokenTest.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.tests;
6 |
7 | import static org.junit.Assert.*;
8 |
9 | import org.junit.Test;
10 |
11 | import de.derivo.sparqldlapi.QueryToken;
12 |
13 | /**
14 | * A jUnit 4.0 test class to test QueryToken
15 | *
16 | * @author Mario Volke
17 | */
18 | public class QueryTokenTest
19 | {
20 | @Test
21 | public void testGetToken()
22 | {
23 | QueryToken token = new QueryToken("token", 1, 2, 3);
24 | assertEquals(token.getToken(), "token");
25 | }
26 |
27 | @Test
28 | public void testGetPos()
29 | {
30 | QueryToken token = new QueryToken("token", 1, 2, 3);
31 | assertEquals(token.getPos(), 1);
32 | }
33 |
34 | @Test
35 | public void testGetCol()
36 | {
37 | QueryToken token = new QueryToken("token", 1, 2, 3);
38 | assertEquals(token.getCol(), 2);
39 | }
40 |
41 | @Test
42 | public void testGetRow()
43 | {
44 | QueryToken token = new QueryToken("token", 1, 2, 3);
45 | assertEquals(token.getRow(), 3);
46 | }
47 |
48 | @Test
49 | public void testEqualsTrue()
50 | {
51 | QueryToken token1 = new QueryToken("token", 1, 2, 3);
52 | QueryToken token2 = new QueryToken("token", 1, 2, 3);
53 | assertTrue(token1.equals(token2));
54 | }
55 |
56 | @Test
57 | public void testEqualsFalse()
58 | {
59 | QueryToken token1 = new QueryToken("token1", 1, 2, 3);
60 | QueryToken token2 = new QueryToken("token2", 1, 2, 3);
61 | assertFalse(token1.equals(token2));
62 | }
63 |
64 |
65 | @Test
66 | public void testHashCodeEqualsTrue()
67 | {
68 | QueryToken token1 = new QueryToken("token", 1, 2, 3);
69 | QueryToken token2 = new QueryToken("token", 1, 2, 3);
70 | assertEquals(token1.hashCode(), token2.hashCode());
71 | }
72 |
73 | @Test
74 | public void testHashCodeEqualsFalse()
75 | {
76 | QueryToken token1 = new QueryToken("token1", 1, 2, 3);
77 | QueryToken token2 = new QueryToken("token2", 1, 2, 3);
78 | assertFalse(token1.hashCode() == token2.hashCode());
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/src/test/java/de/derivo/sparqldlapi/tests/QueryTokenizerTest.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2011. This source code is available under the terms of the GNU Lesser General Public License (LGPL)
2 | // Author: Mario Volke
3 | // derivo GmbH, James-Franck-Ring, 89081 Ulm
4 |
5 | package de.derivo.sparqldlapi.tests;
6 |
7 | import static org.junit.Assert.*;
8 |
9 | import java.util.ArrayList;
10 | import java.util.List;
11 |
12 | import org.junit.Test;
13 |
14 | import de.derivo.sparqldlapi.QueryToken;
15 | import de.derivo.sparqldlapi.QueryTokenizer;
16 | import de.derivo.sparqldlapi.impl.QueryTokenizerImpl;
17 |
18 | /**
19 | * A jUnit 4.0 test class to test the implementation of QueryTokenizer
20 | *
21 | * @author Mario Volke
22 | */
23 | public class QueryTokenizerTest
24 | {
25 | @Test
26 | public void testTokenize()
27 | {
28 | QueryTokenizer tokenizer = new QueryTokenizerImpl();
29 | List tokens = tokenizer.tokenize(
30 | "PREFIX wine: http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#\n" +
31 | "PREFIX foaf: http://xmlns.com/foaf/0.1/\n" +
32 | "SELECT * WHERE PropertyValue(?i, wine:hasColor, ?v), PropertyValue(?p, foaf:name, \"foo \\\" bar\")"
33 | );
34 |
35 | List shouldbe = new ArrayList();
36 | shouldbe.add(new QueryToken("PREFIX", 0, 1, 1));
37 | shouldbe.add(new QueryToken("wine:", 7, 8, 1));
38 | shouldbe.add(new QueryToken("http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#", 13, 14, 1));
39 | shouldbe.add(new QueryToken("PREFIX", 67, 0, 2));
40 | shouldbe.add(new QueryToken("foaf:", 74, 7, 2));
41 | shouldbe.add(new QueryToken("http://xmlns.com/foaf/0.1/", 80, 13, 2));
42 | shouldbe.add(new QueryToken("SELECT", 107, 0, 3));
43 | shouldbe.add(new QueryToken("*", 114, 7, 3));
44 | shouldbe.add(new QueryToken("WHERE", 116, 9, 3));
45 | shouldbe.add(new QueryToken("PropertyValue", 122, 15, 3));
46 | shouldbe.add(new QueryToken("(", 136, 29, 3));
47 | shouldbe.add(new QueryToken("?i", 136, 29, 3));
48 | shouldbe.add(new QueryToken(",", 139, 32, 3));
49 | shouldbe.add(new QueryToken("wine:hasColor", 140, 33, 3));
50 | shouldbe.add(new QueryToken(",", 154, 47, 3));
51 | shouldbe.add(new QueryToken("?v", 155, 48, 3));
52 | shouldbe.add(new QueryToken(")", 158, 51, 3));
53 | shouldbe.add(new QueryToken(",", 159, 52, 3));
54 | shouldbe.add(new QueryToken("PropertyValue", 160, 53, 3));
55 | shouldbe.add(new QueryToken("(", 174, 67, 3));
56 | shouldbe.add(new QueryToken("?p", 174, 67, 3));
57 | shouldbe.add(new QueryToken(",", 177, 70, 3));
58 | shouldbe.add(new QueryToken("foaf:name", 178, 71, 3));
59 | shouldbe.add(new QueryToken(",", 188, 81, 3));
60 | shouldbe.add(new QueryToken("\"foo \" bar\"", 189, 82, 3));
61 | shouldbe.add(new QueryToken(")", 202, 95, 3));
62 | shouldbe.add(new QueryToken("", 202, 95, 3));
63 |
64 | assertEquals(tokens, shouldbe);
65 | }
66 | }
67 |
--------------------------------------------------------------------------------