org.eclipse.rdf4j.query.impl.MapBindingSet Java Examples

The following examples show how to use org.eclipse.rdf4j.query.impl.MapBindingSet. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StatementOutputFormatterTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #2
Source File: BindingSetOutputFormatterTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #3
Source File: KafkaExportIT.java    From rya with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: AccumuloPcjSerializerTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #5
Source File: StatementOutputFormatterTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #6
Source File: DAWGTestResultSetParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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);
	}
}
 
Example #7
Source File: KafkaExportIT.java    From rya with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #8
Source File: BindingSetStringConverterTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #9
Source File: ZeroLengthPathIterationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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"));
	}
}
 
Example #10
Source File: StatementOutputFormatterTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #11
Source File: VisibilityBindingSetTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #12
Source File: FilterEvaluatorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@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) );
}
 
Example #13
Source File: BindingSetStringConverter.java    From rya with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #14
Source File: FilterEvaluatorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@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) );
}
 
Example #15
Source File: MinFunction.java    From rya with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #16
Source File: AccumuloPcjSerializerTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #17
Source File: MaxFunction.java    From rya with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #18
Source File: CountFunction.java    From rya with Apache License 2.0 6 votes vote down vote up
@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));
        }
    }
}
 
Example #19
Source File: LeftOuterJoinTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #20
Source File: BindingSetStringConverterTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #21
Source File: BindingSetStringConverterTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #22
Source File: QueryIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void dateTimeWithinNow() throws Exception {

    final ValueFactory vf = SimpleValueFactory.getInstance();
    final DatatypeFactory dtf = DatatypeFactory.newInstance();
    FunctionRegistry.getInstance().add(new DateTimeWithinPeriod());

    final String sparql = "PREFIX fn: <" + FN.NAMESPACE +">"
            + "SELECT ?event ?startTime WHERE { ?event <uri:startTime> ?startTime. "
            + "FILTER(fn:dateTimeWithin(?startTime, NOW(), 30, <" + OWLTime.SECONDS_URI + "> ))}";

    final ZonedDateTime zTime = ZonedDateTime.now();
    final String time = zTime.format(DateTimeFormatter.ISO_INSTANT);

    final ZonedDateTime zTime1 = zTime.minusSeconds(30);
    final String time1 = zTime1.format(DateTimeFormatter.ISO_INSTANT);

    final Literal lit = vf.createLiteral(dtf.newXMLGregorianCalendar(time));
    final Literal lit1 = vf.createLiteral(dtf.newXMLGregorianCalendar(time1));

    // Create the Statements that will be loaded into Rya.
    final Collection<Statement> statements = Sets.newHashSet(
            vf.createStatement(vf.createIRI("uri:event1"), vf.createIRI("uri:startTime"), lit),
            vf.createStatement(vf.createIRI("uri:event2"), vf.createIRI("uri:startTime"), lit1)
           );

    // Create the expected results of the SPARQL query once the PCJ has been computed.
    final Set<BindingSet> expectedResults = new HashSet<>();

    final MapBindingSet bs = new MapBindingSet();
    bs.addBinding("event", vf.createIRI("uri:event1"));
    bs.addBinding("startTime", lit);
    expectedResults.add(bs);

    // Verify the end results of the query match the expected results.
    runTest(sparql, statements, expectedResults, ExportStrategy.RYA);
}
 
