Java Code Examples for org.eclipse.rdf4j.repository.RepositoryConnection#begin()

The following examples show how to use org.eclipse.rdf4j.repository.RepositoryConnection#begin() . 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: AbstractSHACLTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void upload(Repository rep, Model dataGraph) {
	RepositoryConnection con = rep.getConnection();

	try {
		con.begin();
		con.add(dataGraph);
		con.commit();
	} catch (Exception e) {
		if (con.isActive()) {
			con.rollback();
		}
		throw e;
	} finally {
		con.close();
	}
}
 
Example 2
Source File: RepositoryConfigUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Update the specified RepositoryConnection with the specified set of RepositoryConfigs. This will overwrite all
 * existing configurations in the Repository that have a Repository ID occurring in these RepositoryConfigs. Note:
 * this method does NOT commit the updates on the connection.
 *
 * @param con     the repository connection to perform the update on
 * @param configs The RepositoryConfigs that should be added to or updated in the Repository. The RepositoryConfig's
 *                ID may already occur in the Repository, in which case all previous configuration data for that
 *                Repository will be cleared before the RepositoryConfig is added.
 * @throws RepositoryException
 * @throws RepositoryConfigException
 */
@Deprecated
public static void updateRepositoryConfigs(RepositoryConnection con, RepositoryConfig... configs)
		throws RepositoryException, RepositoryConfigException {
	ValueFactory vf = con.getRepository().getValueFactory();

	con.begin();

	for (RepositoryConfig config : configs) {
		Resource context = getContext(con, config.getID());

		if (context != null) {
			con.clear(context);
		} else {
			context = vf.createBNode();
		}

		con.add(context, RDF.TYPE, REPOSITORY_CONTEXT);

		Model graph = new LinkedHashModel();
		config.export(graph);
		con.add(graph, context);
	}

	con.commit();
}
 
Example 3
Source File: Repositories.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Opens a {@link RepositoryConnection} to the given Repository within a transaction, sends the connection to the
 * given {@link Function}, before either rolling back the transaction if it failed, or committing the transaction if
 * it was successful.
 *
 * @param                 <T> The type of the return value.
 * @param repository      The {@link Repository} to open a connection to.
 * @param processFunction A {@link Function} that performs an action on the connection and returns a result.
 * @return The result of applying the function.
 * @throws RepositoryException              If there was an exception dealing with the Repository.
 * @throws UnknownTransactionStateException If the transaction state was not properly recognised. (Optional specific
 *                                          exception)
 */
public static <T> T get(Repository repository, Function<RepositoryConnection, T> processFunction)
		throws RepositoryException, UnknownTransactionStateException {
	RepositoryConnection conn = null;

	try {
		conn = repository.getConnection();
		conn.begin();
		T result = processFunction.apply(conn);
		conn.commit();
		return result;
	} catch (RepositoryException e) {
		if (conn != null && conn.isActive()) {
			conn.rollback();
		}
		throw e;
	} finally {
		if (conn != null && conn.isOpen()) {
			conn.close();
		}
	}
}
 
Example 4
Source File: SPARQLComplianceTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 5
Source File: SPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void upload(IRI graphURI, Resource context) throws Exception {
	RepositoryConnection con = dataRep.getConnection();

	try {
		con.begin();
		RDFFormat rdfFormat = Rio.getParserFormatForFileName(graphURI.toString()).orElse(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 6
Source File: SPARQLUpdateConformanceTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 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();

		Update update = con.prepareUpdate(QueryLanguage.SPARQL, updateString, requestFileURL);
		update.setDataset(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);
			IRI contextURI = con.getValueFactory().createIRI(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 7
Source File: SPARQL11UpdateComplianceTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void runTest() throws Exception {

	logger.debug("running {}", getName());

	RepositoryConnection con = dataRep.getConnection();
	RepositoryConnection erCon = expectedResultRepo.getConnection();
	try {
		String updateString = readUpdateString();

		con.begin();

		Update update = con.prepareUpdate(QueryLanguage.SPARQL, updateString, requestFile);
		update.setDataset(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);
			IRI contextURI = con.getValueFactory().createIRI(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 8
Source File: IsolationLevelTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected boolean isSupported(IsolationLevels level) throws RepositoryException {
	RepositoryConnection con = store.getConnection();
	try {
		con.begin(level);
		return true;
	} catch (UnknownTransactionStateException e) {
		return false;
	} finally {
		try {
			con.rollback();
		} finally {
			con.close();
		}
	}
}
 
Example 9
Source File: CustomGraphQueryInferencerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected void runTest(final CustomGraphQueryInferencer inferencer) throws RepositoryException, RDFParseException,
		IOException, MalformedQueryException, UpdateExecutionException {
	// Initialize
	Repository sail = new SailRepository(inferencer);
	sail.initialize();
	RepositoryConnection connection = sail.getConnection();
	try {
		connection.begin();
		connection.clear();
		connection.add(new StringReader(initial), BASE, RDFFormat.TURTLE);

		// Test initial inferencer state
		Collection<Value> watchPredicates = inferencer.getWatchPredicates();
		assertThat(watchPredicates).hasSize(testData.predCount);
		Collection<Value> watchObjects = inferencer.getWatchObjects();
		assertThat(watchObjects).hasSize(testData.objCount);
		Collection<Value> watchSubjects = inferencer.getWatchSubjects();
		assertThat(watchSubjects).hasSize(testData.subjCount);
		ValueFactory factory = connection.getValueFactory();
		if (resourceFolder.startsWith(PREDICATE)) {
			assertThat(watchPredicates.contains(factory.createIRI(BASE, "brotherOf"))).isTrue();
			assertThat(watchPredicates.contains(factory.createIRI(BASE, "parentOf"))).isTrue();
		} else {
			IRI bob = factory.createIRI(BASE, "Bob");
			IRI alice = factory.createIRI(BASE, "Alice");
			assertThat(watchSubjects).contains(bob, alice);
			assertThat(watchObjects).contains(bob, alice);
		}

		// Test initial inferencing results
		assertThat(Iterations.asSet(connection.getStatements(null, null, null, true)))
				.hasSize(testData.initialCount);

		// Test results after removing some statements
		connection.prepareUpdate(QueryLanguage.SPARQL, delete).execute();
		assertThat(Iterations.asSet(connection.getStatements(null, null, null, true)))
				.hasSize(testData.countAfterRemove);

		// Tidy up. Storage gets re-used for subsequent tests, so must clear here,
		// in order to properly clear out any inferred statements.
		connection.clear();
		connection.commit();
	} finally {
		connection.close();
	}
	sail.shutDown();
}