下面列出了org.apache.commons.io.serialization.ValidatingObjectInputStream#org.eclipse.rdf4j.query.impl.MapBindingSet 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void unaryResult() {
// Create the input binding set.
final ValueFactory vf = SimpleValueFactory.getInstance();
final MapBindingSet bindingSet = new MapBindingSet();
bindingSet.addBinding("person", vf.createIRI("urn:Alice"));
bindingSet.addBinding("age", vf.createLiteral(34));
final VisibilityBindingSet visBs = new VisibilityBindingSet(bindingSet, "a");
// Mock the processor context that will be invoked.
final ProcessorContext context = mock(ProcessorContext.class);
// Run the test.
final BindingSetOutputFormatter formatter = new BindingSetOutputFormatter();
formatter.init(context);
formatter.process("key", ProcessorResult.make(new UnaryResult(visBs)));
// Verify the mock was invoked with the expected output.
verify(context, times(1)).forward(eq("key"), eq(visBs));
}
private void reportSolution(Resource solutionNode, List<String> bindingNames) throws RDFHandlerException {
MapBindingSet bindingSet = new MapBindingSet(bindingNames.size());
for (Value bindingNode : Models.getProperties(graph, solutionNode, BINDING)) {
if (bindingNode instanceof Resource) {
Binding binding = getBinding((Resource) bindingNode);
bindingSet.addBinding(binding);
} else {
throw new RDFHandlerException("Value for " + BINDING + " is not a resource: " + bindingNode);
}
}
try {
tqrHandler.handleSolution(bindingSet);
} catch (TupleQueryResultHandlerException e) {
throw new RDFHandlerException(e.getMessage(), e);
}
}
/**
* Verify that evaluation of a {@link ZeroLengthPathIteration} does not discard input bindings.
*
* @see https://github.com/eclipse/rdf4j/issues/689
*/
@Test
public void testRetainInputBindings() {
MapBindingSet bindings = new MapBindingSet();
bindings.addBinding("a", RDF.FIRST);
Var subjectVar = new Var("x");
Var objVar = new Var("y");
try (ZeroLengthPathIteration zlp = new ZeroLengthPathIteration(evaluator, subjectVar, objVar, null, null, null,
bindings)) {
BindingSet result = zlp.getNextElement();
assertTrue("zlp evaluation should have retained unrelated input binding", result.hasBinding("a"));
assertTrue("zlp evaluation should binding for subject var", result.hasBinding("x"));
assertTrue("zlp evaluation should binding for object var", result.hasBinding("y"));
}
}
@Test
public void noBindings() throws BindingSetConversionException {
// Create a BindingSet that doesn't have any bindings.
final MapBindingSet original = new MapBindingSet();
// Convert it to a String.
final VariableOrder varOrder = new VariableOrder();
final BindingSetConverter<String> converter = new BindingSetStringConverter();
final String bindingSetString = converter.convert(original, varOrder);
// Convert it back to a binding set.
final BindingSet converted = converter.convert(bindingSetString, varOrder);
// Ensure it is still an empty BindingSet.
assertEquals(original, converted);
}
@Override
public void update(final AggregationElement aggregation, final AggregationState state, final VisibilityBindingSet childBindingSet) {
checkArgument(aggregation.getAggregationType() == AggregationType.MIN, "The MinFunction only accepts MIN AggregationElements.");
requireNonNull(state);
requireNonNull(childBindingSet);
// Only update the min if the child contains the binding that we are finding the min value for.
final String aggregatedName = aggregation.getAggregatedBindingName();
if(childBindingSet.hasBinding(aggregatedName)) {
final MapBindingSet result = state.getBindingSet();
final String resultName = aggregation.getResultBindingName();
final boolean newBinding = !result.hasBinding(resultName);
Value min;
if(newBinding) {
min = childBindingSet.getValue(aggregatedName);
} else {
final Value oldMin = result.getValue(resultName);
final Value chidlMin = childBindingSet.getValue(aggregatedName);
min = compare.compare(chidlMin, oldMin) < 0 ? chidlMin : oldMin;
}
result.addBinding(resultName, min);
}
}
@Override
public void update(final AggregationElement aggregation, final AggregationState state, final VisibilityBindingSet childBindingSet) {
checkArgument(aggregation.getAggregationType() == AggregationType.MAX, "The MaxFunction only accepts MAX AggregationElements.");
requireNonNull(state);
requireNonNull(childBindingSet);
// Only update the max if the child contains the binding that we are finding the max value for.
final String aggregatedName = aggregation.getAggregatedBindingName();
if(childBindingSet.hasBinding(aggregatedName)) {
final MapBindingSet result = state.getBindingSet();
final String resultName = aggregation.getResultBindingName();
final boolean newBinding = !result.hasBinding(resultName);
Value max;
if(newBinding) {
max = childBindingSet.getValue(aggregatedName);
} else {
final Value oldMax = result.getValue(resultName);
final Value childMax = childBindingSet.getValue(aggregatedName);
max = compare.compare(childMax, oldMax) > 0 ? childMax : oldMax;
}
result.addBinding(resultName, max);
}
}
@Override
public void update(final AggregationElement aggregation, final AggregationState state, final VisibilityBindingSet childBindingSet) {
checkArgument(aggregation.getAggregationType() == AggregationType.COUNT, "The CountFunction only accepts COUNT AggregationElements.");
requireNonNull(state);
requireNonNull(childBindingSet);
// Only add one to the count if the child contains the binding that we are counting.
final String aggregatedName = aggregation.getAggregatedBindingName();
if(childBindingSet.hasBinding(aggregatedName)) {
final MapBindingSet result = state.getBindingSet();
final String resultName = aggregation.getResultBindingName();
final boolean newBinding = !result.hasBinding(resultName);
if(newBinding) {
// Initialize the binding.
result.addBinding(resultName, VF.createLiteral(BigInteger.ONE));
} else {
// Update the existing binding.
final Literal count = (Literal) result.getValue(resultName);
final BigInteger updatedCount = count.integerValue().add( BigInteger.ONE );
result.addBinding(resultName, VF.createLiteral(updatedCount));
}
}
}
@Test
public void toString_URIs() throws BindingSetConversionException {
// Setup the binding set that will be converted.
final MapBindingSet originalBindingSet = new MapBindingSet();
originalBindingSet.addBinding("x", VF.createIRI("http://a"));
originalBindingSet.addBinding("y", VF.createIRI("http://b"));
originalBindingSet.addBinding("z", VF.createIRI("http://c"));
// Convert it to a String.
final VariableOrder varOrder = new VariableOrder("y", "z", "x");
final BindingSetConverter<String> converter = new BindingSetStringConverter();
final String bindingSetString = converter.convert(originalBindingSet, varOrder);
// Ensure it converted to the expected result.
final String expected =
"http://b<<~>>http://www.w3.org/2001/XMLSchema#anyURI:::" +
"http://c<<~>>http://www.w3.org/2001/XMLSchema#anyURI:::" +
"http://a<<~>>http://www.w3.org/2001/XMLSchema#anyURI";
assertEquals(expected, bindingSetString);
}
@Test
public void missingPredicate() {
// Create the input binding set.
final ValueFactory vf = SimpleValueFactory.getInstance();
final MapBindingSet bindingSet = new MapBindingSet();
bindingSet.addBinding("subject", vf.createIRI("urn:Alice"));
bindingSet.addBinding("object", vf.createLiteral(34));
final VisibilityBindingSet visBs = new VisibilityBindingSet(bindingSet, "a");
// Mock the processor context that will be invoked.
final ProcessorContext context = mock(ProcessorContext.class);
// Run the test.
final StatementOutputFormatter formatter = new StatementOutputFormatter();
formatter.init(context);
formatter.process("key", ProcessorResult.make(new UnaryResult(visBs)));
// Verify the mock was never invoked.
verify(context, times(0)).forward(any(), any());
}
@Test
public void newLeftResult_noRightMatches() {
final IterativeJoin leftOuterJoin = new LeftOuterJoin();
// There is a new left result.
final MapBindingSet mapLeftResult = new MapBindingSet();
mapLeftResult.addBinding("name", VF.createLiteral("Bob"));
final VisibilityBindingSet newLeftResult = new VisibilityBindingSet(mapLeftResult);
// There are no right results that join with the left result.
final Iterator<VisibilityBindingSet> rightResults= new ArrayList<VisibilityBindingSet>().iterator();
// Therefore, the left result is a new join result.
final Iterator<VisibilityBindingSet> newJoinResultsIt = leftOuterJoin.newLeftResult(newLeftResult, rightResults);
final Set<BindingSet> newJoinResults = new HashSet<>();
while(newJoinResultsIt.hasNext()) {
newJoinResults.add( newJoinResultsIt.next() );
}
final Set<BindingSet> expected = Sets.<BindingSet>newHashSet( newLeftResult );
assertEquals(expected, newJoinResults);
}
/**
* The BindingSet has fewer Bindings than there are variables in the variable
* order, but they are all in the variable order. This is the case where
* the missing bindings were optional.
*/
@Test
public void serialize_bindingsSubsetOfVarOrder() throws BindingSetConversionException {
// Setup the Binding Set.
final MapBindingSet originalBindingSet = new MapBindingSet();
originalBindingSet.addBinding("x", VF.createIRI("http://a"));
originalBindingSet.addBinding("y", VF.createIRI("http://b"));
// Setup the variable order.
final VariableOrder varOrder = new VariableOrder("x", "a", "y", "b");
// Create the byte[] representation of the BindingSet.
BindingSetConverter<byte[]> converter = new AccumuloPcjSerializer();
byte[] serialized = converter.convert(originalBindingSet, varOrder);
// Deserialize the byte[] back into the binding set.
BindingSet deserialized = converter.convert(serialized, varOrder);
// Ensure the deserialized value matches the original.
assertEquals(originalBindingSet, deserialized);
}
@Test
public void matches() throws Exception {
// Read the filter object from a SPARQL query.
final Filter filter = getFilter(
"SELECT * " +
"WHERE { " +
"FILTER(?age < 10)" +
"?person <urn:age> ?age " +
"}");
// Create the input binding set.
final ValueFactory vf = SimpleValueFactory.getInstance();
final MapBindingSet bs = new MapBindingSet();
bs.addBinding("person", vf.createIRI("urn:Alice"));
bs.addBinding("age", vf.createLiteral(9));
final VisibilityBindingSet visBs = new VisibilityBindingSet(bs);
// Test the evaluator.
assertTrue( FilterEvaluator.make(filter).filter(visBs) );
}
@Test
public void doesNotMatch() throws Exception {
// Read the filter object from a SPARQL query.
final Filter filter = getFilter(
"SELECT * " +
"WHERE { " +
"FILTER(?age < 10)" +
"?person <urn:age> ?age " +
"}");
// Create the input binding set.
final ValueFactory vf = SimpleValueFactory.getInstance();
final MapBindingSet bs = new MapBindingSet();
bs.addBinding("person", vf.createIRI("urn:Alice"));
bs.addBinding("age", vf.createLiteral(11));
final VisibilityBindingSet visBs = new VisibilityBindingSet(bs);
// Test the evaluator.
assertFalse( FilterEvaluator.make(filter).filter(visBs) );
}
@Test
public void hashcode() {
// Create a BindingSet, decorate it, and grab its hash code.
final ValueFactory vf = SimpleValueFactory.getInstance();
final MapBindingSet bSet = new MapBindingSet();
bSet.addBinding("name", vf.createLiteral("alice"));
final VisibilityBindingSet visSet = new VisibilityBindingSet(bSet);
final int origHash = visSet.hashCode();
// Add another binding to the binding set and grab the new hash code.
bSet.addBinding("age", vf.createLiteral(37));
final int updatedHash = visSet.hashCode();
// Show those hashes are different.
assertNotEquals(origHash, updatedHash);
}
@Test
public void min() throws Exception {
// A query that finds the minimum price for an item within the inventory.
final String sparql =
"SELECT (min(?price) as ?minPrice) { " +
"?item <urn:price> ?price . " +
"}";
// Create the Statements that will be loaded into Rya.
final ValueFactory vf = SimpleValueFactory.getInstance();
final Collection<Statement> statements = Sets.newHashSet(
vf.createStatement(vf.createIRI("urn:apple"), vf.createIRI("urn:price"), vf.createLiteral(2.50)),
vf.createStatement(vf.createIRI("urn:gum"), vf.createIRI("urn:price"), vf.createLiteral(0.99)),
vf.createStatement(vf.createIRI("urn:sandwich"), vf.createIRI("urn:price"), vf.createLiteral(4.99)));
// Create the PCJ in Fluo and load the statements into Rya.
final String pcjId = loadDataAndCreateQuery(sparql, statements);
// Create the expected results of the SPARQL query once the PCJ has been computed.
final MapBindingSet expectedResult = new MapBindingSet();
expectedResult.addBinding("minPrice", vf.createLiteral(0.99));
// Ensure the last result matches the expected result.
final VisibilityBindingSet result = readLastResult(pcjId);
assertEquals(expectedResult, result);
}
/**
* The BindingSet has fewer Bindings than there are variables in the variable
* order, but they are all in the variable order. This is the case where
* the missing bindings were optional.
*/
@Test
public void toString_bindingsSubsetOfVarOrder() throws BindingSetConversionException {
// Setup the Binding Set.
final MapBindingSet originalBindingSet = new MapBindingSet();
originalBindingSet.addBinding("x", VF.createIRI("http://a"));
originalBindingSet.addBinding("y", VF.createIRI("http://b"));
// Setup the variable order.
final VariableOrder varOrder = new VariableOrder("x", "a", "y", "b");
// Create the String representation of the BindingSet.
final BindingSetConverter<String> converter = new BindingSetStringConverter();
final String bindingSetString = converter.convert(originalBindingSet, varOrder);
// Ensure the expected value was created.
final String expected =
"http://a<<~>>http://www.w3.org/2001/XMLSchema#anyURI:::" +
BindingSetStringConverter.NULL_VALUE_STRING + ":::" +
"http://b<<~>>http://www.w3.org/2001/XMLSchema#anyURI:::" +
BindingSetStringConverter.NULL_VALUE_STRING;
assertEquals(expected, bindingSetString);
}
/**
* The BindingSet has more Bindings than there are variables in the variable order.
* This is the case where a Group By clause does not include all of the Bindings that
* are in the Binding Set.
*/
@Test
public void serialize_bindingNotInVariableOrder() throws RyaTypeResolverException, BindingSetConversionException {
// Setup the Binding Set.
final MapBindingSet originalBindingSet = new MapBindingSet();
originalBindingSet.addBinding("x", VF.createIRI("http://a"));
originalBindingSet.addBinding("y", VF.createIRI("http://b"));
originalBindingSet.addBinding("z", VF.createIRI("http://d"));
// Setup the variable order.
final VariableOrder varOrder = new VariableOrder("x", "y");
// Serialize the Binding Set.
BindingSetConverter<byte[]> converter = new AccumuloPcjSerializer();
byte[] serialized = converter.convert(originalBindingSet, varOrder);
// Deserialize it again.
BindingSet deserialized = converter.convert(serialized, varOrder);
// Show that it only contains the bindings that were part of the Variable Order.
MapBindingSet expected = new MapBindingSet();
expected.addBinding("x", VF.createIRI("http://a"));
expected.addBinding("y", VF.createIRI("http://b"));
assertEquals(expected, deserialized);
}
@Test
public void average() throws Exception {
// A query that finds the average price for an item that is in the inventory.
final String sparql =
"SELECT (avg(?price) as ?averagePrice) { " +
"?item <urn:price> ?price . " +
"}";
// Create the Statements that will be loaded into Rya.
final ValueFactory vf = SimpleValueFactory.getInstance();
final Collection<Statement> statements = Sets.newHashSet(
vf.createStatement(vf.createIRI("urn:apple"), vf.createIRI("urn:price"), vf.createLiteral(3)),
vf.createStatement(vf.createIRI("urn:gum"), vf.createIRI("urn:price"), vf.createLiteral(4)),
vf.createStatement(vf.createIRI("urn:sandwich"), vf.createIRI("urn:price"), vf.createLiteral(8)));
// Create the PCJ in Fluo and load the statements into Rya.
final String pcjId = loadDataAndCreateQuery(sparql, statements);
// Create the expected results of the SPARQL query once the PCJ has been computed.
final MapBindingSet expectedResult = new MapBindingSet();
expectedResult.addBinding("averagePrice", vf.createLiteral("5", XMLSchema.DECIMAL));
// Ensure the last result matches the expected result.
final VisibilityBindingSet result = readLastResult(pcjId);
assertEquals(expectedResult, result);
}
@Test
public void missingSubject() {
// Create the input binding set.
final ValueFactory vf = SimpleValueFactory.getInstance();
final MapBindingSet bindingSet = new MapBindingSet();
bindingSet.addBinding("predicate", vf.createIRI("urn:age"));
bindingSet.addBinding("object", vf.createLiteral(34));
final VisibilityBindingSet visBs = new VisibilityBindingSet(bindingSet, "a");
// Mock the processor context that will be invoked.
final ProcessorContext context = mock(ProcessorContext.class);
// Run the test.
final StatementOutputFormatter formatter = new StatementOutputFormatter();
formatter.init(context);
formatter.process("key", ProcessorResult.make(new UnaryResult(visBs)));
// Verify the mock was never invoked.
verify(context, times(0)).forward(any(), any());
}
@Override
public BindingSet convert(final String bindingSetString, final VariableOrder varOrder) {
requireNonNull(bindingSetString);
requireNonNull(varOrder);
// If both are empty, return an empty binding set.
if(bindingSetString.isEmpty() && varOrder.toString().isEmpty()) {
return new MapBindingSet();
}
// Otherwise parse it.
final String[] bindingStrings = bindingSetString.split(BINDING_DELIM);
final String[] varOrderArr = varOrder.toArray();
checkArgument(varOrderArr.length == bindingStrings.length, "The number of Bindings must match the length of the VariableOrder.");
final QueryBindingSet bindingSet = new QueryBindingSet();
for(int i = 0; i < bindingStrings.length; i++) {
final String bindingString = bindingStrings[i];
if(!NULL_VALUE_STRING.equals(bindingString)) {
final String name = varOrderArr[i];
final Value value = toValue(bindingStrings[i]);
bindingSet.addBinding(name, value);
}
}
return bindingSet;
}
@Test
public void missingObject() {
// Create the input binding set.
final ValueFactory vf = SimpleValueFactory.getInstance();
final MapBindingSet bindingSet = new MapBindingSet();
bindingSet.addBinding("subject", vf.createIRI("urn:Alice"));
bindingSet.addBinding("predicate", vf.createIRI("urn:age"));
final VisibilityBindingSet visBs = new VisibilityBindingSet(bindingSet, "a");
// Mock the processor context that will be invoked.
final ProcessorContext context = mock(ProcessorContext.class);
// Run the test.
final StatementOutputFormatter formatter = new StatementOutputFormatter();
formatter.init(context);
formatter.process("key", ProcessorResult.make(new UnaryResult(visBs)));
// Verify the mock was never invoked.
verify(context, times(0)).forward(any(), any());
}
protected TupleQueryResult createTupleMultipleBindingSets() {
List<String> bindingNames = Arrays.asList("a", "b", "c");
MapBindingSet solution1 = new MapBindingSet(bindingNames.size());
solution1.addBinding("a", vf.createIRI("foo:bar"));
solution1.addBinding("b", vf.createBNode("bnode"));
solution1.addBinding("c", vf.createLiteral("baz"));
MapBindingSet solution2 = new MapBindingSet(bindingNames.size());
solution2.addBinding("a", vf.createLiteral("1", XMLSchema.INTEGER));
solution2.addBinding("c", vf.createLiteral("Hello World!", "en"));
MapBindingSet solution3 = new MapBindingSet(bindingNames.size());
solution3.addBinding("a", vf.createIRI("http://example.org/test/ns/bindingA"));
solution3.addBinding("b", vf.createLiteral("http://example.com/other/ns/bindingB"));
solution3.addBinding("c", vf.createIRI("http://example.com/other/ns/binding,C"));
MapBindingSet solution4 = new MapBindingSet(bindingNames.size());
solution4.addBinding("a", vf.createLiteral("string with newline at the end \n"));
solution4.addBinding("b", vf.createLiteral("string with space at the end "));
solution4.addBinding("c", vf.createLiteral(" "));
MapBindingSet solution5 = new MapBindingSet(bindingNames.size());
solution5.addBinding("a", vf.createLiteral("''single-quoted string"));
solution5.addBinding("b", vf.createLiteral("\"\"double-quoted string"));
solution5.addBinding("c", vf.createLiteral(" unencoded tab characters followed by encoded \t\t"));
MapBindingSet solution6 = new MapBindingSet(bindingNames.size());
solution6.addBinding("a", vf.createTriple(vf.createIRI("urn:a"), RDF.TYPE, vf.createIRI("urn:b")));
solution6.addBinding("b", vf.createIRI("urn:test"));
solution6.addBinding("c", vf.createBNode("bnode1"));
List<? extends BindingSet> bindingSetList = Arrays.asList(solution1, solution2, solution3, solution4,
solution5);
IteratingTupleQueryResult result = new IteratingTupleQueryResult(bindingNames, bindingSetList);
return result;
}
@Test
public final void testRDFStarCompatibility() throws IOException {
ValueFactory vf = SimpleValueFactory.getInstance();
List<String> bindingNames = Arrays.asList("a", "b", "c");
List<BindingSet> bindings = new ArrayList<>();
MapBindingSet bs1 = new MapBindingSet();
// Note that the CSV format seems to ignore the datatype and assume it's xsd:integer
// so no other datatype works with it properly.
bs1.addBinding("a", vf.createLiteral("1984", XMLSchema.INTEGER));
bs1.addBinding("b", vf.createIRI("urn:test"));
bs1.addBinding("c", vf.createBNode("bnode1"));
bindings.add(bs1);
MapBindingSet bs2 = new MapBindingSet();
bs2.addBinding("a", vf.createLiteral("foo"));
bs2.addBinding("b", vf.createTriple(vf.createBNode("bnode2"), RDFS.LABEL,
vf.createLiteral("\"literal with\tfunny\nchars")));
bs2.addBinding("c", vf.createTriple(vf.createTriple(vf.createTriple(vf.createIRI("urn:a"), RDF.TYPE,
vf.createIRI("urn:b")), vf.createIRI("urn:c"), vf.createIRI("urn:d")), vf.createIRI("urn:e"),
vf.createIRI("urn:f")));
bindings.add(bs2);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
QueryResultIO.writeTuple(new IteratingTupleQueryResult(bindingNames, bindings), getTupleFormat(), bos);
System.out.println(bos.toString());
try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray())) {
TupleQueryResult parsedBindings = QueryResultIO.parseTuple(bis, getTupleFormat());
assertEquals(bindingNames, parsedBindings.getBindingNames());
List<BindingSet> actualBindings = new ArrayList<>();
parsedBindings.forEach(actualBindings::add);
assertEquals(bindings, actualBindings);
}
}
}
public ParsedOperation call(Map<IRI, Value> argValues) throws MalformedSpinException {
MapBindingSet args = new MapBindingSet();
for (Argument arg : arguments) {
IRI argPred = arg.getPredicate();
Value argValue = argValues.get(argPred);
if (argValue == null && !arg.isOptional()) {
throw new MalformedSpinException("Missing value for template argument: " + argPred);
}
if (argValue == null) {
argValue = arg.getDefaultValue();
}
if (argValue != null) {
args.addBinding(argPred.getLocalName(), argValue);
}
}
ParsedOperation callOp;
if (parsedOp instanceof ParsedBooleanQuery) {
callOp = new ParsedBooleanTemplate(this, args);
} else if (parsedOp instanceof ParsedTupleQuery) {
callOp = new ParsedTupleTemplate(this, args);
} else if (parsedOp instanceof ParsedGraphQuery) {
callOp = new ParsedGraphTemplate(this, args);
} else if (parsedOp instanceof ParsedUpdate) {
callOp = new ParsedUpdateTemplate(this, args);
} else {
throw new AssertionError("Unrecognised ParsedOperation: " + parsedOp.getClass());
}
return callOp;
}
@Test
public void testReplaceQueryPatternsWithNonEmptyResults() {
final String expectedQueryPlan = "Projection\n" +
" ProjectionElemList\n" +
" ProjectionElem \"toUri\"\n" +
" ProjectionElem \"to\"\n" +
" BindingSetAssignment ([[toUri=urn:subject1;to=\"POINT (2.2945 48.8582)\"^^<http://www.opengis.net/ont/geosparql#wktLiteral>]])\n";
final ParsedQuery query = parseQuery(QUERY);
final List<SearchQueryEvaluator> queries = new ArrayList<>();
new DistanceQuerySpecBuilder(new SearchIndexImpl())
.process(query.getTupleExpr(), EmptyBindingSet.getInstance(), queries);
assertEquals(1, queries.size());
final DistanceQuerySpec querySpec = (DistanceQuerySpec) queries.get(0);
final MapBindingSet bindingSet = new MapBindingSet();
bindingSet.addBinding("toUri", VF.createIRI("urn:subject1"));
bindingSet.addBinding("to", VF.createLiteral("POINT (2.2945 48.8582)", GEO.WKT_LITERAL));
BindingSetAssignment bsa = new BindingSetAssignment();
bsa.setBindingSets(Collections.singletonList(bindingSet));
querySpec.replaceQueryPatternsWithResults(bsa);
String result = querySpec.getParentQueryModelNode().getParentNode().toString().replaceAll("\r\n|\r", "\n");
assertEquals(expectedQueryPlan, result);
}
@Test
public void testReplaceQueryPatternsWithNonEmptyResults() {
final String expectedQueryPlan = "Projection\n" +
" ProjectionElemList\n" +
" ProjectionElem \"matchUri\"\n" +
" ProjectionElem \"match\"\n" +
" BindingSetAssignment ([[toUri=urn:subject4;to=\"POLYGON ((2.3294 48.8726, 2.2719 48.8643, 2.3370 48.8398, 2.3294 48.8726))\"^^<http://www.opengis.net/ont/geosparql#wktLiteral>]])\n";
final ParsedQuery query = parseQuery(QUERY);
final List<SearchQueryEvaluator> queries = new ArrayList<>();
new GeoRelationQuerySpecBuilder(new SearchIndexImpl())
.process(query.getTupleExpr(), EmptyBindingSet.getInstance(), queries);
assertEquals(1, queries.size());
final GeoRelationQuerySpec querySpec = (GeoRelationQuerySpec) queries.get(0);
final MapBindingSet bindingSet = new MapBindingSet();
bindingSet.addBinding("toUri", VF.createIRI("urn:subject4"));
bindingSet.addBinding("to", VF.createLiteral(
"POLYGON ((2.3294 48.8726, 2.2719 48.8643, 2.3370 48.8398, 2.3294 48.8726))", GEO.WKT_LITERAL));
BindingSetAssignment bsa = new BindingSetAssignment();
bsa.setBindingSets(Collections.singletonList(bindingSet));
querySpec.replaceQueryPatternsWithResults(bsa);
String result = querySpec.getParentQueryModelNode().getParentNode().toString().replaceAll("\r\n|\r", "\n");
assertEquals(expectedQueryPlan, result);
}
@Test
public void rountTrip() throws Exception {
final ValueFactory vf = SimpleValueFactory.getInstance();
final MapBindingSet bs = new MapBindingSet();
bs.addBinding("name", vf.createLiteral("Alice"));
bs.addBinding("age", vf.createLiteral(5));
final VisibilityBindingSet original = new VisibilityBindingSet(bs, "u");
final VisibilityBindingSetSerDe serde = new VisibilityBindingSetSerDe();
final Bytes bytes = serde.serialize(original);
final VisibilityBindingSet result = serde.deserialize(bytes);
assertEquals(original, result);
}
@Test
public void readAndWrite() throws Exception {
// Create the object that will be written to the topic.
final ValueFactory vf = SimpleValueFactory.getInstance();
final MapBindingSet bs = new MapBindingSet();
bs.addBinding("urn:name", vf.createIRI("urn:alice"));
bs.addBinding("urn:age", vf.createLiteral(32));
final VisibilityBindingSet original = new VisibilityBindingSet(bs, "a|b|c");
// Write a VisibilityBindingSet to the test topic.
try(Producer<String, VisibilityBindingSet> producer = KafkaTestUtil.makeProducer(
kafka, StringSerializer.class, VisibilityBindingSetSerializer.class)) {
producer.send( new ProducerRecord<String, VisibilityBindingSet>(kafka.getKafkaTopicName(), original) );
}
// Read a VisibilityBindingSet from the test topic.
try(Consumer<String, VisibilityBindingSet> consumer = KafkaTestUtil.fromStartConsumer(
kafka, StringDeserializer.class, VisibilityBindingSetDeserializer.class)) {
// Register the topic.
consumer.subscribe(Arrays.asList(kafka.getKafkaTopicName()));
// Poll for the result.
final List<VisibilityBindingSet> results = KafkaTestUtil.pollForResults(500, 6, 1, consumer);
// Show the written statement matches the read one.
final VisibilityBindingSet read = results.iterator().next();
assertEquals(original, read);
}
}
@Test
public void showWithinWorks() throws Exception {
// Enumerate some topics that will be re-used
final String ryaInstance = UUID.randomUUID().toString();
final UUID queryId = UUID.randomUUID();
final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
// Get the RDF model objects that will be used to build the query.
final String sparql =
"PREFIX time: <http://www.w3.org/2006/time/> \n"
+ "PREFIX tempf: <" + TemporalIRIs.NAMESPACE + ">\n"
+ "SELECT * \n"
+ "WHERE { \n"
+ " <urn:time> time:atTime ?date .\n"
+ " FILTER(tempf:within(?date, \"" + TIME.toString() + "/" + TIME_20.toString() + "\")) "
+ "}";
// Setup a topology.
final TopologyBuilder builder = new TopologyFactory().build(sparql, statementsTopic, resultsTopic, new RandomUUIDFactory());
// Create the statements that will be input into the query.
final List<VisibilityStatement> statements = getStatements();
// Make the expected results.
final Set<VisibilityBindingSet> expected = new HashSet<>();
final MapBindingSet bs = new MapBindingSet();
bs.addBinding("date", VF.createLiteral(TIME_10.toString()));
expected.add( new VisibilityBindingSet(bs, "a") );
// Run the test.
RyaStreamsTestUtil.runStreamProcessingTest(kafka, statementsTopic, resultsTopic, builder, statements, expected, VisibilityBindingSetDeserializer.class);
}
private void addBinding(BindingSet bs, String name, Value value) {
if (bs instanceof QueryBindingSet) {
((QueryBindingSet) bs).addBinding(name, value);
} else if (bs instanceof MapBindingSet) {
((MapBindingSet) bs).addBinding(name, value);
} else {
throw new IllegalStateException("Unexpected BindingSet implementation: " + bs.getClass());
}
}