org.eclipse.rdf4j.query.MalformedQueryException Java Examples

The following examples show how to use org.eclipse.rdf4j.query.MalformedQueryException. 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: AbstractSearchIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Iterable<? extends DocumentResult> evaluateQuery(GeoRelationQuerySpec query) {
	Iterable<? extends DocumentResult> hits = null;

	Literal qgeom = query.getQueryGeometry();
	IRI geoProperty = query.getGeoProperty();
	try {
		if (!GEO.WKT_LITERAL.equals(qgeom.getDatatype())) {
			throw new MalformedQueryException("Unsupported datatype: " + qgeom.getDatatype());
		}
		Shape qshape = parseQueryShape(SearchFields.getPropertyField(geoProperty), qgeom.getLabel());
		hits = geoRelationQuery(query.getRelation(), geoProperty, qshape, query.getContextVar());
	} catch (Exception e) {
		logger.error("There was a problem evaluating spatial relation query '" + query.getRelation() + " "
				+ qgeom.getLabel() + "'!", e);
	}

	return hits;
}
 
Example #2
Source File: ConstructProjectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructProjectionBNodes() throws MalformedQueryException {
    String query = "select ?o where { _:b <uri:talksTo> ?o }";
    
    SPARQLParser parser = new SPARQLParser();
    ParsedQuery pq = parser.parseQuery(query, null);
    List<StatementPattern> patterns = StatementPatternCollector.process(pq.getTupleExpr());
    ConstructProjection projection = new ConstructProjection(patterns.get(0));
    
    QueryBindingSet bs = new QueryBindingSet();
    bs.addBinding("o", VF.createIRI("uri:Bob"));
    VisibilityBindingSet vBs = new VisibilityBindingSet(bs);
    BNode bNode = VF.createBNode();
    Map<String, BNode> bNodeMap = new HashMap<>();
    bNodeMap.put(VarNameUtils.prependAnonymous("1"), bNode);
    RyaStatement statement = projection.projectBindingSet(vBs,bNodeMap);
    
    RyaStatement expected = new RyaStatement(RdfToRyaConversions.convertResource(bNode), new RyaIRI("uri:talksTo"), new RyaIRI("uri:Bob"));
    expected.setTimestamp(statement.getTimestamp());
    expected.setColumnVisibility(new byte[0]);
    
    assertEquals(expected, statement);
}
 
Example #3
Source File: MongoGeoIndexerFilterIT.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test(expected = MalformedQueryException.class)
public void near_invalidDistance() throws Exception {
    final Sail sail = GeoRyaSailFactory.getInstance(conf);
    final SailRepositoryConnection conn = new SailRepository(sail).getConnection();
    try {
        populateRya(conn);

        //Only captial
        final String query =
                "PREFIX geo: <http://www.opengis.net/ont/geosparql#>\n"
                        + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/>\n"
                        + "SELECT * \n" //
                        + "WHERE { \n"
                        + "  <urn:geo> geo:asWKT ?point .\n"
                        + "  FILTER(geof:sfNear(?point, \"POINT(38.8895 77.0353)\"^^geo:wktLiteral, distance))"
                        + "}";

        conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate();
    } finally {
        conn.close();
        sail.shutDown();
    }
}
 
Example #4
Source File: ConstructProjectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructProjectionProjectSubj() throws MalformedQueryException, UnsupportedEncodingException {
    String query = "select ?x where { ?x <uri:talksTo> <uri:Bob> }";
    
    SPARQLParser parser = new SPARQLParser();
    ParsedQuery pq = parser.parseQuery(query, null);
    List<StatementPattern> patterns = StatementPatternCollector.process(pq.getTupleExpr());
    ConstructProjection projection = new ConstructProjection(patterns.get(0));
    
    QueryBindingSet bs = new QueryBindingSet();
    bs.addBinding("x", VF.createIRI("uri:Joe"));
    VisibilityBindingSet vBs = new VisibilityBindingSet(bs, "FOUO");
    RyaStatement statement = projection.projectBindingSet(vBs, new HashMap<>());
    
    RyaStatement expected = new RyaStatement(new RyaIRI("uri:Joe"), new RyaIRI("uri:talksTo"), new RyaIRI("uri:Bob"));
    expected.setColumnVisibility("FOUO".getBytes("UTF-8"));
    expected.setTimestamp(statement.getTimestamp());
    
    assertEquals(expected, statement);
}
 
