Java Code Examples for org.openrdf.query.QueryEvaluationException

The following examples show how to use org.openrdf.query.QueryEvaluationException. 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
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 2
Source Project: cumulusrdf   Source File: CumulusRDFSailConnection.java    License: 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 3
Source Project: anno4j   Source File: ValidatedTransaction.java    License: 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 Project: anno4j   Source File: BuildableRDFSClazzSupport.java    License: 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 Project: database   Source File: SPARQLUpdateTestv2.java    License: 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 6
Source Project: anno4j   Source File: OWLJavaFileGenerator.java    License: 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 7
Source Project: database   Source File: TestTicket348.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 8
Source Project: cumulusrdf   Source File: CumulusRDFSailConnection.java    License: 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 9
Source Project: anno4j   Source File: LowestCommonSuperclass.java    License: 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 10
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 11
Source Project: database   Source File: RDFStoreTest.java    License: 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 12
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 13
Source Project: anno4j   Source File: CachedPropertySet.java    License: 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 14
Source Project: anno4j   Source File: PathTest.java    License: 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 15
Source Project: anno4j   Source File: ObjectCursor.java    License: Apache License 2.0 5 votes vote down vote up
public ObjectCursor(ObjectConnection manager, CloseableIteration<BindingSet, QueryEvaluationException> result,
		String binding) throws QueryEvaluationException {
	this.binding = binding;
	this.result = result;
	this.next = result.hasNext() ? result.next() : null;
	this.manager = manager;
	this.of = manager.getObjectFactory();
}
 
Example 16
Source Project: trainbenchmark   Source File: SesameDriver.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected boolean ask(final String askQuery)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	final BooleanQuery q = connection.prepareBooleanQuery(QueryLanguage.SPARQL, askQuery);
	final boolean result = q.evaluate();
	return result;
}
 
Example 17
Source Project: anno4j   Source File: Transaction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc }
 */
@Override
public <T extends ResourceObject> T findByID(Class<T> type, String id) throws RepositoryException {
    try {
        return this.getConnection().findObject(type, new URIImpl(id));
    } catch (QueryEvaluationException e) {
        throw new RepositoryException("Couldn't evaluate query", e);
    }
}
 
Example 18
Source Project: anno4j   Source File: AnnotationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAudiences() throws RepositoryException, IllegalAccessException, InstantiationException, ParseException, MalformedQueryException, QueryEvaluationException {
    Annotation annotation = this.anno4j.createObject(Annotation.class);

    Annotation result = anno4j.findByID(Annotation.class, annotation.getResourceAsString());

    assertEquals(0, result.getAudiences().size());

    TestAudience audience = this.anno4j.createObject(TestAudience.class);
    annotation.addAudience(audience);

    QueryService qs = this.anno4j.createQueryService();
    qs.addPrefix("schema", "https://schema.org/");
    qs.addCriteria("schema:audience[is-a schema:TestAudience]");

    List<Annotation> results = qs.execute(Annotation.class);
    result = results.get(0);

    assertEquals(1, result.getAudiences().size());

    HashSet<Audience> audiences = new HashSet<>();
    audiences.add(this.anno4j.createObject(TestAudience.class));
    audiences.add(this.anno4j.createObject(TestAudience.class));
    annotation.setAudiences(audiences);

    result = anno4j.findByID(Annotation.class, annotation.getResourceAsString());

    assertEquals(2, result.getAudiences().size());
}
 
Example 19
Source Project: database   Source File: TestTicket1889_2.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Prepares data containing blank nodes, loads it into triplestore,
 * then run an update, which creates additional statements with blank nodes
 * resulting number of statements loaded should be 2*n.
 * Total number of blank nodes will be n+k.
 * @param repo Repository to load data
 * @param n Number of statements to be loaded
 * @param k Number of subjects to be loaded
 */
