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

The following examples show how to use org.openrdf.repository.RepositoryConnection#rollback() . 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: SampleCode.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Add a statement to a repository.
 * 
 * @param repo
 * @throws Exception
 */
public void loadSomeData(Repository repo) throws Exception {
    RepositoryConnection cxn = repo.getConnection();
    
    cxn.setAutoCommit(false);
    try {
        Resource s = new URIImpl("http://www.bigdata.com/rdf#Mike");
        URI p = new URIImpl("http://www.bigdata.com/rdf#loves");
        Value o = new URIImpl("http://www.bigdata.com/rdf#RDF");
        Statement stmt = new StatementImpl(s, p, o);
        cxn.add(stmt);
        cxn.commit();
    } catch (Exception ex) {
        cxn.rollback();
        throw ex;
    } finally {
        // close the repository connection
        cxn.close();
    }
}
 
Example 2
Source File: TestRollbacks.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void reader(final RepositoryConnection conn)
                throws RepositoryException, MalformedQueryException,
                QueryEvaluationException, InterruptedException {
            query(conn);
//            Thread.sleep(100);
            query(conn);
            ++counter;

            if (counter % 3 == 0)
                conn.commit();
            else
                conn.rollback();

            // if (counter % 7 == 0) {
            // conn.close();
            // conn = repo.getConnection();
            // conn.setAutoCommit(false);
            // }
        }
 
Example 3
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 4
Source File: Utils.java    From blazegraph-samples with GNU General Public License v2.0 5 votes vote down vote up
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 5
Source File: SampleCode.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Demonstrate execution of a free-text query.
 * 
 * @param repo
 * @throws Exception
 */
public boolean executeFreeTextQuery(Repository repo) throws Exception {
    if (((BigdataSailRepository) repo).getDatabase().getLexiconRelation()
            .getSearchEngine() == null) {
        /*
         * Only if the free text index exists.
         */
        return false;
    }
    RepositoryConnection cxn = repo.getConnection();
    cxn.setAutoCommit(false);
    try {
        cxn.add(new URIImpl("http://www.bigdata.com/A"), RDFS.LABEL,
                new LiteralImpl("Yellow Rose"));
        cxn.add(new URIImpl("http://www.bigdata.com/B"), RDFS.LABEL,
                new LiteralImpl("Red Rose"));
        cxn.add(new URIImpl("http://www.bigdata.com/C"), RDFS.LABEL,
                new LiteralImpl("Old Yellow House"));
        cxn.add(new URIImpl("http://www.bigdata.com/D"), RDFS.LABEL,
                new LiteralImpl("Loud Yell"));
        cxn.commit();
    } catch (Exception ex) {
        cxn.rollback();
        throw ex;
    } finally {
        // close the repository connection
        cxn.close();
    }
    
    String query = "select ?x where { ?x <"+BDS.SEARCH+"> \"Yell\" . }";
    executeSelectQuery(repo, query, QueryLanguage.SPARQL);
    // will match A, C, and D
    return true;
}
 
Example 6
Source File: SPARQLQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
protected void upload(URI graphURI, Resource context)
	throws Exception
{
	RepositoryConnection con = dataRep.getConnection();

	try {
		con.begin();
		RDFFormat rdfFormat = Rio.getParserFormatForFileName(graphURI.toString(), RDFFormat.TURTLE);
		RDFParser rdfParser = Rio.createParser(rdfFormat, dataRep.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 7
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 8
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 9
Source File: LoadPdb.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public static void loadSomeDataFromADocument(Repository repo, String documentPath) throws Exception {
	int counter = 0;
	File file = new File(documentPath);
	StatementCollector collector = new StatementCollector();
	InputStream in = new FileInputStream(file);
	try {
           final RDFParser parser = RDFParserRegistry.getInstance()
                   .get(RDFFormat.RDFXML).getParser();
		parser.setRDFHandler(collector);
		parser.parse(in, file.toURI().toString());
	} finally {
		in.close();
	}

	RepositoryConnection cxn = repo.getConnection();
	cxn.setAutoCommit(false);

	Statement stmt = null;
	try {
		for (Iterator<Statement> i = collector.getStatements().iterator(); i.hasNext();) {
			stmt = i.next();
			cxn.add(stmt);
			counter++;
		}
		LOG.info("Loaded " + counter + " triples");
		cxn.commit();
	} catch (Exception e) {
		LOG.error("error inserting statement: " + stmt, e);
		cxn.rollback();
	} finally {
		cxn.close();
	}

}
 
Example 10
Source File: HelloBlazegraph.java    From blazegraph-samples with GNU General Public License v2.0 4 votes vote down vote up
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();
		}
	}
 
Example 11
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();
		}
	}
 
Example 12
Source File: TestReadWriteTransactions.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
     * Test of abort semantics.
     */
    public void test_abort() throws Exception {

        class AbortException extends RuntimeException {
            private static final long serialVersionUID = 1L;
        }

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

        // Should be a nop.
        store.rollback();
        
//        final long s = 1, p = 2, o = 3;
        final URI s = uri("a"), p = uri("b"), o = uri("c");

        try {
            
            // add the statement.
//            store.addStatements(new SPO[] { //
//                    new SPO(s, p, o, StatementEnum.Explicit) //
//                    },//
//                    1);
            store.add(stmt(s, p, o));

            // visible in the repo.
            assertTrue(store.hasStatement(s, p, o, true));
            
            // discard the write set.
            store.rollback();

            // no longer visible in the repo.
            assertFalse(store.hasStatement(s, p, o, true));

        } finally {

            store.close();
            
        }
        } finally {
            sail.__tearDownUnitTest();
        }

    }
 
Example 13
Source File: AbstractStreamingOutput.java    From neo4j-sparql-extension with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Rolls back a transaction, if there is a active transaction
 * using a connection.
 * 
 * This method is intended to roll back a transaction after an exception
 * occured. Any occuring exceptions while rolling back will be added as
 * suppressed exceptions to the given exception.
 * @param conn the connection on which the transaction should be rolled back
 * @param ex an exception that caused the rollback
 */
protected void rollback(RepositoryConnection conn, Exception ex) {
	try {
		if (conn.isActive()) {
			conn.rollback();
		}
	} catch (RepositoryException ex2) {
		ex.addSuppressed(ex2);
	}
}