Search in sources :

Example 21 with BindingSet

use of org.eclipse.rdf4j.query.BindingSet in project rdf4j by eclipse.

the class AbstractSPARQLJSONParser method parseQueryResultInternal.

protected boolean parseQueryResultInternal(InputStream in, boolean attemptParseBoolean, boolean attemptParseTuple) throws IOException, QueryResultParseException, QueryResultHandlerException {
    if (!attemptParseBoolean && !attemptParseTuple) {
        throw new IllegalArgumentException("Internal error: Did not specify whether to parse as either boolean and/or tuple");
    }
    JsonParser jp = JSON_FACTORY.createParser(in);
    boolean result = false;
    if (jp.nextToken() != JsonToken.START_OBJECT) {
        throw new QueryResultParseException("Expected SPARQL Results JSON document to start with an Object", jp.getCurrentLocation().getLineNr(), jp.getCurrentLocation().getColumnNr());
    }
    List<String> varsList = new ArrayList<String>();
    boolean varsFound = false;
    Set<BindingSet> bindings = new HashSet<BindingSet>();
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        final String baseStr = jp.getCurrentName();
        if (baseStr.equals(HEAD)) {
            if (jp.nextToken() != JsonToken.START_OBJECT) {
                throw new QueryResultParseException("Did not find object under " + baseStr + " field", jp.getCurrentLocation().getLineNr(), jp.getCurrentLocation().getColumnNr());
            }
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                final String headStr = jp.getCurrentName();
                if (headStr.equals(VARS)) {
                    if (!attemptParseTuple) {
                        throw new QueryResultParseException("Found tuple results variables when attempting to parse SPARQL Results JSON to boolean result");
                    }
                    if (jp.nextToken() != JsonToken.START_ARRAY) {
                        throw new QueryResultParseException("Expected variable labels to be an array", jp.getCurrentLocation().getLineNr(), jp.getCurrentLocation().getColumnNr());
                    }
                    while (jp.nextToken() != JsonToken.END_ARRAY) {
                        varsList.add(jp.getText());
                    }
                    if (this.handler != null) {
                        handler.startQueryResult(varsList);
                    }
                    varsFound = true;
                    // out now.
                    if (!bindings.isEmpty() && this.handler != null) {
                        for (BindingSet nextBinding : bindings) {
                            handler.handleSolution(nextBinding);
                            handler.endQueryResult();
                        }
                        bindings.clear();
                    }
                } else if (headStr.equals(LINK)) {
                    List<String> linksList = new ArrayList<String>();
                    if (jp.nextToken() != JsonToken.START_ARRAY) {
                        throw new QueryResultParseException("Expected links to be an array", jp.getCurrentLocation().getLineNr(), jp.getCurrentLocation().getColumnNr());
                    }
                    while (jp.nextToken() != JsonToken.END_ARRAY) {
                        linksList.add(jp.getText());
                    }
                    if (this.handler != null) {
                        handler.handleLinks(linksList);
                    }
                } else {
                    throw new QueryResultParseException("Found unexpected object in head field: " + headStr, jp.getCurrentLocation().getLineNr(), jp.getCurrentLocation().getColumnNr());
                }
            }
        } else if (baseStr.equals(RESULTS)) {
            if (!attemptParseTuple) {
                throw new QueryResultParseException("Found tuple results bindings when attempting to parse SPARQL Results JSON to boolean result");
            }
            if (jp.nextToken() != JsonToken.START_OBJECT) {
                throw new QueryResultParseException("Found unexpected token in results object: " + jp.getCurrentName(), jp.getCurrentLocation().getLineNr(), jp.getCurrentLocation().getColumnNr());
            }
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                if (jp.getCurrentName().equals(BINDINGS)) {
                    if (jp.nextToken() != JsonToken.START_ARRAY) {
                        throw new QueryResultParseException("Found unexpected token in bindings object", jp.getCurrentLocation().getLineNr(), jp.getCurrentLocation().getColumnNr());
                    }
                    while (jp.nextToken() != JsonToken.END_ARRAY) {
                        MapBindingSet nextBindingSet = new MapBindingSet();
                        if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
                            throw new QueryResultParseException("Did not find object in bindings array: " + jp.getCurrentName(), jp.getCurrentLocation().getLineNr(), jp.getCurrentLocation().getColumnNr());
                        }
                        while (jp.nextToken() != JsonToken.END_OBJECT) {
                            if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
                                throw new QueryResultParseException("Did not find binding name", jp.getCurrentLocation().getLineNr(), jp.getCurrentLocation().getColumnNr());
                            }
                            final String bindingStr = jp.getCurrentName();
                            if (jp.nextToken() != JsonToken.START_OBJECT) {
                                throw new QueryResultParseException("Did not find object for binding value", jp.getCurrentLocation().getLineNr(), jp.getCurrentLocation().getColumnNr());
                            }
                            String lang = null;
                            String type = null;
                            String datatype = null;
                            String value = null;
                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
                                    throw new QueryResultParseException("Did not find value attribute under " + bindingStr + " field", jp.getCurrentLocation().getLineNr(), jp.getCurrentLocation().getColumnNr());
                                }
                                String fieldName = jp.getCurrentName();
                                // move to the value token
                                jp.nextToken();
                                // set the appropriate state variable
                                if (TYPE.equals(fieldName)) {
                                    type = jp.getText();
                                } else if (XMLLANG.equals(fieldName)) {
                                    lang = jp.getText();
                                } else if (DATATYPE.equals(fieldName)) {
                                    datatype = jp.getText();
                                } else if (VALUE.equals(fieldName)) {
                                    value = jp.getText();
                                } else {
                                    throw new QueryResultParseException("Unexpected field name: " + fieldName, jp.getCurrentLocation().getLineNr(), jp.getCurrentLocation().getColumnNr());
                                }
                            }
                            nextBindingSet.addBinding(bindingStr, parseValue(type, value, lang, datatype));
                        }
                        // bindings state
                        if (!varsFound) {
                            // Buffer the bindings to fit with the
                            // QueryResultHandler contract so that startQueryResults
                            // is
                            // always called before handleSolution
                            bindings.add(nextBindingSet);
                        } else if (handler != null) {
                            handler.handleSolution(nextBindingSet);
                        }
                    }
                    if (handler != null) {
                        handler.endQueryResult();
                    }
                } else // SPARQL spec
                if (jp.getCurrentName().equals(DISTINCT) || jp.getCurrentName().equals(ORDERED)) {
                    jp.nextToken();
                } else {
                    throw new QueryResultParseException("Found unexpected field in results: " + jp.getCurrentName(), jp.getCurrentLocation().getLineNr(), jp.getCurrentLocation().getColumnNr());
                }
            }
        } else if (baseStr.equals(BOOLEAN)) {
            if (!attemptParseBoolean) {
                throw new QueryResultParseException("Found boolean results when attempting to parse SPARQL Results JSON to tuple results");
            }
            jp.nextToken();
            result = Boolean.parseBoolean(jp.getText());
            if (handler != null) {
                handler.handleBoolean(result);
            }
        } else {
            throw new QueryResultParseException("Found unexpected object in top level " + baseStr + " field", jp.getCurrentLocation().getLineNr(), jp.getCurrentLocation().getColumnNr());
        }
    }
    return result;
}
Also used : QueryResultParseException(org.eclipse.rdf4j.query.resultio.QueryResultParseException) BindingSet(org.eclipse.rdf4j.query.BindingSet) MapBindingSet(org.eclipse.rdf4j.query.impl.MapBindingSet) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) MapBindingSet(org.eclipse.rdf4j.query.impl.MapBindingSet) JsonParser(com.fasterxml.jackson.core.JsonParser) HashSet(java.util.HashSet)

