org.eclipse.rdf4j.repository.RepositoryConnection Java Examples

The following examples show how to use org.eclipse.rdf4j.repository.RepositoryConnection. 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: SPARQLServiceEvaluationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Verify that all relevant variable names from the SERVICE clause get added to the result set when a BIND clause is
 * present.
 *
 * @see <a href="https://github.com/eclipse/rdf4j/issues/703">#703</a>
 */
@Test
public void testVariableNameHandling() throws Exception {
	String query = "select * { service <" + getRepositoryUrl(1) + "> { ?s ?p ?o . Bind(str(?o) as ?val) .  } }";

	// add some data to the remote endpoint (we don't care about the exact contents)
	prepareTest(null, Arrays.asList("/testcases-service/data13.ttl"));
	try (RepositoryConnection conn = localRepository.getConnection()) {
		TupleQuery tq = conn.prepareTupleQuery(query);
		TupleQueryResult tqr = tq.evaluate();

		assertNotNull(tqr);
		assertTrue(tqr.hasNext());

		List<BindingSet> result = QueryResults.asList(tqr);
		assertTrue(result.size() > 0);
		for (BindingSet bs : result) {
			assertTrue(bs.hasBinding("val"));
			assertTrue(bs.hasBinding("s"));
			assertTrue(bs.hasBinding("p"));
			assertTrue(bs.hasBinding("o"));
		}
	}
}
 
Example #2
Source File: RemoteRepositoryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static List<IRI> retrieveInstances(RepositoryConnection conn, IRI type) throws Exception {

		List<IRI> res = new ArrayList<>();
		RepositoryResult<Statement> qres = null;
		try {
			qres = conn.getStatements(null, RDF.TYPE, type, false);
			while (qres.hasNext() && res.size() < MAX_INSTANCES) {
				Statement next = qres.next();
				res.add((IRI) next.getObject());
			}
		} finally {
			try {
				if (qres != null) {
					qres.close();
				}
			} catch (Exception ignore) {
			}
		}
		return res;
	}
 
Example #3
Source File: KnowledgeBaseServiceImpl.java    From inception with Apache License 2.0 6 votes vote down vote up
@Override
public void update(KnowledgeBase kb, UpdateAction aAction)
{
    if (kb.isReadOnly()) {
        throw new ReadOnlyException(
                "Knowledge base [" + kb.getName() + "] is read only, will not alter!");
    }

    try (RepositoryConnection conn = getConnection(kb)) {
        boolean error = true;
        try {
            conn.begin();
            aAction.accept(conn);
            conn.commit();
            error = false;
        }
        finally {
            if (error) {
                conn.rollback();
            }
        }
    }
}
 
Example #4
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testSPOSubjRange() throws Exception {
    RepositoryConnection conn = repository.getConnection();
    IRI cpu2 = VF.createIRI(litdupsNS, "cpu2");
    IRI cpu3 = VF.createIRI(litdupsNS, "cpu3");
    IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc");
    Literal six = VF.createLiteral("6");
    Literal sev = VF.createLiteral("7");
    Literal ten = VF.createLiteral("10");
    conn.add(cpu, loadPerc, six);
    conn.add(cpu2, loadPerc, sev);
    conn.add(cpu3, loadPerc, ten);
    conn.commit();

    String query = "PREFIX org.apache: <" + NAMESPACE + ">\n" +
            "select * where {" +
            "?s ?p ?o.\n" +
            "FILTER(org.apache:range(?s, <" + cpu.stringValue() + ">, <" + cpu2.stringValue() + ">))." +
            "}";
    TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    CountTupleHandler cth = new CountTupleHandler();
    tupleQuery.evaluate(cth);
    conn.close();
    assertEquals(cth.getCount(), 2);
}
 
Example #5
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testMMRTS152() throws Exception {
        RepositoryConnection conn = repository.getConnection();
        IRI loadPerc = VF.createIRI(litdupsNS, "testPred");
        IRI uri1 = VF.createIRI(litdupsNS, "uri1");
        conn.add(cpu, loadPerc, uri1);
        conn.commit();

        RepositoryResult<Statement> result = conn.getStatements(cpu, loadPerc, null, false);
//        RdfCloudTripleStoreCollectionStatementsIterator iterator = new RdfCloudTripleStoreCollectionStatementsIterator(
//                cpu, loadPerc, null, store.connector,
//                vf, new Configuration(), null);

        while (result.hasNext()) {
            assertTrue(result.hasNext());
            assertNotNull(result.next());
        }

        conn.close();
    }
 