Example #5
Source File: StatementMetadataExternalSetProviderTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void createSingleMongoMetadataNode() throws MalformedQueryException {

    MongoDBRdfConfiguration conf = (MongoDBRdfConfiguration) getConf(true);
    Set<RyaIRI> propertySet = new HashSet<>();
    propertySet.add(new RyaIRI("http://createdBy"));
    conf.setStatementMetadataProperties(propertySet);
    StatementMetadataExternalSetProvider metaProvider = new StatementMetadataExternalSetProvider(conf);
    SPARQLParser parser = new SPARQLParser();
    ParsedQuery pq = parser.parseQuery(query, null);

    List<QueryModelNode> patterns = new ArrayList<>();
    List<StatementMetadataNode<?>> expected = new ArrayList<>();
    Set<StatementPattern> sp = StatementMetadataTestUtils.getMetadataStatementPatterns(pq.getTupleExpr(), propertySet);

    patterns.addAll(StatementPatternCollector.process(pq.getTupleExpr()));
    JoinSegment<StatementMetadataNode<?>> segment = new JoinSegment<>(
            new HashSet<>(patterns), patterns, new HashMap<ValueExpr, Filter>());
    List<StatementMetadataNode<?>> extSets = metaProvider.getExternalSets(segment);

    expected.add(new StatementMetadataNode<>(sp,conf));

    Assert.assertEquals(expected, extSets);

}
 
Example #6
Source File: QueryInvestigator.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Determines whether a SPARQL command is an INSERT with a WHERE clause or not.
 *
 * @param sparql - The SPARQL to evaluate. (not null)
 * @return {@code true} if the provided SPARQL is an INSERT update; otherwise {@code false}.
 * @throws MalformedQueryException The SPARQL is neither a well formed query or update.
 */
public static boolean isInsertWhere(final String sparql) throws MalformedQueryException {
    requireNonNull(sparql);

    try {
        // Inserts are updated, so try to create a ParsedUpdate.
        PARSER.parseUpdate(sparql, null);

        // Check to see if the SPARQL looks like an INSERT query.
        return Pattern.matches("[\\s\\S]*?insert\\s*?\\{[\\s\\S]*?\\}[\\s\\S]*?where\\s*\\{[\\s\\S]*?\\}", sparql.toLowerCase());
    } catch(final MalformedQueryException updateE) {
        try {
            // Maybe it's a query.
            PARSER.parseQuery(sparql, null);

            // It was, so return false.
            return false;

        } catch(final MalformedQueryException queryE) {
            // It's not. Actually malformed.
            throw updateE;
        }
    }
}
 
Example #7
Source File: AbstractLuceneSailTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testUnionQuery() throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	String queryStr = "";
	queryStr += "PREFIX search: <http://www.openrdf.org/contrib/lucenesail#> ";
	queryStr += "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> ";
	queryStr += "SELECT DISTINCT ?result { ";
	queryStr += "{ ?result search:matches ?match1 . ";
	queryStr += "  ?match1 search:query 'one' ; ";
	queryStr += "          search:property <urn:predicate1> . }";
	queryStr += " UNION ";
	queryStr += "{ ?result search:matches ?match2 . ";
	queryStr += "  ?match2 search:query 'one' ; ";
	queryStr += "          search:property <urn:predicate2> . } ";
	queryStr += "} ";

	try (RepositoryConnection connection = repository.getConnection()) {
		// fire a query with the subject pre-specified
		TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
		query.setBinding("result", SUBJECT_1);
		try (TupleQueryResult result = query.evaluate()) {
			// check that this subject and only this subject is returned
			BindingSet bs = result.next();
			assertEquals(SUBJECT_1, bs.getValue("result"));
		}
	}
}
 