Example 22 with BindingSet

use of org.eclipse.rdf4j.query.BindingSet in project rdf4j by eclipse.

the class MutableTupleQueryResult method next.

@Override
public BindingSet next() {
    if (hasNext()) {
        BindingSet result = get(currentIndex);
        lastReturned = currentIndex;
        currentIndex++;
        return result;
    }
    throw new NoSuchElementException();
}
Also used : BindingSet(org.eclipse.rdf4j.query.BindingSet) NoSuchElementException(java.util.NoSuchElementException)

Example 23 with BindingSet

use of org.eclipse.rdf4j.query.BindingSet in project rdf4j by eclipse.

the class SPARQLJSONTupleTest method testBindings1.

@Test
public void testBindings1() throws Exception {
    SPARQLResultsJSONParser parser = new SPARQLResultsJSONParser(SimpleValueFactory.getInstance());
    QueryResultCollector handler = new QueryResultCollector();
    parser.setQueryResultHandler(handler);
    InputStream stream = this.getClass().getResourceAsStream("/sparqljson/bindings1.srj");
    assertNotNull("Could not find test resource", stream);
    parser.parseQueryResult(stream);
    // there must be two variables
    assertEquals(2, handler.getBindingNames().size());
    // first must be called "book", the second "title"
    assertEquals("book", handler.getBindingNames().get(0));
    assertEquals("title", handler.getBindingNames().get(1));
    // should be 7 solutions alltogether
    assertEquals(7, handler.getBindingSets().size());
    // Results are ordered, so first should be book6
    assertEquals("http://example.org/book/book6", handler.getBindingSets().get(0).getValue("book").stringValue());
    for (BindingSet b : handler.getBindingSets()) {
        assertNotNull(b.getValue("book"));
        assertNotNull(b.getValue("title"));
        assertTrue(b.getValue("book") instanceof IRI);
        assertTrue(b.getValue("title") instanceof Literal);
        IRI book = (IRI) b.getValue("book");
        if (book.stringValue().equals("http://example.org/book/book6")) {
            assertEquals("Harry Potter and the Half-Blood Prince", b.getValue("title").stringValue());
        } else if (book.stringValue().equals("http://example.org/book/book7")) {
            assertEquals("Harry Potter and the Deathly Hallows", b.getValue("title").stringValue());
        } else if (book.stringValue().equals("http://example.org/book/book5")) {
            assertEquals("Harry Potter and the Order of the Phoenix", b.getValue("title").stringValue());
        } else if (book.stringValue().equals("http://example.org/book/book4")) {
            assertEquals("Harry Potter and the Goblet of Fire", b.getValue("title").stringValue());
        } else if (book.stringValue().equals("http://example.org/book/book2")) {
            assertEquals("Harry Potter and the Chamber of Secrets", b.getValue("title").stringValue());
        } else if (book.stringValue().equals("http://example.org/book/book3")) {
            assertEquals("Harry Potter and the Prisoner Of Azkaban", b.getValue("title").stringValue());
        } else if (book.stringValue().equals("http://example.org/book/book1")) {
            assertEquals("Harry Potter and the Philosopher's Stone", b.getValue("title").stringValue());
        } else {
            fail("Found unexpected binding set in result: " + b.toString());
        }
    }
}
Also used : BindingSet(org.eclipse.rdf4j.query.BindingSet) IRI(org.eclipse.rdf4j.model.IRI) SPARQLResultsJSONParser(org.eclipse.rdf4j.query.resultio.sparqljson.SPARQLResultsJSONParser) InputStream(java.io.InputStream) Literal(org.eclipse.rdf4j.model.Literal) QueryResultCollector(org.eclipse.rdf4j.query.resultio.helpers.QueryResultCollector) AbstractQueryResultIOTupleTest(org.eclipse.rdf4j.query.resultio.AbstractQueryResultIOTupleTest) Test(org.junit.Test)

