org.openrdf.query.QueryEvaluationException Java Examples

The following examples show how to use org.openrdf.query.QueryEvaluationException. 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: TestTicket4249.java    From database with 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 #2
Source File: BigdataSailBooleanQuery.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public boolean evaluate(final BindingsClause bc) 
		throws QueryEvaluationException {

    final QueryRoot originalQuery = astContainer.getOriginalAST();

    if (bc != null)
    	originalQuery.setBindingsClause(bc);

    if (getMaxQueryTime() > 0)
        originalQuery.setTimeout(TimeUnit.SECONDS
                .toMillis(getMaxQueryTime()));

    originalQuery.setIncludeInferred(getIncludeInferred());

    final boolean queryResult = ASTEvalHelper.evaluateBooleanQuery(
            getTripleStore(), astContainer, new QueryBindingSet(
                    getBindings()), getDataset());

    return queryResult;
}
 
Example #3
Source File: ValidatedTransaction.java    From anno4j with Apache License 2.0 6 votes vote down vote up
/**
 * Returns how many values of the individuals <code>subjectURI</code> property <code>propertyURI</code>
 * are of a certain type.
 * @param subjectURI The URI of the subject for which the property values will be checked.
 * @param propertyURI The URI of the property which values will be checked.
 * @param valueTypeURI The URI of the class that will be counted across the values.
 * @return Returns the number of values of type <code>valueTypeURI</code> that <code>subjectURI</code> has
 * for the property <code>propertyURI</code>.
 * @throws RepositoryException Thrown if an error occurs regarding the connected triplestore.
 * @throws MalformedQueryException Thrown if the issued query to the triplestore is malformed, e.g. because any argument is not a valid IRI.
 * @throws QueryEvaluationException Thrown if the issued query could not be evaluated.
 */
private int getValuesOfTypeCount(String subjectURI, String propertyURI, String valueTypeURI) throws RepositoryException, MalformedQueryException, QueryEvaluationException {
    ObjectQuery query = getConnection().prepareObjectQuery(QUERY_PREFIX + "SELECT (COUNT(DISTINCT ?o) as ?count) " +
                                                        "{" +
                                                        "   <" + subjectURI + "> <" + propertyURI + "> ?o . " +
                                                        "   { " +
                                                        "      ?o a ?t ." +
                                                        "      ?t rdfs:subClassOf+ <" + valueTypeURI + "> . " +
                                                        "   }" +
                                                        "   UNION " +
                                                        "   {" +
                                                        "      ?o a <" + valueTypeURI + "> . " +
                                                        "   }" +
                                                        "}");
    return  ((BigInteger) query.evaluate().next()).intValue();
}
 
Example #4
Source File: BuildableRDFSClazzSupport.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Override
public Set<RDFSClazz> getDirectSuperclazzes() throws RepositoryException {
    ObjectConnection connection = getObjectConnection();
    try {
        ObjectQuery query = connection.prepareObjectQuery(
                "SELECT ?c {" +
                "  <" + getResourceAsString() + "> rdfs:subClassOf ?c . " +
                "  MINUS {" +
                "     <"+ getResourceAsString() + "> rdfs:subClassOf+ ?c2 . " +
                "     ?c2 rdfs:subClassOf+ ?c . " +
                "     FILTER(?c != ?c2 && <" + getResourceAsString() + "> != ?c2)" +
                "  }" +
                "}"
        );
        return query.evaluate(RDFSClazz.class).asSet();

    } catch (MalformedQueryException | QueryEvaluationException e) {
        throw new RepositoryException(e);
    }
}
 
