Java Code Examples for org.openrdf.repository.RepositoryConnection#close()

The following examples show how to use org.openrdf.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: DavidsTestBOps.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void testImplementationDefinedDefaultGraph ()
    throws Exception
{
    final BigdataSail sail = getTheSail () ;
    final ValueFactory vf = sail.getValueFactory();
    final RepositoryConnection cxn = getRepositoryConnection ( sail ) ;
    try {
        final String ns = "http://xyz.com/test#" ;
        final String kb = String.format ( "<%ss> <%sp> <%so> .", ns, ns, ns ) ;
        final String qs = String.format ( "select ?p ?o where { <%ss> ?p ?o .}", ns ) ;

        final Resource graphs [] = new Resource [] { vf.createURI ( String.format ( "%sg1", ns ) ), vf.createURI ( String.format ( "%sg2", ns ) ) } ;

        final Collection<BindingSet> expected = getExpected ( createBindingSet ( new BindingImpl ( "p", new URIImpl ( String.format ( "%sp", ns ) ) )
                                                                               , new BindingImpl ( "o", new URIImpl ( String.format ( "%so", ns ) ) )
                                                                               )
                                                      ) ;
        run ( sail, cxn, kb, graphs, qs, expected ) ;
    } finally {
        cxn.close();
    }
}
 
Example 2
Source File: DavidsTestBOps.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void testExplicitDefaultGraph ()
    throws Exception
{
    final BigdataSail sail = getTheSail () ;
    final ValueFactory vf = sail.getValueFactory();
    final RepositoryConnection cxn = getRepositoryConnection ( sail ) ;
    try {
    String ns = "http://xyz.com/test#" ;
    String kb = String.format ( "<%ss> <%sp> <%so> .", ns, ns, ns ) ;
    String qs = String.format ( "select ?p ?o from <%sg1> from <%sg2> where { <%ss> ?p ?o .}", ns, ns, ns ) ;

    Resource graphs [] = new Resource [] { vf.createURI ( String.format ( "%sg1", ns ) ), vf.createURI ( String.format ( "%sg2", ns ) ) } ;

    Collection<BindingSet> expected = getExpected ( createBindingSet ( new BindingImpl ( "p", new URIImpl ( String.format ( "%sp", ns ) ) )
                                                                     , new BindingImpl ( "o", new URIImpl ( String.format ( "%so", ns ) ) )
                                                                     )
                                                  ) ;
    run ( sail, cxn, kb, graphs, qs, expected ) ;
    } finally {
        cxn.close();
    }
}
 
Example 3
Source File: DavidsTestBOps.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void testExplicitDefaultAndNamedGraphNoGraphKeyword ()
    throws Exception
{
    final BigdataSail sail = getTheSail () ;
    final ValueFactory vf = sail.getValueFactory();
    final RepositoryConnection cxn = getRepositoryConnection ( sail ) ;
    try {
    String ns = "http://xyz.com/test#" ;
    String kb = String.format ( "<%ss> <%sp> <%so> .", ns, ns, ns ) ;
    String qs = String.format ( "select ?s from <%sg1> from named <%sg2> where { ?s ?p ?o .}", ns, ns ) ;

    Resource graphs [] = new Resource [] { vf.createURI ( String.format ( "%sg1", ns ) ), vf.createURI ( String.format ( "%sg2", ns ) ) } ;

    Collection<BindingSet> expected = getExpected ( createBindingSet ( new BindingImpl ( "s", new URIImpl ( String.format ( "%ss", ns ) ) ) ) ) ;

    run ( sail, cxn, kb, graphs, qs, expected ) ;
    } finally {
        cxn.close();
    }
}
 
Example 4
Source File: SemagrowSummariesGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 5
Source File: DavidsTestBOps.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void testNamedGraphNoGraphKeyword2 ()
    throws Exception
{
    final BigdataSail sail = getTheSail () ;
    final ValueFactory vf = sail.getValueFactory();
    final RepositoryConnection cxn = getRepositoryConnection ( sail ) ;
    try {
    String ns = "http://xyz.com/test#" ;
    String kb = String.format ( "<%ss> <%sp> <%so> .", ns, ns, ns ) ;
    String qs = String.format ( "select ?s from named <%sg1> from named <%sg2> where { ?s ?p ?o .}", ns, ns ) ;

    Resource graphs [] = new Resource [] { vf.createURI ( String.format ( "%sg1", ns ) ), vf.createURI ( String.format ( "%sg2", ns ) ) } ;

    Collection<BindingSet> expected = getExpected () ;

    run ( sail, cxn, kb, graphs, qs, expected ) ;
    } finally {
        cxn.close();
    }
}
 