Example #6
Source File: RepositoryPerformance.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private int runQuery(RepositoryConnection conn, IRI instance) throws Exception {

			long start = System.currentTimeMillis();
			TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL,
					"SELECT * WHERE { <" + instance.stringValue() + "> ?p ?o }");

			TupleQueryResult res = null;
			try {
				res = query.evaluate();
				int count = 0;
				while (res.hasNext()) {
					res.next();
					count++;
				}
				System.out.println("Instance " + instance.stringValue() + " has " + count + " results. Duration: "
						+ (System.currentTimeMillis() - start) + "ms");
				return count;
			} finally {
				if (res != null) {
					res.close();
				}
			}
		}
 
Example #7
Source File: ArbitraryLengthQueryTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * This test works. The expected result is 6 rows ranging from "Model1Class 1" through "Model1Class 6".
 *
 * @throws RepositoryException
 * @throws QueryEvaluationException
 * @throws TupleQueryResultHandlerException
 *
 * @throws MalformedQueryException
 */
public void testWithoutSubquery() throws RepositoryException, QueryEvaluationException, TupleQueryResultHandlerException, MalformedQueryException {
    final String query = "SELECT ?i ?i_label ?i_class ?i_v1"
            + "WHERE {"
            + "?i <http://www.w3.org/2000/01/rdf-schema#label> ?i_label ."
            + "?i a ?i_class ."
            + "?i_class <http://www.w3.org/2000/01/rdf-schema#subClassOf>* <http://dragon-research.com/cham/model/model1#Model1Class> ."
            + "OPTIONAL { ?i <http://dragon-research.com/cham/model/model1#name> ?i_v1 } ."
            + "}"
            + "ORDER BY ?i_label";

    final RepositoryConnection conn = repository.getConnection();
    final TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    RdfCloudTripleStoreConnectionTest.CountTupleHandler countTupleHandler = new RdfCloudTripleStoreConnectionTest.CountTupleHandler();
    tupleQuery.evaluate(countTupleHandler);
    assertEquals(6, countTupleHandler.getCount());
    conn.close();
}
 
Example #8
Source File: NamespaceController.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private ModelAndView getExportNamespaceResult(HttpServletRequest request, String prefix)
		throws ServerHTTPException, ClientHTTPException {
	try (RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request)) {
		String namespace = repositoryCon.getNamespace(prefix);

		if (namespace == null) {
			throw new ClientHTTPException(SC_NOT_FOUND, "Undefined prefix: " + prefix);
		}

		Map<String, Object> model = new HashMap<>();
		model.put(SimpleResponseView.CONTENT_KEY, namespace);

		return new ModelAndView(SimpleResponseView.getInstance(), model);
	} catch (RepositoryException e) {
		throw new ServerHTTPException("Repository error: " + e.getMessage(), e);
	}
}
 
Example #9
Source File: TBSSSummariesGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
public static Long getDistinctSubjectCount(String endpoint) {
	String strQuery = "SELECT  (COUNT(distinct ?s) AS ?triples) " + // 
			"WHERE " +
			"{" +
       		"?s ?p ?o " +
       		"} " ;
	SPARQLRepository repo = createSPARQLRepository(endpoint);
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		String v = rs.next().getValue("triples").stringValue();
		rs.close();
		return Long.parseLong(v);
	} finally {
		conn.close();
	}
}
 
Example #10
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 #11
Source File: ExploreServlet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void service(final WorkbenchRequest req, final HttpServletResponse resp, final TupleResultBuilder builder,
		final RepositoryConnection con) throws BadRequestException, RDF4JException {
	final Value value = req.getValue("resource");
	logger.debug("resource = {}", value);

	// At worst, malicious parameter value could cause inaccurate
	// reporting of count in page.
	int count = req.getInt("know_total");
	if (count == 0) {
		count = this.processResource(con, builder, value, 0, Integer.MAX_VALUE, false).getTotalResultCount();
	}
	this.cookies.addTotalResultCountCookie(req, resp, (int) count);
	final int offset = req.getInt("offset");
	int limit = LIMIT_DEFAULT;
	if (req.isParameterPresent(LIMIT)) {
		limit = req.getInt(LIMIT);
		if (0 == limit) {
			limit = Integer.MAX_VALUE;
		}
	}
	this.processResource(con, builder, value, offset, limit, true);
}
 
