Java Code Examples for org.openrdf.repository.RepositoryConnection#add()
The following examples show how to use
org.openrdf.repository.RepositoryConnection#add() .
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: TestTicket348.java From database with GNU General Public License v2.0 | 6 votes |
private void addDuringQueryExec(final RepositoryConnection conn, final Resource subj, final URI pred, final Value obj, final Resource... ctx) throws RepositoryException, MalformedQueryException, QueryEvaluationException { final TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, "select distinct ?s ?p ?o where{?s ?p ?t . ?t <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?o }" ); tq.setBinding("s", subj); tq.setBinding("p", pred); tq.setBinding("o", obj); final TupleQueryResult tqr = tq.evaluate(); try { if (!tqr.hasNext()) { conn.add(subj, pred, obj, ctx); } } finally { tqr.close(); } }
Example 2
Source File: CRUDTest.java From anno4j with Apache License 2.0 | 6 votes |
/** * Tests retrieving resources with a more general type than specified in the repository. */ @Test public void testReadGeneralType() throws Exception { // Create an Anno4j instance and get its repository connection for direct triple access: Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false); RepositoryConnection repoConnection = anno4j.getRepository().getConnection(); // Add some triples to the repository: repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"), new URIImpl(RDF.TYPE), new URIImpl(FOAF.PERSON))); ResourceObject p = anno4j.findByID(Person.class, "urn:anno4j_test:p1"); assertNotNull(p); p = anno4j.findByID(Agent.class, "urn:anno4j_test:p1"); assertNotNull(p); p = anno4j.findByID(ResourceObject.class, "urn:anno4j_test:p1"); assertNotNull(p); }
Example 3
Source File: CustomSesameDataset.java From GeoTriples with Apache License 2.0 | 6 votes |
/** * Load data in specified graph (use default graph if contexts is null) * * @param filePath * @param format * @param contexts * @throws RepositoryException * @throws IOException * @throws RDFParseException */ public void loadDataFromFile(String filePath, RDFFormat format, Resource... contexts) throws RepositoryException, RDFParseException, IOException { RepositoryConnection con = null; try { con = currentRepository.getConnection(); // upload a file File f = new File(filePath); con.add(f, null, format, contexts); } finally { try { con.close(); } catch (RepositoryException e) { e.printStackTrace(); } } }
Example 4
Source File: TestTicket967.java From database with GNU General Public License v2.0 | 6 votes |
private void addDuringQueryExec(final RepositoryConnection conn, final Resource subj, final URI pred, final Value obj, final Resource... ctx) throws RepositoryException, MalformedQueryException, QueryEvaluationException { final TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, "select distinct ?s ?p ?o where{?s ?p ?t . ?t <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?o }" ); tq.setBinding("s", subj); tq.setBinding("p", pred); tq.setBinding("o", obj); final TupleQueryResult tqr = tq.evaluate(); try { if (!tqr.hasNext()) { conn.add(subj, pred, obj, ctx); } } finally { tqr.close(); } }
Example 5
Source File: SesameTransformationRepairPosLength.java From trainbenchmark with Eclipse Public License 1.0 | 6 votes |
@Override public void activate(final Collection<SesamePosLengthMatch> matches) throws RepositoryException { final RepositoryConnection con = driver.getConnection(); final ValueFactory vf = driver.getValueFactory(); final URI lengthProperty = vf.createURI(BASE_PREFIX + LENGTH); for (final SesamePosLengthMatch match : matches) { final Resource segment = match.getSegment(); final Value length = match.getLength(); final RepositoryResult<Statement> statementsToRemove = con.getStatements(segment, lengthProperty, length, true); while (statementsToRemove.hasNext()) { final Statement oldStatement = statementsToRemove.next(); con.remove(oldStatement); } final Integer lengthInteger = new Integer(length.stringValue()); final Integer newLengthInteger = -lengthInteger + 1; final Literal newLength = vf.createLiteral(newLengthInteger); final Statement newStatement = vf.createStatement(segment, lengthProperty, newLength); con.add(newStatement); } }
Example 6
Source File: LoadPdb.java From database with GNU General Public License v2.0 | 5 votes |
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 7
Source File: PropertyTest.java From anno4j with Apache License 2.0 | 5 votes |
@Override protected void setUp() throws Exception { enableLogging(ClassResolver.class); super.setUp(); factory = (ObjectRepository) repository; RepositoryConnection conn = repository.getConnection(); conn.add(getClass().getResourceAsStream("/testcases/sesame-foaf.rdf"), "", RDFFormat.RDFXML); conn.close(); this.manager = factory.getConnection(); }
Example 8
Source File: TestTicket355.java From database with GNU General Public License v2.0 | 5 votes |
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 9
Source File: DavidsTestBOps.java From database with GNU General Public License v2.0 | 5 votes |
private void load ( RepositoryConnection rc, String kb, Resource g ) throws RepositoryException, RDFParseException, IOException { rc.add ( new ByteArrayInputStream ( kb.toString ().getBytes ( "UTF-8" ) ) , "http://xyz.com/test" , RDFFormat.TURTLE , g ) ; rc.commit () ; }
Example 10
Source File: TestRDFSInverseInferencer.java From semweb4j with BSD 2-Clause "Simplified" License | 5 votes |
@Test public void testStrangeBug() throws RepositoryException { // create a Sail stack Sail sail = new MemoryStore(); sail = new ForwardChainingRDFSPlusInverseInferencer(sail); // create a Repository Repository repository = new SailRepository(sail); try { repository.initialize(); } catch (RepositoryException e) { throw new RuntimeException(e); } URI p = new URIImpl("urn:rel:p"); URI q = new URIImpl("urn:rel:q"); URI nrlInverse = ForwardChainingRDFSPlusInverseInferencerConnection.NRL_InverseProperty; URI defaultContext = null; // new Resource[0] RepositoryConnection con = repository.getConnection(); // add p-hasInverse-q con.add(p, nrlInverse, q, defaultContext); assertTrue("just added p-haInv-q, should stil be there", con.hasStatement(p, nrlInverse, q, true, defaultContext) ); assertTrue("expect inferred stmt: q-hasInv-p", con.hasStatement(q, nrlInverse, p, true, defaultContext) ); // add (redundant) inverse stmt: q-hasInv-p con.add(q, nrlInverse, p, defaultContext); assertTrue("added p-haInv-q, should stil be there", con.hasStatement(p, nrlInverse, q, true, defaultContext) ); assertTrue( con.hasStatement(p, nrlInverse, q, true, defaultContext) ); assertTrue("added q-hasInv-p, should still be there", con.hasStatement(q, nrlInverse, p, true, defaultContext) ); }
Example 11
Source File: SesameTransformationRepairSemaphoreNeighbor.java From trainbenchmark with Eclipse Public License 1.0 | 5 votes |
@Override public void activate(final Collection<SesameSemaphoreNeighborMatch> matches) throws RepositoryException { final RepositoryConnection con = driver.getConnection(); final ValueFactory vf = driver.getValueFactory(); final URI entry = vf.createURI(BASE_PREFIX + ENTRY); for (final SesameSemaphoreNeighborMatch match : matches) { final Resource route2 = match.getRoute2(); final Resource semaphore = match.getSemaphore(); con.add(route2, entry, semaphore); } }
Example 12
Source File: RdfIndexerService.java From attic-polygene-java with Apache License 2.0 | 5 votes |
private void indexEntityState( final EntityState entityState, final RepositoryConnection connection ) throws RepositoryException { if( entityState.entityDescriptor().queryable() ) { EntityReference reference = entityState.entityReference(); final URI entityURI = stateSerializer.createEntityURI( getValueFactory(), reference); Graph graph = new GraphImpl(); stateSerializer.serialize( entityState, false, graph ); connection.add( graph, entityURI ); } }
Example 13
Source File: TestTicket2043b.java From database with GNU General Public License v2.0 | 5 votes |
public void testBug() throws Exception { final BigdataSail sail = getSail(); try { BigdataSailRepository repo = new BigdataSailRepository(sail); try { repo.initialize(); final RepositoryConnection conn = repo.getConnection(); conn.setAutoCommit(false); try { conn.add(getClass().getResourceAsStream("TestTicket2043.n3"), "", RDFFormat.TURTLE); conn.commit(); // Check existing int literal executeQuery(conn, "1", 2); // Check not existing int literal executeQuery(conn, "2", 0); // Check not existing plain literal executeQuery(conn, "\"3\"", 0); // Check not existing boolean literal executeQuery(conn, "true", 0); // Check not existing datetime literal executeQuery(conn, "\"2000-01-01T00:00:00Z\"^^xsd:dateTime", 0); } finally { conn.close(); } } finally { repo.shutDown(); } } finally { sail.__tearDownUnitTest(); } }
Example 14
Source File: CustomSesameDataset.java From GeoTriples with Apache License 2.0 | 5 votes |
public void loadDataFromURL(String stringURL) throws RepositoryException, RDFParseException, IOException { RepositoryConnection con = null; try { con = currentRepository.getConnection(); // upload a URL URL url = new URL(stringURL); con.add(url, null, RDFFormat.TURTLE); } finally { try { con.close(); } catch (RepositoryException e) { e.printStackTrace(); } } }
Example 15
Source File: Utils.java From blazegraph-samples with GNU General Public License v2.0 | 5 votes |
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 16
Source File: TestBOpUtility.java From database with GNU General Public License v2.0 | 4 votes |
public void testOpenWorldEq() throws Exception { final Sail sail = new MemoryStore(); final Repository repo = new SailRepository(sail); repo.initialize(); final RepositoryConnection cxn = repo.getConnection(); try { final ValueFactory vf = sail.getValueFactory(); final URI mike = vf.createURI(BD.NAMESPACE + "mike"); final URI age = vf.createURI(BD.NAMESPACE + "age"); final Literal mikeAge = vf.createLiteral(34); cxn.add(vf.createStatement(mike, RDF.TYPE, RDFS.RESOURCE)); cxn.add(vf.createStatement(mike, age, mikeAge)); final String query = "select * " + "where { " + " ?s ?p ?o . " + " filter (?o < 40) " + "}"; final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query); final TupleQueryResult result = tupleQuery.evaluate(); while (result.hasNext()) { final BindingSet tmp = result.next(); if(log.isInfoEnabled()) log.info(tmp.toString()); } } finally { cxn.close(); repo.shutDown(); } }
Example 17
Source File: TestMaterialization.java From database with GNU General Public License v2.0 | 4 votes |
public void testXsdStr() throws Exception { final BigdataSail sail = getSail(); try { sail.initialize(); final BigdataSailRepository repo = new BigdataSailRepository(sail); final RepositoryConnection cxn = repo.getConnection(); try { cxn.setAutoCommit(false); final ValueFactory vf = sail.getValueFactory(); /* * Create some terms. */ final URI X = vf.createURI(BD.NAMESPACE + "X"); final Literal label = vf.createLiteral("John"); /* * Create some statements. */ cxn.add(X, RDF.TYPE, RDFS.RESOURCE); cxn.add(X, RDFS.LABEL, label); /* * Note: The either flush() or commit() is required to flush the * statement buffers to the database before executing any operations * that go around the sail. */ cxn.commit(); if (log.isInfoEnabled()) { log.info(((BigdataSailRepositoryConnection) cxn).getTripleStore().dumpStore()); } { String query = "select * where { ?s ?p ?o . FILTER (xsd:string(?o) = \""+RDF.PROPERTY+"\"^^xsd:string) }"; final SailTupleQuery tupleQuery = (SailTupleQuery) cxn.prepareTupleQuery(QueryLanguage.SPARQL, query); tupleQuery.setIncludeInferred(true /* includeInferred */); if (log.isInfoEnabled()) { log.info(query); final TupleQueryResult result = tupleQuery.evaluate(); if (result.hasNext()) { while (result.hasNext()) log.info(result.next()); } else { fail("expecting result from the vocab"); } } // final Collection<BindingSet> answer = new LinkedList<BindingSet>(); // answer.add(createBindingSet( // new BindingImpl("a", paul), // new BindingImpl("b", mary) // )); // answer.add(createBindingSet( // new BindingImpl("a", brad), // new BindingImpl("b", john) // )); // // final TupleQueryResult result = tupleQuery.evaluate(); // compare(result, answer); } } finally { cxn.close(); } } finally { if (sail instanceof BigdataSail) ((BigdataSail)sail).__tearDownUnitTest();//shutDown(); } }
Example 18
Source File: TestSingleTailRule.java From database with GNU General Public License v2.0 | 4 votes |
public void testOptionalFilter() throws Exception { final BigdataSail sail = getSail(); final BigdataSailRepository repo = new BigdataSailRepository(sail); // final Sail sail = new MemoryStore(); // final Repository repo = new SailRepository(sail); repo.initialize(); final RepositoryConnection cxn = repo.getConnection(); cxn.setAutoCommit(false); try { final ValueFactory vf = sail.getValueFactory(); URI s = vf.createURI("urn:test:s"); URI p1 = vf.createURI("urn:test:p1"); URI p2 = vf.createURI("urn:test:p2"); Literal v1 = vf.createLiteral(1); Literal v2 = vf.createLiteral(2); Literal v3 = vf.createLiteral(3); cxn.add(s, p1, v1); cxn.add(s, p2, v2); cxn.add(s, p1, v3); cxn.commit(); String qry = "PREFIX :<urn:test:> " + "SELECT ?s ?v1 ?v2 " + "WHERE { " + " ?s :p1 ?v1 . " + " OPTIONAL {?s :p2 ?v2 FILTER(?v1 < 3) } " + "}"; TupleQuery query = cxn.prepareTupleQuery(QueryLanguage.SPARQL, qry); TupleQueryResult result = query.evaluate(); // while (result.hasNext()) { // System.err.println(result.next()); // } Collection<BindingSet> solution = new LinkedList<BindingSet>(); solution.add(createBindingSet(new Binding[] { new BindingImpl("s", s), new BindingImpl("v1", v1), new BindingImpl("v2", v2), })); solution.add(createBindingSet(new Binding[] { new BindingImpl("s", s), new BindingImpl("v1", v3), })); compare(result, solution); } finally { cxn.close(); if (sail instanceof BigdataSail) ((BigdataSail)sail).__tearDownUnitTest(); } }
Example 19
Source File: CRUDTest.java From anno4j with Apache License 2.0 | 4 votes |
/** * Tests the triples contained in the repository after updating property values via resource objects. */ @Test public void testUpdate() throws Exception { // Create an Anno4j instance and get its repository connection for direct triple access: Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false); RepositoryConnection repoConnection = anno4j.getRepository().getConnection(); // Add some triples to the repository: repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"), new URIImpl(RDF.TYPE), new URIImpl(FOAF.PERSON))); repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"), new URIImpl(FOAF.MBOX), new LiteralImpl("[email protected]"))); repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"), new URIImpl(RDF.TYPE), new URIImpl(OADM.ANNOTATION))); repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"), new URIImpl(OADM.BODY_TEXT), new LiteralImpl("Text 1"))); repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"), new URIImpl(OADM.BODY_TEXT), new LiteralImpl("Text 2"))); // Modified single-valued property of p1: Person p1 = anno4j.findByID(Person.class, "urn:anno4j_test:p1"); p1.setMbox("[email protected]"); // Get all triples with p1 as subject. There should be exavtly two (rdf:type and new foaf:mbox): Collection<Statement> p1Statements = getStatements(repoConnection, new URIImpl("urn:anno4j_test:p1"), null, null); assertEquals(2, p1Statements.size()); assertTrue(p1Statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:p1"), new URIImpl(RDF.TYPE), new URIImpl(FOAF.PERSON)))); assertTrue(p1Statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:p1"), new URIImpl(FOAF.MBOX), new LiteralImpl("[email protected]")))); // Modify multi-valued property of a1: Annotation a1 = anno4j.findByID(Annotation.class, "urn:anno4j_test:a1"); a1.setBodyTexts(Sets.newHashSet("Text 1")); // Get the triples with a1 as subject. There should be only two now (rdf:type and the oadm:body_text just set): Collection<Statement> a1Statements = getStatements(repoConnection, new URIImpl("urn:anno4j_test:a1"), null, null); assertEquals(2, a1Statements.size()); assertTrue(a1Statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:a1"), new URIImpl(RDF.TYPE), new URIImpl(OADM.ANNOTATION)))); assertTrue(a1Statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:a1"), new URIImpl(OADM.BODY_TEXT), new LiteralImpl("Text 1")))); }
Example 20
Source File: CRUDTest.java From anno4j with Apache License 2.0 | 4 votes |
/** * Tests deletion of resource objects and its effect on the repository. */ @Test public void testDelete() throws Exception { // Create an Anno4j instance and get its repository connection for direct triple access: Anno4j anno4j = new Anno4j(new SailRepository(new MemoryStore()), null, false); RepositoryConnection repoConnection = anno4j.getRepository().getConnection(); // Add some triples to the repository: /* Persisted triples: :p1 a foaf:Person ; foaf:mbox "[email protected]" . :a1 a oadm:Annotation ; oadm:bodyText "Text 1", "Text 2" ; schema:audience :b1, :b2 . :b1 a schema:Audience . */ repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"), new URIImpl(RDF.TYPE), new URIImpl(FOAF.PERSON))); repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:p1"), new URIImpl(FOAF.MBOX), new LiteralImpl("[email protected]"))); repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"), new URIImpl(RDF.TYPE), new URIImpl(OADM.ANNOTATION))); repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"), new URIImpl(OADM.BODY_TEXT), new LiteralImpl("Text 1"))); repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"), new URIImpl(OADM.BODY_TEXT), new LiteralImpl("Text 2"))); repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"), new URIImpl(SCHEMA.AUDIENCE_RELATIONSHIP), new URIImpl("urn:anno4j_test:b1"))); repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:a1"), new URIImpl(SCHEMA.AUDIENCE_RELATIONSHIP), new URIImpl("urn:anno4j_test:b2"))); repoConnection.add(new StatementImpl(new URIImpl("urn:anno4j_test:b1"), new URIImpl(RDF.TYPE), new URIImpl(SCHEMA.AUDIENCE_CLASS))); // Test that all triples are removed: Person p1 = anno4j.findByID(Person.class, "urn:anno4j_test:p1"); p1.delete(); Collection<Statement> p1Statements = getStatements(repoConnection, new URIImpl("urn:anno4j_test:p1"), null, null); assertEquals(0, p1Statements.size()); // Test that all triples are removed that have a1 as subject. b1 should be still retrievable: Annotation a1 = anno4j.findByID(Annotation.class, "urn:anno4j_test:a1"); a1.delete(); Collection<Statement> a1Statements = getStatements(repoConnection, new URIImpl("urn:anno4j_test:a1"), null, null); assertEquals(0, a1Statements.size()); Audience b1 = anno4j.findByID(Audience.class, "urn:anno4j_test:b1"); assertNotNull(b1); // After removing :b1 the repository should be empty. :b2 is removed because it didn't occur as a subject: b1.delete(); Collection<Statement> allStatements = getStatements(repoConnection); assertEquals(0, allStatements.size()); }