Example #23
Source File: KafkaExportIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void count() throws Exception {
    // A query that counts the number of unique items that are in the inventory.
    final String sparql =
            "SELECT (count(?item) as ?itemCount) { " +
                "?item <urn:id> ?id . " +
            "}";

    // Create the Statements that will be loaded into Rya.
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final Collection<Statement> statements = Sets.newHashSet(
            // Three that are part of the count.
            vf.createStatement(vf.createIRI("urn:apple"), vf.createIRI("urn:id"), vf.createLiteral(UUID.randomUUID().toString())),
            vf.createStatement(vf.createIRI("urn:gum"), vf.createIRI("urn:id"), vf.createLiteral(UUID.randomUUID().toString())),
            vf.createStatement(vf.createIRI("urn:sandwich"), vf.createIRI("urn:id"), vf.createLiteral(UUID.randomUUID().toString())),

            // One that is not.
            vf.createStatement(vf.createIRI("urn:sandwich"), vf.createIRI("urn:price"), vf.createLiteral(3.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("itemCount", vf.createLiteral("3", XMLSchema.INTEGER));

    // Ensure the last result matches the expected result.
    final VisibilityBindingSet result = readLastResult(pcjId);
    assertEquals(expectedResult, result);
}
 
Example #24
Source File: BindingSetUtil.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link BindingSet} that only includes the bindings whose names appear within the {@code variableOrder}.
 * If no binding is found for a variable, then that binding is just omitted from the resulting object.
 *
 * @param variableOrder - Defines which bindings will be kept. (not null)
 * @param bindingSet - Contains the source {@link Binding}s. (not null)
 * @return A new {@link BindingSet} containing only the specified bindings.
 */
public static BindingSet keepBindings(final VariableOrder variableOrder, final BindingSet bindingSet) {
    requireNonNull(variableOrder);
    requireNonNull(bindingSet);

    final MapBindingSet result = new MapBindingSet();
    for(final String bindingName : variableOrder) {
        if(bindingSet.hasBinding(bindingName)) {
            final Binding binding = bindingSet.getBinding(bindingName);
            result.addBinding(binding);
        }
    }
    return result;
}
 
Example #25
Source File: MongoPcjDocumentsTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void metadataExists() throws Exception {
    final List<VariableOrder> varOrders = Lists.newArrayList(new VariableOrder("b", "a"), new VariableOrder("a", "b"));
    final MongoPcjDocuments docConverter = new MongoPcjDocuments(getMongoClient(), conf.getRyaInstanceName());
    final String sparql = "SELECT * WHERE { ?a <http://isA> ?b }";
    docConverter.createPcj("pcjTest", sparql);

    PcjMetadata actual = docConverter.getPcjMetadata("pcjTest");
    PcjMetadata expected = new PcjMetadata(sparql, 0, varOrders);
    assertEquals(expected, actual);

    // Setup the binding set that will be converted.
    final MapBindingSet originalBindingSet1 = new MapBindingSet();
    originalBindingSet1.addBinding("x", VF.createIRI("http://a"));
    originalBindingSet1.addBinding("y", VF.createIRI("http://b"));
    originalBindingSet1.addBinding("z", VF.createIRI("http://c"));
    final VisibilityBindingSet results1 = new VisibilityBindingSet(originalBindingSet1, "A&B&C");

    // Setup the binding set that will be converted.
    final MapBindingSet originalBindingSet2 = new MapBindingSet();
    originalBindingSet2.addBinding("x", VF.createIRI("http://1"));
    originalBindingSet2.addBinding("y", VF.createIRI("http://2"));
    originalBindingSet2.addBinding("z", VF.createIRI("http://3"));
    final VisibilityBindingSet results2 = new VisibilityBindingSet(originalBindingSet2, "A&B&C");

    final List<VisibilityBindingSet> bindingSets = new ArrayList<>();
    bindingSets.add(results1);
    bindingSets.add(results2);

    docConverter.addResults("pcjTest", bindingSets);
    actual = docConverter.getPcjMetadata("pcjTest");
    expected = new PcjMetadata(sparql, 2, varOrders);
    assertEquals(expected, actual);

    docConverter.purgePcjs("pcjTest");
    actual = docConverter.getPcjMetadata("pcjTest");
    expected = new PcjMetadata(sparql, 0, varOrders);
    assertEquals(expected, actual);
}
 
Example #26
Source File: BindingSetStringConverterTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void toString_Integer() throws BindingSetConversionException {
    // Setup the binding set that will be converted.
    final MapBindingSet originalBindingSet = new MapBindingSet();
    originalBindingSet.addBinding("x", VF.createLiteral((BigInteger.valueOf(5))));

    // Convert it to a String.
    final VariableOrder varOrder = new VariableOrder("x");
    final BindingSetConverter<String> converter = new BindingSetStringConverter();
    final String bindingSetString = converter.convert(originalBindingSet, varOrder);

    // Ensure it converted to the expected result.
    final String expected = "5<<~>>http://www.w3.org/2001/XMLSchema#integer";
    assertEquals(expected, bindingSetString);
}
 
Example #27
Source File: MongoEntityIndexIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void sparqlQuery_Test() throws Exception {
    final Sail sail = RyaSailFactory.getInstance(conf);
    final SailRepositoryConnection conn = new SailRepository(sail).getConnection();
    conn.begin();

    try(MongoEntityIndexer indexer = new MongoEntityIndexer()) {
        indexer.setConf(conf);
        indexer.init();

        setupTypes(indexer);
        addStatements(conn);

        final String query = "SELECT * WHERE { " +
                "<urn:strawberry> <" + RDF.TYPE + "> <urn:icecream> ."+
                "<urn:strawberry> <urn:brand> ?brand . " +
                "<urn:strawberry> <urn:flavor> ?flavor . " +
                "}";

        final TupleQueryResult rez = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate();
        final Set<BindingSet> results = new HashSet<>();
        while(rez.hasNext()) {
            final BindingSet bs = rez.next();
            results.add(bs);
        }
        final MapBindingSet expected = new MapBindingSet();
        expected.addBinding("flavor", VF.createLiteral("Strawberry"));
        expected.addBinding("brand", VF.createLiteral("Awesome Icecream"));

        assertEquals(1, results.size());
        assertEquals(expected, results.iterator().next());
    } finally {
        conn.close();
    }
}
 
Example #28
Source File: TemporalFilterIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void showAfterWorks() 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:after(?date, \"" + TIME_10.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_20.toString()));
    expected.add( new VisibilityBindingSet(bs, "a") );

    // Run the test.
    RyaStreamsTestUtil.runStreamProcessingTest(kafka, statementsTopic, resultsTopic, builder, statements, expected, VisibilityBindingSetDeserializer.class);
}
 
