VIVO-1248 extend SparqlQueryRunner, and combine with older attempts. (#45)

* Ignore artifacts that Eclipse creates.

* VIVO-1248 Create the utils.sparqlrunner package.

This is a merge of most of the edu.cornell.mannlib.vitro.webapp.utils.sparql package with
edu.cornell.mannlib.vitro.webapp.utils.SparqlQueryRunner

Remove the references to those classes.

* VIVO-1248 extend SparqlQueryRunner, and combine with older attempts.
This commit is contained in:
Jim Blake 2017-01-03 13:16:22 -05:00 committed by GitHub
parent a8ec633f71
commit 9cd5a1329a
31 changed files with 1799 additions and 438 deletions

View file

@ -31,6 +31,11 @@ public class ModelUtilitiesTestHelper {
createResource(classUri));
}
public static Statement objectProperty(String subjectUri, String propertyUri) {
return createStatement(createResource(subjectUri),
createProperty(propertyUri), createResource());
}
public static Statement objectProperty(String subjectUri,
String propertyUri, String objectUri) {
return createStatement(createResource(subjectUri),

View file

@ -16,7 +16,6 @@ import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Level;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
@ -29,7 +28,6 @@ import org.apache.jena.rdf.model.ModelFactory;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.controller.accounts.manageproxies.ProxyRelationshipSelectionCriteria.ProxyRelationshipView;
import edu.cornell.mannlib.vitro.webapp.controller.accounts.manageproxies.ProxyRelationshipSelector.Context;
import edu.cornell.mannlib.vitro.webapp.utils.SparqlQueryRunner;
/**
* TODO

View file

@ -1,92 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils;
import static org.junit.Assert.*;
import static edu.cornell.mannlib.vitro.webapp.utils.SparqlQueryRunner.*;
import org.junit.Test;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
/**
* For now, just test the methods that manipulate the query string.
*/
public class SparqlQueryRunnerTest extends AbstractTestClass {
@Test
public void bindValuesNameNotFound() {
String raw = "No such name here";
String expected = raw;
assertEquals(expected, bindValues(raw, uriValue("bogus", "BOGUS")));
}
@Test
public void bindOneUri() {
String raw = "Replace both ?this and ?this also.";
String expected = "Replace both <URI> and <URI> also.";
assertEquals(expected, bindValues(raw, uriValue("this", "URI")));
}
@Test
public void bindTwoUris() {
String raw = "Replace both ?this and ?that also.";
String expected = "Replace both <URI> and <ANOTHER> also.";
assertEquals(
expected,
bindValues(raw, uriValue("this", "URI"),
uriValue("that", "ANOTHER")));
}
@Test
public void honorWordBoundary() {
String raw = "Replace ?this but not ?thistle.";
String expected = "Replace <URI> but not ?thistle.";
assertEquals(expected, bindValues(raw, uriValue("this", "URI")));
}
@Test
public void honorStringLimit() {
String raw = "?this";
String expected = "<URI>";
assertEquals(expected, bindValues(raw, uriValue("this", "URI")));
}
private static final String REAL_WORLD_RAW = "" //
+ "PREFIX : <http://vitro.mannlib.cornell.edu/ns/vitro/ApplicationConfiguration#> \n" //
+ "\n" //
+ "SELECT DISTINCT ?context ?config \n" //
+ "WHERE { \n" //
+ " ?context a :ConfigContext ; \n" //
+ " :configContextFor ?baseUri ; \n" //
+ " :qualifiedByDomain ?domainUri ; \n" //
+ " :qualifiedBy ?rangeUri ; \n" //
+ " :hasConfiguration ?config . \n" //
+ "} \n"; //
private static final String REAL_WORLD_EXPECTED = "" //
+ "PREFIX : <http://vitro.mannlib.cornell.edu/ns/vitro/ApplicationConfiguration#> \n" //
+ "\n" //
+ "SELECT DISTINCT ?context ?config \n" //
+ "WHERE { \n" //
+ " ?context a :ConfigContext ; \n" //
+ " :configContextFor <http://vivoweb.org/ontology/core#relates> ; \n" //
+ " :qualifiedByDomain <http://vivoweb.org/ontology/core#Contract> ; \n" //
+ " :qualifiedBy <http://vivoweb.org/ontology/core#ResearcherRole> ; \n" //
+ " :hasConfiguration ?config . \n" //
+ "} \n"; //
@Test
public void realWorldExample() {
assertEquals(
REAL_WORLD_EXPECTED,
bindValues(
REAL_WORLD_RAW,
uriValue("baseUri",
"http://vivoweb.org/ontology/core#relates"),
uriValue("domainUri",
"http://vivoweb.org/ontology/core#Contract"),
uriValue("rangeUri",
"http://vivoweb.org/ontology/core#ResearcherRole")));
}
}

View file

@ -0,0 +1,155 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.sparqlrunner;
import static org.junit.Assert.*;
import org.junit.Test;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
/**
* Check the functionality of QueryHolder.
*/
public class QueryHolderTest extends AbstractTestClass {
private static final String SOME_URI = "http://some.uri/";
private static final String SOME_LITERAL = "abracadabra";
private static final String FIND_ONCE = "SELECT ?s ?p WHERE { ?s ?p ?bindMe }";
private static final String URI_BOUND_ONCE = "SELECT ?s ?p WHERE { ?s ?p <"
+ SOME_URI + "> }";
private static final String LITERAL_BOUND_ONCE = "SELECT ?s ?p WHERE { ?s ?p \""
+ SOME_LITERAL + "\" }";
private static final String FIND_TWICE = "CONSTRUCT { ?s ?p ?find_twice } WHERE { ?s ?p ?find_twice }";
private static final String URI_BOUND_TWICE = "CONSTRUCT { ?s ?p <"
+ SOME_URI + "> } WHERE { ?s ?p <" + SOME_URI + "> }";
private static final String LITERAL_BOUND_TWICE = "CONSTRUCT { ?s ?p \""
+ SOME_LITERAL + "\" } WHERE { ?s ?p \"" + SOME_LITERAL + "\" }";
private static final String SQUEEZED = "CONSTRUCT {?s ?p ?squeeze} WHERE {?s ?p ?squeeze}";
private static final String URI_BOUND_SQUEEZED = "CONSTRUCT {?s ?p <"
+ SOME_URI + ">} WHERE {?s ?p <" + SOME_URI + ">}";
private static final String LITERAL_BOUND_SQUEEZED = "CONSTRUCT {?s ?p \""
+ SOME_LITERAL + "\"} WHERE {?s ?p \"" + SOME_LITERAL + "\"}";
private static final String FIND_IN_SELECT_CLAUSE = "SELECT ?s ?p ?bindMe WHERE { ?s ?p ?bindMe }";
private static final String URI_BOUND_IN_SELECT_CLAUSE = "SELECT ?s ?p ?bindMe WHERE { ?s ?p <"
+ SOME_URI + "> }";
// ----------------------------------------------------------------------
// The tests
// ----------------------------------------------------------------------
@Test
public void hasVariable_findsOne() {
assertTrue(new QueryHolder(FIND_ONCE).hasVariable("bindMe"));
}
@Test
public void hasVariable_findsTwo() {
assertTrue(new QueryHolder(FIND_TWICE).hasVariable("find_twice"));
}
@Test
public void hasVariable_doesntFindOne() {
assertFalse(new QueryHolder(FIND_TWICE).hasVariable("notThere"));
}
@Test
public void hasVariable_notFooledByExtendedName() {
assertFalse(new QueryHolder(FIND_ONCE).hasVariable("bind"));
}
@Test
public void hasVariable_notFooledByPunctuation() {
assertTrue(new QueryHolder(SQUEEZED).hasVariable("squeeze"));
}
@Test
public void bindToUri_notFound_noComplaint() {
bindToUri(FIND_ONCE, "notThere", SOME_URI).yields(FIND_ONCE);
}
@Test
public void bindToUri_findsOne_bindsIt() {
bindToUri(FIND_ONCE, "bindMe", SOME_URI).yields(URI_BOUND_ONCE);
}
@Test
public void bindToUri_findsTwo_bindsBoth() {
bindToUri(FIND_TWICE, "find_twice", SOME_URI).yields(URI_BOUND_TWICE);
}
@Test
public void bindToUri_notFooledByExtendedName() {
bindToUri(FIND_ONCE, "bind", SOME_URI).yields(FIND_ONCE);
}
@Test
public void bindToUri_notFooledByPunctuation() {
bindToUri(SQUEEZED, "squeeze", SOME_URI).yields(URI_BOUND_SQUEEZED);
}
@Test
public void bindToPlainLiteral_notFound_noComplaint() {
bindToLiteral(FIND_ONCE, "notThere", SOME_LITERAL).yields(FIND_ONCE);
}
@Test
public void bindToPlainLiteral_findsOne_bindsIt() {
bindToLiteral(FIND_ONCE, "bindMe", SOME_LITERAL)
.yields(LITERAL_BOUND_ONCE);
}
@Test
public void bindToPlainLiteral_findsTwo_bindsBoth() {
bindToLiteral(FIND_TWICE, "find_twice", SOME_LITERAL)
.yields(LITERAL_BOUND_TWICE);
}
@Test
public void bindToPlainLiteral_notFooledByExtendedName() {
bindToLiteral(FIND_ONCE, "bind", SOME_LITERAL).yields(FIND_ONCE);
}
@Test
public void bindToPlainLiteral_notFooledByPunctuation() {
bindToLiteral(SQUEEZED, "squeeze", SOME_LITERAL)
.yields(LITERAL_BOUND_SQUEEZED);
}
@Test
public void variableInSelectClauseIsLeftAlone() {
bindToUri(FIND_IN_SELECT_CLAUSE, "bindMe", SOME_URI)
.yields(URI_BOUND_IN_SELECT_CLAUSE);
}
// ----------------------------------------------------------------------
// Helper methods and classes
// ----------------------------------------------------------------------
private Yielder bindToUri(String query, String name, String uri) {
QueryHolder holder = new QueryHolder(query);
QueryHolder bound = holder.bindToUri(name, uri);
return new Yielder(bound.getQueryString());
}
private Yielder bindToLiteral(String query, String name, String value) {
QueryHolder holder = new QueryHolder(query);
QueryHolder bound = holder.bindToPlainLiteral(name, value);
return new Yielder(bound.getQueryString());
}
private class Yielder {
private final String actual;
public Yielder(String actual) {
this.actual = actual;
}
void yields(String expected) {
assertEquals(expected, actual);
}
}
}

View file

@ -0,0 +1,331 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.sparqlrunner;
import static edu.cornell.mannlib.vitro.testing.ModelUtilitiesTestHelper.dataProperty;
import static edu.cornell.mannlib.vitro.testing.ModelUtilitiesTestHelper.model;
import static edu.cornell.mannlib.vitro.testing.ModelUtilitiesTestHelper.objectProperty;
import static org.apache.jena.datatypes.xsd.XSDDatatype.XSDinteger;
import static org.apache.jena.datatypes.xsd.XSDDatatype.XSDlong;
import static org.junit.Assert.assertEquals;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Model;
import org.apache.log4j.Level;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
public class ResultSetParserTest extends AbstractTestClass {
private static final String NAMESPACE = "http://namespace#";
private static final String SUBJECT = NAMESPACE + "subject";
private static final String PREDICATE_URI = NAMESPACE + "uri";
private static final String OBJECT_URI = NAMESPACE + "objectUri";
private static final String OBJECT_URI_DEFAULT = NAMESPACE
+ "objectUriDefault";
private static final String PREDICATE_ANON = NAMESPACE + "anonymous";
private static final String OBJECT_ANON_DEFAULT = NAMESPACE + "anonDefault";
private static final String PREDICATE_STRING = NAMESPACE + "string";
private static final String OBJECT_STRING = "objectString";
private static final String OBJECT_STRING_DEFAULT = "objectStringDefault";
private static final String PREDICATE_INT = NAMESPACE + "int";
private static final Integer OBJECT_INT = 4;
private static final Integer OBJECT_INT_DEFAULT = -1;
private static final String PREDICATE_LONG = NAMESPACE + "long";
private static final Long OBJECT_LONG = 888L;
private static final Long OBJECT_LONG_DEFAULT = -333L;
private static final Object PARSING_FAILURE = "PARSING_FAILURE";
private static final Object NO_RECORDS_FOUND = "NO_RECORDS_FOUND";
private static final String SELECT_QUERY = "" //
+ "SELECT ?uri ?anonymous ?string ?int ?long \n" //
+ "WHERE { \n" //
+ " ?s <" + PREDICATE_URI + "> ?uri . \n" //
+ " ?s <" + PREDICATE_ANON + "> ?anon . \n" //
+ " ?s <" + PREDICATE_STRING + "> ?string . \n" //
+ " ?s <" + PREDICATE_INT + "> ?int . \n" //
+ " ?s <" + PREDICATE_LONG + "> ?long . \n" //
+ "} \n";
private Model model;
@Before
public void setup() {
setLoggerLevel(ModelSelectQueryContext.class, Level.OFF);
model = model(objectProperty(SUBJECT, PREDICATE_URI, OBJECT_URI),
objectProperty(SUBJECT, PREDICATE_ANON),
dataProperty(SUBJECT, PREDICATE_STRING, OBJECT_STRING),
dataProperty(SUBJECT, PREDICATE_INT, OBJECT_INT, XSDinteger),
dataProperty(SUBJECT, PREDICATE_LONG, OBJECT_LONG, XSDlong));
}
// ----------------------------------------------------------------------
// The tests
// ----------------------------------------------------------------------
@Test
public void errorInParse_yieldsDefaultValue() {
assertParsingResult(PARSING_FAILURE, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
throw new RuntimeException("I refuse to parse this!");
}
});
}
// ----------------------------------------------------------------------
@Test
public void expectedUriFoundUri() {
assertParsingResult(OBJECT_URI, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifResourcePresent(solution, "uri", OBJECT_URI_DEFAULT);
}
});
}
@Test
public void expectedUriFoundNothing_returnsDefault() {
assertParsingResult(OBJECT_URI_DEFAULT, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifResourcePresent(solution, "nothing",
OBJECT_URI_DEFAULT);
}
});
}
/**
* TODO Ignoring because the anonymous node isn't showing up in the
* ResultSet. Why not? Anyway, this behaves like "foundNothing".
*/
@Test
@Ignore
public void expectedUriFoundAnonymous_returnsDefault() {
assertParsingResult(OBJECT_URI_DEFAULT, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifResourcePresent(solution, "anon", OBJECT_URI_DEFAULT);
}
});
}
@Test
public void expectedUriFoundString_returnsDefault() {
assertParsingResult(OBJECT_URI_DEFAULT, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifResourcePresent(solution, "string", OBJECT_URI_DEFAULT);
}
});
}
// ----------------------------------------------------------------------
@Test
public void expectedStringFoundString() {
assertParsingResult(OBJECT_STRING, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifLiteralPresent(solution, "string",
OBJECT_STRING_DEFAULT);
}
});
}
@Test
public void expectedStringFoundNothing_returnsDefault() {
assertParsingResult(OBJECT_STRING_DEFAULT, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifLiteralPresent(solution, "nothing",
OBJECT_STRING_DEFAULT);
}
});
}
@Test
public void expectedStringFoundResource_fails() {
assertParsingResult(PARSING_FAILURE, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifLiteralPresent(solution, "uri", OBJECT_STRING_DEFAULT);
}
});
}
@Test
public void expectedStringFoundInt_returnsStringValueOfInt() {
assertParsingResult(OBJECT_INT.toString(), new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifLiteralPresent(solution, "int", OBJECT_STRING_DEFAULT);
}
});
}
// ----------------------------------------------------------------------
@Test
public void expectedIntFoundInt() {
assertParsingResult(OBJECT_INT, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifIntPresent(solution, "int", OBJECT_INT_DEFAULT);
}
});
}
@Test
public void expectedIntFoundNothing() {
assertParsingResult(OBJECT_INT_DEFAULT, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifIntPresent(solution, "nothing", OBJECT_INT_DEFAULT);
}
});
}
@Test
public void expectedIntFoundResource_fails() {
assertParsingResult(PARSING_FAILURE, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifIntPresent(solution, "uri", OBJECT_INT_DEFAULT);
}
});
}
@Test
public void expectedIntFoundString_fails() {
assertParsingResult(PARSING_FAILURE, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifIntPresent(solution, "string", OBJECT_INT_DEFAULT);
}
});
}
@Test
public void expectedIntFoundLong() {
assertParsingResult(new Integer(OBJECT_LONG.intValue()),
new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifIntPresent(solution, "long",
OBJECT_INT_DEFAULT);
}
});
}
// ----------------------------------------------------------------------
@Test
public void expectedLongFoundLong() {
assertParsingResult(OBJECT_LONG, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifLongPresent(solution, "long", OBJECT_LONG_DEFAULT);
}
});
}
@Test
public void expectedLongFoundNothing() {
assertParsingResult(OBJECT_LONG_DEFAULT, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifLongPresent(solution, "nothing", OBJECT_LONG_DEFAULT);
}
});
}
@Test
public void expectedLongFoundResource_fails() {
assertParsingResult(PARSING_FAILURE, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifLongPresent(solution, "uri", OBJECT_LONG_DEFAULT);
}
});
}
@Test
public void expectedLongFoundString_fails() {
assertParsingResult(PARSING_FAILURE, new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifLongPresent(solution, "string", OBJECT_LONG_DEFAULT);
}
});
}
@Test
public void expectedLongFoundInt() {
assertParsingResult(new Long(OBJECT_INT), new BaseParser() {
@Override
Object parseOneLine(QuerySolution solution) {
return ifLongPresent(solution, "int", OBJECT_LONG_DEFAULT);
}
});
}
/**
* <pre>
* ifLongPresent, return value or default.
* present, absent
* </pre>
*/
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private void assertParsingResult(Object expected, BaseParser parser) {
Object actual = SparqlQueryRunner
.createSelectQueryContext(model, SELECT_QUERY).execute()
.parse(parser);
assertEquals(expected, actual);
}
private abstract static class BaseParser extends ResultSetParser<Object> {
@Override
protected Object defaultValue() {
return PARSING_FAILURE;
}
@Override
protected Object parseResults(String queryStr, ResultSet results) {
if (results.hasNext()) {
return parseOneLine(results.next());
} else {
return NO_RECORDS_FOUND;
}
}
abstract Object parseOneLine(QuerySolution solution);
}
// private String dumpSolution(QuerySolution solution) {
// Map<String, Object> fields = new HashMap<>();
// Iterator<String> names = solution.varNames();
// while (names.hasNext()) {
// String name = names.next();
// fields.put(name, solution.get(name));
// }
// return fields.toString();
// }
//
}

