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

The following examples show how to use org.openrdf.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: SesameTransformationRepairSwitchSet.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void activate(final Collection<SesameSwitchSetMatch> matches) throws RepositoryException {
	final RepositoryConnection con = driver.getConnection();
	final ValueFactory vf = driver.getValueFactory();

	final URI currentPositionProperty = vf.createURI(BASE_PREFIX + CURRENTPOSITION);

	for (final SesameSwitchSetMatch match : matches) {
		final Resource sw = match.getSw();
		final Value position = match.getPosition();
		final Value currentPosition = match.getCurrentPosition();

		final RepositoryResult<Statement> statementsToRemove = con.getStatements(sw, currentPositionProperty, currentPosition, false);
		while (statementsToRemove.hasNext()) {
			con.remove(statementsToRemove.next());
		}

		con.add(sw, currentPositionProperty, position);
	}
}
 
Example 2
Source File: SesameTransformationRepairConnectedSegments.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void activate(final Collection<SesameConnectedSegmentsMatch> matches) throws RepositoryException {
	final RepositoryConnection con = driver.getConnection();
	final ValueFactory vf = driver.getValueFactory();

	final URI connectsTo = vf.createURI(BASE_PREFIX + CONNECTS_TO);
	for (final SesameConnectedSegmentsMatch match : matches) {
		// delete segment2 by removing all (segment2, _, _) and (_, _, segment2) triples
		final RepositoryResult<Statement> outgoingEdges = con.getStatements(match.getSegment2(), null, null, true);
		while (outgoingEdges.hasNext()) {
			con.remove(outgoingEdges.next());
		}
		final RepositoryResult<Statement> incomingEdges = con.getStatements(null, null, match.getSegment2(), true);
		while (incomingEdges.hasNext()) {
			con.remove(incomingEdges.next());
		}

		// insert (segment1)-[:connectsTo]->(segment3) edge
		con.add(match.getSegment1(), connectsTo, match.getSegment3());
	}
}
 
Example 3
Source File: SesameTransformationRepairPosLength.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void activate(final Collection<SesamePosLengthMatch> matches) throws RepositoryException {
	final RepositoryConnection con = driver.getConnection();
	final ValueFactory vf = driver.getValueFactory();

	final URI lengthProperty = vf.createURI(BASE_PREFIX + LENGTH);

	for (final SesamePosLengthMatch match : matches) {
		final Resource segment = match.getSegment();
		final Value length = match.getLength();

		final RepositoryResult<Statement> statementsToRemove = con.getStatements(segment, lengthProperty, length, true);
		while (statementsToRemove.hasNext()) {
			final Statement oldStatement = statementsToRemove.next();
			con.remove(oldStatement);
		}

		final Integer lengthInteger = new Integer(length.stringValue());
		final Integer newLengthInteger = -lengthInteger + 1;
		final Literal newLength = vf.createLiteral(newLengthInteger);
		final Statement newStatement = vf.createStatement(segment, lengthProperty, newLength);
		con.add(newStatement);
	}
}
 
Example 4
Source File: SesameTransformationInjectPosLength.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void activate(final Collection<SesamePosLengthInjectMatch> matches) throws RepositoryException {
	final RepositoryConnection con = driver.getConnection();
	final ValueFactory vf = driver.getValueFactory();

	final URI typeURI = vf.createURI(BASE_PREFIX + ModelConstants.LENGTH);
	final Literal zeroLiteral = vf.createLiteral(0);

	for (final SesamePosLengthInjectMatch match : matches) {
		final URI segment = match.getSegment();

		final RepositoryResult<Statement> statementsToRemove = con.getStatements(segment, typeURI, null, true);
		con.remove(statementsToRemove);

		con.add(segment, typeURI, zeroLiteral);
	}
}
 
