Java Code Examples for org.openrdf.repository.RepositoryConnection

The following examples show how to use org.openrdf.repository.RepositoryConnection. These examples are extracted from open source projects. 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
@Override
public void read(InputStream is, String base, String name) {
    RepositoryConnection cnx = null;
    try {
        cnx = repo.getConnection();
        cnx.begin();
        Resource context = context(cnx, name);
        read(is, base, name, cnx, context);
        cnx.commit();
        addNamespaceForBase(cnx, base);
    } catch (RepositoryException x) {
        throw new TripleStoreException(String.format("Reading. Repo problem %s %s", name, base), x);
    } finally {
        closeConnection(cnx, "Reading");
    }
}
 
Example 2
@Override
public void write(DataSource ds) {
    RepositoryConnection conn = null;
    try {
        conn = repo.getConnection();
        RepositoryResult<Resource> contexts = conn.getContextIDs();
        while (contexts.hasNext()) {
            Resource context = contexts.next();
            write(ds, conn, context);
        }
    } catch (RepositoryException x) {
        throw new TripleStoreException(String.format("Writing on %s", ds), x);
    } finally {
        closeConnection(conn, "Writing on " + ds);
    }
}
 
Example 3
@Override
public void write(DataSource ds, String contextName) {
    RepositoryConnection conn = null;
    try {
        conn = repo.getConnection();
        RepositoryResult<Resource> contexts = conn.getContextIDs();
        while (contexts.hasNext()) {
            Resource context = contexts.next();
            if (context.stringValue().equals(contextName)) {
                write(ds, conn, context);
            }
        }
    } catch (RepositoryException x) {
        throw new TripleStoreException(String.format("Writing on %s", ds), x);
    } finally {
        closeConnection(conn, "Writing on " + ds);
    }
}
 
Example 4
@Override
public Set<String> contextNames() {
    HashSet<String> names = new HashSet<>();
    RepositoryConnection conn = null;
    try {
        conn = repo.getConnection();
        RepositoryResult<Resource> rs = conn.getContextIDs();
        while (rs.hasNext()) {
            names.add(rs.next().stringValue());
        }
        return names;
    } catch (RepositoryException x) {
        LOG.error("getting context names : {}", x.getMessage());
    } finally {
        closeConnection(conn, "Getting context names");
    }
    return names;
}
 
Example 5
Source Project: database   Source File: TestTicket967.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 6
Source Project: GeoTriples   Source File: CustomSesameDataset.java    License: 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 7
Source Project: GeoTriples   Source File: CustomSesameDataset.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tuple pattern query - find all statements with the pattern, where null is
 * a wildcard
 * 
 * @param s
 *            subject (null for wildcard)
 * @param p
 *            predicate (null for wildcard)
 * @param o
 *            object (null for wildcard)
 * @param contexts
 *            varArgs contexts (use default graph if null)
 * @return serialized graph of results
 */
