Java Code Examples for org.eclipse.rdf4j.repository.Repository#getConnection()
The following examples show how to use
org.eclipse.rdf4j.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: AbstractNQuadsParserTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
public TestSuite createTestSuite() throws Exception { // Create test suite TestSuite suite = new TestSuite(this.getClass().getName()); // Add the manifest for W3C test cases to a repository and query it Repository w3cRepository = new SailRepository(new MemoryStore()); w3cRepository.initialize(); RepositoryConnection w3cCon = w3cRepository.getConnection(); InputStream inputStream = this.getClass().getResourceAsStream(TEST_W3C_MANIFEST_URL); w3cCon.add(inputStream, TEST_W3C_MANIFEST_URI_BASE, RDFFormat.TURTLE); parsePositiveNQuadsSyntaxTests(suite, TEST_W3C_FILE_BASE_PATH, TEST_W3C_TEST_URI_BASE, w3cCon); parseNegativeNQuadsSyntaxTests(suite, TEST_W3C_FILE_BASE_PATH, TEST_W3C_TEST_URI_BASE, w3cCon); w3cCon.close(); w3cRepository.shutDown(); return suite; }
Example 2
Source File: SemagrowSailFactory.java From semagrow with Apache License 2.0 | 6 votes |
public void initializeMetadata(Repository metadata, String filename) throws RepositoryException, IOException, RDFParseException { RepositoryConnection conn = null; try { File file = new File(filename); metadata.initialize(); conn = metadata.getConnection(); RDFFormat fileFormat = RDFFormat.matchFileName(file.getAbsolutePath(), RDFParserRegistry.getInstance().getKeys()).orElse(RDFFormat.NTRIPLES); conn.add(file, file.toURI().toString(), fileFormat); } finally { if (conn != null) conn.close(); } }
Example 3
Source File: SPARQLServiceEvaluationTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Load a dataset. Note: the repositories are cleared before loading data * * @param rep * @param datasetFile * @throws RDFParseException * @throws RepositoryException * @throws IOException */ protected void loadDataSet(Repository rep, String datasetFile) throws RDFParseException, RepositoryException, IOException { logger.debug("loading dataset..."); InputStream dataset = SPARQLServiceEvaluationTest.class.getResourceAsStream(datasetFile); if (dataset == null) { throw new IllegalArgumentException("Datasetfile " + datasetFile + " not found."); } RepositoryConnection con = rep.getConnection(); try { con.clear(); con.add(dataset, "", Rio.getParserFormatForFileName(datasetFile).orElseThrow(Rio.unsupportedFormat(datasetFile))); } finally { dataset.close(); con.close(); } logger.debug("dataset loaded."); }
Example 4
Source File: SPARQLServerBaseTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Load a dataset. Note: the repositories are cleared before loading data * * @param rep * @param datasetFile * @throws RDFParseException * @throws RepositoryException * @throws IOException */ protected void loadDataSet(Repository rep, String datasetFile) throws RDFParseException, RepositoryException, IOException { log.debug("loading dataset..."); InputStream dataset = SPARQLServerBaseTest.class.getResourceAsStream(datasetFile); boolean needToShutdown = false; if (!rep.isInitialized()) { rep.init(); needToShutdown = true; } RepositoryConnection con = rep.getConnection(); try { con.clear(); con.add(dataset, "", Rio.getParserFormatForFileName(datasetFile).get()); } finally { dataset.close(); con.close(); if (needToShutdown) { rep.shutDown(); } } log.debug("dataset loaded."); }
Example 5
Source File: Repositories.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * 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 6
Source File: RepositoryUtil.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Compares two models defined by the default context of two repositories and returns the difference between the * first and the second model (that is, all statements that are present in rep1 but not in rep2). Blank node IDs are * not relevant for model equality, they are mapped from one model to the other by using the attached properties. * Note that the method pulls the entire default context of both repositories into main memory. Use with caution. * <p> * <b>NOTE: this algorithm is currently broken; it doesn't actually map blank nodes between the two models.</b> * * @return The collection of statements that is the difference between rep1 and rep2. */ public static Collection<? extends Statement> difference(Repository rep1, Repository rep2) throws RepositoryException { Collection<Statement> model1; Collection<Statement> model2; try (RepositoryConnection con1 = rep1.getConnection()) { model1 = Iterations.asSet(con1.getStatements(null, null, null, false)); } try (RepositoryConnection con2 = rep2.getConnection()) { model2 = Iterations.asSet(con2.getStatements(null, null, null, false)); } return difference(model1, model2); }
Example 7
Source File: RepositoryConfigUtil.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Deprecated public static RepositoryConfig getRepositoryConfig(Repository repository, String repositoryID) throws RepositoryConfigException, RepositoryException { try (RepositoryConnection con = repository.getConnection()) { Statement idStatement = getIDStatement(con, repositoryID); if (idStatement == null) { // No such config return null; } Resource repositoryNode = idStatement.getSubject(); Resource context = idStatement.getContext(); if (context == null) { throw new RepositoryException("No configuration context for repository " + repositoryID); } Model contextGraph = QueryResults.asModel(con.getStatements(null, null, null, true, context)); return RepositoryConfig.create(contextGraph, repositoryNode); } }
Example 8
Source File: RepositoryUtil.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Compares the models of the default context of two repositories and returns true if rep1 is a subset of rep2. Note * that the method pulls the entire default context of both repositories into main memory. Use with caution. */ public static boolean isSubset(Repository rep1, Repository rep2) throws RepositoryException { Set<Statement> model1, model2; try (RepositoryConnection con1 = rep1.getConnection()) { model1 = Iterations.asSet(con1.getStatements(null, null, null, true)); } try (RepositoryConnection con2 = rep2.getConnection()) { model2 = Iterations.asSet(con2.getStatements(null, null, null, true)); } return Models.isSubset(model1, model2); }
Example 9
Source File: TrackAddedStatementsTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private static long size(Repository repo) { try (RepositoryConnection connection = repo.getConnection()) { return connection.getStatements(null, null, null) .stream() .map(Object::toString) .peek(logger::info) .count(); } }
Example 10
Source File: IsolationLevelTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void clear(Repository store) throws RepositoryException { try (RepositoryConnection con = store.getConnection();) { con.begin(); con.clear(); con.commit(); } }
Example 11
Source File: SPARQLUpdateTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * 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 12
Source File: EndpointBase.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void init(FederationContext federationContext) throws RepositoryException { if (isInitialized()) { return; } Repository repo = getRepository(); tripleSource = TripleSourceFactory.tripleSourceFor(this, getType(), federationContext); if (useSingleConnection()) { dependentConn = new ManagedRepositoryConnection(repo, repo.getConnection()); } initialized = true; }
Example 13
Source File: FedXWithInferenceTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
protected void addData(String repoId, Iterable<Statement> model) { Repository repo = repoManager.getRepository(repoId); try (RepositoryConnection conn = repo.getConnection()) { conn.add(model); } }
Example 14
Source File: GenerateFullAxioms.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static void main(String[] args) throws Exception { MemoryStore baseSail = new MemoryStore(); DedupingInferencer deduper = new DedupingInferencer(baseSail); SchemaCachingRDFSInferencer rdfsInferencer = new SchemaCachingRDFSInferencer(deduper); SpinSail spinSail = new SpinSail(rdfsInferencer); Repository repo = new SailRepository(spinSail); repo.initialize(); try (FileWriter writer = new FileWriter("spin-full.ttl")) { try (RepositoryConnection conn = repo.getConnection()) { conn.exportStatements(null, null, null, true, Rio.createWriter(RDFFormat.TURTLE, writer)); } } repo.shutDown(); }
Example 15
Source File: TripleStoreRDF4J.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
@Override public void add(TripleStore source) { Objects.requireNonNull(source); Repository sourceRepo; if (source instanceof TripleStoreRDF4J) { sourceRepo = ((TripleStoreRDF4J) source).repo; try (RepositoryConnection sourceConn = sourceRepo.getConnection()) { try (RepositoryConnection targetConn = repo.getConnection()) { copyNamespacesToRepository(sourceConn, targetConn); // copy statements RepositoryResult<Resource> contexts = sourceConn.getContextIDs(); for (Resource sourceContext : Iterations.asList(contexts)) { Resource targetContext = context(targetConn, sourceContext.stringValue()); RepositoryResult<Statement> statements; statements = sourceConn.getStatements(null, null, null, sourceContext); // add statements to the new repository for (Statement statement : Iterations.asList(statements)) { targetConn.add(statement, targetContext); } } } } } else { throw new TripleStoreException(String.format("Add to %s from source %s is not supported", getImplementationName(), source.getImplementationName())); } }
Example 16
Source File: RyaAccumuloSailFactoryTest.java From rya with Apache License 2.0 | 5 votes |
@Ignore @Test public void testCreateAccumuloSail() throws Exception { SailRepositoryFactory f = new SailRepositoryFactory(); Repository r = f.getRepository(getConfig()); r.initialize(); RepositoryConnection rc = r.getConnection(); rc.close(); }
Example 17
Source File: MemInferencingTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testFastInstantiate() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Repository sailRepository = new SailRepository(createSail()); ValueFactory vf = sailRepository.getValueFactory(); IRI A = vf.createIRI("http://A"); IRI aInstance = vf.createIRI("http://aInstance"); IRI B = vf.createIRI("http://B"); IRI C = vf.createIRI("http://C"); try (RepositoryConnection connection = sailRepository.getConnection()) { connection.add(vf.createStatement(A, RDFS.SUBCLASSOF, C)); } SailRepository sailRepository1 = new SailRepository(SchemaCachingRDFSInferencer.fastInstantiateFrom( (SchemaCachingRDFSInferencer) ((SailRepository) sailRepository).getSail(), new MemoryStore())); sailRepository1.initialize(); try (RepositoryConnection connection = sailRepository1.getConnection()) { connection.add(vf.createStatement(aInstance, RDF.TYPE, A)); } try (RepositoryConnection connection = sailRepository1.getConnection()) { boolean correctInference = connection.hasStatement(aInstance, RDF.TYPE, C, true); assertTrue( "aInstance should be instance of C because A subClassOfC was added to the sail used by fastInstantiateFrom.", correctInference); } }
Example 18
Source File: CustomGraphQueryInferencerTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
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(); }
Example 19
Source File: QueryPlanLogDemo.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
public static void main(String[] args) throws Exception { FedXConfig config = new FedXConfig().withEnableMonitoring(true).withLogQueryPlan(true); Repository repo = FedXFactory.newFederation() .withSparqlEndpoint("http://dbpedia.org/sparql") .withSparqlEndpoint("https://query.wikidata.org/sparql") .withConfig(config) .create(); repo.init(); String q = "PREFIX wd: <http://www.wikidata.org/entity/> " + "PREFIX wdt: <http://www.wikidata.org/prop/direct/> " + "SELECT * WHERE { " + " ?country a <http://dbpedia.org/class/yago/WikicatMemberStatesOfTheEuropeanUnion> ." + " ?country <http://www.w3.org/2002/07/owl#sameAs> ?countrySameAs . " + " ?countrySameAs wdt:P2131 ?gdp ." + "}"; try (RepositoryConnection conn = repo.getConnection()) { TupleQuery query = repo.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, q); try (TupleQueryResult res = query.evaluate()) { int count = 0; while (res.hasNext()) { res.next(); count++; } System.out.println("# Done, " + count + " results"); } System.out.println("# Optimized Query Plan:"); System.out.println(QueryPlanLog.getQueryPlan()); } repo.shutDown(); System.out.println("Done."); System.exit(0); }
Example 20
Source File: RepositoryConfigUtil.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 3 votes |
/** * Update the specified Repository with the specified set of RepositoryConfigs. This will overwrite all existing * configurations in the Repository that have a Repository ID occurring in these RepositoryConfigs. * * @param repository The Repository whose contents will be modified. * @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 When access to the Repository's RepositoryConnection causes a * RepositoryException. * @throws RepositoryConfigException */ @Deprecated public static void updateRepositoryConfigs(Repository repository, RepositoryConfig... configs) throws RepositoryException, RepositoryConfigException { try (RepositoryConnection con = repository.getConnection()) { updateRepositoryConfigs(con, configs); } }