Example 6
Source File: CustomSesameDataset.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
/**
 * 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 7
Source File: CustomSesameDataset.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
/**
 * 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 8
Source File: TestNoExceptions.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final SailRepository repo, final String query)
		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.commit();
			TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
			TupleQueryResult tqr = tq.evaluate();
			tqr.close();
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 9
Source File: CustomSesameDataset.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
/**
 * Dump RDF graph
 * 
 * @param out
 *            output stream for the serialization
 * @param outform
 *            the RDF serialization format for the dump
 * @return
 */
public void dumpRDF(OutputStream out, RDFFormat outform) {
	try {
		RepositoryConnection con = currentRepository.getConnection();
		try {
			RDFWriter w = Rio.createWriter(outform, out);
			con.export(w);
		} finally {
			con.close();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 10
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
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 11
Source File: TestRollbacks.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public Void call() throws Exception {
//            if (writer) {
//                // Initial sleep on the writer.
//                Thread.sleep(500);
//            }
            RepositoryConnection conn = null;
            try {
				int counter2 = 0;
                conn = repo.getConnection();
                conn.setAutoCommit(false);
                while (firstCause.get() == null && counter < maxCounter) {
                    if (writer)
                        writer(conn);
                    else
                        reader(conn);
                    /*
                     * Note: If connection obtained/closed within the loop then
                     * the query is more likely to have some data to visit
                     * within its tx view.
                     */
					if (++counter2 % 4 == 0) {
						conn.close();
						conn = repo.getConnection();
						conn.setAutoCommit(false);
					}
//					conn = repo.getConnection();
//                    conn.setAutoCommit(false);
//                    conn.close();
                }
                return (Void) null;
            } catch (Throwable t) {
                firstCause.compareAndSet(null/* expect */, t);
                throw new RuntimeException(t);
            } finally {
                if (conn != null)
                    conn.close();
            }
        }
 
Example 12
Source File: SPARQLUpdateConformanceTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
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 13
Source File: SampleBlazegraphSesameEmbedded.java    From blazegraph-samples with GNU General Public License v2.0 5 votes vote down vote up
public static void loadDataFromResources(final Repository repo, final String resource, final String baseURL)
		throws OpenRDFException, IOException {

	final RepositoryConnection cxn = repo.getConnection();
	
	try {
		cxn.begin();
		try {
			final InputStream is = SampleBlazegraphSesameEmbedded.class.getResourceAsStream(resource);
			if (is == null) {
				throw new IOException("Could not locate resource: " + resource);
			}
			final 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 14
Source File: TestTicket355.java    From database with GNU General Public License v2.0 5 votes vote down vote up
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 ?subj WHERE { "
					+ "?subj <os:prop> ?val . "
					+ "FILTER(STR(?val) != ?arg)}";
			TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
			tq.setBinding("arg", vf.createLiteral("notValue"));
			TupleQueryResult tqr = tq.evaluate();
			assertTrue(tqr.hasNext());
			tqr.close();
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 15
Source File: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates, initializes and clears a repository.
 * 
 * @return an initialized empty repository.
 * @throws Exception
 */
protected Repository createRepository()
	throws Exception
{
	Repository repository = newRepository();
	repository.initialize();
	RepositoryConnection con = repository.getConnection();
	con.clear();
	con.clearNamespaces();
	con.close();
	return repository;
}
 
Example 16
Source File: NamespacesHandler.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
/**
 * clear the namespaces
 * 
 * @param repository the Repository object
 * @param request the HttpServletRequest object 
 * @param response the HttpServletResponse oject
 * @return EmptySuccessView object if success
 * @throws ServerHTTPException throws when errors in repository
 * @throws RepositoryException throws when errors in closing the RepositoryConnection 
 */
private ModelAndView getClearNamespacesResult(final Repository repository, final HttpServletRequest request, final HttpServletResponse response)
		throws ServerHTTPException, RepositoryException {
	RepositoryConnection repositoryCon = repository.getConnection();
	synchronized (repositoryCon) {
		try {
			repositoryCon.clearNamespaces();
		} catch (RepositoryException e) {
			throw new ServerHTTPException("Repository error: " + e.getMessage(), e);
		}
	}
	repositoryCon.close();
	return new ModelAndView(EmptySuccessView.getInstance());
}
 
Example 17
Source File: SizeHandler.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
@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 18
Source File: TestReadWriteTransactions.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
     * Test the commit semantics in the context of a read-committed view of the
     * database.
     */
    public void test_commit() throws Exception {

        // final LocalTripleStore store = (LocalTripleStore) getStore();
        final BigdataSail sail = getSail();
        try {
        sail.initialize();
        final BigdataSailRepository repo = new BigdataSailRepository(sail);
        final BigdataSailRepositoryConnection isolated = 
            (BigdataSailRepositoryConnection) repo.getReadWriteConnection();
        isolated.setAutoCommit(false);
//        final BigdataSailRepositoryConnection unisolated = 
//            (BigdataSailRepositoryConnection) repo.getUnisolatedConnection();
//        unisolated.setAutoCommit(false);


        // read-committed view of the same database.
        // final AbstractTripleStore view = store.asReadCommittedView();
        RepositoryConnection readView = 
            (BigdataSailRepositoryConnection) repo.getReadOnlyConnection();

        try {

            // final long s = 1, p = 2, o = 3;
            final URI s = uri("a"), p = uri("b"), o = uri("c");

            // add the statement.
//            store.addStatements(new SPO[] { //
//                    new SPO(s, p, o, StatementEnum.Explicit) //
//                    },//
//                    1);
            isolated.add(stmt(s, p, o));
            
//            final boolean stmtInUnisolated = unisolated.hasStatement(s, p, o, true);
//
//            if(log.isInfoEnabled()) log.info("stmtInUnisolated: " + stmtInUnisolated);

            final boolean stmtInIsolated = isolated.hasStatement(s, p, o, true);

            if(log.isInfoEnabled()) log.info("stmtInIsolated: " + stmtInIsolated);

            final boolean stmtInView = readView.hasStatement(s, p, o, true);

            if(log.isInfoEnabled()) log.info("stmtInView: " + stmtInView);

//            // not visible in the repo.
//            assertFalse(stmtInUnisolated);

            // not visible in the view.
            assertFalse(stmtInView);

            // visible in the transaction.
            assertTrue(stmtInIsolated);

            // commit the transaction.
            isolated.commit();

            // verify that the write was published.
            readView = repo.getReadOnlyConnection();
            
            // now visible in the view
            /*
             * Note: this will fail if the Journal#getIndex(name,timestamp) does
             * not return an index view with read-committed (vs read-consistent)
             * semantics. For the index view to have read-committed semantics
             * the view MUST update if there is an intervening commit. This is
             * currently handled by returning a ReadCommittedView for this case
             * rather than a BTree.
             */
            assertTrue(readView.hasStatement(s, p, o, true));
            
        } finally {

            readView.close();
            isolated.close();
//            unisolated.close();

        }
        } finally {
            sail.__tearDownUnitTest();
        }
        
    }
 
Example 19
Source File: ScaleOut.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Issue the query.
 * 
 * @throws Exception
 */
private void doQuery() throws Exception {
   
    // this is how you get a read-only transaction.  MUST be
    // committed or aborted later, see below.
    long transactionId = 
        fed.getTransactionService().newTx(ITx.READ_COMMITTED);
    
    try {

        // open the read-only triple store
        final AbstractTripleStore tripleStore = 
            openTripleStore(fed, transactionId);
        
        // wrap it in a Sesame SAIL
        final BigdataSail sail = new BigdataSail(tripleStore);
        final Repository repo = new BigdataSailRepository(sail);
        repo.initialize();
        
        RepositoryConnection cxn = repo.getConnection();
        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();
        }
        
        repo.shutDown();
        
    } finally {
        
        // MUST close the transaction, abort is sufficient
        fed.getTransactionService().abort(transactionId);
        
    }
    
}
 
Example 20
Source File: SPARQLUpdateConformanceTest.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Override
	protected void runTest()
		throws Exception
	{
		RepositoryConnection con = dataRep.getConnection();
		RepositoryConnection erCon = expectedResultRepo.getConnection();
		try {
			String updateString = readUpdateString();

			con.begin();
//			con.setReadContexts((URI)null);
			
			Update update = con.prepareUpdate(QueryLanguage.SPARQL, updateString, requestFileURL);
			if (this.dataset != null) {
				update.setDataset(this.dataset);
			}
			update.execute();

			con.commit();
			
			// check default graph
			logger.info("checking default graph");
			compareGraphs(Iterations.asList(con.getStatements(null, null, null, true, (Resource)null)),
					Iterations.asList(erCon.getStatements(null, null, null, true, (Resource)null)));

			for (String namedGraph : inputNamedGraphs.keySet()) {
				logger.info("checking named graph {}", namedGraph);
				URI contextURI = con.getValueFactory().createURI(namedGraph.replaceAll("\"", ""));
				compareGraphs(Iterations.asList(con.getStatements(null, null, null, true, contextURI)),
						Iterations.asList(erCon.getStatements(null, null, null, true, contextURI)));
			}
		}
		catch(Exception e) {
			if(con.isActive()) {
				con.rollback();
			}
			throw e;
		}
		finally {
			con.close();
			erCon.close();
		}
	}