public List<Statement> tuplePattern(Resource s, URI p, Value o,
		Resource... contexts) {
	try {
		RepositoryConnection con = currentRepository.getConnection();
		try {
			RepositoryResult<Statement> repres = con.getStatements(s, p, o,
					true, contexts);
			ArrayList<Statement> reslist = new ArrayList<Statement>();
			while (repres.hasNext()) {
				reslist.add(repres.next());
			}
			return reslist;
		} finally {
			con.close();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 8
Source Project: cumulusrdf   Source File: NamespaceHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * update the namespace.
 * 
 * @param repository the Repository object
 * @param request the HttpServletRequest object
 * @param prefix the prefix
 * @return EmptySuccessView object if success
 * @throws IOException throws if there is error reading the namespace from the HttpServletRequest
 * @throws ClientHTTPException throws if No namespace name found in request body
 * @throws ServerHTTPException throws when there is error about the repository
 */
private ModelAndView getUpdateNamespaceResult(final Repository repository, final HttpServletRequest request, final String prefix)
		throws IOException, ClientHTTPException, ServerHTTPException {
	String namespace = IOUtil.readString(request.getReader());
	namespace = namespace.trim();

	if (namespace.length() == 0) {
		throw new ClientHTTPException(SC_BAD_REQUEST, "No namespace name found in request body");
	}

	try {
		RepositoryConnection repositoryCon = repository.getConnection();
		synchronized (repositoryCon) {
			repositoryCon.setNamespace(prefix, namespace);
		}
		repositoryCon.close();
	} catch (RepositoryException e) {
		throw new ServerHTTPException("Repository error: " + e.getMessage(), e);
	}

	return new ModelAndView(EmptySuccessView.getInstance());
}
 
Example 9
/**
 * Get total number of distinct subjects of a dataset
 * @return count 
 */
public static long getSubjectCount(String endpoint) throws Exception {
	String strQuery = "SELECT  (COUNT(DISTINCT ?s) AS ?sbjts) " + // 
			"WHERE " +
			"{" +
       		"?s ?p ?o " +
       		"} " ;
	SPARQLRepository repo = new SPARQLRepository(endpoint);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		return Long.parseLong(rs.next().getValue("sbjts").stringValue());
	} finally {
		conn.close();
		repo.shutDown();
	}
}
 
Example 10
/**
 * 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 11
Source Project: GeoTriples   Source File: CustomSesameDataset.java    License: Apache License 2.0 6 votes vote down vote up
public String printRDF(RDFFormat outform) {
	try {
		RepositoryConnection con = currentRepository.getConnection();
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			RDFWriter w = Rio.createWriter(outform, out);

			con.export(w);
			String result = new String(out.toByteArray(), "UTF-8");
			return result;
		} finally {
			con.close();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 12
Source Project: GeoTriples   Source File: CustomSesameDataset.java    License: 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 13
protected static String getManifestName(Repository manifestRep, RepositoryConnection con,
		String manifestFileURL)
	throws QueryEvaluationException, RepositoryException, MalformedQueryException
{
	// Try to extract suite name from manifest file
	TupleQuery manifestNameQuery = con.prepareTupleQuery(QueryLanguage.SERQL,
			"SELECT ManifestName FROM {ManifestURL} rdfs:label {ManifestName}");
	manifestNameQuery.setBinding("ManifestURL", manifestRep.getValueFactory().createURI(manifestFileURL));
	TupleQueryResult manifestNames = manifestNameQuery.evaluate();
	try {
		if (manifestNames.hasNext()) {
			return manifestNames.next().getValue("ManifestName").stringValue();
		}
	}
	finally {
		manifestNames.close();
	}

	// Derive name from manifest URL
	int lastSlashIdx = manifestFileURL.lastIndexOf('/');
	int secLastSlashIdx = manifestFileURL.lastIndexOf('/', lastSlashIdx - 1);
	return manifestFileURL.substring(secLastSlashIdx + 1, lastSlashIdx);
}
 
Example 14
@Override
public void activate(final Collection<SesameSwitchSetMatch> matches) throws RepositoryException {
	final RepositoryConnection con = driver.getConnection();
	final ValueFactory vf = driver.getValueFactory();

	final URI currentPositionProperty = vf.createURI(BASE_PREFIX + CURRENTPOSITION);

	for (final SesameSwitchSetMatch match : matches) {
		final Resource sw = match.getSw();
		final Value position = match.getPosition();
		final Value currentPosition = match.getCurrentPosition();

		final RepositoryResult<Statement> statementsToRemove = con.getStatements(sw, currentPositionProperty, currentPosition, false);
		while (statementsToRemove.hasNext()) {
			con.remove(statementsToRemove.next());
		}

		con.add(sw, currentPositionProperty, position);
	}
}
 
Example 15
@Override
public void activate(final Collection<SesameSwitchMonitoredMatch> matches) throws Exception {
	final RepositoryConnection con = driver.getConnection();
	final ValueFactory vf = driver.getValueFactory();

	final URI sensorEdgeType = vf.createURI(BASE_PREFIX + MONITORED_BY);
	final URI sensorType = vf.createURI(BASE_PREFIX + SENSOR);
	final URI trackElementType = vf.createURI(BASE_PREFIX + TRACKELEMENT);

	for (final SesameSwitchMonitoredMatch match : matches) {
		final Resource sw = match.getSw();

		final URI sensor = vf.createURI(BASE_PREFIX + ID_PREFIX + driver.generateNewVertexId());

		// set vertex type
		con.add(sensor, RDF.TYPE, sensorType);

		// insert the supertype as well
		if (!driver.isInferencing()) {
			con.add(sensor, RDF.TYPE, trackElementType);
		}

		// insert edge
		con.add(sw, sensorEdgeType, sensor);
	}
}
 
Example 16
@Override
public void activate(final Collection<SesameConnectedSegmentsMatch> matches) throws RepositoryException {
	final RepositoryConnection con = driver.getConnection();
	final ValueFactory vf = driver.getValueFactory();

	final URI connectsTo = vf.createURI(BASE_PREFIX + CONNECTS_TO);
	for (final SesameConnectedSegmentsMatch match : matches) {
		// delete segment2 by removing all (segment2, _, _) and (_, _, segment2) triples
		final RepositoryResult<Statement> outgoingEdges = con.getStatements(match.getSegment2(), null, null, true);
		while (outgoingEdges.hasNext()) {
			con.remove(outgoingEdges.next());
		}
		final RepositoryResult<Statement> incomingEdges = con.getStatements(null, null, match.getSegment2(), true);
		while (incomingEdges.hasNext()) {
			con.remove(incomingEdges.next());
		}

		// insert (segment1)-[:connectsTo]->(segment3) edge
		con.add(match.getSegment1(), connectsTo, match.getSegment3());
	}
}
 
Example 17
Source Project: database   Source File: SPARQLQueryTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected void uploadDataset(Dataset dataset)
	throws Exception
{
	RepositoryConnection con = dataRep.getConnection();
	try {
		// Merge default and named graphs to filter duplicates
		Set<URI> graphURIs = new HashSet<URI>();
		graphURIs.addAll(dataset.getDefaultGraphs());
		graphURIs.addAll(dataset.getNamedGraphs());

		for (Resource graphURI : graphURIs) {
			upload(((URI)graphURI), graphURI);
		}
	}
	finally {
		con.close();
	}
}
 
Example 18
Source Project: anno4j   Source File: CRUDTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests basic object creation and persistence of triples.
 */
@Test
public void testCreate() 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();

    // Test simple object creation:
    Person p = anno4j.createObject(Person.class, (Resource) new URIImpl("urn:anno4j_test:p1"));
    p.setMbox("[email protected]");

    // Two statments (rdf:type, foaf:mbox) should be created:
    Collection<Statement> statements = getStatements(repoConnection);
    assertEquals(2, statements.size());
    assertTrue(statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
                                                     new URIImpl(RDF.TYPE),
                                                     new URIImpl(FOAF.PERSON))));
    assertTrue(statements.contains(new StatementImpl(new URIImpl("urn:anno4j_test:p1"),
            new URIImpl(FOAF.MBOX),
            new LiteralImpl("[email protected]"))));
}
 