Example #5
Source File: RDFStoreTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: TestTicket4249.java    From database with 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 #7
Source File: SPARQLUpdateTestv2.java    From database with GNU General Public License v2.0 6 votes vote down vote up
protected long countSolutions(final String query)
        throws QueryEvaluationException, RepositoryException,
        MalformedQueryException {
    TupleQueryResult result = con.prepareTupleQuery(QueryLanguage.SPARQL,
            query).evaluate();
    try {
        long n = 0;
        while (result.hasNext()) {
            final BindingSet bset = result.next();
            n++;
            if (logger.isInfoEnabled())
                logger.info(bset.toString());
        }
        return n;
    } finally {
        result.close();
    }
}
 
Example #8
Source File: CachedPropertySet.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Override
protected synchronized CloseableIteration<?, ?> getObjects() throws RepositoryException,
		QueryEvaluationException {
	if (creator == null || factory == null) {
		return super.getObjects();
	} else if (binding == null) {
		ObjectQuery query = factory.createQuery(creator);
		if (query == null)
			return super.getObjects();
		try {
			query.setBinding("self", getResource());
			return query.evaluate(creator.getPropertyType());
		} finally {
			factory.returnQuery(creator, query);
		}
	} else {
		CloseableIteratorIteration<BindingSet, QueryEvaluationException> result;
		result = new CloseableIteratorIteration<BindingSet, QueryEvaluationException>(
				bindings.iterator());
		return new ObjectCursor(getObjectConnection(), result, binding);
	}
}
 
Example #9
Source File: OWLJavaFileGenerator.java    From anno4j with Apache License 2.0 6 votes vote down vote up
/**
 * Returns buildable named resource objects of RDFS classes that were found during
 * the last call to {@link #build()} which are pairwise distinct,
 * i.e. that are not declared equivalent.
 * @return All pairwise distinct named classes in the repository.
 * @throws RepositoryException Thrown if an error occurs while querying the repository.
 */
private Collection<BuildableRDFSClazz> getDistinctClasses() throws RepositoryException {
    try {
        ObjectConnection connection = anno4j.getObjectRepository().getConnection();
        ObjectQuery query = connection.prepareObjectQuery(
                "SELECT DISTINCT ?c {\n" +
                "   ?c rdfs:subClassOf+ owl:Thing . \n" +
                "   MINUS {\n" +
                "       ?e owl:equivalentClass ?c . \n" +
                "       FILTER(str(?e) < str(?c))\n" + // Impose order on equivalence. Pick only first lexicographical
                "   }\n" +
                "   FILTER( isIRI(?c) )\n" +
                "}"
        );

        return query.evaluate(BuildableRDFSClazz.class).asSet();

    } catch (MalformedQueryException | QueryEvaluationException e) {
        throw new RepositoryException(e);
    }
}
 
Example #10
Source File: TestTicket348.java    From database with 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 #11
Source File: LowestCommonSuperclass.java    From anno4j with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the superclasses of a class including all transitive superclasses and the class
 * itself.
 * @param clazz The class for which to find superclasses.
 * @return The transitive closure of superclasses of the given class including <code>clazz</code>.
 */
private static Set<BuildableRDFSClazz> getSuperclassClosure(BuildableRDFSClazz clazz) throws RepositoryException {
    Set<BuildableRDFSClazz> closure = Sets.newHashSet(clazz);
    ObjectConnection connection = clazz.getObjectConnection();

    try {
        ObjectQuery query = connection.prepareObjectQuery(
                "SELECT ?super {" +
                "   <" + clazz.getResourceAsString() + "> rdfs:subClassOf+ ?super . " +
                "}"
        );
        closure.addAll(query.evaluate(BuildableRDFSClazz.class).asSet());
    } catch (QueryEvaluationException | MalformedQueryException e) {
        throw new RepositoryException(e);
    }

    return closure;
}
 
Example #12
Source File: PathTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testSecondBody() throws RepositoryException, QueryEvaluationException, MalformedQueryException, ParseException {
    List<Annotation> annotations = queryService
            .addCriteria("oa:hasBody/ex:value", "Value2")
            .execute();

    assertEquals(1, annotations.size());

    // Testing against the serialization date
    Annotation annotation = annotations.get(0);
    assertEquals("2015-01-28T12:00:00Z", annotation.getCreated());

    // Testing if the body was persisted correctly
    PathTestBody testBody = (PathTestBody) annotation.getBodies().iterator().next();
    assertEquals("Value2", testBody.getValue());
}
 
