Java Code Examples for org.eclipse.rdf4j.repository.RepositoryConnection#close()
The following examples show how to use
org.eclipse.rdf4j.repository.RepositoryConnection#close() .
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: CbSailTest.java From rya with Apache License 2.0 | 6 votes |
public void testSimpleQuery() throws Exception { RepositoryConnection conn = repository.getConnection(); IRI cpu = VF.createIRI(litdupsNS, "cpu"); IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc"); IRI uri1 = VF.createIRI(litdupsNS, "uri1"); conn.add(cpu, loadPerc, uri1); conn.commit(); conn.close(); resultEndpoint.expectedMessageCount(1); //query through camel String query = "select * where {" + "<" + cpu.toString() + "> ?p ?o1." + "}"; template.sendBodyAndHeader(null, CbSailComponent.SPARQL_QUERY_PROP, query); assertMockEndpointsSatisfied(); }
Example 2
Source File: TBSSSummariesGenerator.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 getSubjectsCount(String endpoint) { String strQuery = "SELECT (COUNT(DISTINCT ?s) AS ?sbjts) " + // "WHERE " + "{" + "?s ?p ?o " + "} " ; SPARQLRepository repo = createSPARQLRepository(endpoint); 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(); } }
Example 3
Source File: SummaryGenerator.java From CostFed with GNU Affero General Public License v3.0 | 6 votes |
public static Long getDistinctSubjectCount(String endpoint) { String strQuery = "SELECT (COUNT(distinct ?s) AS ?triples) " + "WHERE " + "{" + "?s ?p ?o " + "} " ; SPARQLRepository repo = createSPARQLRepository(endpoint); RepositoryConnection conn = repo.getConnection(); try { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); TupleQueryResult rs = query.evaluate(); String v = rs.next().getValue("triples").stringValue(); rs.close(); return Long.parseLong(v); } finally { conn.close(); } }
Example 4
Source File: SummaryGenerator.java From CostFed with GNU Affero General Public License v3.0 | 6 votes |
/** * Get total number of triple for a predicate * @param pred Predicate * @param m model * @return triples */ public static Long getTripleCount(String pred, String endpoint) { String strQuery = "SELECT (COUNT(*) AS ?triples) " + // "WHERE " + "{" + "?s <"+pred+"> ?o " + "} " ; SPARQLRepository repo = createSPARQLRepository(endpoint); RepositoryConnection conn = repo.getConnection(); try { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); TupleQueryResult rs = query.evaluate(); String v = rs.next().getValue("triples").stringValue(); rs.close(); return Long.parseLong(v); } finally { conn.close(); } }
Example 5
Source File: RdfCloudTripleStoreConnectionTest.java From rya with Apache License 2.0 | 6 votes |
public void testEvaluateMultiLine() throws Exception { RepositoryConnection conn = repository.getConnection(); IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc"); IRI uri1 = VF.createIRI(litdupsNS, "uri1"); IRI pred2 = VF.createIRI(litdupsNS, "pred2"); IRI uri2 = VF.createIRI(litdupsNS, "uri2"); conn.add(cpu, loadPerc, uri1); conn.add(cpu, pred2, uri2); conn.commit(); String query = "select * where {" + "?x <" + loadPerc.stringValue() + "> ?o1." + "?x <" + pred2.stringValue() + "> ?o2." + "}"; TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); tupleQuery.setBinding(RdfCloudTripleStoreConfiguration.CONF_QUERYPLAN_FLAG, RdfCloudTripleStoreConstants.VALUE_FACTORY.createLiteral(true)); CountTupleHandler cth = new CountTupleHandler(); tupleQuery.evaluate(cth); conn.close(); assertEquals(cth.getCount(), 1); }
Example 6
Source File: SAILFederatedService.java From CostFed with GNU Affero General Public License v3.0 | 6 votes |
@Override public boolean ask(Service service, BindingSet bindings, String baseUri) throws QueryEvaluationException { RepositoryConnection conn = endpoint.getConn(); try { BooleanQuery query = conn.prepareBooleanQuery(QueryLanguage.SPARQL, service.getAskQueryString(), baseUri); Iterator<Binding> bIter = bindings.iterator(); while (bIter.hasNext()) { Binding b = bIter.next(); if (service.getServiceVars().contains(b.getName())) query.setBinding(b.getName(), b.getValue()); } return query.evaluate(); } catch(Throwable e) { throw new QueryEvaluationException(e); } finally { conn.close(); } }
Example 7
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) { 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 8
Source File: RdfCloudTripleStoreConnectionTest.java From rya with Apache License 2.0 | 5 votes |
public void testAddStatement() throws Exception { RepositoryConnection conn = repository.getConnection(); IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc"); IRI uri1 = VF.createIRI(litdupsNS, "uri1"); conn.add(cpu, loadPerc, uri1); conn.commit(); RepositoryResult<Statement> result = conn.getStatements(cpu, loadPerc, null, true); int count = 0; while (result.hasNext()) { count++; result.next(); } result.close(); assertEquals(1, count); //clean up conn.remove(cpu, loadPerc, uri1); // //test removal result = conn.getStatements(cpu, loadPerc, null, true); count = 0; while (result.hasNext()) { count++; result.next(); } result.close(); assertEquals(0, count); conn.close(); }
Example 9
Source File: RdfControllerAccumuloTest.java From rya with Apache License 2.0 | 5 votes |
@Before public void setup() { this.mockMvc = standaloneSetup(controller).build(); try { RepositoryConnection con = repository.getConnection(); con.add(getClass().getResourceAsStream("/test.nt"), "", RDFFormat.NTRIPLES); con.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
Example 10
Source File: SPARQLEmbeddedServer.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
public void stop() throws Exception { Repository systemRepo = new HTTPRepository(Protocol.getRepositoryLocation(getServerUrl(), SystemRepository.ID)); RepositoryConnection con = systemRepo.getConnection(); try { con.clear(); } finally { con.close(); systemRepo.shutDown(); } jetty.stop(); System.clearProperty("org.mortbay.log.class"); }
Example 11
Source File: ContextsController.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> model = new HashMap<>(); 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<>(); RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request); try { try (CloseableIteration<? extends Resource, RepositoryException> contextIter = repositoryCon .getContextIDs()) { while (contextIter.hasNext()) { BindingSet bindingSet = new ListBindingSet(columnNames, contextIter.next()); contexts.add(bindingSet); } } model.put(QueryResultView.QUERY_RESULT_KEY, new IteratingTupleQueryResult(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())); model.put(QueryResultView.CONNECTION_KEY, repositoryCon); } catch (RepositoryException e) { // normally the QueryResultView closes the connection, but not if an exception occurred repositoryCon.close(); throw new ServerHTTPException("Repository error: " + e.getMessage(), e); } } return new ModelAndView(TupleQueryResultView.getInstance(), model); }
Example 12
Source File: RdfControllerTest.java From rya with Apache License 2.0 | 5 votes |
@Before public void setup() { this.mockMvc = standaloneSetup(controller).build(); try { RepositoryConnection con = repository.getConnection(); con.add(getClass().getResourceAsStream("/test.nt"), "", RDFFormat.NTRIPLES); con.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
Example 13
Source File: Federation.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void closeAll(Iterable<RepositoryConnection> connections) { for (RepositoryConnection con : connections) { try { con.close(); } catch (RepositoryException e) { LOGGER.error(e.getMessage(), e); } } }
Example 14
Source File: RdfCloudTripleStoreConnectionTest.java From rya with Apache License 2.0 | 5 votes |
public void testNamespaceUsage() throws Exception { RepositoryConnection conn = repository.getConnection(); conn.setNamespace("lit", litdupsNS); IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc"); final IRI uri1 = VF.createIRI(litdupsNS, "uri1"); conn.add(cpu, loadPerc, uri1); conn.commit(); String query = "PREFIX lit: <" + litdupsNS + ">\n" + "select * where {lit:cpu lit:loadPerc ?o.}"; TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); tupleQuery.evaluate(new TupleQueryResultHandler() { @Override public void startQueryResult(List<String> strings) throws TupleQueryResultHandlerException { } @Override public void endQueryResult() throws TupleQueryResultHandlerException { } @Override public void handleSolution(BindingSet bindingSet) throws TupleQueryResultHandlerException { assertTrue(uri1.toString().equals(bindingSet.getBinding("o").getValue().stringValue())); } @Override public void handleBoolean(boolean paramBoolean) throws QueryResultHandlerException { } @Override public void handleLinks(List<String> paramList) throws QueryResultHandlerException { } }); conn.close(); }
Example 15
Source File: RepositoryFederatedService.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private static void closeQuietly(RepositoryConnection conn) { if (conn == null) { return; } try { conn.close(); } catch (Throwable t) { logger.warn("Failed to close connection:" + t.getMessage()); logger.debug("Details: ", t); } }
Example 16
Source File: GetStatementsRyaCommand.java From rya with Apache License 2.0 | 5 votes |
@Override protected Object doRyaExecute() throws Exception { if (subject == null && predicate == null && object == null && context == null) { System.out.println("Please specify subject|predicate|object|context"); return null; } System.out.println(subject); System.out.println(predicate); System.out.println(object); System.out.println(context); RepositoryConnection connection = null; try { connection = repository.getConnection(); RepositoryResult<Statement> statements = connection.getStatements( (subject != null) ? (Resource) createValue(subject) : null, (predicate != null) ? (IRI) createValue(predicate) : null, (object != null) ? createValue(object) : null, false, (context != null) ? new Resource[]{(Resource) createValue(context)} : new Resource[0]); while(statements.hasNext()) { System.out.println(statements.next()); } statements.close(); } finally { if (connection != null) { connection.close(); } } return null; }
Example 17
Source File: SPARQLComplianceTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
protected void upload(IRI graphURI, Resource context) throws Exception { RepositoryConnection con = getDataRepository().getConnection(); try { con.begin(); RDFFormat rdfFormat = Rio.getParserFormatForFileName(graphURI.toString()).orElse(RDFFormat.TURTLE); RDFParser rdfParser = Rio.createParser(rdfFormat, getDataRepository().getValueFactory()); rdfParser.setVerifyData(false); rdfParser.setDatatypeHandling(DatatypeHandling.IGNORE); // rdfParser.setPreserveBNodeIDs(true); RDFInserter rdfInserter = new RDFInserter(con); rdfInserter.enforceContext(context); rdfParser.setRDFHandler(rdfInserter); URL graphURL = new URL(graphURI.toString()); InputStream in = graphURL.openStream(); try { rdfParser.parse(in, graphURI.toString()); } finally { in.close(); } con.commit(); } catch (Exception e) { if (con.isActive()) { con.rollback(); } throw e; } finally { con.close(); } }
Example 18
Source File: ConnectionManager.java From semagrow with Apache License 2.0 | 5 votes |
public void closeQuietly(RepositoryConnection conn) { try { if (conn.isOpen()) { conn.close(); synchronized (this) { countconn--; } logger.info("Close [{}]", conn); } } catch (RepositoryException e) { logger.warn("Connection [{}] cannot be closed", conn, e); } }
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 RDF4J data types Resource targetSubject = ConversionUtil.toRDF4J(subject, factory); IRI targetPredicate = ConversionUtil.toRDF4J(predicate, factory); Value targetObject = ConversionUtil.toRDF4J(object, factory); IRI context = RepositoryModel.DEFAULT_RDF4J_CONTEXT; // make sure this statement is contained in this model assertTrue(connection.hasStatement(targetSubject, targetPredicate, targetObject, 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: RdfCloudTripleStoreConnectionTest.java From rya with Apache License 2.0 | 4 votes |
public void testNamedGraphLoadWAuth() throws Exception { InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("namedgraphs.trig"); assertNotNull(stream); RdfCloudTripleStore tstore = new MockRdfCloudStore(); NamespaceManager nm = new NamespaceManager(tstore.getRyaDAO(), tstore.getConf()); tstore.setNamespaceManager(nm); SailRepository repo = new SailRepository(tstore); tstore.getRyaDAO().getConf().setCv("1|2"); repo.initialize(); RepositoryConnection conn = repo.getConnection(); conn.add(stream, "", RDFFormat.TRIG); conn.commit(); String query = "PREFIX ex: <http://www.example.org/exampleDocument#>\n" + "PREFIX voc: <http://www.example.org/vocabulary#>\n" + "PREFIX foaf: <http://xmlns.com/foaf/0.1/>\n" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" + "\n" + "SELECT * \n" + // "FROM NAMED <http://www.example.org/exampleDocument#G1>\n" + "WHERE\n" + "{\n" + " GRAPH ex:G1\n" + " {\n" + " ?m voc:name ?name ;\n" + " voc:homepage ?hp .\n" + " } .\n" + " GRAPH ex:G2\n" + " {\n" + " ?m voc:hasSkill ?skill .\n" + " } .\n" + "}"; TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); tupleQuery.setBinding(RdfCloudTripleStoreConfiguration.CONF_QUERY_AUTH, VF.createLiteral("2")); CountTupleHandler tupleHandler = new CountTupleHandler(); tupleQuery.evaluate(tupleHandler); assertEquals(1, tupleHandler.getCount()); tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); //no auth tupleHandler = new CountTupleHandler(); tupleQuery.evaluate(tupleHandler); assertEquals(0, tupleHandler.getCount()); conn.close(); repo.shutDown(); }