@Override
protected void executeQuery(final BigdataSailRepository repo, final int n, final int k)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, IOException, UpdateExecutionException {
	final BigdataSailRepositoryConnection conn = repo.getConnection();
	conn.setAutoCommit(false);
	conn.clear();
	try {
		StringBuilder data = new StringBuilder();
		for (int i = 0; i < n; i++) {
			data.append("_:s").append(i%k).append(" <http://p> _:o").append(i).append(" <http://c> .\n");
		}
		conn.add(new ByteArrayInputStream(data.toString().getBytes()), "",
				RDFFormat.NQUADS);
		conn.commit();
		
		final String query = "prefix h: <http://>\r\n" + 
				"\r\n" + 
				"INSERT { \r\n" + 
				"    ?s h:p1 ?o .\r\n" + 
				"}\r\n" + 
				"WHERE {\r\n" + 
				"  ?s h:p ?o .\r\n" + 
				"}";
		final Update q = conn.prepareUpdate(QueryLanguage.SPARQL, query);
		q.execute();
		assertEquals(n * 2 + 4 /*4 inferred statements about predicates*/, conn.getTripleStore().getStatementCount(true));
	} finally {
		conn.close();
	}
}
 
Example 20
@Override
public TupleQueryResult evaluate() throws QueryEvaluationException {
	try {
		configureConnectOptions(q);
		return q.evaluate();
	} catch (Exception ex) {
		throw new QueryEvaluationException(ex);
	}
}
 
Example 21
Source Project: anno4j   Source File: ValidatedTransaction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether every <code>owl:InverseFunctionalProperty</code> which maps to a value from any of the given resources
 * in <code>anchors</code> is actually functional.
 * @param anchors A set of resources which properties will be checked.
 * @throws RepositoryException Thrown if an error occurs querying the connected triplestore.
 * @throws ValidationFailedException Thrown if any of the checked properties violates the above condition.
 */
private void validateInverseFunctional(Collection<ResourceObject> anchors) throws RepositoryException, ValidationFailedException {
    // Query for subjects that are not in a owl:sameAs relation:
    String q = QUERY_PREFIX + "SELECT ?prop ?o ?v ?i " +
            "{ " +
            buildValuesClause(anchors, "i") +
            "?i ?prop ?v . " +
            "?o ?prop ?v . " +
            "?prop a owl:InverseFunctionalProperty . " +
            "FILTER( ?i != ?o ) " +
            "MINUS { " +
            "        { ?i owl:sameAs+ ?o } UNION { ?o owl:sameAs+ ?i }" +
            "   } " +
            "} LIMIT 1";

    try {
        ObjectQuery query = getConnection().prepareObjectQuery(q);
        Set<?> result = query.evaluate().asSet();

        if(result.size() > 0) {
            Object[] row = (Object[]) result.iterator().next();
            String propertyIri = row[0].toString();
            String secondPreImage = row[1].toString();
            String objectIri = row[3].toString();


            throw new ValidationFailedException("Inverse functional property " + propertyIri
                    + " has multiple distinct pre-images (" + objectIri + ", " + secondPreImage
                    + ") for image " + row[2].toString(),
                    this);
        }

    } catch (QueryEvaluationException | MalformedQueryException e) {
        throw new RepositoryException(e);
    }
}
 
Example 22
Source Project: anno4j   Source File: ValidatedTransaction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether every <code>owl:SymmetricProperty</code> which maps to a value from any of the given resources
 * in <code>anchors</code> is actually symmetric.
 * @param anchors A set of resources which properties will be checked.
 * @throws RepositoryException Thrown if an error occurs querying the connected triplestore.
 * @throws ValidationFailedException Thrown if any of the checked properties violates the above condition.
 */
private void validateSymmetric(Collection<ResourceObject> anchors) throws RepositoryException, ValidationFailedException {
    // Query for mappings where the inverse side is missing:
    String q = QUERY_PREFIX + "SELECT ?p ?o ?i " +
            "{" +
            buildValuesClause(anchors, "i") +
            "   ?i ?p ?o ." +
            "   ?p a owl:SymmetricProperty ." +

            "   MINUS {" +
            "      ?o ?p ?i . " +
            "   }" +

            "} LIMIT 1";

    Set<?> result;
    try {
        ObjectQuery query = getConnection().prepareObjectQuery(q);
        result = query.evaluate().asSet();
    } catch (MalformedQueryException | RepositoryException | QueryEvaluationException e) {
        throw new RepositoryException(e);
    }

    if(result.size() > 0) {
        Object[] row = (Object[]) result.iterator().next();
        String propertyIri = row[0].toString();
        String asymmetricTargetIri = row[1].toString();
        String objectIri = row[2].toString();

        throw new ValidationFailedException("Symmetric property " + propertyIri + " maps " + objectIri +
                " to " + asymmetricTargetIri + ", but does not map inversely.",
                this);
    }

}
 
