org.openrdf.repository.RepositoryResult Java Examples

The following examples show how to use org.openrdf.repository.RepositoryResult. 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: 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 #3
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 #4
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 #5
Source File: TypeManager.java    From anno4j with Apache License 2.0 6 votes vote down vote up
public Set<URI> getTypes(Resource res) throws RepositoryException {
	if (!readTypes)
		return Collections.emptySet();
	RepositoryResult<Statement> match = conn.getStatements(res, RDF.TYPE, null);
	try {
		if (!match.hasNext())
			return Collections.emptySet();
		Value obj = match.next().getObject();
		if (obj instanceof URI && !match.hasNext())
			return Collections.singleton((URI) obj);
		Set<URI> types = new HashSet<URI>(4);
		if (obj instanceof URI) {
			types.add((URI) obj);
		}
		while (match.hasNext()) {
			obj = match.next().getObject();
			if (obj instanceof URI) {
				types.add((URI) obj);
			}
		}
		return types;
	} finally {
		match.close();
	}
}
 
Example #6
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 #7
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 #8
Source File: DeletionTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Test
public void deletePlainAnnotation() throws RepositoryException, IllegalAccessException, InstantiationException, QueryEvaluationException, ParseException, MalformedQueryException {
    // Create test annotation
    Annotation annotation = anno4j.createObject(Annotation.class);
    annotation.setCreated("2015-01-28T12:00:00Z");
    annotation.setGenerated("2015-01-28T12:00:00Z");

    // query persisted object
    Annotation result = (Annotation) anno4j.createQueryService().execute().get(0);

    assertEquals(annotation.getResource().toString(), result.getResource().toString());

    // delete the annotation
    result.delete();

    // checking if there are no statements left
    RepositoryResult<Statement> statements = anno4j.getObjectRepository().getConnection().getStatements(null, null, null);
    assertEquals(false, statements.hasNext());

    // confirming the empty result set with the QueryService
    List<Annotation> emptyList = anno4j.createQueryService().execute();
    assertEquals(0, emptyList.size());
}
 
Example #9
Source File: RepositoryModel.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public Map<String,String> getNamespaces() {
	assertModel();
	Map<String,String> nsMap = new HashMap<String,String>();
	try {
		RepositoryResult<Namespace> openrdfMap = this.connection.getNamespaces();
		openrdfMap.enableDuplicateFilter();
		List<Namespace> openrdfList =  Iterations.asList(openrdfMap);
		for(Namespace openrdfNamespace : openrdfList) {
			nsMap.put(openrdfNamespace.getPrefix(), openrdfNamespace.getName());
		}
		return nsMap;
	} catch(RepositoryException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public Set<String> contextNames() {
    HashSet<String> names = new HashSet<>();
    RepositoryConnection conn = null;
    try {
        conn = repo.getConnection();
        RepositoryResult<Resource> rs = conn.getContextIDs();
        while (rs.hasNext()) {
            names.add(rs.next().stringValue());
        }
        return names;
    } catch (RepositoryException x) {
        LOG.error("getting context names : {}", x.getMessage());
    } finally {
        closeConnection(conn, "Getting context names");
    }
    return names;
}
 
Example #17
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 #18
Source File: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testInsertWhereWithOptional()
	throws Exception
{
	logger.debug("executing testInsertWhereWithOptional");

	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append(" INSERT { ?s ex:age ?incAge } ");
	// update.append(" DELETE { ?s ex:age ?age } ");
	update.append(" WHERE { ?s foaf:name ?name . ");
	update.append(" OPTIONAL {?s ex:age ?age . BIND ((?age + 1) as ?incAge)  } ");
	update.append(" } ");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	URI age = f.createURI(EX_NS, "age");

	assertFalse(con.hasStatement(alice, age, null, true));
	assertTrue(con.hasStatement(bob, age, null, true));

	operation.execute();

	RepositoryResult<Statement> result = con.getStatements(bob, age, null, true);

	while (result.hasNext()) {
		System.out.println(result.next().toString());
	}

	assertTrue(con.hasStatement(bob, age, f.createLiteral("43", XMLSchema.INTEGER), true));

	result = con.getStatements(alice, age, null, true);

	while (result.hasNext()) {
		System.out.println(result.next());
	}
	assertFalse(con.hasStatement(alice, age, null, true));
}
 
Example #19
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 #20
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 #21
Source File: TestBigdataSailRemoteRepository.java    From database with GNU General Public License v2.0 5 votes vote down vote up
protected RepositoryResult<Statement> doGetWithAccessPath(//
         final URI s,//
         final URI p,//
         final Value o,//
         final URI... c//
         ) throws Exception {

	return cxn.getStatements(s, p, o, false/*includeInferred*/, c);
	
}
 
Example #22
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 #23
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 #24
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 #25
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 #26
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 #27
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 #28
Source File: RDFModelParser.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private void closeQuietly(RepositoryResult<?> results, String message) {
	if(results!=null) {
		try {
			results.close();
		} catch (OpenRDFException e) {
			if(LOGGER.isWarnEnabled()) {
				LOGGER.warn(message,e);
			}
		}
	}
}
 
Example #29
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 #30
Source File: RepositoryModelSet.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public ClosableIterator<Statement> iterator() {
	this.assertModel();
	try {
		// find the matching OpenRDF Statements
		RepositoryResult<org.openrdf.model.Statement> statements = this.connection
		        .getStatements(null, null, null, true);
		// wrap them in an iterator that converts them to RDF2Go Statements
		return new StatementIterator(statements);
	} catch(RepositoryException e) {
		throw new ModelRuntimeException(e);
	}
}