Java源码示例:org.openrdf.query.Binding
示例1
protected int verifyQueryResult(
CloseableIteration<? extends BindingSet, QueryEvaluationException> resultIter,
int expectedBindingCount)
throws QueryEvaluationException
{
int resultCount = 0;
while (resultIter.hasNext()) {
BindingSet resultBindings = resultIter.next();
resultCount++;
assertEquals("Wrong number of binding names for binding set", expectedBindingCount,
resultBindings.getBindingNames().size());
int bindingCount = 0;
Iterator<Binding> bindingIter = resultBindings.iterator();
while (bindingIter.hasNext()) {
bindingIter.next();
bindingCount++;
}
assertEquals("Wrong number of bindings in binding set", expectedBindingCount, bindingCount);
}
return resultCount;
}
示例2
protected long debugPrintSolutions(final String query)
throws QueryEvaluationException, RepositoryException,
MalformedQueryException {
TupleQueryResult result = con.prepareTupleQuery(QueryLanguage.SPARQL,
query).evaluate();
try {
long n = 0;
while (result.hasNext()) {
System.err.println("==> NEXT SOLUTION");
final BindingSet bset = result.next();
for (final String bindingName : bset.getBindingNames()) {
final Binding b = bset.getBinding(bindingName);
System.err.println(bindingName + " -> " + b);
}
n++;
}
return n;
} finally {
result.close();
}
}
示例3
protected BindingSet createBindingSet(final Binding... bindings) {
final QueryBindingSet bindingSet = new QueryBindingSet();
if (bindings != null) {
for (Binding b : bindings) {
bindingSet.addBinding(b);
}
}
return bindingSet;
}
示例4
/**
* @see org.openrdf.http.client.HTTPClient#getQueryMethodParameters(QueryLanguage, String, String, Dataset, boolean, int, Binding...)
*/
protected void configureConnectOptions(IPreparedQuery q) {
if (baseURI != null) {
q.addRequestParam(RemoteRepositoryDecls.BASE_URI, baseURI);
}
q.addRequestParam(RemoteRepositoryDecls.INCLUDE_INFERRED,
Boolean.toString(includeInferred));
if (maxQueryTime > 0) {
q.addRequestParam(RemoteRepositoryDecls.MAX_QUERY_TIME_MILLIS, Long.toString(1000L*maxQueryTime));
}
if (dataset != null) {
String[] defaultGraphs = new String[dataset.getDefaultGraphs().size()];
int i=0;
for (URI defaultGraphURI : dataset.getDefaultGraphs()) {
defaultGraphs[i++] = String.valueOf(defaultGraphURI);
}
q.addRequestParam(q.isUpdate() ? RemoteRepositoryDecls.USING_GRAPH_URI
: RemoteRepositoryDecls.DEFAULT_GRAPH_URI, defaultGraphs);
String[] namedGraphs = new String[dataset.getNamedGraphs().size()];
i=0;
for (URI namedGraphURI : dataset.getNamedGraphs()) {
namedGraphs[i++] = String.valueOf(String.valueOf(namedGraphURI));
}
q.addRequestParam(q.isUpdate() ? RemoteRepositoryDecls.USING_NAMED_GRAPH_URI
: RemoteRepositoryDecls.NAMED_GRAPH_URI, namedGraphs);
}
for (Binding binding: bindings) {
String paramName = RemoteRepositoryDecls.BINDING_PREFIX + binding.getName();
String paramValue = EncodeDecodeValue.encodeValue(binding.getValue());
q.addRequestParam(paramName, paramValue);
}
}
示例5
protected BindingSet createBindingSet(final Binding... bindings) {
final QueryBindingSet bindingSet = new QueryBindingSet();
if (bindings != null) {
for (Binding b : bindings) {
bindingSet.addBinding(b);
}
}
return bindingSet;
}
示例6
/**
* Return <code>true</code> iff (a) there is more than one solution; and (b)
* any of the solutions has a blank node which is bound for more than one
* variable. We need to use a different strategy for vectoring the solutions
* to the remote service when this is true.
*
* @param bindingSets
* The solutions.
*/
static private boolean hasCorrelatedBlankNodeBindings(
final BindingSet[] bindingSets) {
if (bindingSets.length <= 1) {
/*
* Correlation in the variables through shared blank nodes is Ok as
* long as there is only one solution flowing into the service end
* point.
*/
return false;
}
for (BindingSet bindingSet : bindingSets) {
Set<BNode> bnodes = null;
for (Binding b : bindingSet) {
final Value v = b.getValue();
if (!(v instanceof BNode))
continue;
if (bnodes == null)
bnodes = new HashSet<BNode>();
final BNode t = (BNode) v;
if (bnodes.add(t)) {
/*
* This solution has at least two variable bindings for the
* same blank node.
*/
return true;
}
}
}
/*
* No solution has two or more variables which are bound in that
* solution to the same blank node.
*/
return false;
}
示例7
/**
* Return a correlated blank node / variables map.
* <p>
* Note: This is necessary because we can not have a blank node in a
* FunctionCall in SPARQL. However, unlike with the BINDINGS clause, we have
* to do it for each solution because we can vector more than one solution
* involving correlated blank nodes.
*
* @return The correlated variable bindings map -or- <code>null</code> iff
* there are no variables which are correlated through shared blank
* nodes.
*/
static private Map<BNode, Set<String/* vars */>> getCorrelatedVarsMap(
final BindingSet bindingSet) {
Map<BNode, Set<String/* vars */>> bnodes = null;
for (Binding b : bindingSet) {
final Value v = b.getValue();
if (!(v instanceof BNode))
continue;
if (bnodes == null)
bnodes = new LinkedHashMap<BNode, Set<String>>();
final BNode bnd = (BNode) v;
// Set of correlated variables.
Set<String> cvars = bnodes.get(bnd);
if (cvars == null) {
bnodes.put(bnd, cvars = new LinkedHashSet<String>());
} else {
/*
* Correlated. This blank node is already the binding for some
* other variable in this solution.
*
* Note: A FILTER can be used to enforce a same-term constraint
* for variables correlated via blank nodes, but only for a
* single solution.
*/
}
if (!cvars.add(b.getName())) {
/*
* This would imply the same variable was bound more
* than once in the solution.
*/
throw new AssertionError();
}
}
return bnodes;
}
示例8
/**
* When loading quads into a triple store, the context is striped away by
* default.
*/
public void testDateFunction() throws Exception {
BigdataSailRepositoryConnection cxn = null;
final BigdataSail sail = getSail(getTriplesNoInference());
try {
sail.initialize();
final BigdataSailRepository repo = new BigdataSailRepository(sail);
cxn = (BigdataSailRepositoryConnection) repo.getConnection();
cxn.begin();
try {
InputStream is = TestTicket1388.class.getResourceAsStream("testTicket1388.n3");
if (is == null) {
throw new IOException("Could not locate resource: " + "testTicket1388.n3");
}
Reader reader = new InputStreamReader(new BufferedInputStream(is));
try {
cxn.add(reader, "", RDFFormat.N3);
} finally {
reader.close();
}
cxn.commit();
} catch (OpenRDFException ex) {
cxn.rollback();
throw ex;
}
cxn.commit();
final String query = "SELECT ?myDate (count(?doc) as ?countDoc) \n " + //
"{ ?doc rdf:type <http://www.example.com/Document> . \n " + //
" ?doc <http://www.example.com/created> ?date . \n " + //
" filter((<http://www.w3.org/2001/XMLSchema#date>(?date)) >= \"2014-04-11\"^^<http://www.w3.org/2001/XMLSchema#date>) .\n " + //
" filter((<http://www.w3.org/2001/XMLSchema#date>(?date)) < \"2014-05-30\"^^<http://www.w3.org/2001/XMLSchema#date>) .\n " + //
" bind((<http://www.w3.org/2001/XMLSchema#date>(?date)) as ?myDate) .\n " + //
"} group by ?myDate";
final TupleQuery q = cxn.prepareTupleQuery(QueryLanguage.SPARQL,
query);
final TupleQueryResult tqr = q.evaluate();
final Collection<BindingSet> solution = new LinkedList<BindingSet>();
//[myDate="2014-04-11"^^<http://www.w3.org/2001/XMLSchema#date>;countDoc="3"^^<http://www.w3.org/2001/XMLSchema#integer>]
//[myDate="2014-05-29"^^<http://www.w3.org/2001/XMLSchema#date>;countDoc="2"^^<http://www.w3.org/2001/XMLSchema#integer>]
solution.add(createBindingSet(new Binding[] {
new BindingImpl("myDate", new LiteralImpl("2014-04-11", XMLSchema.DATE)),
new BindingImpl("countDoc", new LiteralImpl(Integer.toString(3), XMLSchema.INTEGER))
}));
solution.add(createBindingSet(new Binding[] {
new BindingImpl("myDate", new LiteralImpl("2014-05-29", XMLSchema.DATE)),
new BindingImpl("countDoc", new LiteralImpl(Integer.toString(2), XMLSchema.INTEGER))
}));
compare(tqr, solution);
tqr.close();
} finally {
if (cxn != null)
cxn.close();
sail.__tearDownUnitTest();
}
}
示例9
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();
}
}
示例10
@Override
public void run() {
RepositoryConnection conn = null;
TupleQueryResult result = null;
int loop = 0;
while (stopRequested == false) {
try {
System.out.println("[Read ] snooze");
snooze(MILLIS_BETWEEN_QUERY_BURSTS);
System.out.println("[Read ] enter loop " + loop);
for (int invocation = 0; invocation < NUM_SELECTS; ++invocation) {
conn = repo.getReadOnlyConnection();
conn.setAutoCommit(false);
final String sparql = "SELECT ?s WHERE { ?s ?p ?o } LIMIT "
+ NUM_STATEMENTS_PER_SELECT;
final TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, sparql);
result = query.evaluate();
final List<String> duds = new ArrayList<String>();
while (result.hasNext()) {
final BindingSet bindingSet = result.next();
for (final Iterator<Binding> i = bindingSet.iterator(); i.hasNext();) {
final Binding b = i.next();
if (b.getValue() != null) {
duds.add(b.getValue().stringValue());
}
}
}
result.close();
result = null;
conn.close();
conn = null;
}
} catch (Throwable t) {
printError("Read Only threw in loop " + loop, t);
} finally {
closeNoException(result);
closeNoException(conn);
}
System.out.println("[Read ] leave loop " + loop);
++loop;
}
}
示例11
/**
* Tests adding query hints in SPARQL.
*
* @throws Exception
*/
public void testPruneBindingSets() throws Exception {
final BigdataSail sail = getSail();
try {
sail.initialize();
final BigdataSailRepository repo = new BigdataSailRepository(sail);
final BigdataSailRepositoryConnection cxn =
(BigdataSailRepositoryConnection) repo.getConnection();
try {
cxn.setAutoCommit(false);
URI x = new URIImpl("_:X");
URI a = new URIImpl("_:A");
URI b = new URIImpl("_:B");
URI c = new URIImpl("_:C");
URI d = new URIImpl("_:D");
URI e = new URIImpl("_:E");
/**/
cxn.add(a, x, b);
cxn.add(b, x, c);
cxn.add(c, x, d);
cxn.add(d, x, e);
/**/
/*
* 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.flush();//commit();
cxn.commit();
/**/
if (log.isInfoEnabled()) {
log.info(cxn.getTripleStore().dumpStore());
}
{
String query =
"select ?a " +
"WHERE { " +
" ?a <"+x+"> ?b ." +
" ?b <"+x+"> ?c ." +
" ?c <"+x+"> ?d ." +
" ?d <"+x+"> <"+e+"> ." +
"}";
final TupleQuery tupleQuery =
cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
TupleQueryResult result = tupleQuery.evaluate();
Collection<BindingSet> solution = new LinkedList<BindingSet>();
solution.add(createBindingSet(new Binding[] {
new BindingImpl("a", a)
}));
compare(result, solution);
}
} finally {
cxn.close();
}
} finally {
sail.__tearDownUnitTest();
}
}
示例12
public void testInlineValuesLT() throws Exception {
final BigdataSail sail = getSail();
sail.initialize();
final BigdataSailRepository repo = new BigdataSailRepository(sail);
final BigdataSailRepositoryConnection cxn =
(BigdataSailRepositoryConnection) repo.getConnection();
cxn.setAutoCommit(false);
try {
final ValueFactory vf = sail.getValueFactory();
URI A = vf.createURI("_:A");
URI B = vf.createURI("_:B");
URI X = vf.createURI("_:X");
URI AGE = vf.createURI("_:AGE");
Literal _25 = vf.createLiteral(25);
Literal _45 = vf.createLiteral(45);
cxn.add(A, RDF.TYPE, X);
cxn.add(B, RDF.TYPE, X);
cxn.add(A, AGE, _25);
cxn.add(B, AGE, _45);
/*
* 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.flush();//commit();
if (log.isInfoEnabled()) {
log.info(cxn.getTripleStore().dumpStore());
}
{
String query =
"select ?s ?age " +
"WHERE { " +
" ?s <"+RDF.TYPE+"> <"+X+"> . " +
" ?s <"+AGE+"> ?age . " +
" FILTER( ?age < 35 ) . " +
"}";
final TupleQuery tupleQuery =
cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
TupleQueryResult result = tupleQuery.evaluate();
Collection<BindingSet> solution = new LinkedList<BindingSet>();
solution.add(createBindingSet(new Binding[] {
new BindingImpl("s", A),
new BindingImpl("age", _25)
}));
compare(result, solution);
}
} finally {
cxn.close();
sail.__tearDownUnitTest();
}
}
示例13
public void testInlineValuesGT() throws Exception {
final BigdataSail sail = getSail();
sail.initialize();
final BigdataSailRepository repo = new BigdataSailRepository(sail);
final BigdataSailRepositoryConnection cxn =
(BigdataSailRepositoryConnection) repo.getConnection();
cxn.setAutoCommit(false);
try {
final ValueFactory vf = sail.getValueFactory();
URI A = vf.createURI("_:A");
URI B = vf.createURI("_:B");
URI X = vf.createURI("_:X");
URI AGE = vf.createURI("_:AGE");
Literal _25 = vf.createLiteral(25);
Literal _45 = vf.createLiteral(45);
cxn.add(A, RDF.TYPE, X);
cxn.add(B, RDF.TYPE, X);
cxn.add(A, AGE, _25);
cxn.add(B, AGE, _45);
/*
* 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.flush();//commit();
if (log.isInfoEnabled()) {
log.info(cxn.getTripleStore().dumpStore());
}
{
String query =
"select ?s ?age " +
"WHERE { " +
" ?s <"+RDF.TYPE+"> <"+X+"> . " +
" ?s <"+AGE+"> ?age . " +
" FILTER( ?age > 35 ) . " +
"}";
final TupleQuery tupleQuery =
cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
TupleQueryResult result = tupleQuery.evaluate();
Collection<BindingSet> solution = new LinkedList<BindingSet>();
solution.add(createBindingSet(new Binding[] {
new BindingImpl("s", B),
new BindingImpl("age", _45)
}));
compare(result, solution);
}
} finally {
cxn.close();
sail.__tearDownUnitTest();
}
}
示例14
public void testSimpleJoin() throws Exception {
final BigdataSail sail = getSail();
try {
sail.initialize();
final BigdataSailRepository repo = new BigdataSailRepository(sail);
final BigdataSailRepositoryConnection cxn =
(BigdataSailRepositoryConnection) repo.getConnection();
cxn.setAutoCommit(false);
try {
// final ValueFactory vf = sail.getValueFactory();
final String ns = BD.NAMESPACE;
final URI mike = new URIImpl(ns+"Mike");
final URI bryan = new URIImpl(ns+"Bryan");
final URI person = new URIImpl(ns+"Person");
final URI likes = new URIImpl(ns+"likes");
final URI rdf = new URIImpl(ns+"RDF");
final Literal l1 = new LiteralImpl("Mike");
final Literal l2 = new LiteralImpl("Bryan");
/**/
cxn.setNamespace("ns", ns);
cxn.add(mike, RDF.TYPE, person);
cxn.add(mike, likes, rdf);
cxn.add(mike, RDFS.LABEL, l1);
cxn.add(bryan, RDF.TYPE, person);
cxn.add(bryan, likes, rdf);
cxn.add(bryan, RDFS.LABEL, l2);
/*
* 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.flush();//commit();
cxn.commit();//
if (log.isInfoEnabled()) {
log.info("\n" + cxn.getTripleStore().dumpStore());
}
{
final String query =
"PREFIX rdf: <"+RDF.NAMESPACE+"> " +
"PREFIX rdfs: <"+RDFS.NAMESPACE+"> " +
"PREFIX ns: <"+ns+"> " +
"select * " +
"WHERE { " +
" ?s rdf:type ns:Person . " +
" ?s ns:likes ?likes . " +
" ?s rdfs:label ?label . " +
"}";
final TupleQuery tupleQuery =
cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
final TupleQueryResult result = tupleQuery.evaluate();
// while (result.hasNext()) {
// System.err.println(result.next());
// }
final Collection<BindingSet> solution = new LinkedList<BindingSet>();
solution.add(createBindingSet(new Binding[] {
new BindingImpl("s", mike),
new BindingImpl("likes", rdf),
new BindingImpl("label", l1)
}));
solution.add(createBindingSet(new Binding[] {
new BindingImpl("s", bryan),
new BindingImpl("likes", rdf),
new BindingImpl("label", l2)
}));
compare(result, solution);
}
} finally {
cxn.close();
}
} finally {
sail.__tearDownUnitTest();
}
}
示例15
public void testSimpleConstraint() throws Exception {
final BigdataSail sail = getSail();
try {
sail.initialize();
final BigdataSailRepository repo = new BigdataSailRepository(sail);
final BigdataSailRepositoryConnection cxn =
(BigdataSailRepositoryConnection) repo.getConnection();
cxn.setAutoCommit(false);
try {
final ValueFactory vf = sail.getValueFactory();
final String ns = BD.NAMESPACE;
final URI jill = new URIImpl(ns+"Jill");
final URI jane = new URIImpl(ns+"Jane");
final URI person = new URIImpl(ns+"Person");
final URI age = new URIImpl(ns+"age");
final URI IQ = new URIImpl(ns+"IQ");
final Literal l1 = new LiteralImpl("Jill");
final Literal l2 = new LiteralImpl("Jane");
final Literal age1 = vf.createLiteral(20);
final Literal age2 = vf.createLiteral(30);
final Literal IQ1 = vf.createLiteral(130);
final Literal IQ2 = vf.createLiteral(140);
/**/
cxn.setNamespace("ns", ns);
cxn.add(jill, RDF.TYPE, person);
cxn.add(jill, RDFS.LABEL, l1);
cxn.add(jill, age, age1);
cxn.add(jill, IQ, IQ1);
cxn.add(jane, RDF.TYPE, person);
cxn.add(jane, RDFS.LABEL, l2);
cxn.add(jane, age, age2);
cxn.add(jane, IQ, IQ2);
/*
* 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.flush();//commit();
cxn.commit();//
if (log.isInfoEnabled()) {
log.info("\n" + cxn.getTripleStore().dumpStore());
}
{
final String query =
"PREFIX rdf: <"+RDF.NAMESPACE+"> " +
"PREFIX rdfs: <"+RDFS.NAMESPACE+"> " +
"PREFIX ns: <"+ns+"> " +
"select * " +
"WHERE { " +
" ?s rdf:type ns:Person . " +
" ?s ns:age ?age . " +
" ?s ns:IQ ?iq . " +
" ?s rdfs:label ?label . " +
" FILTER( ?age < 25 && ?iq > 125 ) . " +
"}";
final TupleQuery tupleQuery =
cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
final TupleQueryResult result = tupleQuery.evaluate();
// while (result.hasNext()) {
// System.err.println(result.next());
// }
final Collection<BindingSet> solution = new LinkedList<BindingSet>();
solution.add(createBindingSet(new Binding[] {
new BindingImpl("s", jill),
new BindingImpl("age", age1),
new BindingImpl("iq", IQ1),
new BindingImpl("label", l1)
}));
compare(result, solution);
}
} finally {
cxn.close();
}
} finally {
sail.__tearDownUnitTest();
}
}
示例16
public void testSimpleOptional() throws Exception {
final BigdataSail sail = getSail();
try {
sail.initialize();
final BigdataSailRepository repo = new BigdataSailRepository(sail);
final BigdataSailRepositoryConnection cxn =
(BigdataSailRepositoryConnection) repo.getConnection();
cxn.setAutoCommit(false);
try {
// final ValueFactory vf = sail.getValueFactory();
final String ns = BD.NAMESPACE;
final URI mike = new URIImpl(ns+"Mike");
final URI bryan = new URIImpl(ns+"Bryan");
final URI person = new URIImpl(ns+"Person");
final URI likes = new URIImpl(ns+"likes");
final URI rdf = new URIImpl(ns+"RDF");
final Literal l1 = new LiteralImpl("Mike");
// final Literal l2 = new LiteralImpl("Bryan");
/**/
cxn.setNamespace("ns", ns);
cxn.add(mike, RDF.TYPE, person);
cxn.add(mike, likes, rdf);
cxn.add(mike, RDFS.LABEL, l1);
cxn.add(bryan, RDF.TYPE, person);
cxn.add(bryan, likes, rdf);
// cxn.add(bryan, RDFS.LABEL, l2);
/*
* 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.flush();//commit();
cxn.commit();//
if (log.isInfoEnabled()) {
log.info("\n" + cxn.getTripleStore().dumpStore());
}
{
final String query =
"PREFIX rdf: <"+RDF.NAMESPACE+"> " +
"PREFIX rdfs: <"+RDFS.NAMESPACE+"> " +
"PREFIX ns: <"+ns+"> " +
"select * " +
"WHERE { " +
" ?s rdf:type ns:Person . " +
" ?s ns:likes ?likes . " +
" OPTIONAL { ?s rdfs:label ?label . } " +
"}";
final TupleQuery tupleQuery =
cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
final TupleQueryResult result = tupleQuery.evaluate();
// while (result.hasNext()) {
// System.err.println(result.next());
// }
final Collection<BindingSet> solution = new LinkedList<BindingSet>();
solution.add(createBindingSet(new Binding[] {
new BindingImpl("s", mike),
new BindingImpl("likes", rdf),
new BindingImpl("label", l1)
}));
solution.add(createBindingSet(new Binding[] {
new BindingImpl("s", bryan),
new BindingImpl("likes", rdf),
// new BindingImpl("label", l2)
}));
compare(result, solution);
}
} finally {
cxn.close();
}
} finally {
sail.__tearDownUnitTest();
}
}
示例17
public void testOrEquals() throws Exception {
final BigdataSail sail = getSail();
try {
sail.initialize();
final BigdataSailRepository repo = new BigdataSailRepository(sail);
final BigdataSailRepositoryConnection cxn =
(BigdataSailRepositoryConnection) repo.getConnection();
cxn.setAutoCommit(false);
try {
// final ValueFactory vf = sail.getValueFactory();
//
// final LexiconRelation lex = sail.getDatabase().getLexiconRelation();
final String ns = BD.NAMESPACE;
final URI mike = new URIImpl(ns+"Mike");
final URI bryan = new URIImpl(ns+"Bryan");
final URI martyn = new URIImpl(ns+"Martyn");
final URI person = new URIImpl(ns+"Person");
final URI p = new URIImpl(ns+"p");
final Literal l1 = new LiteralImpl("Mike");
final Literal l2 = new LiteralImpl("Bryan");
final Literal l3 = new LiteralImpl("Martyn");
/**/
cxn.setNamespace("ns", ns);
cxn.add(mike, RDF.TYPE, person);
cxn.add(mike, RDFS.LABEL, l1);
cxn.add(bryan, RDF.TYPE, person);
cxn.add(bryan, RDFS.COMMENT, l2);
cxn.add(martyn, RDF.TYPE, person);
cxn.add(martyn, p, l3);
/*
* 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.flush();//commit();
cxn.commit();//
if (log.isInfoEnabled()) {
log.info("\n" + cxn.getTripleStore().dumpStore());
}
{
String query =
"PREFIX rdf: <"+RDF.NAMESPACE+"> " +
"PREFIX rdfs: <"+RDFS.NAMESPACE+"> " +
"PREFIX ns: <"+ns+"> " +
"select * " +
"WHERE { " +
" ?s rdf:type ns:Person . " +
" ?s ?p ?label . " +
" FILTER ( ?p = rdfs:label || ?p = rdfs:comment ) . " +
"}";
final TupleQuery tupleQuery =
cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
final TupleQueryResult result = tupleQuery.evaluate();
// while (result.hasNext()) {
// System.err.println(result.next());
// }
final Collection<BindingSet> solution = new LinkedList<BindingSet>();
solution.add(createBindingSet(new Binding[] {
new BindingImpl("s", mike),
new BindingImpl("p", RDFS.LABEL),
new BindingImpl("label", l1)
}));
solution.add(createBindingSet(new Binding[] {
new BindingImpl("s", bryan),
new BindingImpl("p", RDFS.COMMENT),
new BindingImpl("label", l2)
}));
compare(result, solution);
}
} finally {
cxn.close();
}
} finally {
sail.__tearDownUnitTest();
}
}
示例18
/**
* Return an ordered collection of the distinct variable names used in the
* given caller's solution set.
*
* @param bindingSets
* The solution set.
*
* @return The distinct, ordered collection of variables used.
*/
protected LinkedHashSet<String> getDistinctVars(final BindingSet[] bindingSets) {
final LinkedHashSet<String> vars = new LinkedHashSet<String>();
for (BindingSet bindingSet : bindingSets) {
for (Binding binding : bindingSet) {
vars.add(binding.getName());
}
}
return vars;
}
示例19
/**
* Return a correlated blank node / variables map.
* <p>
* Note: This is necessary because the BINDINGS clause does not permit blank
* nodes.
*
* @return The correlated variable bindings map -or- <code>null</code> iff
* there are no variables which are correlated through shared blank
* nodes.
*
* @throws UnsupportedOperationException
* If there are correlated variables and there is more than one
* source solution (for this case you need to use the SPARQL 1.0
* compatible query generator).
*
* @see RemoteSparql10QueryBuilder
*/
protected static Map<BNode, Set<String>> getCorrelatedVariables(
final BindingSet[] bindingSets) {
Map<BNode, Set<String/* vars */>> bnodes = null;
for (BindingSet bindingSet : bindingSets) {
for (Binding b : bindingSet) {
final Value v = b.getValue();
if (!(v instanceof BNode))
continue;
if (bnodes == null)
bnodes = new LinkedHashMap<BNode, Set<String>>();
final BNode bnd = (BNode) v;
// Set of correlated variables.
Set<String> cvars = bnodes.get(bnd);
if (cvars == null) {
bnodes.put(bnd, cvars = new LinkedHashSet<String>());
} else {
/*
* Correlated. This blank node is already the binding
* for some other variable in this solution.
*
* Note: A FILTER can be used to enforce a same-term
* constraint for variables correlated via blank nodes,
* but only for a single solution. If there is more than
* one solution then you CAN NOT use the BINDINGS clause
* to communicate the binding sets without also
* rewriting the SERVICE clause as a UNION of the
* original SERVICE class for each source binding set.
*/
if (bindingSets.length > 1)
throw new UnsupportedOperationException();
}
if (!cvars.add(b.getName())) {
/*
* This would imply the same variable was bound more
* than once in the solution.
*/
throw new AssertionError();
}
}
}
return bnodes;
}
示例20
/**
* Copied from org.openrdf.query.QueryResultUtil
*/
private static boolean bindingSetsMatch(final BindingSet bs1, final BindingSet bs2) {
if (bs1.size() != bs2.size()) {
return false;
}
for (Binding binding1 : bs1) {
Value value1 = binding1.getValue();
Value value2 = bs2.getValue(binding1.getName());
if ((value1 instanceof BNode) && (value2 instanceof BNode)) {
// BNode mappedBNode = bNodeMapping.get(value1);
//
// if (mappedBNode != null) {
// // bNode 'value1' was already mapped to some other bNode
// if (!value2.equals(mappedBNode)) {
// // 'value1' and 'value2' do not match
// return false;
// }
// } else {
// // 'value1' was not yet mapped, we need to check if 'value2'
// // is a
// // possible mapping candidate
// if (bNodeMapping.containsValue(value2)) {
// // 'value2' is already mapped to some other value.
// return false;
// }
// }
return value1.equals(value2);
} else {
// values are not (both) bNodes
if ((value1 instanceof Literal) && (value2 instanceof Literal)) {
// do literal value-based comparison for supported datatypes
Literal leftLit = (Literal) value1;
Literal rightLit = (Literal) value2;
URI dt1 = leftLit.getDatatype();
URI dt2 = rightLit.getDatatype();
if ((dt1 != null) && (dt2 != null) && dt1.equals(dt2) && XMLDatatypeUtil.isValidValue(leftLit.getLabel(), dt1)
&& XMLDatatypeUtil.isValidValue(rightLit.getLabel(), dt2)) {
Integer compareResult = null;
if (dt1.equals(XMLSchema.DOUBLE)) {
compareResult = Double.compare(leftLit.doubleValue(), rightLit.doubleValue());
} else if (dt1.equals(XMLSchema.FLOAT)) {
compareResult = Float.compare(leftLit.floatValue(), rightLit.floatValue());
} else if (dt1.equals(XMLSchema.DECIMAL)) {
compareResult = leftLit.decimalValue().compareTo(rightLit.decimalValue());
} else if (XMLDatatypeUtil.isIntegerDatatype(dt1)) {
compareResult = leftLit.integerValue().compareTo(rightLit.integerValue());
} else if (dt1.equals(XMLSchema.BOOLEAN)) {
Boolean leftBool = Boolean.valueOf(leftLit.booleanValue());
Boolean rightBool = Boolean.valueOf(rightLit.booleanValue());
compareResult = leftBool.compareTo(rightBool);
} else if (XMLDatatypeUtil.isCalendarDatatype(dt1)) {
XMLGregorianCalendar left = leftLit.calendarValue();
XMLGregorianCalendar right = rightLit.calendarValue();
compareResult = left.compare(right);
}
if (compareResult != null) {
if (compareResult.intValue() != 0) {
return false;
}
} else if (!value1.equals(value2)) {
return false;
}
} else if (!value1.equals(value2)) {
return false;
}
} else if (!value1.equals(value2)) {
return false;
}
}
}
return true;
}
示例21
@Test
public void queryOrderAscTest() throws RepositoryException, MalformedQueryException, QueryEvaluationException {
Iterator<String> iter = _orderByAscQueries.iterator();
while (iter.hasNext()) {
String query = iter.next();
TupleQuery cq = CUMULUS_CONNECTION.prepareTupleQuery(QueryLanguage.SPARQL, query);
TupleQueryResult cRes = cq.evaluate();
String last = null;
String current = null;
while (cRes.hasNext()) {
BindingSet bs = cRes.next();
Iterator<Binding> bindings = bs.iterator();
while (bindings.hasNext()) {
Binding b = bindings.next();
Value v = b.getValue();
if (v instanceof Literal) {
current = v.stringValue();
try {
double currDouble = Double.parseDouble(current);
double lastDouble;
if (last == null) {
lastDouble = -Double.MAX_VALUE;
} else {
lastDouble = Double.parseDouble(last);
}
assertTrue(currDouble >= lastDouble);
last = current;
} catch (NumberFormatException ne) {
if (last == null) {
last = "";
}
assertTrue(last.compareTo(current) <= 0);
last = current;
}
}
}
}
}
}
示例22
@Test
public void queryOrderDescTest() throws RepositoryException, MalformedQueryException, QueryEvaluationException {
Iterator<String> iter = _orderByDescQueries.iterator();
while (iter.hasNext()) {
String query = iter.next();
TupleQuery cq = CUMULUS_CONNECTION.prepareTupleQuery(QueryLanguage.SPARQL, query);
TupleQueryResult cRes = cq.evaluate();
String last = null;
String current = null;
while (cRes.hasNext()) {
BindingSet bs = cRes.next();
Iterator<Binding> bindings = bs.iterator();
while (bindings.hasNext()) {
Binding b = bindings.next();
Value v = b.getValue();
if (v instanceof Literal) {
current = v.stringValue();
try {
double currDouble = Double.parseDouble(current);
double lastDouble;
if (last == null) {
lastDouble = Double.MAX_VALUE;
} else {
lastDouble = Double.parseDouble(last);
}
assertTrue(currDouble <= lastDouble);
last = current;
} catch (NumberFormatException ne) {
if (last == null) {
last = "_";
}
assertTrue(last.compareTo(current) >= 0);
last = current;
}
}
}
}
}
}
示例23
public GlobalSecurityValidator(final Repository repo) {
final TupleQueryResult result;
try {
result = Utils.executeSelectQuery(repo, GRANTED_DOCUMENTS, QueryLanguage.SPARQL);
while(result.hasNext()){
BindingSet bs = result.next();
Binding user = bs.getBinding("user");
Binding document = bs.getBinding("doc");
if(securityInfo.containsKey(user)){
securityInfo.get(user).add(document.getValue());
}else{
List<Value> docs = new LinkedList<Value>();
docs.add(document.getValue());
securityInfo.put(user.getValue(), docs);
}
}
} catch (OpenRDFException e) {
log.error("Security info was not collected", e);
}
}
示例24
/**
* Convert a Sesame {@link BindingSet} into a bigdata {@link IBindingSet}.
*
* @param src
* The {@link BindingSet} (optional).
*
* @return The {@link IBindingSet}. When the source is null or empty, an
* empty {@link ListBindingSet} is returned.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private static IBindingSet[] toBindingSet(final BindingSet src) {
if (src == null || src.size() == 0) {
return new IBindingSet[] { new ListBindingSet() };
}
final ListBindingSet bindingSet = new ListBindingSet();
final Iterator<Binding> itr = src.iterator();
while (itr.hasNext()) {
final Binding binding = itr.next();
final IVariable<IV> var = com.bigdata.bop.Var.var(binding.getName());
final IV iv = ((BigdataValue) binding.getValue()).getIV();
final IConstant<IV> val = new Constant<IV>(iv);
bindingSet.set(var, val);
}
return new IBindingSet[]{ bindingSet };
}
示例25
@Override
public BindingSet next() throws QueryEvaluationException {
if (!open)
throw new QueryEvaluationException("Closed");
final BindingSet bs = src.next();
for (IVariable<?> var : originalVars) {
final Binding binding = bs.getBinding(var.getName());
if (binding == null)
continue;
final BigdataValue boundValue = (BigdataValue) binding.getValue();
if (boundValue != null) {
if(describedResources.add(boundValue)) {
if(log.isInfoEnabled()) {
log.info("Will describe: var=" + var + ",boundValue="
+ boundValue);
}
}
}
}
return bs;
}
示例26
public GlobalSecurityValidator(final RemoteRepositoryManager m_repo) throws Exception {
GraphQueryResult repoDescription = m_repo.getRepositoryDescriptions();
Set<String> namespaces = new HashSet<String>();
while (repoDescription.hasNext()) {
Statement stmt = repoDescription.next();
if (stmt.getPredicate()
.toString()
.equals(SD.KB_NAMESPACE.stringValue())) {
namespaces.add(stmt.getObject().stringValue());
}
}
TupleQueryResult result;
for (String namespace : namespaces) {
try {
RemoteRepository repo = m_repo.getRepositoryForNamespace(namespace);
result = repo.prepareTupleQuery(GRANTED_DOCUMENTS).evaluate();
while(result.hasNext()){
BindingSet bs = result.next();
Binding user = bs.getBinding("user");
Binding document = bs.getBinding("doc");
if(securityInfo.containsKey(user)){
securityInfo.get(user).add(document.getValue());
}else{
List<Value> docs = new LinkedList<Value>();
docs.add(document.getValue());
securityInfo.put(user.getValue(), docs);
}
}
} catch (Exception e) {
log.error("Security info was not collected", e);
}
}
}
示例27
/**
* Aligns a bigdata {@link IBindingSet} with the Sesame 2 {@link BindingSet}.
*
* @param src
* A bigdata {@link IBindingSet} containing only
* {@link BigdataValue}s.
*
* @return The corresponding Sesame 2 {@link BindingSet}.
*
* @throws IllegalArgumentException
* if the argument is <code>null</code>.
* @throws ClassCastException
* if a bound value is not a {@link BigdataValue}.
*/
@SuppressWarnings("rawtypes")
private BindingSet getBindingSet(final IBindingSet src) {
if (src == null)
throw new IllegalArgumentException();
final int n = src.size();
final MapBindingSet bindingSet = new MapBindingSet(n /* capacity */);
final Iterator<Map.Entry<IVariable,IConstant>> itr = src.iterator();
while (itr.hasNext()) {
final Map.Entry<IVariable, IConstant> entry = itr.next();
final IVariable<?> v = entry.getKey();
final IConstant<?> c = entry.getValue();
final Object val = c.get();
final BigdataValue value;
if (val instanceof IV) {
/*
* The bound value is an IV. The IV MUST have the BigdataValue
* cached.
*/
value = ((IV) val).getValue();
} else {
// Otherwise the bound value must be a BigdataValue.
value = (BigdataValue) val;
}
bindingSet.addBinding(v.getName(), value);
}
if (constants != null) {
final Iterator<Binding> it = constants.iterator();
while (it.hasNext()) {
final Binding b = it.next();
bindingSet.addBinding(b.getName(), b.getValue());
}
}
return bindingSet;
}
示例28
/**
* Convert an openrdf {@link BindingSet} into a bigdata {@link IBindingSet}.
* The {@link BindingSet} MUST contain {@link BigdataValue}s and the
* {@link IV}s for those {@link BigdataValue}s MUST have been resolved
* against the database and the {@link IVCache} association set.
*
* @param vars
* The variables to be projected (optional). When given, only the
* projected variables are in the returned {@link IBindingSet}.
* @param in
* The openrdf {@link BindingSet}
*
* @return The bigdata {@link IBindingSet}.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
static private IBindingSet openrdf2Bigdata(//
final Set<IVariable<?>> vars,//
final BindingSet in//
) {
final IBindingSet out = new ListBindingSet();
final Iterator<Binding> itr = in.iterator();
while(itr.hasNext()) {
final Binding e = itr.next();
final String name = e.getName();
final IVariable<?> var = Var.var(name);
if (vars != null && !vars.contains(var)) {
// This variable is not being projected.
continue;
}
// Note: MUST already be BigdataValues.
final BigdataValue value = (BigdataValue) e.getValue();
// Note: IVs MUST already be resolved.
final IV<?,?> iv = value.getIV();
if(iv == null)
throw new AssertionError();
// IV must have cached Value.
if (!iv.hasValue())
throw new AssertionError();
// The cached Value must be the Value (objects point at each other)
if(iv.getValue() != value)
throw new AssertionError();
out.set(var, new Constant(iv));
}
return out;
}