Example 19
Source Project: database   Source File: TestTicket4249.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final RepositoryConnection conn, final Literal string, final int start, final int length, final Literal expected)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	final ValueFactory vf = conn.getValueFactory();
	final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start, ?length) as ?substring ) . }";
	final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
	q.setBinding("string", string);
	q.setBinding("start", vf.createLiteral(start));
	q.setBinding("length", vf.createLiteral(length));
	final TupleQueryResult tqr = q.evaluate();
	try {
		while (tqr.hasNext()) {
			final BindingSet bindings = tqr.next();
			// assert expected value
			assertEquals(expected, bindings.getBinding("substring").getValue());
		}
	} finally {
		tqr.close();
	}
}
 
Example 20
Source Project: database   Source File: Concurrency.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Issue the query.
 * 
 * @throws Exception
 */
private void doQuery() throws Exception {
   
    RepositoryConnection cxn = repo.getReadOnlyConnection();
    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();
    }
        
}
 
Example 21
Source Project: anno4j   Source File: ObjectRepository.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new ObjectConnection that will need to be closed by the caller.
 */
@Override
public ObjectConnection getConnection() throws RepositoryException {
	BlobStore blobs;
	try {
		blobs = getBlobStore();
	} catch (ObjectStoreConfigException e) {
		throw new RepositoryException(e);
	}
	ObjectFactory factory = service.createObjectFactory();
	RepositoryConnection conn = getDelegate().getConnection();
	ObjectConnection con = new ObjectConnection(this, conn, factory,
			createTypeManager(), blobs, idGenerator);
	con.setIncludeInferred(isIncludeInferred());
	con.setMaxQueryTime(getMaxQueryTime());
	// con.setQueryResultLimit(getQueryResultLimit());
	con.setQueryLanguage(getQueryLanguage());
	con.setReadContexts(getReadContexts());
	con.setAddContexts(getAddContexts());
	con.setRemoveContexts(getRemoveContexts());
	con.setArchiveContexts(getArchiveContexts());
	return con;
}
 