Example #12
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testOSPObjRange() throws Exception {
    RepositoryConnection conn = repository.getConnection();
    IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc");
    Literal six = VF.createLiteral("6");
    Literal sev = VF.createLiteral("7");
    Literal ten = VF.createLiteral("10");
    conn.add(cpu, loadPerc, six);
    conn.add(cpu, loadPerc, sev);
    conn.add(cpu, loadPerc, ten);
    conn.commit();

    String query = "PREFIX org.apache: <" + NAMESPACE + ">\n" +
            "select * where {" +
            "?s ?p ?o.\n" +
            "FILTER(org.apache:range(?o, '6', '8'))." +
            "}";
    TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    CountTupleHandler cth = new CountTupleHandler();
    tupleQuery.evaluate(cth);
    conn.close();
    assertEquals(cth.getCount(), 2);
}
 
Example #13
Source File: PcjTables.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new PCJ Table in Accumulo and populates it by scanning an
 * instance of Rya for historic matches.
 * <p>
 * If any portion of this operation fails along the way, the partially
 * create PCJ table will be left in Accumulo.
 *
 * @param ryaConn - Connects to the Rya that will be scanned. (not null)
 * @param accumuloConn - Connects to the accumulo that hosts the PCJ results. (not null)
 * @param pcjTableName - The name of the PCJ table that will be created. (not null)
 * @param sparql - The SPARQL query whose results will be loaded into the table. (not null)
 * @param resultVariables - The variables that are included in the query's resulting binding sets. (not null)
 * @param pcjVarOrderFactory - An optional factory that indicates the various variable orders
 *   the results will be stored in. If one is not provided, then {@link ShiftVarOrderFactory}
 *   is used by default. (not null)
 * @throws PCJStorageException The PCJ table could not be create or the values from
 *   Rya were not able to be loaded into it.
 */
public void createAndPopulatePcj(
        final RepositoryConnection ryaConn,
        final Connector accumuloConn,
        final String pcjTableName,
        final String sparql,
        final String[] resultVariables,
        final Optional<PcjVarOrderFactory> pcjVarOrderFactory) throws PCJStorageException {
    checkNotNull(ryaConn);
    checkNotNull(accumuloConn);
    checkNotNull(pcjTableName);
    checkNotNull(sparql);
    checkNotNull(resultVariables);
    checkNotNull(pcjVarOrderFactory);

    // Create the PCJ's variable orders.
    final PcjVarOrderFactory varOrderFactory = pcjVarOrderFactory.or(DEFAULT_VAR_ORDER_FACTORY);
    final Set<VariableOrder> varOrders = varOrderFactory.makeVarOrders( new VariableOrder(resultVariables) );

    // Create the PCJ table in Accumulo.
    createPcjTable(accumuloConn, pcjTableName, varOrders, sparql);

    // Load historic matches from Rya into the PCJ table.
    populatePcj(accumuloConn, pcjTableName, ryaConn);
}
 
Example #14
Source File: AbstractGenericLuceneTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testIndexWriterState() throws Exception {
	final String brokenTrig = "{ broken }";
	RepositoryConnection conn = repository.getConnection();
	try (StringReader sr = new StringReader(brokenTrig)) {
		conn.add(sr, "http://example.org/", RDFFormat.TRIG);
	} catch (Exception e) {
		// expected parse exception
		LOG.debug("Parse exception: {}", e.getMessage());
	}
	conn.close();
	conn = repository.getConnection();
	conn.clear(); // make sure this can be executed multiple times
	conn.add(FOAF.PERSON, RDFS.LABEL, SimpleValueFactory.getInstance().createLiteral("abc"));
	conn.close();
}
 
