You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@clerezza.apache.org by ha...@apache.org on 2018/11/14 03:04:05 UTC

[1/6] clerezza git commit: CLEREZZA-1026: Introduce GraphStore to remove dependency to TcProvider and refactor sparql

Repository: clerezza
Updated Branches:
  refs/heads/reunited 829e5fa56 -> eec0ac73d


http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/test/java/org/apache/clerezza/sparql/QueryParserTest.java
----------------------------------------------------------------------
diff --git a/sparql/src/test/java/org/apache/clerezza/sparql/QueryParserTest.java b/sparql/src/test/java/org/apache/clerezza/sparql/QueryParserTest.java
new file mode 100644
index 0000000..fe1ce88
--- /dev/null
+++ b/sparql/src/test/java/org/apache/clerezza/sparql/QueryParserTest.java
@@ -0,0 +1,367 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql;
+
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.api.Language;
+import org.apache.clerezza.api.impl.literal.PlainLiteralImpl;
+import org.apache.clerezza.sparql.query.*;
+import org.apache.clerezza.sparql.query.impl.SimpleTriplePattern;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ *
+ * @author hasan
+ */
+public class QueryParserTest {
+
+    @Test
+    public void testSelectQuery() throws ParseException {
+
+// SELECT ?title FROM <http://example.org/library>
+// WHERE { <http://example.org/book/book1> <http://purl.org/dc/elements/1.1/title> ?title . }
+
+        final String variable = "title";
+        final String defaultGraph = "http://example.org/library";
+        final String subject = "http://example.org/book/book1";
+        final String predicate = "http://purl.org/dc/elements/1.1/title";
+
+        StringBuffer queryStrBuf = new StringBuffer();
+        queryStrBuf.append("SELECT ?").append(variable)
+                .append(" FROM <").append(defaultGraph)
+                .append("> WHERE { <").append(subject).append("> <")
+                .append(predicate).append("> ?").append(variable).append(" . }");
+
+        Query q = QueryParser.getInstance().parse(queryStrBuf.toString());
+        Assert.assertTrue(SelectQuery.class.isAssignableFrom(q.getClass()));
+        SelectQuery selectQuery = (SelectQuery) q;
+        Assert.assertTrue(selectQuery.getSelection().get(0)
+                .equals(new Variable(variable)));
+        Assert.assertTrue(selectQuery.getDataSet().getDefaultGraphs().toArray()[0]
+                .equals(new IRI(defaultGraph)));
+
+        GraphPattern gp = (GraphPattern) selectQuery.getQueryPattern()
+                .getGraphPatterns().toArray()[0];
+        Assert.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass()));
+        BasicGraphPattern bgp = (BasicGraphPattern) gp;
+
+        Set<TriplePattern> triplePatterns = bgp.getTriplePatterns();
+        Assert.assertTrue(triplePatterns.size()==1);
+
+        ResourceOrVariable s = new ResourceOrVariable(new IRI(subject));
+        UriRefOrVariable p = new UriRefOrVariable(new IRI(predicate));
+        ResourceOrVariable o = new ResourceOrVariable(new Variable(variable));
+
+        Assert.assertTrue(triplePatterns.contains(
+                new SimpleTriplePattern(s, p, o)));
+    }
+
+    @Test(expected=ParseException.class)
+    public void testInvalidQuery() throws ParseException {
+        Query q = QueryParser.getInstance().parse("Hello");
+    }
+
+    @Test
+    public void testSelectQuerySelection() throws ParseException {
+        SelectQuery q = (SelectQuery) QueryParser.getInstance().parse(
+                "SELECT ?a ?b WHERE {?a ?x ?b}");
+        Set<Variable> selectionSet = new HashSet<Variable>(
+                q.getSelection());
+        Set<Variable> expected = new HashSet<Variable>();
+        expected.add(new Variable("a"));
+        expected.add(new Variable("b"));
+        Assert.assertEquals(expected, selectionSet);
+        Assert.assertFalse(q.isSelectAll());
+
+    }
+
+    @Test
+    public void testSelectAll() throws ParseException {
+        SelectQuery q = (SelectQuery) QueryParser.getInstance().parse(
+                "SELECT * WHERE {?a ?x ?b}");
+        Set<Variable> selectionSet = new HashSet<Variable>(
+                q.getSelection());
+        Set<Variable> expected = new HashSet<Variable>();
+        expected.add(new Variable("a"));
+        expected.add(new Variable("b"));
+        expected.add(new Variable("x"));
+        Assert.assertEquals(expected, selectionSet);
+        Assert.assertTrue(q.isSelectAll());
+
+    }
+
+    @Test
+    public void testPlainLiteral() throws ParseException {
+        SelectQuery q = (SelectQuery) QueryParser.getInstance().parse(
+                "SELECT * WHERE {?a ?x 'tiger' . ?a ?x 'lion'@en . }");
+
+        GraphPattern gp = (GraphPattern) q.getQueryPattern()
+                .getGraphPatterns().toArray()[0];
+        Assert.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass()));
+        BasicGraphPattern bgp = (BasicGraphPattern) gp;
+
+        Set<TriplePattern> triplePatterns = bgp.getTriplePatterns();
+        Assert.assertTrue(triplePatterns.size()==2);
+
+        Assert.assertTrue(triplePatterns.contains(new SimpleTriplePattern(
+                new Variable("a"), new Variable("x"),
+                new PlainLiteralImpl("tiger"))));
+
+        Assert.assertTrue(triplePatterns.contains(new SimpleTriplePattern(
+                new Variable("a"), new Variable("x"),
+                new PlainLiteralImpl("lion", new Language("en")))));
+    }
+
+    @Test
+    public void testOrderBy() throws ParseException {
+        SelectQuery q = (SelectQuery) QueryParser.getInstance().parse(
+                "SELECT * WHERE {?a ?x ?b} ORDER BY DESC(?b)");
+
+        List<OrderCondition> oc = ((QueryWithSolutionModifier) q).getOrderConditions();
+        Assert.assertTrue(oc.size()==1);
+        Assert.assertFalse(oc.get(0).isAscending());
+        Variable b = new Variable("b");
+        Assert.assertEquals(b, oc.get(0).getExpression());
+    }
+
+    @Test
+    public void testConstructQuery() throws ParseException {
+
+// CONSTRUCT { <http://example.org/person#Alice> <http://www.w3.org/2001/vcard-rdf/3.0#FN> ?name}
+// WHERE { ?x <http://xmlns.com/foaf/0.1/name> ?name}
+
+
+        final String variable1 = "name";
+        final String variable2 = "x";
+        final String subject1 = "http://example.org/person#Alice";
+        final String predicate1 = "http://www.w3.org/2001/vcard-rdf/3.0#FN";
+        final String predicate2 = "http://xmlns.com/foaf/0.1/name";
+
+        StringBuffer queryStrBuf = new StringBuffer();
+        queryStrBuf.append("CONSTRUCT { <").append(subject1).append("> <")
+                .append(predicate1).append("> ?").append(variable1)
+                .append("} WHERE { ?").append(variable2).append(" <")
+                .append(predicate2).append("> ?").append(variable1).append("}");
+
+        Query q = QueryParser.getInstance().parse(queryStrBuf.toString());
+        Assert.assertTrue(ConstructQuery.class.isAssignableFrom(q.getClass()));
+        ConstructQuery constructQuery = (ConstructQuery) q;
+        Set<TriplePattern> triplePatterns = constructQuery
+                .getConstructTemplate();
+        Assert.assertTrue(triplePatterns.size()==1);
+
+        ResourceOrVariable s = new ResourceOrVariable(new IRI(subject1));
+        UriRefOrVariable p = new UriRefOrVariable(new IRI(predicate1));
+        ResourceOrVariable o = new ResourceOrVariable(new Variable(variable1));
+
+        Assert.assertTrue(triplePatterns.contains(
+                new SimpleTriplePattern(s, p, o)));
+
+        GraphPattern gp = (GraphPattern) constructQuery.getQueryPattern()
+                .getGraphPatterns().toArray()[0];
+        Assert.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass()));
+        BasicGraphPattern bgp = (BasicGraphPattern) gp;
+        triplePatterns = bgp.getTriplePatterns();
+        Assert.assertTrue(triplePatterns.size()==1);
+
+        s = new ResourceOrVariable(new Variable(variable2));
+        p = new UriRefOrVariable(new IRI(predicate2));
+
+        Assert.assertTrue(triplePatterns.contains(
+                new SimpleTriplePattern(s, p, o)));
+    }
+
+    @Test
+    public void testDescribeQuery() throws ParseException {
+
+// DESCRIBE <http://example.org/book/book1>
+
+        final String resource = "http://example.org/book/book1";
+
+        StringBuffer queryStrBuf = new StringBuffer();
+        queryStrBuf.append("DESCRIBE <").append(resource).append(">");
+
+        Query q = QueryParser.getInstance().parse(queryStrBuf.toString());
+        Assert.assertTrue(DescribeQuery.class.isAssignableFrom(q.getClass()));
+        DescribeQuery describeQuery = (DescribeQuery) q;
+        Assert.assertTrue(describeQuery.getResourcesToDescribe().get(0)
+                .getResource().equals(new IRI(resource)));
+    }
+
+    @Test
+    public void testAskQuery() throws ParseException {
+
+// ASK { ?x <http://xmlns.com/foaf/0.1/name> "Alice" }
+
+        final String variable = "x";
+        final String predicate = "http://xmlns.com/foaf/0.1/name";
+        final String object = "Alice";
+
+        StringBuffer queryStrBuf = new StringBuffer();
+        queryStrBuf.append("ASK { ?").append(variable).append(" <")
+                .append(predicate).append("> \"").append(object).append("\" }");
+
+        Query q = QueryParser.getInstance().parse(queryStrBuf.toString());
+        Assert.assertTrue(AskQuery.class.isAssignableFrom(q.getClass()));
+        AskQuery askQuery = (AskQuery) q;
+
+        GraphPattern gp = (GraphPattern) askQuery.getQueryPattern()
+                .getGraphPatterns().toArray()[0];
+        Assert.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass()));
+        BasicGraphPattern bgp = (BasicGraphPattern) gp;
+
+        Set<TriplePattern> triplePatterns = bgp.getTriplePatterns();
+        Assert.assertTrue(triplePatterns.size()==1);
+
+        Assert.assertTrue(triplePatterns.contains(new SimpleTriplePattern(new Variable(variable),
+                new IRI(predicate), new PlainLiteralImpl(object))));
+    }
+
+    @Test
+    public void testBaseAndPrefix() throws ParseException {
+
+// BASE    <http://example.org/book/>
+// PREFIX  dc: <http://purl.org/dc/elements/1.1/>
+//
+// SELECT  $title
+// WHERE   { <book1>  dc:title  ?title }
+
+        final String base = "http://example.org/book/";
+        final String prefix = "dc";
+        final String prefixUri = "http://purl.org/dc/elements/1.1/";
+        final String variable = "title";
+        final String subject = "book1";
+        final String predicate = "title";
+
+        StringBuffer queryStrBuf = new StringBuffer();
+        queryStrBuf.append("BASE <").append(base).append(">")
+                .append(" PREFIX ").append(prefix).append(": <")
+                .append(prefixUri).append("> SELECT $").append(variable)
+                .append(" WHERE { <").append(subject).append("> ")
+                .append(prefix).append(":").append(predicate).append(" ?")
+                .append(variable).append(" }");
+
+        Query q = QueryParser.getInstance().parse(queryStrBuf.toString());
+        Assert.assertTrue(SelectQuery.class.isAssignableFrom(q.getClass()));
+        SelectQuery selectQuery = (SelectQuery) q;
+        Assert.assertTrue(selectQuery.getSelection().get(0)
+                .equals(new Variable(variable)));
+
+        GraphPattern gp = (GraphPattern) selectQuery.getQueryPattern()
+                .getGraphPatterns().toArray()[0];
+        Assert.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass()));
+        BasicGraphPattern bgp = (BasicGraphPattern) gp;
+
+        Set<TriplePattern> triplePatterns = bgp.getTriplePatterns();
+        Assert.assertTrue(triplePatterns.size()==1);
+
+        ResourceOrVariable s = new ResourceOrVariable(new IRI(base+subject));
+        UriRefOrVariable p = new UriRefOrVariable(new IRI(prefixUri+predicate));
+        ResourceOrVariable o = new ResourceOrVariable(new Variable(variable));
+
+        Assert.assertTrue(triplePatterns.contains(
+                new SimpleTriplePattern(s, p, o)));
+    }
+
+    @Test
+    public void testOptionalAndFilter() throws ParseException {
+
+// PREFIX dc: <http://purl.org/dc/elements/1.1/>
+// PREFIX books: <http://example.org/book/>
+//
+// SELECT ?book ?title
+// WHERE
+//  { ?book dc:title ?title .
+//    OPTIONAL
+//     { ?book books:author ?author .}
+//     FILTER ( ! bound(?author) )
+//  }
+        final String prefix1 = "dc";
+        final String prefix1Uri = "http://purl.org/dc/elements/1.1/";
+        final String prefix2 = "books";
+        final String prefix2Uri = "http://example.org/book/";
+        final String variable1 = "book";
+        final String variable2 = "title";
+        final String variable3 = "author";
+        final String predicate1 = "title";
+        final String predicate2 = "author";
+
+        StringBuffer queryStrBuf = new StringBuffer();
+        queryStrBuf.append("PREFIX ").append(prefix1).append(": <").append(prefix1Uri)
+                .append("> PREFIX ").append(prefix2).append(": <").append(prefix2Uri)
+                .append("> SELECT ?").append(variable1).append(" ?").append(variable2)
+                .append(" WHERE { ?").append(variable1).append(" ")
+                .append(prefix1).append(":").append(predicate1)
+                .append(" ?").append(variable2).append(" . OPTIONAL { ?")
+                .append(variable1).append(" ").append(prefix2).append(":")
+                .append(predicate2).append(" ?").append(variable3)
+                .append(" .} FILTER ( ! bound(?").append(variable3).append(") ) }");
+
+        Query q = QueryParser.getInstance().parse(queryStrBuf.toString());
+        Assert.assertTrue(SelectQuery.class.isAssignableFrom(q.getClass()));
+        SelectQuery selectQuery = (SelectQuery) q;
+        Assert.assertTrue(selectQuery.getSelection().size() == 2);
+        Set<Variable> vars = new HashSet<Variable>(2);
+        Variable var1 = new Variable(variable1);
+        Variable var2 = new Variable(variable2);
+        vars.add(var1);
+        vars.add(var2);
+        Assert.assertTrue(selectQuery.getSelection().containsAll(vars));
+
+        GroupGraphPattern ggp = selectQuery.getQueryPattern();
+        List<Expression> constraints = ggp.getFilter();
+        Assert.assertTrue(UnaryOperation.class.isAssignableFrom(constraints
+                .get(0).getClass()));
+        UnaryOperation uop = (UnaryOperation) constraints.get(0);
+        Assert.assertTrue(uop.getOperatorString().equals("!"));
+        Assert.assertTrue(BuiltInCall.class.isAssignableFrom(uop.getOperand()
+                .getClass()));
+        BuiltInCall bic = (BuiltInCall) uop.getOperand();
+        Assert.assertTrue(bic.getName().equals("BOUND"));
+        Variable var3 = new Variable(variable3);
+        Assert.assertTrue(bic.getArguements().get(0).equals(var3));
+
+        GraphPattern gp = (GraphPattern) ggp.getGraphPatterns().toArray()[0];
+        Assert.assertTrue(OptionalGraphPattern.class.isAssignableFrom(gp.getClass()));
+        OptionalGraphPattern ogp = (OptionalGraphPattern) gp;
+        Assert.assertTrue(BasicGraphPattern.class.isAssignableFrom(
+                ogp.getMainGraphPattern().getClass()));
+        BasicGraphPattern bgp = (BasicGraphPattern) ogp.getMainGraphPattern();
+
+        Set<TriplePattern> triplePatterns = bgp.getTriplePatterns();
+        Assert.assertTrue(triplePatterns.size() == 1);
+        Assert.assertTrue(triplePatterns.contains(new SimpleTriplePattern(var1, new IRI(prefix1Uri + predicate1),
+                var2)));
+
+        GraphPattern gp2 = (GraphPattern) ogp.getOptionalGraphPattern()
+                .getGraphPatterns().toArray()[0];
+        Assert.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp2.getClass()));
+        bgp = (BasicGraphPattern) gp2;
+
+        triplePatterns = bgp.getTriplePatterns();
+        Assert.assertTrue(triplePatterns.size() == 1);
+        Assert.assertTrue(triplePatterns.contains(new SimpleTriplePattern(var1, new IRI(prefix2Uri + predicate2),
+                var3)));
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/test/java/org/apache/clerezza/sparql/QuerySerializerTest.java
----------------------------------------------------------------------
diff --git a/sparql/src/test/java/org/apache/clerezza/sparql/QuerySerializerTest.java b/sparql/src/test/java/org/apache/clerezza/sparql/QuerySerializerTest.java
new file mode 100644
index 0000000..deb84f5
--- /dev/null
+++ b/sparql/src/test/java/org/apache/clerezza/sparql/QuerySerializerTest.java
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql;
+
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.api.impl.literal.LiteralFactory;
+import org.apache.clerezza.sparql.query.*;
+import org.apache.clerezza.sparql.query.impl.*;
+import org.junit.Assert;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ *
+ * @author hasan
+ */
+public class QuerySerializerTest {
+
+    @Test
+    public void testSelectQuery() {
+
+        final String queryString = "SELECT ?title FROM <http://example.org/library>" +
+                " WHERE { <http://example.org/book/book1>" +
+                " <http://purl.org/dc/elements/1.1/title> ?title . }";
+
+        SimpleSelectQuery selectQuery = new SimpleSelectQuery();
+        Variable variable = new Variable("title");
+        selectQuery.addSelection(variable);
+        IRI defaultGraph = new IRI("http://example.org/library");
+        selectQuery.addDefaultGraph(defaultGraph);
+        ResourceOrVariable subject = new ResourceOrVariable(
+                new IRI("http://example.org/book/book1"));
+        UriRefOrVariable predicate = new UriRefOrVariable(
+                new IRI("http://purl.org/dc/elements/1.1/title"));
+        ResourceOrVariable object = new ResourceOrVariable(variable);
+        TriplePattern triplePattern = new SimpleTriplePattern(subject, predicate, object);
+        Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>();
+        triplePatterns.add(triplePattern);
+
+        SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns);
+        SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern();
+        queryPattern.addGraphPattern(bgp);
+        selectQuery.setQueryPattern(queryPattern);
+
+        Assert.assertTrue(selectQuery.toString()
+                .replaceAll("( |\n)+", " ").trim().equals(queryString));
+    }
+
+    @Test
+    public void testConstructQuery() {
+
+        final String queryString = "CONSTRUCT { <http://example.org/person#Alice> " +
+                "<http://www.w3.org/2001/vcard-rdf/3.0#FN> ?name . } " +
+                "WHERE { ?x <http://xmlns.com/foaf/0.1/name> ?name . }";
+
+        ResourceOrVariable s = new ResourceOrVariable(
+                new IRI("http://example.org/person#Alice"));
+        UriRefOrVariable p = new UriRefOrVariable(
+                new IRI("http://www.w3.org/2001/vcard-rdf/3.0#FN"));
+        ResourceOrVariable o = new ResourceOrVariable(new Variable("name"));
+        Set<TriplePattern> constructTriplePatterns = new HashSet<TriplePattern>();
+        constructTriplePatterns.add(new SimpleTriplePattern(s, p, o));
+        SimpleConstructQuery constructQuery = new SimpleConstructQuery(constructTriplePatterns);
+
+        s = new ResourceOrVariable(new Variable("x"));
+        p = new UriRefOrVariable(new IRI("http://xmlns.com/foaf/0.1/name"));
+        Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>();
+        triplePatterns.add(new SimpleTriplePattern(s, p, o));
+
+        SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns);
+        SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern();
+        queryPattern.addGraphPattern(bgp);
+        constructQuery.setQueryPattern(queryPattern);
+
+        Assert.assertTrue(constructQuery.toString()
+                .replaceAll("( |\n)+", " ").trim().equals(queryString));
+    }
+
+    @Test
+    public void testDescribeQuery() {
+
+        final String queryString = "DESCRIBE <http://example.org/book/book1>";
+
+        SimpleDescribeQuery describeQuery = new SimpleDescribeQuery();
+        describeQuery.addResourceToDescribe(new ResourceOrVariable(
+                new IRI("http://example.org/book/book1")));
+
+        Assert.assertTrue(describeQuery.toString()
+                .replaceAll("( |\n)+", " ").trim().equals(queryString));
+    }
+
+    @Test
+    public void testAskQuery() {
+
+        final String queryString = "ASK WHERE { ?x <http://xmlns.com/foaf/0.1/name> " +
+                "\"Alice\"^^<http://www.w3.org/2001/XMLSchema#string> . }";
+
+        ResourceOrVariable s = new ResourceOrVariable(new Variable("x"));
+        UriRefOrVariable p = new UriRefOrVariable(
+                new IRI("http://xmlns.com/foaf/0.1/name"));
+        ResourceOrVariable o = new ResourceOrVariable(
+                LiteralFactory.getInstance().createTypedLiteral("Alice"));
+
+        Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>();
+        triplePatterns.add(new SimpleTriplePattern(s, p, o));
+        SimpleAskQuery askQuery = new SimpleAskQuery();
+
+        SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns);
+        SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern();
+        queryPattern.addGraphPattern(bgp);
+        askQuery.setQueryPattern(queryPattern);
+
+        Assert.assertTrue(askQuery.toString()
+                .replaceAll("( |\n)+", " ").trim().equals(queryString));
+    }
+
+    /**
+     * Ignoring: given that triplePatterns is a Set I don't see what is supposed 
+     * to guarantee the expected ordering.
+     */
+    @Ignore
+    @Test
+    public void testFilter() {
+
+        final String queryString = "SELECT ?title ?price WHERE { " +
+                "?x <http://purl.org/dc/elements/1.1/title> ?title . " +
+                "?x <http://example.org/ns#price> ?price . " +
+                "FILTER ((?price) < (\"30.5\"^^<http://www.w3.org/2001/XMLSchema#double>)) " +
+                "}";
+
+        Variable price = new Variable("price");
+        Variable title = new Variable("title");
+        SimpleSelectQuery selectQuery = new SimpleSelectQuery();
+        selectQuery.addSelection(title);
+        selectQuery.addSelection(price);
+
+        Variable x = new Variable("x");
+        Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>();
+        triplePatterns.add(new SimpleTriplePattern(x,
+                new IRI("http://example.org/ns#price"), price));
+        triplePatterns.add(new SimpleTriplePattern(x,
+                new IRI("http://purl.org/dc/elements/1.1/title"), title));
+
+        SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns);
+        SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern();
+        queryPattern.addGraphPattern(bgp);
+        BinaryOperation constraint = new BinaryOperation("<",
+                price, new LiteralExpression(LiteralFactory.getInstance().createTypedLiteral(30.5)));
+        queryPattern.addConstraint(constraint);
+        selectQuery.setQueryPattern(queryPattern);
+
+        Assert.assertTrue(selectQuery.toString()
+                .replaceAll("( |\n)+", " ").trim().equals(queryString));
+    }
+
+    @Test
+    public void testUriRefExpression() {
+
+        final String queryString = "SELECT ?resource WHERE { " +
+                "?resource <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?myType . " +
+                "FILTER ((?resource) = (<http://example.org/ontology#special>)) " +
+                "}";
+
+        Variable resource = new Variable("resource");
+        SimpleSelectQuery selectQuery = new SimpleSelectQuery();
+        selectQuery.addSelection(resource);
+
+        Variable myType = new Variable("myType");
+        Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>();
+        triplePatterns.add(new SimpleTriplePattern(resource,
+                new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), myType));
+
+        SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns);
+        SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern();
+        queryPattern.addGraphPattern(bgp);
+        BinaryOperation constraint = new BinaryOperation("=",
+                resource, new UriRefExpression(new IRI("http://example.org/ontology#special")));
+        queryPattern.addConstraint(constraint);
+        selectQuery.setQueryPattern(queryPattern);
+
+        Assert.assertTrue(selectQuery.toString()
+                .replaceAll("( |\n)+", " ").trim().equals(queryString));
+    }
+
+    @Test
+    public void testOrderBy() {
+
+        final String queryString = "SELECT * WHERE { ?a ?b ?c . } ORDER BY DESC(?c)";
+
+        Variable a = new Variable("a");
+        Variable b = new Variable("b");
+        Variable c = new Variable("c");
+        SimpleSelectQuery selectQuery = new SimpleSelectQuery();
+        selectQuery.setSelectAll();
+        selectQuery.addSelection(a);
+        selectQuery.addSelection(b);
+        selectQuery.addSelection(c);
+
+        Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>();
+        triplePatterns.add(new SimpleTriplePattern(a, b, c));
+        SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns);
+        SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern();
+        queryPattern.addGraphPattern(bgp);
+        selectQuery.setQueryPattern(queryPattern);
+        selectQuery.addOrderCondition(new SimpleOrderCondition(c, false));
+
+        Assert.assertTrue(selectQuery.toString()
+                .replaceAll("( |\n)+", " ").trim().equals(queryString));
+    }
+
+    @Test
+    public void testOptional() {
+
+        final String queryString = "SELECT ?title ?price WHERE { " +
+                "?x <http://purl.org/dc/elements/1.1/title> ?title . " +
+                "OPTIONAL { ?x <http://example.org/ns#price> ?price . } " +
+                "}";
+
+        Variable title = new Variable("title");
+        Variable price = new Variable("price");
+        SimpleSelectQuery selectQuery = new SimpleSelectQuery();
+        selectQuery.addSelection(title);
+        selectQuery.addSelection(price);
+
+        Variable x = new Variable("x");
+        Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>();
+        triplePatterns.add(new SimpleTriplePattern(x,
+                new IRI("http://purl.org/dc/elements/1.1/title"), title));
+
+        SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns);
+
+        Set<TriplePattern> triplePatternsOpt = new HashSet<TriplePattern>();
+        triplePatternsOpt.add(new SimpleTriplePattern(x,
+                new IRI("http://example.org/ns#price"), price));
+
+        SimpleBasicGraphPattern bgpOpt =
+                new SimpleBasicGraphPattern(triplePatternsOpt);
+
+        SimpleGroupGraphPattern ggpOpt = new SimpleGroupGraphPattern();
+        ggpOpt.addGraphPattern(bgpOpt);
+
+        SimpleOptionalGraphPattern ogp = new SimpleOptionalGraphPattern(bgp, ggpOpt);
+
+        SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern();
+        queryPattern.addGraphPattern(ogp);
+        selectQuery.setQueryPattern(queryPattern);
+
+        Assert.assertTrue(selectQuery.toString()
+                .replaceAll("( |\n)+", " ").trim().equals(queryString));
+    }
+
+    @Test
+    public void testRegex() {
+
+        final String queryString = "SELECT ?p WHERE { " +
+                "<http://localhost/testitem> ?p ?x . " +
+                "FILTER REGEX(?x,\".*uni.*\"^^<http://www.w3.org/2001/XMLSchema#string>) }";
+
+        Variable p = new Variable("p");
+        SimpleSelectQuery selectQuery = new SimpleSelectQuery();
+        selectQuery.addSelection(p);
+
+        Variable x = new Variable("x");
+        Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>();
+        triplePatterns.add(new SimpleTriplePattern(
+                new IRI("http://localhost/testitem"), p, x));
+
+        SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns);
+        SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern();
+        queryPattern.addGraphPattern(bgp);
+
+        List<Expression> arguments = new ArrayList<Expression>();
+        arguments.add(x);
+        arguments.add(new LiteralExpression(LiteralFactory.getInstance().
+                createTypedLiteral(".*uni.*")));
+        BuiltInCall constraint = new BuiltInCall("REGEX", arguments);
+        queryPattern.addConstraint(constraint);
+        selectQuery.setQueryPattern(queryPattern);
+        Assert.assertTrue(selectQuery.toString()
+                .replaceAll("( |\n)+", " ").trim().equals(queryString));
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/test/java/org/apache/clerezza/sparql/SparqlPreParserTest.java
----------------------------------------------------------------------
diff --git a/sparql/src/test/java/org/apache/clerezza/sparql/SparqlPreParserTest.java b/sparql/src/test/java/org/apache/clerezza/sparql/SparqlPreParserTest.java
new file mode 100644
index 0000000..b08e078
--- /dev/null
+++ b/sparql/src/test/java/org/apache/clerezza/sparql/SparqlPreParserTest.java
@@ -0,0 +1,511 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql;
+
+import org.apache.clerezza.api.IRI;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ *
+ * @author hasan
+ */
+public class SparqlPreParserTest {
+
+    private final static IRI STORED_NAME_GRAPH = new IRI("http://example.org/named.graph");
+
+    private class TestGraphStore implements GraphStore {
+
+        private IRI namedGraph;
+
+        public TestGraphStore(IRI namedGraph) {
+            this.namedGraph = namedGraph;
+        }
+
+        @Override
+        public Set<IRI> listGraphs() {
+            return this.listNamedGraphs();
+        }
+
+        @Override
+        public Set<IRI> listNamedGraphs() {
+            return Collections.singleton(this.namedGraph);
+        }
+    }
+
+    private TestGraphStore graphStore = new TestGraphStore(STORED_NAME_GRAPH);
+
+    private final static IRI DEFAULT_GRAPH = new IRI("http://example.org/default.graph");
+    private final static IRI TEST_GRAPH = new IRI("http://example.org/test.graph");
+
+    @Test
+    public void testDefaultGraphInSelectQuery() throws ParseException {
+
+        StringBuilder queryStrBuilder = new StringBuilder();
+        queryStrBuilder.append(
+                "PREFIX : <http://example.org/>\n" +
+                "SELECT ?x \n" +
+                "{\n" +
+                ":order :item/:price ?x\n" +
+                "}\n");
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStrBuilder.toString(), DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH));
+    }
+
+    @Test
+    public void testAllGraphReferenceInSelectQuery() throws ParseException {
+
+        StringBuilder queryStrBuilder = new StringBuilder();
+        queryStrBuilder.append("SELECT DISTINCT ?g { GRAPH ?g { ?s ?p ?o } }\n");
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStrBuilder.toString(), DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs == null);
+    }
+
+    @Test
+    public void testSelectQuery() throws ParseException {
+
+        StringBuilder queryStrBuilder = new StringBuilder();
+        queryStrBuilder.append(
+                "PREFIX : <http://example.org/>\n" +
+                "SELECT ?x (foo(2*3, ?x < ?y) AS ?f) (GROUP_CONCAT(?x ; separator=\"|\") AS ?gc) (sum(distinct *) AS ?total)\n" +
+                "FROM " + TEST_GRAPH.toString() + "\n" +
+                "{\n" +
+                ":order :item/:price ?x\n" +
+                "}\n");
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStrBuilder.toString(), DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH));
+    }
+
+    @Test
+    public void testSimpleDescribe() throws ParseException {
+
+        String queryStr = "DESCRIBE <http://example.org/>";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH));
+    }
+
+    @Test
+    public void testLoadingToDefaultGraph() throws ParseException {
+
+        String queryStr = "LOAD SILENT <http://example.org/mydata>";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Set<IRI> expected = new HashSet<>();
+        expected.add(DEFAULT_GRAPH);
+        expected.add(new IRI("http://example.org/mydata"));
+        Assert.assertTrue(referredGraphs.containsAll(expected));
+    }
+
+    @Test
+    public void testLoadingToGraph() throws ParseException {
+
+        String queryStr = "LOAD SILENT <http://example.org/mydata> INTO GRAPH " + TEST_GRAPH.toString();
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Set<IRI> expected = new HashSet<>();
+        expected.add(TEST_GRAPH);
+        expected.add(new IRI("http://example.org/mydata"));
+        Assert.assertTrue(referredGraphs.containsAll(expected));
+    }
+
+    @Test
+    public void testClearingDefaultGraph() throws ParseException {
+
+        String queryStr = "CLEAR SILENT DEFAULT";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH));
+    }
+
+    @Test
+    public void testClearingNamedGraph() throws ParseException {
+
+        String queryStr = "CLEAR SILENT NAMED";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.contains(STORED_NAME_GRAPH));
+    }
+
+    @Test
+    public void testClearingGraph() throws ParseException {
+
+        String queryStr = "CLEAR SILENT GRAPH " + TEST_GRAPH.toString();
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH));
+    }
+
+    @Test
+    public void testDroppingDefaultGraph() throws ParseException {
+
+        String queryStr = "DROP SILENT DEFAULT";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH));
+    }
+
+    @Test
+    public void testDroppingNamedGraph() throws ParseException {
+
+        String queryStr = "DROP SILENT NAMED";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.contains(STORED_NAME_GRAPH));
+    }
+
+    @Test
+    public void testDroppingGraph() throws ParseException {
+
+        String queryStr = "DROP SILENT GRAPH " + TEST_GRAPH.toString();
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH));
+    }
+
+    @Test
+    public void testCreatingGraph() throws ParseException {
+
+        String queryStr = "CREATE SILENT GRAPH " + TEST_GRAPH.toString();
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH));
+    }
+
+    @Test
+    public void testAddingTriplesFromDefaultGraphToNamedGraph() throws ParseException {
+
+        String queryStr = "ADD SILENT DEFAULT TO GRAPH " + TEST_GRAPH.toString();
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Set<IRI> expected = new HashSet<>();
+        expected.add(DEFAULT_GRAPH);
+        expected.add(TEST_GRAPH);
+        Assert.assertTrue(referredGraphs.containsAll(expected));
+    }
+
+    @Test
+    public void testAddingTriplesFromNamedGraphToDefaultGraph() throws ParseException {
+
+        String queryStr = "ADD SILENT GRAPH " + TEST_GRAPH.toString() + " TO DEFAULT";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Set<IRI> expected = new HashSet<>();
+        expected.add(DEFAULT_GRAPH);
+        expected.add(TEST_GRAPH);
+        Assert.assertTrue(referredGraphs.containsAll(expected));
+    }
+
+    @Test
+    public void testMovingTriplesFromDefaultGraphToNamedGraph() throws ParseException {
+
+        String queryStr = "MOVE SILENT DEFAULT TO GRAPH " + TEST_GRAPH.toString();
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Set<IRI> expected = new HashSet<>();
+        expected.add(DEFAULT_GRAPH);
+        expected.add(TEST_GRAPH);
+        Assert.assertTrue(referredGraphs.containsAll(expected));
+    }
+
+    @Test
+    public void testMovingTriplesFromNamedGraphToDefaultGraph() throws ParseException {
+
+        String queryStr = "MOVE SILENT GRAPH " + TEST_GRAPH.toString() + " TO DEFAULT";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Set<IRI> expected = new HashSet<>();
+        expected.add(DEFAULT_GRAPH);
+        expected.add(TEST_GRAPH);
+        Assert.assertTrue(referredGraphs.containsAll(expected));
+    }
+
+    @Test
+    public void testCopyingTriplesFromDefaultGraphToNamedGraph() throws ParseException {
+
+        String queryStr = "COPY SILENT DEFAULT TO GRAPH " + TEST_GRAPH.toString();
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Set<IRI> expected = new HashSet<>();
+        expected.add(DEFAULT_GRAPH);
+        expected.add(TEST_GRAPH);
+        Assert.assertTrue(referredGraphs.containsAll(expected));
+    }
+
+    @Test
+    public void testCopyingTriplesFromNamedGraphToDefaultGraph() throws ParseException {
+
+        String queryStr = "COPY SILENT GRAPH " + TEST_GRAPH.toString() + " TO DEFAULT";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Set<IRI> expected = new HashSet<>();
+        expected.add(DEFAULT_GRAPH);
+        expected.add(TEST_GRAPH);
+        Assert.assertTrue(referredGraphs.containsAll(expected));
+    }
+
+    @Test
+    public void testInsertDataToDefaultGraph() throws ParseException {
+
+        String queryStr = "PREFIX dc: <http://purl.org/dc/elements/1.1/> INSERT DATA { \n" +
+                "<http://example/book1> dc:title \"A new book\" ; dc:creator \"A.N.Other\" . }";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH));
+    }
+
+    @Test
+    public void testInsertDataToNamedGraph() throws ParseException {
+
+        String queryStr = "PREFIX ns: <http://example.org/ns#>\n" +
+                "INSERT DATA { GRAPH " + TEST_GRAPH.toString() + " { <http://example/book1>  ns:price  42 } }";
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH));
+    }
+
+    @Test
+    public void testDeleteDataInDefaultGraph() throws ParseException {
+
+        String queryStr = "PREFIX dc: <http://purl.org/dc/elements/1.1/> DELETE DATA { \n" +
+                "<http://example/book1> dc:title \"A new book\" ; dc:creator \"A.N.Other\" . }";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH));
+    }
+
+    @Test
+    public void testDeleteDataInNamedGraph() throws ParseException {
+
+        String queryStr = "PREFIX ns: <http://example.org/ns#>\n" +
+                "DELETE DATA { GRAPH " + TEST_GRAPH.toString() + " { <http://example/book1>  ns:price  42 } }";
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH));
+    }
+
+    @Test
+    public void testInsertAndDeleteData() throws ParseException {
+
+        String queryStr = "PREFIX ns: <http://example.org/ns#> " +
+                "INSERT DATA { <http://example/book1>  ns:price  42 }; " +
+                "DELETE DATA { GRAPH " + TEST_GRAPH.toString() + " { <http://example/book1>  ns:price  42 } }";
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+
+        Set<IRI> expected = new HashSet<>();
+        expected.add(DEFAULT_GRAPH);
+        expected.add(TEST_GRAPH);
+        Assert.assertTrue(referredGraphs.containsAll(expected));
+    }
+
+    @Test
+    public void testDeleteWhereInDefaultGraph() throws ParseException {
+
+        String queryStr = "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
+                "DELETE WHERE { ?person foaf:givenName 'Fred'; ?property ?value }";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH));
+    }
+
+    @Test
+    public void testDeleteWhereInNamedGraphs() throws ParseException {
+
+        String queryStr = "PREFIX foaf: <http://xmlns.com/foaf/0.1/> DELETE WHERE " +
+                "{ GRAPH <http://example.com/names> { ?person foaf:givenName 'Fred' ; ?property1 ?value1 } " +
+                "  GRAPH <http://example.com/addresses> { ?person ?property2 ?value2 } }";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+
+        Set<IRI> expected = new HashSet<>();
+        expected.add(new IRI("http://example.com/names"));
+        expected.add(new IRI("http://example.com/addresses"));
+        Assert.assertTrue(referredGraphs.containsAll(expected));
+    }
+
+    @Test
+    public void testModifyOperationWithFallbackGraph() throws ParseException {
+        String queryStr = "PREFIX foaf: <http://xmlns.com/foaf/0.1/> WITH " + TEST_GRAPH.toString() +
+                " DELETE { ?person foaf:givenName 'Bill' } INSERT { ?person foaf:givenName 'William' }" +
+                " WHERE { ?person foaf:givenName 'Bill' }";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Set<IRI> expected = new HashSet<>();
+        expected.add(TEST_GRAPH);
+        expected.add(DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.containsAll(expected));
+    }
+
+    @Test
+    public void testDeleteOperationInDefaultGraph() throws ParseException {
+        String queryStr = "PREFIX dc:  <http://purl.org/dc/elements/1.1/> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " +
+                "DELETE { ?book ?p ?v } WHERE { ?book dc:date ?date . " +
+                "FILTER ( ?date > \"1970-01-01T00:00:00-02:00\"^^xsd:dateTime ) ?book ?p ?v }";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH));
+    }
+
+    @Test
+    public void testInsertOperationToNamedGraph() throws ParseException {
+        String queryStr = "PREFIX dc:  <http://purl.org/dc/elements/1.1/> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " +
+                "INSERT { GRAPH <http://example/bookStore2> { ?book ?p ?v } } " +
+                "WHERE { GRAPH <http://example/bookStore> { ?book dc:date ?date . " +
+                "FILTER ( ?date > \"1970-01-01T00:00:00-02:00\"^^xsd:dateTime ) ?book ?p ?v } }";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+
+        Set<IRI> expected = new HashSet<>();
+        expected.add(new IRI("http://example/bookStore2"));
+        expected.add(new IRI("http://example/bookStore"));
+        Assert.assertTrue(referredGraphs.containsAll(expected));
+    }
+
+    @Test
+    public void testInsertAndDeleteWithCommonPrefix() throws ParseException {
+        String queryStr = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" +
+                "PREFIX dcmitype: <http://purl.org/dc/dcmitype/>\n" +
+                "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n\n" +
+                "INSERT\n" +
+                "  { GRAPH <http://example/bookStore2> { ?book ?p ?v } }\n" +
+                "WHERE\n" +
+                "  { GRAPH <http://example/bookStore>\n" +
+                "    { ?book dc:date ?date . \n" +
+                "      FILTER ( ?date < \"2000-01-01T00:00:00-02:00\"^^xsd:dateTime )\n" +
+                "      ?book ?p ?v\n" +
+                "    }\n" +
+                "  } ;\n\n" +
+                "WITH <http://example/bookStore>\n" +
+                "DELETE\n" +
+                " { ?book ?p ?v }\n" +
+                "WHERE\n" +
+                "  { ?book dc:date ?date ;\n" +
+                "          dc:type dcmitype:PhysicalObject .\n" +
+                "    FILTER ( ?date < \"2000-01-01T00:00:00-02:00\"^^xsd:dateTime ) \n" +
+                "    ?book ?p ?v\n" +
+                "  }";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+
+        Set<IRI> expected = new HashSet<>();
+        expected.add(new IRI("http://example/bookStore2"));
+        expected.add(new IRI("http://example/bookStore"));
+        Assert.assertTrue(referredGraphs.containsAll(expected));
+    }
+
+    @Test
+    public void testExistsFunction() throws ParseException {
+        String queryStr = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" +
+                "PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n\n" +
+                "SELECT ?person\n" +
+                "WHERE \n" +
+                "{\n" +
+                "  ?person rdf:type foaf:Person .\n" +
+                "  FILTER EXISTS { ?person foaf:name ?name }\n" +
+                "}";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH));
+    }
+
+    @Test
+    public void testNotExistsFunction() throws ParseException {
+        String queryStr = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" +
+                "PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n\n" +
+                "SELECT ?person\n" +
+                "WHERE \n" +
+                "{\n" +
+                "  ?person rdf:type foaf:Person .\n" +
+                "  FILTER NOT EXISTS { ?person foaf:name ?name }\n" +
+                "}";
+
+        SparqlPreParser parser;
+        parser = new SparqlPreParser(this.graphStore);
+        Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH);
+        Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH));
+    }
+}


[4/6] clerezza git commit: CLEREZZA-1026: Introduce GraphStore to remove dependency to TcProvider and refactor sparql

Posted by ha...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleServiceGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleServiceGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleServiceGraphPattern.java
new file mode 100644
index 0000000..b527d52
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleServiceGraphPattern.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.sparql.query.GroupGraphPattern;
+import org.apache.clerezza.sparql.query.ServiceGraphPattern;
+import org.apache.clerezza.sparql.query.UriRefOrVariable;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleServiceGraphPattern implements ServiceGraphPattern {
+
+    private UriRefOrVariable service;
+    private GroupGraphPattern groupGraphPattern;
+    private boolean silent;
+
+    public SimpleServiceGraphPattern(UriRefOrVariable service,
+            GroupGraphPattern groupGraphPattern) {
+        if (service == null) {
+            throw new IllegalArgumentException("Service endpoint may not be null");
+        }
+        if (groupGraphPattern == null) {
+            throw new IllegalArgumentException("Group ImmutableGraph Pattern may not be null");
+        }
+        this.service = service;
+        this.groupGraphPattern = groupGraphPattern;
+        this.silent = false;
+    }
+
+    @Override
+    public UriRefOrVariable getService() {
+        return service;
+    }
+
+    @Override
+    public GroupGraphPattern getGroupGraphPattern() {
+        return groupGraphPattern;
+    }
+
+    public void setSilent(boolean silent) {
+        this.silent = silent;
+    }
+
+    public boolean isSilent() {
+        return silent;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleSparqlUnit.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleSparqlUnit.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleSparqlUnit.java
new file mode 100644
index 0000000..d1fe59a
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleSparqlUnit.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.sparql.query.Query;
+import org.apache.clerezza.sparql.query.SparqlUnit;
+import org.apache.clerezza.sparql.update.Update;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleSparqlUnit implements SparqlUnit {
+
+    private final Query query;
+	private final Update update;
+
+	public SimpleSparqlUnit(Query query) {
+		if (query == null) {
+			throw new IllegalArgumentException("Invalid query: null");
+		}
+		this.query = query;
+		update = null;
+	}
+
+	public SimpleSparqlUnit(Update update) {
+		if (update == null) {
+			throw new IllegalArgumentException("Invalid update: null");
+		}
+		this.update = update;
+		query = null;
+	}
+
+
+    @Override
+    public boolean isQuery() {
+        return update == null;
+    }
+
+    @Override
+    public Query getQuery() {
+        return query;
+    }
+
+    @Override
+    public Update getUpdate() {
+        return update;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleStringQuerySerializer.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleStringQuerySerializer.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleStringQuerySerializer.java
new file mode 100644
index 0000000..d268dbc
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleStringQuerySerializer.java
@@ -0,0 +1,295 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.api.BlankNode;
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.api.RDFTerm;
+import org.apache.clerezza.sparql.StringQuerySerializer;
+import org.apache.clerezza.sparql.query.*;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+import java.util.Set;
+
+/**
+ * This class implements abstract methods of {@link StringQuerySerializer}
+ * to serialize specific {@link Query} types.
+ *
+ * @author hasan
+ */
+public class SimpleStringQuerySerializer extends StringQuerySerializer {
+
+    private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+    @Override
+    public String serialize(SelectQuery selectQuery) {
+        StringBuffer s = new StringBuffer("SELECT ");
+        if (selectQuery.isDistinct()) {
+            s.append("DISTINCT\n");
+        }
+        if (selectQuery.isReduced()) {
+            s.append("REDUCED\n");
+        }
+        if (selectQuery.isSelectAll()) {
+            s.append("*");
+        } else {
+            for (Variable v : selectQuery.getSelection()) {
+                appendVariable(s, v);
+                s.append(" ");
+            }
+        }
+        s.append("\n");
+
+        appendDataSet(s, (SimpleQuery) selectQuery);
+        appendWhere(s, (SimpleQuery) selectQuery);
+        appendModifier(s, (SimpleQueryWithSolutionModifier) selectQuery);
+
+        return s.toString();
+    }
+
+    private void appendVariable(StringBuffer s, Variable v) {
+        s.append("?").append(v.getName());
+    }
+
+    private void appendDataSet(StringBuffer s, SimpleQuery q) {
+        DataSet dataSet = q.getDataSet();
+        if (dataSet != null) {
+            for (IRI dg : dataSet.getDefaultGraphs()) {
+                s.append("FROM ").append(dg.toString()).append("\n");
+            }
+            for (IRI ng : dataSet.getNamedGraphs()) {
+                s.append("FROM NAMED ").append(ng.toString()).append("\n");
+            }
+        }
+    }
+
+    private void appendWhere(StringBuffer s, SimpleQuery q) {
+        GroupGraphPattern queryPattern = q.getQueryPattern();
+        if (queryPattern == null) {
+            return;
+        }
+        s.append("WHERE\n");
+        appendGroupGraphPattern(s, q.getQueryPattern());
+    }
+
+    private void appendGroupGraphPattern(StringBuffer s,
+            GroupGraphPattern groupGraphPattern) {
+
+        s.append("{ ");
+        for (GraphPattern graphPattern : groupGraphPattern.getGraphPatterns()) {
+            appendGraphPattern(s, graphPattern);
+        }
+        for (Expression e : groupGraphPattern.getFilter()) {
+            boolean brackettedExpr = !((e instanceof BuiltInCall)
+                    || (e instanceof FunctionCall));
+            s.append("FILTER ");
+            if (brackettedExpr) {
+                s.append("(");
+            }
+            appendExpression(s, e);
+            if (brackettedExpr) {
+                s.append(")");
+            }
+            s.append("\n");
+        }
+        s.append("} ");
+    }
+
+    private void appendGraphPattern(StringBuffer s, GraphPattern graphPattern) {
+        if (graphPattern instanceof BasicGraphPattern) {
+            appendTriplePatterns(s,
+                    ((BasicGraphPattern) graphPattern).getTriplePatterns());
+        } else if (graphPattern instanceof GroupGraphPattern) {
+            appendGroupGraphPattern(s, (GroupGraphPattern) graphPattern);
+        } else if (graphPattern instanceof OptionalGraphPattern) {
+            appendGraphPattern(s,
+                    ((OptionalGraphPattern) graphPattern).getMainGraphPattern());
+            s.append(" OPTIONAL ");
+            appendGroupGraphPattern(s,
+                    ((OptionalGraphPattern) graphPattern).getOptionalGraphPattern());
+        } else if (graphPattern instanceof AlternativeGraphPattern) {
+            List<GroupGraphPattern> alternativeGraphPatterns =
+                    ((AlternativeGraphPattern) graphPattern).getAlternativeGraphPatterns();
+            if ((alternativeGraphPatterns != null) &&
+                    (!alternativeGraphPatterns.isEmpty())) {
+                appendGroupGraphPattern(s, alternativeGraphPatterns.get(0));
+                int size = alternativeGraphPatterns.size();
+                int i = 1;
+                while (i < size) {
+                    s.append(" UNION ");
+                    appendGroupGraphPattern(s, alternativeGraphPatterns.get(i));
+                    i++;
+                }
+            }
+        } else if (graphPattern instanceof GraphGraphPattern) {
+            s.append("ImmutableGraph ");
+            appendResourceOrVariable(s, ((GraphGraphPattern) graphPattern).getGraph());
+            s.append(" ");
+            appendGroupGraphPattern(s, ((GraphGraphPattern) graphPattern).getGroupGraphPattern());
+        } else {
+            logger.warn("Unsupported GraphPattern {}", graphPattern.getClass());
+        }
+    }
+
+    private void appendTriplePatterns(StringBuffer s,
+            Set<TriplePattern> triplePatterns) {
+
+        for (TriplePattern p : triplePatterns) {
+            appendResourceOrVariable(s, p.getSubject());
+            s.append(" ");
+            appendResourceOrVariable(s, p.getPredicate());
+            s.append(" ");
+            appendResourceOrVariable(s, p.getObject());
+            s.append(" .\n");
+        }
+    }
+
+    private void appendResourceOrVariable(StringBuffer s, ResourceOrVariable n) {
+        if (n.isVariable()) {
+            appendVariable(s, n.getVariable());
+        } else {
+            RDFTerm r = n.getResource();
+            if (r instanceof BlankNode) {
+                s.append("_:").append(r.toString().replace("@", "."));
+            } else {
+                s.append(r.toString());
+            }
+        }
+    }
+
+    private void appendExpression(StringBuffer s, Expression e) {
+        if (e instanceof Variable) {
+            appendVariable(s, (Variable) e);
+        } else if (e instanceof BinaryOperation) {
+            BinaryOperation bo = (BinaryOperation) e;
+            s.append("(");
+            appendExpression(s, bo.getLhsOperand());
+            s.append(") ").append(bo.getOperatorString()).append(" (");
+            appendExpression(s, bo.getRhsOperand());
+            s.append(")");
+        } else if (e instanceof UnaryOperation) {
+            UnaryOperation uo = (UnaryOperation) e;
+            s.append(uo.getOperatorString()).append(" (");
+            appendExpression(s, uo.getOperand());
+            s.append(")");
+        } else if (e instanceof BuiltInCall) {
+            BuiltInCall b = (BuiltInCall) e;
+            appendCall(s, b.getName(), b.getArguements());
+        } else if (e instanceof FunctionCall) {
+            FunctionCall f = (FunctionCall) e;
+            appendCall(s, f.getName().getUnicodeString(), f.getArguements());
+        } else if (e instanceof LiteralExpression) {
+            appendLiteralExpression(s, (LiteralExpression) e);
+        } else if (e instanceof UriRefExpression) {
+            s.append(((UriRefExpression) e).getUriRef().toString());
+        }
+    }
+
+    private void appendCall(StringBuffer s, String name, List<Expression> expr) {
+        s.append(name).append("(");
+        for (Expression e : expr) {
+            appendExpression(s, e);
+            s.append(",");
+        }
+        if (expr.isEmpty()) {
+            s.append(")");
+        } else {
+            s.setCharAt(s.length()-1, ')');
+        }
+    }
+
+    private void appendLiteralExpression(StringBuffer s, LiteralExpression le) {
+        s.append(le.getLiteral().toString());
+    }
+
+    private void appendModifier(StringBuffer s, SimpleQueryWithSolutionModifier q) {
+        List<OrderCondition> orderConditions = q.getOrderConditions();
+        if ((orderConditions != null) && (!orderConditions.isEmpty())) {
+            s.append("ORDER BY ");
+            for (OrderCondition oc : orderConditions) {
+                appendOrderCondition(s, oc);
+                s.append("\n");
+            }
+        }
+        if (q.getOffset() > 0) {
+            s.append("OFFSET ").append(q.getOffset()).append("\n");
+        }
+        if (q.getLimit() >= 0) {
+            s.append("LIMIT ").append(q.getLimit()).append("\n");
+        }
+    }
+
+    private void appendOrderCondition(StringBuffer s, OrderCondition oc) {
+        if (!oc.isAscending()) {
+            s.append("DESC(");
+        }
+        appendExpression(s, oc.getExpression());
+        if (!oc.isAscending()) {
+            s.append(")");
+        }
+        s.append(" ");
+    }
+
+    @Override
+    public String serialize(ConstructQuery constructQuery) {
+        StringBuffer s = new StringBuffer("CONSTRUCT\n");
+        Set<TriplePattern> triplePatterns = constructQuery.getConstructTemplate();
+        s.append("{ ");
+        if (triplePatterns != null && !triplePatterns.isEmpty()) {
+            appendTriplePatterns(s, triplePatterns);
+        }
+        s.append("}\n");
+
+        appendDataSet(s, (SimpleQuery) constructQuery);
+        appendWhere(s, (SimpleQuery) constructQuery);
+        appendModifier(s, (SimpleQueryWithSolutionModifier) constructQuery);
+
+        return s.toString();
+    }
+
+    @Override
+    public String serialize(DescribeQuery describeQuery) {
+        StringBuffer s = new StringBuffer("DESCRIBE\n");
+
+        if (describeQuery.isDescribeAll()) {
+            s.append("*");
+        } else {
+            for (ResourceOrVariable n : describeQuery.getResourcesToDescribe()) {
+                appendResourceOrVariable(s, n);
+                s.append(" ");
+            }
+        }
+        appendDataSet(s, (SimpleQuery) describeQuery);
+        appendWhere(s, (SimpleQuery) describeQuery);
+        appendModifier(s, (SimpleQueryWithSolutionModifier) describeQuery);
+
+        return s.toString();
+    }
+
+    @Override
+    public String serialize(AskQuery askQuery) {
+        StringBuffer s = new StringBuffer("ASK\n");
+        appendDataSet(s, (SimpleQuery) askQuery);
+        appendWhere(s, (SimpleQuery) askQuery);
+
+        return s.toString();
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleTriplePattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleTriplePattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleTriplePattern.java
new file mode 100644
index 0000000..ca91b57
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleTriplePattern.java
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.api.BlankNodeOrIRI;
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.api.RDFTerm;
+import org.apache.clerezza.sparql.query.ResourceOrVariable;
+import org.apache.clerezza.sparql.query.TriplePattern;
+import org.apache.clerezza.sparql.query.UriRefOrVariable;
+import org.apache.clerezza.sparql.query.Variable;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleTriplePattern implements TriplePattern {
+
+    private ResourceOrVariable subject;
+    private UriRefOrVariable predicate;
+    private ResourceOrVariable object;
+
+    public SimpleTriplePattern(ResourceOrVariable subject,
+            UriRefOrVariable predicate,
+            ResourceOrVariable object) {
+        if (subject == null) {
+            throw new IllegalArgumentException("Invalid subject: null");
+        }
+        if (predicate == null) {
+            throw new IllegalArgumentException("Invalid predicate: null");
+        }
+        if (object == null) {
+            throw new IllegalArgumentException("Invalid object: null");
+        }
+        this.subject = subject;
+        this.predicate = predicate;
+        this.object = object;
+    }
+
+    public SimpleTriplePattern(Variable subject, Variable predicate, Variable object) {
+        this(new ResourceOrVariable(subject), new UriRefOrVariable(predicate),
+                new ResourceOrVariable(object));
+    }
+
+    public SimpleTriplePattern(BlankNodeOrIRI subject, Variable predicate, Variable object) {
+        this(new ResourceOrVariable(subject), new UriRefOrVariable(predicate),
+                new ResourceOrVariable(object));
+    }
+
+    public SimpleTriplePattern(Variable subject, IRI predicate, Variable object) {
+        this(new ResourceOrVariable(subject), new UriRefOrVariable(predicate),
+                new ResourceOrVariable(object));
+    }
+
+    public SimpleTriplePattern(BlankNodeOrIRI subject, IRI predicate, Variable object) {
+        this(new ResourceOrVariable(subject), new UriRefOrVariable(predicate),
+                new ResourceOrVariable(object));
+    }
+
+    public SimpleTriplePattern(Variable subject, Variable predicate, RDFTerm object) {
+        this(new ResourceOrVariable(subject), new UriRefOrVariable(predicate),
+                new ResourceOrVariable(object));
+    }
+
+    public SimpleTriplePattern(BlankNodeOrIRI subject, Variable predicate, RDFTerm object) {
+        this(new ResourceOrVariable(subject), new UriRefOrVariable(predicate),
+                new ResourceOrVariable(object));
+    }
+
+    public SimpleTriplePattern(Variable subject, IRI predicate, RDFTerm object) {
+        this(new ResourceOrVariable(subject), new UriRefOrVariable(predicate),
+                new ResourceOrVariable(object));
+    }
+
+    public SimpleTriplePattern(BlankNodeOrIRI subject, IRI predicate, RDFTerm object) {
+        this(new ResourceOrVariable(subject), new UriRefOrVariable(predicate),
+                new ResourceOrVariable(object));
+    }
+
+    @Override
+    public ResourceOrVariable getSubject() {
+        return subject;
+    }
+
+    @Override
+    public UriRefOrVariable getPredicate() {
+        return predicate;
+    }
+
+    @Override
+    public ResourceOrVariable getObject() {
+        return object;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof TriplePattern)) {
+            return false;
+        }
+        final TriplePattern other = (TriplePattern) obj;
+        if (!this.subject.equals(other.getSubject())) {
+            return false;
+        }
+        if (!this.predicate.equals(other.getPredicate())) {
+            return false;
+        }
+        if (!this.object.equals(other.getObject())) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        return (subject.hashCode() >> 1) ^ subject.hashCode() ^ (subject.hashCode() << 1);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/Update.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/Update.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/Update.java
new file mode 100644
index 0000000..73616a8
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/Update.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update;
+
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.sparql.GraphStore;
+
+import java.util.Set;
+
+/**
+ * <p>This interface represents a SPARQL Update.</p>
+ *
+ * @author hasan
+ */
+public interface Update {
+
+    /**
+     * 
+     * @param defaultGraph
+     *      if default graph is referred either implicitly or explicitly in a SPARQL {@link Update}
+     *      the specified defaultGraph should be returned in the resulting set.
+     * @param graphStore
+     *      the specified tcProvider is used to get the named graphs referred in the SPARQL {@link Update}.
+     * @return a set of graphs referred in the {@link Update}.
+     */
+    public Set<IRI> getReferredGraphs(IRI defaultGraph, GraphStore graphStore);
+
+    public void addOperation(UpdateOperation updateOperation);
+
+    /**
+     *
+     * @return A valid String representation of the {@link Update}.
+     */
+    @Override
+    public abstract String toString();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/UpdateOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/UpdateOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/UpdateOperation.java
new file mode 100644
index 0000000..990967e
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/UpdateOperation.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update;
+
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.sparql.GraphStore;
+
+import java.util.Set;
+
+/**
+ * SPARQL Update Operation
+ *
+ * @author hasan
+ */
+public interface UpdateOperation {
+    public enum GraphSpec {
+        GRAPH, DEFAULT, NAMED, ALL
+    }
+
+    /**
+     * 
+     * @param defaultGraph
+     *      if default graph is referred either implicitly or explicitly as an input graph in this operation
+     *      the specified defaultGraph should be returned in the resulting set.
+     * @param graphStore
+     *      the specified tcProvider is used to get the named graphs referred as input graphs in this operation.
+     * @return a set of graphs referred as input graphs in this operation.
+     */
+    public Set<IRI> getInputGraphs(IRI defaultGraph, GraphStore graphStore);
+
+    /**
+     * 
+     * @param defaultGraph
+     *      if default graph is referred either implicitly or explicitly as a destination graph in this operation
+     *      the specified defaultGraph should be returned in the resulting set.
+     * @param graphStore
+     *      the specified tcProvider is used to get the named graphs referred as destination graphs in this operation.
+     * @return a set of graphs referred as destination graphs in this operation.
+     */
+    public Set<IRI> getDestinationGraphs(IRI defaultGraph, GraphStore graphStore);
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/AddOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/AddOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/AddOperation.java
new file mode 100644
index 0000000..d13e9f7
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/AddOperation.java
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+/**
+ * The ADD operation is a shortcut for inserting all data from an input ImmutableGraph into a destination ImmutableGraph. 
+ * Data from the input ImmutableGraph is not affected, and initial data from the destination ImmutableGraph, if any, is kept intact.
+ * @see <a href="http://www.w3.org/TR/2013/REC-sparql11-update-20130321/#add">SPARQL 1.1 Update: 3.2.5 ADD</a>
+ * 
+ * @author hasan
+ */
+public class AddOperation extends SimpleUpdateOperation {
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/BaseUpdateOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/BaseUpdateOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/BaseUpdateOperation.java
new file mode 100644
index 0000000..e782458
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/BaseUpdateOperation.java
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.sparql.GraphStore;
+import org.apache.clerezza.sparql.update.UpdateOperation;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ *
+ * @author hasan
+ */
+public abstract class BaseUpdateOperation implements UpdateOperation {
+
+    protected Set<IRI> inputGraphs = new HashSet<IRI>();
+    protected Set<IRI> destinationGraphs = new HashSet<IRI>();
+    protected GraphSpec inputGraphSpec = GraphSpec.GRAPH;
+    protected GraphSpec destinationGraphSpec = GraphSpec.GRAPH;
+
+    public void setInputGraphSpec(GraphSpec inputGraphSpec) {
+        this.inputGraphSpec = inputGraphSpec;
+    }
+
+    public GraphSpec getInputGraphSpec() {
+        return inputGraphSpec;
+    }
+
+    public void setDestinationGraphSpec(GraphSpec destinationGraphSpec) {
+        this.destinationGraphSpec = destinationGraphSpec;
+    }
+
+    public GraphSpec getDestinationGraphSpec() {
+        return destinationGraphSpec;
+    }
+
+    @Override
+    public Set<IRI> getInputGraphs(IRI defaultGraph, GraphStore graphStore) {
+        return getGraphs(defaultGraph, graphStore, inputGraphSpec, inputGraphs);
+    }
+
+    private Set<IRI> getGraphs(IRI defaultGraph, GraphStore graphStore, GraphSpec graphSpec, Set<IRI> graphs) {
+        switch (graphSpec) {
+            case DEFAULT:
+                Set<IRI> result = new HashSet<IRI>();
+                result.add(defaultGraph);
+                return result;
+            case NAMED:
+            case ALL:
+                return graphStore.listGraphs();
+            default:
+                return graphs;
+        }
+    }
+
+    @Override
+    public Set<IRI> getDestinationGraphs(IRI defaultGraph, GraphStore graphStore) {
+        return getGraphs(defaultGraph, graphStore, destinationGraphSpec, destinationGraphs);
+    }
+
+    public void addInputGraph(IRI ImmutableGraph) {
+        inputGraphs.add(ImmutableGraph);
+    }
+
+    public void addDestinationGraph(IRI ImmutableGraph) {
+        destinationGraphs.add(ImmutableGraph);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/ClearOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/ClearOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/ClearOperation.java
new file mode 100644
index 0000000..f3972a7
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/ClearOperation.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+/**
+ *
+ * @author hasan
+ */
+public class ClearOperation extends ClearOrDropOperation {
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/ClearOrDropOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/ClearOrDropOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/ClearOrDropOperation.java
new file mode 100644
index 0000000..ae4a1c8
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/ClearOrDropOperation.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.sparql.GraphStore;
+import org.apache.clerezza.sparql.update.UpdateOperation;
+
+import java.util.Set;
+
+/**
+ *
+ * @author hasan
+ */
+public class ClearOrDropOperation extends BaseUpdateOperation {
+    private boolean silent;
+
+    public ClearOrDropOperation() {
+        this.silent = false;
+        destinationGraphSpec = UpdateOperation.GraphSpec.DEFAULT;
+    }
+
+    public void setSilent(boolean silent) {
+        this.silent = silent;
+    }
+
+    public boolean isSilent() {
+        return silent;
+    }
+
+    public void setDestinationGraph(IRI destination) {
+        destinationGraphSpec = UpdateOperation.GraphSpec.GRAPH;
+        destinationGraphs.clear();
+        destinationGraphs.add(destination);
+    }
+
+    public IRI getDestinationGraph(IRI defaultGraph, GraphStore graphStore) {
+        Set<IRI> result = getDestinationGraphs(defaultGraph, graphStore);
+        if (result.isEmpty()) {
+            return null;
+        } else {
+            return result.iterator().next();
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/CopyOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/CopyOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/CopyOperation.java
new file mode 100644
index 0000000..9ec5b7b
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/CopyOperation.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+/**
+ *
+ * @author hasan
+ */
+public class CopyOperation extends SimpleUpdateOperation {
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/CreateOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/CreateOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/CreateOperation.java
new file mode 100644
index 0000000..7b2a46c
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/CreateOperation.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+import org.apache.clerezza.api.IRI;
+
+/**
+ *
+ * @author hasan
+ */
+public class CreateOperation extends BaseUpdateOperation {
+
+    private boolean silent;
+
+    public CreateOperation() {
+        this.silent = false;
+    }
+
+    public void setSilent(boolean silent) {
+        this.silent = silent;
+    }
+
+    public boolean isSilent() {
+        return silent;
+    }
+
+    public void setDestinationGraph(IRI destination) {
+        destinationGraphs.clear();
+        destinationGraphs.add(destination);
+    }
+
+    public IRI getDestinationGraph() {
+        if (destinationGraphs.isEmpty()) {
+            return null;
+        } else {
+            return destinationGraphs.iterator().next();
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/DeleteDataOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/DeleteDataOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/DeleteDataOperation.java
new file mode 100644
index 0000000..f1f59f0
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/DeleteDataOperation.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+/**
+ *
+ * @author hasan
+ */
+public class DeleteDataOperation extends UpdateOperationWithQuads {
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/DeleteWhereOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/DeleteWhereOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/DeleteWhereOperation.java
new file mode 100644
index 0000000..8614b7b
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/DeleteWhereOperation.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+/**
+ *
+ * @author hasan
+ */
+public class DeleteWhereOperation extends UpdateOperationWithQuads {
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/DropOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/DropOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/DropOperation.java
new file mode 100644
index 0000000..9e79ab1
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/DropOperation.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+/**
+ *
+ * @author hasan
+ */
+public class DropOperation extends ClearOrDropOperation {
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/InsertDataOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/InsertDataOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/InsertDataOperation.java
new file mode 100644
index 0000000..dbc3b93
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/InsertDataOperation.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+/**
+ *
+ * @author hasan
+ */
+public class InsertDataOperation extends UpdateOperationWithQuads {
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/LoadOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/LoadOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/LoadOperation.java
new file mode 100644
index 0000000..1020d77
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/LoadOperation.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+import org.apache.clerezza.api.IRI;
+
+/**
+ * The LOAD operation reads an RDF document from a IRI and inserts its triples into the specified ImmutableGraph in the ImmutableGraph Store. 
+ * If the destination ImmutableGraph already exists, then no data in that ImmutableGraph will be removed.
+ * If no destination ImmutableGraph IRI is provided to load the triples into, then the data will be loaded into the default ImmutableGraph.
+ * @see <a href="http://www.w3.org/TR/2013/REC-sparql11-update-20130321/#load">SPARQL 1.1 Update: 3.1.4 LOAD</a>
+ * @author hasan
+ */
+public class LoadOperation extends SimpleUpdateOperation {
+
+    public void setSource(IRI source) {
+        setInputGraph(source);
+    }
+
+    public IRI getSource() {
+        return getInputGraph(null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/ModifyOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/ModifyOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/ModifyOperation.java
new file mode 100644
index 0000000..f4f5134
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/ModifyOperation.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.sparql.GraphStore;
+import org.apache.clerezza.sparql.query.GroupGraphPattern;
+import org.apache.clerezza.sparql.query.impl.SimpleDataSet;
+import org.apache.clerezza.sparql.update.UpdateOperation;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * This ModifyOperation is a DELETE/INSERT operation.
+ * @see <a href="http://www.w3.org/TR/2013/REC-sparql11-update-20130321/#deleteInsert">SPARQL 1.1 Update: 3.1.3 DELETE/INSERT</a>
+ * 
+ * The DELETE/INSERT operation can be used to remove or add triples from/to the ImmutableGraph Store based on bindings 
+ * for a query pattern specified in a WHERE clause.
+ * 
+ * @author hasan
+ */
+public class ModifyOperation implements UpdateOperation {
+    private IRI fallbackGraph = null;
+    private UpdateOperationWithQuads deleteOperation = null;
+    private UpdateOperationWithQuads insertOperation = null;
+    private SimpleDataSet dataSet = null;
+    private GroupGraphPattern queryPattern = null;
+
+    public void setFallbackGraph(IRI fallbackGraph) {
+        this.fallbackGraph = fallbackGraph;
+    }
+
+    public void setDeleteOperation(UpdateOperationWithQuads deleteOperation) {
+        this.deleteOperation = deleteOperation;
+    }
+
+    public void setInsertOperation(UpdateOperationWithQuads insertOperation) {
+        this.insertOperation = insertOperation;
+    }
+
+    public void setDataSet(SimpleDataSet dataSet) {
+        this.dataSet = dataSet;
+    }
+
+    public void addGraphToDataSet(IRI ImmutableGraph) {
+        if (dataSet == null) {
+            dataSet = new SimpleDataSet();
+        }
+        dataSet.addDefaultGraph(ImmutableGraph);
+    }
+
+    public void addNamedGraphToDataSet(IRI namedGraph) {
+        if (dataSet == null) {
+            dataSet = new SimpleDataSet();
+        }
+        dataSet.addNamedGraph(namedGraph);
+    }
+
+    public void setQueryPattern(GroupGraphPattern queryPattern) {
+        this.queryPattern = queryPattern;
+    }
+
+    @Override
+    public Set<IRI> getInputGraphs(IRI defaultGraph, GraphStore graphStore) {
+        Set<IRI> graphs = new HashSet<IRI>();
+        if (dataSet != null) {
+            graphs.addAll(dataSet.getDefaultGraphs());
+            graphs.addAll(dataSet.getNamedGraphs());
+        } else {
+            if (fallbackGraph != null) {
+                graphs.add(fallbackGraph);
+            }
+        }
+        if (graphs.isEmpty()) {
+            graphs.add(defaultGraph);
+        }
+        if (queryPattern != null) {
+            graphs.addAll(queryPattern.getReferredGraphs());
+        }
+        return graphs;
+    }
+
+    @Override
+    public Set<IRI> getDestinationGraphs(IRI defaultGraph, GraphStore graphStore) {
+        Set<IRI> graphs = new HashSet<IRI>();
+        IRI dfltGraph = (fallbackGraph != null) ? fallbackGraph : defaultGraph;
+        if (deleteOperation != null) {
+            graphs.addAll(deleteOperation.getDestinationGraphs(dfltGraph, graphStore));
+        }
+        if (insertOperation != null) {
+            graphs.addAll(insertOperation.getDestinationGraphs(dfltGraph, graphStore));
+        }
+        return graphs;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/MoveOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/MoveOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/MoveOperation.java
new file mode 100644
index 0000000..1447c04
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/MoveOperation.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+/**
+ *
+ * @author hasan
+ */
+public class MoveOperation extends SimpleUpdateOperation {
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/Quad.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/Quad.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/Quad.java
new file mode 100644
index 0000000..d402429
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/Quad.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+import org.apache.clerezza.sparql.query.TriplePattern;
+import org.apache.clerezza.sparql.query.UriRefOrVariable;
+import org.apache.clerezza.sparql.query.impl.SimpleBasicGraphPattern;
+
+import java.util.Set;
+
+/**
+ *
+ * @author hasan
+ */
+public class Quad extends SimpleBasicGraphPattern {
+
+    private UriRefOrVariable ImmutableGraph = null;
+
+    public Quad(UriRefOrVariable ImmutableGraph, Set<TriplePattern> triplePatterns) {
+        super(triplePatterns);
+        this.ImmutableGraph = ImmutableGraph;
+    }
+
+    public UriRefOrVariable getGraph() {
+        return this.ImmutableGraph;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/SimpleUpdate.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/SimpleUpdate.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/SimpleUpdate.java
new file mode 100644
index 0000000..ce27266
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/SimpleUpdate.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.sparql.GraphStore;
+import org.apache.clerezza.sparql.update.Update;
+import org.apache.clerezza.sparql.update.UpdateOperation;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleUpdate implements Update {
+    protected List<UpdateOperation> operations = new ArrayList<UpdateOperation>();
+
+    @Override
+    public Set<IRI> getReferredGraphs(IRI defaultGraph, GraphStore graphStore) {
+        Set<IRI> referredGraphs = new HashSet<IRI>();
+        for (UpdateOperation operation : operations) {
+            referredGraphs.addAll(operation.getInputGraphs(defaultGraph, graphStore));
+            referredGraphs.addAll(operation.getDestinationGraphs(defaultGraph, graphStore));
+        }
+        return referredGraphs;
+    }
+
+    @Override
+    public void addOperation(UpdateOperation updateOperation) {
+        operations.add(updateOperation);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/SimpleUpdateOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/SimpleUpdateOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/SimpleUpdateOperation.java
new file mode 100644
index 0000000..b613088
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/SimpleUpdateOperation.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.sparql.update.UpdateOperation;
+
+import java.util.Set;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleUpdateOperation extends BaseUpdateOperation {
+
+    private boolean silent;
+
+    public SimpleUpdateOperation() {
+        this.silent = false;
+        inputGraphSpec = UpdateOperation.GraphSpec.DEFAULT;
+        destinationGraphSpec = UpdateOperation.GraphSpec.DEFAULT;
+    }
+
+    public void setSilent(boolean silent) {
+        this.silent = silent;
+    }
+
+    public boolean isSilent() {
+        return silent;
+    }
+
+    public void setInputGraph(IRI source) {
+        inputGraphSpec = UpdateOperation.GraphSpec.GRAPH;
+        inputGraphs.clear();
+        inputGraphs.add(source);
+    }
+
+    public IRI getInputGraph(IRI defaultGraph) {
+        Set<IRI> result = getInputGraphs(defaultGraph, null);
+        if (result.isEmpty()) {
+            return null;
+        } else {
+            return result.iterator().next();
+        }
+    }
+
+    public void setDestinationGraph(IRI destination) {
+        destinationGraphSpec = UpdateOperation.GraphSpec.GRAPH;
+        destinationGraphs.clear();
+        destinationGraphs.add(destination);
+    }
+
+    public IRI getDestinationGraph(IRI defaultGraph) {
+        Set<IRI> result = getDestinationGraphs(defaultGraph, null);
+        if (result.isEmpty()) {
+            return null;
+        } else {
+            return result.iterator().next();
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/UpdateOperationWithQuads.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/UpdateOperationWithQuads.java b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/UpdateOperationWithQuads.java
new file mode 100644
index 0000000..e24fbb7
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/update/impl/UpdateOperationWithQuads.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.update.impl;
+
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.sparql.GraphStore;
+import org.apache.clerezza.sparql.query.TriplePattern;
+import org.apache.clerezza.sparql.query.UriRefOrVariable;
+import org.apache.clerezza.sparql.update.UpdateOperation;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ *
+ * @author hasan
+ */
+public class UpdateOperationWithQuads implements UpdateOperation {
+
+    private Quad defaultQuad = null;
+    private List<Quad> quads = new ArrayList<Quad>();
+
+    public UpdateOperationWithQuads() {
+    }
+
+    public void addQuad(Set<TriplePattern> triplePatterns) {
+        if (defaultQuad == null) {
+            defaultQuad = new Quad(null, triplePatterns);
+        } else {
+            defaultQuad.addTriplePatterns(triplePatterns);
+        }
+    }
+
+    public void addQuad(UriRefOrVariable ImmutableGraph, Set<TriplePattern> triplePatterns) {
+        if (ImmutableGraph == null) {
+            addQuad(triplePatterns);
+        } else {
+            quads.add(new Quad(ImmutableGraph, triplePatterns));
+        }
+    }
+
+    @Override
+    public Set<IRI> getInputGraphs(IRI defaultGraph, GraphStore graphStore) {
+        return new HashSet<IRI>();
+    }
+
+    @Override
+    public Set<IRI> getDestinationGraphs(IRI defaultGraph, GraphStore graphStore) {
+        Set<IRI> graphs = new HashSet<IRI>();
+        if (defaultQuad != null) {
+            graphs.add(defaultGraph);
+        }
+        for (Quad quad : quads) {
+            UriRefOrVariable ImmutableGraph = quad.getGraph();
+            if (!ImmutableGraph.isVariable()) {
+                graphs.add(ImmutableGraph.getResource());
+            }
+        }
+        return graphs;
+    }
+}


[5/6] clerezza git commit: CLEREZZA-1026: Introduce GraphStore to remove dependency to TcProvider and refactor sparql

Posted by ha...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertyPathPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertyPathPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertyPathPattern.java
new file mode 100644
index 0000000..9c15a36
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertyPathPattern.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * Defines a property path pattern consisting of a subject, a property path expression, and an object.
+ * The subject and object are of type {@link ResourceOrVariable}, whereas
+ * the predicate is of type {@link PropertyPathExpressionOrVariable}.
+ * @see <a href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#sparqlPropertyPaths">
+ * SPARQL 1.1 Query Language: 18.1.7 Property Path Patterns</a>
+ *
+ * @author hasan
+ */
+public interface PropertyPathPattern {
+
+    /**
+     * @return the subject
+     */
+    public ResourceOrVariable getSubject();
+
+    /**
+     * @return the property path expression
+     */
+    public PropertyPathExpressionOrVariable getPropertyPathExpression();
+
+    /**
+     * @return the object
+     */
+    public ResourceOrVariable getObject();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertySet.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertySet.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertySet.java
new file mode 100644
index 0000000..fc7e122
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertySet.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * A property set is intended to store only predicate paths and inverse predicate paths.
+ *
+ * @author hasan
+ */
+public class PropertySet implements PropertyPathExpression {
+    private Set<PropertyPathExpression> propertySet = new HashSet<PropertyPathExpression>();
+
+    /**
+     * 
+     * @param propertyPathExpression expected value is a predicate path or an inverse predicate path
+     */
+    public void addElement(PropertyPathExpression propertyPathExpression) {
+        this.propertySet.add(propertyPathExpression);
+    }
+
+    public Set<PropertyPathExpression> getPropertySet() {
+        return propertySet;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/Query.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/Query.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/Query.java
new file mode 100644
index 0000000..2bb5e42
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/Query.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * <p>This interface represents a SPARQL query.</p>
+ * <p>There are four types of SPARQL queries: {@link SelectQuery},
+ * {@link ConstructQuery}, {@link DescribeQuery}, and {@link AskQuery}.</p>
+ *
+ * @author hasan
+ */
+public interface Query {
+
+    /**
+     * <p>Gets {@link DataSet} containing the specification of the default
+     * ImmutableGraph and named graphs, if any.</p>
+     * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#specifyingDataset">
+     * SPARQL Query Language: 8.2 Specifying RDF Datasets</a>
+     * @return
+     *        null if no data set is specified, indicating the use of
+     *        system default ImmutableGraph. Otherwise a {@link DataSet} object is returned.
+     */
+    public DataSet getDataSet();
+
+    /**
+     * <p>Gets the query pattern of the WHERE clause for the query.</p>
+     * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#GraphPattern">
+     * SPARQL Query Language: 5 ImmutableGraph Patterns</a>
+     * @return
+     *        the {@link GroupGraphPattern} of the WHERE clause for this query.
+     *        If the WHERE clause is not specified, null is returned.
+     */
+    public GroupGraphPattern getQueryPattern();
+    
+    public InlineData getInlineData();
+
+    /**
+     * 
+     * @return A valid String representation of the query.
+     */
+    @Override
+    public abstract String toString();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/QueryWithSolutionModifier.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/QueryWithSolutionModifier.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/QueryWithSolutionModifier.java
new file mode 100644
index 0000000..45db17b
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/QueryWithSolutionModifier.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import java.util.List;
+
+/**
+ * <p>This interface represents a SPARQL query which contains a specification
+ * of solution modifiers: GROUP BY, HAVING, ORDER BY, OFFSET, and LIMIT.</p>
+ *
+ * @see <a href="http://www.w3.org/TR/sparql11-query/#aggregates">
+ * SPARQL 1.1 Query Language: 11 Aggregates</a>
+ * and
+ * @see <a href="http://www.w3.org/TR/sparql11-query/#solutionModifiers">
+ * SPARQL 1.1 Query Language: 15 Solution Sequences and Modifiers</a>
+ *
+ * @author hasan
+ */
+public interface QueryWithSolutionModifier extends Query {
+
+    public List<Expression> getGroupConditions();
+
+    public List<Expression> getHavingConditions();
+
+    /**
+     * <p>Gets the list of required ordering conditions in decreasing ordering
+     * priority.</p>
+     * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#modOrderBy">
+     * SPARQL Query Language: 9.1 ORDER BY</a>
+     * @return A list of {@link OrderCondition}s, in order of priority.
+     */
+    public List<OrderCondition> getOrderConditions();
+
+    /**
+     * <p>Gets the numeric offset of the first row to be returned by the query. 
+     * The default offset is 0, meaning to start at the beginning.</p>
+     * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#modOffset">
+     * SPARQL Query Language: 9.4 OFFSET</a>
+     * @return The number of rows to skip in the result.
+     */
+    public int getOffset();
+
+    /**
+     * <p>Gets the maximum number of results to be returned by the query. 
+     * A limit of -1 means no limit (return all results).
+     * A limit of 0 means that no results should be returned.</p>
+     * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#modResultLimit">
+     * SPARQL Query Language: 9.5 LIMIT</a>
+     * @return The maximum number of rows to returned by the query.
+     */
+    public int getLimit();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/ResourceOrVariable.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/ResourceOrVariable.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/ResourceOrVariable.java
new file mode 100644
index 0000000..6e8b258
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/ResourceOrVariable.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import org.apache.clerezza.api.RDFTerm;
+
+/**
+ * Wraps either a {@link RDFTerm} or a {@link Variable}
+ *
+ * @author hasan
+ */
+public class ResourceOrVariable {
+
+    private final RDFTerm resource;
+    private final Variable variable;
+
+    public ResourceOrVariable(RDFTerm resource) {
+        if (resource == null) {
+            throw new IllegalArgumentException("Invalid resource: null");
+        }
+        this.resource = resource;
+        variable = null;
+    }
+
+    public ResourceOrVariable(Variable variable) {
+        if (variable == null) {
+            throw new IllegalArgumentException("Invalid variable: null");
+        }
+        this.variable = variable;
+        resource = null;
+    }
+
+    /**
+     *
+     * @return
+     *        true if it is a {@link Variable}, false if it is a {@link RDFTerm}
+     */
+    public boolean isVariable() {
+        return resource == null;
+    }
+
+    /**
+     * 
+     * @return
+     *        the wrapped Resource if it is a Resource, null otherwise
+     */
+    public RDFTerm getResource() {
+        return resource;
+    }
+    
+    /**
+     * 
+     * @return
+     *        the wrapped Variable if it is a Variable, null otherwise
+     */
+    public Variable getVariable() {
+        return variable;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof ResourceOrVariable)) {
+            return false;
+        }
+        final ResourceOrVariable other = (ResourceOrVariable) obj;
+        if (this.isVariable() != other.isVariable()) {
+            return false;
+        }
+        if (this.isVariable()) {
+            if (!this.getVariable().equals(other.getVariable())) {
+                return false;
+            }
+        } else {
+            if (!this.getResource().equals(other.getResource())) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        return (isVariable()
+                ? 13 * getVariable().hashCode() + 7
+                : 13 * getResource().hashCode() + 7);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/RhsListBinaryOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/RhsListBinaryOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/RhsListBinaryOperation.java
new file mode 100644
index 0000000..a2224ec
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/RhsListBinaryOperation.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import java.util.List;
+
+/**
+ * Defines an operation with two operands: a left hand side and a right hand side operand
+ * where the right hand side operand is a list.
+ *
+ * @author hasan
+ */
+public class RhsListBinaryOperation extends AbstractOperation {
+
+	private Expression lhsOperand;
+    private List<Expression> rhsOperand;
+
+	public RhsListBinaryOperation(String operator, Expression lhsOperand, List<Expression> rhsOperand) {
+		super(operator);
+		this.lhsOperand = lhsOperand;
+		this.rhsOperand = rhsOperand;
+	}
+
+	public Expression getLhsOperand() {
+		return lhsOperand;
+	}
+
+	public List<Expression> getRhsOperand() {
+		return rhsOperand;
+	}
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/SelectQuery.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/SelectQuery.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/SelectQuery.java
new file mode 100644
index 0000000..9760f19
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/SelectQuery.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import java.util.List;
+
+/**
+ * <p>This interface represents a SPARQL SELECT query.</p>
+ *
+ * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#select">
+ * SPARQL Query Language: 10.1 SELECT</a>
+ *
+ * @author hasan
+ */
+public interface SelectQuery extends QueryWithSolutionModifier {
+
+    /**
+     * <p>Tests if this query should return distinct results.</p>
+     * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#modDistinct">
+     * SPARQL Query Language: 9.3.1 DISTINCT</a>
+     * @return <code>true</code> if the query should return distinct results.
+     */
+    public boolean isDistinct();
+
+    /**
+     * <p>Tests if this query should return reduced results.</p>
+     * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#modReduced">
+     * SPARQL Query Language: 9.3.2 REDUCED</a>
+     * @return <code>true</code> if the query should return reduced results.
+     */
+    public boolean isReduced();
+
+    /**
+     * <p>Tests if this query returns all its variables, and not a projected subset.</p>
+     * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#solutionModifiers">
+     * SPARQL Query Language: 9 Solution Sequences and Modifiers</a>
+     * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#modProjection">
+     * SPARQL Query Language: 9.2 Projection</a>
+     * @return <code>true</code> if the query should return all variables.
+     */
+    public boolean isSelectAll();
+
+    /**
+     * <p>Gets the list of {@link Variable}s to project the solution to.
+     * If {@link #isSelectAll()} returns <code>true</code> then
+     * this list contains all the variables from the query.</p>
+     * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#select">
+     * SPARQL Query Language: 10.1 SELECT</a>
+     * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#modProjection">
+     * SPARQL Query Language: 9.2 Projection</a>
+     * @return A list of {@link Variable}s to return from the query.
+     */
+    public List<Variable> getSelection();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/ServiceGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/ServiceGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/ServiceGraphPattern.java
new file mode 100644
index 0000000..973de90
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/ServiceGraphPattern.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * Defines a service ImmutableGraph pattern.
+ * @see <a href="http://www.w3.org/TR/sparql11-federated-query/">
+ * SPARQL 1.1 Federated Query</a>
+ *
+ * @author hasan
+ */
+public interface ServiceGraphPattern extends GraphPattern {
+
+    /**
+     *
+     * @return a {@link UriRefOrVariable} which specifies the service endpoint.
+     */
+    public UriRefOrVariable getService();
+
+    /**
+     * 
+     * @return the pattern to match.
+     */
+    public GroupGraphPattern getGroupGraphPattern();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/SparqlUnit.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/SparqlUnit.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/SparqlUnit.java
new file mode 100644
index 0000000..b0ab668
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/SparqlUnit.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import org.apache.clerezza.sparql.update.Update;
+
+/**
+ * <p>This interface represents a SPARQL Query or Update.</p>
+ *
+ * @author hasan
+ */
+public interface SparqlUnit {
+
+    /**
+     * 
+	 * @return
+	 *		true if it is a {@link Query}, false if it is an {@link Update}
+     */
+    public boolean isQuery();
+
+    /**
+     * 
+	 * @return
+	 *		the wrapped Query if it is a {@link Query}, null otherwise
+     */
+	public Query getQuery();
+
+    /**
+     * 
+	 * @return
+	 *		the wrapped Update if it is an {@link Update}, null otherwise
+     */
+	public Update getUpdate();
+
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/TriplePattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/TriplePattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/TriplePattern.java
new file mode 100644
index 0000000..37cdf32
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/TriplePattern.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * Defines a triple pattern consisting of a subject, a predicate, and an object.
+ * The subject and object are of type {@link ResourceOrVariable}, whereas
+ * the predicate is of type {@link UriRefOrVariable}.
+ *
+ * @author hasan
+ */
+public interface TriplePattern {
+
+    /**
+     * @return the subject
+     */
+    public ResourceOrVariable getSubject();
+
+    /**
+     * @return the predicate
+     */
+    public UriRefOrVariable getPredicate();
+
+    /**
+     * @return the object
+     */
+    public ResourceOrVariable getObject();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/UnaryOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/UnaryOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/UnaryOperation.java
new file mode 100644
index 0000000..4101870
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/UnaryOperation.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * Defines an operation with a single operand.
+ *
+ * @author hasan
+ */
+public class UnaryOperation extends AbstractOperation {
+
+    private Expression operand;
+
+    public UnaryOperation(String operator, Expression operand) {
+        super(operator);
+        this.operand = operand;
+    }
+
+    public Expression getOperand() {
+        return operand;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/UnaryPropertyPathOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/UnaryPropertyPathOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/UnaryPropertyPathOperation.java
new file mode 100644
index 0000000..0126c2f
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/UnaryPropertyPathOperation.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ *
+ * @author hasan
+ */
+public class UnaryPropertyPathOperation implements PropertyPathExpression {
+    private String operator;
+    private PropertyPathExpression operand;
+
+    public UnaryPropertyPathOperation(String operator, PropertyPathExpression operand) {
+        this.operator = operator;
+        this.operand = operand;
+    }
+
+    public PropertyPathExpression getOperand() {
+        return operand;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/UriRefExpression.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/UriRefExpression.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/UriRefExpression.java
new file mode 100644
index 0000000..98a1aba
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/UriRefExpression.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import org.apache.clerezza.api.IRI;
+
+/**
+ * Wraps a {@link IRI} in an {@link Expression}.
+ *
+ * @author hasan
+ */
+public class UriRefExpression implements Expression {
+
+    private final IRI uriRef;
+
+    public UriRefExpression(IRI uriRef) {
+        this.uriRef = uriRef;
+    }
+
+    public IRI getUriRef() {
+        return uriRef;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/UriRefOrVariable.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/UriRefOrVariable.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/UriRefOrVariable.java
new file mode 100644
index 0000000..22c1a1f
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/UriRefOrVariable.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import org.apache.clerezza.api.IRI;
+
+/**
+ * Wraps either a {@link IRI} or a {@link Variable}.
+ *
+ * @author rbn
+ */
+public class UriRefOrVariable extends ResourceOrVariable {
+
+    public UriRefOrVariable(Variable variable) {
+        super(variable);
+    }
+
+    public UriRefOrVariable(IRI resource) {
+        super(resource);
+    }
+
+    @Override
+    public IRI getResource() {
+        return (IRI)super.getResource();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/Variable.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/Variable.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/Variable.java
new file mode 100644
index 0000000..ba0317c
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/Variable.java
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import java.util.UUID;
+
+/**
+ * Defines a Variable. A Variable can occur in an {@link Expression} and is
+ * itself an {@link Expression}.
+ * 
+ * @author hasan
+ */
+public class Variable implements Expression {
+
+	private String name;
+	private Expression boundExpression;
+
+	public Variable() {
+		this.name = UUID.randomUUID().toString();
+	}
+
+	/**
+	 * Creates a variable with the specified name
+	 *
+	 * @param name
+	 */
+	public Variable(String name) {
+		if (name == null) {
+			throw new IllegalArgumentException("name may not be null");
+		}
+		this.name = name;
+	}
+
+	public Variable(String name, Expression boundExpression) {
+		this.name = name;
+		this.boundExpression = boundExpression;
+	}
+
+	/**
+	 * @return the name
+	 */
+	public String getName() {
+		return name;
+	}
+
+	public Expression getBoundExpression() {
+		return boundExpression;
+	}
+
+	public void setBoundExpression(Expression boundExpression) {
+		this.boundExpression = boundExpression;
+	}
+
+	@Override
+	public boolean equals(Object obj) {
+		if (obj == null) {
+			return false;
+		}
+		if (getClass() != obj.getClass()) {
+			return false;
+		}
+		final Variable other = (Variable) obj;
+		return name.equals(other.name);
+	}
+
+	@Override
+	public int hashCode() {
+		return name.hashCode();
+	}
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleAlternativeGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleAlternativeGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleAlternativeGraphPattern.java
new file mode 100644
index 0000000..eb2362b
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleAlternativeGraphPattern.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.sparql.query.AlternativeGraphPattern;
+import org.apache.clerezza.sparql.query.GroupGraphPattern;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleAlternativeGraphPattern implements AlternativeGraphPattern {
+
+    private List<GroupGraphPattern> alternativeGraphPatterns;
+
+    public SimpleAlternativeGraphPattern(
+            List<GroupGraphPattern> alternativeGraphPatterns) {
+        this.alternativeGraphPatterns = (alternativeGraphPatterns == null)
+                ? new ArrayList<GroupGraphPattern>()
+                : alternativeGraphPatterns;
+
+        this.alternativeGraphPatterns = alternativeGraphPatterns;
+    }
+
+    public SimpleAlternativeGraphPattern(GroupGraphPattern... groupGraphPatterns) {
+        alternativeGraphPatterns = new ArrayList<GroupGraphPattern>();
+        GroupGraphPattern[] g = groupGraphPatterns;
+        for (int i = 0; i < g.length; i++) {
+            alternativeGraphPatterns.add(g[i]);
+        }
+    }
+
+    @Override
+    public List<GroupGraphPattern> getAlternativeGraphPatterns() {
+        return alternativeGraphPatterns;
+    }
+
+    public void addAlternativeGraphPattern(GroupGraphPattern groupGraphPattern) {
+        alternativeGraphPatterns.add(groupGraphPattern);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleAskQuery.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleAskQuery.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleAskQuery.java
new file mode 100644
index 0000000..93d05f6
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleAskQuery.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.sparql.query.AskQuery;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleAskQuery extends SimpleQueryWithSolutionModifier implements AskQuery {
+
+    @Override
+    public String toString() {
+        return (new SimpleStringQuerySerializer()).serialize(this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleBasicGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleBasicGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleBasicGraphPattern.java
new file mode 100644
index 0000000..1a8d549
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleBasicGraphPattern.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.sparql.query.BasicGraphPattern;
+import org.apache.clerezza.sparql.query.TriplePattern;
+
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleBasicGraphPattern implements BasicGraphPattern {
+
+    private Set<TriplePattern> triplePatterns;
+
+    public SimpleBasicGraphPattern(Set<TriplePattern> triplePatterns) {
+        this.triplePatterns = (triplePatterns == null)
+                ? new LinkedHashSet<TriplePattern>()
+                : triplePatterns;
+    }
+
+    @Override
+    public Set<TriplePattern> getTriplePatterns() {
+        return triplePatterns;
+    }
+
+    public void addTriplePatterns(Set<TriplePattern> triplePatterns) {
+        this.triplePatterns.addAll(triplePatterns);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleConstructQuery.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleConstructQuery.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleConstructQuery.java
new file mode 100644
index 0000000..6cffd65
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleConstructQuery.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.sparql.query.ConstructQuery;
+import org.apache.clerezza.sparql.query.TriplePattern;
+
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleConstructQuery extends SimpleQueryWithSolutionModifier
+        implements ConstructQuery {
+
+    private Set<TriplePattern> triplePatterns;
+
+    public SimpleConstructQuery(Set<TriplePattern> triplePatterns) {
+        this.triplePatterns = (triplePatterns == null)
+                ? new LinkedHashSet<TriplePattern>()
+                : triplePatterns;
+    }
+
+    @Override
+    public Set<TriplePattern> getConstructTemplate() {
+        return triplePatterns;
+    }
+
+    @Override
+    public String toString() {
+        return (new SimpleStringQuerySerializer()).serialize(this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleDataSet.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleDataSet.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleDataSet.java
new file mode 100644
index 0000000..2e64bff
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleDataSet.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.sparql.query.DataSet;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleDataSet implements DataSet {
+    private Set<IRI> defaultGraphs = new HashSet<IRI>();
+    private Set<IRI> namedGraphs = new HashSet<IRI>();
+
+    @Override
+    public Set<IRI> getDefaultGraphs() {
+        return defaultGraphs;
+    }
+
+    @Override
+    public Set<IRI> getNamedGraphs() {
+        return namedGraphs;
+    }
+
+    public void addDefaultGraph(IRI defaultGraph) {
+        defaultGraphs.add(defaultGraph);
+    }
+
+    public void addNamedGraph(IRI namedGraph) {
+        namedGraphs.add(namedGraph);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleDescribeQuery.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleDescribeQuery.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleDescribeQuery.java
new file mode 100644
index 0000000..030a05a
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleDescribeQuery.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.sparql.query.DescribeQuery;
+import org.apache.clerezza.sparql.query.ResourceOrVariable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleDescribeQuery extends SimpleQueryWithSolutionModifier
+        implements DescribeQuery {
+
+    private boolean describeAll;
+    private List<ResourceOrVariable> resourcesToDescribe =
+            new ArrayList<ResourceOrVariable>();
+
+    @Override
+    public boolean isDescribeAll() {
+        return describeAll;
+    }
+
+    @Override
+    public List<ResourceOrVariable> getResourcesToDescribe() {
+        return resourcesToDescribe;
+    }
+
+    public void setDescribeAll() {
+        assert resourcesToDescribe.isEmpty();
+        describeAll = true;
+    }
+
+    public void addResourceToDescribe(ResourceOrVariable node) {
+        resourcesToDescribe.add(node);
+    }
+
+    @Override
+    public String toString() {
+        return (new SimpleStringQuerySerializer()).serialize(this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleGraphGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleGraphGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleGraphGraphPattern.java
new file mode 100644
index 0000000..567d2ad
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleGraphGraphPattern.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.sparql.query.GraphGraphPattern;
+import org.apache.clerezza.sparql.query.GroupGraphPattern;
+import org.apache.clerezza.sparql.query.UriRefOrVariable;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleGraphGraphPattern implements GraphGraphPattern {
+
+    private UriRefOrVariable ImmutableGraph;
+    private GroupGraphPattern groupGraphPattern;
+
+    public SimpleGraphGraphPattern(UriRefOrVariable ImmutableGraph,
+            GroupGraphPattern groupGraphPattern) {
+        if (ImmutableGraph == null) {
+            throw new IllegalArgumentException("ImmutableGraph may not be null");
+        }
+        if (groupGraphPattern == null) {
+            throw new IllegalArgumentException("Group ImmutableGraph Pattern may not be null");
+        }
+        this.ImmutableGraph = ImmutableGraph;
+        this.groupGraphPattern = groupGraphPattern;
+    }
+
+    @Override
+    public UriRefOrVariable getGraph() {
+        return ImmutableGraph;
+    }
+
+    @Override
+    public GroupGraphPattern getGroupGraphPattern() {
+        return groupGraphPattern;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleGroupGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleGroupGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleGroupGraphPattern.java
new file mode 100644
index 0000000..89beff9
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleGroupGraphPattern.java
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.sparql.query.*;
+
+import java.util.*;
+
+/**
+ * This class implements {@link GroupGraphPattern}.
+ *
+ * @author hasan
+ */
+public class SimpleGroupGraphPattern implements GroupGraphPattern {
+
+	private List<Expression> constraints = new ArrayList<Expression>();
+	private List<GraphPattern> graphPatterns = new ArrayList<GraphPattern>();
+    private SelectQuery subSelect = null;
+    private boolean lastBasicGraphPatternIsComplete = true;
+
+    @Override
+    public boolean isSubSelect() {
+        return subSelect != null;
+    }
+
+    @Override
+    public SelectQuery getSubSelect() {
+        return subSelect;
+    }
+
+    @Override
+	public Set<GraphPattern> getGraphPatterns() {
+		return subSelect == null ? new LinkedHashSet(graphPatterns) : null;
+	}
+
+	@Override
+	public List<Expression> getFilter() {
+		return subSelect == null ? constraints : null;
+	}
+
+    public void setSubSelect(SelectQuery subSelect) {
+        this.subSelect = subSelect;
+    }
+
+    /**
+	 * Adds a {@link GraphPattern} to the group.
+	 *
+	 * @param graphPattern
+	 *		the GraphPattern to be added.
+	 */
+	public void addGraphPattern(GraphPattern graphPattern) {
+        subSelect = null;
+        graphPatterns.add(graphPattern);
+        lastBasicGraphPatternIsComplete =
+                !(graphPattern instanceof BasicGraphPattern || graphPattern instanceof PathSupportedBasicGraphPattern);
+	}
+
+	/**
+	 * Adds a constraint to the {@link GroupGraphPattern}.
+	 *
+	 * @param constraint
+	 *		an {@link Expression} as the constraint to be added.
+	 */
+	public void addConstraint(Expression constraint) {
+        subSelect = null;
+		constraints.add(constraint);
+	}
+
+    public void endLastBasicGraphPattern() {
+        lastBasicGraphPatternIsComplete = true;
+    }
+
+    /**
+	 * If the last {@link GraphPattern} added to the group is not a 
+	 * {@link SimplePathSupportedBasicGraphPattern}, then creates one containing the 
+	 * specified {@link PropertyPathPattern}s and adds it to the group.
+	 * Otherwise, adds the specified {@link PropertyPathPattern}s to the last
+	 * added {@link SimplePathSupportedBasicGraphPattern} in the group.
+	 * 
+	 * @param propertyPathPatterns
+	 *		a set of {@link PropertyPathPattern}s to be added into a 
+	 *		{@link SimplePathSupportedBasicGraphPattern} of the group.
+	 */
+	public void addPropertyPathPatterns(Set<PropertyPathPattern> propertyPathPatterns) {
+        subSelect = null;
+        if (lastBasicGraphPatternIsComplete) {
+            graphPatterns.add(new SimplePathSupportedBasicGraphPattern(propertyPathPatterns));
+            lastBasicGraphPatternIsComplete = false;
+        } else {
+            GraphPattern prevGraphPattern;
+        	int size = graphPatterns.size();
+			prevGraphPattern = graphPatterns.get(size-1);
+            if (prevGraphPattern instanceof SimplePathSupportedBasicGraphPattern) {
+                ((SimplePathSupportedBasicGraphPattern) prevGraphPattern).addPropertyPathPatterns(propertyPathPatterns);
+            }
+        }
+	}
+
+	/**
+	 * If the last {@link GraphPattern} added to the group is not a 
+	 * {@link SimpleBasicGraphPattern}, then creates one containing the 
+	 * specified {@link TriplePattern}s and adds it to the group.
+	 * Otherwise, adds the specified {@link TriplePattern}s to the last
+	 * added {@link SimpleBasicGraphPattern} in the group.
+	 * 
+	 * @param triplePatterns
+	 *		a set of {@link TriplePattern}s to be added into a 
+	 *		{@link SimpleBasicGraphPattern} of the group.
+	 */
+	public void addTriplePatterns(Set<TriplePattern> triplePatterns) {
+        subSelect = null;
+        GraphPattern prevGraphPattern;
+		int size = graphPatterns.size();
+		if (!lastBasicGraphPatternIsComplete && (size > 0)) {
+			prevGraphPattern = graphPatterns.get(size-1);
+			if (prevGraphPattern instanceof SimpleBasicGraphPattern) {
+				((SimpleBasicGraphPattern) prevGraphPattern)
+						.addTriplePatterns(triplePatterns);
+				return;
+			}
+		}
+		graphPatterns.add(new SimpleBasicGraphPattern(triplePatterns));
+        lastBasicGraphPatternIsComplete = false;
+	}
+
+	/**
+	 * Adds an {@link OptionalGraphPattern} to the group consisting of
+	 * a main ImmutableGraph pattern and the specified {@link GroupGraphPattern} as
+	 * the optional pattern.
+	 * The main ImmutableGraph pattern is taken from the last added {@link GraphPattern}
+	 * in the group, if it exists. Otherwise, the main ImmutableGraph pattern is null.
+	 *
+	 * @param optional
+	 *		a {@link GroupGraphPattern} as the optional pattern of
+	 *		an {@link OptionalGraphPattern}.
+	 */
+	public void addOptionalGraphPattern(GroupGraphPattern optional) {
+        subSelect = null;
+		GraphPattern prevGraphPattern = null;
+		int size = graphPatterns.size();
+		if (size > 0) {
+			prevGraphPattern = graphPatterns.remove(size-1);
+		}
+		graphPatterns.add(new SimpleOptionalGraphPattern(prevGraphPattern, optional));
+        lastBasicGraphPatternIsComplete = true;
+	}
+
+    public void addMinusGraphPattern(GroupGraphPattern subtrahend) {
+        subSelect = null;
+		GraphPattern prevGraphPattern = null;
+		int size = graphPatterns.size();
+		if (size > 0) {
+			prevGraphPattern = graphPatterns.remove(size-1);
+		}
+		graphPatterns.add(new SimpleMinusGraphPattern(prevGraphPattern, subtrahend));
+        lastBasicGraphPatternIsComplete = true;
+	}
+
+    @Override
+    public Set<IRI> getReferredGraphs() {
+        Set<IRI> referredGraphs = new HashSet<IRI>();
+        if (subSelect != null) {
+            GroupGraphPattern queryPattern = subSelect.getQueryPattern();
+            referredGraphs.addAll(queryPattern.getReferredGraphs());
+        } else {
+            for (GraphPattern graphPattern : graphPatterns) {
+                referredGraphs.addAll(getReferredGraphs(graphPattern));
+            }
+        }
+        return referredGraphs;
+    }
+
+    private Set<IRI> getReferredGraphs(GraphPattern graphPattern) {
+        Set<IRI> referredGraphs = new HashSet<IRI>();
+        if (graphPattern instanceof GraphGraphPattern) {
+            GraphGraphPattern graphGraphPattern = (GraphGraphPattern) graphPattern;
+            UriRefOrVariable ImmutableGraph = graphGraphPattern.getGraph();
+            if (!ImmutableGraph.isVariable()) {
+                referredGraphs.add(ImmutableGraph.getResource());
+            }
+            referredGraphs.addAll(graphGraphPattern.getGroupGraphPattern().getReferredGraphs());
+        } else if (graphPattern instanceof AlternativeGraphPattern) {
+            List<GroupGraphPattern> alternativeGraphPatterns =
+                    ((AlternativeGraphPattern) graphPattern).getAlternativeGraphPatterns();
+            for (GroupGraphPattern groupGraphPattern : alternativeGraphPatterns) {
+                referredGraphs.addAll(groupGraphPattern.getReferredGraphs());
+            }
+        } else if (graphPattern instanceof OptionalGraphPattern) {
+            GraphPattern mainGraphPattern = ((OptionalGraphPattern) graphPattern).getMainGraphPattern();
+            referredGraphs.addAll(getReferredGraphs(mainGraphPattern));
+            GroupGraphPattern optionalGraphPattern = ((OptionalGraphPattern) graphPattern).getOptionalGraphPattern();
+            referredGraphs.addAll(optionalGraphPattern.getReferredGraphs());
+        } else if (graphPattern instanceof MinusGraphPattern) {
+            GraphPattern minuendGraphPattern = ((MinusGraphPattern) graphPattern).getMinuendGraphPattern();
+            referredGraphs.addAll(getReferredGraphs(minuendGraphPattern));
+            GroupGraphPattern subtrahendGraphPattern = ((MinusGraphPattern) graphPattern).getSubtrahendGraphPattern();
+            referredGraphs.addAll(subtrahendGraphPattern.getReferredGraphs());
+        } else if (graphPattern instanceof GroupGraphPattern) {
+            GroupGraphPattern groupGraphPattern = (GroupGraphPattern) graphPattern;
+            referredGraphs.addAll(groupGraphPattern.getReferredGraphs());
+        }
+        return referredGraphs;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleInlineData.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleInlineData.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleInlineData.java
new file mode 100644
index 0000000..e5ecbc7
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleInlineData.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.api.RDFTerm;
+import org.apache.clerezza.sparql.query.InlineData;
+import org.apache.clerezza.sparql.query.Variable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleInlineData implements InlineData {
+
+    private List<Variable> variables = new ArrayList<Variable>();
+    private List<List<RDFTerm>> values = new ArrayList<List<RDFTerm>>();
+
+    @Override
+    public List<Variable> getVariables() {
+        return variables;
+    }
+
+    @Override
+    public List<List<RDFTerm>> getValues() {
+        return values;
+    }
+
+    public void addVariable(Variable variable) {
+        variables.add(variable);
+    }
+
+    public void addValues(List<RDFTerm> values) {
+        this.values.add(values);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleMinusGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleMinusGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleMinusGraphPattern.java
new file mode 100644
index 0000000..a93071d
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleMinusGraphPattern.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.sparql.query.GraphPattern;
+import org.apache.clerezza.sparql.query.GroupGraphPattern;
+import org.apache.clerezza.sparql.query.MinusGraphPattern;
+
+/**
+ * This class implements {@link MinusGraphPattern}.
+ *
+ * @author hasan
+ */
+public class SimpleMinusGraphPattern implements MinusGraphPattern {
+
+    private GraphPattern minuendGraphPattern;
+    private GroupGraphPattern subtrahendGraphPattern;
+
+    /**
+     * Constructs a {@link MinusGraphPattern} out of a {@link GraphPattern}
+     * as the minuend ImmutableGraph pattern and a {@link GroupGraphPattern} as the 
+     * subtrahend pattern.
+     * 
+     * @param minuendGraphPattern
+     *        a {@link GraphPattern} specifying the minuend pattern.
+     * @param subtrahendGraphPattern
+     *        a {@link GroupGraphPattern} specifying the subtrahend pattern.
+     */
+    public SimpleMinusGraphPattern(GraphPattern minuendGraphPattern, GroupGraphPattern subtrahendGraphPattern) {
+        if (subtrahendGraphPattern == null) {
+            throw new IllegalArgumentException("Subtrahend ImmutableGraph pattern may not be null");
+        }
+        if (minuendGraphPattern == null) {
+            this.minuendGraphPattern = new SimpleGroupGraphPattern();
+        } else {
+            this.minuendGraphPattern = minuendGraphPattern;
+        }
+        this.subtrahendGraphPattern = subtrahendGraphPattern;
+    }
+
+    @Override
+    public GraphPattern getMinuendGraphPattern() {
+        return minuendGraphPattern;
+    }
+
+    @Override
+    public GroupGraphPattern getSubtrahendGraphPattern() {
+        return subtrahendGraphPattern;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleOptionalGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleOptionalGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleOptionalGraphPattern.java
new file mode 100644
index 0000000..8f489e3
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleOptionalGraphPattern.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.sparql.query.GraphPattern;
+import org.apache.clerezza.sparql.query.GroupGraphPattern;
+import org.apache.clerezza.sparql.query.OptionalGraphPattern;
+
+/**
+ * This class implements {@link OptionalGraphPattern}.
+ *
+ * @author hasan
+ */
+public class SimpleOptionalGraphPattern implements OptionalGraphPattern {
+
+    private GraphPattern mainGraphPattern;
+    private GroupGraphPattern optionalGraphPattern;
+
+    /**
+     * Constructs an {@link OptionalGraphPattern} out of a {@link GraphPattern}
+     * as the main ImmutableGraph pattern and a {@link GroupGraphPattern} as the 
+     * optional pattern.
+     * 
+     * @param mainGraphPattern
+     *        a {@link GraphPattern} specifying the main pattern.
+     * @param optionalGraphPattern
+     *        a {@link GroupGraphPattern} specifying the optional pattern.
+     */
+    public SimpleOptionalGraphPattern(GraphPattern mainGraphPattern,
+            GroupGraphPattern optionalGraphPattern) {
+        if (optionalGraphPattern == null) {
+            throw new IllegalArgumentException("Optional ImmutableGraph pattern may not be null");
+        }
+        if (mainGraphPattern == null) {
+            this.mainGraphPattern = new SimpleGroupGraphPattern();
+        } else {
+            this.mainGraphPattern = mainGraphPattern;
+        }
+        this.optionalGraphPattern = optionalGraphPattern;
+    }
+
+    @Override
+    public GraphPattern getMainGraphPattern() {
+        return mainGraphPattern;
+    }
+
+    @Override
+    public GroupGraphPattern getOptionalGraphPattern() {
+        return optionalGraphPattern;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleOrderCondition.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleOrderCondition.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleOrderCondition.java
new file mode 100644
index 0000000..2111137
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleOrderCondition.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.sparql.query.Expression;
+import org.apache.clerezza.sparql.query.OrderCondition;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleOrderCondition implements OrderCondition {
+    private Expression expression;
+    private boolean ascending;
+
+    public SimpleOrderCondition(Expression expression, boolean ascending) {
+        this.expression = expression;
+        this.ascending = ascending;
+    }
+
+    @Override
+    public Expression getExpression() {
+        return expression;
+    }
+
+    @Override
+    public boolean isAscending() {
+        return ascending;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimplePathSupportedBasicGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimplePathSupportedBasicGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimplePathSupportedBasicGraphPattern.java
new file mode 100644
index 0000000..a7aaf55
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimplePathSupportedBasicGraphPattern.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.sparql.query.PathSupportedBasicGraphPattern;
+import org.apache.clerezza.sparql.query.PropertyPathPattern;
+
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimplePathSupportedBasicGraphPattern implements PathSupportedBasicGraphPattern {
+
+    private Set<PropertyPathPattern> propertyPathPatterns;
+
+    public SimplePathSupportedBasicGraphPattern(Set<PropertyPathPattern> propertyPathPatterns) {
+        this.propertyPathPatterns = (propertyPathPatterns == null)
+                ? new LinkedHashSet<PropertyPathPattern>()
+                : propertyPathPatterns;
+    }
+
+    @Override
+    public Set<PropertyPathPattern> getPropertyPathPatterns() {
+        return propertyPathPatterns;
+    }
+
+    public void addPropertyPathPatterns(Set<PropertyPathPattern> propertyPathPatterns) {
+        this.propertyPathPatterns.addAll(propertyPathPatterns);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimplePropertyPathPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimplePropertyPathPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimplePropertyPathPattern.java
new file mode 100644
index 0000000..cb79bfb
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimplePropertyPathPattern.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.api.BlankNodeOrIRI;
+import org.apache.clerezza.api.RDFTerm;
+import org.apache.clerezza.sparql.query.*;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimplePropertyPathPattern implements PropertyPathPattern {
+
+    private ResourceOrVariable subject;
+    private PropertyPathExpressionOrVariable propertyPathExpression;
+    private ResourceOrVariable object;
+
+    public SimplePropertyPathPattern(ResourceOrVariable subject,
+            PropertyPathExpressionOrVariable propertyPathExpression,
+            ResourceOrVariable object) {
+        if (subject == null) {
+            throw new IllegalArgumentException("Invalid subject: null");
+        }
+        if (propertyPathExpression == null) {
+            throw new IllegalArgumentException("Invalid property path expression: null");
+        }
+        if (object == null) {
+            throw new IllegalArgumentException("Invalid object: null");
+        }
+        this.subject = subject;
+        this.propertyPathExpression = propertyPathExpression;
+        this.object = object;
+    }
+
+    public SimplePropertyPathPattern(Variable subject, Variable propertyPathExpression, Variable object) {
+        this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
+                new ResourceOrVariable(object));
+    }
+
+    public SimplePropertyPathPattern(BlankNodeOrIRI subject, Variable propertyPathExpression, Variable object) {
+        this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
+                new ResourceOrVariable(object));
+    }
+
+    public SimplePropertyPathPattern(Variable subject, Variable propertyPathExpression, RDFTerm object) {
+        this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
+                new ResourceOrVariable(object));
+    }
+
+    public SimplePropertyPathPattern(BlankNodeOrIRI subject, Variable propertyPathExpression, RDFTerm object) {
+        this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
+                new ResourceOrVariable(object));
+    }
+
+    public SimplePropertyPathPattern(Variable subject, PropertyPathExpression propertyPathExpression, Variable object) {
+        this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
+                new ResourceOrVariable(object));
+    }
+
+    public SimplePropertyPathPattern(BlankNodeOrIRI subject, PropertyPathExpression propertyPathExpression, Variable object) {
+        this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
+                new ResourceOrVariable(object));
+    }
+
+    public SimplePropertyPathPattern(Variable subject, PropertyPathExpression propertyPathExpression, RDFTerm object) {
+        this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
+                new ResourceOrVariable(object));
+    }
+
+    public SimplePropertyPathPattern(BlankNodeOrIRI subject, PropertyPathExpression propertyPathExpression, RDFTerm object) {
+        this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
+                new ResourceOrVariable(object));
+    }
+
+    @Override
+    public ResourceOrVariable getSubject() {
+        return subject;
+    }
+
+    @Override
+    public PropertyPathExpressionOrVariable getPropertyPathExpression() {
+        return propertyPathExpression;
+    }
+
+    @Override
+    public ResourceOrVariable getObject() {
+        return object;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof PropertyPathPattern)) {
+            return false;
+        }
+        final PropertyPathPattern other = (PropertyPathPattern) obj;
+        if (!this.subject.equals(other.getSubject())) {
+            return false;
+        }
+        if (!this.propertyPathExpression.equals(other.getPropertyPathExpression())) {
+            return false;
+        }
+        if (!this.object.equals(other.getObject())) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        return (subject.hashCode() >> 1) ^ propertyPathExpression.hashCode() ^ (object.hashCode() << 1);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleQuery.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleQuery.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleQuery.java
new file mode 100644
index 0000000..3c1ba0b
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleQuery.java
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.sparql.query.DataSet;
+import org.apache.clerezza.sparql.query.GroupGraphPattern;
+import org.apache.clerezza.sparql.query.InlineData;
+import org.apache.clerezza.sparql.query.Query;
+
+/**
+ *
+ * @author hasan
+ */
+public abstract class SimpleQuery implements Query {
+
+    private SimpleDataSet dataSet = null;
+    private GroupGraphPattern queryPattern = null;
+    private InlineData inlineData = null;
+
+    @Override
+    public DataSet getDataSet() {
+        return dataSet;
+    }
+
+    @Override
+    public GroupGraphPattern getQueryPattern() {
+        return queryPattern;
+    }
+
+    @Override
+    public InlineData getInlineData() {
+        return inlineData;
+    }
+
+    public void addDefaultGraph(IRI defaultGraph) {
+        if (dataSet == null) {
+            dataSet = new SimpleDataSet();
+        }
+        dataSet.addDefaultGraph(defaultGraph);
+    }
+
+    public void addNamedGraph(IRI namedGraph) {
+        if (dataSet == null) {
+            dataSet = new SimpleDataSet();
+        }
+        dataSet.addNamedGraph(namedGraph);
+    }
+
+    public void setQueryPattern(GroupGraphPattern queryPattern) {
+        this.queryPattern = queryPattern;
+    }
+
+    public void setInlineData(InlineData inlineData) {
+        this.inlineData = inlineData;
+    }
+
+    @Override
+    public abstract String toString();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleQueryWithSolutionModifier.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleQueryWithSolutionModifier.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleQueryWithSolutionModifier.java
new file mode 100644
index 0000000..aea83f6
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleQueryWithSolutionModifier.java
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.sparql.query.Expression;
+import org.apache.clerezza.sparql.query.OrderCondition;
+import org.apache.clerezza.sparql.query.QueryWithSolutionModifier;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ *
+ * @author hasan
+ */
+public abstract class SimpleQueryWithSolutionModifier extends SimpleQuery
+        implements QueryWithSolutionModifier {
+
+    private List<Expression> groupConditions = new ArrayList<Expression>();
+    private List<Expression> havingConditions = new ArrayList<Expression>();
+    private List<OrderCondition> orderConditions = new ArrayList<OrderCondition>();
+
+    /**
+     * Result offset. 0 means no offset.
+     */
+    private int offset = 0;
+
+    /**
+     * Result limit. -1 means no limit.
+     */
+    private int limit = -1;
+
+    @Override
+    public List<Expression> getGroupConditions() {
+        return groupConditions;
+    }
+
+    @Override
+    public List<Expression> getHavingConditions() {
+        return havingConditions;
+    }
+
+    @Override
+    public List<OrderCondition> getOrderConditions() {
+        return orderConditions;
+    }
+
+    @Override
+    public int getOffset() {
+        return offset;
+    }
+
+    @Override
+    public int getLimit() {
+        return limit;
+    }
+
+    public void addGroupCondition(Expression groupCondition) {
+        groupConditions.add(groupCondition);
+    }
+
+    public void addHavingCondition(Expression havingCondition) {
+        havingConditions.add(havingCondition);
+    }
+
+    public void addOrderCondition(OrderCondition orderCondition) {
+        orderConditions.add(orderCondition);
+    }
+
+    public void setOffset(int offset) {
+        this.offset = offset;
+    }
+
+    public void setLimit(int limit) {
+        this.limit = limit;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleSelectQuery.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleSelectQuery.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleSelectQuery.java
new file mode 100644
index 0000000..fb4d5dc
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/impl/SimpleSelectQuery.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query.impl;
+
+import org.apache.clerezza.sparql.query.SelectQuery;
+import org.apache.clerezza.sparql.query.Variable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ *
+ * @author hasan
+ */
+public class SimpleSelectQuery extends SimpleQueryWithSolutionModifier
+        implements SelectQuery {
+
+    private boolean distinct;
+    private boolean reduced;
+    private boolean selectAll;
+    private List<Variable> variables = new ArrayList<Variable>();
+
+    @Override
+    public boolean isDistinct() {
+        return distinct;
+    }
+
+    @Override
+    public boolean isReduced() {
+        return reduced;
+    }
+
+    @Override
+    public boolean isSelectAll() {
+        return selectAll;
+    }
+
+    @Override
+    public List<Variable> getSelection() {
+        return variables;
+    }
+
+    public void setDistinct() {
+        distinct = true;
+    }
+
+    public void setReduced() {
+        reduced = true;
+    }
+
+    public void setSelectAll() {
+        assert variables.isEmpty();
+        selectAll = true;
+    }
+
+    public void addSelection(Variable var) {
+        variables.add(var);
+    }
+
+    @Override
+    public String toString() {
+        return (new SimpleStringQuerySerializer()).serialize(this);
+    }
+}


[6/6] clerezza git commit: CLEREZZA-1026: Introduce GraphStore to remove dependency to TcProvider and refactor sparql

Posted by ha...@apache.org.
CLEREZZA-1026: Introduce GraphStore to remove dependency to TcProvider and refactor sparql


Project: http://git-wip-us.apache.org/repos/asf/clerezza/repo
Commit: http://git-wip-us.apache.org/repos/asf/clerezza/commit/eec0ac73
Tree: http://git-wip-us.apache.org/repos/asf/clerezza/tree/eec0ac73
Diff: http://git-wip-us.apache.org/repos/asf/clerezza/diff/eec0ac73

Branch: refs/heads/reunited
Commit: eec0ac73d7d0496fb179093afb51f77bae9bb0a7
Parents: 829e5fa
Author: Hasan <ha...@apache.org>
Authored: Wed Nov 14 04:03:36 2018 +0100
Committer: Hasan <ha...@apache.org>
Committed: Wed Nov 14 04:03:36 2018 +0100

----------------------------------------------------------------------
 sparql/pom.xml                                  |  133 +
 .../org/apache/clerezza/sparql/GraphStore.java  |   22 +
 .../clerezza/sparql/NoQueryEngineException.java |   42 +
 .../org/apache/clerezza/sparql/QueryEngine.java |   45 +
 .../org/apache/clerezza/sparql/QueryParser.java |   71 +
 .../org/apache/clerezza/sparql/ResultSet.java   |   39 +
 .../apache/clerezza/sparql/SolutionMapping.java |   51 +
 .../apache/clerezza/sparql/SparqlPreParser.java |  160 ++
 .../clerezza/sparql/StringQuerySerializer.java  |   90 +
 .../sparql/query/AbstractOperation.java         |   41 +
 .../sparql/query/AlternativeGraphPattern.java   |   38 +
 .../apache/clerezza/sparql/query/AskQuery.java  |   29 +
 .../sparql/query/BasicGraphPattern.java         |   38 +
 .../clerezza/sparql/query/BinaryOperation.java  |   46 +
 .../query/BinaryPropertyPathOperation.java      |   44 +
 .../clerezza/sparql/query/BuiltInCall.java      |   47 +
 .../clerezza/sparql/query/ConstructQuery.java   |   41 +
 .../apache/clerezza/sparql/query/DataSet.java   |   47 +
 .../clerezza/sparql/query/DescribeQuery.java    |   50 +
 .../clerezza/sparql/query/Expression.java       |   42 +
 .../clerezza/sparql/query/FunctionCall.java     |   49 +
 .../sparql/query/GraphGraphPattern.java         |   42 +
 .../clerezza/sparql/query/GraphPattern.java     |   30 +
 .../sparql/query/GroupGraphPattern.java         |   70 +
 .../clerezza/sparql/query/InlineData.java       |   32 +
 .../sparql/query/LiteralExpression.java         |   40 +
 .../sparql/query/MinusGraphPattern.java         |   40 +
 .../sparql/query/OptionalGraphPattern.java      |   45 +
 .../clerezza/sparql/query/OrderCondition.java   |   37 +
 .../query/PathSupportedBasicGraphPattern.java   |   43 +
 .../sparql/query/PatternExistenceCondition.java |   66 +
 .../clerezza/sparql/query/PredicatePath.java    |   38 +
 .../sparql/query/PropertyPathExpression.java    |   29 +
 .../query/PropertyPathExpressionOrVariable.java |  104 +
 .../sparql/query/PropertyPathPattern.java       |   46 +
 .../clerezza/sparql/query/PropertySet.java      |   44 +
 .../org/apache/clerezza/sparql/query/Query.java |   59 +
 .../sparql/query/QueryWithSolutionModifier.java |   68 +
 .../sparql/query/ResourceOrVariable.java        |  106 +
 .../sparql/query/RhsListBinaryOperation.java    |   47 +
 .../clerezza/sparql/query/SelectQuery.java      |   70 +
 .../sparql/query/ServiceGraphPattern.java       |   41 +
 .../clerezza/sparql/query/SparqlUnit.java       |   51 +
 .../clerezza/sparql/query/TriplePattern.java    |   44 +
 .../clerezza/sparql/query/UnaryOperation.java   |   38 +
 .../query/UnaryPropertyPathOperation.java       |   37 +
 .../clerezza/sparql/query/UriRefExpression.java |   39 +
 .../clerezza/sparql/query/UriRefOrVariable.java |   43 +
 .../apache/clerezza/sparql/query/Variable.java  |   86 +
 .../impl/SimpleAlternativeGraphPattern.java     |   60 +
 .../sparql/query/impl/SimpleAskQuery.java       |   33 +
 .../query/impl/SimpleBasicGraphPattern.java     |   49 +
 .../sparql/query/impl/SimpleConstructQuery.java |   51 +
 .../sparql/query/impl/SimpleDataSet.java        |   52 +
 .../sparql/query/impl/SimpleDescribeQuery.java  |   61 +
 .../query/impl/SimpleGraphGraphPattern.java     |   55 +
 .../query/impl/SimpleGroupGraphPattern.java     |  221 ++
 .../sparql/query/impl/SimpleInlineData.java     |   54 +
 .../query/impl/SimpleMinusGraphPattern.java     |   67 +
 .../query/impl/SimpleOptionalGraphPattern.java  |   68 +
 .../sparql/query/impl/SimpleOrderCondition.java |   47 +
 .../SimplePathSupportedBasicGraphPattern.java   |   49 +
 .../query/impl/SimplePropertyPathPattern.java   |  132 +
 .../clerezza/sparql/query/impl/SimpleQuery.java |   76 +
 .../impl/SimpleQueryWithSolutionModifier.java   |   93 +
 .../sparql/query/impl/SimpleSelectQuery.java    |   80 +
 .../query/impl/SimpleServiceGraphPattern.java   |   66 +
 .../sparql/query/impl/SimpleSparqlUnit.java     |   65 +
 .../query/impl/SimpleStringQuerySerializer.java |  295 ++
 .../sparql/query/impl/SimpleTriplePattern.java  |  136 +
 .../apache/clerezza/sparql/update/Update.java   |   52 +
 .../clerezza/sparql/update/UpdateOperation.java |   57 +
 .../sparql/update/impl/AddOperation.java        |   29 +
 .../sparql/update/impl/BaseUpdateOperation.java |   86 +
 .../sparql/update/impl/ClearOperation.java      |   26 +
 .../update/impl/ClearOrDropOperation.java       |   61 +
 .../sparql/update/impl/CopyOperation.java       |   26 +
 .../sparql/update/impl/CreateOperation.java     |   55 +
 .../sparql/update/impl/DeleteDataOperation.java |   26 +
 .../update/impl/DeleteWhereOperation.java       |   26 +
 .../sparql/update/impl/DropOperation.java       |   26 +
 .../sparql/update/impl/InsertDataOperation.java |   26 +
 .../sparql/update/impl/LoadOperation.java       |   39 +
 .../sparql/update/impl/ModifyOperation.java     |  112 +
 .../sparql/update/impl/MoveOperation.java       |   26 +
 .../clerezza/sparql/update/impl/Quad.java       |   43 +
 .../sparql/update/impl/SimpleUpdate.java        |   52 +
 .../update/impl/SimpleUpdateOperation.java      |   77 +
 .../update/impl/UpdateOperationWithQuads.java   |   79 +
 .../sparql/JavaCCGeneratedQueryParser.jj        | 1285 +++++++++
 .../sparql/JavaCCGeneratedSparqlPreParser.jj    | 2557 ++++++++++++++++++
 .../QueryParserSerializerCombinationTest.java   |  135 +
 .../apache/clerezza/sparql/QueryParserTest.java |  367 +++
 .../clerezza/sparql/QuerySerializerTest.java    |  303 +++
 .../clerezza/sparql/SparqlPreParserTest.java    |  511 ++++
 95 files changed, 10492 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/pom.xml
----------------------------------------------------------------------
diff --git a/sparql/pom.xml b/sparql/pom.xml
new file mode 100644
index 0000000..10e64ad
--- /dev/null
+++ b/sparql/pom.xml
@@ -0,0 +1,133 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!--
+
+   Licensed to  the Apache Software Foundation (ASF)  under  one  or  more
+   contributor license agreements.  See the NOTICE file  distributed  with
+   this work for  additional information  regarding  copyright  ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not  use  this file  except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by  applicable law  or  agreed to in writing,  software
+   distributed  under  the  License  is  distributed on  an "AS IS"  BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the  License for the specific  language  governing  permissions and
+   limitations under the License.
+
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <parent>
+        <groupId>org.apache.clerezza</groupId>
+        <artifactId>clerezza</artifactId>
+        <version>8-SNAPSHOT</version>
+        <relativePath/>
+    </parent>
+
+    <artifactId>sparql</artifactId>
+    <packaging>bundle</packaging>
+    <version>1.0.2-SNAPSHOT</version>
+    <name>Clerezza - SPARQL</name>
+    <description>Model SPARQL query and update</description>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.clerezza</groupId>
+            <artifactId>api</artifactId>
+            <version>8-SNAPSHOT</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.clerezza</groupId>
+            <artifactId>api.impl</artifactId>
+            <version>8-SNAPSHOT</version>
+        </dependency>
+        <dependency>
+            <groupId>org.osgi</groupId>
+            <artifactId>org.osgi.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.osgi</groupId>
+            <artifactId>org.osgi.compendium</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-simple</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.felix</groupId>
+            <artifactId>org.apache.felix.scr.annotations</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.felix</groupId>
+            <artifactId>org.apache.felix.scr.ds-annotations</artifactId>
+            <version>1.2.8</version>
+        </dependency>
+    </dependencies>
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>javacc-maven-plugin</artifactId>
+                <version>2.5</version>
+                <executions>
+                    <execution>
+                        <id>javacc</id>
+                        <goals>
+                            <goal>javacc</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+            <plugin>
+                <groupId>org.codehaus.xsite</groupId>
+                <artifactId>xsite-maven-plugin</artifactId>
+                <configuration>
+                    <sourceDirectoryPath>${basedir}/src/site/xsite</sourceDirectoryPath>
+                    <sitemapPath>content/sitemap.xml</sitemapPath>
+                    <skinPath>templates/skin.html</skinPath>
+                    <outputDirectoryPath>${basedir}/target/site/documentation</outputDirectoryPath>
+                </configuration>
+                <executions>
+                    <execution>
+                        <phase>site</phase>
+                        <goals>
+                            <goal>run</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Export-Package>org.apache.clerezza.sparql.*</Export-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <id>generate-scr-scrdescriptor</id>
+                        <goals>
+                            <goal>scr</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+</project>

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/GraphStore.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/GraphStore.java b/sparql/src/main/java/org/apache/clerezza/sparql/GraphStore.java
new file mode 100644
index 0000000..34113b9
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/GraphStore.java
@@ -0,0 +1,22 @@
+package org.apache.clerezza.sparql;
+
+import org.apache.clerezza.api.IRI;
+
+import java.util.Set;
+
+public interface GraphStore {
+
+    /**
+     * Lists the name of the <Code>Graph</code>s available through this <code>GraphStore</code>.
+     *
+     * @return the list of <Code>Graph</code>s
+     */
+    Set<IRI> listGraphs();
+
+    /**
+     * Lists the name of the named <Code>Graph</code>s available through this <code>GraphStore</code>.
+     *
+     * @return the list of named <Code>Graph</code>s
+     */
+    Set<IRI> listNamedGraphs();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/NoQueryEngineException.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/NoQueryEngineException.java b/sparql/src/main/java/org/apache/clerezza/sparql/NoQueryEngineException.java
new file mode 100644
index 0000000..37547ef
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/NoQueryEngineException.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql;
+
+/**
+ * Indicates that there is no available query engine for resolving a query.
+ *
+ * @author rbn
+ */
+public class NoQueryEngineException extends RuntimeException {
+
+    /**
+     * Creates a new instance of <code>NoQueryEngineException</code> without detail message.
+     */
+    public NoQueryEngineException() {
+    }
+
+
+    /**
+     * Constructs an instance of <code>NoQueryEngineException</code> with the specified detail message.
+     * @param msg the detail message.
+     */
+    public NoQueryEngineException(String msg) {
+        super(msg);
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/QueryEngine.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/QueryEngine.java b/sparql/src/main/java/org/apache/clerezza/sparql/QueryEngine.java
new file mode 100644
index 0000000..1592fa7
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/QueryEngine.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql;
+
+import org.apache.clerezza.api.Graph;
+import org.apache.clerezza.sparql.query.Query;
+
+/**
+ * A QueryEngine can process SPARQL queries against an arbitrary set of graphs.
+ * 
+ * @author rbn
+ */
+public interface QueryEngine {
+
+	/**
+	 * Executes any sparql query. The type of the result object will vary
+	 * depending on the type of the query.
+	 * 
+	 * @param graphStore
+	 *            where the query originates.
+	 * @param defaultGraph
+	 *            the default ImmutableGraph against which to execute the query if no
+	 *            FROM clause is present
+	 * @param query
+	 *            string to be executed.
+	 * @return the resulting ResultSet, ImmutableGraph or Boolean value
+	 */
+	public Object execute(GraphStore graphStore, Graph defaultGraph, String query);
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/QueryParser.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/QueryParser.java b/sparql/src/main/java/org/apache/clerezza/sparql/QueryParser.java
new file mode 100644
index 0000000..259d282
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/QueryParser.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql;
+
+import org.apache.clerezza.sparql.query.Query;
+import org.osgi.service.component.annotations.Component;
+
+import java.io.StringReader;
+
+/**
+ * This class implements an OSGi service to provide a method to parse a
+ * SPARQL query and generate a {@link Query} object.
+ *
+ * @author hasan
+ */
+
+@Component(service = QueryParser.class)
+public class QueryParser {
+
+    private static volatile QueryParser instance;
+    public QueryParser() {
+        QueryParser.instance = this;
+    }
+
+    /**
+     * Returns an instance of this class.
+     * This method is provided due to backward compatibility.
+     */
+    public static QueryParser getInstance() {
+        if (instance == null) {
+            synchronized (QueryParser.class) {
+                if (instance == null) {
+                    new QueryParser();
+                }
+            }
+        }
+        return instance;
+    }
+
+    /**
+     * Parses a SPARQL query string into a {@link Query} object.
+     *
+     * @param queryString
+     *        SPARQL query string
+     * @return
+     *        {@link Query} object corresponding to the specified query string
+     *
+     * @throws org.apache.clerezza.sparql.ParseException
+     */
+    public Query parse(final String queryString) throws ParseException {
+        JavaCCGeneratedQueryParser parser = new JavaCCGeneratedQueryParser(
+                new StringReader(queryString));
+        return parser.parse();
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/ResultSet.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/ResultSet.java b/sparql/src/main/java/org/apache/clerezza/sparql/ResultSet.java
new file mode 100644
index 0000000..bf5ae89
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/ResultSet.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql;
+
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * The reult of a sparql SELECT-query. This corresponds to a Solution Sequence
+ * as per section 12.1.6 of http://www.w3.org/TR/rdf-sparql-query/.
+ *
+ * Note that the scope of blank nodes is the reult set and not the
+ * Graph from where they originate.
+ *
+ * @author rbn
+ */
+public interface ResultSet extends Iterator<SolutionMapping> {
+
+    /** Iterate over the variable names (strings) in this QuerySolution.
+     * @return Iterator of strings
+     */ 
+    public List<String> getResultVars() ;
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/SolutionMapping.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/SolutionMapping.java b/sparql/src/main/java/org/apache/clerezza/sparql/SolutionMapping.java
new file mode 100644
index 0000000..0831d0b
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/SolutionMapping.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql;
+
+import org.apache.clerezza.api.RDFTerm;
+import org.apache.clerezza.sparql.query.Variable;
+
+import java.util.Map;
+
+/**
+ * A set of mapping from variable names to solutions.
+ *
+ * a variable name has the form: ( PN_CHARS_U | [0-9] ) ( PN_CHARS_U | [0-9]
+ * | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040] )*
+ * where PN_CHARS_U =      [A-Z] | [a-z] | [#x00C0-#x00D6] | [#x00D8-#x00F6]
+ * | [#x00F8-#x02FF] | [#x0370-#x037D] | [#x037F-#x1FFF] | [#x200C-#x200D]
+ * | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF]
+ * | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] | '_'
+ *
+ *
+ * @author rbn
+ */
+public interface SolutionMapping extends Map<Variable, RDFTerm> {
+
+    /**
+     * Should be the equivalent to this:
+     * public Resource get(String name) {
+     *    return get(new Variable(name));
+     * }
+     *
+     * @param name
+     * @return
+     */
+    public RDFTerm get(String name);
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/SparqlPreParser.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/SparqlPreParser.java b/sparql/src/main/java/org/apache/clerezza/sparql/SparqlPreParser.java
new file mode 100644
index 0000000..eb34511
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/SparqlPreParser.java
@@ -0,0 +1,160 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql;
+
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.sparql.query.*;
+import org.apache.clerezza.sparql.update.Update;
+
+import java.io.StringReader;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * This class implements an OSGi service to provide a method to obtain referred Graphs in a SPARQL Query or Update.
+ *
+ * @author hasan
+ */
+
+
+public class SparqlPreParser {
+
+    GraphStore graphStore;
+
+    public SparqlPreParser() {
+    }
+
+    public SparqlPreParser(GraphStore graphStore) {
+        this.graphStore = graphStore;
+    }
+
+    /**
+     * This returns the graphs targeted by the queryString. These are the 
+     * triple collections explicitly referred in FROM and FROM NAMED clauses, 
+     * and if the queryString contains no FROM clause the defaultGraph.
+     * 
+     * For queries that are not limited to a specified set of graphs, null is returned.
+     * 
+     * @param queryString
+     * @param defaultGraph
+     * @return 
+     * @throws ParseException 
+     */
+    public Set<IRI> getReferredGraphs(String queryString, IRI defaultGraph) throws ParseException {
+        Set<IRI> referredGraphs;
+        JavaCCGeneratedSparqlPreParser parser = new JavaCCGeneratedSparqlPreParser(new StringReader(queryString));
+        SparqlUnit sparqlUnit;
+        sparqlUnit = parser.parse();
+        boolean referringVariableNamedGraph = false;
+        if (sparqlUnit.isQuery()) {
+            Query q = sparqlUnit.getQuery();
+            DataSet dataSet = q.getDataSet();
+            if (dataSet != null) {
+                referredGraphs = dataSet.getDefaultGraphs();
+                referredGraphs.addAll(dataSet.getNamedGraphs());
+            } else {
+                referredGraphs = new HashSet<IRI>();
+            }
+            GroupGraphPattern queryPattern = q.getQueryPattern();
+            if (queryPattern != null) {
+                Set<GraphPattern> graphPatterns = queryPattern.getGraphPatterns();
+                for (GraphPattern graphPattern : graphPatterns) {
+                }
+            }
+//            referringVariableNamedGraph = q.referringVariableNamedGraph();
+            referringVariableNamedGraph = referringVariableNamedGraph(q);
+        } else {
+            Update u = sparqlUnit.getUpdate();
+            referredGraphs = u.getReferredGraphs(defaultGraph, graphStore);
+        }
+        if (referredGraphs.isEmpty()) {
+            if (referringVariableNamedGraph) {
+                return null;
+            }
+            referredGraphs.add(defaultGraph);
+        }
+        return referredGraphs;
+    }
+
+    private boolean referringVariableNamedGraph(Query query) {
+        GroupGraphPattern queryPattern = query.getQueryPattern();
+        if (queryPattern == null) {
+            return false;
+        }
+        Set<GraphPattern> graphPatterns = queryPattern.getGraphPatterns();
+        return referringVariableNamedGraph(graphPatterns);
+    }
+
+    private boolean referringVariableNamedGraph(Set<GraphPattern> graphPatterns) {
+        boolean referringVariableNamedGraph = false;
+        for (GraphPattern graphPattern : graphPatterns) {
+            if (referringVariableNamedGraph(graphPattern)) {
+                referringVariableNamedGraph = true;
+                break;
+            }
+        }
+        return referringVariableNamedGraph;
+    }
+
+    private boolean referringVariableNamedGraph(GraphPattern graphPattern) {
+        if (graphPattern instanceof GraphGraphPattern) {
+            return ((GraphGraphPattern) graphPattern).getGraph().isVariable();
+        }
+        if (graphPattern instanceof AlternativeGraphPattern) {
+            List<GroupGraphPattern> alternativeGraphPatterns =
+                    ((AlternativeGraphPattern) graphPattern).getAlternativeGraphPatterns();
+            boolean referringVariableNamedGraph = false;
+            for (GroupGraphPattern groupGraphPattern : alternativeGraphPatterns) {
+                if (referringVariableNamedGraph(groupGraphPattern)) {
+                    referringVariableNamedGraph = true;
+                    break;
+                }
+            }
+            return referringVariableNamedGraph;
+        }
+        if (graphPattern instanceof OptionalGraphPattern) {
+            GraphPattern mainGraphPattern = ((OptionalGraphPattern) graphPattern).getMainGraphPattern();
+            if (referringVariableNamedGraph(mainGraphPattern)) {
+                return true;
+            }
+            GroupGraphPattern optionalGraphPattern = ((OptionalGraphPattern) graphPattern).getOptionalGraphPattern();
+            return referringVariableNamedGraph(optionalGraphPattern);
+        }
+        if (graphPattern instanceof MinusGraphPattern) {
+            GraphPattern minuendGraphPattern = ((MinusGraphPattern) graphPattern).getMinuendGraphPattern();
+            if (referringVariableNamedGraph(minuendGraphPattern)) {
+                return true;
+            }
+            GroupGraphPattern subtrahendGraphPattern = ((MinusGraphPattern) graphPattern).getSubtrahendGraphPattern();
+            return referringVariableNamedGraph(subtrahendGraphPattern);
+        }
+        if (graphPattern instanceof GroupGraphPattern) {
+            GroupGraphPattern groupGraphPattern = (GroupGraphPattern) graphPattern;
+            if (groupGraphPattern.isSubSelect()) {
+                Query query = ((GroupGraphPattern) graphPattern).getSubSelect();
+                return referringVariableNamedGraph(query);
+            } else {
+                Set<GraphPattern> graphPatterns = ((GroupGraphPattern) graphPattern).getGraphPatterns();
+                return referringVariableNamedGraph(graphPatterns);
+            }
+        }
+        return false;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/StringQuerySerializer.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/StringQuerySerializer.java b/sparql/src/main/java/org/apache/clerezza/sparql/StringQuerySerializer.java
new file mode 100644
index 0000000..54c548a
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/StringQuerySerializer.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql;
+
+import org.apache.clerezza.sparql.query.*;
+
+/**
+ * This abstract class provides a method to generate a {@link String}
+ * representation of a {@link Query}.
+ *
+ * @author hasan
+ */
+public abstract class StringQuerySerializer {
+
+    /**
+     * Serializes a {@link Query} object to a {@link String}.
+     *
+     * @param query
+     *        the Query object to be serialized
+     * @return
+     *        a String representation of the specified Query object.
+     */
+    public String serialize(Query query) {
+        if (query instanceof SelectQuery) {
+            return serialize((SelectQuery) query);
+        } else if (query instanceof ConstructQuery) {
+            return serialize((ConstructQuery) query);
+        } else if (query instanceof DescribeQuery) {
+            return serialize((DescribeQuery) query);
+        } else {
+            return serialize((AskQuery) query);
+        }
+    }
+
+    /**
+     * Serializes a {@link SelectQuery} object to a {@link String}.
+     *
+     * @param selectQuery
+     *        the SelectQuery object to be serialized
+     * @return
+     *        a String representation of the specified SelectQuery object.
+     */
+    public abstract String serialize(SelectQuery selectQuery);
+
+    /**
+     * Serializes a {@link ConstructQuery} object to a {@link String}.
+     *
+     * @param constructQuery
+     *        the ConstructQuery object to be serialized
+     * @return
+     *        a String representation of the specified ConstructQuery object.
+     */
+    public abstract String serialize(ConstructQuery constructQuery);
+
+    /**
+     * Serializes a {@link DescribeQuery} object to a {@link String}.
+     *
+     * @param describeQuery
+     *        the DescribeQuery object to be serialized
+     * @return
+     *        a String representation of the specified DescribeQuery object.
+     */
+    public abstract String serialize(DescribeQuery describeQuery);
+
+    /**
+     * Serializes an {@link AskQuery} object to a {@link String}.
+     *
+     * @param askQuery
+     *        the AskQuery object to be serialized
+     * @return
+     *        a String representation of the specified AskQuery object.
+     */
+    public abstract String serialize(AskQuery askQuery);
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/AbstractOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/AbstractOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/AbstractOperation.java
new file mode 100644
index 0000000..8e76209
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/AbstractOperation.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * Defines an operation in an {@link Expression}. An operation has an operator
+ * and one or more operands.
+ *
+ * @author hasan
+ */
+public abstract class AbstractOperation implements Expression {
+    private String operator;
+
+    public AbstractOperation(String operator) {
+        this.operator = operator;
+    }
+
+    /**
+     * A string representation of the operator
+     * @return The operator as a string
+     */
+    public String getOperatorString() {
+        return operator;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/AlternativeGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/AlternativeGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/AlternativeGraphPattern.java
new file mode 100644
index 0000000..f42f317
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/AlternativeGraphPattern.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import java.util.List;
+
+/**
+ * Defines alternative ImmutableGraph patterns.
+ * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#alternatives">
+ * SPARQL Query Language: 7 Matching Alternatives</a>
+ *
+ * @author hasan
+ */
+public interface AlternativeGraphPattern extends GraphPattern {
+
+    /**
+     *
+     * @return
+     *        a list of alternative {@link GroupGraphPattern}s
+     */
+    public List<GroupGraphPattern> getAlternativeGraphPatterns();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/AskQuery.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/AskQuery.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/AskQuery.java
new file mode 100644
index 0000000..8bdb9fa
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/AskQuery.java
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * <p>This interface represents a SPARQL ASK query.</p>
+ * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#ask">
+ * SPARQL Query Language: 10.3 ASK</a>
+ *
+ * @author hasan
+ */
+public interface AskQuery extends Query {
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/BasicGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/BasicGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/BasicGraphPattern.java
new file mode 100644
index 0000000..7f0bf4c
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/BasicGraphPattern.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import java.util.Set;
+
+/**
+ * Defines a basic ImmutableGraph pattern.
+ * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#BasicGraphPatterns">
+ * SPARQL Query Language: 5.1 Basic ImmutableGraph Patterns</a>
+ *
+ * @author hasan
+ */
+public interface BasicGraphPattern extends GraphPattern {
+
+    /**
+     *
+     * @return a set of all triple patterns to match.
+     */
+    public Set<TriplePattern> getTriplePatterns();
+
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/BinaryOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/BinaryOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/BinaryOperation.java
new file mode 100644
index 0000000..2c06cdc
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/BinaryOperation.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * Defines an operation with two operands: a left hand side and a right hand side
+ * operand.
+ *
+ * @author hasan
+ */
+public class BinaryOperation extends AbstractOperation {
+
+    private Expression lhsOperand;
+    private Expression rhsOperand;
+
+    public BinaryOperation(String operator,
+            Expression lhsOperand, Expression rhsOperand) {
+        super(operator);
+        this.lhsOperand = lhsOperand;
+        this.rhsOperand = rhsOperand;
+    }
+
+    public Expression getLhsOperand() {
+        return lhsOperand;
+    }
+
+    public Expression getRhsOperand() {
+        return rhsOperand;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/BinaryPropertyPathOperation.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/BinaryPropertyPathOperation.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/BinaryPropertyPathOperation.java
new file mode 100644
index 0000000..d3847fb
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/BinaryPropertyPathOperation.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ *
+ * @author hasan
+ */
+public class BinaryPropertyPathOperation implements PropertyPathExpression {
+    private String operator;
+    private PropertyPathExpression lhsOperand;
+    private PropertyPathExpression rhsOperand;
+
+    public BinaryPropertyPathOperation(String operator, PropertyPathExpression lhsOperand, PropertyPathExpression rhsOperand) {
+        this.operator = operator;
+        this.lhsOperand = lhsOperand;
+        this.rhsOperand = rhsOperand;
+    }
+
+    public PropertyPathExpression getLhsOperand() {
+        return lhsOperand;
+    }
+
+    public PropertyPathExpression getRhsOperand() {
+        return rhsOperand;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/BuiltInCall.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/BuiltInCall.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/BuiltInCall.java
new file mode 100644
index 0000000..81b9905
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/BuiltInCall.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import java.util.List;
+
+/**
+ * Defines a built-in call which is one form of {@link Expression}.
+ * A built-in call has a name of type String and a list of arguments,
+ * where each argument is an {@link Expression}.
+ *
+ * @author hasan
+ */
+public class BuiltInCall implements Expression {
+
+    protected String name;
+    private final List<Expression> arguments;
+
+    public BuiltInCall(String name, List<Expression> arguments) {
+        this.name = name;
+        this.arguments = arguments;
+    }
+
+    public String getName() {
+        return name;
+    };
+
+    public List<Expression> getArguements() {
+        return arguments;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/ConstructQuery.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/ConstructQuery.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/ConstructQuery.java
new file mode 100644
index 0000000..53bb293
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/ConstructQuery.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import java.util.Set;
+
+/**
+ * <p>This interface represents a SPARQL CONSTRUCT query.</p>
+ *
+ * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#construct">
+ * SPARQL Query Language: 10.2 CONSTRUCT</a>
+ *
+ * @author hasan
+ */
+public interface ConstructQuery extends QueryWithSolutionModifier {
+
+    /**
+     * <p>Gets the template for constructing triples in a CONSTRUCT query.</p>
+     * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#construct">
+     * SPARQL Query Language: 10.2 CONSTRUCT</a>
+     * @return a template as a set of triple patterns for constructing
+     *         new triples.
+     */
+    public Set<TriplePattern> getConstructTemplate();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/DataSet.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/DataSet.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/DataSet.java
new file mode 100644
index 0000000..c1c9ae3
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/DataSet.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import org.apache.clerezza.api.IRI;
+
+import java.util.Set;
+
+/**
+ * This interface definition is not yet stable and may change in future.
+ * 
+ * @author hasan
+ */
+public interface DataSet {
+
+    /**
+     * 
+     * @return
+     *        an empty set if no default ImmutableGraph is specified,
+     *        otherwise a set of their UriRefs
+     */
+    public Set<IRI> getDefaultGraphs();
+
+    /**
+     *
+     * @return
+     *        an empty set if no named ImmutableGraph is specified,
+     *        otherwise a set of their UriRefs
+     */
+    public Set<IRI> getNamedGraphs();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/DescribeQuery.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/DescribeQuery.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/DescribeQuery.java
new file mode 100644
index 0000000..313c2a1
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/DescribeQuery.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import java.util.List;
+
+/**
+ * <p>This interface represents a SPARQL SELECT query.</p>
+ *
+ * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#describe">
+ * SPARQL Query Language: 10.4 DESCRIBE (Informative)</a>
+ *
+ * @author hasan
+ */
+public interface DescribeQuery extends QueryWithSolutionModifier {
+
+    /**
+     * <p>Tests if all variables in the query should be described.</p>
+     * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#describe">
+     * SPARQL Query Language: 10.4 DESCRIBE (Informative)</a>
+     * @return <code>true</code> if the query should return all variables.
+     */
+    public boolean isDescribeAll();
+
+    /**
+     * <p>Gets the list of {@link ResourceOrVariable}s to describe.
+     * If {@link #isDescribeAll()} returns <code>true</code> then
+     * this list contains all the variables from the query.</p>
+     * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#describe">
+     * SPARQL Query Language: 10.4 DESCRIBE (Informative)</a>
+     * @return A list of {@link ResourceOrVariable}s to describe.
+     */
+    public List<ResourceOrVariable> getResourcesToDescribe();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/Expression.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/Expression.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/Expression.java
new file mode 100644
index 0000000..0bc9422
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/Expression.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import java.io.Serializable;
+
+/**
+ * This interface models logical, relational, and numeric expression.
+ * This includes terms and factors in mathematical formulas which can contain
+ * variables, literals, and function calls.
+ * In a SPARQL query, expressions can occur in an ORDER BY clause or
+ * a FILTER constraint.
+ *
+ * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#modOrderBy">
+ * SPARQL Query Language: 9.1 ORDER BY</a>
+ *
+ * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#termConstraint">
+ * SPARQL Query Language: 3 RDF Term Constraints (Informative)</a>
+ * 
+ * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#evaluation">
+ * SPARQL Query Language: 11.2 Filter Evaluation</a>
+ *
+ * @author hasan
+ */
+public interface Expression extends Serializable {
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/FunctionCall.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/FunctionCall.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/FunctionCall.java
new file mode 100644
index 0000000..8190dec
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/FunctionCall.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import org.apache.clerezza.api.IRI;
+
+import java.util.List;
+
+/**
+ * Defines a function call which is one form of {@link Expression}.
+ * A function call has a name of type {@link IRI} and a list of arguments,
+ * where each argument is an {@link Expression}.
+ *
+ * @author hasan
+ */
+public class FunctionCall implements Expression {
+
+    private final IRI name;
+    private final List<Expression> arguments;
+
+    public FunctionCall(IRI name, List<Expression> arguments) {
+        this.name = name;
+        this.arguments = arguments;
+    }
+
+    public IRI getName() {
+        return name;
+    };
+
+    public List<Expression> getArguements() {
+        return arguments;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/GraphGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/GraphGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/GraphGraphPattern.java
new file mode 100644
index 0000000..86f1a97
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/GraphGraphPattern.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * Defines a ImmutableGraph ImmutableGraph pattern.
+ * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#queryDataset">
+ * SPARQL Query Language: 8.3 Querying the Dataset</a>
+ *
+ * @author hasan
+ */
+public interface GraphGraphPattern extends GraphPattern {
+
+    /**
+     *
+     * @return a {@link UriRefOrVariable} which specifies the ImmutableGraph
+     *        against which the pattern should match.
+     */
+    public UriRefOrVariable getGraph();
+
+    /**
+     * 
+     * @return the pattern to match.
+     */
+    public GroupGraphPattern getGroupGraphPattern();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/GraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/GraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/GraphPattern.java
new file mode 100644
index 0000000..048bb84
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/GraphPattern.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * This is the generic interface for all types of ImmutableGraph patterns:
+ * {@link BasicGraphPattern}, {@link PathSupportedBasicGraphPattern}, {@link GroupGraphPattern},
+ * {@link GraphGraphPattern}, {@link AlternativeGraphPattern}, and
+ * {@link OptionalGraphPattern}
+ *
+ * @author hasan
+ */
+public interface GraphPattern {
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/GroupGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/GroupGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/GroupGraphPattern.java
new file mode 100644
index 0000000..4025e03
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/GroupGraphPattern.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import org.apache.clerezza.api.IRI;
+
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Defines a group ImmutableGraph pattern.
+ * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#GroupPatterns">
+ * SPARQL Query Language: 5.2 Group ImmutableGraph Patterns</a>
+ *
+ * @author hasan
+ */
+public interface GroupGraphPattern extends GraphPattern {
+
+	/**
+	 *
+	 * @return 
+     *      true if it wraps a {@link SelectQuery}, false otherwise.
+	 */
+	public boolean isSubSelect();
+
+	/**
+	 *
+	 * @return 
+     *      the wrapped subselect if it wraps a {@link SelectQuery}, null otherwise.
+	 */
+	public SelectQuery getSubSelect();
+
+	/**
+	 *
+	 * @return
+     *      null if it wraps a {@link SelectQuery}, otherwise
+     *      a set of all patterns, ANDed together.
+	 */
+	public Set<GraphPattern> getGraphPatterns();
+
+    /**
+     * 
+     * @return
+     *      all graphs referred in this ImmutableGraph pattern.
+     */
+    public Set<IRI> getReferredGraphs();
+
+    /**
+	 * @return 
+     *      null if it wraps a {@link SelectQuery}, otherwise
+	 *		a list of filter expressions for all patterns in the group if any.
+	 */
+	public List<Expression> getFilter();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/InlineData.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/InlineData.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/InlineData.java
new file mode 100644
index 0000000..6bd4377
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/InlineData.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import org.apache.clerezza.api.RDFTerm;
+
+import java.util.List;
+
+/**
+ *
+ * @author hasan
+ */
+public interface InlineData extends GraphPattern {
+    public List<Variable> getVariables();
+    public List<List<RDFTerm>> getValues();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/LiteralExpression.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/LiteralExpression.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/LiteralExpression.java
new file mode 100644
index 0000000..9532908
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/LiteralExpression.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import org.apache.clerezza.api.Literal;
+
+/**
+ * Wraps a {@link Literal} in an {@link Expression}.
+ *
+ * @author hasan
+ */
+public class LiteralExpression implements Expression {
+
+    private final Literal literal;
+
+    public LiteralExpression(Literal literal) {
+        this.literal = literal;
+    }
+
+    public Literal getLiteral() {
+        return literal;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/MinusGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/MinusGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/MinusGraphPattern.java
new file mode 100644
index 0000000..5696fab
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/MinusGraphPattern.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * 
+ * @author hasan
+ */
+public interface MinusGraphPattern extends GraphPattern {
+
+    /**
+     *
+     * @return
+     *        the minuend ImmutableGraph pattern to match
+     */
+    public GraphPattern getMinuendGraphPattern();
+
+    /**
+     *
+     * @return
+     *        the subtrahend ImmutableGraph pattern to match
+     */
+    public GroupGraphPattern getSubtrahendGraphPattern();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/OptionalGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/OptionalGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/OptionalGraphPattern.java
new file mode 100644
index 0000000..ae09193
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/OptionalGraphPattern.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * Specifying an optional ImmutableGraph pattern implies the existence of a main ImmutableGraph
+ * pattern.
+ * The main ImmutableGraph pattern is an empty group pattern if it is not specified.
+ * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#optionals">
+ * SPARQL Query Language: 6 Including Optional Values</a>
+ * 
+ * @author hasan
+ */
+public interface OptionalGraphPattern extends GraphPattern {
+
+    /**
+     *
+     * @return
+     *        the main ImmutableGraph pattern to match
+     */
+    public GraphPattern getMainGraphPattern();
+
+    /**
+     *
+     * @return
+     *        the optional ImmutableGraph pattern to match
+     */
+    public GroupGraphPattern getOptionalGraphPattern();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/OrderCondition.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/OrderCondition.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/OrderCondition.java
new file mode 100644
index 0000000..5c5ace5
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/OrderCondition.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * Defines an order condition in an ORDER BY clause.
+ *
+ * @see <a href="http://www.w3.org/TR/rdf-sparql-query/#modOrderBy">
+ * SPARQL Query Language: 9.1 ORDER BY</a>
+ *
+ * @author hasan
+ */
+public interface OrderCondition {
+
+    public Expression getExpression();
+
+    /**
+     * @return <code>true</code> if ascending, <code>false</code> if descending
+     */
+    public boolean isAscending();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/PathSupportedBasicGraphPattern.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/PathSupportedBasicGraphPattern.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/PathSupportedBasicGraphPattern.java
new file mode 100644
index 0000000..535bdd5
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/PathSupportedBasicGraphPattern.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import java.util.Set;
+
+/**
+ * Defines a basic ImmutableGraph pattern that supports property path expressions.
+ * A {@link PathSupportedBasicGraphPattern} is a set of {@link PropertyPathPattern}s.
+ * A {@link PropertyPathPattern} is a generalization of a {@link TriplePattern} to include
+ * a {@link PropertyPathExpression} in the property position.
+ * Therefore, a {@link PathSupportedBasicGraphPattern} can be seen as a generalization of a {@link BasicGraphPattern}
+ * @see <a href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#sparqlBasicGraphPatterns">
+ * SPARQL 1.1 Query Language: 18.1.6 Basic ImmutableGraph Patterns</a>
+ * and <a href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#sparqlPropertyPaths">
+ * SPARQL 1.1 Query Language: 18.1.7 Property Path Patterns</a>
+ *
+ * @author hasan
+ */
+public interface PathSupportedBasicGraphPattern extends GraphPattern {
+
+    /**
+     *
+     * @return a set of all property path patterns to match.
+     */
+    public Set<PropertyPathPattern> getPropertyPathPatterns();
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/PatternExistenceCondition.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/PatternExistenceCondition.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/PatternExistenceCondition.java
new file mode 100644
index 0000000..fb0aa2b
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/PatternExistenceCondition.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * This expression is intended to be used as a filter expression to test whether a ImmutableGraph pattern matches 
+ * the dataset or not, given the values of variables in the group ImmutableGraph pattern in which the filter occurs.
+ * It does not generate any additional bindings.
+ * 
+ * @see <a href="http://www.w3.org/TR/sparql11-query/#neg-pattern">SPARQL 1.1 Query Language: 8.1 Filtering Using ImmutableGraph Patterns</a>
+ * 
+ * @author hasan
+ */
+public class PatternExistenceCondition extends BuiltInCall {
+    private boolean negated = false;
+    private GroupGraphPattern pattern;
+
+    public PatternExistenceCondition() {
+        super("EXISTS", new ArrayList<Expression>());
+    }
+
+    public PatternExistenceCondition(String name, List<Expression> arguments) {
+        super(name, new ArrayList<Expression>());
+        if (!(name.equalsIgnoreCase("EXISTS") || name.equalsIgnoreCase("NOT EXISTS"))) {
+            throw new RuntimeException("Unsupported name: " + name);
+        } else {
+            this.negated = name.equalsIgnoreCase("NOT EXISTS");
+        }
+    }
+
+    public boolean isExistenceTest() {
+        return !negated;
+    }
+
+    public GroupGraphPattern getPattern() {
+        return pattern;
+    }
+
+    public void setExistenceTest(boolean existenceTest) {
+        this.negated = !existenceTest;
+        this.name = existenceTest ? "EXISTS" : "NOT EXISTS";
+    }
+
+    public void setPattern(GroupGraphPattern pattern) {
+        this.pattern = pattern;
+    }
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/PredicatePath.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/PredicatePath.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/PredicatePath.java
new file mode 100644
index 0000000..a63e227
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/PredicatePath.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+import org.apache.clerezza.api.IRI;
+
+/**
+ *
+ * @author hasan
+ */
+public class PredicatePath implements PropertyPathExpression {
+    private IRI predicatePath;
+
+    public PredicatePath(IRI predicatePath) {
+        this.predicatePath = predicatePath;
+    }
+
+    public IRI getPredicatePath() {
+        return predicatePath;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertyPathExpression.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertyPathExpression.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertyPathExpression.java
new file mode 100644
index 0000000..905aa71
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertyPathExpression.java
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * This interface models property path expressions.
+ * @see <a href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#propertypaths">
+ * SPARQL 1.1 Query Language: 9 Property Paths</a>
+ * 
+ * @author hasan
+ */
+public interface PropertyPathExpression {
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertyPathExpressionOrVariable.java
----------------------------------------------------------------------
diff --git a/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertyPathExpressionOrVariable.java b/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertyPathExpressionOrVariable.java
new file mode 100644
index 0000000..552f8a4
--- /dev/null
+++ b/sparql/src/main/java/org/apache/clerezza/sparql/query/PropertyPathExpressionOrVariable.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql.query;
+
+/**
+ * Wraps either a {@link PropertyPathExpression} or a {@link Variable}
+ *
+ * @author hasan
+ */
+public class PropertyPathExpressionOrVariable {
+
+    private final PropertyPathExpression propertyPathExpression;
+    private final Variable variable;
+
+    public PropertyPathExpressionOrVariable(PropertyPathExpression propertyPathExpression) {
+        if (propertyPathExpression == null) {
+            throw new IllegalArgumentException("Invalid propertyPathExpression: null");
+        }
+        this.propertyPathExpression = propertyPathExpression;
+        variable = null;
+    }
+
+    public PropertyPathExpressionOrVariable(Variable variable) {
+        if (variable == null) {
+            throw new IllegalArgumentException("Invalid variable: null");
+        }
+        this.variable = variable;
+        propertyPathExpression = null;
+    }
+
+    /**
+     *
+     * @return
+     *        true if it is a {@link Variable}, false if it is a {@link PropertyPathExpression}
+     */
+    public boolean isVariable() {
+        return propertyPathExpression == null;
+    }
+
+    /**
+     * 
+     * @return
+     *        the wrapped PropertyPathExpression if it is a PropertyPathExpression, null otherwise
+     */
+    public PropertyPathExpression getPropertyPathExpression() {
+        return propertyPathExpression;
+    }
+    
+    /**
+     * 
+     * @return
+     *        the wrapped Variable if it is a Variable, null otherwise
+     */
+    public Variable getVariable() {
+        return variable;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof PropertyPathExpressionOrVariable)) {
+            return false;
+        }
+        final PropertyPathExpressionOrVariable other = (PropertyPathExpressionOrVariable) obj;
+        if (this.isVariable() != other.isVariable()) {
+            return false;
+        }
+        if (this.isVariable()) {
+            if (!this.getVariable().equals(other.getVariable())) {
+                return false;
+            }
+        } else {
+            if (!this.getPropertyPathExpression().equals(other.getPropertyPathExpression())) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        return (isVariable()
+                ? 13 * getVariable().hashCode() + 17
+                : 13 * getPropertyPathExpression().hashCode() + 17);
+    }
+}


[2/6] clerezza git commit: CLEREZZA-1026: Introduce GraphStore to remove dependency to TcProvider and refactor sparql

Posted by ha...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/javacc/org/apache/clerezza/sparql/JavaCCGeneratedSparqlPreParser.jj
----------------------------------------------------------------------
diff --git a/sparql/src/main/javacc/org/apache/clerezza/sparql/JavaCCGeneratedSparqlPreParser.jj b/sparql/src/main/javacc/org/apache/clerezza/sparql/JavaCCGeneratedSparqlPreParser.jj
new file mode 100644
index 0000000..8c145ed
--- /dev/null
+++ b/sparql/src/main/javacc/org/apache/clerezza/sparql/JavaCCGeneratedSparqlPreParser.jj
@@ -0,0 +1,2557 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+options
+{
+   STATIC=false;
+   UNICODE_INPUT=true;
+   IGNORE_CASE=false;
+   JAVA_UNICODE_ESCAPE=false;
+   DEBUG_PARSER=false;
+   JDK_VERSION="1.6";
+}
+
+PARSER_BEGIN(JavaCCGeneratedSparqlPreParser)
+
+package org.apache.clerezza.sparql;
+
+import org.apache.clerezza.api.BlankNode;
+import org.apache.clerezza.api.impl.literal.LiteralFactory;
+import org.apache.clerezza.api.impl.literal.PlainLiteralImpl;
+import org.apache.clerezza.api.impl.literal.TypedLiteralImpl;
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.api.Language;
+import org.apache.clerezza.api.Literal;
+import org.apache.clerezza.api.RDFTerm;
+import org.apache.clerezza.sparql.query.AlternativeGraphPattern;
+import org.apache.clerezza.sparql.query.BinaryOperation;
+import org.apache.clerezza.sparql.query.BinaryPropertyPathOperation;
+import org.apache.clerezza.sparql.query.BuiltInCall;
+import org.apache.clerezza.sparql.query.Expression;
+import org.apache.clerezza.sparql.query.FunctionCall;
+import org.apache.clerezza.sparql.query.GroupGraphPattern;
+import org.apache.clerezza.sparql.query.InlineData;
+import org.apache.clerezza.sparql.query.LiteralExpression;
+import org.apache.clerezza.sparql.query.PatternExistenceCondition;
+import org.apache.clerezza.sparql.query.PredicatePath;
+import org.apache.clerezza.sparql.query.PropertyPathExpressionOrVariable;
+import org.apache.clerezza.sparql.query.PropertyPathExpression;
+import org.apache.clerezza.sparql.query.PropertyPathPattern;
+import org.apache.clerezza.sparql.query.PropertySet;
+import org.apache.clerezza.sparql.query.Query;
+import org.apache.clerezza.sparql.query.ResourceOrVariable;
+import org.apache.clerezza.sparql.query.RhsListBinaryOperation;
+import org.apache.clerezza.sparql.query.SelectQuery;
+import org.apache.clerezza.sparql.query.SparqlUnit;
+import org.apache.clerezza.sparql.query.TriplePattern;
+import org.apache.clerezza.sparql.query.UnaryOperation;
+import org.apache.clerezza.sparql.query.UnaryPropertyPathOperation;
+import org.apache.clerezza.sparql.query.UriRefExpression;
+import org.apache.clerezza.sparql.query.UriRefOrVariable;
+import org.apache.clerezza.sparql.query.Variable;
+import org.apache.clerezza.sparql.query.impl.SimpleAlternativeGraphPattern;
+import org.apache.clerezza.sparql.query.impl.SimpleAskQuery;
+import org.apache.clerezza.sparql.query.impl.SimpleConstructQuery;
+import org.apache.clerezza.sparql.query.impl.SimpleDataSet;
+import org.apache.clerezza.sparql.query.impl.SimpleDescribeQuery;
+import org.apache.clerezza.sparql.query.impl.SimpleGraphGraphPattern;
+import org.apache.clerezza.sparql.query.impl.SimpleGroupGraphPattern;
+import org.apache.clerezza.sparql.query.impl.SimpleInlineData;
+import org.apache.clerezza.sparql.query.impl.SimpleOrderCondition;
+import org.apache.clerezza.sparql.query.impl.SimplePropertyPathPattern;
+import org.apache.clerezza.sparql.query.impl.SimpleQuery;
+import org.apache.clerezza.sparql.query.impl.SimpleQueryWithSolutionModifier;
+import org.apache.clerezza.sparql.query.impl.SimpleSelectQuery;
+import org.apache.clerezza.sparql.query.impl.SimpleServiceGraphPattern;
+import org.apache.clerezza.sparql.query.impl.SimpleSparqlUnit;
+import org.apache.clerezza.sparql.query.impl.SimpleTriplePattern;
+import org.apache.clerezza.sparql.update.Update;
+import org.apache.clerezza.sparql.update.UpdateOperation;
+import org.apache.clerezza.sparql.update.UpdateOperation.GraphSpec;
+import org.apache.clerezza.sparql.update.impl.AddOperation;
+import org.apache.clerezza.sparql.update.impl.ClearOperation;
+import org.apache.clerezza.sparql.update.impl.ClearOrDropOperation;
+import org.apache.clerezza.sparql.update.impl.CopyOperation;
+import org.apache.clerezza.sparql.update.impl.CreateOperation;
+import org.apache.clerezza.sparql.update.impl.DeleteDataOperation;
+import org.apache.clerezza.sparql.update.impl.DeleteWhereOperation;
+import org.apache.clerezza.sparql.update.impl.DropOperation;
+import org.apache.clerezza.sparql.update.impl.InsertDataOperation;
+import org.apache.clerezza.sparql.update.impl.LoadOperation;
+import org.apache.clerezza.sparql.update.impl.ModifyOperation;
+import org.apache.clerezza.sparql.update.impl.MoveOperation;
+import org.apache.clerezza.sparql.update.impl.SimpleUpdate;
+import org.apache.clerezza.sparql.update.impl.SimpleUpdateOperation;
+import org.apache.clerezza.sparql.update.impl.UpdateOperationWithQuads;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.Set;
+
+/**
+ *
+ * Credits: Fedora Commons, Inc.
+ *            - for initial grammar of this file (available in mulgara project).
+ * Modified by: Hasan <ha...@trialox.org>
+ */
+class JavaCCGeneratedSparqlPreParser {
+
+    private static final IRI RDF_TYPE =
+        new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
+    private static final IRI RDF_FIRST =
+        new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#first");
+    private static final IRI RDF_REST =
+        new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#rest");
+    private static final IRI RDF_NIL =
+        new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#nil");
+
+    /** A RegEx pattern for separating out a namespace from a prefixed name. */
+    private static final Pattern pfxNamePattern = Pattern.compile("([^:]*):(.*)");
+
+    private String base;
+    private Map<String, String> prefixes;
+    private Map<String, ResourceOrVariable> bNodes;
+    private int count;
+
+    private class GraphRefAllSpec {
+        GraphSpec graphSpec;
+        IRI graph;
+        public void setGraphSpec(GraphSpec graphSpec) {
+            this.graphSpec = graphSpec;
+        }
+        public GraphSpec getGraphSpec() {
+            return this.graphSpec;
+        }
+        public void setGraph(IRI graph){
+            this.graph = graph;
+        }
+        public IRI getGraph() {
+            return this.graph;
+        }
+    }
+
+    void initialize() {
+        base = null;
+        prefixes = new HashMap<String, String>();
+        bNodes = new HashMap<String, ResourceOrVariable>();
+        count = 0;
+    }
+
+    SparqlUnit parse() throws ParseException {
+        SparqlUnit sparqlUnit;
+        initialize();
+        sparqlUnit = this.SparqlUnit();
+        return sparqlUnit;
+    }
+
+    Query parseQuery() throws ParseException {
+        Query query;
+        initialize();
+        query = this.QueryUnit();
+        return query;
+    }
+
+    Update parseUpdate() throws ParseException {
+        Update update;
+        initialize();
+        update = this.UpdateUnit();
+        return update;
+    }
+
+    private static String unquote(String s) {
+        return s.substring(1, s.length() - 1);
+    }
+
+    private static String unTripleQuote(String s) {
+        return s.substring(3, s.length() - 3);
+    }
+
+    private Variable createVariable(String name) {
+        name = name.substring(1);
+        Variable v = new Variable(name);
+        return v;
+    }
+
+    private void addPropertyPathPatterns(Set<PropertyPathPattern> propertyPathPatterns,
+            ResourceOrVariable subject,
+            PropertyPathExpressionOrVariable propertyPathExpression,
+            Set<ResourceOrVariable> objects) {
+
+        for (ResourceOrVariable object : objects) {
+            propertyPathPatterns.add(
+                new SimplePropertyPathPattern(subject, propertyPathExpression, object));
+        }
+    }
+
+    // nodes contain at least one element
+    private ResourceOrVariable addPropertyPathPatterns(Set<PropertyPathPattern> propertyPathPatterns,
+            List<ResourceOrVariable> nodes) {
+
+        ResourceOrVariable head = null;
+        PropertyPathExpressionOrVariable rdfFirst = new PropertyPathExpressionOrVariable(new PredicatePath(RDF_FIRST));
+        PropertyPathExpressionOrVariable rdfRest = new PropertyPathExpressionOrVariable(new PredicatePath(RDF_REST));
+        UriRefOrVariable rdfNil = new UriRefOrVariable(RDF_NIL);
+
+        ResourceOrVariable prevSubject = null;
+        for (ResourceOrVariable node : nodes) {
+            ResourceOrVariable currentSubject = getNewBNode();
+            if (prevSubject != null) {
+                propertyPathPatterns.add(
+                    new SimplePropertyPathPattern(prevSubject, rdfRest, currentSubject));
+            } else {
+                head = currentSubject;
+            }
+            propertyPathPatterns.add(
+                new SimplePropertyPathPattern(currentSubject, rdfFirst, node));
+            prevSubject = currentSubject;
+        }
+        if (prevSubject != null) {
+            propertyPathPatterns.add(
+                new SimplePropertyPathPattern(prevSubject, rdfRest, rdfNil));
+        }
+        return head;
+    }
+
+    private void addTriplePatterns(Set<TriplePattern> triplePatterns,
+            ResourceOrVariable subject,
+            UriRefOrVariable predicate,
+            Set<ResourceOrVariable> objects) {
+
+        for (ResourceOrVariable object : objects) {
+            triplePatterns.add(
+                new SimpleTriplePattern(subject, predicate, object));
+        }
+    }
+
+    // nodes contain at least one element
+    private ResourceOrVariable addTriplePatterns(
+            Set<TriplePattern> triplePatterns,
+            List<ResourceOrVariable> nodes) {
+
+        ResourceOrVariable head = null;
+        UriRefOrVariable rdfFirst = new UriRefOrVariable(RDF_FIRST);
+        UriRefOrVariable rdfRest = new UriRefOrVariable(RDF_REST);
+        UriRefOrVariable rdfNil = new UriRefOrVariable(RDF_NIL);
+
+        ResourceOrVariable prevSubject = null;
+        for (ResourceOrVariable node : nodes) {
+            ResourceOrVariable currentSubject = getNewBNode();
+            if (prevSubject != null) {
+                triplePatterns.add(
+                    new SimpleTriplePattern(prevSubject, rdfRest, currentSubject));
+            } else {
+                head = currentSubject;
+            }
+            triplePatterns.add(
+                new SimpleTriplePattern(currentSubject, rdfFirst, node));
+            prevSubject = currentSubject;
+        }
+        if (prevSubject != null) {
+            triplePatterns.add(
+                new SimpleTriplePattern(prevSubject, rdfRest, rdfNil));
+        }
+        return head;
+    }
+
+    private ResourceOrVariable getNewBNode() {
+        ResourceOrVariable bNode = new ResourceOrVariable(new BlankNode());
+        bNodes.put("*" + count++, bNode);
+        return bNode;
+    }
+
+    private ResourceOrVariable getBNode(String label) {
+        ResourceOrVariable bNode = bNodes.get(label);
+        if (bNode == null) {
+            bNode = new ResourceOrVariable(new BlankNode());
+            bNodes.put(label, bNode);
+        }
+        return bNode;
+    }
+
+    private IRI createUriRef(String r) throws ParseException {
+        // Create an IRI directly if the string does not start with a prefix
+        Matcher m = pfxNamePattern.matcher(r);
+        if (!m.matches()) {
+            // either a normal IRI, or one with a BASE
+            return isRelative(r) ? new IRI(base + r) : new IRI(r);
+        }
+        // extract the prefix, and attempt to convert to a URI before creating the reference
+        String ns = prefixes.get(m.group(1));
+        return ns == null ? new IRI(r) : new IRI(ns + m.group(2));
+    }
+
+    /**
+     * Tests if the string for a URI is relative or absolute. The test is based on a scheme existing
+     * in the string, which in turn expects a : character to follow it. If there is no colon, then
+     * it is presumed to be relative. Otherwise, if there are special characters preceding the first
+     * colon these are presumed to not be in a scheme.
+     * @param u A string for a URI.
+     * @return <code>true</code> if the URI appears to be relative, <code>false</code> otherwise.
+     */
+    private static boolean isRelative(String u) {
+        int colon = u.indexOf(':');
+        if (colon < 0) {
+            return true;
+        }
+        for (int c = 0; c < colon; c++) {
+            // if there a non-alphanum characters then this is not a scheme, so the URI is relative
+            if (!Character.isLetterOrDigit(u.charAt(c))) {
+                return true;
+            }
+        }
+        // found a (probably) valid scheme, so the URI is absolute
+        return false;
+    }
+}
+PARSER_END(JavaCCGeneratedSparqlPreParser)
+
+SKIP :
+{
+    "\t" | "\n" | "\r" | "\f" | " "
+}
+
+MORE :
+{
+    "#" : IN_COMMENT
+}
+
+<IN_COMMENT>
+SPECIAL_TOKEN :
+{
+  <COMMENT: ( ~[ "\r","\n" ] )* > : DEFAULT
+}
+
+TOKEN [IGNORE_CASE] :
+{
+    < SELECT : "SELECT" >
+|   < BASE : "BASE" >
+|   < ORDER : "ORDER" >
+|   < BY : "BY" >
+|   < FROM : "FROM" >
+|   < GRAPH : "GRAPH" >
+|   < PREFIX : "PREFIX" >
+|   < CONSTRUCT : "CONSTRUCT" >
+|   < LIMIT : "LIMIT" >
+|   < NAMED : "NAMED" >
+|   < OPTIONAL : "OPTIONAL" >
+|   < DESCRIBE : "DESCRIBE" >
+|   < OFFSET : "OFFSET" >
+|   < WHERE : "WHERE" >
+|   < UNION : "UNION" >
+|   < ASK : "ASK" >
+|   < DISTINCT : "DISTINCT" >
+|   < FILTER : "FILTER" >
+|   < REDUCED : "REDUCED" >
+|   < GROUP_CONCAT : "GROUP_CONCAT" >
+|   < BOUND : "bound" >
+|   < TRUE : "TRUE" >
+|   < FALSE : "FALSE" >
+|   < VALUES : "VALUES" >
+|   < UNDEF : "UNDEF" >
+|   < AS : "AS" >
+|   < BIND : "BIND" >
+|   < MINUS : "MINUS" >
+|   < SERVICE : "SERVICE" >
+|   < GROUP : "GROUP" >
+|   < HAVING : "HAVING" >
+|   < LOAD : "LOAD" >
+|   < SILENT : "SILENT" >
+|   < INTO : "INTO" >
+|   < CLEAR : "CLEAR" >
+|   < DROP : "DROP" >
+|   < CREATE : "CREATE" >
+|   < ADD : "ADD" >
+|   < TO : "TO" >
+|   < MOVE : "MOVE" >
+|   < COPY : "COPY" >
+|   < INSERT : "INSERT" >
+|   < DELETE : "DELETE" >
+|   < DATA : "DATA" >
+|   < WITH : "WITH" >
+|   < USING : "USING" >
+|   < DEFAULT_T : "DEFAULT" >
+|   < ALL : "ALL" >
+|   < IN : "IN" >
+|   < NOT : "NOT" >
+|   < EXISTS : "EXISTS" >
+|   < BNODE : "BNODE" >
+|   < RAND : "RAND" >
+|   < CONCAT : "CONCAT" >
+|   < NOW : "NOW" >
+|   < UUID : "UUID" >
+|   < STRUUID : "STRUUID" >
+|   < COALESCE : "COALESCE" >
+|   < SEPARATOR : "SEPARATOR" >
+}
+
+/* SparqlUnit ::= Prologue ( Query | Update ) */
+private SparqlUnit SparqlUnit() : {
+    Query query;
+    Update update; } {
+
+    Prologue()
+    (
+        query=QueryUnit() {
+        return new SimpleSparqlUnit(query); }
+    |
+        update=UpdateUnit() {
+        return new SimpleSparqlUnit(update); }
+    )
+}
+
+/* [1]    QueryUnit ::= Query */
+private Query QueryUnit() : {
+    Query query; } {
+
+    query=Query() {
+    return query; }
+}
+
+/* [2]    Query ::= Prologue ( SelectQuery | ConstructQuery | DescribeQuery | AskQuery ) ValuesClause */
+/* [2]    Query ::= ( SelectQuery | ConstructQuery | DescribeQuery | AskQuery ) ValuesClause */
+private Query Query() : {
+    Query query; } {
+    (
+        query = SelectQuery()
+    |
+        query = ConstructQuery()
+    |
+        query = DescribeQuery()
+    |
+        query = AskQuery()
+    ) {
+    return query;
+    }
+}
+
+/* [3]    UpdateUnit ::= Update */
+private Update UpdateUnit() : {
+    Update update = new SimpleUpdate(); } {
+    Update(update) {
+    return update; }
+}
+
+/* [4]    Prologue ::= ( BaseDecl | PrefixDecl )* */
+private void Prologue() : {} {
+    ( BaseDecl() | PrefixDecl() )*
+}
+
+/* [5]    BaseDecl ::= 'BASE' IRIREF */
+private void BaseDecl() : {
+    Token iriRef; } {
+
+    <BASE> iriRef=<IRIREF> { base = unquote(iriRef.image); }
+}
+
+/* [6]    PrefixDecl ::= 'PREFIX' PNAME_NS IRIREF */
+private void PrefixDecl() : {
+    Token ns, iriRef; } {
+
+    <PREFIX> ns=<PNAME_NS> iriRef=<IRIREF> {
+    String pfx = ns.image;
+    prefixes.put(pfx.substring(0, pfx.length() - 1), unquote(iriRef.image)); }
+}
+
+/* [7]    SelectQuery ::= SelectClause DatasetClause* WhereClause SolutionModifier */
+private Query SelectQuery() : {
+    Query query; } {
+    query = SelectClause()
+    ( DatasetClause(query) )*
+    WhereClause(query)
+    SolutionModifier(query) {
+    return query; }
+}
+
+/* [8]    SubSelect ::= SelectClause WhereClause SolutionModifier ValuesClause */
+private Query SubSelect() : {
+    Query query; } {
+    query = SelectClause()
+    WhereClause(query)
+    SolutionModifier(query)
+    ValuesClause(query) {
+    return query; }
+}
+
+/* [9]    SelectClause ::= 'SELECT' ( 'DISTINCT' | 'REDUCED' )? ( ( Var | ( '(' Expression 'AS' Var ')' ) )+ | '*' ) */
+private Query SelectClause() : {
+    Query query;
+    Variable v; 
+    Expression e; } {
+
+    <SELECT> {
+    query = new SimpleSelectQuery(); }
+    (
+        <DISTINCT> {
+        ((SimpleSelectQuery) query).setDistinct(); }
+    |
+        <REDUCED> {
+        ((SimpleSelectQuery) query).setReduced(); }
+    )?
+    (
+        (
+            v=Var() {
+            ((SimpleSelectQuery) query).addSelection(v); }
+        |
+            (
+                "("
+                e=Expression()
+                <AS>
+                v=Var() {
+                v.setBoundExpression(e); 
+                ((SimpleSelectQuery) query).addSelection(v); }
+                ")"
+            )
+        )+
+    |
+        "*" {
+        ((SimpleSelectQuery) query).setSelectAll(); }
+    ) {
+    return query; }
+}
+
+/* [10]    ConstructQuery ::= 'CONSTRUCT' ( ConstructTemplate DatasetClause* WhereClause SolutionModifier | DatasetClause* 'WHERE' '{' TriplesTemplate? '}' SolutionModifier ) */
+private Query ConstructQuery() : {
+    Query query;
+    Set<TriplePattern> triplePatterns = null;
+    GroupGraphPattern queryPattern; } {
+
+    <CONSTRUCT>
+    (
+        triplePatterns=ConstructTemplate() {
+        query = new SimpleConstructQuery(triplePatterns); }
+        ( DatasetClause(query) )*
+        WhereClause(query)
+    |
+        {
+        query = new SimpleConstructQuery(triplePatterns); }
+        ( DatasetClause(query) )*
+        <WHERE>
+        "{" {
+        queryPattern = new SimpleGroupGraphPattern(); }
+        (
+            triplePatterns=TriplesTemplate()
+        )? {
+        ((SimpleGroupGraphPattern) queryPattern).addTriplePatterns(triplePatterns); }
+        "}" {
+        ((SimpleQuery) query).setQueryPattern(queryPattern); }
+    )
+    SolutionModifier(query) {
+    return query; }
+}
+
+/* [11]    DescribeQuery ::= 'DESCRIBE' ( VarOrIRI+ | '*' ) DatasetClause* WhereClause? SolutionModifier */
+private Query DescribeQuery() : {
+    Query query;
+    UriRefOrVariable node; } {
+
+    <DESCRIBE> {
+    query = new SimpleDescribeQuery(); }
+    (
+        ( node=VarOrIRI() {
+            ((SimpleDescribeQuery) query).addResourceToDescribe(node); } )+
+        |
+        "*" {
+            ((SimpleDescribeQuery) query).setDescribeAll(); }
+    )
+    ( DatasetClause(query) )*
+    ( WhereClause(query) )?
+    SolutionModifier(query) {
+    return query; }
+}
+
+/* [12]    AskQuery ::= 'ASK' DatasetClause* WhereClause SolutionModifier */
+private Query AskQuery() : {
+    Query query; } {
+
+    <ASK> {
+    query = new SimpleAskQuery(); }
+    ( DatasetClause(query) )*
+    WhereClause(query)
+    SolutionModifier(query) {
+    return query; }
+}
+
+/* [13]    DatasetClause ::= 'FROM' ( DefaultGraphClause | NamedGraphClause ) */
+private void DatasetClause(Query query) : {} {
+    <FROM> (DefaultGraphClause(query) | NamedGraphClause(query))
+}
+
+/* [14]    DefaultGraphClause ::= SourceSelector */
+private void DefaultGraphClause(Query query) : {
+    IRI defaultGraph; } {
+
+    defaultGraph=SourceSelector() {
+    ((SimpleQuery) query).addDefaultGraph(defaultGraph); }
+}
+
+/* [15]    NamedGraphClause ::= 'NAMED' SourceSelector */
+private void NamedGraphClause(Query query) : {
+    IRI namedGraph; } {
+
+    <NAMED> namedGraph=SourceSelector() {
+    ((SimpleQuery) query).addNamedGraph(namedGraph); }
+}
+
+/* [16]    SourceSelector ::= iri */
+private IRI SourceSelector() : {
+    IRI graph; } {
+
+    graph=IRI() {
+    return graph; }
+}
+
+/* [17]    WhereClause ::= 'WHERE'? GroupGraphPattern */
+private void WhereClause(Query query) : {
+    GroupGraphPattern queryPattern; } {
+
+    (<WHERE>)?
+    queryPattern=GroupGraphPattern() {
+    ((SimpleQuery) query).setQueryPattern(queryPattern); }
+}
+
+/* [18] SolutionModifier ::= GroupClause? HavingClause? OrderClause? LimitOffsetClauses? */
+private void SolutionModifier(Query query) : {} {
+    ( GroupClause(query) )?
+    ( HavingClause(query) )?
+    ( OrderClause(query) )?
+    ( LimitOffsetClauses(query) )?
+}
+
+/* [19] GroupClause ::= 'GROUP' 'BY' GroupCondition+ */
+private void GroupClause(Query query) : {} {
+    <GROUP> <BY> ( GroupCondition(query) )+
+}
+
+/* [20] GroupCondition ::= BuiltInCall | FunctionCall | '(' Expression ( 'AS' Var )? ')' | Var */
+private void GroupCondition(Query query) : {
+    Expression e;
+    Variable v; } {
+    (
+        e=BuiltInCall()
+    |
+        e=FunctionCall()
+    |
+        (
+            "("
+            e=Expression()
+            (
+                <AS>
+                v=Var() {
+                v.setBoundExpression(e);
+                e = v; }
+            )?
+            ")"
+        )
+    |
+        e=Var()
+    ) {
+    ((SimpleQueryWithSolutionModifier) query).addGroupCondition(e); }
+}
+
+/* [21] HavingClause ::= 'HAVING' HavingCondition+ */
+private void HavingClause(Query query) : {} {
+    <HAVING> ( HavingCondition(query) )+
+}
+
+/* [22] HavingCondition ::= Constraint */
+private void HavingCondition(Query query) : {
+    Expression c; } {
+
+    c=Constraint() {
+    ((SimpleQueryWithSolutionModifier) query).addHavingCondition(c); }
+}
+
+/* [23] OrderClause ::= 'ORDER' 'BY' OrderCondition+ */
+private void OrderClause(Query query) : {} {
+    <ORDER> <BY> ( OrderCondition(query) )+
+}
+
+/* [24] OrderCondition ::= ( ( 'ASC' | 'DESC' ) BrackettedExpression ) | ( Constraint | Var ) */
+private void OrderCondition(Query query) : {
+    boolean asc = true;
+    Expression e; } {
+
+    (
+        ( ( "ASC" | "DESC" { asc = false; } ) e=BrackettedExpression() )
+    |
+        ( e=Constraint() | e=Var() )
+    ) {
+    ((SimpleQueryWithSolutionModifier) query).addOrderCondition(new SimpleOrderCondition(e, asc)); }
+}
+
+/* [25] LimitOffsetClauses ::= LimitClause OffsetClause? | OffsetClause LimitClause? */
+private void LimitOffsetClauses(Query query) : {} {
+    ( LimitClause(query) (OffsetClause(query))? )
+    |
+    ( OffsetClause(query) (LimitClause(query))? )
+}
+
+/* [26] LimitClause ::= 'LIMIT' INTEGER */
+private void LimitClause(Query query) : {
+    Token t; } {
+
+    <LIMIT> t=<INTEGER> {
+    ((SimpleQueryWithSolutionModifier) query).setLimit(Integer.parseInt(t.image)); }
+}
+
+/* [27] OffsetClause ::= 'OFFSET' INTEGER */
+private void OffsetClause(Query query) : {
+    Token t; } {
+
+    <OFFSET> t=<INTEGER> {
+    ((SimpleQueryWithSolutionModifier) query).setOffset(Integer.parseInt(t.image)); }
+}
+
+/* [28] ValuesClause ::= ( 'VALUES' DataBlock )? */
+private void ValuesClause(Query query) : {
+    InlineData data; } {
+    (
+        <VALUES>
+        data=DataBlock() {
+        ((SimpleQuery) query).setInlineData(data); }
+    )?
+}
+
+/* [29]    Update ::= Prologue ( Update1 ( ';' Update )? )? */
+/* [29]    Update ::= ( Update1 ( ';' Prologue Update )? )? */
+private void Update(Update update) : {} {
+    (
+        Update1(update)
+        (
+            ";"
+            Prologue()
+            Update(update)
+        )?
+    )?
+}
+
+/* [30]    Update1 ::= Load | Clear | Drop | Add | Move | Copy | Create | InsertData | DeleteData | DeleteWhere | Modify */
+private void Update1(Update update) : {
+    UpdateOperation updateOperation = null; } {
+
+    (
+        updateOperation = Load()
+    |
+        updateOperation = Clear()
+    |
+        updateOperation = Drop()
+    |
+        updateOperation = Add()
+    |
+        updateOperation = Move()
+    |
+        updateOperation = Copy()
+    |
+        updateOperation = Create()
+    |
+        LOOKAHEAD(2)
+        updateOperation = InsertData()
+    |
+        LOOKAHEAD(2)
+        updateOperation = DeleteData()
+    |
+        LOOKAHEAD(2)
+        updateOperation = DeleteWhere()
+    |
+        updateOperation = Modify()
+    ) {
+    if (updateOperation != null) {
+        update.addOperation(updateOperation);
+    } }
+}
+
+/* [31]    Load ::= 'LOAD' 'SILENT'? iri ( 'INTO' GraphRef )? */
+private UpdateOperation Load() : {
+    IRI uriRef;
+    LoadOperation operation; } {
+    <LOAD> {
+    operation = new LoadOperation(); }
+    (
+        <SILENT> {
+        operation.setSilent(true); }
+    )?
+    uriRef = IRI() {
+    operation.setSource(uriRef); }
+    (
+        <INTO>
+        uriRef = GraphRef() {
+        operation.setDestinationGraph(uriRef); }
+    )? {
+    return operation; }
+}
+
+/* [32]    Clear ::= 'CLEAR' 'SILENT'? GraphRefAll */
+private UpdateOperation Clear() : {
+    ClearOperation operation; } {
+    <CLEAR> {
+    operation = new ClearOperation(); }
+    ProcessParametersOfClearOrDropOperation(operation) {
+    return operation; }
+}
+
+private void ProcessParametersOfClearOrDropOperation(ClearOrDropOperation operation) : {
+    GraphRefAllSpec graphRefAllSpec;
+    GraphSpec graphSpec; } {
+    (
+        <SILENT> {
+        operation.setSilent(true); }
+    )?
+    graphRefAllSpec = GraphRefAll() {
+    graphSpec = graphRefAllSpec.getGraphSpec();
+    operation.setDestinationGraphSpec(graphSpec);
+    if (graphSpec == GraphSpec.GRAPH) {
+        operation.setDestinationGraph(graphRefAllSpec.getGraph());
+    } }
+}
+
+/* [33]    Drop ::= 'DROP' 'SILENT'? GraphRefAll */
+private UpdateOperation Drop() : {
+    DropOperation operation; } {
+    <DROP> {
+    operation = new DropOperation(); }
+    ProcessParametersOfClearOrDropOperation(operation) {
+    return operation; }
+}
+
+/* [34]    Create ::= 'CREATE' 'SILENT'? GraphRef */
+private UpdateOperation Create() : {
+    IRI uriRef;
+    CreateOperation operation; } {
+    <CREATE> {
+    operation = new CreateOperation(); }
+    (
+        <SILENT> {
+        operation.setSilent(true); }
+    )?
+    uriRef = GraphRef() {
+    operation.setDestinationGraph(uriRef);
+    return operation; }
+}
+
+/* [35]    Add ::= 'ADD' 'SILENT'? GraphOrDefault 'TO' GraphOrDefault */
+private UpdateOperation Add() : {
+    AddOperation operation; } {
+    <ADD> {
+    operation = new AddOperation(); }
+    ProcessParametersOfAddMoveOrCopyOperation(operation) {
+    return operation; }
+}
+
+private void ProcessParametersOfAddMoveOrCopyOperation(SimpleUpdateOperation operation) : {
+    GraphRefAllSpec graphRefAllSpec;
+    GraphSpec graphSpec; } {
+    (
+        <SILENT> {
+        operation.setSilent(true); }
+    )?
+    graphRefAllSpec = GraphOrDefault() {
+    graphSpec = graphRefAllSpec.getGraphSpec();
+    if (graphSpec == GraphSpec.GRAPH) {
+        operation.setInputGraph(graphRefAllSpec.getGraph());
+    } else {
+        operation.setInputGraphSpec(graphSpec);
+    } }
+    <TO>
+    graphRefAllSpec = GraphOrDefault() {
+    graphSpec = graphRefAllSpec.getGraphSpec();
+    if (graphSpec == GraphSpec.GRAPH) {
+        operation.setDestinationGraph(graphRefAllSpec.getGraph());
+    } else {
+        operation.setDestinationGraphSpec(graphSpec);
+    } }
+}
+
+/* [36]    Move ::= 'MOVE' 'SILENT'? GraphOrDefault 'TO' GraphOrDefault */
+private UpdateOperation Move() : {
+    MoveOperation operation; } {
+    <MOVE> {
+    operation = new MoveOperation(); }
+    ProcessParametersOfAddMoveOrCopyOperation(operation) {
+    return operation; }
+}
+
+/* [37]    Copy ::= 'COPY' 'SILENT'? GraphOrDefault 'TO' GraphOrDefault */
+private UpdateOperation Copy() : {
+    CopyOperation operation; } {
+    <COPY> {
+    operation = new CopyOperation(); }
+    ProcessParametersOfAddMoveOrCopyOperation(operation) {
+    return operation; }
+}
+
+/* [38]    InsertData ::= 'INSERT DATA' QuadData */
+private UpdateOperation InsertData() : {
+    InsertDataOperation operation; } {
+    <INSERT> <DATA> {
+    operation = new InsertDataOperation(); }
+    QuadData(operation) {
+    return operation; }
+}
+
+/* [39]    DeleteData ::= 'DELETE DATA' QuadData */
+private UpdateOperation DeleteData() : {
+    DeleteDataOperation operation; } {
+    <DELETE> <DATA> {
+    operation = new DeleteDataOperation(); }
+    QuadData(operation) {
+    return operation; }
+}
+
+/* [40]    DeleteWhere ::= 'DELETE WHERE' QuadPattern */
+private UpdateOperation DeleteWhere() : {
+    DeleteWhereOperation operation; } {
+    <DELETE> <WHERE> {
+    operation = new DeleteWhereOperation(); }
+    QuadPattern(operation) {
+    return operation; }
+}
+
+/* [41]    Modify ::= ( 'WITH' iri )? ( DeleteClause InsertClause? | InsertClause ) UsingClause* 'WHERE' GroupGraphPattern */
+private UpdateOperation Modify() : {
+    IRI fallbackGraph = null;
+    UpdateOperationWithQuads deleteOperation = null;
+    UpdateOperationWithQuads insertOperation = null;
+    SimpleDataSet dataSet = new SimpleDataSet();
+    GroupGraphPattern queryPattern;
+    ModifyOperation operation; } {
+    (
+        <WITH>
+        fallbackGraph = IRI()
+    )?
+    (
+        deleteOperation = DeleteClause()
+        (
+            insertOperation = InsertClause()
+        )?
+    |
+        insertOperation = InsertClause()
+    ) {
+    operation = new ModifyOperation();
+    if (fallbackGraph != null) {
+        operation.setFallbackGraph(fallbackGraph);
+    }
+    if (deleteOperation != null) {
+        operation.setDeleteOperation(deleteOperation);
+    }
+    if (insertOperation != null) {
+        operation.setInsertOperation(insertOperation);
+    } }
+    (
+        UsingClause(dataSet)
+    )* {
+    operation.setDataSet(dataSet); }
+
+    <WHERE>
+    queryPattern = GroupGraphPattern() {
+    operation.setQueryPattern(queryPattern);
+    return operation; }
+}
+
+/* [42]    DeleteClause ::= 'DELETE' QuadPattern */
+private UpdateOperationWithQuads DeleteClause() : {
+    UpdateOperationWithQuads operation; } {
+    <DELETE> {
+    operation = new UpdateOperationWithQuads(); }
+    QuadPattern(operation) {
+    return operation; }
+}
+
+/* [43]    InsertClause ::= 'INSERT' QuadPattern */
+private UpdateOperationWithQuads InsertClause() : {
+    UpdateOperationWithQuads operation; } {
+    <INSERT> {
+    operation = new UpdateOperationWithQuads(); }
+    QuadPattern(operation) {
+    return operation; }
+}
+
+/* [44]    UsingClause ::= 'USING' ( iri | 'NAMED' iri ) */
+private void UsingClause(SimpleDataSet dataSet) : {
+    IRI graph; } {
+    <USING>
+    (
+        graph = IRI() {
+        dataSet.addDefaultGraph(graph); }
+    |
+        <NAMED>
+        graph = IRI() {
+        dataSet.addNamedGraph(graph); }
+    )
+}
+
+/* [45]    GraphOrDefault ::= 'DEFAULT_T' | 'GRAPH'? iri */
+private GraphRefAllSpec GraphOrDefault() : {
+    IRI uriRef;
+    GraphRefAllSpec graphRefAllSpec = new GraphRefAllSpec(); } {
+    (
+        <DEFAULT_T> {
+        graphRefAllSpec.setGraphSpec(GraphSpec.DEFAULT); }
+    |
+        (
+            <GRAPH>
+        )?
+        uriRef = IRI() {
+        graphRefAllSpec.setGraph(uriRef);
+        graphRefAllSpec.setGraphSpec(GraphSpec.GRAPH); }
+    ) {
+    return graphRefAllSpec; }
+}
+
+/* [46]    GraphRef ::= 'GRAPH' iri */
+private IRI GraphRef() : {
+    IRI uriRef; } {
+    <GRAPH>
+    uriRef = IRI() {
+    return uriRef; }
+}
+
+/* [47]    GraphRefAll ::= GraphRef | 'DEFAULT_T' | 'NAMED' | 'ALL' */
+private GraphRefAllSpec GraphRefAll() : {
+    IRI uriRef;
+    GraphRefAllSpec graphRefAllSpec = new GraphRefAllSpec(); } {
+    (
+        uriRef = GraphRef() {
+        graphRefAllSpec.setGraph(uriRef);
+        graphRefAllSpec.setGraphSpec(GraphSpec.GRAPH); }
+    |
+        <DEFAULT_T> {
+        graphRefAllSpec.setGraphSpec(GraphSpec.DEFAULT); }
+    |
+        <NAMED> {
+        graphRefAllSpec.setGraphSpec(GraphSpec.NAMED); }
+    |
+        <ALL> {
+        graphRefAllSpec.setGraphSpec(GraphSpec.ALL); }
+    ) {
+    return graphRefAllSpec; }
+}
+
+/* [48]    QuadPattern ::= '{' Quads '}' */
+private void QuadPattern(UpdateOperationWithQuads operation) : {} {
+    "{"
+    Quads(operation)
+    "}"
+}
+
+/* [49]    QuadData ::= '{' Quads '}' */
+private void QuadData(UpdateOperationWithQuads operation) : {} {
+    "{"
+    Quads(operation)
+    "}"
+}
+
+/* [50]    Quads ::= TriplesTemplate? ( QuadsNotTriples '.'? TriplesTemplate? )* */
+private void Quads(UpdateOperationWithQuads operation) : {
+    Set<TriplePattern> triplePatterns; } {
+    (
+        triplePatterns=TriplesTemplate() {
+        operation.addQuad(triplePatterns); }
+    )?
+    (
+        QuadsNotTriples(operation)
+        ( "." )?
+        (
+            triplePatterns=TriplesTemplate() {
+            operation.addQuad(triplePatterns); }
+        )?
+    )*
+}
+
+/* [51]    QuadsNotTriples ::= 'GRAPH' VarOrIRI '{' TriplesTemplate? '}' */
+private void QuadsNotTriples(UpdateOperationWithQuads operation) : {
+    UriRefOrVariable graph;
+    Set<TriplePattern> triplePatterns = null; } {
+
+    <GRAPH>
+    graph=VarOrIRI()
+    "{"
+    (
+        triplePatterns=TriplesTemplate()
+    )?
+    "}" {
+    operation.addQuad(graph, triplePatterns); }
+}
+
+/* [52]    TriplesTemplate ::= TriplesSameSubject ( '.' TriplesTemplate? )? */
+private Set<TriplePattern> TriplesTemplate() : {
+    Set<TriplePattern> triplePatterns, t; } {
+
+    triplePatterns=TriplesSameSubject()
+    (
+        "."
+        (
+            t=TriplesTemplate() {
+            triplePatterns.addAll(t); }
+        )?
+    )? {
+    return triplePatterns; }
+}
+
+/* [53]    GroupGraphPattern ::= '{' ( SubSelect | GroupGraphPatternSub ) '}' */
+private GroupGraphPattern GroupGraphPattern() : {
+    Query query;
+    GroupGraphPattern groupGraphPattern = new SimpleGroupGraphPattern(); } {
+    "{"
+    (
+        query = SubSelect() {
+        ((SimpleGroupGraphPattern) groupGraphPattern).setSubSelect((SelectQuery) query); }
+    |
+        GroupGraphPatternSub(groupGraphPattern)
+    )
+    "}" {
+    return groupGraphPattern; }
+}
+
+/* [54]    GroupGraphPatternSub ::= TriplesBlock? ( GraphPatternNotTriples '.'? TriplesBlock? )* */
+private void GroupGraphPatternSub(GroupGraphPattern groupGraphPattern) : {} {
+    ( TriplesBlock(groupGraphPattern) )?
+    (
+        GraphPatternNotTriples(groupGraphPattern)
+        (".")?
+        ( TriplesBlock(groupGraphPattern) )?
+    )*
+}
+
+/* [55]    TriplesBlock ::= TriplesSameSubjectPath ( '.' TriplesBlock? )? */
+private void TriplesBlock(GroupGraphPattern groupGraphPattern) : {
+    Set<PropertyPathPattern> propertyPathPatterns; } {
+
+    propertyPathPatterns=TriplesSameSubjectPath() {
+    ((SimpleGroupGraphPattern) groupGraphPattern).addPropertyPathPatterns(propertyPathPatterns); }
+    (
+        "." ( TriplesBlock(groupGraphPattern) )?
+    )?
+}
+
+/* [56]    GraphPatternNotTriples ::= GroupOrUnionGraphPattern | OptionalGraphPattern | MinusGraphPattern | GraphGraphPattern | ServiceGraphPattern | Filter | Bind | InlineData */
+private void GraphPatternNotTriples(GroupGraphPattern groupGraphPattern) : {
+    Expression constraint;
+    Variable v; } {
+    (
+        GroupOrUnionGraphPattern(groupGraphPattern)
+    |
+        OptionalGraphPattern(groupGraphPattern)
+    |
+        MinusGraphPattern(groupGraphPattern)
+    |
+        GraphGraphPattern(groupGraphPattern)
+    |
+        ServiceGraphPattern(groupGraphPattern)
+    |
+        constraint=Filter() {
+        ((SimpleGroupGraphPattern) groupGraphPattern).addConstraint(constraint); }
+    |
+        v=Bind() {
+        // We should either store this binding in the respective variable in SelectQuery
+        // or we extend the BasicGraphPattern to store such binding.
+        // If we store the binding in the respective variable in SelectQuery, a serializer
+        // won't be able to determine whether a binding is defined by the BIND keyword or
+        // by an expression in the SELECT clause.
+        // The pre parser needs only to consume tokens, thus may ignore this binding.
+
+        // The use of BIND ends the preceding basic graph pattern, thus ...
+        ((SimpleGroupGraphPattern) groupGraphPattern).endLastBasicGraphPattern(); }
+    |
+        InlineData(groupGraphPattern)
+    )
+}
+
+/* [57]    OptionalGraphPattern ::= 'OPTIONAL' GroupGraphPattern */
+private void OptionalGraphPattern(GroupGraphPattern groupGraphPattern) : {
+    GroupGraphPattern optional; } {
+
+    <OPTIONAL>
+    optional=GroupGraphPattern() {
+    ((SimpleGroupGraphPattern) groupGraphPattern).addOptionalGraphPattern(optional); }
+}
+
+/* [58]    GraphGraphPattern ::= 'GRAPH' VarOrIRI GroupGraphPattern */
+private void GraphGraphPattern(GroupGraphPattern groupGraphPattern) : {
+    UriRefOrVariable graph;
+    GroupGraphPattern g; } {
+
+    <GRAPH>
+    graph=VarOrIRI()
+    g=GroupGraphPattern() {
+    ((SimpleGroupGraphPattern) groupGraphPattern).addGraphPattern(new SimpleGraphGraphPattern(graph, g)); }
+}
+
+/* [59]    ServiceGraphPattern ::= 'SERVICE' 'SILENT'? VarOrIRI GroupGraphPattern */
+private void ServiceGraphPattern(GroupGraphPattern groupGraphPattern) : {
+    UriRefOrVariable service;
+    GroupGraphPattern g;
+    boolean silent = false; } {
+
+    <SERVICE>
+    (
+        <SILENT> {
+        silent = true; }
+    )?
+    service=VarOrIRI()
+    g=GroupGraphPattern() {
+    SimpleServiceGraphPattern simpleServiceGraphPattern;
+    simpleServiceGraphPattern = new SimpleServiceGraphPattern(service, g);
+    ((SimpleGroupGraphPattern) groupGraphPattern).addGraphPattern(simpleServiceGraphPattern);
+    if (silent) {
+        simpleServiceGraphPattern.setSilent(true);
+    } }
+}
+
+/* [60]    Bind ::= 'BIND' '(' Expression 'AS' Var ')' */
+private Variable Bind() : {
+    Variable v;
+    Expression e; } {
+
+    <BIND>
+    "("
+    e=Expression()
+    <AS>
+    v=Var() {
+    v.setBoundExpression(e); }
+    ")" {
+    return v; }
+}
+
+/* [61]    InlineData ::= 'VALUES' DataBlock */
+private void InlineData(GroupGraphPattern groupGraphPattern) : {
+    InlineData data; } {
+
+    <VALUES>
+    data=DataBlock() {
+    ((SimpleGroupGraphPattern) groupGraphPattern).addGraphPattern(data); }
+}
+
+/* [62]    DataBlock ::= InlineDataOneVar | InlineDataFull */
+private InlineData DataBlock() : {
+    InlineData inlineData = new SimpleInlineData(); } {
+
+    (
+        InlineDataOneVar(inlineData)
+    |
+        InlineDataFull(inlineData)
+    ) {
+    return inlineData; }
+}
+
+/* [63]    InlineDataOneVar ::= Var '{' DataBlockValue* '}' */
+private void InlineDataOneVar(InlineData inlineData) : {
+    Variable var;
+    RDFTerm val; } {
+
+    var=Var() {
+    ((SimpleInlineData) inlineData).addVariable(var); }
+    "{"
+    (
+        val=DataBlockValue() {
+        List<RDFTerm> values = new ArrayList<RDFTerm>();
+        values.add(val);
+        ((SimpleInlineData) inlineData).addValues(values); }
+    )*
+    "}"
+}
+
+/* [64]    InlineDataFull ::= ( NIL | '(' Var* ')' ) '{' ( '(' DataBlockValue* ')' | NIL )* '}' */
+private void InlineDataFull(InlineData inlineData) : {
+    Variable var;
+    RDFTerm val; } {
+    (
+        <NIL>
+    |
+        "("
+        (
+            var=Var() {
+            ((SimpleInlineData) inlineData).addVariable(var); }
+        )*
+        
+        ")"
+    )
+    "{"
+    (
+        (
+            "(" {
+            List<RDFTerm> values = new ArrayList<RDFTerm>(); }
+            (
+                val=DataBlockValue() {
+                values.add(val); }
+            )*
+            ")" {
+            ((SimpleInlineData) inlineData).addValues(values); }
+        )
+    |
+        <NIL> {
+        ((SimpleInlineData) inlineData).addValues(new ArrayList<RDFTerm>()); }
+    )*
+    "}"
+}
+
+/* [65]    DataBlockValue ::= iri | RDFLiteral | NumericLiteral | BooleanLiteral | 'UNDEF' */
+private RDFTerm DataBlockValue() : {
+    RDFTerm r = null; } {
+    (r=IRI() | r=RDFLiteral() | r=NumericLiteral() | r=BooleanLiteral() | <UNDEF> ) {
+    return r; }
+}
+
+/* [66]    MinusGraphPattern ::= 'MINUS' GroupGraphPattern */
+private void MinusGraphPattern(GroupGraphPattern groupGraphPattern) : {
+    GroupGraphPattern subtrahend; } {
+
+    <MINUS>
+    subtrahend=GroupGraphPattern() {
+    ((SimpleGroupGraphPattern) groupGraphPattern).addMinusGraphPattern(subtrahend); }
+}
+
+/* [67]    GroupOrUnionGraphPattern ::= GroupGraphPattern ( 'UNION' GroupGraphPattern )* */
+private void GroupOrUnionGraphPattern(GroupGraphPattern groupGraphPattern) : {
+    GroupGraphPattern g;
+    AlternativeGraphPattern unionGraphPattern = null; } {
+
+    g=GroupGraphPattern()
+    (
+        <UNION> {
+        if (unionGraphPattern == null) {
+            unionGraphPattern = new SimpleAlternativeGraphPattern(g);
+        } }
+        g=GroupGraphPattern() {
+        ((SimpleAlternativeGraphPattern) unionGraphPattern).addAlternativeGraphPattern(g); }
+    )* {
+    if (unionGraphPattern != null) {
+        ((SimpleGroupGraphPattern) groupGraphPattern).addGraphPattern(unionGraphPattern);
+    } else {
+        ((SimpleGroupGraphPattern) groupGraphPattern).addGraphPattern(g);
+    } }
+}
+
+/* [68]    Filter ::= 'FILTER' Constraint */
+private Expression Filter() : {
+    Expression c; } {
+
+    <FILTER>
+    c=Constraint() {
+    return c; }
+}
+
+/* [69]    Constraint ::= BrackettedExpression | BuiltInCall | FunctionCall */
+private Expression Constraint() : {
+    Expression c; } {
+
+    ( c=BrackettedExpression() | c=BuiltInCall() | c=FunctionCall() ) {
+    return c; }
+}
+
+/* [70]    FunctionCall ::= iri ArgList */
+private FunctionCall FunctionCall() : {
+    IRI name;
+    List<Expression> arguments; } {
+
+    name=IRI()
+    arguments=ArgList() {
+    return new FunctionCall(name, arguments); }
+}
+
+/* [71]    ArgList ::= NIL | '(' 'DISTINCT'? Expression ( ',' Expression )* ')' */
+private List<Expression> ArgList() : {
+    List<Expression> args = new ArrayList<Expression>();
+    Expression e; } {
+
+    (
+        <NIL>
+    |
+        (
+            "("
+            (
+                <DISTINCT>
+            )?
+            e=Expression() {
+            args.add(e); }
+            (
+                ","
+                e=Expression() {
+                args.add(e); }
+            )*
+            ")"
+        )
+    ) {
+    return args; }
+}
+
+/* [72]    ExpressionList ::= NIL | '(' Expression ( ',' Expression )* ')' */
+private List<Expression> ExpressionList() : {
+    List<Expression> args = new ArrayList<Expression>();
+    Expression e; } {
+
+    (
+        <NIL>
+    |
+        (
+            "("
+            e=Expression() {
+            args.add(e); }
+            (
+                ","
+                e=Expression() {
+                args.add(e); }
+            )*
+            ")"
+        )
+    ) {
+    return args; }
+}
+
+/* [73]    ConstructTemplate ::= '{' ConstructTriples? '}' */
+private Set<TriplePattern> ConstructTemplate() : {
+    Set<TriplePattern> triplePatterns = null; } {
+
+    "{"
+    (
+        triplePatterns=ConstructTriples()
+    )?
+    "}" {
+    return triplePatterns; }
+}
+
+/* [74]    ConstructTriples ::= TriplesSameSubject ( '.' ConstructTriples? )? */
+private Set<TriplePattern> ConstructTriples() : {
+    Set<TriplePattern> triplePatterns, t; } {
+
+    triplePatterns=TriplesSameSubject()
+    (
+        "."
+        (
+            t=ConstructTriples() {
+            triplePatterns.addAll(t); }
+        )?
+    )? {
+    return triplePatterns; }
+}
+
+/* [75]    TriplesSameSubject ::= VarOrTerm PropertyListNotEmpty |  TriplesNode PropertyList */
+private Set<TriplePattern> TriplesSameSubject() : {
+    Set<TriplePattern> triplePatterns = new LinkedHashSet<TriplePattern>();
+    ResourceOrVariable subject; } {
+
+    ( subject=VarOrTerm() PropertyListNotEmpty(subject, triplePatterns) {
+        return triplePatterns; }
+    )
+    |
+    ( subject=TriplesNode(triplePatterns) PropertyList(subject, triplePatterns) {
+        return triplePatterns; }
+    )
+}
+
+/* [76]    PropertyList ::= PropertyListNotEmpty? */
+private void PropertyList(ResourceOrVariable subject, Set<TriplePattern> triplePatterns) : { } {
+    ( PropertyListNotEmpty(subject, triplePatterns) )?
+}
+
+/* [77]    PropertyListNotEmpty ::= Verb ObjectList ( ';' ( Verb ObjectList )? )* */
+private void PropertyListNotEmpty(ResourceOrVariable subject, Set<TriplePattern> triplePatterns) : {
+    UriRefOrVariable predicate;
+    Set<ResourceOrVariable> objects; } {
+    predicate=Verb()
+    objects=ObjectList(triplePatterns) {
+    addTriplePatterns(triplePatterns, subject, predicate, objects); }
+
+    ( ";"
+        ( predicate=Verb() objects=ObjectList(triplePatterns) {
+            addTriplePatterns(triplePatterns, subject, predicate, objects); }
+        )?
+    )*
+}
+
+/* [78]    Verb ::= VarOrIRI | 'a' */
+private UriRefOrVariable Verb() : {
+    UriRefOrVariable predicate; } {
+
+    predicate=VarOrIRI() {
+    return predicate; }
+    | "a" {
+    return new UriRefOrVariable(RDF_TYPE); }
+}
+
+/* [79]    ObjectList ::= Object ( ',' Object )* */
+private Set<ResourceOrVariable> ObjectList(Set<TriplePattern> triplePatterns) : {
+    ResourceOrVariable object; } {
+
+    {
+    Set<ResourceOrVariable> objects = new LinkedHashSet<ResourceOrVariable>();
+    }
+    object=Object(triplePatterns) {
+    objects.add(object); }
+
+    ( ","
+        object=Object(triplePatterns) {
+            objects.add(object); }
+    )* {
+    return objects; }
+}
+
+/* [80]    Object ::= GraphNode */
+private ResourceOrVariable Object(Set<TriplePattern> triplePatterns) : {
+    ResourceOrVariable object; } {
+
+    object=GraphNode(triplePatterns) {
+    return object; }
+}
+
+/* [81]    TriplesSameSubjectPath ::= VarOrTerm PropertyListPathNotEmpty | TriplesNodePath PropertyListPath */
+private Set<PropertyPathPattern> TriplesSameSubjectPath() : {
+    Set<PropertyPathPattern> propertyPathPatterns = new LinkedHashSet<PropertyPathPattern>();
+    ResourceOrVariable subject; } {
+
+    (
+        subject=VarOrTerm()
+        PropertyListPathNotEmpty(subject, propertyPathPatterns) {
+        return propertyPathPatterns; }
+    )
+    |
+    (
+        subject=TriplesNodePath(propertyPathPatterns)
+        PropertyListPath(subject, propertyPathPatterns) {
+        return propertyPathPatterns; }
+    )
+}
+
+/* [82]    PropertyListPath ::= PropertyListPathNotEmpty? */
+private void PropertyListPath(ResourceOrVariable subject, Set<PropertyPathPattern> propertyPathPatterns) : { } {
+    (
+        PropertyListPathNotEmpty(subject, propertyPathPatterns)
+    )?
+}
+
+/* [83]    PropertyListPathNotEmpty ::= ( VerbPath | VerbSimple ) ObjectListPath ( ';' ( ( VerbPath | VerbSimple ) ObjectList )? )* */
+private void PropertyListPathNotEmpty(ResourceOrVariable subject, Set<PropertyPathPattern> propertyPathPatterns) : {
+    PropertyPathExpressionOrVariable propertyPathExpressionOrVariable;
+    PropertyPathExpression propertyPathExpression;
+    Variable v;
+    Set<ResourceOrVariable> objects; } {
+    (
+        propertyPathExpression=VerbPath() {
+        propertyPathExpressionOrVariable = new PropertyPathExpressionOrVariable(propertyPathExpression); }
+    |
+        v=VerbSimple() {
+        propertyPathExpressionOrVariable = new PropertyPathExpressionOrVariable(v); }
+    )
+    objects=ObjectListPath(propertyPathPatterns) {
+    addPropertyPathPatterns(propertyPathPatterns, subject, propertyPathExpressionOrVariable, objects); }
+    (
+        ";"
+        (
+            (
+                propertyPathExpression=VerbPath() {
+                propertyPathExpressionOrVariable = new PropertyPathExpressionOrVariable(propertyPathExpression); }
+
+            |
+                v=VerbSimple() {
+                propertyPathExpressionOrVariable = new PropertyPathExpressionOrVariable(v); }
+            )
+            objects=ObjectListPath(propertyPathPatterns) {
+            addPropertyPathPatterns(propertyPathPatterns, subject, propertyPathExpressionOrVariable, objects); }
+        )?
+    )*
+}
+
+/* [84]    VerbPath ::= Path */
+private PropertyPathExpression VerbPath() : {
+    PropertyPathExpression propertyPathExpression; } {
+    propertyPathExpression=Path() {
+    return propertyPathExpression; }
+}
+
+/* [85]    VerbSimple ::= Var */
+private Variable VerbSimple() : {
+    Variable v; } {
+    v=Var() {
+    return v; }
+}
+
+/* [86]    ObjectListPath ::= ObjectPath ( ',' ObjectPath )* */
+private Set<ResourceOrVariable> ObjectListPath(Set<PropertyPathPattern> propertyPathPatterns) : {
+    ResourceOrVariable object; } {
+    {
+    Set<ResourceOrVariable> objects = new LinkedHashSet<ResourceOrVariable>();
+    }
+    object=ObjectPath(propertyPathPatterns) {
+    objects.add(object); }
+
+    (
+        ","
+        object=ObjectPath(propertyPathPatterns) {
+        objects.add(object); }
+    )* {
+    return objects; }
+}
+
+/* [87]    ObjectPath ::= GraphNodePath */
+private ResourceOrVariable ObjectPath(Set<PropertyPathPattern> propertyPathPatterns) : {
+    ResourceOrVariable object; } {
+
+    object=GraphNodePath(propertyPathPatterns) {
+    return object; }
+}
+
+/* [88]    Path ::= PathAlternative */
+private PropertyPathExpression Path() : {
+    PropertyPathExpression propertyPathExpression; } {
+    propertyPathExpression=PathAlternative() {
+    return propertyPathExpression; }
+}
+
+/* [89]    PathAlternative ::= PathSequence ( '|' PathSequence )* */
+private PropertyPathExpression PathAlternative() : {
+    PropertyPathExpression ppe, pathSequence; } {
+
+    ppe=PathSequence()
+    (
+        "|"
+        pathSequence=PathSequence() {
+        ppe = new BinaryPropertyPathOperation("|", ppe, pathSequence); }
+    )* {
+    return ppe; }
+}
+
+/* [90]    PathSequence ::= PathEltOrInverse ( '/' PathEltOrInverse )* */
+private PropertyPathExpression PathSequence() : {
+    PropertyPathExpression ppe, pathEltOrInverse; } {
+
+    ppe=PathEltOrInverse()
+    (
+        "/"
+        pathEltOrInverse=PathEltOrInverse() {
+        ppe = new BinaryPropertyPathOperation("/", ppe, pathEltOrInverse); }
+    )* {
+    return ppe; }
+}
+
+/* [91]    PathElt ::= PathPrimary PathMod? */
+private PropertyPathExpression PathElt() : {
+    PropertyPathExpression ppe;
+    String pathMode; } {
+
+    ppe=PathPrimary()
+    (
+        pathMode=PathMod() {
+        ppe = new UnaryPropertyPathOperation(pathMode, ppe); }
+    )? {
+    return ppe; }
+}
+
+/* [92]    PathEltOrInverse ::= PathElt | '^' PathElt */
+private PropertyPathExpression PathEltOrInverse() : {
+    PropertyPathExpression ppe; } {
+
+    (
+        ppe=PathElt() {
+        return ppe; }
+    |
+        "^"
+        ppe=PathElt() {
+        return new UnaryPropertyPathOperation("^", ppe); }
+    )
+}
+
+/* [93]    PathMod ::= '?' | '*' | '+' */
+private String PathMod() : {} {
+    (
+        "?" {
+        return "?"; }
+    |
+        "*" {
+        return "*"; }
+    |
+        "+" {
+        return "+"; }
+    )
+}
+
+/* [94]    PathPrimary ::= iri | 'a' | '!' PathNegatedPropertySet | '(' Path ')' */
+private PropertyPathExpression PathPrimary() : {
+    PropertyPathExpression ppe;
+    IRI uriRef; } {
+
+    (
+        uriRef=IRI() {
+        return new PredicatePath(uriRef); }
+    |
+        "a" {
+        return new PredicatePath(RDF_TYPE); }
+    |
+        "!"
+        ppe=PathNegatedPropertySet() {
+        return new UnaryPropertyPathOperation("!", ppe); }
+    |
+        "("
+        ppe=Path() {
+        return ppe; }
+        ")"
+    )
+}
+
+/* [95]    PathNegatedPropertySet ::= PathOneInPropertySet | '(' ( PathOneInPropertySet ( '|' PathOneInPropertySet )* )? ')' */
+private PropertyPathExpression PathNegatedPropertySet() : {
+    PropertyPathExpression pathOneInPropertySet;
+    PropertySet propertySet = new PropertySet(); } {
+
+    (
+        pathOneInPropertySet=PathOneInPropertySet() {
+        return pathOneInPropertySet; }
+    |
+        "("
+        (
+            pathOneInPropertySet=PathOneInPropertySet() {
+            propertySet.addElement(pathOneInPropertySet); }
+            (
+                "|"
+                pathOneInPropertySet=PathOneInPropertySet() {
+                propertySet.addElement(pathOneInPropertySet); }
+            )*
+        )?
+        ")" {
+        return propertySet; }
+    )
+}
+
+/* [96]    PathOneInPropertySet ::= iri | 'a' | '^' ( iri | 'a' ) */
+private PropertyPathExpression PathOneInPropertySet() : {
+    IRI uriRef; } {
+
+    (
+        uriRef=IRI() {
+        return new PredicatePath(uriRef); }
+    |
+        "a" {
+        return new PredicatePath(RDF_TYPE); }
+    |
+        "^"
+        (
+            uriRef=IRI() {
+            return new UnaryPropertyPathOperation("^", new PredicatePath(uriRef)); }
+        |
+            "a" {
+            return new UnaryPropertyPathOperation("^", new PredicatePath(RDF_TYPE)); }
+        )
+    )
+}
+
+/* [97]    Integer ::= INTEGER */
+
+// Fill in the specified set of TriplePattern and returns the subject node
+/* [98]    TriplesNode ::= Collection |  BlankNodePropertyList */
+private ResourceOrVariable TriplesNode(Set<TriplePattern> triplePatterns) : {
+    ResourceOrVariable subject; } {
+    (
+        subject=Collection(triplePatterns)
+    |
+        subject=BlankNodePropertyList(triplePatterns)
+    ) {
+    return subject; }
+}
+
+/* [99]    BlankNodePropertyList ::= '[' PropertyListNotEmpty ']' */
+private ResourceOrVariable BlankNodePropertyList(Set<TriplePattern> triplePatterns) : { } {
+    {
+    ResourceOrVariable subject = getNewBNode();
+    }
+    "["
+    PropertyListNotEmpty(subject, triplePatterns)
+    "]" {
+    return subject; }
+}
+
+/* [100] TriplesNodePath ::= CollectionPath | BlankNodePropertyListPath */
+private ResourceOrVariable TriplesNodePath(Set<PropertyPathPattern> propertyPathPatterns) : {
+    ResourceOrVariable subject; } {
+    (
+        subject=CollectionPath(propertyPathPatterns)
+    |
+        subject=BlankNodePropertyListPath(propertyPathPatterns)
+    ) {
+    return subject; }
+}
+
+
+/* [101] BlankNodePropertyListPath ::= '[' PropertyListPathNotEmpty ']' */
+private ResourceOrVariable BlankNodePropertyListPath(Set<PropertyPathPattern> propertyPathPatterns) : {} {
+    {
+    ResourceOrVariable subject = getNewBNode();
+    }
+    "["
+    PropertyListPathNotEmpty(subject, propertyPathPatterns)
+    "]" {
+    return subject; }
+}
+
+/* [102]    Collection ::= '(' GraphNode+ ')' */
+private ResourceOrVariable Collection(Set<TriplePattern> triplePatterns) : {
+    ResourceOrVariable node;
+    List<ResourceOrVariable> nodes = new ArrayList<ResourceOrVariable>(); } {
+
+    "("
+    (
+        node=GraphNode(triplePatterns) {
+        nodes.add(node); }
+    )+
+    ")" {
+    return addTriplePatterns(triplePatterns, nodes); }
+}
+
+/* [103]    CollectionPath ::= '(' GraphNodePath+ ')' */
+private ResourceOrVariable CollectionPath(Set<PropertyPathPattern> propertyPathPatterns) : {
+    ResourceOrVariable node;
+    List<ResourceOrVariable> nodes = new ArrayList<ResourceOrVariable>(); } {
+
+    "("
+    (
+        node=GraphNodePath(propertyPathPatterns) {
+        nodes.add(node); }
+    )+
+    ")" {
+    return addPropertyPathPatterns(propertyPathPatterns, nodes); }
+}
+
+/* [104]    GraphNode ::= VarOrTerm | TriplesNode */
+private ResourceOrVariable GraphNode(Set<TriplePattern> triplePatterns) : {
+    ResourceOrVariable node; } {
+    (
+        node=VarOrTerm()
+    |
+        node=TriplesNode(triplePatterns)
+    ) {
+    return node; }
+}
+
+/* [105]    GraphNodePath ::= VarOrTerm | TriplesNodePath */
+private ResourceOrVariable GraphNodePath(Set<PropertyPathPattern> propertyPathPatterns) : {
+    ResourceOrVariable node; } {
+    (
+        node=VarOrTerm()
+    |
+        node=TriplesNodePath(propertyPathPatterns)
+    ) {
+    return node; }
+}
+
+/* [106]    VarOrTerm ::= Var | GraphTerm */
+private ResourceOrVariable VarOrTerm() : {
+    ResourceOrVariable r;
+    Variable v; } {
+
+    (
+        v=Var() {
+        return new ResourceOrVariable(v); }
+    |
+        r=GraphTerm() {
+        return r; }
+    )
+}
+
+/* [107]    VarOrIRI ::= Var | iri */
+private UriRefOrVariable VarOrIRI() : {
+    Variable var;
+    IRI uriRef; } {
+
+    (
+    var=Var() {
+    return new UriRefOrVariable(var); }
+    |
+    uriRef=IRI() {
+    return new UriRefOrVariable(uriRef); }
+    )
+}
+
+/* [108]    Var ::= VAR1 | VAR2 */
+private Variable Var() : {
+    Token t;} {
+
+    (t=<VAR1> | t=<VAR2>) {
+    return createVariable(t.image); }
+}
+
+/* [109]    GraphTerm ::= IRI | RDFLiteral | NumericLiteral | BooleanLiteral | BlankNode | NIL */
+private ResourceOrVariable GraphTerm() : {
+    ResourceOrVariable bNode = null;
+    RDFTerm r = null; } {
+
+    (r=IRI() | r=RDFLiteral() | r=NumericLiteral() | r=BooleanLiteral() | bNode=BlankNode() | <NIL> {
+        r = RDF_NIL; }) {
+    if (bNode == null) {
+        return new ResourceOrVariable(r);
+    }
+    return bNode; }
+}
+
+/* [110]    Expression ::= ConditionalOrExpression */
+private Expression Expression() : {
+    Expression e; } {
+
+    e=ConditionalOrExpression() {
+    return e; }
+}
+
+/* [111]    ConditionalOrExpression ::= ConditionalAndExpression ( '||' ConditionalAndExpression )* */
+private Expression ConditionalOrExpression() : {
+    Expression e, ae; } {
+
+    e=ConditionalAndExpression()
+    (
+        "||" ae=ConditionalAndExpression() {
+        e = new BinaryOperation("||", e, ae); }
+    )* {
+    return e; }
+}
+
+/* [112]    ConditionalAndExpression ::= ValueLogical ( '&&' ValueLogical )* */
+private Expression ConditionalAndExpression() : {
+    Expression e, e2; } {
+
+    e=ValueLogical()
+    (
+        "&&" e2=ValueLogical() {
+        e = new BinaryOperation("&&", e, e2); }
+    )* {
+    return e; }
+}
+
+/* [113]    ValueLogical ::= RelationalExpression */
+private Expression ValueLogical() : {
+    Expression e; } {
+
+    e=RelationalExpression() {
+    return e; }
+}
+
+/* [114]    RelationalExpression ::= NumericExpression ( '=' NumericExpression | '!=' NumericExpression | '<' NumericExpression | '>' NumericExpression | '<=' NumericExpression | '>=' NumericExpression | 'IN' ExpressionList | 'NOT' 'IN' ExpressionList )? */
+private Expression RelationalExpression() : {
+    Expression e, e2; 
+    List<Expression> l; } {
+
+    e=NumericExpression()
+    (
+        "=" e2=NumericExpression() {
+        e = new BinaryOperation("=", e, e2); }
+    |
+        "!=" e2=NumericExpression() {
+        e = new BinaryOperation("!=", e, e2); }
+    |
+        "<" e2=NumericExpression() {
+        e = new BinaryOperation("<", e, e2); }
+    |
+        ">" e2=NumericExpression() {
+        e = new BinaryOperation(">", e, e2); }
+    |
+        "<=" e2=NumericExpression() {
+        e = new BinaryOperation("<=", e, e2); }
+    |
+        ">=" e2=NumericExpression() {
+        e = new BinaryOperation(">=", e, e2); }
+    |
+        <IN> l=ExpressionList() {
+        e = new RhsListBinaryOperation("IN", e, l); }
+    |
+        <NOT> <IN> l=ExpressionList() {
+        e = new RhsListBinaryOperation("NOT IN", e, l); }
+    )? {
+    return e; }
+}
+
+/* [115]    NumericExpression ::= AdditiveExpression */
+private Expression NumericExpression() : {
+    Expression e; } {
+
+    e=AdditiveExpression() {
+    return e; }
+}
+
+/* [116]    AdditiveExpression ::= MultiplicativeExpression ( '+' MultiplicativeExpression | '-' MultiplicativeExpression | ( NumericLiteralPositive | NumericLiteralNegative ) ( ( '*' UnaryExpression ) | ( '/' UnaryExpression ) )* )* */
+private Expression AdditiveExpression() : {
+    Expression e, e2, u;
+    Literal l; } {
+
+    e=MultiplicativeExpression()
+    (
+        "+" e2=MultiplicativeExpression() {
+        e = new BinaryOperation("+", e, e2); }
+    |
+        "-" e2=MultiplicativeExpression() {
+        e = new BinaryOperation("-", e, e2); }
+    |
+        (
+            (
+                l=NumericLiteralPositive()
+            |
+                l=NumericLiteralNegative()
+            ) {
+            e2 = new LiteralExpression(l); }
+            (
+                "*" u=UnaryExpression() {
+                e2 = new BinaryOperation("*", e2, u); }
+            |
+                "/" u=UnaryExpression() {
+                e2 = new BinaryOperation("/", e2, u); }
+            )*
+        ) {
+        e = new BinaryOperation("+", e, e2); }
+    )* {
+    return e; }
+}
+
+/* [117]    MultiplicativeExpression ::= UnaryExpression ( '*' UnaryExpression | '/' UnaryExpression )* */
+private Expression MultiplicativeExpression() : {
+    Expression e, e2; } {
+
+    e=UnaryExpression()
+    (
+        "*" e2=UnaryExpression() {
+        e = new BinaryOperation("*", e, e2); }
+    |
+        "/" e2=UnaryExpression() {
+        e = new BinaryOperation("/", e, e2); }
+    )* {
+    return e; }
+}
+
+/* [118]    UnaryExpression ::=   '!' PrimaryExpression  |  '+' PrimaryExpression  | '-' PrimaryExpression  | PrimaryExpression */
+private Expression UnaryExpression() : {
+    Expression e; } {
+
+        "!" e=PrimaryExpression() {
+        return new UnaryOperation("!", e); }
+    |
+        "+" e=PrimaryExpression() {
+        return new UnaryOperation("+", e); }
+    |
+        "-" e=PrimaryExpression() {
+        return new UnaryOperation("-", e); }
+    |
+        e=PrimaryExpression() {
+        return e; }
+}
+
+/* [119]    PrimaryExpression ::= BrackettedExpression | BuiltInCall | iriOrFunction | RDFLiteral | NumericLiteral | BooleanLiteral | Var */
+private Expression PrimaryExpression() : {
+    Expression e = null;
+    Literal l = null; } {
+
+    (
+        e=BrackettedExpression()
+/* There is a capture all names in BuiltInCall, so put it last
+    |
+        e=BuiltInCall()
+*/
+    |
+        e=IRIOrFunction()
+    |
+        l=RDFLiteral()
+    |
+        l=NumericLiteral()
+    |
+        l=BooleanLiteral()
+    |
+        e=Var()
+    |
+        e=BuiltInCall()
+    ) {
+    if (l != null) {
+        return new LiteralExpression(l);
+    }
+    return e; }
+}
+
+/* [120]    BrackettedExpression ::= '(' Expression ')' */
+private Expression BrackettedExpression() : {
+    Expression e; } {
+
+    "("
+    e=Expression()
+    ")" {
+    return e; }
+}
+
+/* [121]    BuiltInCall ::= Aggregate 
+|    'STR' '(' Expression ')' 
+|    'LANG' '(' Expression ')' 
+|    'LANGMATCHES' '(' Expression ',' Expression ')' 
+|    'DATATYPE' '(' Expression ')' 
+|    'BOUND' '(' Var ')' 
+|    'IRI' '(' Expression ')' 
+|    'URI' '(' Expression ')' 
+|    'BNODE' ( '(' Expression ')' | NIL ) 
+|    'RAND' NIL 
+|    'ABS' '(' Expression ')' 
+|    'CEIL' '(' Expression ')' 
+|    'FLOOR' '(' Expression ')' 
+|    'ROUND' '(' Expression ')' 
+|    'CONCAT' ExpressionList 
+|    SubstringExpression 
+|    'STRLEN' '(' Expression ')' 
+|    StrReplaceExpression 
+|    'UCASE' '(' Expression ')' 
+|    'LCASE' '(' Expression ')' 
+|    'ENCODE_FOR_URI' '(' Expression ')' 
+|    'CONTAINS' '(' Expression ',' Expression ')' 
+|    'STRSTARTS' '(' Expression ',' Expression ')' 
+|    'STRENDS' '(' Expression ',' Expression ')' 
+|    'STRBEFORE' '(' Expression ',' Expression ')' 
+|    'STRAFTER' '(' Expression ',' Expression ')' 
+|    'YEAR' '(' Expression ')' 
+|    'MONTH' '(' Expression ')' 
+|    'DAY' '(' Expression ')' 
+|    'HOURS' '(' Expression ')' 
+|    'MINUTES' '(' Expression ')' 
+|    'SECONDS' '(' Expression ')' 
+|    'TIMEZONE' '(' Expression ')' 
+|    'TZ' '(' Expression ')' 
+|    'NOW' NIL 
+|    'UUID' NIL 
+|    'STRUUID' NIL 
+|    'MD5' '(' Expression ')' 
+|    'SHA1' '(' Expression ')' 
+|    'SHA256' '(' Expression ')' 
+|    'SHA384' '(' Expression ')' 
+|    'SHA512' '(' Expression ')' 
+|    'COALESCE' ExpressionList 
+|    'IF' '(' Expression ',' Expression ',' Expression ')' 
+|    'STRLANG' '(' Expression ',' Expression ')' 
+|    'STRDT' '(' Expression ',' Expression ')' 
+|    'sameTerm' '(' Expression ',' Expression ')' 
+|    'isIRI' '(' Expression ')' 
+|    'isURI' '(' Expression ')' 
+|    'isBLANK' '(' Expression ')' 
+|    'isLITERAL' '(' Expression ')' 
+|    'isNUMERIC' '(' Expression ')' 
+|    RegexExpression 
+|    ExistsFunc 
+|    NotExistsFunc
+
+[122]    RegexExpression ::= 'REGEX' '(' Expression ',' Expression ( ',' Expression )? ')'
+[123]    SubstringExpression ::= 'SUBSTR' '(' Expression ',' Expression ( ',' Expression )? ')'
+[124]    StrReplaceExpression ::= 'REPLACE' '(' Expression ',' Expression ',' Expression ( ',' Expression )? ')'
+
+[127]    Aggregate ::= 'COUNT' '(' 'DISTINCT'? ( '*' | Expression ) ')' 
+| 'SUM' '(' 'DISTINCT'? Expression ')' 
+| 'MIN' '(' 'DISTINCT'? Expression ')' 
+| 'MAX' '(' 'DISTINCT'? Expression ')' 
+| 'AVG' '(' 'DISTINCT'? Expression ')' 
+| 'SAMPLE' '(' 'DISTINCT'? Expression ')' 
+| 'GROUP_CONCAT' '(' 'DISTINCT'? Expression ( ';' 'SEPARATOR' '=' String )? ')'
+
+*/
+
+private BuiltInCall BuiltInCall() : {
+    List<Expression> args = new ArrayList<Expression>();
+    String name, s;
+    Expression e; } {
+    (
+        <GROUP_CONCAT> {
+        name = "GROUP_CONCAT"; }
+        "("
+        (
+            <DISTINCT>
+        )?
+        (
+            e=Expression() {
+            args.add(e); }
+            (
+                ";"
+                <SEPARATOR>
+                "="
+                s = String()
+            )?
+        )
+        ")"
+    |
+        <BOUND> {
+        name = "BOUND"; }
+        "("
+        e=Var() {
+        args.add(e); }
+        ")"
+    |
+        <BNODE> {
+        name = "BNODE"; }
+        (
+            (
+                "("
+                e=Expression() {
+                args.add(e); }
+                ")"
+            )
+        |
+            <NIL>
+        )
+    |
+        <RAND> {
+        name = "RAND"; }
+        <NIL>
+    |
+        <CONCAT> {
+        name = "CONCAT"; }
+        args=ExpressionList()
+    |
+        <NOW> {
+        name = "NOW"; }
+        <NIL>
+    |
+        <UUID> {
+        name = "UUID"; }
+        <NIL>
+    |
+        <STRUUID> {
+        name = "STRUUID"; }
+        <NIL>
+    |
+        <COALESCE> {
+        name = "COALESCE"; }
+        args=ExpressionList()
+    |
+        e=NotExistsFunc() {
+        return (BuiltInCall) e; }
+    |
+        e=ExistsFunc() {
+        return (BuiltInCall) e; }
+    |
+        name=BuiltInCallName()
+        "("
+        (
+            <DISTINCT>
+        )?
+        (
+            "*"
+        |
+            (
+                e=Expression() {
+                args.add(e); }
+                (
+                    ","
+                    e=Expression() {
+                    args.add(e); }
+                )*
+            )
+        )
+        ")"
+    ) {
+    return new BuiltInCall(name, args); }
+}
+
+private String BuiltInCallName() : {
+    Token t;} {
+
+    t=<BUILT_IN_CALL_NAME> {
+    return t.image; }
+}
+
+/* [125]    ExistsFunc ::= 'EXISTS' GroupGraphPattern */
+private Expression ExistsFunc() : {
+    GroupGraphPattern pattern; 
+    PatternExistenceCondition patternExistenceCondition; } {
+
+    <EXISTS>
+    pattern = GroupGraphPattern() {
+    patternExistenceCondition = new PatternExistenceCondition();
+    patternExistenceCondition.setPattern(pattern);
+    return patternExistenceCondition; }
+}
+
+/* [126]    NotExistsFunc ::= 'NOT' 'EXISTS' GroupGraphPattern */
+private Expression NotExistsFunc() : {
+    GroupGraphPattern pattern; 
+    PatternExistenceCondition patternExistenceCondition; } {
+
+    <NOT> <EXISTS>
+    pattern = GroupGraphPattern() {
+    patternExistenceCondition = new PatternExistenceCondition();
+    patternExistenceCondition.setPattern(pattern);
+    patternExistenceCondition.setExistenceTest(false);
+    return patternExistenceCondition; }
+}
+
+/* [128]    IRIOrFunction ::= iri ArgList? */
+private Expression IRIOrFunction() : {
+    IRI uriRef;
+    List<Expression> args; } {
+
+    uriRef=IRI()
+    (
+        args=ArgList() {
+        return new FunctionCall(uriRef, args); }
+    )? {
+    return new UriRefExpression(uriRef); }
+}
+
+/* [129]    RDFLiteral ::= String ( LANGTAG | ( '^^' iri ) )? */
+private Literal RDFLiteral() : {
+    Token t;
+    String s;
+    IRI type; } {
+
+    s = String()
+    (
+        t=<LANGTAG> {
+        return new PlainLiteralImpl(s, new Language(t.image.substring(1))); }
+    |
+        (
+            "^^"
+            type=IRI() {
+            return new TypedLiteralImpl(s, type); }
+        )
+    )? {
+    return new PlainLiteralImpl(s); }
+}
+
+/* [130]    NumericLiteral ::= NumericLiteralUnsigned | NumericLiteralPositive | NumericLiteralNegative */
+private Literal NumericLiteral() : {
+    Literal l; } {
+
+    (
+        l=NumericLiteralUnsigned()
+    |
+        l=NumericLiteralPositive()
+    |
+        l=NumericLiteralNegative()
+    ) {
+    return l; }
+}
+
+/* [131]    NumericLiteralUnsigned ::= INTEGER |  DECIMAL |  DOUBLE */
+private Literal NumericLiteralUnsigned() : {
+    Token t; } {
+
+        t=<INTEGER> {
+        return LiteralFactory.getInstance().createTypedLiteral(Long.valueOf(t.image)); }
+    |
+        t=<DECIMAL> {
+        return LiteralFactory.getInstance().createTypedLiteral(Float.valueOf(t.image)); }
+    |
+        t=<DOUBLE> {
+        return LiteralFactory.getInstance().createTypedLiteral(Double.valueOf(t.image)); }
+}
+
+/* [132]    NumericLiteralPositive ::= INTEGER_POSITIVE |  DECIMAL_POSITIVE |  DOUBLE_POSITIVE */
+private Literal NumericLiteralPositive() : {
+    Token t; } {
+
+        t=<INTEGER_POSITIVE> {
+        return LiteralFactory.getInstance().createTypedLiteral(Long.valueOf(t.image)); }
+    |
+        t=<DECIMAL_POSITIVE> {
+        return LiteralFactory.getInstance().createTypedLiteral(Float.valueOf(t.image)); }
+    |
+        t=<DOUBLE_POSITIVE> {
+        return LiteralFactory.getInstance().createTypedLiteral(Double.valueOf(t.image)); }
+}
+
+/* [133]    NumericLiteralNegative ::= INTEGER_NEGATIVE | DECIMAL_NEGATIVE | DOUBLE_NEGATIVE */
+private Literal NumericLiteralNegative() : {
+    Token t; } {
+
+        t=<INTEGER_NEGATIVE> {
+        return LiteralFactory.getInstance().createTypedLiteral(Long.valueOf(t.image)); }
+    |
+        t=<DECIMAL_NEGATIVE> {
+        return LiteralFactory.getInstance().createTypedLiteral(Float.valueOf(t.image)); }
+    |
+        t=<DOUBLE_NEGATIVE> {
+        return LiteralFactory.getInstance().createTypedLiteral(Double.valueOf(t.image)); }
+}
+
+/* [134]    BooleanLiteral ::= 'true' | 'false' */
+private Literal BooleanLiteral() : {} {
+
+        <TRUE> {
+        return LiteralFactory.getInstance().createTypedLiteral(true); }
+    |
+        <FALSE> {
+        return LiteralFactory.getInstance().createTypedLiteral(false); }
+}
+
+/* [135]    String ::= STRING_LITERAL1 | STRING_LITERAL2 | STRING_LITERAL_LONG1 | STRING_LITERAL_LONG2 */
+private String String() : {
+    Token t; } {
+
+        t=<STRING_LITERAL1> {
+        return unquote(t.image) ; }
+    |
+        t=<STRING_LITERAL2> {
+        return unquote(t.image) ; }
+    |
+        t=<STRING_LITERAL_LONG1> {
+        return unTripleQuote(t.image) ; }
+    |
+        t=<STRING_LITERAL_LONG2> {
+        return unTripleQuote(t.image) ; }
+}
+
+/* [136]    iri ::= IRIREF |  PrefixedName */
+private IRI IRI() : {
+    IRI uriRef;
+    Token t; } {
+
+        t=<IRIREF> {
+        return createUriRef(unquote(t.image)); }
+    |
+        uriRef=PrefixedName() {
+        return uriRef; }
+}
+
+/* [137]    PrefixedName ::= PNAME_LN | PNAME_NS */
+private IRI PrefixedName() : {
+    Token t; } {
+
+    ( t=<PNAME_LN> | t=<PNAME_NS> ) {
+    return createUriRef(t.image); }
+}
+
+/* [138]    BlankNode ::= BLANK_NODE_LABEL | ANON */
+private ResourceOrVariable BlankNode() : {
+    Token t; } {
+
+        t=<BLANK_NODE_LABEL> {
+        return getBNode(t.image); }
+    |
+        <ANON> {
+        return getNewBNode(); }
+}
+
+
+TOKEN : {
+  /* [139]    IRIREF ::= '<' ([^<>"{}|^`\]-[#x00-#x20])* '>' */
+  < IRIREF : "<" ( ~["<", ">", "\"", "{", "}", "|", "^", "`", "\\", "\u0000"-"\u0020"] )* ">" >
+  |
+  /* [140]    PNAME_NS ::= PN_PREFIX? ':' */
+  < PNAME_NS : (<PN_PREFIX>)? ":" >
+  |
+  /* [141]    PNAME_LN ::= PNAME_NS PN_LOCAL */
+  < PNAME_LN : <PNAME_NS> <PN_LOCAL> >
+  |
+  /* [142]    BLANK_NODE_LABEL ::= '_:' ( PN_CHARS_U | [0-9] ) ((PN_CHARS|'.')* PN_CHARS)? */
+  < BLANK_NODE_LABEL : "_:" ( <PN_CHARS_U> | ["0"-"9"] ) ( ( <PN_CHARS> | "." )* <PN_CHARS> )? >
+  |
+  /* [143]    VAR1 ::= '?' VARNAME */
+  < VAR1 : "?" <VARNAME> >
+  |
+  /* [144]    VAR2 ::= '$' VARNAME */
+  < VAR2 : "$" <VARNAME> >
+  |
+  /* [145]    LANGTAG ::= '@' [a-zA-Z]+ ('-' [a-zA-Z0-9]+)* */
+  < LANGTAG : "@" (["a"-"z", "A"-"Z"])+ ( "-" (["a"-"z", "A"-"Z", "0"-"9"])+ )* >
+  |
+  < BUILT_IN_CALL_NAME : ["a"-"z", "A"-"Z", "_"] (["a"-"z", "A"-"Z", "0"-"9", "_"])* >
+}
+
+TOKEN : {
+  < #Z_9 : ["0"-"9"] >
+  |
+  < #Z_9r : (<Z_9>)+ >
+  |
+  < #Z_9o : (<Z_9>)* >
+  |
+  /* [146]    INTEGER ::= [0-9]+ */
+  < INTEGER : <Z_9r> >
+  |
+  /* [147]    DECIMAL ::= [0-9]* '.' [0-9]+ */
+  < DECIMAL : <Z_9o> "." <Z_9r> >
+  |
+  /* [148]    DOUBLE ::= [0-9]+ '.' [0-9]* EXPONENT | '.' ([0-9])+ EXPONENT | ([0-9])+ EXPONENT */
+  < DOUBLE : ( <Z_9r> "." <Z_9o>  <EXPONENT> ) | ( "." <Z_9r> <EXPONENT> ) | ( <Z_9r> <EXPONENT> ) >
+  |
+  /* [149]    INTEGER_POSITIVE ::= '+' INTEGER */
+  < INTEGER_POSITIVE : "+" <INTEGER> >
+  |
+  /* [150]    DECIMAL_POSITIVE ::= '+' DECIMAL */
+  < DECIMAL_POSITIVE : "+" <DECIMAL> >
+  |
+  /* [151]    DOUBLE_POSITIVE ::= '+' DOUBLE */
+  < DOUBLE_POSITIVE : "+" <DOUBLE> >
+  |
+  /* [152]    INTEGER_NEGATIVE ::= '-' INTEGER */
+  < INTEGER_NEGATIVE : "-" <INTEGER> >
+  |
+  /* [153]    DECIMAL_NEGATIVE ::= '-' DECIMAL */
+  < DECIMAL_NEGATIVE : "-" <DECIMAL> >
+  |
+  /* [154]    DOUBLE_NEGATIVE ::= '-' DOUBLE */
+  < DOUBLE_NEGATIVE : "-" <DOUBLE> >
+  |
+  /* [155]    EXPONENT ::= [eE] [+-]? [0-9]+ */
+  < #EXPONENT : ["e","E"] (["+","-"])? <Z_9r> >
+}
+
+TOKEN : {
+  /* [156]    STRING_LITERAL1 ::= "'" ( ([^#x27#x5C#xA#xD]) | ECHAR )* "'" */
+  < STRING_LITERAL1 : "'" ( ~["'", "\\", "\r", "\n"] | <ECHAR> )* "'" >
+  |
+  /* [157]    STRING_LITERAL2 ::= '"' ( ([^#x22#x5C#xA#xD]) | ECHAR )* '"' */
+  < STRING_LITERAL2 : "\"" ( ~["\"", "\\", "\r", "\n"] | <ECHAR> )* "\"" >
+  |
+  /* [158]    STRING_LITERAL_LONG1 ::= "'''" ( ( "'" | "''" )? ( [^'\] | ECHAR ) )* "'''" */
+  < STRING_LITERAL_LONG1 : "'''" ( ( "'" | "''" )? ( ~["'","\\"] | <ECHAR> ) )* "'''" >
+  |
+  /* [159]    STRING_LITERAL_LONG2 ::= '"""' ( ( '"' | '""' )? ( [^"\] | ECHAR ) )* '"""' */
+  < STRING_LITERAL_LONG2 : "\"\"\"" ( ( "\"" | "\"\"" )? ( ~["\"","\\"] | <ECHAR> ) )* "\"\"\"" >
+  |
+  /* [160]    #ECHAR ::= '\' [tbnrf\"'] */
+  < #ECHAR : "\\" ["t","b","n","r","f","\\","\"","'"] >
+}
+
+TOKEN : {
+  /* [161]    NIL ::= '(' WS* ')' */
+  < NIL : "(" (<WS>)* ")" >
+  |
+  /* [162]    WS ::= #x20 | #x9 | #xD | #xA */
+  < #WS : " " | "\t" | "\n" | "\r" >
+  |
+  /* [163]    ANON ::= '[' WS* ']' */
+  < ANON : "[" (<WS>)* "]" >
+}
+
+TOKEN : {
+  /* [164]    #PN_CHARS_BASE ::= [A-Z] | [a-z] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x02FF] | [#x0370-#x037D] | [#x037F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] */
+  < #PN_CHARS_BASE : ["A"-"Z", "a"-"z", "\u00C0"-"\u00D6", "\u00D8"-"\u00F6", "\u00F8"-"\u02FF", "\u0370"-"\u037D", "\u037F"-"\u1FFF", "\u200C"-"\u200D", "\u2070"-"\u218F", "\u2C00"-"\u2FEF", "\u3001"-"\uD7FF", "\uF900"-"\uFDCF", "\uFDF0"-"\uFFFD"] >
+  |
+  /* [165]    #PN_CHARS_U ::= PN_CHARS_BASE | '_' */
+  < #PN_CHARS_U : <PN_CHARS_BASE> | "_" >
+  |
+  /* [166]    #VARNAME ::= ( PN_CHARS_U | [0-9] ) ( PN_CHARS_U | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040] )* */
+  < #VARNAME : (<PN_CHARS_U> | <Z_9>) (<PN_CHARS_U> | <Z_9> | "\u00b7" | ["\u0300"-"\u036f"] | ["\u203f"-"\u2040"])* >
+  |
+  /* [167]    #PN_CHARS ::= PN_CHARS_U | '-' | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040] */
+  < #PN_CHARS : <PN_CHARS_U> | "-" | <Z_9> | "\u00b7" | ["\u0300"-"\u036f"] | ["\u203f"-"\u2040"] >
+  |
+  /* [168]    PN_PREFIX ::= PN_CHARS_BASE ((PN_CHARS|'.')* PN_CHARS)? */
+  < PN_PREFIX : <PN_CHARS_BASE> ((<PN_CHARS> | "." )* <PN_CHARS>)? >
+  |
+  /* [169]    PN_LOCAL ::= ( PN_CHARS_U | ':' | [0-9] | PLX ) ((PN_CHARS | '.' | ':' | PLX)* (PN_CHARS | ':' | PLX) )? */
+  /* Note that SPARQL local names allow leading digits while XML local names do not. */
+  < PN_LOCAL : (<PN_CHARS_U> | ":" | <Z_9> | <PLX>) ((<PN_CHARS> | "." | ":" | <PLX>)* (<PN_CHARS> | ":" | <PLX>) )? >
+  |
+  /* [170]    PLX ::= PERCENT | PN_LOCAL_ESC */
+  < PLX : <PERCENT> | <PN_LOCAL_ESC> >
+  |
+  /* [171]    PERCENT ::= '%' HEX HEX */
+  < PERCENT : "%" <HEX> <HEX> >
+  |
+  /* [172]    HEX ::= [0-9] | [A-F] | [a-f] */
+  < #HEX : <Z_9> | ["A"-"F", "a"-"f"] >
+  |
+  /* [173]    PN_LOCAL_ESC ::= '\' ( '_' | '~' | '.' | '-' | '!' | '$' | '&' | "'" | '(' | ')' | '*' | '+' | ',' | ';' | '=' | '/' | '?' | '#' | '@' | '%' ) */
+  < PN_LOCAL_ESC : "\\" ( "_" | "~" | "." | "-" | "!" | "$" | "&" | "'" | "(" | ")" | "*" | "+" | "," | ";" | "=" | "/" | "?" | "#" | "@" | "%" ) >
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/test/java/org/apache/clerezza/sparql/QueryParserSerializerCombinationTest.java
----------------------------------------------------------------------
diff --git a/sparql/src/test/java/org/apache/clerezza/sparql/QueryParserSerializerCombinationTest.java b/sparql/src/test/java/org/apache/clerezza/sparql/QueryParserSerializerCombinationTest.java
new file mode 100644
index 0000000..b84c388
--- /dev/null
+++ b/sparql/src/test/java/org/apache/clerezza/sparql/QueryParserSerializerCombinationTest.java
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.sparql;
+
+import org.apache.clerezza.sparql.query.Query;
+import org.junit.*;
+
+/**
+ *
+ * @author hasan
+ */
+public class QueryParserSerializerCombinationTest {
+    
+    public QueryParserSerializerCombinationTest() {
+    }
+    
+    @BeforeClass
+    public static void setUpClass() {
+    }
+    
+    @AfterClass
+    public static void tearDownClass() {
+    }
+    
+    @Before
+    public void setUp() {
+    }
+    
+    @After
+    public void tearDown() {
+    }
+
+    @Test
+    public void testPatternOrderPreservation() throws Exception {
+        String queryString =
+                "SELECT ?property ?range ?property_description ?subproperty ?subproperty_description \n"
+                + "WHERE\n"
+                + "{ ?property <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#ObjectProperty> .\n"
+                + "{ { ?property <http://www.w3.org/2000/01/rdf-schema#domain> ?superclass .\n"
+                + "<http://example.org/ontologies/market_ontology.owl#Company> <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?superclass .\n"
+                + "}  UNION { ?property <http://www.w3.org/2000/01/rdf-schema#domain> ?dunion .\n"
+                + "?dunion <http://www.w3.org/2002/07/owl#unionOf> ?dlist .\n"
+                + "?dlist <http://jena.hpl.hp.com/ARQ/list#member> ?superclass .\n"
+                + "<http://example.org/ontologies/market_ontology.owl#Company> <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?superclass .\n"
+                + "} } { { ?property <http://www.w3.org/2000/01/rdf-schema#range> ?superrange .\n"
+                + "?range <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?superrange .\n"
+                + "FILTER (! (isBLANK(?range)))\n"
+                + "}  UNION { ?property <http://www.w3.org/2000/01/rdf-schema#range> ?range .\n"
+                + "FILTER (! (isBLANK(?range)))\n"
+                + "} }  OPTIONAL { ?somesub <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?range .\n"
+                + "FILTER (((?somesub) != (<http://www.w3.org/2002/07/owl#Nothing>)) && ((?somesub) != (?range)))\n"
+                + "}  OPTIONAL { ?subproperty <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?property .\n"
+                 + " OPTIONAL { ?subproperty <http://purl.org/dc/elements/1.1/description> ?subproperty_description .\n"
+                + "} FILTER (((?subproperty) != (<http://www.w3.org/2002/07/owl#bottomObjectProperty>)) && ((?subproperty) != (?property)))\n"
+                + "}  OPTIONAL { ?property <http://purl.org/dc/elements/1.1/description> ?property_description .\n"
+                + "} FILTER ((?property) != (<http://www.w3.org/2002/07/owl#bottomObjectProperty>))\n"
+                + "FILTER ((?range) != (<http://www.w3.org/2002/07/owl#Nothing>))\n"
+                + "FILTER (! (BOUND(?somesub)))\n"
+                + "} \n";
+
+        Query query = QueryParser.getInstance().parse(queryString);
+        Assert.assertEquals(queryString.replaceAll("\\s", "").trim(), query.toString().replaceAll("\\s", "").trim());
+    }
+
+    @Test
+    public void testParsingAndSerializationStability() throws Exception {
+        String queryString =
+                "PREFIX mo: <http://example.org/ontologies/market_ontology.owl#>\n"
+                + "PREFIX list: <http://jena.hpl.hp.com/ARQ/list#>\n"
+                + "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n"
+                + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
+                + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
+                + "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n"
+                + "SELECT ?property ?range ?property_description ?subproperty ?subproperty_description\n"
+                + "WHERE {\n"
+                + "    ?property a owl:ObjectProperty .\n"
+                + "    FILTER (?property != owl:bottomObjectProperty) .\n"
+                + "    {\n"
+                + "        {\n"
+                + "            ?property rdfs:domain ?superclass .\n"
+                + "            mo:Company rdfs:subClassOf ?superclass .\n"
+                + "        }\n"
+                + "        UNION\n"
+                + "        {\n"
+                + "            ?property rdfs:domain ?dunion .\n"
+                + "            ?dunion owl:unionOf ?dlist .\n"
+                + "            ?dlist list:member ?superclass .\n"
+                + "            mo:Company rdfs:subClassOf ?superclass .\n"
+                + "        }\n"
+                + "    }\n"
+                + "    {\n"
+                + "        {\n"
+                + "            ?property rdfs:range ?superrange .\n"
+                + "            ?range rdfs:subClassOf ?superrange .\n"
+                + "            FILTER (!isBlank(?range)) .\n"
+                + "        }\n"
+                + "        UNION\n"
+                + "        {\n"
+                + "            ?property rdfs:range ?range .\n"
+                + "            FILTER (!isBlank(?range)) .\n"
+                + "        }\n"
+                + "    } .\n"
+                + "    FILTER (?range != owl:Nothing) .\n"
+                + "    OPTIONAL { ?somesub rdfs:subClassOf ?range . FILTER(?somesub != owl:Nothing && ?somesub != ?range)}\n"
+                + "    FILTER (!bound(?somesub)) .\n"
+                + "    OPTIONAL {\n"
+                + "        ?subproperty rdfs:subPropertyOf ?property .\n"
+                + "        FILTER(?subproperty != owl:bottomObjectProperty && ?subproperty != ?property)\n"
+                + "        OPTIONAL { ?subproperty dc:description ?subproperty_description . }\n"
+                + "    }\n"
+                + "    OPTIONAL { ?property dc:description ?property_description . }\n"
+                + "} ";
+
+        Query query1 = QueryParser.getInstance().parse(queryString);
+        Thread.sleep(5000l);
+        Query query2 = QueryParser.getInstance().parse(queryString);
+        Assert.assertEquals(query1.toString(), query2.toString());
+    }
+}


[3/6] clerezza git commit: CLEREZZA-1026: Introduce GraphStore to remove dependency to TcProvider and refactor sparql

Posted by ha...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/eec0ac73/sparql/src/main/javacc/org/apache/clerezza/sparql/JavaCCGeneratedQueryParser.jj
----------------------------------------------------------------------
diff --git a/sparql/src/main/javacc/org/apache/clerezza/sparql/JavaCCGeneratedQueryParser.jj b/sparql/src/main/javacc/org/apache/clerezza/sparql/JavaCCGeneratedQueryParser.jj
new file mode 100644
index 0000000..7771c07
--- /dev/null
+++ b/sparql/src/main/javacc/org/apache/clerezza/sparql/JavaCCGeneratedQueryParser.jj
@@ -0,0 +1,1285 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+options
+{
+   STATIC=false;
+   SUPPORT_CLASS_VISIBILITY_PUBLIC=false;
+   UNICODE_INPUT=true;
+   IGNORE_CASE=false;
+   JAVA_UNICODE_ESCAPE=false;
+   DEBUG_PARSER=false;
+   JDK_VERSION="1.6";
+}
+
+PARSER_BEGIN(JavaCCGeneratedQueryParser)
+
+package org.apache.clerezza.sparql;
+
+import org.apache.clerezza.api.BlankNode;
+import org.apache.clerezza.api.Language;
+import org.apache.clerezza.api.Literal;
+import org.apache.clerezza.api.RDFTerm;
+import org.apache.clerezza.api.IRI;
+import org.apache.clerezza.api.impl.literal.LiteralFactory;
+import org.apache.clerezza.api.impl.literal.PlainLiteralImpl;
+import org.apache.clerezza.api.impl.literal.TypedLiteralImpl;
+import org.apache.clerezza.sparql.query.GroupGraphPattern;
+import org.apache.clerezza.sparql.query.BinaryOperation;
+import org.apache.clerezza.sparql.query.Variable;
+import org.apache.clerezza.sparql.query.ResourceOrVariable;
+import org.apache.clerezza.sparql.query.UriRefOrVariable;
+import org.apache.clerezza.sparql.query.FunctionCall;
+import org.apache.clerezza.sparql.query.TriplePattern;
+import org.apache.clerezza.sparql.query.Query;
+import org.apache.clerezza.sparql.query.LiteralExpression;
+import org.apache.clerezza.sparql.query.AlternativeGraphPattern;
+import org.apache.clerezza.sparql.query.BuiltInCall;
+import org.apache.clerezza.sparql.query.Expression;
+import org.apache.clerezza.sparql.query.UriRefExpression;
+import org.apache.clerezza.sparql.query.UnaryOperation;
+import org.apache.clerezza.sparql.query.impl.SimpleAlternativeGraphPattern;
+import org.apache.clerezza.sparql.query.impl.SimpleAskQuery;
+import org.apache.clerezza.sparql.query.impl.SimpleConstructQuery;
+import org.apache.clerezza.sparql.query.impl.SimpleDescribeQuery;
+import org.apache.clerezza.sparql.query.impl.SimpleGraphGraphPattern;
+import org.apache.clerezza.sparql.query.impl.SimpleGroupGraphPattern;
+import org.apache.clerezza.sparql.query.impl.SimpleOrderCondition;
+import org.apache.clerezza.sparql.query.impl.SimpleQuery;
+import org.apache.clerezza.sparql.query.impl.SimpleQueryWithSolutionModifier;
+import org.apache.clerezza.sparql.query.impl.SimpleSelectQuery;
+import org.apache.clerezza.sparql.query.impl.SimpleTriplePattern;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.Set;
+
+/**
+ *
+ * Credits: Fedora Commons, Inc.
+ *            - for initial grammar of this file (available in mulgara project).
+ * Modified by: Hasan <ha...@trialox.org>
+ */
+class JavaCCGeneratedQueryParser {
+
+	private static final IRI RDF_TYPE =
+		new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
+	private static final IRI RDF_FIRST =
+		new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#first");
+	private static final IRI RDF_REST =
+		new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#rest");
+	private static final IRI RDF_NIL =
+		new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#nil");
+
+	/** A RegEx pattern for separating out a namespace from a prefixed name. */
+	private static final Pattern pfxNamePattern = Pattern.compile("([^:]*):(.*)");
+
+	private Query query;
+	private String base;
+	private Map<String, String> prefixes;
+	private Map<String, ResourceOrVariable> bNodes;
+	private int count;
+	private Map<String, Variable> vars;
+
+	void initialize() {
+		query = null;
+		base = null;
+		prefixes = new HashMap<String, String>();
+		bNodes = new HashMap<String, ResourceOrVariable>();
+		count = 0;
+		vars = new HashMap<String, Variable>();
+	}
+
+	Query parse() throws ParseException {
+		initialize();
+		this.Query();
+		return this.query;
+	}
+
+	private static String unquote(String s) {
+		return s.substring(1, s.length() - 1);
+	}
+
+	private static String unTripleQuote(String s) {
+		return s.substring(3, s.length() - 3);
+	}
+
+	private Variable getVariable(String name) {
+		name = name.substring(1);
+		Variable v = vars.get(name);
+		if (v == null) {
+			v = new Variable(name);
+			vars.put(name, v);
+			if (query instanceof SimpleSelectQuery) {
+				SimpleSelectQuery sq = (SimpleSelectQuery) query;
+				if (sq.isSelectAll()) {
+					sq.addSelection(v);
+				}
+			} else if (query instanceof SimpleDescribeQuery) {
+				SimpleDescribeQuery dq = (SimpleDescribeQuery) query;
+				if (dq.isDescribeAll()) {
+					dq.addResourceToDescribe(new ResourceOrVariable(v));
+				}
+			}
+		}
+		return v;
+	}
+
+	private void addTriplePatterns(Set<TriplePattern> triplePatterns,
+			ResourceOrVariable subject,
+			UriRefOrVariable predicate,
+			Set<ResourceOrVariable> objects) {
+
+		for (ResourceOrVariable object : objects) {
+			triplePatterns.add(
+				new SimpleTriplePattern(subject, predicate, object));
+		}
+	}
+
+	// nodes contain at least one element
+	private ResourceOrVariable addTriplePatterns(
+			Set<TriplePattern> triplePatterns,
+			List<ResourceOrVariable> nodes) {
+
+		ResourceOrVariable head = null;
+		UriRefOrVariable rdfFirst = new UriRefOrVariable(RDF_FIRST);
+		UriRefOrVariable rdfRest = new UriRefOrVariable(RDF_REST);
+		UriRefOrVariable rdfNil = new UriRefOrVariable(RDF_NIL);
+
+		ResourceOrVariable prevSubject = null;
+		for (ResourceOrVariable node : nodes) {
+			ResourceOrVariable currentSubject = getNewBNode();
+			if (prevSubject != null) {
+				triplePatterns.add(
+					new SimpleTriplePattern(prevSubject, rdfRest, currentSubject));
+			} else {
+				head = currentSubject;
+			}
+			triplePatterns.add(
+				new SimpleTriplePattern(currentSubject, rdfFirst, node));
+			prevSubject = currentSubject;
+		}
+		if (prevSubject != null) {
+			triplePatterns.add(
+				new SimpleTriplePattern(prevSubject, rdfRest, rdfNil));
+		}
+		return head;
+	}
+
+	private ResourceOrVariable getNewBNode() {
+		ResourceOrVariable bNode = new ResourceOrVariable(new BlankNode());
+		bNodes.put("*" + count++, bNode);
+		return bNode;
+	}
+
+	private ResourceOrVariable getBNode(String label) {
+		ResourceOrVariable bNode = bNodes.get(label);
+		if (bNode == null) {
+			bNode = new ResourceOrVariable(new BlankNode());
+			bNodes.put(label, bNode);
+		}
+		return bNode;
+	}
+
+	private IRI createUriRef(String r) throws ParseException {
+		// Create an IRI directly if the string does not start with a prefix
+		Matcher m = pfxNamePattern.matcher(r);
+		if (!m.matches()) {
+			// either a normal IRI, or one with a BASE
+			return isRelative(r) ? new IRI(base + r) : new IRI(r);
+		}
+		// extract the prefix, and attempt to convert to a URI before creating the reference
+		String ns = prefixes.get(m.group(1));
+		return ns == null ? new IRI(r) : new IRI(ns + m.group(2));
+	}
+
+	/**
+	 * Tests if the string for a URI is relative or absolute. The test is based on a scheme existing
+	 * in the string, which in turn expects a : character to follow it. If there is no colon, then
+	 * it is presumed to be relative. Otherwise, if there are special characters preceding the first
+	 * colon these are presumed to not be in a scheme.
+	 * @param u A string for a URI.
+	 * @return <code>true</code> if the URI appears to be relative, <code>false</code> otherwise.
+	 */
+	private static boolean isRelative(String u) {
+		int colon = u.indexOf(':');
+		if (colon < 0) {
+			return true;
+		}
+		for (int c = 0; c < colon; c++) {
+			// if there a non-alphanum characters then this is not a scheme, so the URI is relative
+			if (!Character.isLetterOrDigit(u.charAt(c))) {
+				return true;
+			}
+		}
+		// found a (probably) valid scheme, so the URI is absolute
+		return false;
+	}
+}
+PARSER_END(JavaCCGeneratedQueryParser)
+
+SKIP :
+{
+    "\t" | "\n" | "\r" | "\f" | " "
+}
+
+MORE :
+{
+    "#" : IN_COMMENT
+}
+
+<IN_COMMENT>
+SPECIAL_TOKEN :
+{
+  <COMMENT: ( ~[ "\r","\n" ] )* > : DEFAULT
+}
+
+TOKEN [IGNORE_CASE] :
+{
+    < SELECT : "SELECT" >
+|   < BASE : "BASE" >
+|   < ORDER : "ORDER" >
+|   < BY : "BY" >
+|   < FROM : "FROM" >
+|   < GRAPH : "GRAPH" >
+|   < STR : "STR" >
+|   < IS_URI : "isURI" >
+|   < PREFIX : "PREFIX" >
+|   < CONSTRUCT : "CONSTRUCT" >
+|   < LIMIT : "LIMIT" >
+|   < NAMED : "NAMED" >
+|   < OPTIONAL : "OPTIONAL" >
+|   < LANG : "lang" >
+|   < IS_IRI : "isIRI" >
+|   < DESCRIBE : "DESCRIBE" >
+|   < OFFSET : "OFFSET" >
+|   < WHERE : "WHERE" >
+|   < UNION : "UNION" >
+|   < LANGMATCHES : "langMatches" >
+|   < IS_BLANK : "isBlank" >
+|   < IS_LITERAL : "isLiteral" >
+|   < ASK : "ASK" >
+|   < DISTINCT : "DISTINCT" >
+|   < FILTER : "FILTER" >
+|   < DATATYPE : "datatype" >
+|   < REGEX : "regex" >
+|   < REDUCED : "REDUCED" >
+|   < BOUND : "bound" >
+|   < TRUE : "TRUE" >
+|   < SAME_TERM : "sameTerm" >
+|   < FALSE : "FALSE" >
+}
+
+
+/* [1]      Query      ::=      Prologue ( SelectQuery | ConstructQuery | DescribeQuery | AskQuery ) */
+private void Query() : {} {
+	Prologue() ( SelectQuery() | ConstructQuery() | DescribeQuery() | AskQuery() ) <EOF>
+}
+
+/* [2]      Prologue      ::=      BaseDecl? PrefixDecl* */
+private void Prologue() : {} {
+	( BaseDecl() )? ( PrefixDecl() )*
+}
+
+/* [3]      BaseDecl      ::=      'BASE' IRI_REF */
+private void BaseDecl() : {
+	Token iriRef; } {
+
+	<BASE> iriRef=<IRI_REF> { base = unquote(iriRef.image); }
+}
+
+/* [4]      PrefixDecl      ::=      'PREFIX' PNAME_NS IRI_REF */
+private void PrefixDecl() : {
+	Token ns, iriRef; } {
+
+	<PREFIX> ns=<PNAME_NS> iriRef=<IRI_REF> {
+	String pfx = ns.image;
+	prefixes.put(pfx.substring(0, pfx.length() - 1), unquote(iriRef.image)); }
+}
+
+/* [5]      SelectQuery   ::=   'SELECT' ( 'DISTINCT' | 'REDUCED' )? ( Var+ | '*' ) DatasetClause* WhereClause SolutionModifier */
+private void SelectQuery() : {
+	Variable v; } {
+
+	<SELECT> {
+	query = new SimpleSelectQuery(); }
+	(
+		<DISTINCT> {
+		((SimpleSelectQuery) query).setDistinct(); }
+	|
+		<REDUCED> {
+		((SimpleSelectQuery) query).setReduced(); }
+	)?
+	(
+		( v=Var() {
+			((SimpleSelectQuery) query).addSelection(v); } )+
+		|
+		"*" {
+			((SimpleSelectQuery) query).setSelectAll(); }
+	)
+	( DatasetClause() )*
+	WhereClause()
+	SolutionModifier()
+}
+
+/* [6]      ConstructQuery    ::=   'CONSTRUCT' ConstructTemplate DatasetClause* WhereClause SolutionModifier */
+private void ConstructQuery() : {
+	Set<TriplePattern> triplePatterns = null; } {
+
+	<CONSTRUCT>
+	triplePatterns=ConstructTemplate() {
+	query = new SimpleConstructQuery(triplePatterns); }
+	( DatasetClause() )*
+	WhereClause()
+	SolutionModifier()
+}
+
+/* [7]      DescribeQuery      ::=      'DESCRIBE' ( VarOrIRIref+ | '*' ) DatasetClause* WhereClause? SolutionModifier */
+private void DescribeQuery() : {
+	UriRefOrVariable node; } {
+
+	<DESCRIBE> {
+	query = new SimpleDescribeQuery(); }
+	(
+		( node=VarOrIRIref() {
+			((SimpleDescribeQuery) query).addResourceToDescribe(node); } )+
+		|
+		"*" {
+			((SimpleDescribeQuery) query).setDescribeAll(); }
+	)
+	( DatasetClause() )*
+	( WhereClause() )?
+	SolutionModifier()
+}
+
+/* [8]      AskQuery      ::=   'ASK' DatasetClause* WhereClause */
+private void AskQuery() : {} {
+	<ASK> {
+	query = new SimpleAskQuery(); }
+	( DatasetClause() )*
+	WhereClause()
+}
+
+/* [9]   DatasetClause   ::=   'FROM' ( DefaultGraphClause | NamedGraphClause ) */
+private void DatasetClause() : {} {
+	<FROM> (DefaultGraphClause() | NamedGraphClause())
+}
+
+/* [10]    DefaultGraphClause    ::=    SourceSelector */
+private void DefaultGraphClause() : {
+	IRI defaultGraph; } {
+
+	defaultGraph=SourceSelector() {
+	((SimpleQuery) query).addDefaultGraph(defaultGraph); }
+}
+
+/* [11]    NamedGraphClause    ::=    'NAMED' SourceSelector */
+private void NamedGraphClause() : {
+	IRI namedGraph; } {
+
+	<NAMED> namedGraph=SourceSelector() {
+	((SimpleQuery) query).addNamedGraph(namedGraph); }
+}
+
+/* [12]    SourceSelector    ::=    IRIref */
+private IRI SourceSelector() : {
+	IRI graph; } {
+
+	graph=IRIref() {
+	return graph; }
+}
+
+/* [13]    WhereClause    ::=    'WHERE'? GroupGraphPattern */
+private void WhereClause() : {
+	GroupGraphPattern queryPattern; } {
+
+	(<WHERE>)? queryPattern=GroupGraphPattern() {
+	((SimpleQuery) query).setQueryPattern(queryPattern); }
+}
+
+/* [14]    SolutionModifier    ::=    OrderClause? LimitOffsetClauses? */
+private void SolutionModifier() : {} {
+	( OrderClause() )?
+	( LimitOffsetClauses() )?
+}
+
+/* [15]    LimitOffsetClauses    ::=    ( LimitClause OffsetClause? | OffsetClause LimitClause? ) */
+private void LimitOffsetClauses() : {} {
+	( LimitClause() (OffsetClause())? )
+	|
+	( OffsetClause() (LimitClause())? )
+}
+
+/* [16]    OrderClause    ::=    'ORDER' 'BY' OrderCondition+ */
+private void OrderClause() : {} {
+	<ORDER> <BY> ( OrderCondition() )+
+}
+
+/* [17]    OrderCondition    ::=     ( ( 'ASC' | 'DESC' ) BrackettedExpression ) | ( Constraint | Var ) */
+private void OrderCondition() : {
+	boolean asc = true;
+	Expression e; } {
+
+	(
+		( ( "ASC" | "DESC" { asc = false; } ) e=BrackettedExpression() )
+		|
+		( e=Constraint() | e=Var() )
+	) {
+	((SimpleQueryWithSolutionModifier) query).addOrderCondition(new SimpleOrderCondition(e, asc)); }
+}
+
+/* [18]    LimitClause    ::=    'LIMIT' INTEGER */
+private void LimitClause() : {
+	Token t; } {
+
+	<LIMIT> t=<INTEGER> {
+	((SimpleQueryWithSolutionModifier) query).setLimit(Integer.parseInt(t.image)); }
+}
+
+/* [19]    OffsetClause    ::=    'OFFSET' INTEGER */
+private void OffsetClause() : {
+	Token t; } {
+
+	<OFFSET> t=<INTEGER> {
+	((SimpleQueryWithSolutionModifier) query).setOffset(Integer.parseInt(t.image)); }
+}
+
+/* [20]    GroupGraphPattern    ::=    '{' TriplesBlock? ( ( GraphPatternNotTriples | Filter ) '.'? TriplesBlock? )* '}' */
+private GroupGraphPattern GroupGraphPattern() : {
+	GroupGraphPattern groupGraphPattern = new SimpleGroupGraphPattern();
+	Expression constraint; } {
+
+	"{"
+	( TriplesBlock(groupGraphPattern) )?
+	(
+		(
+		GraphPatternNotTriples(groupGraphPattern)
+		|
+		constraint=Filter() {
+		((SimpleGroupGraphPattern) groupGraphPattern).addConstraint(constraint); }
+		)
+
+		(".")?
+
+		(
+		TriplesBlock(groupGraphPattern)
+		)?
+	)*
+	"}" {
+	return groupGraphPattern; }
+}
+
+/* [21]    TriplesBlock    ::=    TriplesSameSubject ( '.' TriplesBlock? )? */
+private void TriplesBlock(GroupGraphPattern groupGraphPattern) : {
+	Set<TriplePattern> triplePatterns; } {
+
+	triplePatterns=TriplesSameSubject() {
+	((SimpleGroupGraphPattern) groupGraphPattern).addTriplePatterns(triplePatterns); }
+
+	( "." (TriplesBlock(groupGraphPattern) )?
+	)?
+}
+
+/* [22]    GraphPatternNotTriples    ::=    OptionalGraphPattern | GroupOrUnionGraphPattern | GraphGraphPattern */
+private void GraphPatternNotTriples(GroupGraphPattern groupGraphPattern) : {} {
+
+	(
+	OptionalGraphPattern(groupGraphPattern)
+	|
+	GroupOrUnionGraphPattern(groupGraphPattern)
+	|
+	GraphGraphPattern(groupGraphPattern)
+	)
+}
+
+/* [23]    OptionalGraphPattern    ::=    'OPTIONAL' GroupGraphPattern */
+private void OptionalGraphPattern(GroupGraphPattern groupGraphPattern) : {
+	GroupGraphPattern optional; } {
+
+	<OPTIONAL>
+	optional=GroupGraphPattern() {
+	((SimpleGroupGraphPattern) groupGraphPattern).addOptionalGraphPattern(optional); }
+}
+
+/* [24]    GraphGraphPattern    ::=    'GRAPH' VarOrIRIref GroupGraphPattern */
+private void GraphGraphPattern(GroupGraphPattern groupGraphPattern) : {
+	UriRefOrVariable graph;
+	GroupGraphPattern g; } {
+
+	<GRAPH>
+	graph=VarOrIRIref()
+	g=GroupGraphPattern() {
+	((SimpleGroupGraphPattern) groupGraphPattern).addGraphPattern(
+		new SimpleGraphGraphPattern(graph, g)); }
+}
+
+/* [25]    GroupOrUnionGraphPattern    ::=    GroupGraphPattern ( 'UNION' GroupGraphPattern )* */
+private void GroupOrUnionGraphPattern(GroupGraphPattern groupGraphPattern) : {
+	GroupGraphPattern g;
+	AlternativeGraphPattern unionGraphPattern = null; } {
+
+	g=GroupGraphPattern()
+	(
+		<UNION> {
+		if (unionGraphPattern == null) {
+			unionGraphPattern = new SimpleAlternativeGraphPattern(g);
+		} }
+		g=GroupGraphPattern() {
+		((SimpleAlternativeGraphPattern) unionGraphPattern).addAlternativeGraphPattern(g); }
+	)* {
+	if (unionGraphPattern != null) {
+		((SimpleGroupGraphPattern) groupGraphPattern).addGraphPattern(unionGraphPattern);
+	} else {
+		((SimpleGroupGraphPattern) groupGraphPattern).addGraphPattern(g);
+	} }
+}
+
+/* [26]    Filter    ::=    'FILTER' Constraint */
+private Expression Filter() : {
+	Expression c; } {
+
+	<FILTER>
+	c=Constraint() {
+	return c; }
+}
+
+/* [27]    Constraint    ::=    BrackettedExpression | BuiltInCall | FunctionCall */
+private Expression Constraint() : {
+	Expression c; } {
+
+    ( c=BrackettedExpression() | c=BuiltInCall() | c=FunctionCall() ) {
+	return c; }
+}
+
+/* [28]    FunctionCall    ::=    IRIref ArgList */
+private FunctionCall FunctionCall() : {
+	IRI name;
+	List<Expression> arguments;} {
+
+	name=IRIref()
+	arguments=ArgList() {
+	return new FunctionCall(name, arguments); }
+}
+
+/* [29]    ArgList    ::=    ( NIL | '(' Expression ( ',' Expression )* ')' ) */
+private List<Expression> ArgList() : {
+	List<Expression> args = new ArrayList<Expression>();
+	Expression e; } {
+
+	(
+		<NIL>
+		|
+		(
+			"("
+			e=Expression() {
+			args.add(e); }
+				( ","
+				e=Expression() {
+				args.add(e); }
+				)*
+			")"
+		)
+	) {
+	return args; }
+}
+
+/* [30]    ConstructTemplate    ::=    '{' ConstructTriples? '}' */
+private Set<TriplePattern> ConstructTemplate() : {
+	Set<TriplePattern> triplePatterns = null; } {
+
+	"{" (
+	triplePatterns=ConstructTriples()
+	)? "}" {
+	return triplePatterns; }
+}
+
+/* [31]    ConstructTriples    ::=    TriplesSameSubject ( '.' ConstructTriples? )? */
+private Set<TriplePattern> ConstructTriples() : {
+	Set<TriplePattern> triplePatterns, t; } {
+
+	triplePatterns=TriplesSameSubject()
+	( "."
+		(
+		t=ConstructTriples() {
+		triplePatterns.addAll(t); }
+		)?
+	)? {
+	return triplePatterns; }
+}
+
+/* [32]    TriplesSameSubject    ::=    VarOrTerm PropertyListNotEmpty |  TriplesNode PropertyList */
+private Set<TriplePattern> TriplesSameSubject() : {
+	Set<TriplePattern> triplePatterns = new LinkedHashSet<TriplePattern>();
+	ResourceOrVariable subject; } {
+
+	( subject=VarOrTerm() PropertyListNotEmpty(subject, triplePatterns) {
+		return triplePatterns; }
+	)
+	|
+	( subject=TriplesNode(triplePatterns) PropertyList(subject, triplePatterns) {
+		return triplePatterns; }
+	)
+}
+
+/* [33]    PropertyListNotEmpty    ::=    Verb ObjectList ( ';' ( Verb ObjectList )? )* */
+private void PropertyListNotEmpty(ResourceOrVariable subject,
+		Set<TriplePattern> triplePatterns) : {
+	UriRefOrVariable predicate;
+	Set<ResourceOrVariable> objects; } {
+	predicate=Verb()
+	objects=ObjectList(triplePatterns) {
+	addTriplePatterns(triplePatterns, subject, predicate, objects); }
+
+	( ";"
+		( predicate=Verb() objects=ObjectList(triplePatterns) {
+			addTriplePatterns(triplePatterns, subject, predicate, objects); }
+		)?
+	)*
+}
+
+/* [34]    PropertyList    ::=    PropertyListNotEmpty? */
+private void PropertyList(ResourceOrVariable subject,
+		Set<TriplePattern> triplePatterns) : { } {
+	( PropertyListNotEmpty(subject, triplePatterns) )?
+}
+
+/* [35]    ObjectList    ::=    Object ( ',' Object )* */
+private Set<ResourceOrVariable> ObjectList(Set<TriplePattern> triplePatterns) : {
+	ResourceOrVariable object; } {
+
+	{
+	Set<ResourceOrVariable> objects = new LinkedHashSet<ResourceOrVariable>();
+	}
+	object=Object(triplePatterns) {
+	objects.add(object); }
+
+	( ","
+		object=Object(triplePatterns) {
+			objects.add(object); }
+	)* {
+	return objects; }
+}
+
+/* [36]    Object    ::=    GraphNode */
+private ResourceOrVariable Object(Set<TriplePattern> triplePatterns) : {
+	ResourceOrVariable object; } {
+
+	object=GraphNode(triplePatterns) {
+	return object; }
+}
+
+/* [37]    Verb    ::=    VarOrIRIref | 'a' */
+private UriRefOrVariable Verb() : {
+	UriRefOrVariable predicate; } {
+
+	predicate=VarOrIRIref() {
+	return predicate; }
+	| "a" {
+	return new UriRefOrVariable(RDF_TYPE); }
+}
+
+// Fill in the specified set of TriplePattern and returns the subject node
+/* [38]    TriplesNode    ::=    Collection |  BlankNodePropertyList */
+private ResourceOrVariable TriplesNode(Set<TriplePattern> triplePatterns) : {
+	ResourceOrVariable subject; } {
+	(
+		subject=Collection(triplePatterns)
+	|
+		subject=BlankNodePropertyList(triplePatterns)
+	) {
+	return subject; }
+}
+
+/* [39]    BlankNodePropertyList    ::=    '[' PropertyListNotEmpty ']' */
+private ResourceOrVariable BlankNodePropertyList(Set<TriplePattern> triplePatterns) : { } {
+	{
+	ResourceOrVariable subject = getNewBNode();
+	}
+	"[" PropertyListNotEmpty(subject, triplePatterns) "]" {
+	return subject; }
+}
+
+/* [40]    Collection    ::=    '(' GraphNode+ ')' */
+private ResourceOrVariable Collection(Set<TriplePattern> triplePatterns) : {
+	ResourceOrVariable node;
+	List<ResourceOrVariable> nodes = new ArrayList<ResourceOrVariable>(); } {
+
+	"("
+		(
+		node=GraphNode(triplePatterns) {
+		nodes.add(node); }
+		)+
+	")" {
+	return addTriplePatterns(triplePatterns, nodes); }
+}
+
+/* [41]    GraphNode    ::=    VarOrTerm |  TriplesNode */
+private ResourceOrVariable GraphNode(Set<TriplePattern> triplePatterns) : {
+	ResourceOrVariable node; } {
+
+	(
+	node=VarOrTerm()
+	|
+	node=TriplesNode(triplePatterns)
+	) {
+	return node; }
+}
+
+/* [42]    VarOrTerm    ::=    Var | GraphTerm */
+private ResourceOrVariable VarOrTerm() : {
+	ResourceOrVariable r;
+	Variable v; } {
+
+    (
+	v=Var() {
+	return new ResourceOrVariable(v); }
+	|
+	r=GraphTerm() {
+	return r; }
+	)
+}
+
+/* [43]    VarOrIRIref    ::=    Var | IRIref */
+private UriRefOrVariable VarOrIRIref() : {
+	Variable var;
+	IRI IRI; } {
+
+	(
+	var=Var() {
+	return new UriRefOrVariable(var); }
+	|
+	IRI=IRIref() {
+	return new UriRefOrVariable(IRI); }
+	)
+}
+
+/* [44]    Var    ::=    VAR1 | VAR2 */
+private Variable Var() : {
+	Token t;} {
+
+	(t=<VAR1> | t=<VAR2>) {
+	return getVariable(t.image); }
+}
+
+/* [45]    GraphTerm    ::=    IRIref |  RDFLiteral |  NumericLiteral |  BooleanLiteral |  BlankNode |  NIL */
+private ResourceOrVariable GraphTerm() : {
+	ResourceOrVariable bNode = null;
+	RDFTerm r = null; } {
+
+	(r=IRIref() | r=RDFLiteral() | r=NumericLiteral() | r=BooleanLiteral() | bNode=BlankNode() | <NIL> {
+		r = RDF_NIL; }) {
+	if (bNode == null) {
+		return new ResourceOrVariable(r);
+	}
+	return bNode; }
+}
+
+/* [46]    Expression    ::=    ConditionalOrExpression */
+private Expression Expression() : {
+	Expression e; } {
+
+	e=ConditionalOrExpression() {
+	return e; }
+}
+
+/* [47]    ConditionalOrExpression    ::=    ConditionalAndExpression ( '||' ConditionalAndExpression )* */
+private Expression ConditionalOrExpression() : {
+	Expression e, ae; } {
+
+	e=ConditionalAndExpression()
+	( "||"
+		ae=ConditionalAndExpression() {
+		e = new BinaryOperation("||", e, ae); }
+	)* {
+	return e; }
+}
+
+/* [48]    ConditionalAndExpression    ::=    ValueLogical ( '&&' ValueLogical )* */
+private Expression ConditionalAndExpression() : {
+	Expression e, e2; } {
+
+	e=ValueLogical()
+	( "&&"
+		e2=ValueLogical() {
+		e = new BinaryOperation("&&", e, e2); }
+	)* {
+	return e; }
+}
+
+/* [49]    ValueLogical    ::=    RelationalExpression */
+private Expression ValueLogical() : {
+	Expression e; } {
+
+	e=RelationalExpression() {
+	return e; }
+}
+
+/* [50]    RelationalExpression    ::=    NumericExpression ( '=' NumericExpression | '!=' NumericExpression | '<' NumericExpression | '>' NumericExpression | '<=' NumericExpression | '>=' NumericExpression )? */
+private Expression RelationalExpression() : {
+	Expression e, e2; } {
+
+	e=NumericExpression()
+	(
+		"=" e2=NumericExpression() {
+			e = new BinaryOperation("=", e, e2); }
+		| "!=" e2=NumericExpression() {
+			e = new BinaryOperation("!=", e, e2); }
+		| "<" e2=NumericExpression() {
+			e = new BinaryOperation("<", e, e2); }
+		| ">" e2=NumericExpression() {
+			e = new BinaryOperation(">", e, e2); }
+		| "<=" e2=NumericExpression() {
+			e = new BinaryOperation("<=", e, e2); }
+		| ">=" e2=NumericExpression() {
+			e = new BinaryOperation(">=", e, e2); }
+	)? {
+	return e; }
+}
+
+/* [51]    NumericExpression    ::=    AdditiveExpression */
+private Expression NumericExpression() : {
+	Expression e; } {
+
+	e=AdditiveExpression() {
+	return e; }
+}
+
+/* [52]    AdditiveExpression    ::=    MultiplicativeExpression ( '+' MultiplicativeExpression | '-' MultiplicativeExpression | NumericLiteralPositive | NumericLiteralNegative )* */
+private Expression AdditiveExpression() : {
+	Expression e, e2;
+	Literal l; } {
+
+	e=MultiplicativeExpression()
+	(
+		"+" e2=MultiplicativeExpression() {
+			e = new BinaryOperation("+", e, e2); }
+		| "-" e2=MultiplicativeExpression() {
+			e = new BinaryOperation("-", e, e2); }
+		| l=NumericLiteralPositive() {
+			e = new BinaryOperation("+", e, new LiteralExpression(l)); }
+		| l=NumericLiteralNegative() {
+			e = new BinaryOperation("-", e, new LiteralExpression(l)); }
+	)* {
+	return e; }
+}
+
+/* [53]    MultiplicativeExpression    ::=    UnaryExpression ( '*' UnaryExpression | '/' UnaryExpression )* */
+private Expression MultiplicativeExpression() : {
+	Expression e, e2; } {
+
+	e=UnaryExpression()
+	(
+		"*" e2=UnaryExpression() {
+			e = new BinaryOperation("*", e, e2); }
+		| "/" e2=UnaryExpression() {
+			e = new BinaryOperation("/", e, e2); }
+	)* {
+	return e; }
+}
+
+/* [54]    UnaryExpression    ::=      '!' PrimaryExpression  |  '+' PrimaryExpression  | '-' PrimaryExpression  | PrimaryExpression */
+private Expression UnaryExpression() : {
+	Expression e; } {
+
+	"!" e=PrimaryExpression() {
+		return new UnaryOperation("!", e); }
+    | "+" e=PrimaryExpression() {
+		return new UnaryOperation("+", e); }
+    | "-" e=PrimaryExpression() {
+		return new UnaryOperation("-", e); }
+    | e=PrimaryExpression() {
+		return e; }
+}
+
+/* [55]    PrimaryExpression    ::=    BrackettedExpression | BuiltInCall | IRIrefOrFunction | RDFLiteral | NumericLiteral | BooleanLiteral | Var */
+private Expression PrimaryExpression() : {
+	Expression e = null;
+	Literal l = null; } {
+
+	(
+	e=BrackettedExpression() | e=BuiltInCall() | e=IRIrefOrFunction() | l=RDFLiteral() | l=NumericLiteral() | l=BooleanLiteral() | e=Var()
+	) {
+	if (l != null) {
+		return new LiteralExpression(l);
+	}
+	return e; }
+}
+
+/* [56]    BrackettedExpression    ::=    '(' Expression ')' */
+private Expression BrackettedExpression() : {
+	Expression e; } {
+
+	"("
+	e=Expression()
+	")" {
+	return e; }
+}
+
+/* [57]    BuiltInCall    ::=      'STR' '(' Expression ')' */
+/* |  'LANG' '(' Expression ')' */
+/* |  'LANGMATCHES' '(' Expression ',' Expression ')' */
+/* |  'DATATYPE' '(' Expression ')' */
+/* |  'BOUND' '(' Var ')' */
+/* |  'sameTerm' '(' Expression ',' Expression ')' */
+/* |  'isIRI' '(' Expression ')' */
+/* |  'isURI' '(' Expression ')' */
+/* |  'isBLANK' '(' Expression ')' */
+/* |  'isLITERAL' '(' Expression ')' */
+/* |  RegexExpression */
+private BuiltInCall BuiltInCall() : {
+	List<Expression> args = new ArrayList<Expression>();
+	String name;
+	Expression e; } {
+	(
+	<STR> {
+		name = "STR"; }
+		"("
+		e=Expression() {
+		args.add(e); }
+		")"
+	| <LANG> {
+		name = "LANG"; }
+		"("
+		e=Expression() {
+		args.add(e); }
+		")"
+	| <LANGMATCHES> {
+		name = "LANGMATCHES"; }
+		"("
+		e=Expression() {
+		args.add(e); }
+		","
+		e=Expression() {
+		args.add(e); }
+		")"
+	| <DATATYPE> {
+		name = "DATATYPE"; }
+		"("
+		e=Expression() {
+		args.add(e); }
+		")"
+	| <BOUND> {
+		name = "BOUND"; }
+		"("
+		e=Var() {
+		args.add(e); }
+		")"
+	| <SAME_TERM> {
+		name = "sameTerm"; }
+		"("
+		e=Expression() {
+		args.add(e); }
+		","
+		e=Expression() {
+		args.add(e); }
+		")"
+	| <IS_IRI> {
+		name = "isIRI"; }
+		"("
+		e=Expression() {
+		args.add(e); }
+		")"
+	| <IS_URI> {
+		name = "isURI"; }
+		"("
+		e=Expression() {
+		args.add(e); }
+		")"
+	| <IS_BLANK> {
+		name = "isBLANK"; }
+		"("
+		e=Expression() {
+		args.add(e); }
+		")"
+	| <IS_LITERAL> {
+		name = "isLITERAL"; }
+		"("
+		e=Expression() {
+		args.add(e); }
+		")"
+	| e=RegexExpression() {
+		return (BuiltInCall) e; }
+	) {
+		return new BuiltInCall(name, args);
+	}
+}
+
+/* [58]    RegexExpression    ::=    'REGEX' '(' Expression ',' Expression ( ',' Expression )? ')' */
+private BuiltInCall RegexExpression() : {
+	List<Expression> args = new ArrayList<Expression>();
+	Expression e = null; } {
+
+	<REGEX>
+	"("
+	e=Expression() {
+	args.add(e); }
+	","
+	e=Expression() {
+	args.add(e); }
+	(
+		","
+		e=Expression() {
+		args.add(e); }
+	)?
+	")" {
+	return new BuiltInCall("REGEX", args); }
+}
+
+/* [59]    IRIrefOrFunction    ::=    IRIref ArgList? */
+private Expression IRIrefOrFunction() : {
+	IRI IRI;
+	List<Expression> args; } {
+
+	IRI=IRIref()
+	(
+		args=ArgList() {
+		return new FunctionCall(IRI, args); }
+	)? {
+	return new UriRefExpression(IRI); }
+}
+
+/* [60]    RDFLiteral    ::=    String ( LANGTAG | ( '^^' IRIref ) )? */
+private Literal RDFLiteral() : {
+	Token t;
+	String s;
+	IRI type; } {
+
+	s = String()
+	(
+		t=<LANGTAG> {
+		return new PlainLiteralImpl(s, new Language(t.image.substring(1))); }
+		|
+		( "^^"
+			type=IRIref() {
+			return new TypedLiteralImpl(s, type); }
+		)
+	)? {
+	return new PlainLiteralImpl(s); }
+}
+
+/* [61]    NumericLiteral    ::=    NumericLiteralUnsigned | NumericLiteralPositive | NumericLiteralNegative */
+private Literal NumericLiteral() : {
+	Literal l; } {
+
+	( l=NumericLiteralUnsigned() | l=NumericLiteralPositive() | l=NumericLiteralNegative() ) {
+	return l; }
+}
+
+/* [62]    NumericLiteralUnsigned    ::=    INTEGER |  DECIMAL |  DOUBLE */
+private Literal NumericLiteralUnsigned() : {
+	Token t; } {
+
+	t=<INTEGER> {
+		return LiteralFactory.getInstance().createTypedLiteral(Long.valueOf(t.image)); }
+	| t=<DECIMAL> {
+		return LiteralFactory.getInstance().createTypedLiteral(Float.valueOf(t.image)); }
+	| t=<DOUBLE> {
+		return LiteralFactory.getInstance().createTypedLiteral(Double.valueOf(t.image)); }
+}
+
+/* [63]    NumericLiteralPositive    ::=    INTEGER_POSITIVE |  DECIMAL_POSITIVE |  DOUBLE_POSITIVE */
+private Literal NumericLiteralPositive() : {
+	Token t; } {
+
+	t=<INTEGER_POSITIVE> {
+		return LiteralFactory.getInstance().createTypedLiteral(Long.valueOf(t.image)); }
+	| t=<DECIMAL_POSITIVE> {
+		return LiteralFactory.getInstance().createTypedLiteral(Float.valueOf(t.image)); }
+	| t=<DOUBLE_POSITIVE> {
+		return LiteralFactory.getInstance().createTypedLiteral(Double.valueOf(t.image)); }
+}
+
+/* [64]    NumericLiteralNegative    ::=    INTEGER_NEGATIVE |  DECIMAL_NEGATIVE |  DOUBLE_NEGATIVE */
+private Literal NumericLiteralNegative() : {
+	Token t; } {
+
+	t=<INTEGER_NEGATIVE> {
+		return LiteralFactory.getInstance().createTypedLiteral(Long.valueOf(t.image)); }
+	| t=<DECIMAL_NEGATIVE> {
+		return LiteralFactory.getInstance().createTypedLiteral(Float.valueOf(t.image)); }
+	| t=<DOUBLE_NEGATIVE> {
+		return LiteralFactory.getInstance().createTypedLiteral(Double.valueOf(t.image)); }
+}
+
+/* [65]    BooleanLiteral    ::=    'true' |  'false' */
+private Literal BooleanLiteral() : {} {
+
+	<TRUE> {
+		return LiteralFactory.getInstance().createTypedLiteral(true); }
+	| <FALSE> {
+		return LiteralFactory.getInstance().createTypedLiteral(false); }
+}
+
+/* [66]    String    ::=    STRING_LITERAL1 | STRING_LITERAL2 | STRING_LITERAL_LONG1 | STRING_LITERAL_LONG2 */
+private String String() : {
+	Token t; } {
+	t=<STRING_LITERAL1> {
+		return unquote(t.image) ; }
+	| t=<STRING_LITERAL2> {
+		return unquote(t.image) ; }
+	| t=<STRING_LITERAL_LONG1> {
+		return unTripleQuote(t.image) ; }
+	| t=<STRING_LITERAL_LONG2> {
+		return unTripleQuote(t.image) ; }
+}
+
+/* [67]    IRIref    ::=    IRI_REF |  PrefixedName */
+private IRI IRIref() : {
+	IRI IRI;
+	Token t; } {
+
+	t=<IRI_REF> {
+	return createUriRef(unquote(t.image)); }
+	|
+	IRI=PrefixedName() {
+	return IRI; }
+}
+
+/* [68]    PrefixedName    ::=    PNAME_LN | PNAME_NS */
+private IRI PrefixedName() : {
+	Token t; } {
+
+	( t=<PNAME_LN> | t=<PNAME_NS> ) {
+	return createUriRef(t.image); }
+}
+
+/* [69]    BlankNode    ::=    BLANK_NODE_LABEL |  ANON */
+private ResourceOrVariable BlankNode() : {
+	Token t; } {
+
+	t=<BLANK_NODE_LABEL> {
+	return getBNode(t.image); }
+	| <ANON> {
+	return getNewBNode(); }
+}
+
+
+TOKEN : {
+  /* [70]    IRI_REF    ::=    '<' ([^<>"{}|^`\]-[#x00-#x20])* '>' */
+  < IRI_REF : "<" ( ~["<", ">", "\"", "{", "}", "|", "^", "`", "\\", "\u0000"-"\u0020"] )* ">" >
+  |
+  /* [71]    PNAME_NS    ::=    PN_PREFIX? ':' */
+  < PNAME_NS : (<PN_PREFIX>)? ":" >
+  |
+  /* [72]    PNAME_LN    ::=    PNAME_NS PN_LOCAL */
+  < PNAME_LN : <PNAME_NS> <PN_LOCAL> >
+  |
+  /* [73]    BLANK_NODE_LABEL    ::=    '_:' PN_LOCAL */
+  < BLANK_NODE_LABEL : "_:" <PN_LOCAL> >
+  |
+  /* [74]    VAR1    ::=    '?' VARNAME */
+  < VAR1 : "?" <VARNAME> >
+  |
+  /* [75]    VAR2    ::=    '$' VARNAME */
+  < VAR2 : "$" <VARNAME> >
+  |
+  /* [76]    LANGTAG    ::=    '@' [a-zA-Z]+ ('-' [a-zA-Z0-9]+)* */
+  < LANGTAG : "@" (["a"-"z", "A"-"Z"])+ ( "-" (["a"-"z", "A"-"Z", "0"-"9"])+ )* >
+}
+
+TOKEN : {
+  < #Z_9 : ["0"-"9"] >
+  |
+  < #Z_9r : (<Z_9>)+ >
+  |
+   < #Z_9o : (<Z_9>)* >
+  |
+  /* [77]    INTEGER    ::=    [0-9]+ */
+  < INTEGER : <Z_9r> >
+  |
+  /* [78]    DECIMAL    ::=    [0-9]+ '.' [0-9]* | '.' [0-9]+ */
+  < DECIMAL : ( <Z_9r> "." <Z_9o> ) | ( "." <Z_9r> ) >
+  |
+  /* [79]    DOUBLE    ::=    [0-9]+ '.' [0-9]* EXPONENT | '.' ([0-9])+ EXPONENT | ([0-9])+ EXPONENT */
+  < DOUBLE : ( <Z_9r> "." <Z_9o>  <EXPONENT> ) | ( "." <Z_9r> <EXPONENT> ) | ( <Z_9r> <EXPONENT> ) >
+  |
+  /* [80]    INTEGER_POSITIVE    ::=    '+' INTEGER */
+  < INTEGER_POSITIVE : "+" <INTEGER> >
+  |
+  /* [81]    DECIMAL_POSITIVE    ::=    '+' DECIMAL */
+  < DECIMAL_POSITIVE : "+" <DECIMAL> >
+  |
+  /* [82]    DOUBLE_POSITIVE    ::=    '+' DOUBLE */
+  < DOUBLE_POSITIVE : "+" <DOUBLE> >
+  |
+  /* [83]    INTEGER_NEGATIVE    ::=    '-' INTEGER */
+  < INTEGER_NEGATIVE : "-" <INTEGER> >
+  |
+  /* [84]    DECIMAL_NEGATIVE    ::=    '-' DECIMAL */
+  < DECIMAL_NEGATIVE : "-" <DECIMAL> >
+  |
+  /* [85]    DOUBLE_NEGATIVE    ::=    '-' DOUBLE */
+  < DOUBLE_NEGATIVE : "-" <DOUBLE> >
+  |
+  /* [86]    EXPONENT    ::=    [eE] [+-]? [0-9]+ */
+  < #EXPONENT : ["e","E"] (["+","-"])? <Z_9r> >
+}
+
+TOKEN : {
+  /* [87]    STRING_LITERAL1    ::=    "'" ( ([^#x27#x5C#xA#xD]) | ECHAR )* "'" */
+  < STRING_LITERAL1 : "'" ( ~["'", "\\", "\r", "\n"] | <ECHAR> )* "'" >
+  |
+  /* [88]    STRING_LITERAL2    ::=    '"' ( ([^#x22#x5C#xA#xD]) | ECHAR )* '"' */
+  < STRING_LITERAL2 : "\"" ( ~["\"", "\\", "\r", "\n"] | <ECHAR> )* "\"" >
+  |
+  /* [89]    STRING_LITERAL_LONG1    ::=    "'''" ( ( "'" | "''" )? ( [^'\] | ECHAR ) )* "'''" */
+  < STRING_LITERAL_LONG1 : "'''" ( ( "'" | "''" )? ( ~["'","\\"] | <ECHAR> ) )* "'''" >
+  |
+  /* [90]    STRING_LITERAL_LONG2    ::=    '"""' ( ( '"' | '""' )? ( [^"\] | ECHAR ) )* '"""' */
+  < STRING_LITERAL_LONG2 : "\"\"\"" ( ( "\"" | "\"\"" )? ( ~["\"","\\"] | <ECHAR> ) )* "\"\"\"" >
+  |
+  /* [91]    #ECHAR    ::=    '\' [tbnrf\"'] */
+  < #ECHAR : "\\" ["t","b","n","r","f","\\","\"","'"] >
+}
+
+TOKEN : {
+  /* [92]    NIL    ::=    '(' WS* ')' */
+  < NIL : "(" (<WS>)* ")" >
+  |
+  /* [93]    WS    ::=    #x20 | #x9 | #xD | #xA */
+  < #WS : " " | "\t" | "\n" | "\r" >
+  |
+  /* [94]   ANON    ::=    '[' WS* ']' */
+  < ANON : "[" (<WS>)* "]" >
+}
+
+TOKEN : {
+  /* [95]   #PN_CHARS_BASE ::=  [A-Z] | [a-z] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x02FF] | [#x0370-#x037D] | [#x037F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] */
+  < #PN_CHARS_BASE : ["A"-"Z", "a"-"z", "\u00C0"-"\u00D6", "\u00D8"-"\u00F6", "\u00F8"-"\u02FF", "\u0370"-"\u037D", "\u037F"-"\u1FFF", "\u200C"-"\u200D", "\u2070"-"\u218F", "\u2C00"-"\u2FEF", "\u3001"-"\uD7FF", "\uF900"-"\uFDCF", "\uFDF0"-"\uFFFD"] >
+  |
+  /* [96]   #PN_CHARS_U    ::=  PN_CHARS_BASE | '_' */
+  < #PN_CHARS_U : <PN_CHARS_BASE> | "_" >
+  |
+  /* [97]   #VARNAME  ::=   ( PN_CHARS_U | [0-9] ) ( PN_CHARS_U | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040] )* */
+  < #VARNAME : (<PN_CHARS_U> | <Z_9>) ( <PN_CHARS_U> | <Z_9> | "\u00b7" | ["\u0300"-"\u036f"] | ["\u203f"-"\u2040"] )* >
+  |
+  /* [98]   #PN_CHARS  ::=  PN_CHARS_U | '-' | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040] */
+  < #PN_CHARS : <PN_CHARS_U> | "-" | <Z_9> | "\u00b7" | ["\u0300"-"\u036f"] | ["\u203f"-"\u2040"] >
+  |
+  /* [99]   PN_PREFIX  ::=  PN_CHARS_BASE ((PN_CHARS|'.')* PN_CHARS)? */
+  < PN_PREFIX : <PN_CHARS_BASE> (( <PN_CHARS> | "." )* <PN_CHARS>)? >
+  |
+  /* [100]  PN_LOCAL  ::=   ( PN_CHARS_U | [0-9] ) ((PN_CHARS|'.')* PN_CHARS)?  */
+  /* Note that SPARQL local names allow leading digits while XML local names do not. */
+  < PN_LOCAL : ( <PN_CHARS_U> | <Z_9> ) (( <PN_CHARS> | "." )* <PN_CHARS>)? >
+}