Example #29
Source File: NaturalJoinTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void newRightResult_noLeftMatches() {
    final IterativeJoin naturalJoin = new NaturalJoin();

    // There are no left results.
    final Iterator<VisibilityBindingSet> leftResults= new ArrayList<VisibilityBindingSet>().iterator();

    // There is a new right result.
    final MapBindingSet newRightResult = new MapBindingSet();
    newRightResult.addBinding("name", VF.createLiteral("Bob"));

    // Therefore, there are no new join results.
    final Iterator<VisibilityBindingSet> newJoinResultsIt = naturalJoin.newRightResult(leftResults, new VisibilityBindingSet(newRightResult));
    assertFalse( newJoinResultsIt.hasNext() );
}
 
Example #30
Source File: EntityQueryNodeIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void evaluate_constantSubject() throws Exception {
    final EntityStorage storage = new MongoEntityStorage(super.getMongoClient(), "testDB");
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final RyaIRI subject = new RyaIRI("urn:SSN:111-11-1111");
    final Entity entity = Entity.builder()
        .setSubject(subject)
        .setExplicitType(PERSON_TYPE.getId())
        .setProperty(PERSON_TYPE.getId(), new Property(new RyaIRI("urn:age"), RdfToRyaConversions.convertLiteral(vf.createLiteral(BigInteger.valueOf(20)))))
        .setProperty(PERSON_TYPE.getId(), new Property(new RyaIRI("urn:eye"), RdfToRyaConversions.convertLiteral(vf.createLiteral("blue"))))
        .setProperty(PERSON_TYPE.getId(), new Property(new RyaIRI("urn:name"), RdfToRyaConversions.convertLiteral(vf.createLiteral("Bob"))))
        .build();

    storage.create(entity);
    // A set of patterns that match a sepecific Entity subject.
    final List<StatementPattern> patterns = getSPs(
            "SELECT * WHERE { " +
                "<urn:SSN:111-11-1111> <" + RDF.TYPE + "> <urn:person> ."+
                "<urn:SSN:111-11-1111> <urn:age> ?age . " +
                "<urn:SSN:111-11-1111> <urn:eye> ?eye . " +
                "<urn:SSN:111-11-1111> <urn:name> ?name . " +
            "}");

    final EntityQueryNode node = new EntityQueryNode(PERSON_TYPE, patterns, storage);
    final CloseableIteration<BindingSet, QueryEvaluationException> rez = node.evaluate(new MapBindingSet());
    final MapBindingSet expected = new MapBindingSet();
    expected.addBinding("age", vf.createLiteral("20"));
    expected.addBinding("eye", vf.createLiteral("blue"));
    expected.addBinding("name", vf.createLiteral("Bob"));
    while(rez.hasNext()) {
        assertEquals(expected, rez.next());
        break;
    }
}