Example #15
Source File: SolrSailExample.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static void tupleQuery(String queryString, RepositoryConnection connection)
		throws QueryEvaluationException, RepositoryException, MalformedQueryException {
	System.out.println("Running query: \n" + queryString);
	TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
	try (TupleQueryResult result = query.evaluate()) {
		// print the results
		System.out.println("Query results:");
		while (result.hasNext()) {
			BindingSet bindings = result.next();
			System.out.println("found match: ");
			for (Binding binding : bindings) {
				System.out.println("\t" + binding.getName() + ": " + binding.getValue());
			}
		}
	}
}
 
Example #16
Source File: TurtleParserTestCase.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void parseNegativeNTriplesSyntaxTests(TestSuite suite, String fileBasePath, String testBaseUrl,
		String manifestBaseUrl, RepositoryConnection con) throws Exception {
	StringBuilder negativeQuery = new StringBuilder();
	negativeQuery.append(" PREFIX mf:   <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#>\n");
	negativeQuery.append(" PREFIX qt:   <http://www.w3.org/2001/sw/DataAccess/tests/test-query#>\n");
	negativeQuery.append(" PREFIX rdft: <http://www.w3.org/ns/rdftest#>\n");
	negativeQuery.append(" SELECT ?test ?testName ?inputURL ?outputURL \n");
	negativeQuery.append(" WHERE { \n");
	negativeQuery.append("     ?test a rdft:TestNTriplesNegativeSyntax . ");
	negativeQuery.append("     ?test mf:name ?testName . ");
	negativeQuery.append("     ?test mf:action ?inputURL . ");
	negativeQuery.append(" }");

	TupleQueryResult queryResult = con.prepareTupleQuery(QueryLanguage.SPARQL, negativeQuery.toString()).evaluate();

	// Add all negative parser tests to the test suite
	while (queryResult.hasNext()) {
		BindingSet bindingSet = queryResult.next();
		IRI nextTestUri = (IRI) bindingSet.getValue("test");
		String nextTestName = ((Literal) bindingSet.getValue("testName")).getLabel();
		String nextTestFile = removeBase(((IRI) bindingSet.getValue("inputURL")).toString(), manifestBaseUrl);
		String nextInputURL = fileBasePath + nextTestFile;

		String nextBaseUrl = testBaseUrl + nextTestFile;

		suite.addTest(new NegativeParserTest(nextTestUri, nextTestName, nextInputURL, nextBaseUrl,
				createNTriplesParser(), FailureMode.DO_NOT_IGNORE_FAILURE));
	}

	queryResult.close();

}
 
Example #17
Source File: LuceneSailExample.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void graphQuery(String queryString, RepositoryConnection connection)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	System.out.println("Running query: \n" + queryString);
	GraphQuery query = connection.prepareGraphQuery(QueryLanguage.SPARQL, queryString);
	try (GraphQueryResult result = query.evaluate()) {
		// print the results
		while (result.hasNext()) {
			Statement stmt = result.next();
			System.out.println("found match: " + stmt.getSubject().stringValue() + "\t"
					+ stmt.getPredicate().stringValue() + "\t" + stmt.getObject().stringValue());
		}
	}

}
 
Example #18
Source File: ExceptionUtil.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Trace the exception source within the exceptions to identify the originating endpoint. The message
 * of the provided exception is adapted to "@ endpoint.getId() - %orginalMessage".<p>
 * 
 * Note that in addition HTTP error codes are extracted from the title, if the exception resulted from
 * an HTTP error, such as for instance "503 Service unavailable"
 * 
 * @param conn
 * 			the connection to identify the the endpoint
 * @param ex
 * 			the exception
 * @param additionalInfo
 * 			additional information that might be helpful, e.g. the subquery
 * 
 * @return
 * 		 	a modified exception with endpoint source
 */
public static QueryEvaluationException traceExceptionSource(EndpointManager endpointManager, RepositoryConnection conn, QueryEvaluationException ex, String additionalInfo) {
	
	Endpoint e = endpointManager.getEndpoint(conn);
	
	String eID;
	
	if (e==null) {
		log.warn("No endpoint found for connection, probably changed from different thread.");
		eID = "unknown";
	} else {
		eID = e.getId();
	}
	
	// check for http error code (heuristic)
	String message = ex.getMessage();
	message = message==null ? "n/a" : message;
	Matcher m = httpErrorPattern.matcher(message);
	if (m.matches()) {
		log.error("HTTP error detected for endpoint " + eID + ":\n" + message);
		message = "HTTP Error: " + m.group(1);
	} else {
		log.info("No http error found, found: " + message);
	}

	
	QueryEvaluationException res = new QueryEvaluationException("@ " + eID + " - " + message + ". " + additionalInfo, ex.getCause());
	res.setStackTrace(ex.getStackTrace());
	return res;
}
 
