Java Code Examples for org.eclipse.rdf4j.common.iteration.CloseableIteration#next()

The following examples show how to use org.eclipse.rdf4j.common.iteration.CloseableIteration#next() . 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: KafkaQueryChangeLogIT.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void readFromPosition_positionStartsNotBegining() throws Exception {
    final List<QueryChange> expected = write10ChangesToChangeLog().subList(5, 10);

    // set the position to some non-0 position
    final TopicPartition partition = new TopicPartition(topic, 0);
    consumer.assign(Lists.newArrayList(partition));
    consumer.seekToEnd(Lists.newArrayList(partition));
    final CloseableIteration<ChangeLogEntry<QueryChange>, QueryChangeLogException> iter = changeLog.readFromPosition(5L);

    final List<QueryChange> actual = new ArrayList<>();
    while (iter.hasNext()) {
        final ChangeLogEntry<QueryChange> entry = iter.next();
        actual.add(entry.getEntry());
    }
    assertEquals(expected, actual);
}
 
Example 2
Source File: SailSourceModel.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public synchronized void removeTermIteration(Iterator<Statement> iter, Resource subj, IRI pred, Value obj,
		Resource... contexts) {
	try {
		CloseableIteration<? extends Statement, SailException> stmts;
		stmts = dataset().getStatements(subj, pred, obj, contexts);
		try {

			while (stmts.hasNext()) {
				Statement st = stmts.next();
				sink.deprecate(st);
			}

		} finally {
			stmts.close();
		}
		size = -1;
	} catch (SailException e) {
		throw new ModelException(e);
	}
}
 
Example 3
Source File: SailUpdateExecutor.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @param add
 * @param uc
 * @throws SailException
 */
protected void executeAdd(Add add, UpdateContext uc, int maxExecTime) throws SailException {
	ValueConstant sourceGraph = add.getSourceGraph();
	ValueConstant destinationGraph = add.getDestinationGraph();

	Resource source = sourceGraph != null ? (Resource) sourceGraph.getValue() : null;
	Resource destination = destinationGraph != null ? (Resource) destinationGraph.getValue() : null;

	if (source == null && destination == null || (source != null && source.equals(destination))) {
		// source and destination are the same, copy is a null-operation.
		return;
	}

	// get all statements from source and add them to destination
	CloseableIteration<? extends Statement, SailException> statements = null;
	try {
		statements = con.getStatements(null, null, null, uc.isIncludeInferred(), (Resource) source);

		if (maxExecTime > 0) {
			statements = new TimeLimitIteration<Statement, SailException>(statements, 1000L * maxExecTime) {

				@Override
				protected void throwInterruptedException() throws SailException {
					throw new SailException("execution took too long");
				}
			};
		}

		while (statements.hasNext()) {
			Statement st = statements.next();
			con.addStatement(uc, st.getSubject(), st.getPredicate(), st.getObject(), (Resource) destination);
		}
	} finally {
		if (statements != null) {
			statements.close();
		}
	}
}
 
Example 4
Source File: ForwardChainingRDFSInferencerConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private int applyRuleRdfs9_1() throws SailException {
	int nofInferred = 0;

	Iterable<Statement> ntIter = newThisIteration.getStatements(null, RDFS.SUBCLASSOF, null);

	for (Statement nt : ntIter) {
		Resource xxx = nt.getSubject();
		Value yyy = nt.getObject();

		if (yyy instanceof Resource) {
			CloseableIteration<? extends Statement, SailException> t1Iter;
			t1Iter = getWrappedConnection().getStatements(null, RDF.TYPE, xxx, true);

			while (t1Iter.hasNext()) {
				Statement t1 = t1Iter.next();

				Resource aaa = t1.getSubject();

				boolean added = addInferredStatement(aaa, RDF.TYPE, yyy);
				if (added) {
					nofInferred++;
				}
			}
			t1Iter.close();
		}
	}

	return nofInferred;
}
 
Example 5
Source File: ForwardChainingRDFSInferencerConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private int applyRuleRdfs7_2() throws SailException {
	int nofInferred = 0;

	Iterable<Statement> ntIter = newThisIteration.getStatements(null, RDFS.SUBPROPERTYOF, null);

	for (Statement nt : ntIter) {
		Resource aaa = nt.getSubject();
		Value bbb = nt.getObject();

		if (aaa instanceof IRI && bbb instanceof IRI) {
			CloseableIteration<? extends Statement, SailException> t1Iter;
			t1Iter = getWrappedConnection().getStatements(null, (IRI) aaa, null, true);

			while (t1Iter.hasNext()) {
				Statement t1 = t1Iter.next();

				Resource xxx = t1.getSubject();
				Value yyy = t1.getObject();

				boolean added = addInferredStatement(xxx, (IRI) bbb, yyy);
				if (added) {
					nofInferred++;
				}
			}
			t1Iter.close();
		}
	}

	return nofInferred;
}
 