Example 24 with BindingSet

use of org.eclipse.rdf4j.query.BindingSet in project rdf4j by eclipse.

the class SPARQLCSVTupleBackgroundTest method matchBindingSets.

private boolean matchBindingSets(List<? extends BindingSet> queryResult1, Iterable<? extends BindingSet> queryResult2, Map<BNode, BNode> bNodeMapping, int idx) {
    boolean result = false;
    if (idx < queryResult1.size()) {
        BindingSet bs1 = queryResult1.get(idx);
        List<BindingSet> matchingBindingSets = findMatchingBindingSets(bs1, queryResult2, bNodeMapping);
        for (BindingSet bs2 : matchingBindingSets) {
            // Map bNodes in bs1 to bNodes in bs2
            Map<BNode, BNode> newBNodeMapping = new HashMap<BNode, BNode>(bNodeMapping);
            for (Binding binding : bs1) {
                if (binding.getValue() instanceof BNode) {
                    newBNodeMapping.put((BNode) binding.getValue(), (BNode) bs2.getValue(binding.getName()));
                }
            }
            // FIXME: this recursive implementation has a high risk of
            // triggering a stack overflow
            // Enter recursion
            result = matchBindingSets(queryResult1, queryResult2, newBNodeMapping, idx + 1);
            if (result == true) {
                // models match, look no further
                break;
            }
        }
    } else {
        // All statements have been mapped successfully
        result = true;
    }
    return result;
}
Also used : Binding(org.eclipse.rdf4j.query.Binding) BindingSet(org.eclipse.rdf4j.query.BindingSet) BNode(org.eclipse.rdf4j.model.BNode) HashMap(java.util.HashMap)