Example 23
Source Project: database   Source File: TestTicket275.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void executeQuery(final SailRepository repo)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, IOException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		conn.setAutoCommit(false);
		try {
			conn.add(getClass().getResourceAsStream("TestTicket275.ttl"), "",
					RDFFormat.TURTLE);
			conn.commit();

			final String query = "SELECT ?lookup WHERE { ?lookup <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <os:class/Lookup> . ?lookup <os:prop/lookup/majorType> ?majorType . OPTIONAL{?lookup <os:prop/lookup/minorType> ?minorType}. FILTER(STR(?majorType) = ?argMajorType). FILTER(!bound(?minorType))}";
			final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL,
					query);
			q.setBinding("argMajorType", conn.getValueFactory()
					.createLiteral("majoor"));
			final TupleQueryResult tqr = q.evaluate();
			while (tqr.hasNext()) {
			    final Set<String> bindingNames = tqr.next().getBindingNames();
			    if(log.isInfoEnabled())
			        log.info("bindingNames="+bindingNames);
			}
			tqr.close();
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 24
@Test
public void testSES1991UUIDEvaluation()
	throws Exception
{
	loadTestData("/testdata-query/defaultgraph.ttl");
	String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(UUID() as ?uid) } LIMIT 2";

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

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

		URI uuid1 = (URI)result.next().getValue("uid");
		URI uuid2 = (URI)result.next().getValue("uid");

		assertNotNull(uuid1);
		assertNotNull(uuid2);
		assertFalse(uuid1.equals(uuid2));

		result.close();
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example 25
Source Project: anno4j   Source File: ValidatedTransaction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether every <code>owl:allValuesFrom</code> restriction imposed on any of the classes of the instances
 * <code>anchors</code> is fulfilled.
 * @param anchors A set of resources which properties will be checked.
 * @throws RepositoryException Thrown if an error occurs querying the connected triplestore.
 * @throws ValidationFailedException Thrown if any of the checked properties violates the above condition.
 */
private void validateAllValuesFrom(Collection<ResourceObject> anchors) throws RepositoryException, ValidationFailedException {
    String q = QUERY_PREFIX + "SELECT ?p ?o ?c ?i " +
            "{" +
            buildValuesClause(anchors, "i") +
            "    ?i a ?t ." +

            "    ?t rdfs:subClassOf+ ?r ." +
            "    ?r a owl:Restriction ." +
            "    ?r owl:onProperty ?p ." +
            "    ?r owl:allValuesFrom ?c ." +

            "    ?i ?p ?o ." +

            "    MINUS { " +
            "        { ?o a ?c . } UNION { ?o a ?d . ?d rdfs:subClassOf+ ?c . }" +
            "    }" +
            "} LIMIT 1";

    Set<?> result;
    try {
        ObjectQuery query = getConnection().prepareObjectQuery(q);
        result = query.evaluate().asSet();

    } catch (MalformedQueryException | RepositoryException | QueryEvaluationException e) {
        throw new RepositoryException(e);
    }

    if(result.size() > 0) {
        Object[] row = (Object[]) result.iterator().next();
        String propertyIri = row[0].toString();
        String valueIri = row[1].toString();
        String targetClassIri = row[2].toString();
        String objectIri = row[3].toString();


        throw new ValidationFailedException("Value " + valueIri + " of " + propertyIri +
                " (from " + objectIri + ") is not of required type " + targetClassIri, this);
    }
}
 
Example 26
Source Project: anno4j   Source File: ResourceObjectTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryYourself() throws RepositoryException, IllegalAccessException, InstantiationException, ParseException, MalformedQueryException, QueryEvaluationException {
    TextualBody body = this.anno4j.createObject(TextualBody.class, (Resource) new URIImpl("http://example.org/resource1"));

    QueryService qs = this.anno4j.createQueryService();
    qs.addCriteria(".", "http://example.org/resource1");

    List<TextualBody> result = qs.execute(TextualBody.class);

    assertEquals(1, result.size());
}
 
Example 27
Source Project: anno4j   Source File: SchemaAnnotationGenerationTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Fetches the annotation specification of a certain type that the code generation would add to the
 * getter method of the generated interface.
 * @param declaringClazzIri The IRI of the class for which the field would be generated.
 * @param propertyIri The IRI of the property that is mapped by the field.
 * @param annotationType The type of the annotation to get.
 * @return Returns the JavaPoet annotation specification of the annotation if there is one of the given type.
 * Otherwise null is returned.
 * @throws RepositoryException Thrown if an error occurs while querying the connected repository.
 */