Example #13
Source File: CumulusRDFSailConnection.java    From cumulusrdf with Apache License 2.0 6 votes vote down vote up
public CloseableIteration<? extends Statement, QueryEvaluationException> getRangeStatements(
		final Resource subj, 
		final URI pred, 
		final Literal lowerBound,
		final boolean lower_equals, 
		final Literal upperBound, 
		final boolean upper_equals, 
		final Literal equals, 
		final boolean reverse) throws QueryEvaluationException {
	try {
		return createRangeStatementIterator(subj, pred, lowerBound, lower_equals, upperBound, upper_equals, equals, reverse);
	} catch (SailException e) {
		e.printStackTrace();
		throw new QueryEvaluationException(e);
	}
}
 
Example #14
Source File: CumulusRDFSailConnection.java    From cumulusrdf with Apache License 2.0 6 votes vote down vote up
@Override
public CloseableIteration<? extends Statement, QueryEvaluationException> getStatements(
		final Resource subj,
		final URI pred,
		final Value obj,
		final Resource... contexts) throws QueryEvaluationException {
	try {
		if (contexts != null && contexts.length > 0) {
			@SuppressWarnings("unchecked")
			final CloseableIteration<Statement, QueryEvaluationException>[] iterations = new CloseableIteration[contexts.length];
			
			for (int i = 0; i < contexts.length; i++) {
				iterations[i] = newStatementIterator(subj, pred, obj, contexts[i]);
			}

			return new CloseableMultiIterator<Statement, QueryEvaluationException>(iterations);
		} else {
			return newStatementIterator(subj, pred, obj, contexts);
		}
	} catch (final SailException exception) {
		LOGGER.error(MessageCatalog._00025_CUMULUS_SYSTEM_INTERNAL_FAILURE, exception);
		throw new QueryEvaluationException(exception);
	}
}
 
Example #15
Source File: ObjectQuery.java    From anno4j with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates the query returning a result of Object[].
 */
public Result<Object[]> evaluate(Class<?>... concepts)
		throws QueryEvaluationException {
	TupleQueryResult tuple = query.evaluate();
	List<String> bindings = tuple.getBindingNames();
	bindings = bindings.subList(0, concepts.length);
	return new ResultImpl(new ObjectArrayCursor(manager, tuple, bindings));
}
 
Example #16
Source File: PathTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Test
public void falseTest() throws RepositoryException, QueryEvaluationException, MalformedQueryException, ParseException {
    List<Annotation> annotations = queryService
            .addCriteria("oa:hasBody/ex:value", "Value3")
            .execute();

    assertEquals(0, annotations.size());
}
 
Example #17
Source File: DataTypeTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Test
/**
 *  Querying for all annotations, that has bodies with a xsd:double values < 4.0 set.
 */
public void doubleLtTest() throws RepositoryException, QueryEvaluationException, MalformedQueryException, ParseException {
    List<Annotation> list = queryService
            .addPrefix("ex", "http://www.example.com/schema#")
            .addCriteria("oa:hasBody/ex:doubleValue[^^xsd:double]", 4.0, Comparison.LT)
            .execute();

    assertEquals(1, list.size());
    assertEquals(new Double(2.0), ((DataTypeBody) list.get(0).getBodies().iterator().next()).getDoubleValue());
}
 
Example #18
Source File: DataTypeTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Test
/**
 * Querying for all annotations, that has bodies with xsd:double values set, using eq comparison.
 */