Example #8
Source File: MongoPcjQueryNode.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link MongoPcjQueryNode}.
 *
 * @param sparql - sparql query whose results will be stored in PCJ document. (not empty of null)
 * @param pcjId - name of an existing PCJ. (not empty or null)
 * @param pcjDocs - {@link MongoPcjDocuments} used to maintain PCJs in mongo. (not null)
 *
 * @throws MalformedQueryException - The SPARQL query needs to contain a projection.
 */
public MongoPcjQueryNode(final String sparql, final String pcjId, final MongoPcjDocuments pcjDocs) throws MalformedQueryException {
    checkArgument(!Strings.isNullOrEmpty(sparql));
    checkArgument(!Strings.isNullOrEmpty(pcjId));
    this.pcjDocs = checkNotNull(pcjDocs);
    this.pcjId = pcjId;
    final SPARQLParser sp = new SPARQLParser();
    final ParsedTupleQuery pq = (ParsedTupleQuery) sp.parseQuery(sparql, null);
    final TupleExpr te = pq.getTupleExpr();
    Preconditions.checkArgument(PCJOptimizerUtilities.isPCJValid(te), "TupleExpr is an invalid PCJ.");

    final Optional<Projection> projection = new ParsedQueryUtil().findProjection(pq);
    if (!projection.isPresent()) {
        throw new MalformedQueryException("SPARQL query '" + sparql + "' does not contain a Projection.");
    }
    setProjectionExpr(projection.get());
}
 
Example #9
Source File: RdfController.java    From rya with Apache License 2.0 6 votes vote down vote up
private void performUpdate(final String query, final SailRepositoryConnection conn, final ServletOutputStream os, final String infer, final String vis) throws RepositoryException, MalformedQueryException, IOException {
    final Update update = conn.prepareUpdate(QueryLanguage.SPARQL, query);
    if (infer != null && infer.length() > 0) {
        update.setBinding(RdfCloudTripleStoreConfiguration.CONF_INFER, VALUE_FACTORY.createLiteral(Boolean.parseBoolean(infer)));
    }

    if (conn.getSailConnection() instanceof RdfCloudTripleStoreConnection && vis != null) {
        final RdfCloudTripleStoreConnection<?> sailConnection = (RdfCloudTripleStoreConnection<?>) conn.getSailConnection();
        sailConnection.getConf().set(RdfCloudTripleStoreConfiguration.CONF_CV, vis);
    }

    final long startTime = System.currentTimeMillis();

    try {
        update.execute();
    } catch (final UpdateExecutionException e) {
        final String message = "Update could not be successfully completed for query: ";
        os.print(String.format(message + "%s\n\n", StringEscapeUtils.escapeHtml4(query)));
        log.error(message + LogUtils.clean(query), e);
    }

    log.info(String.format("Update Time = %.3f\n", (System.currentTimeMillis() - startTime) / 1000.));
}
 
Example #10
Source File: SparqlTripleSource.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public CloseableIteration<Statement, QueryEvaluationException> getStatements(
		Resource subj, IRI pred, Value obj, QueryInfo queryInfo,
		Resource... contexts) throws RepositoryException,
		MalformedQueryException, QueryEvaluationException {

	return withConnection((conn, resultHolder) -> {
		monitorRemoteRequest();
		RepositoryResult<Statement> repoResult = conn.getStatements(subj, pred, obj,
				queryInfo.getIncludeInferred(), contexts);

		resultHolder.set(new ExceptionConvertingIteration<Statement, QueryEvaluationException>(repoResult) {
			@Override
			protected QueryEvaluationException convert(Exception ex) {
				if (ex instanceof QueryEvaluationException) {
					return (QueryEvaluationException) ex;
				}
				return new QueryEvaluationException(ex);
			}
		});
	});
}
 
Example #11
Source File: SolrSailExample.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static void tupleQuery(String queryString, RepositoryConnection connection)
		throws QueryEvaluationException, RepositoryException, MalformedQueryException {
	System.out.println("Running query: \n" + queryString);
	TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
	try (TupleQueryResult result = query.evaluate()) {
		// print the results
		System.out.println("Query results:");
		while (result.hasNext()) {
			BindingSet bindings = result.next();
			System.out.println("found match: ");
			for (Binding binding : bindings) {
				System.out.println("\t" + binding.getName() + ": " + binding.getValue());
			}
		}
	}
}
 