private AnnotationSpec getBuiltAnnotation(String declaringClazzIri, String propertyIri, Class<?> annotationType) throws RepositoryException {
    ObjectConnection connection = modelBuilder.getConnection();
    BuildableRDFSClazz clazz;
    BuildableRDFSProperty property;
    try {
        clazz = connection.findObject(BuildableRDFSClazz.class, new URIImpl(declaringClazzIri));
        property = connection.findObject(BuildableRDFSProperty.class, new URIImpl(propertyIri));
    } catch (QueryEvaluationException e) {
        throw new RepositoryException(e);
    }

    MethodSpec getter = property.buildGetter(clazz, generationConfig);
    for (AnnotationSpec currentAnnotation : getter.annotations) {
        // Check for container annotations:
        if(currentAnnotation.type.equals(ClassName.get(MinCardinalities.class)) && annotationType.equals(MinCardinality.class)) {
            return currentAnnotation;
        } else if(currentAnnotation.type.equals(ClassName.get(MaxCardinalities.class)) && annotationType.equals(MaxCardinality.class)) {
            return currentAnnotation;
        } else if(currentAnnotation.type.equals(ClassName.get(Cardinalities.class)) && annotationType.equals(Cardinality.class)) {
            return currentAnnotation;
        }

        if(currentAnnotation.type.equals(AnnotationSpec.builder(annotationType).build().type)) {
            return currentAnnotation;
        }
    }
    return null;
}
 
Example 28
Source Project: anno4j   Source File: ObjectConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Loads the list of resources assumed to implement the given concept. The
 * concept must be a named concept and cannot be mapped to rdfs:Resource.
 */
public synchronized <T> Result<T> getObjects(final Class<T> concept,
		Resource... resources) throws RepositoryException,
		QueryEvaluationException {
	try {
		int size = resources.length;
		ObjectQuery query = getObjectQuery(concept, size);
		if (size == 1) {
			query.setBinding(ObjectFactory.VAR_PREFIX, resources[0]);
		} else if (size > 1) {
			for (int i = 0; i < size; i++) {
				query.setBinding(ObjectFactory.VAR_PREFIX + i, resources[i]);
			}
		}
		final List<Resource> list = new ArrayList<Resource>(size);
		list.addAll(Arrays.asList(resources));
		CloseableIteration<T, QueryEvaluationException> iter;
		final Result<T> result = query.evaluate(concept);
		iter = new LookAheadIteration<T, QueryEvaluationException>() {
			@Override
			protected T getNextElement() throws QueryEvaluationException {
				T next = result.next();
				if (next != null) {
					list.remove(((RDFObject) next).getResource());
					return next;
				}
				if (!list.isEmpty())
					return (T) cache(of.createObject(list.remove(0)));
				return null;
			}
		};
		return new ResultImpl<T>(iter);
	} catch (MalformedQueryException e) {
		throw new AssertionError(e);
	}
}
 
Example 29
Source Project: anno4j   Source File: BuildableRDFSClazzSupport.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Set<RDFSClazz> getSubclazzes() throws RepositoryException {
    try {
        ObjectQuery query = getObjectConnection().prepareObjectQuery(
                "SELECT ?sub {" +
                        "   ?sub rdfs:subClassOf <" + getResourceAsString() + "> . " +
                        "   FILTER(?super != <"  + getResourceAsString() + ">)" +
                        "}"
        );
        return query.evaluate(RDFSClazz.class).asSet();
    } catch (MalformedQueryException | QueryEvaluationException e) {
        throw new RepositoryException(e);
    }
}
 
Example 30
Source Project: anno4j   Source File: BuildableRDFSClazzSupport.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasParent(String resource) throws RepositoryException {
    try {
        BooleanQuery query = getObjectConnection().prepareBooleanQuery(QueryLanguage.SPARQL,
                "ASK {" +
                        "   <" + getResourceAsString() + "> rdfs:subClassOf+ <" + resource + "> . " +
                        "}"
        );
        return query.evaluate();
    } catch (MalformedQueryException | QueryEvaluationException e) {
        throw new RepositoryException(e);
    }
}