org.openrdf.repository.RepositoryConnection Java Examples
The following examples show how to use
org.openrdf.repository.RepositoryConnection.
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: Concurrency.java From database with GNU General Public License v2.0 | 6 votes |
/** * Issue the query. * * @throws Exception */ private void doQuery() throws Exception { RepositoryConnection cxn = repo.getReadOnlyConnection(); try { final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query); tupleQuery.setIncludeInferred(true /* includeInferred */); TupleQueryResult result = tupleQuery.evaluate(); // do something with the results int resultCount = 0; while (result.hasNext()) { BindingSet bindingSet = result.next(); // log.info(bindingSet); resultCount++; } log.info(resultCount + " results"); } finally { // close the repository connection cxn.close(); } }
Example #2
Source File: TestTicket967.java From database with GNU General Public License v2.0 | 6 votes |
private void addDuringQueryExec(final RepositoryConnection conn, final Resource subj, final URI pred, final Value obj, final Resource... ctx) throws RepositoryException, MalformedQueryException, QueryEvaluationException { final TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, "select distinct ?s ?p ?o where{?s ?p ?t . ?t <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?o }" ); tq.setBinding("s", subj); tq.setBinding("p", pred); tq.setBinding("o", obj); final TupleQueryResult tqr = tq.evaluate(); try { if (!tqr.hasNext()) { conn.add(subj, pred, obj, ctx); } } finally { tqr.close(); } }
Example #3
Source File: ListTest.java From anno4j with Apache License 2.0 | 6 votes |
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 #4
Source File: TestTicket276.java From database with GNU General Public License v2.0 | 6 votes |
private void addData(final RepositoryConnection conn) throws IOException, RDFParseException, RepositoryException, RDFHandlerException { final RDFParser rdfParser = Rio.createParser(RDFFormat.NTRIPLES, conn.getValueFactory()); rdfParser.setVerifyData(true); rdfParser.setStopAtFirstError(true); rdfParser.setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE); rdfParser.setRDFHandler(new RDFHandlerBase() { @Override public void handleStatement(Statement st) throws RDFHandlerException { try { conn.add(st); } catch (OpenRDFException e) { throw new RDFHandlerException(e); } } }); rdfParser.parse(getClass().getResourceAsStream("TestTicket276.n3"), ""); }
Example #5
Source File: TestTicket4249.java From database with GNU General Public License v2.0 | 6 votes |
private void executeQuery(final RepositoryConnection conn, final String string, final double start, final double length, final String expected) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFParseException, IOException, VisitorException { final ValueFactory vf = conn.getValueFactory(); final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start, ?length) as ?substring ) . }"; final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); q.setBinding("string", vf.createLiteral(string)); q.setBinding("start", vf.createLiteral(start)); q.setBinding("length", vf.createLiteral(length)); final TupleQueryResult tqr = q.evaluate(); try { while (tqr.hasNext()) { final BindingSet bindings = tqr.next(); // assert expected value assertEquals(expected, bindings.getBinding("substring").getValue().stringValue()); } } finally { tqr.close(); } }
Example #6
Source File: CustomSesameDataset.java From GeoTriples with Apache License 2.0 | 6 votes |
/** * 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: TestTicket4249.java From database with GNU General Public License v2.0 | 6 votes |
private void executeQuery(final RepositoryConnection conn, final Literal string, final int start, final Literal expected) throws RepositoryException, MalformedQueryException, QueryEvaluationException { final ValueFactory vf = conn.getValueFactory(); final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start) as ?substring ) . }"; final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); q.setBinding("string", string); q.setBinding("start", vf.createLiteral(start)); final TupleQueryResult tqr = q.evaluate(); try { while (tqr.hasNext()) { final BindingSet bindings = tqr.next(); // assert expected value assertEquals(expected, bindings.getBinding("substring").getValue()); } } finally { tqr.close(); } }
Example #8
Source File: TripleStoreBlazegraph.java From powsybl-core with Mozilla Public License 2.0 | 6 votes |
@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 #9
Source File: TripleStoreBlazegraph.java From powsybl-core with Mozilla Public License 2.0 | 6 votes |
@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 #10
Source File: TripleStoreBlazegraph.java From powsybl-core with Mozilla Public License 2.0 | 6 votes |
@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 #11
Source File: CustomSesameDataset.java From GeoTriples with Apache License 2.0 | 6 votes |
/** * Literal factory * * @param s * the literal value * @param typeuri * uri representing the type (generally xsd) * @return */ public org.openrdf.model.Literal Literal(String s, URI typeuri) { try { RepositoryConnection con = currentRepository.getConnection(); try { ValueFactory vf = con.getValueFactory(); if (typeuri == null) { return vf.createLiteral(s); } else { return vf.createLiteral(s, typeuri); } } finally { con.close(); } } catch (Exception e) { e.printStackTrace(); return null; } }
Example #12
Source File: TripleStoreBlazegraph.java From powsybl-core with Mozilla Public License 2.0 | 6 votes |
@Override public void read(InputStream is, String base, String name) { RepositoryConnection cnx = null; try { cnx = repo.getConnection(); cnx.begin(); Resource context = context(cnx, name); read(is, base, name, cnx, context); cnx.commit(); addNamespaceForBase(cnx, base); } catch (RepositoryException x) { throw new TripleStoreException(String.format("Reading. Repo problem %s %s", name, base), x); } finally { closeConnection(cnx, "Reading"); } }
Example #13
Source File: ObjectRepository.java From anno4j with Apache License 2.0 | 6 votes |
/** * Creates a new ObjectConnection that will need to be closed by the caller. */ @Override public ObjectConnection getConnection() throws RepositoryException { BlobStore blobs; try { blobs = getBlobStore(); } catch (ObjectStoreConfigException e) { throw new RepositoryException(e); } ObjectFactory factory = service.createObjectFactory(); RepositoryConnection conn = getDelegate().getConnection(); ObjectConnection con = new ObjectConnection(this, conn, factory, createTypeManager(), blobs, idGenerator); con.setIncludeInferred(isIncludeInferred()); con.setMaxQueryTime(getMaxQueryTime()); // con.setQueryResultLimit(getQueryResultLimit()); con.setQueryLanguage(getQueryLanguage()); con.setReadContexts(getReadContexts()); con.setAddContexts(getAddContexts()); con.setRemoveContexts(getRemoveContexts()); con.setArchiveContexts(getArchiveContexts()); return con; }
Example #14
Source File: NamespaceHandler.java From cumulusrdf with Apache License 2.0 | 6 votes |
/** * update the namespace. * * @param repository the Repository object * @param request the HttpServletRequest object * @param prefix the prefix * @return EmptySuccessView object if success * @throws IOException throws if there is error reading the namespace from the HttpServletRequest * @throws ClientHTTPException throws if No namespace name found in request body * @throws ServerHTTPException throws when there is error about the repository */ private ModelAndView getUpdateNamespaceResult(final Repository repository, final HttpServletRequest request, final String prefix) throws IOException, ClientHTTPException, ServerHTTPException { String namespace = IOUtil.readString(request.getReader()); namespace = namespace.trim(); if (namespace.length() == 0) { throw new ClientHTTPException(SC_BAD_REQUEST, "No namespace name found in request body"); } try { RepositoryConnection repositoryCon = repository.getConnection(); synchronized (repositoryCon) { repositoryCon.setNamespace(prefix, namespace); } repositoryCon.close(); } catch (RepositoryException e) { throw new ServerHTTPException("Repository error: " + e.getMessage(), e); } return new ModelAndView(EmptySuccessView.getInstance()); }
Example #15
Source File: TestTicket4249.java From database with GNU General Public License v2.0 | 6 votes |
private void executeQuery(final RepositoryConnection conn, final Literal string, final int start, final int length, final Literal expected) throws RepositoryException, MalformedQueryException, QueryEvaluationException { final ValueFactory vf = conn.getValueFactory(); final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start, ?length) as ?substring ) . }"; final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); q.setBinding("string", string); q.setBinding("start", vf.createLiteral(start)); q.setBinding("length", vf.createLiteral(length)); final TupleQueryResult tqr = q.evaluate(); try { while (tqr.hasNext()) { final BindingSet bindings = tqr.next(); // assert expected value assertEquals(expected, bindings.getBinding("substring").getValue()); } } finally { tqr.close(); } }
Example #16
Source File: SemagrowSummariesGenerator.java From CostFed with GNU Affero General Public License v3.0 | 6 votes |
/** * Get total number of distinct subjects of a dataset * @return count */ public static long getSubjectCount(String endpoint) throws Exception { String strQuery = "SELECT (COUNT(DISTINCT ?s) AS ?sbjts) " + // "WHERE " + "{" + "?s ?p ?o " + "} " ; SPARQLRepository repo = new SPARQLRepository(endpoint); repo.initialize(); RepositoryConnection conn = repo.getConnection(); try { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); TupleQueryResult rs = query.evaluate(); return Long.parseLong(rs.next().getValue("sbjts").stringValue()); } finally { conn.close(); repo.shutDown(); } }
Example #17
Source File: CRUDTest.java From anno4j with Apache License 2.0 | 6 votes |
/** * Tests basic object creation and persistence of triples. */ @Test public void testCreate() throws Exception { // Create an Anno4j instance and get its repository connection for direct triple access: Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false); RepositoryConnection repoConnection = anno4j.getRepository().getConnection(); // Test simple object creation: Person p = anno4j.createObject(Person.class, (Resource) new URIImpl("urn:anno4j_test:p1")); p.setMbox("[email protected]"); // Two statments (rdf:type, foaf:mbox) should be created: Collection<Statement> statements = getStatements(repoConnection); assertEquals(2, statements.size()); assertTrue(statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:p1"), new URIImpl(RDF.TYPE), new URIImpl(FOAF.PERSON)))); assertTrue(statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:p1"), new URIImpl(FOAF.MBOX), new LiteralImpl("[email protected]")))); }
Example #18
Source File: SPARQLQueryTest.java From database with GNU General Public License v2.0 | 6 votes |
protected void uploadDataset(Dataset dataset) throws Exception { RepositoryConnection con = dataRep.getConnection(); try { // Merge default and named graphs to filter duplicates Set<URI> graphURIs = new HashSet<URI>(); graphURIs.addAll(dataset.getDefaultGraphs()); graphURIs.addAll(dataset.getNamedGraphs()); for (Resource graphURI : graphURIs) { upload(((URI)graphURI), graphURI); } } finally { con.close(); } }
Example #19
Source File: SemagrowSummariesGenerator.java From CostFed with GNU Affero General Public License v3.0 | 6 votes |
/** * Get Predicate List * @param endPointUrl SPARQL endPoint Url * @param graph Named graph * @return predLst Predicates List */ private static List<String> getPredicates(String endPointUrl, String graph) throws Exception { List<String> predLst = new ArrayList<String>(); String strQuery = getPredQuery(graph); SPARQLRepository repo = new SPARQLRepository(endPointUrl); repo.initialize(); RepositoryConnection conn = repo.getConnection(); try { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); TupleQueryResult res = query.evaluate(); while (res.hasNext()) { String pred = res.next().getValue("p").toString(); predLst.add(pred); } } finally { conn.close(); repo.shutDown(); } return predLst; }
Example #20
Source File: CustomSesameDataset.java From GeoTriples with Apache License 2.0 | 6 votes |
public String printRDF(RDFFormat outform) { try { RepositoryConnection con = currentRepository.getConnection(); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); RDFWriter w = Rio.createWriter(outform, out); con.export(w); String result = new String(out.toByteArray(), "UTF-8"); return result; } finally { con.close(); } } catch (Exception e) { e.printStackTrace(); } return null; }
Example #21
Source File: CustomSesameDataset.java From GeoTriples with Apache License 2.0 | 6 votes |
/** * Execute a CONSTRUCT/DESCRIBE SPARQL query against the graphs * * @param qs * CONSTRUCT or DESCRIBE SPARQL query * @param format * the serialization format for the returned graph * @return serialized graph of results */ public String runSPARQL(String qs, RDFFormat format) { try { RepositoryConnection con = currentRepository.getConnection(); try { GraphQuery query = con.prepareGraphQuery( org.openrdf.query.QueryLanguage.SPARQL, qs); StringWriter stringout = new StringWriter(); RDFWriter w = Rio.createWriter(format, stringout); query.evaluate(w); return stringout.toString(); } finally { con.close(); } } catch (Exception e) { e.printStackTrace(); } return null; }
Example #22
Source File: SPARQLUpdateConformanceTest.java From database with GNU General Public License v2.0 | 6 votes |
protected static String getManifestName(Repository manifestRep, RepositoryConnection con, String manifestFileURL) throws QueryEvaluationException, RepositoryException, MalformedQueryException { // Try to extract suite name from manifest file TupleQuery manifestNameQuery = con.prepareTupleQuery(QueryLanguage.SERQL, "SELECT ManifestName FROM {ManifestURL} rdfs:label {ManifestName}"); manifestNameQuery.setBinding("ManifestURL", manifestRep.getValueFactory().createURI(manifestFileURL)); TupleQueryResult manifestNames = manifestNameQuery.evaluate(); try { if (manifestNames.hasNext()) { return manifestNames.next().getValue("ManifestName").stringValue(); } } finally { manifestNames.close(); } // Derive name from manifest URL int lastSlashIdx = manifestFileURL.lastIndexOf('/'); int secLastSlashIdx = manifestFileURL.lastIndexOf('/', lastSlashIdx - 1); return manifestFileURL.substring(secLastSlashIdx + 1, lastSlashIdx); }
Example #23
Source File: SesameTransformationRepairConnectedSegments.java From trainbenchmark with Eclipse Public License 1.0 | 6 votes |
@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 #24
Source File: SesameTransformationRepairSwitchMonitored.java From trainbenchmark with Eclipse Public License 1.0 | 6 votes |
@Override public void activate(final Collection<SesameSwitchMonitoredMatch> matches) throws Exception { final RepositoryConnection con = driver.getConnection(); final ValueFactory vf = driver.getValueFactory(); final URI sensorEdgeType = vf.createURI(BASE_PREFIX + MONITORED_BY); final URI sensorType = vf.createURI(BASE_PREFIX + SENSOR); final URI trackElementType = vf.createURI(BASE_PREFIX + TRACKELEMENT); for (final SesameSwitchMonitoredMatch match : matches) { final Resource sw = match.getSw(); final URI sensor = vf.createURI(BASE_PREFIX + ID_PREFIX + driver.generateNewVertexId()); // set vertex type con.add(sensor, RDF.TYPE, sensorType); // insert the supertype as well if (!driver.isInferencing()) { con.add(sensor, RDF.TYPE, trackElementType); } // insert edge con.add(sw, sensorEdgeType, sensor); } }
Example #25
Source File: SesameTransformationRepairSwitchSet.java From trainbenchmark with Eclipse Public License 1.0 | 6 votes |
@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 #26
Source File: NativeRepositoryService.java From attic-polygene-java with Apache License 2.0 | 5 votes |
@Override public RepositoryConnection getConnection() throws RepositoryException { if( isNotInitialized ) { return null; } return repo.getConnection(); }
Example #27
Source File: RDFModelFormater.java From ldp4j with Apache License 2.0 | 5 votes |
protected String exportRepository(RepositoryConnection connection) throws RepositoryException, RDFHandlerException { StringWriter writer=new StringWriter(); RDFWriter rdfWriter=Rio.createWriter(getFormat(),writer); if(rdfWriter instanceof TurtleWriter) { rdfWriter=new RebasingTurtleWriter(writer); } connection.export(rdfWriter); return writer.toString(); }
Example #28
Source File: TripleStoreBlazegraph.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
private void closeConnection(RepositoryConnection cnx, String operation) { if (cnx != null) { try { cnx.close(); } catch (RepositoryException x) { LOG.error("{}. Error closing repository connection: {}", operation, x.getMessage()); } } }
Example #29
Source File: SPARQLGraphStreamingOutput.java From neo4j-sparql-extension with GNU General Public License v3.0 | 5 votes |
/** * Creates a new graph streaming output that executes a CONSTRUCT query * and streams the result. * * @param query the CONSTRUCT query to execute * @param writerFactory a RDF writer factory to use for serialisation * @param conn the connection to use for query execution */ public SPARQLGraphStreamingOutput( GraphQuery query, RDFWriterFactory writerFactory, RepositoryConnection conn) { super(conn); this.query = query; this.factory = writerFactory; }
Example #30
Source File: TestTicket353.java From database with GNU General Public License v2.0 | 5 votes |
private void executeQuery(final SailRepository repo) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFParseException, IOException, RDFHandlerException { try { repo.initialize(); final RepositoryConnection conn = repo.getConnection(); conn.setAutoCommit(false); try { final ValueFactory vf = conn.getValueFactory(); conn.add(vf.createURI("os:subject"), vf.createURI("os:prop"), vf.createLiteral("value")); conn.commit(); String query = "SELECT ?b { {} union { ?a ?b ?c } }" ; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); TupleQueryResult tqr = tq.evaluate(); assertTrue(tqr.hasNext()); while (tqr.hasNext()) { System.err.println(tqr.next()); } tqr.close(); } finally { conn.close(); } } finally { repo.shutDown(); } }