Example #12
Source File: SourceRanking.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
public static List<StatementSource> getRankedSources(Summary summary, String queryString, int k) throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	List<StatementSource> rankedSources = new ArrayList<StatementSource>();
	TupleQuery tupleQuery = summary.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, queryString);
	//System.out.println(queryString);
	TupleQueryResult result = tupleQuery.evaluate();
	int count = 0 ;
	while(result.hasNext() && count <k)
	{
		String endpoint = result.next().getValue("url").stringValue();
		String id = "sparql_" + endpoint.replace("http://", "").replace("/", "_");
		StatementSource src =  new StatementSource(id, StatementSourceType.REMOTE);
		rankedSources.add(src);
		count++;
	}

	return rankedSources;
}
 
Example #13
Source File: StatsGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String getFscores(String queryNo,TupleQueryResult res) throws QueryEvaluationException, RepositoryException, MalformedQueryException 
{
	
	String Fscores = "" ;
	double precision, recall,F1;
	Set<String> curResults =  getCurrentResult(res) ;
	//System.out.println("current:"+ curResults);
	Set<String> actualResults = getActualResults(queryNo) ;
	//System.out.println("actual:" +actualResults);
	Set<String> diffSet = Sets.difference(actualResults, curResults);
	//System.out.println(diffSet);
	//System.out.println(Sets.difference( curResults,actualResults));
	double correctResults = actualResults.size()-diffSet.size();
	precision = (correctResults/curResults.size());
	recall = correctResults/actualResults.size();
	F1 = 2*(precision*recall)/(precision+recall);
	Fscores = "Precision: "+precision+", Recall: " + recall +", F1: "+F1;
	return Fscores;
	
}
 
Example #14
Source File: RepositoryConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private int size(IRI defaultGraph) throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	TupleQuery qry = testCon.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { ?s ?p ?o }");
	SimpleDataset dataset = new SimpleDataset();
	dataset.addDefaultGraph(defaultGraph);
	qry.setDataset(dataset);
	TupleQueryResult result = qry.evaluate();
	try {
		int count = 0;
		while (result.hasNext()) {
			result.next();
			count++;
		}
		return count;
	} finally {
		result.close();
	}
}
 
Example #15
Source File: TupleReArrangerTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void tupleReArrangeTest2() throws MalformedQueryException {

    String queryString = ""//
            + "SELECT ?a ?b ?c ?d ?e ?x ?y" //
            + "{" //
            + " ?e <uri:laughsAt> ?x ." //
            + " ?e <uri:livesIn> ?y . "//
            + "{ ?a a ?b .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?c  }"//
            + " UNION { ?a <uri:talksTo> ?d .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?e  }"//
            + "}";//

    SPARQLParser sp = new SPARQLParser();
    ParsedQuery pq = sp.parseQuery(queryString, null);
    List<TupleExpr> tuples = TupleReArranger.getTupleReOrderings(pq.getTupleExpr());


    Assert.assertEquals(24, tuples.size());

}
 
Example #16
Source File: CheckStatementPattern.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(BindingSet bindings)
		throws QueryEvaluationException {

	StatementPattern st = (StatementPattern) stmt;

	try {
		// return true if at least one endpoint has a result for this binding set
		for (StatementSource source : stmt.getStatementSources()) {
			Endpoint ownedEndpoint = queryInfo.getFederationContext()
					.getEndpointManager()
					.getEndpoint(source.getEndpointID());
			TripleSource t = ownedEndpoint.getTripleSource();
			if (t.hasStatements(st, bindings, queryInfo, queryInfo.getDataset())) {
				return new SingleBindingSetIteration(bindings);
			}
		}
	} catch (RepositoryException | MalformedQueryException e) {
		throw new QueryEvaluationException(e);
	}

	// XXX return NULL instead and add an additional check?
	return new EmptyIteration<>();
}
 