public void doubleEqualTest() throws RepositoryException, QueryEvaluationException, MalformedQueryException, ParseException {
    List<Annotation> list = queryService
            .addPrefix("ex", "http://www.example.com/schema#")
            .addCriteria("oa:hasBody/ex:doubleValue[^^xsd:double]")
            .execute();

    assertEquals(1, list.size());
    assertEquals(new Double(2.0), ((DataTypeBody) list.get(0).getBodies().iterator().next()).getDoubleValue());
}
 
Example #19
Source File: WebTestUtils.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.openrdf.query.QueryResultUtil
 */
public static boolean matchTupleQueryResults(TupleQueryResult res1, TupleQueryResult res2) throws QueryEvaluationException {

	List<BindingSet> queryResult1 = Iterations.asList(res1);
	List<BindingSet> queryResult2 = Iterations.asList(res2);

	if (queryResult1.size() != queryResult2.size()) {
		return false;
	}

	for (BindingSet bs1 : queryResult1) {

		boolean hit = false;

		for (BindingSet bs2 : queryResult2) {

			if (bindingSetsMatch(bs1, bs2)) {
				hit = true;
				break;
			}
		}

		if (!hit) {
			return false;
		}
	}

	return true;
}
 
Example #20
Source File: DataTypeTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Test
/**
 *  Querying for all annotations, that has bodies with xsd:double values > 4.0 set. This should not return any result
 *  because no such object was persisted before.
 */
public void falseGtTest() throws RepositoryException, QueryEvaluationException, MalformedQueryException, ParseException {
    List<Annotation> list = queryService
            .addPrefix("ex", "http://www.example.com/schema#")
            .addCriteria("oa:hasBody/ex:doubleValue[^^xsd:double]", 4.0, Comparison.GT)
            .execute();

    assertEquals(0, list.size());
}
 