Example 22
Source Project: database   Source File: TestTicket4249.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final RepositoryConnection conn, final String string, final double start, final double length, final String expected)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, IOException, VisitorException {

	final ValueFactory vf = conn.getValueFactory();
	final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start, ?length) as ?substring ) . }";
	final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
	q.setBinding("string", vf.createLiteral(string));
	q.setBinding("start", vf.createLiteral(start));
	q.setBinding("length", vf.createLiteral(length));
	final TupleQueryResult tqr = q.evaluate();
	try {
		while (tqr.hasNext()) {
			final BindingSet bindings = tqr.next();
			// assert expected value
			assertEquals(expected, bindings.getBinding("substring").getValue().stringValue());
		}
	} finally {
		tqr.close();
	}
}
 
Example 23
Source Project: anno4j   Source File: ListTest.java    License: Apache License 2.0 6 votes vote down vote up
private int getSize(Repository repository) throws RepositoryException {
	int size = 0;
	RepositoryConnection connection = null;
	RepositoryResult<Statement> iter = null;
	try {
		connection = repository.getConnection();
		iter = connection.getStatements(null, null, null, false);
		while (iter.hasNext()) {
			iter.next();
			++size;
		}
	} finally {
		if (iter != null)
			iter.close();
		if (connection != null)
			connection.close();
	}
	return size;
}
 
Example 24
Source Project: database   Source File: TestTicket276.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void addData(final RepositoryConnection conn) throws IOException,
		RDFParseException, RepositoryException, RDFHandlerException {

    final RDFParser rdfParser = Rio.createParser(RDFFormat.NTRIPLES,
			conn.getValueFactory());
	rdfParser.setVerifyData(true);
	rdfParser.setStopAtFirstError(true);
	rdfParser.setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE);
	rdfParser.setRDFHandler(new RDFHandlerBase() {
		@Override
		public void handleStatement(Statement st)
				throws RDFHandlerException {
			try {
				conn.add(st);
			} catch (OpenRDFException e) {
				throw new RDFHandlerException(e);
			}
		}
	});
	rdfParser.parse(getClass().getResourceAsStream("TestTicket276.n3"), "");
}
 
Example 25
Source Project: database   Source File: TestTicket4249.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final RepositoryConnection conn, final Literal string, final int start, final Literal expected)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	final ValueFactory vf = conn.getValueFactory();
	final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start) as ?substring ) . }";
	final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
	q.setBinding("string", string);
	q.setBinding("start", vf.createLiteral(start));
	final TupleQueryResult tqr = q.evaluate();
	try {
		while (tqr.hasNext()) {
			final BindingSet bindings = tqr.next();
			// assert expected value
			assertEquals(expected, bindings.getBinding("substring").getValue());
		}
	} finally {
		tqr.close();
	}
}
 
Example 26
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 27
private void write(DataSource ds, RepositoryConnection conn, Resource context) throws RepositoryException {
    LOG.info("Writing context {}", context);

    RepositoryResult<Statement> statements = conn.getStatements(null, null, null, true, context);
    Model model = new LinkedHashModel();
    QueryResults.addAll(statements, model);
    copyNamespacesToModel(conn, model);

    String outname = context.toString();
    write(model, outputStream(ds, outname));
}
 
Example 28
@Override
public void print(PrintStream out) {
    out.println("TripleStore based on Blazegraph");
    RepositoryConnection conn;
    try {
        conn = repo.getConnection();
        try {
            RepositoryResult<Resource> ctxs = conn.getContextIDs();
            while (ctxs.hasNext()) {
                Resource ctx = ctxs.next();
                int size = statementsCount(conn, ctx);
                out.println("    " + ctx + " : " + size);
                if (PRINT_ALL_STATEMENTS) {
                    RepositoryResult<Statement> statements = conn.getStatements(null, null, null, true, ctx);
                    while (statements.hasNext()) {
                        Statement statement = statements.next();
                        out.println("        " + statement.getSubject() + " " + statement.getPredicate() + " "
                            + statement.getObject());
                    }
                }
            }
        } finally {
            closeConnection(conn, "Printing");
        }
    } catch (RepositoryException e) {
        LOG.error(e.getMessage());
    }
}
 
Example 29
Source Project: database   Source File: TestTicket2043b.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 30
private void update(RepositoryConnection conn, String query) {
    try {
        conn.prepareUpdate(QueryLanguage.SPARQL, query).execute();
    } catch (MalformedQueryException | UpdateExecutionException | RepositoryException e) {
        throw new TripleStoreException(String.format("Query [%s]", query), e);
    } finally {
        closeConnection(conn, "Update operation");
    }
}