Example #19
Source File: TripleStoreRDF4J.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void update(String query) {
    try (RepositoryConnection conn = repo.getConnection()) {
        conn.prepareUpdate(QueryLanguage.SPARQL, adjustedQuery(query)).execute();
    } catch (MalformedQueryException | UpdateExecutionException | RepositoryException e) {
        throw new TripleStoreException(String.format("Query [%s]", query), e);
    }
}
 
Example #20
Source File: TurtleParserTestCase.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void parseNegativeTurtleEvalTests(TestSuite suite, String fileBasePath, String testBaseUrl,
		String manifestBaseUrl, RepositoryConnection con) throws Exception {
	StringBuilder negativeEvalQuery = new StringBuilder();
	negativeEvalQuery.append(" PREFIX mf:   <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#>\n");
	negativeEvalQuery.append(" PREFIX qt:   <http://www.w3.org/2001/sw/DataAccess/tests/test-query#>\n");
	negativeEvalQuery.append(" PREFIX rdft: <http://www.w3.org/ns/rdftest#>\n");
	negativeEvalQuery.append(" SELECT ?test ?testName ?inputURL ?outputURL \n");
	negativeEvalQuery.append(" WHERE { \n");
	negativeEvalQuery.append("     ?test a rdft:TestTurtleNegativeEval . ");
	negativeEvalQuery.append("     ?test mf:name ?testName . ");
	negativeEvalQuery.append("     ?test mf:action ?inputURL . ");
	negativeEvalQuery.append(" }");

	TupleQueryResult queryResult = con.prepareTupleQuery(QueryLanguage.SPARQL, negativeEvalQuery.toString())
			.evaluate();

	// Add all negative eval tests to the test suite
	while (queryResult.hasNext()) {
		BindingSet bindingSet = queryResult.next();
		IRI nextTestUri = (IRI) bindingSet.getValue("test");
		String nextTestName = ((Literal) bindingSet.getValue("testName")).getLabel();
		String nextTestFile = removeBase(((IRI) bindingSet.getValue("inputURL")).toString(), manifestBaseUrl);
		String nextInputURL = fileBasePath + nextTestFile;

		String nextBaseUrl = testBaseUrl + nextTestFile;

		suite.addTest(new NegativeParserTest(nextTestUri, nextTestName, nextInputURL, nextBaseUrl,
				createTurtleParser(), FailureMode.DO_NOT_IGNORE_FAILURE));
	}

	queryResult.close();
}
 
Example #21
Source File: FedXWithLocalRepositoryManagerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testWithLocalRepositoryManager() throws Exception {

	addMemoryStore("repo1");
	addMemoryStore("repo2");

	ValueFactory vf = SimpleValueFactory.getInstance();
	addData("repo1", Lists.newArrayList(
			vf.createStatement(vf.createIRI("http://ex.org/p1"), RDF.TYPE, FOAF.PERSON)));
	addData("repo2", Lists.newArrayList(
			vf.createStatement(vf.createIRI("http://ex.org/p2"), RDF.TYPE, FOAF.PERSON)));

	FedXRepository repo = FedXFactory.newFederation()
			.withResolvableEndpoint("repo1")
			.withResolvableEndpoint("repo2")
			.withRepositoryResolver(repoManager)
			.create();
	try {

		repo.init();
		try (RepositoryConnection conn = repo.getConnection()) {

			List<Statement> sts = Iterations.asList(conn.getStatements(null, RDF.TYPE, FOAF.PERSON));
			Assertions.assertEquals(2, sts.size()); // two persons
		}

	} finally {
		repo.shutDown();
	}

}
 
Example #22
Source File: LocalRepositoryManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Set<Resource> getRemovedContexts(RepositoryConnection conn) {
	Set<Resource> result = removedContextsByConnection.get(conn);
	if (result == null) {
		result = new HashSet<>();
		removedContextsByConnection.put(conn, result);
	}
	return result;
}
 