Example #17
Source File: SPARQLQueryBuilderAsserts.java    From inception with Apache License 2.0 6 votes vote down vote up
public static List<KBHandle> asHandles(Repository aRepo, SPARQLQuery aBuilder)
{
    try (RepositoryConnection conn = aRepo.getConnection()) {
        printQuery(aBuilder);
        
        long startTime = System.currentTimeMillis();

        List<KBHandle> results = aBuilder.asHandles(conn, true);

        System.out.printf("Results : %d in %dms%n", results.size(),
                System.currentTimeMillis() - startTime);
        results.stream().limit(10).forEach(r -> System.out.printf("          %s%n", r));
        if (results.size() > 10) {
            System.out.printf("          ... and %d more ...%n", results.size() - 10);
        }
        
        return results;
    }
    catch (MalformedQueryException e) {
        throw handleParseException(aBuilder, e);
    }
}
 
Example #18
Source File: FedSumSourceSelection.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Index lookup for rdf:type and its its corresponding values
 * @param p Predicate i.e. rdf:type
 * @param o Predicate value
 * @param stmt Statement Pattern
 * @throws RepositoryException
 * @throws MalformedQueryException
 * @throws QueryEvaluationException
 */
public void FedSumClassLookup(StatementPattern stmt, String p, String o) throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	
	  String  queryString = "Prefix ds:<http://aksw.org/fedsum/> "
		   		+ "SELECT  Distinct ?url "
			   	+ " WHERE {?s ds:url ?url. "
				+ " 		?s ds:capability ?cap. "
				+ "		   ?cap ds:predicate <" + p + ">."
						+ "?cap ds:objAuthority  <" + o + "> }" ;
	    TupleQuery tupleQuery = FedSumConfig.con.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
		 TupleQueryResult result = tupleQuery.evaluate();
		   while(result.hasNext())
		   {
			  String endpoint = result.next().getValue("url").stringValue();
				String id = "sparql_" + endpoint.replace("http://", "").replace("/", "_");
				addSource(stmt, new StatementSource(id, StatementSourceType.REMOTE));
		   }
}
 
Example #19
Source File: SPARQLQueryBuilderAsserts.java    From inception with Apache License 2.0 6 votes vote down vote up
public static boolean exists(Repository aRepo, SPARQLQuery aBuilder)
{
    try (RepositoryConnection conn = aRepo.getConnection()) {
        printQuery(aBuilder);
        
        long startTime = System.currentTimeMillis();

        boolean result = aBuilder.exists(conn, true);

        System.out.printf("Results : %b in %dms%n", result,
                System.currentTimeMillis() - startTime);
        
        return result;
    }
    catch (MalformedQueryException e) {
        throw handleParseException(aBuilder, e);
    }
}
 
Example #20
Source File: SPARQLTupleQuery.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void evaluate(TupleQueryResultHandler handler)
		throws QueryEvaluationException, TupleQueryResultHandlerException {

	SPARQLProtocolSession client = getHttpClient();
	try {
		client.sendTupleQuery(QueryLanguage.SPARQL, getQueryString(), baseURI, dataset, getIncludeInferred(),
				getMaxExecutionTime(), handler, getBindingsArray());
	} catch (IOException | RepositoryException | MalformedQueryException e) {
		throw new QueryEvaluationException(e.getMessage(), e);
	}
}
 