Example 6
Source File: ForwardChainingRDFSInferencerConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private int applyRuleRdfs7_1() throws SailException {
	int nofInferred = 0;

	Iterable<Statement> ntIter = newThisIteration.getStatements(null, null, null);

	for (Statement nt : ntIter) {
		Resource xxx = nt.getSubject();
		IRI aaa = nt.getPredicate();
		Value yyy = nt.getObject();

		CloseableIteration<? extends Statement, SailException> t1Iter;
		t1Iter = getWrappedConnection().getStatements(aaa, RDFS.SUBPROPERTYOF, null, true);

		while (t1Iter.hasNext()) {
			Statement t1 = t1Iter.next();

			Value bbb = t1.getObject();
			if (bbb instanceof IRI) {
				boolean added = addInferredStatement(xxx, (IRI) bbb, yyy);
				if (added) {
					nofInferred++;
				}
			}
		}
		t1Iter.close();
	}

	return nofInferred;
}
 
Example 7
Source File: ForwardChainingRDFSInferencerConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private int applyRuleRdfs5_1() throws SailException {
	int nofInferred = 0;

	Iterable<Statement> ntIter = newThisIteration.getStatements(null, RDFS.SUBPROPERTYOF, null);

	for (Statement nt : ntIter) {
		Resource aaa = nt.getSubject();
		Value bbb = nt.getObject();

		if (bbb instanceof Resource) {
			CloseableIteration<? extends Statement, SailException> t1Iter;
			t1Iter = getWrappedConnection().getStatements((Resource) bbb, RDFS.SUBPROPERTYOF, null, true);

			while (t1Iter.hasNext()) {
				Statement t1 = t1Iter.next();

				Value ccc = t1.getObject();
				if (ccc instanceof Resource) {
					boolean added = addInferredStatement(aaa, RDFS.SUBPROPERTYOF, ccc);
					if (added) {
						nofInferred++;
					}
				}
			}
			t1Iter.close();

		}
	}

	return nofInferred;
}
 
Example 8
Source File: ForwardChainingRDFSInferencerConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private int applyRuleRdfs3_2() throws SailException {
	int nofInferred = 0;

	Iterable<Statement> ntIter = newThisIteration.getStatements(null, RDFS.RANGE, null);

	for (Statement nt : ntIter) {
		Resource aaa = nt.getSubject();
		Value zzz = nt.getObject();

		if (aaa instanceof IRI && zzz instanceof Resource) {
			CloseableIteration<? extends Statement, SailException> t1Iter;
			t1Iter = getWrappedConnection().getStatements(null, (IRI) aaa, null, true);

			while (t1Iter.hasNext()) {
				Statement t1 = t1Iter.next();

				Value uuu = t1.getObject();
				if (uuu instanceof Resource) {
					boolean added = addInferredStatement((Resource) uuu, RDF.TYPE, zzz);
					if (added) {
						nofInferred++;
					}
				}
			}
			t1Iter.close();
		}
	}

	return nofInferred;

}
 
Example 9
Source File: ForwardChainingRDFSInferencerConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private int applyRuleRdfs2_2() throws SailException {
	int nofInferred = 0;

	Iterable<Statement> ntIter = newThisIteration.getStatements(null, RDFS.DOMAIN, null);

	for (Statement nt : ntIter) {
		Resource aaa = nt.getSubject();
		Value zzz = nt.getObject();

		if (aaa instanceof IRI && zzz instanceof Resource) {
			CloseableIteration<? extends Statement, SailException> t1Iter;
			t1Iter = getWrappedConnection().getStatements(null, (IRI) aaa, null, true);

			while (t1Iter.hasNext()) {
				Statement t1 = t1Iter.next();

				Resource xxx = t1.getSubject();
				boolean added = addInferredStatement(xxx, RDF.TYPE, zzz);
				if (added) {
					nofInferred++;
				}
			}
			t1Iter.close();
		}
	}

	return nofInferred;
}
 