Example #21
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testSES1898LeftJoinSemantics2()
	throws Exception
{
	loadTestData("/testdata-query/dataset-ses1898.trig");
	StringBuilder query = new StringBuilder();
	query.append("  PREFIX : <http://example.org/> ");
	query.append("  SELECT * WHERE { ");
	query.append("    ?s :p1 ?v1 . ");
	query.append("    ?s :p3 ?v2 . ");
	query.append("    OPTIONAL {?s :p2 ?v2 } .");
	query.append("  } ");

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString());

	try {
		TupleQueryResult result = tq.evaluate();
		assertNotNull(result);

		int count = 0;
		while (result.hasNext()) {
			result.next();
			count++;
		}
		assertEquals(1, count);
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example #22
Source File: PathEqualityTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Test
public void inequalityTest() throws RepositoryException, QueryEvaluationException, MalformedQueryException, ParseException, RepositoryConfigException, IllegalAccessException, InstantiationException {
    List<Annotation> list = queryService.addCriteria("oa:hasBody[!ex:pathEqualityTestFirstValue is \"First Value\"]").execute();
    assertEquals(1, list.size());

    FirstPathEqualityTestBody firstPathEqualityTestBody = (FirstPathEqualityTestBody) list.get(0).getBodies().iterator().next();
    assertEquals("Second Value", firstPathEqualityTestBody.getValue());
}
 
Example #23
Source File: ReversePathTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testFirstBody() throws RepositoryException, QueryEvaluationException, MalformedQueryException, ParseException {
    List<Annotation> annotations = queryService
            .addCriteria("oa:hasBody[is-a ex:inverseBody]/^oa:hasBody/dcterms:issued", "2015-01-28T12:00:00Z")
            .execute();

    assertEquals(1, annotations.size());

    Annotation annotation = annotations.get(0);
    assertEquals("2015-01-28T12:00:00Z", annotation.getGenerated());

    // Testing if the body was persisted correctly
    InverseBody testBody = (InverseBody) annotation.getBodies().iterator().next();
    assertEquals("Some Testing Value", testBody.getValue());
}
 
Example #24
Source File: ComparisonTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Test
/**
 * Querying for all annotations, that has bodies where the string value matches exact a certain value.
 */
public void exactMatchTest() throws RepositoryException, QueryEvaluationException, MalformedQueryException, ParseException {
    List<Annotation> list = queryService
            .addPrefix("ex", "http://www.example.com/schema#")
            .addCriteria("oa:hasBody/ex:comparisonBodyStringValue", "Test", Comparison.EQ)
            .execute();

    assertEquals(1, list.size());
}
 
Example #25
Source File: ComparisonTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Test
/**
 * Querying for all annotations, that has bodies where the string value contains a certain value.
 */
public void containsTest() throws RepositoryException, QueryEvaluationException, MalformedQueryException, ParseException {
    List<Annotation> list = queryService
            .addPrefix("ex", "http://www.example.com/schema#")
            .addCriteria("oa:hasBody/ex:comparisonBodyStringValue", "Test", Comparison.CONTAINS)
            .execute();

    assertEquals(3, list.size());
}
 
Example #26
Source File: ClazzBuildingSupport.java    From anno4j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the given resource in {@link BuildableRDFSProperty} type.
 * @param property The property resource which should be converted.
 * @return The property in the {@link BuildableRDFSProperty} type or null if there is no such property
 * in the repository.
 * @throws RepositoryException Thrown if an error occurs while querying the repository.
 */
BuildableRDFSProperty asBuildableProperty(RDFSProperty property) throws RepositoryException {
    try {
        return getObjectConnection().findObject(BuildableRDFSProperty.class, property.getResource());
    } catch (QueryEvaluationException e) {
        throw new RepositoryException(e);
    }
}
 
Example #27
Source File: RDFSContainer.java    From anno4j with Apache License 2.0 5 votes vote down vote up
private Object[] loadBlock(int b) throws RepositoryException, QueryEvaluationException {
	TupleQuery query = createBlockQuery(b);
	TupleQueryResult result = query.evaluate();
	BindingSet bindings = result.next();
	ObjectConnection con = getObjectConnection();
	Object[] list = new Object[BSIZE];
	while (bindings != null) {
		URI pred = (URI) bindings.getValue("pred");
		int idx = getIndex(pred);
		Value value = bindings.getValue("value");
		Set<URI> types = new HashSet<URI>(4);
		do {
			Value c = bindings.getValue("value_class");
			if (c instanceof URI) {
				types.add((URI) c);
			}
			bindings = result.hasNext() ? result.next() : null;
		} while (bindings != null && pred.equals(bindings.getValue("pred")));
		int i = idx % BSIZE;
		if (value instanceof Literal) {
			list[i] = con.getObject((Literal) value);
		} else {
			list[i] = con.getObject(types, (Resource) value);
		}
	}
	return list;
}
 
Example #28
Source File: GraphIterator.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void remove() {
	try {
		this.iterator.remove();
	}
	catch (QueryEvaluationException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example #29
Source File: OWLSchemaPersistingManager.java    From anno4j with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to find the class resource and returns it.
 * If no class with such an IRI exists then a new one is created and returned.
 * @param clazzIri The IRI of the class to retrieve.
 * @return Returns the {@link OWLClazz} object for the given IRI.
 * @throws RepositoryException Thrown if an error occurs while retrieving/creating the class object.
 */
private OWLClazz createClazzOnDemand(String clazzIri) throws RepositoryException {
    try {
        OWLClazz clazz = getConnection().findObject(OWLClazz.class, new URIImpl(clazzIri));

        if(clazz == null) {
            return createObject(OWLClazz.class, new URIImpl(clazzIri));
        } else {
            return clazz;
        }

    } catch (QueryEvaluationException e) {
        throw new RepositoryException(e);
    }
}
 
Example #30
Source File: BackgroundGraphResult.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void close() throws QueryEvaluationException {
   closed = true;
   interruptParserThread();
   try {
      queue.close();
      in.close(); // close the input stream.
   } catch (IOException e) {
      throw new QueryEvaluationException(e);
   }
}