Java Code Examples for org.eclipse.rdf4j.repository.RepositoryConnection#getStatements()

The following examples show how to use org.eclipse.rdf4j.repository.RepositoryConnection#getStatements() . 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: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testNotDuplicateUris() throws Exception {
    RepositoryConnection conn = repository.getConnection();

    IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc");
    IRI uri1 = VF.createIRI(litdupsNS, "uri1");
    IRI uri2 = VF.createIRI(litdupsNS, "uri1");
    IRI uri3 = VF.createIRI(litdupsNS, "uri1");

    conn.add(cpu, loadPerc, uri1);
    conn.add(cpu, loadPerc, uri2);
    conn.add(cpu, loadPerc, uri3);
    conn.commit();

    RepositoryResult<Statement> result = conn.getStatements(cpu, loadPerc, null, true);
    int count = 0;
    while (result.hasNext()) {
        count++;
        result.next();
    }
    result.close();
    assertEquals(1, count);

    //clean up
    conn.remove(cpu, loadPerc, uri1);
    conn.close();
}
 
Example 2
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testNamedGraphLoad2() throws Exception {
    InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("namedgraphs.trig");
    assertNotNull(stream);
    RepositoryConnection conn = repository.getConnection();
    conn.add(stream, "", RDFFormat.TRIG);
    conn.commit();

    RepositoryResult<Statement> statements = conn.getStatements(null, VF.createIRI("http://www.example.org/vocabulary#name"), null, true, VF.createIRI("http://www.example.org/exampleDocument#G1"));
    int count = 0;
    while (statements.hasNext()) {
        statements.next();
        count++;
    }
    statements.close();
    assertEquals(1, count);

    conn.close();
}
 
Example 3
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testMMRTS152() throws Exception {
        RepositoryConnection conn = repository.getConnection();
        IRI loadPerc = VF.createIRI(litdupsNS, "testPred");
        IRI uri1 = VF.createIRI(litdupsNS, "uri1");
        conn.add(cpu, loadPerc, uri1);
        conn.commit();

        RepositoryResult<Statement> result = conn.getStatements(cpu, loadPerc, null, false);
//        RdfCloudTripleStoreCollectionStatementsIterator iterator = new RdfCloudTripleStoreCollectionStatementsIterator(
//                cpu, loadPerc, null, store.connector,
//                vf, new Configuration(), null);

        while (result.hasNext()) {
            assertTrue(result.hasNext());
            assertNotNull(result.next());
        }

        conn.close();
    }
 
Example 4
Source File: SailTripleSource.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public CloseableIteration<Statement, QueryEvaluationException> getStatements(RepositoryConnection conn, Resource subj, IRI pred, Value obj, Resource... contexts) throws RepositoryException,
		MalformedQueryException, QueryEvaluationException {
	
	// TODO add handling for contexts
	RepositoryResult<Statement> repoResult = conn.getStatements(subj, pred, obj, true);
	
	// XXX implementation remark and TODO taken from Sesame
	// The same variable might have been used multiple times in this
	// StatementPattern, verify value equality in those cases.
	
	return new ExceptionConvertingIteration<Statement, QueryEvaluationException>(repoResult) {
		@Override
		protected QueryEvaluationException convert(Exception arg0) {
			return new QueryEvaluationException(arg0);
		}
	};
}
 
Example 5
Source File: SparqlTripleSource.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public CloseableIteration<Statement, QueryEvaluationException> getStatements(
		RepositoryConnection conn, Resource subj, IRI pred, Value obj,
		Resource... contexts) throws RepositoryException,
		MalformedQueryException, QueryEvaluationException
{
	
	// TODO add handling for contexts
	monitorRemoteRequest();
	RepositoryResult<Statement> repoResult = conn.getStatements(subj, pred, obj, true);
	
	return new ExceptionConvertingIteration<Statement, QueryEvaluationException>(repoResult) {
		@Override
		protected QueryEvaluationException convert(Exception arg0) {
			return new QueryEvaluationException(arg0);
		}
	};		
}
 