Example 5
Source File: CustomSesameDataset.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
/**
 * Tuple pattern query - find all statements with the pattern, where null is
 * a wildcard
 * 
 * @param s
 *            subject (null for wildcard)
 * @param p
 *            predicate (null for wildcard)
 * @param o
 *            object (null for wildcard)
 * @param contexts
 *            varArgs contexts (use default graph if null)
 * @return serialized graph of results
 */
public List<Statement> tuplePattern(Resource s, URI p, Value o,
		Resource... contexts) {
	try {
		RepositoryConnection con = currentRepository.getConnection();
		try {
			RepositoryResult<Statement> repres = con.getStatements(s, p, o,
					true, contexts);
			ArrayList<Statement> reslist = new ArrayList<Statement>();
			while (repres.hasNext()) {
				reslist.add(repres.next());
			}
			return reslist;
		} finally {
			con.close();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 6
Source File: ListTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
private int getSize(Repository repository) throws RepositoryException {
	int size = 0;
	RepositoryConnection connection = null;
	RepositoryResult<Statement> iter = null;
	try {
		connection = repository.getConnection();
		iter = connection.getStatements(null, null, null, false);
		while (iter.hasNext()) {
			iter.next();
			++size;
		}
	} finally {
		if (iter != null)
			iter.close();
		if (connection != null)
			connection.close();
	}
	return size;
}
 
Example 7
Source File: RDFModelParser.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private void importRepository(RepositoryConnection connection, TripleSink sink) throws RepositoryException {
	RepositoryResult<Statement> statements = null;
	try {
		statements=connection.getStatements(null, null, null, false);
		SesameModelParser tripleParser=new SesameModelParser(getNamespaces(connection));
		while(statements.hasNext()) {
			sink.addTriple(tripleParser.parseStatement(statements.next()));
		}
	} finally {
		closeQuietly(statements, "Could not close results after parsing statements");
	}
}
 
Example 8
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
private void write(DataSource ds, RepositoryConnection conn, Resource context) throws RepositoryException {
    LOG.info("Writing context {}", context);

    RepositoryResult<Statement> statements = conn.getStatements(null, null, null, true, context);
    Model model = new LinkedHashModel();
    QueryResults.addAll(statements, model);
    copyNamespacesToModel(conn, model);

    String outname = context.toString();
    write(model, outputStream(ds, outname));
}
 
Example 9
Source File: RDFSingleDataSet.java    From mustard with MIT License 5 votes vote down vote up
@Override
public List<Statement> getStatements(Resource subject, URI predicate, Value object, boolean allowInference) {
	List<Statement> resGraph = new ArrayList<Statement>();

	try {
		RepositoryConnection repCon = rdfRep.getConnection();

		try {
			
			
			RepositoryResult<Statement> statements = repCon.getStatements(subject, predicate, object, allowInference);

			try {
				while (statements.hasNext()) {
					resGraph.add(statements.next());
				}
			}
			finally {
				statements.close();
			}
		} finally {
			repCon.close();
		}

	} catch (Exception e) {
		e.printStackTrace();
	}

	return resGraph;		
}
 
Example 10
Source File: LoadPdb.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public static void readSomeData(Repository repo) throws Exception {

		RepositoryConnection cxn = repo.getConnection();
		int counter = 0;
		try {

			RepositoryResult<Statement> stmts = cxn.getStatements(null, null, null, true /*
																						* include
																						* inferred
																						*/);
			while (stmts.hasNext()) {
				Statement stmt = stmts.next();
				Resource s = stmt.getSubject();
				URI p = stmt.getPredicate();
				Value o = stmt.getObject();
				// do something with the statement
				LOG.info(stmt);

				// cast to BigdataStatement to get at additional information
				BigdataStatement bdStmt = (BigdataStatement) stmt;
				if (bdStmt.isExplicit()) {
					// do one thing
				} else if (bdStmt.isInferred()) {
					// do another thing
				} else { // bdStmt.isAxiom()
					// do something else
				}
				LOG.info(bdStmt.getStatementType());
				counter++;
			}

		} finally {
			// close the repository connection
			cxn.close();

			LOG.info("Number of Triples: " + counter);
		}

	}
 
Example 11
Source File: TestTicket348.java    From database with GNU General Public License v2.0 5 votes vote down vote up
private void executeTest(final SailRepository repo)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, RDFHandlerException,
		IOException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		try {
			conn.setAutoCommit(false);
			final ValueFactory vf = conn.getValueFactory();
	        final URI uri = vf.createURI("os:/elem/example");
	        // run a query which looks for a statement and then adds it if it is not found.
	        addDuringQueryExec(conn, uri, RDF.TYPE, vf.createURI("os:class/Clazz"));
	        // now try to export the statements.
        	final RepositoryResult<Statement> stats = conn.getStatements(null, null, null, false);
	        try {
	        	// materialize the newly added statement.
	        	stats.next();
	        } catch (RuntimeException e) {
	        	fail(e.getLocalizedMessage(), e); // With Bigdata this fails
	        } finally {
	        	stats.close();
	        }
	        conn.rollback(); // discard the result (or commit, but do something to avoid a logged warning from Sesame).
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 12
Source File: StressTest_ClosedByInterrupt_RW.java    From database with GNU General Public License v2.0 5 votes vote down vote up
private Collection<Statement> getStatementsForContext(final RepositoryConnection conn,
        final URI context) throws RepositoryException {
    RepositoryResult<Statement> res = null;
    final Collection<Statement> statements = new ArrayList<Statement>();
    try {
        res = conn.getStatements(null, null, null, false, context);
        while (res.hasNext()) {
            statements.add(res.next());
        }
    } finally {
        res.close();
    }
    return statements;
}
 
Example 13
Source File: TestTicket967.java    From database with GNU General Public License v2.0 5 votes vote down vote up
private void executeTest(final SailRepository repo)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, RDFHandlerException,
		IOException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		try {
			conn.setAutoCommit(false);
			final ValueFactory vf = conn.getValueFactory();
	        final URI uri = vf.createURI("os:/elem/example");
	        // run a query which looks for a statement and then adds it if it is not found.
	        addDuringQueryExec(conn, uri, RDF.TYPE, vf.createURI("os:class/Clazz"));
	        // now try to export the statements.
        	final RepositoryResult<Statement> stats = conn.getStatements(null, null, null, false);
	        try {
	        	// materialize the newly added statement.
	        	stats.next();
	        } catch (RuntimeException e) {
	        	fail(e.getLocalizedMessage(), e); // With Bigdata this fails
	        } finally {
	        	stats.close();
	        }
	        conn.rollback(); // discard the result (or commit, but do something to avoid a logged warning from Sesame).
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 14
Source File: CRUDTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all statements that are present in any context of a repository having the specified subject, predicate and/or object.
 * @param connection A connection to the repository to query.
 * @param subject The subject the returned triples should have or null for any subject.
 * @param predicate The predicate the returned triples should have or null for any predicate.
 * @param object The object the returned triples should have or null for any object.
 * @return Returns the set of all triples present in the repository having the desired spo-structure.
 * @throws RepositoryException Thrown if an error occurs while querying the repository.
 */
private Collection<Statement> getStatements(RepositoryConnection connection, Resource subject, URI predicate, Value object) throws RepositoryException {
    // Query the repository:
    RepositoryResult<Statement> result = connection.getStatements(subject, predicate, object, false);

    // Fetch all statements from the result:
    Collection<Statement> statements = new HashSet<>();
    while (result.hasNext()) {
        statements.add(result.next());
    }
    return statements;
}
 
Example 15
Source File: SesameTransformationInjectSwitchSet.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<SesameSwitchSetInjectMatch> matches) throws RepositoryException {
	final RepositoryConnection con = driver.getConnection();
	final ValueFactory vf = driver.getValueFactory();

	final URI currentPositionProperty = vf.createURI(BASE_PREFIX + CURRENTPOSITION);

	for (final SesameSwitchSetInjectMatch match : matches) {
		final URI sw = match.getSw();
		final RepositoryResult<Statement> statements = con.getStatements(sw, currentPositionProperty, null, true);
		if (!statements.hasNext()) {
			continue;
		}

		final Statement oldStatement = statements.next();

		// delete old statement
		con.remove(oldStatement);

		// get next enum value
		final URI currentPositionURI = (URI) oldStatement.getObject();
		final String currentPositionRDFString = currentPositionURI.getLocalName();
		final String currentPositionString = RdfHelper.removePrefix(Position.class, currentPositionRDFString);
		final Position currentPosition = Position.valueOf(currentPositionString);
		final Position newCurrentPosition = Position.values()[(currentPosition.ordinal() + 1) % Position.values().length];
		final String newCurrentPositionString = RdfHelper.addEnumPrefix(newCurrentPosition);
		final URI newCurrentPositionUri = vf.createURI(BASE_PREFIX + newCurrentPositionString);

		// set new value
		con.add(sw, currentPositionProperty, newCurrentPositionUri);
	}
}
 
Example 16
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
private static int statementsCount(RepositoryConnection conn, Resource ctx) {
    int counter = 0;
    try {
        RepositoryResult<Statement> statements = conn.getStatements(null, null, null, true, ctx);
        while (statements.hasNext()) {
            counter++;
            statements.next();
        }
    } catch (RepositoryException e) {
        LOG.error(e.getMessage());
    }
    return counter;
}
 
Example 17
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void print(PrintStream out) {
    out.println("TripleStore based on Blazegraph");
    RepositoryConnection conn;
    try {
        conn = repo.getConnection();
        try {
            RepositoryResult<Resource> ctxs = conn.getContextIDs();
            while (ctxs.hasNext()) {
                Resource ctx = ctxs.next();
                int size = statementsCount(conn, ctx);
                out.println("    " + ctx + " : " + size);
                if (PRINT_ALL_STATEMENTS) {
                    RepositoryResult<Statement> statements = conn.getStatements(null, null, null, true, ctx);
                    while (statements.hasNext()) {
                        Statement statement = statements.next();
                        out.println("        " + statement.getSubject() + " " + statement.getPredicate() + " "
                            + statement.getObject());
                    }
                }
            }
        } finally {
            closeConnection(conn, "Printing");
        }
    } catch (RepositoryException e) {
        LOG.error(e.getMessage());
    }
}
 
Example 18
Source File: SampleCode.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Read some statements from a repository.
 * 
 * @param repo
 * @param uri
 * @throws Exception
 */
public void readSomeData(Repository repo, URI uri) throws Exception {
    
    /*
     * With MVCC, you read from a historical state to avoid blocking and
     * being blocked by writers.  BigdataSailRepository.getQueryConnection
     * gives you a view of the repository at the last commit point.
     */
    RepositoryConnection cxn;
    if (repo instanceof BigdataSailRepository) { 
        cxn = ((BigdataSailRepository) repo).getReadOnlyConnection();
    } else {
        cxn = repo.getConnection();
    }
    
    try {
        
        RepositoryResult<Statement> stmts = 
            cxn.getStatements(uri, null, null, true /* include inferred */);
        while (stmts.hasNext()) {
            Statement stmt = stmts.next();
            Resource s = stmt.getSubject();
            URI p = stmt.getPredicate();
            Value o = stmt.getObject();
            // do something with the statement
            log.info(stmt);
            
            // cast to BigdataStatement to get at additional information
            BigdataStatement bdStmt = (BigdataStatement) stmt;
            if (bdStmt.isExplicit()) {
                // do one thing
            } else if (bdStmt.isInferred()) {
                // do another thing
            } else { // bdStmt.isAxiom()
                // do something else
            }
            log.info(bdStmt.getStatementType());
        }
        
    } finally {
        // close the repository connection
        cxn.close();
    }
    
}