Example #21
Source File: GeowaveDirectExample.java    From rya with Apache License 2.0 5 votes vote down vote up
private static void testGeoFreetextWithPCJSearch(
		final SailRepositoryConnection conn)
		throws MalformedQueryException, RepositoryException,
		TupleQueryResultHandlerException, QueryEvaluationException {
	// ring outside point
	final String queryString = "PREFIX geo: <http://www.opengis.net/ont/geosparql#>  "//
			+ "PREFIX fts: <http://rdf.useekm.com/fts#>  "//
			+ "PREFIX geof: <http://www.opengis.net/def/function/geosparql/>  "//
			+ "SELECT ?feature ?point ?wkt ?e ?c ?l ?o ?person ?match " //
			+ "{" //
			+ "  ?person a <http://example.org/ontology/Person> . "//
			+ "  ?person <http://www.w3.org/2000/01/rdf-schema#label> ?match . "//
			+ "  FILTER(fts:text(?match, \"!alice & hose\")) " //
			+ "  ?e a ?c . "//
			+ "  ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l . "//
			+ "  ?e <uri:talksTo> ?o . "//
			+ "  ?feature a geo:Feature . "//
			+ "  ?feature geo:hasGeometry ?point . "//
			+ "  ?point a geo:Point . "//
			+ "  ?point geo:asWKT ?wkt . "//
			+ "  FILTER(geof:sfWithin(?wkt, \"POLYGON((-78 39, -77 39, -77 38, -78 38, -78 39))\"^^geo:wktLiteral)) " //
			+ "}";//
	final TupleQuery tupleQuery = conn.prepareTupleQuery(
			QueryLanguage.SPARQL, queryString);
	final CountingResultHandler tupleHandler = new CountingResultHandler();
	tupleQuery.evaluate(tupleHandler);
	log.info("Result count : " + tupleHandler.getCount());
	Validate.isTrue(tupleHandler.getCount() == 0);// TODO ==1  some data is missing for this query!
}
 
Example #22
Source File: AbstractLuceneSailTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testComplexQueryTwo() throws MalformedQueryException, RepositoryException, QueryEvaluationException {
	// prepare the query
	StringBuilder buffer = new StringBuilder();
	buffer.append("SELECT Resource, Matching, Score ");
	buffer.append("FROM {Resource} <" + PREDICATE_3 + "> {Matching} ");
	buffer.append(" <" + MATCHES + "> {} ");
	buffer.append(" <" + QUERY + "> {\"two\"}; ");
	buffer.append(" <" + SCORE + "> {Score} ");
	String q = buffer.toString();

	try (RepositoryConnection connection = repository.getConnection()) {
		// fire a query for all subjects with a given term
		TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SERQL, q);
		try (TupleQueryResult result = query.evaluate()) {

			// check the results
			assertTrue(result.hasNext());
			BindingSet bindings = result.next();
			assertEquals(SUBJECT_3, (IRI) bindings.getValue("Resource"));
			assertEquals(SUBJECT_1, (IRI) bindings.getValue("Matching"));
			assertNotNull(bindings.getValue("Score"));

			assertFalse(result.hasNext());

		}
	}
}
 
Example #23
Source File: FederationEvalStrategy.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CloseableIteration<BindingSet, QueryEvaluationException> evaluateSingleSourceQuery(SingleSourceQuery query,
		BindingSet bindings) throws QueryEvaluationException {

	try {
		Endpoint source = query.getSource();
		return source.getTripleSource()
				.getStatements(query.getQueryString(), bindings, query.getQueryInfo().getQueryType(),
						query.getQueryInfo());
	} catch (RepositoryException | MalformedQueryException e) {
		throw new QueryEvaluationException(e);
	}

}
 
