Java Code Examples for org.openrdf.repository.Repository#getConnection()
The following examples show how to use
org.openrdf.repository.Repository#getConnection() .
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: NamespaceHandler.java From cumulusrdf with Apache License 2.0 | 6 votes |
/** * * @param repository the Repository object * @param request the HttpServletRequest object * @param prefix the prefix * @return the SimpleResponseView which will return the namesapce * @throws ServerHTTPException throws when there is error about the repository * @throws ClientHTTPException throws when there is undefined prefix */ private ModelAndView getExportNamespaceResult(final Repository repository, final HttpServletRequest request, final String prefix) throws ServerHTTPException, ClientHTTPException { try { String namespace = null; RepositoryConnection repositoryCon = repository.getConnection(); synchronized (repositoryCon) { namespace = repositoryCon.getNamespace(prefix); } if (namespace == null) { throw new ClientHTTPException(SC_NOT_FOUND, "Undefined prefix: " + prefix); } Map<String, Object> model = new HashMap<String, Object>(); model.put(SimpleResponseView.CONTENT_KEY, namespace); repositoryCon.close(); return new ModelAndView(SimpleResponseView.getInstance(), model); } catch (RepositoryException e) { throw new ServerHTTPException("Repository error: " + e.getMessage(), e); } }
Example 2
Source File: Utils.java From blazegraph-samples with GNU General Public License v2.0 | 6 votes |
public static TupleQueryResult executeSelectQuery(Repository repo, String query, QueryLanguage ql) throws OpenRDFException { RepositoryConnection cxn; if (repo instanceof BigdataSailRepository) { cxn = ((BigdataSailRepository) repo).getReadOnlyConnection(); } else { cxn = repo.getConnection(); } try { final TupleQuery tupleQuery = cxn.prepareTupleQuery(ql, query); tupleQuery.setIncludeInferred(true /* includeInferred */); return tupleQuery.evaluate(); } finally { // close the repository connection cxn.close(); } }
Example 3
Source File: LoadPdb.java From database with GNU General Public License v2.0 | 6 votes |
public static void executeSelectQuery(Repository repo, String query) throws Exception { RepositoryConnection cxn = repo.getConnection(); int counter = 0; try { final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query); tupleQuery.setIncludeInferred(true /* includeInferred */); TupleQueryResult result = tupleQuery.evaluate(); // do something with the results while (result.hasNext()) { BindingSet bindingSet = result.next(); LOG.info(bindingSet); counter++; } } finally { // close the repository connection cxn.close(); // LOG.info System.err.println ("Number of results: " + counter); } }
Example 4
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 5
Source File: TripleStoreBlazegraph.java From powsybl-core with Mozilla Public License 2.0 | 6 votes |
@Override public void add(TripleStore source) { Objects.requireNonNull(source); Repository sourceRepository; if (source instanceof TripleStoreBlazegraph) { sourceRepository = ((TripleStoreBlazegraph) source).repo; RepositoryConnection sourceConn = null; try { sourceConn = sourceRepository.getConnection(); copyFrom(sourceConn); } catch (RepositoryException e) { LOG.error("Connecting to the source repository : {}", e.getMessage()); } finally { if (sourceConn != null) { closeConnection(sourceConn, "Copying from source"); } } } else { throw new TripleStoreException(String.format("Add to %s from source %s is not supported", getImplementationName(), source.getImplementationName())); } }
Example 6
Source File: GraphHandler.java From cumulusrdf with Apache License 2.0 | 6 votes |
/** * Delete data from the graph. * * @param repository the Repository object * @param request the HttpServletRequest object * @param response the HttpServletResponse object * @return the EmptySuccessView if successes * @throws ClientHTTPException throws when there are errors in getting the name of the Graph * @throws ServerHTTPException throws when errors happens update the data */ private ModelAndView getDeleteDataResult(final Repository repository, final HttpServletRequest request, final HttpServletResponse response) throws ClientHTTPException, ServerHTTPException { ProtocolUtil.logRequestParameters(request); ValueFactory vf = repository.getValueFactory(); URI graph = getGraphName(request, vf); try { RepositoryConnection repositoryCon = repository.getConnection(); synchronized (repositoryCon) { repositoryCon.clear(graph); } repositoryCon.close(); return new ModelAndView(EmptySuccessView.getInstance()); } catch (RepositoryException e) { throw new ServerHTTPException("Repository update error: " + e.getMessage(), e); } }
Example 7
Source File: SizeHandler.java From cumulusrdf with Apache License 2.0 | 5 votes |
@Override public ModelAndView serve(final Repository repository, final HttpServletRequest request, final HttpServletResponse response) throws Exception { ProtocolUtil.logRequestParameters(request); Map<String, Object> model = new HashMap<String, Object>(); final boolean headersOnly = METHOD_HEAD.equals(request.getMethod()); if (!headersOnly) { ValueFactory vf = repository.getValueFactory(); Resource[] contexts = ProtocolUtil.parseContextParam(request, Protocol.CONTEXT_PARAM_NAME, vf); long size = -1; try { RepositoryConnection repositoryCon = repository.getConnection(); synchronized (repositoryCon) { size = repositoryCon.size(contexts); } repositoryCon.close(); } catch (RepositoryException e) { throw new ServerHTTPException("Repository error: " + e.getMessage(), e); } model.put(SimpleResponseView.CONTENT_KEY, String.valueOf(size)); } return new ModelAndView(SimpleResponseView.getInstance(), model); }
Example 8
Source File: TestRDFSInverseInferencer.java From semweb4j with BSD 2-Clause "Simplified" License | 5 votes |
@Test public void testStrangeBug() throws RepositoryException { // create a Sail stack Sail sail = new MemoryStore(); sail = new ForwardChainingRDFSPlusInverseInferencer(sail); // create a Repository Repository repository = new SailRepository(sail); try { repository.initialize(); } catch (RepositoryException e) { throw new RuntimeException(e); } URI p = new URIImpl("urn:rel:p"); URI q = new URIImpl("urn:rel:q"); URI nrlInverse = ForwardChainingRDFSPlusInverseInferencerConnection.NRL_InverseProperty; URI defaultContext = null; // new Resource[0] RepositoryConnection con = repository.getConnection(); // add p-hasInverse-q con.add(p, nrlInverse, q, defaultContext); assertTrue("just added p-haInv-q, should stil be there", con.hasStatement(p, nrlInverse, q, true, defaultContext) ); assertTrue("expect inferred stmt: q-hasInv-p", con.hasStatement(q, nrlInverse, p, true, defaultContext) ); // add (redundant) inverse stmt: q-hasInv-p con.add(q, nrlInverse, p, defaultContext); assertTrue("added p-haInv-q, should stil be there", con.hasStatement(p, nrlInverse, q, true, defaultContext) ); assertTrue( con.hasStatement(p, nrlInverse, q, true, defaultContext) ); assertTrue("added q-hasInv-p, should still be there", con.hasStatement(q, nrlInverse, p, true, defaultContext) ); }
Example 9
Source File: Utils.java From blazegraph-samples with GNU General Public License v2.0 | 5 votes |
public static void loadDataFromResources(Repository repo, String resource, String baseURL) throws OpenRDFException, IOException { RepositoryConnection cxn = repo.getConnection(); try { cxn.begin(); try { InputStream is = SampleBlazegraphCustomFunctionEmbedded.class.getClassLoader().getResourceAsStream(resource); if (is == null) { throw new IOException("Could not locate resource: " + resource); } Reader reader = new InputStreamReader(new BufferedInputStream(is)); try { cxn.add(reader, baseURL, RDFFormat.N3); } finally { reader.close(); } cxn.commit(); } catch (OpenRDFException ex) { cxn.rollback(); throw ex; } } finally { // close the repository connection cxn.close(); } }
Example 10
Source File: StatementHandler.java From cumulusrdf with Apache License 2.0 | 5 votes |
/** * Delete data from the repository. * * @param repository the Repository object * @param request the HttpServletRequest object * @param response the HttpServletResponse object * @return EmptySuccessView if success * @throws HTTPException throws when there are repository update errors */ private ModelAndView getDeleteDataResult(final Repository repository, final HttpServletRequest request, final HttpServletResponse response) throws HTTPException { ProtocolUtil.logRequestParameters(request); ValueFactory vf = repository.getValueFactory(); Resource subj = ProtocolUtil.parseResourceParam(request, SUBJECT_PARAM_NAME, vf); URI pred = ProtocolUtil.parseURIParam(request, PREDICATE_PARAM_NAME, vf); Value obj = ProtocolUtil.parseValueParam(request, OBJECT_PARAM_NAME, vf); Resource[] contexts = ProtocolUtil.parseContextParam(request, CONTEXT_PARAM_NAME, vf); try { RepositoryConnection repositoryCon = repository.getConnection(); synchronized (repositoryCon) { repositoryCon.remove(subj, pred, obj, contexts); } repositoryCon.close(); return new ModelAndView(EmptySuccessView.getInstance()); } catch (RepositoryException e) { if (e.getCause() != null && e.getCause() instanceof HTTPException) { // custom signal from the backend, throw as HTTPException directly // (see SES-1016). throw (HTTPException) e.getCause(); } else { throw new ServerHTTPException("Repository update error: " + e.getMessage(), e); } } }
Example 11
Source File: ContextsHandler.java From cumulusrdf with Apache License 2.0 | 5 votes |
@Override public ModelAndView serve(final Repository repository, final HttpServletRequest request, final HttpServletResponse response) throws Exception { Map<String, Object> model = new HashMap<String, Object>(); TupleQueryResultWriterFactory factory = ProtocolUtil.getAcceptableService(request, response, TupleQueryResultWriterRegistry.getInstance()); if (METHOD_GET.equals(request.getMethod())) { List<String> columnNames = Arrays.asList("contextID"); List<BindingSet> contexts = new ArrayList<BindingSet>(); RepositoryConnection repositoryCon = repository.getConnection(); synchronized (repositoryCon) { try { CloseableIteration<? extends Resource, RepositoryException> contextIter = repositoryCon.getContextIDs(); try { while (contextIter.hasNext()) { BindingSet bindingSet = new ListBindingSet(columnNames, contextIter.next()); contexts.add(bindingSet); } } finally { contextIter.close(); } } catch (RepositoryException e) { throw new ServerHTTPException("Repository error: " + e.getMessage(), e); } } model.put(QueryResultView.QUERY_RESULT_KEY, new TupleQueryResultImpl(columnNames, contexts)); } model.put(QueryResultView.FILENAME_HINT_KEY, "contexts"); model.put(QueryResultView.FACTORY_KEY, factory); model.put(QueryResultView.HEADERS_ONLY, METHOD_HEAD.equals(request.getMethod())); return new ModelAndView(TupleQueryResultView.getInstance(), model); }
Example 12
Source File: SampleCode.java From database with GNU General Public License v2.0 | 5 votes |
/** * Execute a "select" query. * * @param repo * @param query * @param ql * @throws Exception */ public void executeSelectQuery(Repository repo, String query, QueryLanguage ql) 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 { final TupleQuery tupleQuery = cxn.prepareTupleQuery(ql, query); tupleQuery.setIncludeInferred(true /* includeInferred */); TupleQueryResult result = tupleQuery.evaluate(); // do something with the results while (result.hasNext()) { BindingSet bindingSet = result.next(); log.info(bindingSet); } } finally { // close the repository connection cxn.close(); } }
Example 13
Source File: SampleCode.java From database with GNU General Public License v2.0 | 5 votes |
/** * Execute a "construct" query. * * @param repo * @param query * @param ql * @throws Exception */ public void executeConstructQuery(Repository repo, String query, QueryLanguage ql) 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 { // silly construct queries, can't guarantee distinct results final Set<Statement> results = new LinkedHashSet<Statement>(); final GraphQuery graphQuery = cxn.prepareGraphQuery(ql, query); graphQuery.setIncludeInferred(true /* includeInferred */); graphQuery.evaluate(new StatementCollector(results)); // do something with the results for (Statement stmt : results) { log.info(stmt); } } finally { // close the repository connection cxn.close(); } }
Example 14
Source File: SPARQLQueryTest.java From database with GNU General Public License v2.0 | 5 votes |
protected Repository createRepository() throws Exception { Repository repo = newRepository(); repo.initialize(); RepositoryConnection con = repo.getConnection(); try { con.clear(); con.clearNamespaces(); } finally { con.close(); } return repo; }
Example 15
Source File: NamespacesHandler.java From cumulusrdf with Apache License 2.0 | 4 votes |
/** * * @param repository the Repository object * @param request the HttpServletRequest object * @param response the HttpServletResponse oject * @return QueryResultView object include the namespaces * @throws ClientHTTPException throws when errors in the request * @throws ServerHTTPException throws when errors in the Repository * @throws RepositoryException throws when errors in closing the RepositoryConnection */ private ModelAndView getExportNamespacesResult(final Repository repository, final HttpServletRequest request, final HttpServletResponse response) throws ClientHTTPException, ServerHTTPException, RepositoryException { final boolean headersOnly = METHOD_HEAD.equals(request.getMethod()); Map<String, Object> model = new HashMap<String, Object>(); if (!headersOnly) { List<String> columnNames = Arrays.asList("prefix", "namespace"); List<BindingSet> namespaces = new ArrayList<BindingSet>(); RepositoryConnection repositoryCon = repository.getConnection(); synchronized (repositoryCon) { try { CloseableIteration<? extends Namespace, RepositoryException> iter = repositoryCon.getNamespaces(); try { while (iter.hasNext()) { Namespace ns = iter.next(); Literal prefix = new LiteralImpl(ns.getPrefix()); Literal namespace = new LiteralImpl(ns.getName()); BindingSet bindingSet = new ListBindingSet(columnNames, prefix, namespace); namespaces.add(bindingSet); } } finally { iter.close(); } } catch (RepositoryException e) { throw new ServerHTTPException("Repository error: " + e.getMessage(), e); } } model.put(QueryResultView.QUERY_RESULT_KEY, new TupleQueryResultImpl(columnNames, namespaces)); repositoryCon.close(); } TupleQueryResultWriterFactory factory = ProtocolUtil.getAcceptableService(request, response, TupleQueryResultWriterRegistry.getInstance()); model.put(QueryResultView.FILENAME_HINT_KEY, "namespaces"); model.put(QueryResultView.HEADERS_ONLY, headersOnly); model.put(QueryResultView.FACTORY_KEY, factory); return new ModelAndView(TupleQueryResultView.getInstance(), model); }
Example 16
Source File: RepositoryListHandler.java From cumulusrdf with Apache License 2.0 | 4 votes |
@Override public ModelAndView serve(final Repository repository, final HttpServletRequest request, final HttpServletResponse response) throws Exception { Map<String, Object> model = new HashMap<String, Object>(); if (METHOD_GET.equals(request.getMethod())) { Repository systemRepository = _repositoryManager.getSystemRepository(); ValueFactory vf = systemRepository.getValueFactory(); try { RepositoryConnection con = systemRepository.getConnection(); try { // connection before returning. Would be much better to stream the query result directly to the client. List<String> bindingNames = new ArrayList<String>(); List<BindingSet> bindingSets = new ArrayList<BindingSet>(); TupleQueryResult queryResult = con.prepareTupleQuery(QueryLanguage.SERQL, REPOSITORY_LIST_QUERY).evaluate(); try { // Determine the repository's URI StringBuffer requestURL = request.getRequestURL(); if (requestURL.charAt(requestURL.length() - 1) != '/') { requestURL.append('/'); } String namespace = requestURL.toString(); while (queryResult.hasNext()) { QueryBindingSet bindings = new QueryBindingSet(queryResult.next()); String id = bindings.getValue("id").stringValue(); bindings.addBinding("uri", vf.createURI(namespace, id)); bindingSets.add(bindings); } bindingNames.add("uri"); bindingNames.addAll(queryResult.getBindingNames()); } finally { queryResult.close(); } model.put(QueryResultView.QUERY_RESULT_KEY, new TupleQueryResultImpl(bindingNames, bindingSets)); } finally { con.close(); } } catch (RepositoryException e) { throw new ServerHTTPException(e.getMessage(), e); } } TupleQueryResultWriterFactory factory = ProtocolUtil.getAcceptableService(request, response, TupleQueryResultWriterRegistry.getInstance()); model.put(QueryResultView.FILENAME_HINT_KEY, "repositories"); model.put(QueryResultView.FACTORY_KEY, factory); model.put(QueryResultView.HEADERS_ONLY, METHOD_HEAD.equals(request.getMethod())); return new ModelAndView(TupleQueryResultView.getInstance(), model); }
Example 17
Source File: TestBOpUtility.java From database with GNU General Public License v2.0 | 4 votes |
public void testOpenWorldEq() throws Exception { final Sail sail = new MemoryStore(); final Repository repo = new SailRepository(sail); repo.initialize(); final RepositoryConnection cxn = repo.getConnection(); try { final ValueFactory vf = sail.getValueFactory(); final URI mike = vf.createURI(BD.NAMESPACE + "mike"); final URI age = vf.createURI(BD.NAMESPACE + "age"); final Literal mikeAge = vf.createLiteral(34); cxn.add(vf.createStatement(mike, RDF.TYPE, RDFS.RESOURCE)); cxn.add(vf.createStatement(mike, age, mikeAge)); final String query = "select * " + "where { " + " ?s ?p ?o . " + " filter (?o < 40) " + "}"; final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query); final TupleQueryResult result = tupleQuery.evaluate(); while (result.hasNext()) { final BindingSet tmp = result.next(); if(log.isInfoEnabled()) log.info(tmp.toString()); } } finally { cxn.close(); repo.shutDown(); } }
Example 18
Source File: SampleCode.java From database with GNU General Public License v2.0 | 4 votes |
/** * 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(); } }
Example 19
Source File: RepositoryModelTest.java From semweb4j with BSD 2-Clause "Simplified" License | 4 votes |
@Test public void testDirectRepositoryAccess() throws Exception { Model model = getModelFactory().createModel(); model.open(); // fetch the Repository, a Connection and a ValueFactory Repository repository = (Repository) model .getUnderlyingModelImplementation(); RepositoryConnection connection = repository.getConnection(); ValueFactory factory = repository.getValueFactory(); // add a statement model.addStatement(subject, predicate, object); // convert the statement parts to OpenRDF data types Resource openRdfSubject = ConversionUtil.toOpenRDF(subject, factory); org.openrdf.model.URI openRdfPredicate = ConversionUtil.toOpenRDF( predicate, factory); Value openRdfObject = ConversionUtil.toOpenRDF(object, factory); org.openrdf.model.URI context = RepositoryModel.DEFAULT_OPENRDF_CONTEXT; // make sure this statement is contained in this model assertTrue(connection.hasStatement(openRdfSubject, openRdfPredicate, openRdfObject, false, context)); // make sure this statement can also be found through the Model API ClosableIterator<? extends Statement> sit = model.findStatements( subject, predicate, object); assertNotNull(sit); assertTrue(sit.hasNext()); Statement s2 = sit.next(); URI s2s = (URI) s2.getSubject(); URI s2p = s2.getPredicate(); URI s2o = (URI) s2.getObject(); assertEquals(subject, s2s); assertEquals(predicate, s2p); assertEquals(object, s2o); // make sure that this statement is only returned once assertFalse(sit.hasNext()); // clean-up sit.close(); connection.close(); model.close(); }
Example 20
Source File: HelloBlazegraph.java From blazegraph-samples with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws OpenRDFException { final Properties props = new Properties(); /* * For more configuration parameters see * http://www.blazegraph.com/docs/api/index.html?com/bigdata/journal/BufferMode.html */ props.put(Options.BUFFER_MODE, BufferMode.DiskRW); // persistent file system located journal props.put(Options.FILE, "/tmp/blazegraph/test.jnl"); // journal file location final BigdataSail sail = new BigdataSail(props); // instantiate a sail final Repository repo = new BigdataSailRepository(sail); // create a Sesame repository repo.initialize(); try { // prepare a statement final URIImpl subject = new URIImpl("http://blazegraph.com/Blazegraph"); final URIImpl predicate = new URIImpl("http://blazegraph.com/says"); final Literal object = new LiteralImpl("hello"); final Statement stmt = new StatementImpl(subject, predicate, object); // open repository connection RepositoryConnection cxn = repo.getConnection(); // upload data to repository try { cxn.begin(); cxn.add(stmt); cxn.commit(); } catch (OpenRDFException ex) { cxn.rollback(); throw ex; } finally { // close the repository connection cxn.close(); } // open connection if (repo instanceof BigdataSailRepository) { cxn = ((BigdataSailRepository) repo).getReadOnlyConnection(); } else { cxn = repo.getConnection(); } // evaluate sparql query try { final TupleQuery tupleQuery = cxn .prepareTupleQuery(QueryLanguage.SPARQL, "select ?p ?o where { <http://blazegraph.com/Blazegraph> ?p ?o . }"); final TupleQueryResult result = tupleQuery.evaluate(); try { while (result.hasNext()) { final BindingSet bindingSet = result.next(); System.err.println(bindingSet); } } finally { result.close(); } } finally { // close the repository connection cxn.close(); } } finally { repo.shutDown(); } }