Example 6
Source File: RepositoryPerformance.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private List<IRI> retrieveInstances(RepositoryConnection conn) throws Exception {

			List<IRI> res = new ArrayList<>();
			RepositoryResult<Statement> qres = null;
			try {
				qres = conn.getStatements(null, RDF.TYPE, type, false);
				while (qres.hasNext() && res.size() < MAX_INSTANCES) {
					Statement next = qres.next();
					res.add((IRI) next.getObject());
				}
			} finally {
				try {
					if (qres != null) {
						qres.close();
					}
				} catch (Exception ignore) {
				}
			}
			return res;
		}
 
Example 7
Source File: RemoteRepositoryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static List<IRI> retrieveInstances(RepositoryConnection conn, IRI type) throws Exception {

		List<IRI> res = new ArrayList<>();
		RepositoryResult<Statement> qres = null;
		try {
			qres = conn.getStatements(null, RDF.TYPE, type, false);
			while (qres.hasNext() && res.size() < MAX_INSTANCES) {
				Statement next = qres.next();
				res.add((IRI) next.getObject());
			}
		} finally {
			try {
				if (qres != null) {
					qres.close();
				}
			} catch (Exception ignore) {
			}
		}
		return res;
	}
 
Example 8
Source File: ExportServlet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void service(WorkbenchRequest req, HttpServletResponse resp, TupleResultBuilder builder,
		RepositoryConnection con) throws Exception {
	int limit = ExploreServlet.LIMIT_DEFAULT;
	if (req.getInt(ExploreServlet.LIMIT) > 0) {
		limit = req.getInt(ExploreServlet.LIMIT);
	}
	try (RepositoryResult<Statement> result = con.getStatements(null, null, null, false)) {
		for (int i = 0; result.hasNext() && (i < limit || limit < 1); i++) {
			Statement st = result.next();
			builder.result(st.getSubject(), st.getPredicate(), st.getObject(), st.getContext());
		}
	}
}
 
Example 9
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 5 votes vote down vote up
public void testAddStatement() throws Exception {
        RepositoryConnection conn = repository.getConnection();

        IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc");
        IRI uri1 = VF.createIRI(litdupsNS, "uri1");
        conn.add(cpu, loadPerc, uri1);
        conn.commit();

        RepositoryResult<Statement> result = conn.getStatements(cpu, loadPerc, null, true);
        int count = 0;
        while (result.hasNext()) {
            count++;
            result.next();
        }
        result.close();
        assertEquals(1, count);

        //clean up
        conn.remove(cpu, loadPerc, uri1);

//        //test removal
        result = conn.getStatements(cpu, loadPerc, null, true);
        count = 0;
        while (result.hasNext()) {
            count++;
            result.next();
        }
        result.close();
        assertEquals(0, count);

        conn.close();
    }
 
Example 10
Source File: LocalRepositoryManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private String getRepositoryID(RepositoryConnection con, Resource context) throws RepositoryException {
	String result = null;

	try (RepositoryResult<Statement> idStatements = con.getStatements(null, REPOSITORYID, null, true,
			context)) {
		if (idStatements.hasNext()) {
			Statement idStatement = idStatements.next();
			result = idStatement.getObject().stringValue();
		}
	}

	return result;
}
 
Example 11
Source File: NoReification.java    From inception with Apache License 2.0 5 votes vote down vote up
private void delete(RepositoryConnection aConnection, KnowledgeBase kb, String aIdentifier)
{
    ValueFactory vf = aConnection.getValueFactory();
    IRI iri = vf.createIRI(aIdentifier);
    try (RepositoryResult<Statement> subStmts = aConnection.getStatements(iri, null, null);
            RepositoryResult<Statement> predStmts = aConnection.getStatements(null, iri, null);
            RepositoryResult<Statement> objStmts = aConnection.getStatements(null, null, iri)) {
        aConnection.remove(subStmts);
        aConnection.remove(predStmts);
        aConnection.remove(objStmts);
    }
}
 