Example #24
Source File: RepositoryModel.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlConstruct(String query) throws ModelRuntimeException {
	assertModel();
	try {
		GraphQuery prepared = this.connection.prepareGraphQuery(QueryLanguage.SPARQL, query);
		GraphQueryResult graphQueryResult = prepared.evaluate();
		return new GraphIterable(graphQueryResult, this);
	} catch (MalformedQueryException | RepositoryException |
			UnsupportedQueryLanguageException | QueryEvaluationException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example #25
Source File: QueryManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Prepare a {@link Query} which uses the underlying federation to evaluate the SPARQL query.
 * <p>
 *
 * The queryString is modified to use the declared PREFIX declarations, see
 * {@link FedXConfig#getPrefixDeclarations()} for details.
 *
 * @param queryString
 * @return the prepared {@link Query}
 * @throws MalformedQueryException
 */
public Query prepareQuery(String queryString) throws MalformedQueryException {

	if (prefixDeclarations.size() > 0) {

		/*
		 * we have to check for prefixes in the query to not add duplicate entries. In case duplicates are present
		 * RDF4J throws a MalformedQueryException
		 */
		if (prefixCheck.matcher(queryString).matches()) {
			queryString = getPrefixDeclarationsCheck(queryString) + queryString;
		} else {
			queryString = getPrefixDeclarations() + queryString;
		}
	}

	Query q;
	try {
		q = getOrCreateConn().prepareQuery(QueryLanguage.SPARQL, queryString);
	} catch (RepositoryException e) {
		throw new FedXRuntimeException(e); // cannot occur
	}

	// TODO set query time

	return q;
}
 
Example #26
Source File: TripleSourceBase.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean hasStatements(ExclusiveTupleExpr group, BindingSet bindings)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException {

	monitorRemoteRequest();
	String preparedAskQuery = QueryStringUtil.askQueryString(group, bindings, group.getQueryInfo().getDataset());
	try (RepositoryConnection conn = endpoint.getConnection()) {
		BooleanQuery query = conn.prepareBooleanQuery(QueryLanguage.SPARQL, preparedAskQuery);
		configureInference(query, group.getQueryInfo());
		applyMaxExecutionTimeUpperBound(query);
		return query.evaluate();
	}
}
 
Example #27
Source File: ExecuteHibiscusQuery.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unused")
private static void printParseQuery(String query) throws MalformedQueryException {
	SPARQLParserFactory factory = new SPARQLParserFactory();
	QueryParser parser = factory.getParser();
	ParsedQuery parsedQuery = parser.parseQuery(query, null);
	System.out.println(parsedQuery.toString());


}
 
Example #28
Source File: AccumuloIndexSet.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param sparql
 *            - name of sparql query whose results will be stored in PCJ
 *            table
 * @param accCon
 *            - connection to a valid Accumulo instance
 * @param tablename
 *            - name of an existing PCJ table
 * @throws MalformedQueryException
 * @throws SailException
 * @throws QueryEvaluationException
 * @throws TableNotFoundException
 * @throws AccumuloSecurityException
 * @throws AccumuloException
 * @throws PCJStorageException
 */
public AccumuloIndexSet(final String sparql, final Configuration conf,
		final String tablename) throws MalformedQueryException, SailException,
		QueryEvaluationException, TableNotFoundException, AccumuloException, AccumuloSecurityException, PCJStorageException {
	this.tablename = tablename;
	this.accCon = ConfigUtils.getConnector(conf);
	this.auths = getAuthorizations(conf);
	final SPARQLParser sp = new SPARQLParser();
	final ParsedTupleQuery pq = (ParsedTupleQuery) sp.parseQuery(sparql, null);
	final TupleExpr te = pq.getTupleExpr();
	Preconditions.checkArgument(PCJOptimizerUtilities.isPCJValid(te),
			"TupleExpr is an invalid PCJ.");

	final Optional<Projection> projection = new ParsedQueryUtil()
			.findProjection(pq);
	if (!projection.isPresent()) {
		throw new MalformedQueryException("SPARQL query '" + sparql
				+ "' does not contain a Projection.");
	}
	setProjectionExpr(projection.get());
	Set<VariableOrder> orders = null;
	orders = pcj.getPcjMetadata(accCon, tablename).getVarOrders();

	varOrder = Lists.newArrayList();
	for (final VariableOrder var : orders) {
		varOrder.add(var.toString());
	}
	setLocalityGroups(tablename, accCon, varOrder);
	this.setSupportedVariableOrderMap(varOrder);
}
 
Example #29
Source File: SPARQLConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void exportStatements(Resource subj, IRI pred, Value obj, boolean includeInferred, RDFHandler handler,
		Resource... contexts) throws RepositoryException, RDFHandlerException {
	try {
		GraphQuery query = prepareGraphQuery(SPARQL, EVERYTHING, "");
		setBindings(query, subj, pred, obj, contexts);
		query.evaluate(handler);
	} catch (MalformedQueryException | QueryEvaluationException e) {
		throw new RepositoryException(e);
	}
}
 
Example #30
Source File: SparqlTripleSource.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public CloseableIteration<BindingSet, QueryEvaluationException> getStatements(
		StatementPattern stmt, BindingSet bindings, FilterValueExpr filterExpr, QueryInfo queryInfo)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException {

	throw new RuntimeException("NOT YET IMPLEMENTED.");
}