Example 10
Source File: MongoTemporalIndexerIT.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * interval is after the given interval.  Find interval beginnings after the endings of the given interval.
 * {@link MongoTemporalIndexer#queryIntervalAfter(TemporalInterval, StatementContraints).
 *
 * @throws IOException
 * @throws QueryEvaluationException
 */
@Test
public void testQueryIntervalAfter() throws IOException, QueryEvaluationException {
    try(MongoTemporalIndexer tIndexer = new MongoTemporalIndexer()) {
        tIndexer.setConf(conf);
        tIndexer.init();

        // tiB02_E30 read as: Begins 2 seconds, ends at 30 seconds
        tIndexer.storeStatement(convertStatement(spo_B00_E01));
        tIndexer.storeStatement(convertStatement(spo_B02_E29)); //<- after this one.
        tIndexer.storeStatement(convertStatement(spo_B02_E30));
        tIndexer.storeStatement(convertStatement(spo_B02_E31));
        tIndexer.storeStatement(convertStatement(spo_B02_E40));
        tIndexer.storeStatement(convertStatement(spo_B03_E20));
        tIndexer.storeStatement(convertStatement(spo_B29_E30));
        tIndexer.storeStatement(convertStatement(spo_B30_E32));
        // instants should be ignored.
        tIndexer.storeStatement(convertStatement(spo_B02));
        tIndexer.storeStatement(convertStatement(seriesSpo[1])); // instance at 1 seconds
        tIndexer.storeStatement(convertStatement(seriesSpo[2]));
        tIndexer.storeStatement(convertStatement(seriesSpo[31]));

        CloseableIteration<Statement, QueryEvaluationException> iter;
        iter = tIndexer.queryIntervalAfter(tvB02_E29, EMPTY_CONSTRAINTS);
        // Should be found twice:
        assertTrue("spo_B30_E32 should be found, but actually returned empty results. spo_B30_E32=" + spo_B30_E32, iter.hasNext());
        final Statement s = iter.next();
        assertTrue("spo_B30_E32 should be found, but found another. spo_B30_E32="+spo_B30_E32+", but found="+s, spo_B30_E32.equals(s));
        assertFalse("Find no more than one, but actually has more.", iter.hasNext());
    }
}
 
Example 11
Source File: ForwardChainingRDFSInferencerConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private int applyRuleRdfs11_1() throws SailException {
	int nofInferred = 0;

	Iterable<Statement> ntIter = newThisIteration.getStatements(null, RDFS.SUBCLASSOF, null);

	for (Statement nt : ntIter) {
		Resource xxx = nt.getSubject();
		Value yyy = nt.getObject();

		if (yyy instanceof Resource) {
			CloseableIteration<? extends Statement, SailException> t1Iter;
			t1Iter = getWrappedConnection().getStatements((Resource) yyy, RDFS.SUBCLASSOF, null, true);

			while (t1Iter.hasNext()) {
				Statement t1 = t1Iter.next();

				Value zzz = t1.getObject();

				if (zzz instanceof Resource) {
					boolean added = addInferredStatement(xxx, RDFS.SUBCLASSOF, zzz);
					if (added) {
						nofInferred++;
					}
				}
			}
			t1Iter.close();
		}
	}

	return nofInferred;
}
 
Example 12
Source File: MongoDbSmartUriIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testStorage() throws SmartUriException, RuntimeException {
    smartUriConverter.storeEntity(BOB_ENTITY);

    final String sparql = "SELECT * WHERE { " +
        "<" + BOB.getData() + "> <" + RDF.TYPE + "> <" + PERSON_TYPE.getId().getData() + "> . " +
        "<" + BOB.getData() + "> <" + HAS_SSN.getData() + "> ?ssn . " +
        "<" + BOB.getData() + "> <" + HAS_AGE.getData() + "> ?age . " +
        "<" + BOB.getData() + "> <" + HAS_WEIGHT.getData() + "> ?weight . " +
        "<" + BOB.getData() + "> <" + HAS_ADDRESS.getData() + "> ?address . " +
    "}";

    final StatementPatternCollector spCollector = new StatementPatternCollector();
    new SPARQLParser().parseQuery(sparql, null).getTupleExpr().visit(spCollector);
    final List<StatementPattern> patterns = spCollector.getStatementPatterns();
    final EntityQueryNode entityQueryNode = new EntityQueryNode(PERSON_TYPE, patterns, smartUriConverter.getEntityStorage());
    final QueryBindingSet queryBindingSet = new QueryBindingSet();
    final Property ssnProperty = BOB_ENTITY.lookupTypeProperty(PERSON_TYPE, HAS_SSN).get();
    queryBindingSet.addBinding(HAS_SSN.getData(), RyaToRdfConversions.convertValue(ssnProperty.getValue()));

    final CloseableIteration<BindingSet, QueryEvaluationException> iter = entityQueryNode.evaluate(queryBindingSet);
    int count = 0;
    // These should match what was used in the SPARQL query.
    final List<String> queryParamNames = Lists.newArrayList("ssn", "age", "weight", "address");
    while (iter.hasNext()) {
        final BindingSet bs = iter.next();
        assertTrue(bs.getBindingNames().containsAll(queryParamNames));
        count++;
    }
    assertEquals(count, 1);
}
 
Example 13
Source File: AccumuloIndexSetTest.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void accumuloIndexSetTestWithTwoBindingSets() throws RepositoryException, PcjException, TableNotFoundException,
RyaTypeResolverException, MalformedQueryException, SailException, QueryEvaluationException, AccumuloException, AccumuloSecurityException {
    // Load some Triples into Rya.
    final Set<Statement> triples = new HashSet<>();
    triples.add( VF.createStatement(VF.createIRI("http://Alice"), VF.createIRI("http://hasAge"), VF.createLiteral(BigInteger.valueOf(14))) );
    triples.add( VF.createStatement(VF.createIRI("http://Alice"), VF.createIRI("http://playsSport"), VF.createLiteral("Soccer")) );
    triples.add( VF.createStatement(VF.createIRI("http://Bob"), VF.createIRI("http://hasAge"), VF.createLiteral(BigInteger.valueOf(16))) );
    triples.add( VF.createStatement(VF.createIRI("http://Bob"), VF.createIRI("http://playsSport"), VF.createLiteral("Soccer")) );
    triples.add( VF.createStatement(VF.createIRI("http://Charlie"), VF.createIRI("http://hasAge"), VF.createLiteral(BigInteger.valueOf(12))) );
    triples.add( VF.createStatement(VF.createIRI("http://Charlie"), VF.createIRI("http://playsSport"), VF.createLiteral("Soccer")) );
    triples.add( VF.createStatement(VF.createIRI("http://Eve"), VF.createIRI("http://hasAge"), VF.createLiteral(43)) );
    triples.add( VF.createStatement(VF.createIRI("http://Eve"), VF.createIRI("http://playsSport"), VF.createLiteral("Soccer")) );

    for(final Statement triple : triples) {
        ryaConn.add(triple);
    }

    // Create a PCJ table will include those triples in its results.
    final String sparql =
            "SELECT ?name ?age " +
            "{" +
              "FILTER(?age < 30) ." +
              "?name <http://hasAge> ?age." +
              "?name <http://playsSport> \"Soccer\" " +
            "}";

    final String pcjTableName = new PcjTableNameFactory().makeTableName(prefix, "testPcj");

    // Create and populate the PCJ table.
    PcjIntegrationTestingUtil.createAndPopulatePcj(ryaConn, accumuloConn, pcjTableName, sparql, new String[]{"name", "age"}, Optional.absent());

    final AccumuloIndexSet ais = new AccumuloIndexSet(conf, pcjTableName);

    final QueryBindingSet bs = new QueryBindingSet();
    bs.addBinding("birthDate",VF.createLiteral("1983-03-17",VF.createIRI("http://www.w3.org/2001/XMLSchema#date")));
    bs.addBinding("name",VF.createIRI("http://Alice"));

    final QueryBindingSet bs2 = new QueryBindingSet();
    bs2.addBinding("birthDate",VF.createLiteral("1983-04-18",VF.createIRI("http://www.w3.org/2001/XMLSchema#date")));
    bs2.addBinding("name",VF.createIRI("http://Bob"));

    final Set<BindingSet> bSets = Sets.newHashSet(bs,bs2);

    final CloseableIteration<BindingSet, QueryEvaluationException> results = ais.evaluate(bSets);

    final QueryBindingSet alice = new QueryBindingSet();
    alice.addBinding("name", VF.createIRI("http://Alice"));
    alice.addBinding("age", VF.createLiteral(BigInteger.valueOf(14)));
    alice.addBinding("birthDate", VF.createLiteral("1983-03-17",VF.createIRI("http://www.w3.org/2001/XMLSchema#date")));

    final QueryBindingSet bob = new QueryBindingSet();
    bob.addBinding("name", VF.createIRI("http://Bob"));
    bob.addBinding("age", VF.createLiteral(BigInteger.valueOf(16)));
    bob.addBinding("birthDate", VF.createLiteral("1983-04-18",VF.createIRI("http://www.w3.org/2001/XMLSchema#date")));

    final Set<BindingSet> fetchedResults = new HashSet<>();
    while(results.hasNext()) {
        final BindingSet next = results.next();
        System.out.println(next);
        fetchedResults.add(next);
    }

    Assert.assertEquals(Sets.<BindingSet>newHashSet(alice,bob), fetchedResults);
}
 
Example 14
Source File: AccumuloIndexSetTest.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void accumuloIndexSetTestWithTwoDirectProductBindingSetsWithConstantMapping() throws Exception {
    // Load some Triples into Rya.
    final Set<Statement> triples = new HashSet<>();
    triples.add( VF.createStatement(VF.createIRI("http://Alice"), VF.createIRI("http://hasAge"), VF.createLiteral(BigInteger.valueOf(14))) );
    triples.add( VF.createStatement(VF.createIRI("http://Alice"), VF.createIRI("http://playsSport"), VF.createLiteral("Soccer")) );
    triples.add( VF.createStatement(VF.createIRI("http://Bob"), VF.createIRI("http://hasAge"), VF.createLiteral(BigInteger.valueOf(16))) );
    triples.add( VF.createStatement(VF.createIRI("http://Bob"), VF.createIRI("http://playsSport"), VF.createLiteral("Soccer")) );
    triples.add( VF.createStatement(VF.createIRI("http://Charlie"), VF.createIRI("http://hasAge"), VF.createLiteral(BigInteger.valueOf(12))) );
    triples.add( VF.createStatement(VF.createIRI("http://Charlie"), VF.createIRI("http://playsSport"), VF.createLiteral("Soccer")) );
    triples.add( VF.createStatement(VF.createIRI("http://Eve"), VF.createIRI("http://hasAge"), VF.createLiteral(43)) );
    triples.add( VF.createStatement(VF.createIRI("http://Eve"), VF.createIRI("http://playsSport"), VF.createLiteral("Soccer")) );

    for(final Statement triple : triples) {
        ryaConn.add(triple);
    }

    // Create a PCJ table will include those triples in its results.
    final String sparql =
            "SELECT ?name ?age " +
            "{" +
              "?name <http://hasAge> ?age." +
              "?name <http://playsSport> \"Soccer\" " +
            "}";

    final String pcjTableName = new PcjTableNameFactory().makeTableName(prefix, "testPcj");

    // Create and populate the PCJ table.
    PcjIntegrationTestingUtil.createAndPopulatePcj(ryaConn, accumuloConn, pcjTableName, sparql, new String[]{"name", "age"}, Optional.absent());

    final String sparql2 =
            "SELECT ?x " +
            "{" +
              "?x <http://hasAge> 16 ." +
              "?x <http://playsSport> \"Soccer\" " +
            "}";

    final SPARQLParser p = new SPARQLParser();
    final ParsedQuery pq1 = p.parseQuery(sparql, null);
    final ParsedQuery pq2 = p.parseQuery(sparql2, null);

    final AccumuloIndexSet ais = new AccumuloIndexSet(conf, pcjTableName);
    ais.setProjectionExpr((Projection) QueryVariableNormalizer.getNormalizedIndex(pq2.getTupleExpr(), pq1.getTupleExpr()).get(0));

    final QueryBindingSet bs = new QueryBindingSet();
    bs.addBinding("birthDate",VF.createLiteral("1983-03-17",VF.createIRI("http://www.w3.org/2001/XMLSchema#date")));
    bs.addBinding("x",VF.createIRI("http://Alice"));

    final QueryBindingSet bs2 = new QueryBindingSet();
    bs2.addBinding("birthDate",VF.createLiteral("1983-04-18",VF.createIRI("http://www.w3.org/2001/XMLSchema#date")));
    bs2.addBinding("x",VF.createIRI("http://Bob"));

    final Set<BindingSet> bSets = Sets.newHashSet(bs,bs2);

    final CloseableIteration<BindingSet, QueryEvaluationException> results = ais.evaluate(bSets);

    final Set<BindingSet> fetchedResults = new HashSet<>();
    while(results.hasNext()) {
        final BindingSet next = results.next();
        fetchedResults.add(next);
    }

    Assert.assertEquals(Sets.<BindingSet>newHashSet(bs2), fetchedResults);
}
 
Example 15
Source File: HashJoinTest.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void testSimpleMergeJoinPredicateOnly2() throws Exception {
    //add data
    RyaIRI pred1 = new RyaIRI(litdupsNS, "pred1");
    RyaIRI pred2 = new RyaIRI(litdupsNS, "pred2");
    RyaType one = new RyaType("1");
    RyaType two = new RyaType("2");
    RyaType three = new RyaType("3");
    RyaIRI subj1 = new RyaIRI(litdupsNS, "subj1");
    RyaIRI subj2 = new RyaIRI(litdupsNS, "subj2");
    RyaIRI subj3 = new RyaIRI(litdupsNS, "subj3");
    RyaIRI subj4 = new RyaIRI(litdupsNS, "subj4");

    dao.add(new RyaStatement(subj1, pred1, one));
    dao.add(new RyaStatement(subj1, pred1, two));
    dao.add(new RyaStatement(subj1, pred1, three));
    dao.add(new RyaStatement(subj1, pred2, one));
    dao.add(new RyaStatement(subj1, pred2, two));
    dao.add(new RyaStatement(subj1, pred2, three));
    dao.add(new RyaStatement(subj2, pred1, one));
    dao.add(new RyaStatement(subj2, pred1, two));
    dao.add(new RyaStatement(subj2, pred1, three));
    dao.add(new RyaStatement(subj2, pred2, one));
    dao.add(new RyaStatement(subj2, pred2, two));
    dao.add(new RyaStatement(subj2, pred2, three));
    dao.add(new RyaStatement(subj3, pred1, one));
    dao.add(new RyaStatement(subj3, pred1, two));
    dao.add(new RyaStatement(subj3, pred1, three));
    dao.add(new RyaStatement(subj3, pred2, one));
    dao.add(new RyaStatement(subj3, pred2, two));
    dao.add(new RyaStatement(subj3, pred2, three));
    dao.add(new RyaStatement(subj4, pred1, one));
    dao.add(new RyaStatement(subj4, pred1, two));
    dao.add(new RyaStatement(subj4, pred1, three));
    dao.add(new RyaStatement(subj4, pred2, one));
    dao.add(new RyaStatement(subj4, pred2, two));
    dao.add(new RyaStatement(subj4, pred2, three));
    

    //1 join
    HashJoin ijoin = new HashJoin(dao.getQueryEngine());
    CloseableIteration<RyaStatement, RyaDAOException> join = ijoin.join(null, pred1, pred2);

    int count = 0;
    while (join.hasNext()) {
        RyaStatement next = join.next();
        count++;
    }
    assertEquals(12, count);
    join.close();
}
 
Example 16
Source File: LeftJoinIterator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected BindingSet getNextElement() throws QueryEvaluationException {
	try {
		CloseableIteration<BindingSet, QueryEvaluationException> nextRightIter = rightIter;
		while (nextRightIter.hasNext() || leftIter.hasNext()) {
			BindingSet leftBindings = null;

			if (!nextRightIter.hasNext()) {
				// Use left arg's bindings in case join fails
				leftBindings = leftIter.next();

				nextRightIter.close();
				nextRightIter = rightIter = strategy.evaluate(join.getRightArg(), leftBindings);
			}

			while (nextRightIter.hasNext()) {
				BindingSet rightBindings = nextRightIter.next();

				try {
					if (join.getCondition() == null) {
						return rightBindings;
					} else {
						// Limit the bindings to the ones that are in scope for
						// this filter
						QueryBindingSet scopeBindings = new QueryBindingSet(rightBindings);
						scopeBindings.retainAll(scopeBindingNames);

						if (strategy.isTrue(join.getCondition(), scopeBindings)) {
							return rightBindings;
						}
					}
				} catch (ValueExprEvaluationException e) {
					// Ignore, condition not evaluated successfully
				}
			}

			if (leftBindings != null) {
				// Join failed, return left arg's bindings
				return leftBindings;
			}
		}
	} catch (NoSuchElementException ignore) {
		// probably, one of the iterations has been closed concurrently in
		// handleClose()
	}

	return null;
}
 
Example 17
Source File: RulesetCopyIT.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
    public void testRulesetCopyTool() throws Exception {
        // Should be copied and are involved in the solution:
        final RyaStatement[] solutionStatements = {
            statement("test:FullProfessor1", "rdf:type", "test:FullProfessor"),
            statement("test:GraduateStudent1", "test:advisor", "test:FullProfessor1"),
            statement("test:FullProfessor1", "test:telephone", literal("123-456-7890")),
            statement("test:University1", "test:telephone", literal("555")),
            statement("test:FullProfessor1", "test:worksFor", "test:University1"),
            statement("test:FullProfessor1", "test:hired", literal("2001-01-01T04:01:02.000Z", XMLSchema.DATETIME)),
            statement("test:University1", "geo:asWKT", literal("Point(-77.03524 38.889468)", VF.createIRI("http://www.opengis.net/ont/geosparql#wktLiteral")))
        };
        // These aren't solutions but should be copied:
        final RyaStatement[] copyStatements = {
            statement("test:FullProfessor2", "rdf:type", "test:FullProfessor"),
            statement("test:GraduateStudent1", "test:advisor", "test:AssistantProfessor1"),
            statement("test:GraduateStudent1", "test:telephone", literal("555-123-4567")),
            statement("test:FullProfessor1", "test:telephone", literal("567-8901")),
            statement("test:University1", "test:telephone", literal("800-123-4567"))
        };
        // Should not be copied:
        final RyaStatement[] irrelevantStatements = {
            statement("test:GraduateStudent2", "test:advisor", "test:FullProfessor1"),
            statement("test:UndergraduateStudent1", "rdf:type", "test:UndergraduateStudent"),
            statement("test:UndergraduateStudent2", "rdf:type", "test:UndergraduateStudent"),
            statement("test:GraduateStudent1", "rdf:type", "test:GraduateStudent"),
            statement("test:GraduateStudent1", "test:name", literal("GraduateStudent1")),
            statement("test:UndergraduateStudent2", "test:name", literal("UndergraduateStudent2")),
            statement("test:Course1", "test:name", literal("Course1")),
            statement("test:GraduateStudent1", "test:emailAddress", literal("[email protected]")),
            statement("test:GraduateStudent1", "test:teachingAssistantOf", "test:Course1"),
            statement("test:GraduateStudent2", "test:undergraduateDegreeFrom", "test:University1"),
            statement("test:AssistantProfessor1", "test:teacherOf", "test:Course1"),
            statement("test:FullProfessor1", "test:telephone", literal("xxx-xxx-xxxx")),
            statement("test:University1", "test:telephone", literal("0000")),
            // If inferencing is disabled, these shouldn't matter:
            statement("test:employs", "owl:inverseOf", "test:worksFor"),
            statement("test:University1", "test:employs", "test:FullProfessor2")
        };

        final String query = QUERY_PREFIXES + "SELECT * {\n"
            + "    test:GraduateStudent1 test:advisor ?person .\n"
            + "    ?person rdf:type test:FullProfessor .\n"
            + "    ?person test:telephone ?number .\n"
            + "    ?person test:worksFor ?university .\n"
            + "    FILTER regex(?number, \"...-...-....\")\n"
            + "    ?university geo:asWKT ?place .\n"
            + "    FILTER regex(?number, \"^[0-9]\")\n"
            + "    ?university test:telephone ?universityNumber\n"
            + "    FILTER regex(?universityNumber, \"^5\")\n"
// Would be good to test index functions, but indexing is unreliable (see RYA-72):
            + "    ?person test:hired ?time .\n"
//            + "    FILTER(tempo:after(?time, '2000-01-01T01:01:03-08:00'))\n"
            + "}";

        final int parentNamespaceCount = 2;
        int childNamespaceCount = 0;
        parentDao.addNamespace("ns1", "http://www.example.com/ns1#");
        parentDao.addNamespace("ns2", "http://www.example.com/ns2#");
        // Run the test
        final AccumuloRyaDAO childDao = runRulesetCopyTest(solutionStatements, copyStatements, irrelevantStatements, query, 1, false);
        // Verify namespaces were copied
        final CloseableIteration<Namespace, RyaDAOException> nsIter = childDao.iterateNamespace();
        while (nsIter.hasNext()) {
            childNamespaceCount++;
            nsIter.next();
        }
        Assert.assertEquals("Incorrect number of namespaces copied to child:", parentNamespaceCount, childNamespaceCount);
        log.info("DONE");
    }
 
Example 18
Source File: SailUpdateExecutor.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * @param move
 * @param uc
 * @throws SailException
 */
protected void executeMove(Move move, UpdateContext uc, int maxExecutionTime) throws SailException {
	ValueConstant sourceGraph = move.getSourceGraph();
	ValueConstant destinationGraph = move.getDestinationGraph();

	Resource source = sourceGraph != null ? (Resource) sourceGraph.getValue() : null;
	Resource destination = destinationGraph != null ? (Resource) destinationGraph.getValue() : null;

	if (source == null && destination == null || (source != null && source.equals(destination))) {
		// source and destination are the same, move is a null-operation.
		return;
	}

	// clear destination
	final long start = System.currentTimeMillis();
	con.clear((Resource) destination);
	final long clearTime = (System.currentTimeMillis() - start) / 1000;

	if (maxExecutionTime > 0 && clearTime > maxExecutionTime) {
		throw new SailException("execution took too long");
	}

	// remove all statements from source and add them to destination
	CloseableIteration<? extends Statement, SailException> statements = null;

	try {
		statements = con.getStatements(null, null, null, uc.isIncludeInferred(), (Resource) source);
		if (maxExecutionTime > 0) {
			statements = new TimeLimitIteration<Statement, SailException>(statements,
					1000L * (maxExecutionTime - clearTime)) {

				@Override
				protected void throwInterruptedException() throws SailException {
					throw new SailException("execution took too long");
				}
			};
		}

		while (statements.hasNext()) {
			Statement st = statements.next();
			con.addStatement(uc, st.getSubject(), st.getPredicate(), st.getObject(), (Resource) destination);
			con.removeStatement(uc, st.getSubject(), st.getPredicate(), st.getObject(), (Resource) source);
		}
	} finally {
		if (statements != null) {
			statements.close();
		}
	}
}
 
Example 19
Source File: TupleFunctionFederatedService.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public final CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Service service,
		CloseableIteration<BindingSet, QueryEvaluationException> bindings, String baseUri)
		throws QueryEvaluationException {
	if (!bindings.hasNext()) {
		return new EmptyIteration<>();
	}

	TupleExpr expr = service.getArg();
	if (!(expr instanceof TupleFunctionCall)) {
		return new EmptyIteration<>();
	}

	TupleFunctionCall funcCall = (TupleFunctionCall) expr;
	TupleFunction func = tupleFunctionRegistry.get(funcCall.getURI())
			.orElseThrow(() -> new QueryEvaluationException("Unknown tuple function '" + funcCall.getURI() + "'"));

	List<ValueExpr> argExprs = funcCall.getArgs();

	List<CloseableIteration<BindingSet, QueryEvaluationException>> resultIters = new ArrayList<>();
	while (bindings.hasNext()) {
		BindingSet bs = bindings.next();
		Value[] argValues = new Value[argExprs.size()];
		for (int i = 0; i < argExprs.size(); i++) {
			ValueExpr argExpr = argExprs.get(i);
			Value argValue;
			if (argExpr instanceof Var) {
				argValue = getValue((Var) argExpr, bs);
			} else if (argExpr instanceof ValueConstant) {
				argValue = ((ValueConstant) argExpr).getValue();
			} else {
				throw new ValueExprEvaluationException(
						"Unsupported ValueExpr for argument " + i + ": " + argExpr.getClass().getSimpleName());
			}
			argValues[i] = argValue;
		}
		resultIters
				.add(TupleFunctionEvaluationStrategy.evaluate(func, funcCall.getResultVars(), bs, vf, argValues));
	}
	return (resultIters.size() > 1) ? new DistinctIteration<>(new UnionIteration<>(resultIters))
			: resultIters.get(0);
}
 