Example 12
Source File: GetStatementsRyaCommand.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
protected Object doRyaExecute() throws Exception {
    if (subject == null && predicate == null && object == null && context == null) {
        System.out.println("Please specify subject|predicate|object|context");
        return null;
    }

    System.out.println(subject);
    System.out.println(predicate);
    System.out.println(object);
    System.out.println(context);
    RepositoryConnection connection = null;
    try {
        connection = repository.getConnection();
        RepositoryResult<Statement> statements = connection.getStatements(
                (subject != null) ? (Resource) createValue(subject) : null,
                (predicate != null) ? (IRI) createValue(predicate) : null,
                (object != null) ? createValue(object) : null,
                false,
                (context != null) ? new Resource[]{(Resource) createValue(context)} : new Resource[0]);
        while(statements.hasNext()) {
            System.out.println(statements.next());
        }
        statements.close();
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
    return null;
}
 
Example 13
Source File: IsolationLevelTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected Literal readLiteral(RepositoryConnection con, final IRI subj, final IRI pred) throws RepositoryException {
	try (CloseableIteration<? extends Statement, RepositoryException> stmts = con.getStatements(subj, pred, null,
			false);) {
		if (!stmts.hasNext()) {
			return null;
		}
		Value obj = stmts.next().getObject();
		if (stmts.hasNext()) {
			org.junit.Assert.fail("multiple literals: " + obj + " and " + stmts.next());
		}
		return (Literal) obj;
	}
}
 
Example 14
Source File: IsolationLevelTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected long count(RepositoryConnection con, Resource subj, IRI pred, Value obj, boolean includeInferred,
		Resource... contexts) throws RepositoryException {
	try (CloseableIteration<Statement, RepositoryException> stmts = con.getStatements(subj, pred, obj,
			includeInferred, contexts);) {
		long counter = 0;
		while (stmts.hasNext()) {
			stmts.next();
			counter++;
		}
		return counter;
	}
}
 
Example 15
Source File: SailTripleSource.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public CloseableIteration<BindingSet, QueryEvaluationException> getStatements(
		StatementPattern stmt, RepositoryConnection conn,
		final BindingSet bindings, FilterValueExpr filterExpr)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException  {

	Value subjValue = QueryAlgebraUtil.getVarValue(stmt.getSubjectVar(), bindings);
	Value predValue = QueryAlgebraUtil.getVarValue(stmt.getPredicateVar(), bindings);
	Value objValue = QueryAlgebraUtil.getVarValue(stmt.getObjectVar(), bindings);			
	
	RepositoryResult<Statement> repoResult = conn.getStatements((Resource)subjValue, (IRI)predValue, objValue, true, new Resource[0]);
			
	// XXX implementation remark and TODO taken from Sesame
	// The same variable might have been used multiple times in this
	// StatementPattern, verify value equality in those cases.
	
	// an iterator that converts the statements to var bindings
	CloseableIteration<BindingSet, QueryEvaluationException> res = new StatementConversionIteration(repoResult, bindings, stmt);
			
	// if filter is set, apply it
	if (filterExpr != null) {
		CloseableIteration<BindingSet, QueryEvaluationException> fres = new FilteringIteration(strategy, filterExpr, res);
		if (!fres.hasNext())
			return new EmptyIteration<BindingSet, QueryEvaluationException>();
		return fres;
	}		
	
	return res;
}
 
Example 16
Source File: TripleStoreRDF4J.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
private static int statementsCount(RepositoryConnection conn, Resource ctx) {
    RepositoryResult<Statement> statements = conn.getStatements(null, null, null, ctx);
    int counter = 0;
    while (statements.hasNext()) {
        counter++;
        statements.next();
    }
    return counter;
}
 
Example 17
Source File: AbstractLuceneSailSpinTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public int countStatements(RepositoryConnection connection) throws Exception {
	RepositoryResult<Statement> sts = connection.getStatements(null, null, null, new Resource[] {});
	return Iterations.asList(sts).size();
}
 
Example 18
Source File: LinearTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private int size(RepositoryConnection con, Resource subj, IRI pred, Value obj, boolean inf, Resource... ctx)
		throws Exception {
	try (RepositoryResult<Statement> statements = con.getStatements(subj, pred, obj, inf, ctx);) {
		return QueryResults.asList(statements).size();
	}
}
 
Example 19
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 4 votes vote down vote up
public void testSubClassOf() throws Exception {
      if(internalInferenceEngine == null)
 {
	return; //infer not supported;
}

      RepositoryConnection conn = repository.getConnection();
      conn.add(VF.createStatement(VF.createIRI(litdupsNS, "UndergraduateStudent"), RDFS.SUBCLASSOF, VF.createIRI(litdupsNS, "Student")));
      conn.add(VF.createStatement(VF.createIRI(litdupsNS, "Student"), RDFS.SUBCLASSOF, VF.createIRI(litdupsNS, "Person")));
      conn.add(VF.createStatement(VF.createIRI(litdupsNS, "UgradA"), RDF.TYPE, VF.createIRI(litdupsNS, "UndergraduateStudent")));
      conn.add(VF.createStatement(VF.createIRI(litdupsNS, "StudentB"), RDF.TYPE, VF.createIRI(litdupsNS, "Student")));
      conn.add(VF.createStatement(VF.createIRI(litdupsNS, "PersonC"), RDF.TYPE, VF.createIRI(litdupsNS, "Person")));
      conn.commit();
      conn.close();

      internalInferenceEngine.refreshGraph();

      conn = repository.getConnection();

      //simple api first
      RepositoryResult<Statement> person = conn.getStatements(null, RDF.TYPE, VF.createIRI(litdupsNS, "Person"), true);
      int count = 0;
      while (person.hasNext()) {
          count++;
          person.next();
      }
      person.close();
      assertEquals(3, count);

      String query = "PREFIX rdfs: <" + RDFS.NAMESPACE + ">\n" +
              "PREFIX rdf: <" + RDF.NAMESPACE + ">\n" +
              "PREFIX lit: <" + litdupsNS + ">\n" +
              "select * where {?s rdf:type lit:Person.}";

      TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
      CountTupleHandler tupleHandler = new CountTupleHandler();
      tupleQuery.evaluate(tupleHandler);
      assertEquals(3, tupleHandler.getCount());

      query = "PREFIX rdfs: <" + RDFS.NAMESPACE + ">\n" +
              "PREFIX rdf: <" + RDF.NAMESPACE + ">\n" +
              "PREFIX lit: <" + litdupsNS + ">\n" +
              "select * where {?s rdf:type lit:Student.}";

      tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
      tupleHandler = new CountTupleHandler();
      tupleQuery.evaluate(tupleHandler);
      assertEquals(2, tupleHandler.getCount());

      query = "PREFIX rdfs: <" + RDFS.NAMESPACE + ">\n" +
              "PREFIX rdf: <" + RDF.NAMESPACE + ">\n" +
              "PREFIX lit: <" + litdupsNS + ">\n" +
              "select * where {?s rdf:type lit:UndergraduateStudent.}";

      tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
      tupleHandler = new CountTupleHandler();
      tupleQuery.evaluate(tupleHandler);
      assertEquals(1, tupleHandler.getCount());

      conn.close();
  }
 
Example 20
Source File: Connections.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Retrieve a single {@link Statement} matching with the supplied subject, predicate, object and context(s) from the
 * given {@link RepositoryConnection}. If more than one Statement matches, any one Statement is selected and
 * returned.
 *
 * @param conn      the {@link RepositoryConnection} from which to retrieve the statement.
 * @param subject   the subject to which the statement should match. May be {@code null}.
 * @param predicate the predicate to which the statement should match. May be {@code null}.
 * @param object    the object to which the statement should match. May be {@code null} .
 * @param contexts  the context(s) from which to read the Statement. This argument is an optional vararg and can be
 *                  left out.
 * @return an {@link Optional} of {@link Statement}. If no matching Statement was found, {@link Optional#empty()} is
 *         returned.
 * @throws RepositoryException
 */
public static Optional<Statement> getStatement(RepositoryConnection conn, Resource subject, IRI predicate,
		Value object, Resource... contexts) throws RepositoryException {
	try (RepositoryResult<Statement> stmts = conn.getStatements(subject, predicate, object, contexts)) {
		Statement st = stmts.hasNext() ? stmts.next() : null;
		return Optional.ofNullable(st);
	}
}