Example 25 with BindingSet

use of org.eclipse.rdf4j.query.BindingSet in project rdf4j by eclipse.

the class SPARQLCSVTupleTest method matchBindingSets.

private boolean matchBindingSets(List<? extends BindingSet> queryResult1, Iterable<? extends BindingSet> queryResult2, Map<BNode, BNode> bNodeMapping, int idx) {
    boolean result = false;
    if (idx < queryResult1.size()) {
        BindingSet bs1 = queryResult1.get(idx);
        List<BindingSet> matchingBindingSets = findMatchingBindingSets(bs1, queryResult2, bNodeMapping);
        for (BindingSet bs2 : matchingBindingSets) {
            // Map bNodes in bs1 to bNodes in bs2
            Map<BNode, BNode> newBNodeMapping = new HashMap<BNode, BNode>(bNodeMapping);
            for (Binding binding : bs1) {
                if (binding.getValue() instanceof BNode) {
                    newBNodeMapping.put((BNode) binding.getValue(), (BNode) bs2.getValue(binding.getName()));
                }
            }
            // FIXME: this recursive implementation has a high risk of
            // triggering a stack overflow
            // Enter recursion
            result = matchBindingSets(queryResult1, queryResult2, newBNodeMapping, idx + 1);
            if (result == true) {
                // models match, look no further
                break;
            }
        }
    } else {
        // All statements have been mapped successfully
        result = true;
    }
    return result;
}
Also used : Binding(org.eclipse.rdf4j.query.Binding) BindingSet(org.eclipse.rdf4j.query.BindingSet) BNode(org.eclipse.rdf4j.model.BNode) HashMap(java.util.HashMap)

Aggregations

BindingSet (org.eclipse.rdf4j.query.BindingSet)28 ArrayList (java.util.ArrayList)9 IRI (org.eclipse.rdf4j.model.IRI)8 Value (org.eclipse.rdf4j.model.Value)8 QueryEvaluationException (org.eclipse.rdf4j.query.QueryEvaluationException)6 TupleQueryResult (org.eclipse.rdf4j.query.TupleQueryResult)6 RepositoryException (org.eclipse.rdf4j.repository.RepositoryException)6 IOException (java.io.IOException)5 Literal (org.eclipse.rdf4j.model.Literal)5 Binding (org.eclipse.rdf4j.query.Binding)5 ListBindingSet (org.eclipse.rdf4j.query.impl.ListBindingSet)5 InputStream (java.io.InputStream)4 BNode (org.eclipse.rdf4j.model.BNode)4 AbstractQueryResultIOTupleTest (org.eclipse.rdf4j.query.resultio.AbstractQueryResultIOTupleTest)4 QueryResultCollector (org.eclipse.rdf4j.query.resultio.helpers.QueryResultCollector)4 SPARQLResultsJSONParser (org.eclipse.rdf4j.query.resultio.sparqljson.SPARQLResultsJSONParser)4 Test (org.junit.Test)4 Resource (org.eclipse.rdf4j.model.Resource)3 Var (org.eclipse.rdf4j.query.algebra.Var)3 InputStreamReader (java.io.InputStreamReader)2