Example #23
Source File: TripleStoreRDF4J.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void print(PrintStream out) {
    out.println("TripleStore based on RDF4J. Graph names and sizes");
    try (RepositoryConnection conn = repo.getConnection()) {
        RepositoryResult<Resource> ctxs = conn.getContextIDs();
        while (ctxs.hasNext()) {
            Resource ctx = ctxs.next();
            int size = statementsCount(conn, ctx);
            out.println("    " + ctx + " : " + size);
        }
    }
}
 
Example #24
Source File: DebugRepositoryConnectionListener.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void rollback(RepositoryConnection conn) {
	if (printing) {
		stream.println("ROLLBACK (" + getConnectionID(conn) + ")");
	}
	if (dumpingStack) {
		Thread.dumpStack();
	}
}
 
Example #25
Source File: TypesServlet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void service(TupleResultBuilder builder, RepositoryConnection con) throws Exception {
	TupleQuery query = con.prepareTupleQuery(SPARQL, DISTINCT_TYPE);
	try (TupleQueryResult result = query.evaluate()) {
		while (result.hasNext()) {
			builder.result(result.next().getValue("type"));
		}
	}
}
 
Example #26
Source File: HTTPRepository.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public RepositoryConnection getConnection() throws RepositoryException {
	if (!isInitialized()) {
		init();
	}
	return new HTTPRepositoryConnection(this, createHTTPClient());
}
 
Example #27
Source File: SchemaCachingRDFSInferencer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void initialize()
		throws SailException {
	super.initialize();

	if (sharedSchema) {
		return;
	}

	try (final SchemaCachingRDFSInferencerConnection conn = getConnection()) {
		conn.begin();

		conn.addAxiomStatements();

		List<Statement> tboxStatments = new ArrayList<>();

		if (schema != null) {

			try (RepositoryConnection schemaConnection = schema.getConnection()) {
				schemaConnection.begin();
				try (Stream<Statement> stream = schemaConnection.getStatements(null, null, null).stream()) {
					tboxStatments = stream
							.peek(conn::processForSchemaCache)
							.collect(Collectors.toList());
				}
				schemaConnection.commit();
			}
		}

		calculateInferenceMaps(conn, true);

		if (schema != null) {
			tboxStatments.forEach(statement -> conn.addStatement(statement.getSubject(),
					statement.getPredicate(), statement.getObject(), statement.getContext()));
		}

		conn.commit();
	}

}
 
Example #28
Source File: SPARQLUpdateTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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 #29
Source File: AbstractLuceneSailTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testPropertyVar() throws MalformedQueryException, RepositoryException, QueryEvaluationException {
	StringBuilder buffer = new StringBuilder();
	buffer.append("SELECT \n");
	buffer.append("  Resource, Property \n");
	buffer.append("FROM \n");
	buffer.append("  {Resource} <" + MATCHES + "> {} ");
	buffer.append("    <" + QUERY + "> {\"one\"}; ");
	buffer.append("    <" + PROPERTY + "> {Property} ");
	String q = buffer.toString();

	try (RepositoryConnection connection = repository.getConnection()) {
		// fire the query
		TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SERQL, q);
		try (TupleQueryResult result = query.evaluate()) {

			int results = 0;
			Map<IRI, IRI> expectedSubject = new HashMap<>();
			expectedSubject.put(SUBJECT_1, PREDICATE_1);
			expectedSubject.put(SUBJECT_2, PREDICATE_1);
			expectedSubject.put(SUBJECT_3, PREDICATE_2);
			while (result.hasNext()) {
				results++;
				BindingSet bindings = result.next();

				// the resource should be among the set of expected subjects, if so,
				// remove it from the set
				Value subject = bindings.getValue("Resource");
				IRI expectedProperty = expectedSubject.remove(subject);
				assertEquals("For subject " + subject, expectedProperty, bindings.getValue("Property"));
			}

			// there should have been 3 results
			assertEquals(3, results);
		}
	}
}
 
Example #30
Source File: AbstractFederationConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public CloseableIteration<? extends Resource, SailException> getContextIDsInternal() throws SailException {
	CloseableIteration<? extends Resource, SailException> cursor = union(RepositoryConnection::getContextIDs);

	cursor = new DistinctIteration<Resource, SailException>(cursor);

	return cursor;
}