Example 20
Source File: AccumuloIndexSetTest.java    From rya with Apache License 2.0 4 votes vote down vote up
@Test
public void accumuloIndexSetTestAttemptJoinAcrossTypes() throws Exception {
    // Load some Triples into Rya.
    final Set<Statement> triples = new HashSet<>();
    triples.add( VF.createStatement(VF.createIRI("http://Alice"), VF.createIRI("http://hasAge"), VF.createLiteral(BigInteger.valueOf(14))) );
    triples.add( VF.createStatement(VF.createIRI("http://Alice"), VF.createIRI("http://playsSport"), VF.createLiteral("Soccer")) );
    triples.add( VF.createStatement(VF.createIRI("http://Bob"), VF.createIRI("http://hasAge"), VF.createLiteral(BigInteger.valueOf(16))) );
    triples.add( VF.createStatement(VF.createIRI("http://Bob"), VF.createIRI("http://playsSport"), VF.createLiteral("Soccer")) );

    for(final Statement triple : triples) {
        ryaConn.add(triple);
    }

    // Create a PCJ table will include those triples in its results.
    final String sparql =
            "SELECT ?name ?age " +
            "{" +
              "?name <http://hasAge> ?age." +
              "?name <http://playsSport> \"Soccer\" " +
            "}";

    final String pcjTableName = new PcjTableNameFactory().makeTableName(prefix, "testPcj");

    // Create and populate the PCJ table.
    PcjIntegrationTestingUtil.createAndPopulatePcj(ryaConn, accumuloConn, pcjTableName, sparql, new String[]{"name", "age"}, Optional.absent());
    final AccumuloIndexSet ais = new AccumuloIndexSet(conf,pcjTableName);

    final QueryBindingSet bs1 = new QueryBindingSet();
    bs1.addBinding("age", VF.createLiteral("16"));
    final QueryBindingSet bs2 = new QueryBindingSet();
    bs2.addBinding("age", VF.createLiteral(BigInteger.valueOf(14)));

    final Set<BindingSet> bSets = Sets.newHashSet(bs1,bs2);

    final CloseableIteration<BindingSet, QueryEvaluationException> results = ais.evaluate(bSets);

    final Set<BindingSet> fetchedResults = new HashSet<>();
    while(results.hasNext()) {
        final BindingSet next = results.next();
        fetchedResults.add(next);
    }

    bs2.addBinding("name", VF.createIRI("http://Alice"));
    Assert.assertEquals(Sets.<BindingSet>newHashSet(bs2), fetchedResults);
}