Java Code Examples for org.openrdf.repository.RepositoryResult#next()

The following examples show how to use org.openrdf.repository.RepositoryResult#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: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void write(DataSource ds, String contextName) {
    RepositoryConnection conn = null;
    try {
        conn = repo.getConnection();
        RepositoryResult<Resource> contexts = conn.getContextIDs();
        while (contexts.hasNext()) {
            Resource context = contexts.next();
            if (context.stringValue().equals(contextName)) {
                write(ds, conn, context);
            }
        }
    } catch (RepositoryException x) {
        throw new TripleStoreException(String.format("Writing on %s", ds), x);
    } finally {
        closeConnection(conn, "Writing on " + ds);
    }
}
 
Example 2
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void write(DataSource ds) {
    RepositoryConnection conn = null;
    try {
        conn = repo.getConnection();
        RepositoryResult<Resource> contexts = conn.getContextIDs();
        while (contexts.hasNext()) {
            Resource context = contexts.next();
            write(ds, conn, context);
        }
    } catch (RepositoryException x) {
        throw new TripleStoreException(String.format("Writing on %s", ds), x);
    } finally {
        closeConnection(conn, "Writing on " + ds);
    }
}
 
Example 3
Source File: RepositoryModelSet.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public Map<String,String> getNamespaces() {
	this.assertModel();
	Map<String,String> nsMap = new HashMap<String,String>();
	try {
		RepositoryResult<Namespace> openrdfMap = this.connection.getNamespaces();
		openrdfMap.enableDuplicateFilter();
		while (openrdfMap.hasNext()) {
			Namespace openrdfNamespace = openrdfMap.next();
			nsMap.put(openrdfNamespace.getPrefix(), openrdfNamespace.getName());
		}
		return nsMap;
	} catch(RepositoryException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example 4
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public List<PrefixNamespace> getNamespaces() {
    List<PrefixNamespace> namespaces = new ArrayList<>();
    RepositoryConnection cnx = null;
    try {
        cnx = repo.getConnection();
        RepositoryResult<Namespace> ns = cnx.getNamespaces();
        while (ns.hasNext()) {
            Namespace namespace = ns.next();
            namespaces.add(new PrefixNamespace(namespace.getPrefix(), namespace.getName()));
        }
    } catch (RepositoryException x) {
        throw new TripleStoreException("Getting namespaces", x);
    } finally {
        closeConnection(cnx, "Getting namespaces");
    }
    return namespaces;
}
 
Example 5
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 6
Source File: Util.java    From cumulusrdf with Apache License 2.0 6 votes vote down vote up
public static <T> Iterator<T> toResultIterator (final RepositoryResult<T> result) {
	
	return new AbstractIterator<T>() {

		@Override
		protected T computeNext() {
			
			try {
				
				if(result.hasNext()) {
					return result.next();
				}
				
			} catch (RepositoryException e) {
				LOGGER.error(MessageCatalog._00025_CUMULUS_SYSTEM_INTERNAL_FAILURE_MSG + " Could not compute next result.", e);
			}
			return endOfData();
		}
	};
}
 
Example 7
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 8
Source File: AugurTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
public void test_naive() throws Exception {
	ValueFactory vf = con.getValueFactory();
	final URI Bean = vf.createURI(NS, "Bean");
	final URI name = vf.createURI(NS, "name");
	final URI parent = vf.createURI(NS, "parent");
	final URI friend = vf.createURI(NS, "friend");
	long start = System.currentTimeMillis();
	RepositoryResult<Statement> beans = con.getStatements(null, RDF.TYPE, Bean);
	while (beans.hasNext()) {
		Statement st = beans.next();
		Resource bean = st.getSubject();
		QueryResults.asList(con.getStatements(bean, name, null));
		RepositoryResult<Statement> match;
		match = con.getStatements(bean, parent, null);
		while (match.hasNext()) {
			QueryResults.asList(con.getStatements((Resource)match.next().getObject(), name, null));
		}
		match = con.getStatements(bean, friend, null);
		while (match.hasNext()) {
			QueryResults.asList(con.getStatements((Resource)match.next().getObject(), name, null));
		}
	}
	long end = System.currentTimeMillis();
	System.out.println((end - start) / 1000.0);
}
 
Example 9
Source File: TestBigdataSailRemoteRepository.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test the CONTEXTS method.
 */
public void test_CONTEXTS() throws Exception {

	if (getTestMode() != TestMode.quads)
		return;

    doInsertbyURL("POST", packagePath
            + "test_estcard.trig");
    
    final RepositoryResult<Resource> contexts = cxn.getContextIDs();
    
    int size = 0;
    while (contexts.hasNext()) {
    	contexts.next();
    	size++;
    }
    
    assertEquals(3, size);
    
}
 
Example 10
Source File: RDFModelParser.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private Namespaces getNamespaces(RepositoryConnection connection) throws RepositoryException {
	Namespaces ns = new Namespaces();
	RepositoryResult<Namespace> rr = null;
	try {
		rr=connection.getNamespaces();
		while(rr.hasNext()) {
			Namespace n=rr.next();
			ns.addPrefix(n.getPrefix(), n.getName());
		}
	} finally {
		closeQuietly(rr,"Could not close results after retrieving namespaces");
	}
	return ns;
}
 
Example 11
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 12
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 13
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the #of solutions in a result set.
 * 
 * @param result
 *           The result set.
 * 
 * @return The #of solutions.
 */
static protected long countResults(final RepositoryResult<Statement> result)
      throws Exception {

   try {
      long i;
      for (i = 0; result.hasNext(); i++) {
         result.next();
      }
      return i;
   } finally {
      result.close();
   }

}
 
Example 14
Source File: TestTicket1086.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * When loading quads into a triple store, the context is striped away by
 * default.
 */
public void testQuadStripping() throws Exception {

    BigdataSailRepositoryConnection cxn = null;

    final BigdataSail sail = getSail(getTriplesNoInference());

    try {

        sail.initialize();
        final BigdataSailRepository repo = new BigdataSailRepository(sail);
        cxn = (BigdataSailRepositoryConnection) repo.getConnection();

        final BigdataValueFactory vf = (BigdataValueFactory) sail
              .getValueFactory();
        final URI s = vf.createURI("http://test/s");
        final URI p = vf.createURI("http://test/p");
        final URI o = vf.createURI("http://test/o");
        final URI c = vf.createURI("http://test/c");

        BigdataStatement stmt = vf.createStatement(s, p, o, c);
        cxn.add(stmt); 

        RepositoryResult<Statement> stmts = cxn.getStatements(null, null,
              null, false);
        Statement res = stmts.next();
        assertEquals(s, res.getSubject());
        assertEquals(p, res.getPredicate());
        assertEquals(o, res.getObject());
        assertEquals(null, res.getContext());

    } finally {
        if (cxn != null)
            cxn.close();
        sail.__tearDownUnitTest();
    }
}
 
Example 15
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 16
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 17
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 18
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 19
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();
    }
    
}