View file

@ -0,0 +1,170 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.sparqlrunner;
import static edu.cornell.mannlib.vitro.testing.ModelUtilitiesTestHelper.dataProperty;
import static edu.cornell.mannlib.vitro.testing.ModelUtilitiesTestHelper.model;
import static edu.cornell.mannlib.vitro.webapp.utils.sparqlrunner.SparqlQueryRunner.createConstructQueryContext;
import static edu.cornell.mannlib.vitro.webapp.utils.sparqlrunner.SparqlQueryRunner.createSelectQueryContext;
import static edu.cornell.mannlib.vitro.webapp.utils.sparqlrunner.SparqlQueryRunner.queryHolder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import org.apache.jena.atlas.json.JSON;
import org.apache.jena.atlas.json.JsonObject;
import org.apache.jena.rdf.model.Model;
import org.junit.Before;
import org.junit.Test;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.jena.model.RDFServiceModel;
/**
* Top-level smoke tests for the SparqlQueryRunnerTest. Exercise all of the
* methods that create contexts, and show that we can do the simplest of
* operations against them.
*/
public class SparqlQueryRunnerTest extends AbstractTestClass {
private static final String SUBJECT_URI = "http://namespace/subject_uri";
private static final String PREDICATE_URI = "http://namespace/predicate_uri";
private static final String OBJECT_VALUE = "object_value";
private static final String SELECT_QUERY = "SELECT ?s ?p ?o WHERE { ?s ?p ?o . }";
private static final JsonObject EXPECTED_SELECT_RESULTS = JSON.parse(""
+ "{ " //
+ " 'head' : { " //
+ " 'vars' : [ 's', 'p', 'o' ] " //
+ " } , " //
+ " 'results' : { " //
+ " 'bindings' : [ " //
+ " { " //
+ " 'p' : { " //
+ " 'type' : 'uri' , " //
+ " 'value' : 'http://namespace/predicate_uri' " //
+ " } , " //
+ " 'o' : { " //
+ " 'type' : 'literal' , " //
+ " 'value' : 'object_value' " //
+ " } , " //
+ " 's' : { " //
+ " 'type' : 'uri' , " //
+ " 'value' : 'http://namespace/subject_uri' " //
+ " } " //
+ " } " //
+ " ] " //
+ " } " //
+ "} ");
private static final String CONSTRUCT_QUERY = "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }";
private Model model;
private RDFService rdfService;
private ByteArrayOutputStream buffer;
private Model constructed;
@Before
public void setup() {
model = model(dataProperty(SUBJECT_URI, PREDICATE_URI, OBJECT_VALUE));
rdfService = new RDFServiceModel(model);
buffer = new ByteArrayOutputStream();
}
// ----------------------------------------------------------------------
// SELECT tests
// ----------------------------------------------------------------------
@Test
public void selectQueryAgainstModel() {
createSelectQueryContext(model, SELECT_QUERY).execute().writeToOutput(
buffer);
assertExpectedSelectResults();
}
@Test
public void selectQueryHolderAgainstModel() {
createSelectQueryContext(model, queryHolder(SELECT_QUERY)).execute()
.writeToOutput(buffer);
assertExpectedSelectResults();
}
@Test
public void selectQueryAgainstRDFService() {
createSelectQueryContext(rdfService, SELECT_QUERY).execute()
.writeToOutput(buffer);
assertExpectedSelectResults();
}
@Test
public void selectQueryHolderAgainstRDFService() {
createSelectQueryContext(rdfService, queryHolder(SELECT_QUERY))
.execute().writeToOutput(buffer);
assertExpectedSelectResults();
}
/**
* We've shown that all select contexts work. It should suffice that one of
* them can convert to string fields.
*/
@Test
public void selectToStringFields() {
List<String> objectValues = createSelectQueryContext(model,
SELECT_QUERY).execute().toStringFields("o").flatten();
assertEquals(Arrays.asList(OBJECT_VALUE), objectValues);
}
// ----------------------------------------------------------------------
// CONSTRUCT tests
// ----------------------------------------------------------------------
@Test
public void constructQueryAgainstModel() {
constructed = createConstructQueryContext(model, CONSTRUCT_QUERY)
.execute().toModel();
assertExpectedConstructResults();
}
@Test
public void constructQueryHolderAgainstModel() {
constructed = createConstructQueryContext(model,
queryHolder(CONSTRUCT_QUERY)).execute().toModel();
assertExpectedConstructResults();
}
@Test
public void constructQueryAgainstRDFService() {
constructed = createConstructQueryContext(rdfService, CONSTRUCT_QUERY)
.execute().toModel();
assertExpectedConstructResults();
}
@Test
public void constructQueryHolderAgainstRDFService() {
constructed = createConstructQueryContext(rdfService,
queryHolder(CONSTRUCT_QUERY)).execute().toModel();
assertExpectedConstructResults();
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private void assertExpectedSelectResults() {
try {
JsonObject actual = JSON.parse(buffer.toString("UTF-8"));
assertEquals(EXPECTED_SELECT_RESULTS, actual);
} catch (UnsupportedEncodingException e) {
fail(e.toString());
}
}
private void assertExpectedConstructResults() {
assertEquals(model.listStatements().toSet(), constructed
.listStatements().toSet());
}
}

View file

@ -0,0 +1,140 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.sparqlrunner;
import static edu.cornell.mannlib.vitro.testing.ModelUtilitiesTestHelper.dataProperty;
import static edu.cornell.mannlib.vitro.testing.ModelUtilitiesTestHelper.model;
import static edu.cornell.mannlib.vitro.webapp.utils.sparqlrunner.SparqlQueryRunner.createSelectQueryContext;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.jena.rdf.model.Model;
import org.junit.Before;
import org.junit.Test;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
public class StringResultsMappingTest extends AbstractTestClass {
private static final String SUBJECT_URI_1 = "http://namespace/subject_uri_1";
private static final String PREDICATE_URI_1 = "http://namespace/predicate_uri_1";
private static final String OBJECT_VALUE_1 = "object_value_1";
private static final String SUBJECT_URI_2 = "http://namespace/subject_uri_2";
private static final String PREDICATE_URI_2 = "http://namespace/predicate_uri_2";
private static final String OBJECT_VALUE_2 = "object_value_2";
private static final String SELECT_QUERY = "SELECT ?s ?p ?o WHERE { ?s ?p ?o . }";
private static final List<Map<String, String>> LIST_ALL_FIELDS = list(
map(entry("s", SUBJECT_URI_1), entry("p", PREDICATE_URI_1),
entry("o", OBJECT_VALUE_1)),
map(entry("s", SUBJECT_URI_2), entry("p", PREDICATE_URI_2),
entry("o", OBJECT_VALUE_2)));
private static final List<Map<String, String>> LIST_ONE_FIELD = list(
map(entry("o", OBJECT_VALUE_1)), map(entry("o", OBJECT_VALUE_2)));
private static final List<String> FLATTEN_ALL_FIELDS = list(SUBJECT_URI_1,
PREDICATE_URI_1, OBJECT_VALUE_1, SUBJECT_URI_2, PREDICATE_URI_2,
OBJECT_VALUE_2);
private static final List<String> FLATTEN_ONE_FIELD = list(OBJECT_VALUE_1,
OBJECT_VALUE_2);
private Model model;
@Before
public void setup() {
model = model(
dataProperty(SUBJECT_URI_1, PREDICATE_URI_1, OBJECT_VALUE_1),
dataProperty(SUBJECT_URI_2, PREDICATE_URI_2, OBJECT_VALUE_2));
}
@Test
public void checkMapsOfAllFields() {
assertEquivalentUnorderedLists(LIST_ALL_FIELDS,
createSelectQueryContext(model, SELECT_QUERY).execute()
.toStringFields().getListOfMaps());
}
@Test
public void checkMapsOfOneField() {
assertEquivalentUnorderedLists(LIST_ONE_FIELD,
createSelectQueryContext(model, SELECT_QUERY).execute()
.toStringFields("o").getListOfMaps());
}
@Test
public void checkFlattenAllFields() {
assertEquivalentUnorderedLists(FLATTEN_ALL_FIELDS,
createSelectQueryContext(model, SELECT_QUERY).execute()
.toStringFields().flatten());
}
@Test
public void checkFlattenOneField() {
assertEquivalentUnorderedLists(FLATTEN_ONE_FIELD,
createSelectQueryContext(model, SELECT_QUERY).execute()
.toStringFields("o").flatten());
}
@Test
public void checkFlattenToSet() {
assertEquals(new HashSet<>(FLATTEN_ONE_FIELD),
createSelectQueryContext(model, SELECT_QUERY).execute()
.toStringFields("o").flattenToSet());
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private <T> void assertEquivalentUnorderedLists(List<T> list1, List<T> list2) {
Collections.sort(list1, new ArbitraryOrder<>());
Collections.sort(list2, new ArbitraryOrder<>());
assertEquals(list1, list2);
}
private static class ArbitraryOrder<T> implements Comparator<T> {
@Override
public int compare(T t1, T t2) {
return t1.hashCode() - t2.hashCode();
}
}
@SafeVarargs
private static <T> List<T> list(T... items) {
List<T> l = new ArrayList<>();
for (T item : items) {
l.add(item);
}
return l;
}
private static Map<String, String> map(Entry... entries) {
Map<String, String> m = new HashMap<>();
for (Entry entry : entries) {
m.put(entry.key, entry.value);
}
return m;
}
private static Entry entry(String key, String value) {
return new Entry(key, value);
}
private static class Entry {
final String key;
final String value;
Entry(String key, String value) {
this.key = key;
this.value = value;
}
}
}