org.eclipse.rdf4j.query.parser.ParsedOperation Java Examples

The following examples show how to use org.eclipse.rdf4j.query.parser.ParsedOperation. 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: ConvertSpinRDFToString.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length < 1 || args.length > 2) {
		throw new ValueExprEvaluationException("Incorrect number of arguments");
	}
	if (!(args[0] instanceof Resource)) {
		throw new ValueExprEvaluationException("First argument must be the root of a SPIN RDF query");
	}
	if (args.length == 2 && !(args[1] instanceof Literal)) {
		throw new ValueExprEvaluationException("Second argument must be a string");
	}
	Resource q = (Resource) args[0];
	boolean useHtml = (args.length == 2) ? ((Literal) args[1]).booleanValue() : false;
	String sparqlString;
	try {
		ParsedOperation op = parser.parse(q, getCurrentQueryPreparer().getTripleSource());
		sparqlString = new SPARQLQueryRenderer().render((ParsedQuery) op);
	} catch (Exception e) {
		throw new ValueExprEvaluationException(e);
	}
	return valueFactory.createLiteral(sparqlString);
}
 
Example #2
Source File: QueryManager.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Retrieve the query plan for the given query string.
 */
public String getQueryPlan(String queryString, Object summary) {
	if (prefixDeclarations.size() > 0) {
		
		/* we have to check for prefixes in the query to not add
		 * duplicate entries. In case duplicates are present
		 * Sesame throws a MalformedQueryException
		 */
		if (prefixCheck.matcher(queryString).matches()) {
			queryString = getPrefixDeclarationsCheck(queryString) + queryString;
		} else {
			queryString = getPrefixDeclarations() + queryString;
		}
	}
	
	ParsedOperation query = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, queryString, null);
	if (!(query instanceof ParsedQuery))
		throw new MalformedQueryException("Not a ParsedQuery: " + query.getClass());
	// we use a dummy query info object here
	QueryInfo qInfo = new QueryInfo(conn.getSailConnection(), queryString, QueryType.SELECT, summary);
	TupleExpr tupleExpr = ((ParsedQuery)query).getTupleExpr();
	try {
		tupleExpr = Optimizer.optimize(tupleExpr, new SimpleDataset(), EmptyBindingSet.getInstance(), conn.getSailConnection().getStrategy(), qInfo);
		return tupleExpr.toString();
	} catch (SailException e) {
		throw new FedXException("Unable to retrieve query plan: " + e.getMessage());
	}		
}
 
Example #3
Source File: SpinInferencing.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void addBindings(Resource subj, Resource opResource, ParsedOperation parsedOp, Operation op,
		TripleSource tripleSource, SpinParser parser) throws OpenRDFException {
	if (!parser.isThisUnbound(opResource, tripleSource)) {
		op.setBinding(THIS_VAR, subj);
	}
	if (parsedOp instanceof ParsedTemplate) {
		for (Binding b : ((ParsedTemplate) parsedOp).getBindings()) {
			op.setBinding(b.getName(), b.getValue());
		}
	}
}
 
Example #4
Source File: SpinInferencing.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static int executeRule(Resource subj, Resource rule, QueryPreparer queryPreparer, SpinParser parser,
		InferencerConnection conn) throws OpenRDFException {
	int nofInferred;
	TripleSource tripleSource = queryPreparer.getTripleSource();
	ParsedOperation parsedOp = parser.parse(rule, tripleSource);
	if (parsedOp instanceof ParsedGraphQuery) {
		ParsedGraphQuery graphQuery = (ParsedGraphQuery) parsedOp;
		GraphQuery queryOp = queryPreparer.prepare(graphQuery);
		addBindings(subj, rule, graphQuery, queryOp, tripleSource, parser);
		CountingRDFInferencerInserter handler = new CountingRDFInferencerInserter(conn,
				tripleSource.getValueFactory());
		queryOp.evaluate(handler);
		nofInferred = handler.getStatementCount();
	} else if (parsedOp instanceof ParsedUpdate) {
		ParsedUpdate graphUpdate = (ParsedUpdate) parsedOp;
		Update updateOp = queryPreparer.prepare(graphUpdate);
		addBindings(subj, rule, graphUpdate, updateOp, tripleSource, parser);
		UpdateCountListener listener = new UpdateCountListener();
		conn.addConnectionListener(listener);
		updateOp.execute();
		conn.removeConnectionListener(listener);
		// number of statement changes
		nofInferred = listener.getAddedStatementCount() + listener.getRemovedStatementCount();
	} else {
		throw new MalformedSpinException("Invalid rule: " + rule);
	}
	return nofInferred;
}
 
Example #5
Source File: QueryManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Retrieve the query plan for the given query string.
 *
 * @param queryString
 * @return the query plan
 * @throws MalformedQueryException
 * @throws FedXException
 */
public String getQueryPlan(String queryString) throws MalformedQueryException, FedXException {

	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;
		}
	}

	ParsedOperation query = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, queryString, null);
	if (!(query instanceof ParsedQuery)) {
		throw new MalformedQueryException("Not a ParsedQuery: " + query.getClass());
	}
	// we use a dummy query info object here
	QueryInfo qInfo = new QueryInfo(queryString, QueryType.SELECT,
			federationContext.getConfig().getIncludeInferredDefault(), federationContext,
			((ParsedQuery) query).getDataset());
	TupleExpr tupleExpr = ((ParsedQuery) query).getTupleExpr();
	try {
		FederationEvaluationStatistics evaluationStatistics = new FederationEvaluationStatistics(qInfo,
				new SimpleDataset());
		tupleExpr = federationContext.getStrategy()
				.optimize(tupleExpr, evaluationStatistics, EmptyBindingSet.getInstance());
		return tupleExpr.toString();
	} catch (SailException e) {
		throw new FedXException("Unable to retrieve query plan: " + e.getMessage());
	}
}
 
Example #6
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void render(ParsedOperation operation, RDFHandler handler) throws RDFHandlerException {
	if (operation instanceof ParsedQuery) {
		render((ParsedQuery) operation, handler);
	} else if (operation instanceof ParsedUpdate) {
		render((ParsedUpdate) operation, handler);
	} else {
		throw new AssertionError("Unrecognised ParsedOperation: " + operation.getClass());
	}
}
 
Example #7
Source File: SpinRendererTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSpinRenderer() throws IOException, RDF4JException {
	StatementCollector expected = new StatementCollector();
	RDFParser parser = Rio.createParser(RDFFormat.TURTLE);
	parser.setRDFHandler(expected);
	try (InputStream rdfStream = testURL.openStream()) {
		parser.parse(rdfStream, testURL.toString());
	}

	// get query from sp:text
	String query = null;
	for (Statement stmt : expected.getStatements()) {
		if (SP.TEXT_PROPERTY.equals(stmt.getPredicate())) {
			query = stmt.getObject().stringValue();
			break;
		}
	}
	assertNotNull(query);

	ParsedOperation parsedOp = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, query, testURL.toString());

	StatementCollector actual = new StatementCollector();
	renderer.render(parsedOp, actual);

	Object operation = (parsedOp instanceof ParsedQuery) ? ((ParsedQuery) parsedOp).getTupleExpr()
			: ((ParsedUpdate) parsedOp).getUpdateExprs();
	assertTrue("Operation was\n" + operation + "\nExpected\n" + toRDF(expected) + "\nbut was\n" + toRDF(actual),
			Models.isomorphic(actual.getStatements(), expected.getStatements()));
}
 
Example #8
Source File: SpinParserTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSpinParser() throws IOException, RDF4JException {
	StatementCollector expected = new StatementCollector();
	RDFParser parser = Rio.createParser(RDFFormat.TURTLE);
	parser.setRDFHandler(expected);
	try (InputStream rdfStream = testURL.openStream()) {
		parser.parse(rdfStream, testURL.toString());
	}

	// get query resource from sp:text
	Resource queryResource = null;
	for (Statement stmt : expected.getStatements()) {
		if (SP.TEXT_PROPERTY.equals(stmt.getPredicate())) {
			queryResource = stmt.getSubject();
			break;
		}
	}
	assertNotNull(queryResource);

	TripleSource store = new ModelTripleSource(new TreeModel(expected.getStatements()));
	ParsedOperation textParsedOp = textParser.parse(queryResource, store);
	ParsedOperation rdfParsedOp = rdfParser.parse(queryResource, store);

	if (textParsedOp instanceof ParsedQuery) {
		assertEquals(((ParsedQuery) textParsedOp).getTupleExpr(), ((ParsedQuery) rdfParsedOp).getTupleExpr());
	} else {
		assertEquals(((ParsedUpdate) textParsedOp).getUpdateExprs(), ((ParsedUpdate) rdfParsedOp).getUpdateExprs());
	}
}
 
Example #9
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private ParsedOperation parseText(Resource queryResource, IRI queryType, TripleSource store) throws RDF4JException {
	Value text = TripleSources.singleValue(queryResource, SP.TEXT_PROPERTY, store);
	if (text != null) {
		if (QUERY_TYPES.contains(queryType)) {
			return QueryParserUtil.parseQuery(QueryLanguage.SPARQL, text.stringValue(), null);
		} else if (UPDATE_TYPES.contains(queryType)) {
			return QueryParserUtil.parseUpdate(QueryLanguage.SPARQL, text.stringValue(), null);
		} else {
			throw new MalformedSpinException(String.format("Unrecognised command type: %s", queryType));
		}
	} else {
		return null;
	}
}
 
Example #10
Source File: Template.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public ParsedOperation call(Map<IRI, Value> argValues) throws MalformedSpinException {
	MapBindingSet args = new MapBindingSet();
	for (Argument arg : arguments) {
		IRI argPred = arg.getPredicate();
		Value argValue = argValues.get(argPred);
		if (argValue == null && !arg.isOptional()) {
			throw new MalformedSpinException("Missing value for template argument: " + argPred);
		}
		if (argValue == null) {
			argValue = arg.getDefaultValue();
		}
		if (argValue != null) {
			args.addBinding(argPred.getLocalName(), argValue);
		}
	}

	ParsedOperation callOp;
	if (parsedOp instanceof ParsedBooleanQuery) {
		callOp = new ParsedBooleanTemplate(this, args);
	} else if (parsedOp instanceof ParsedTupleQuery) {
		callOp = new ParsedTupleTemplate(this, args);
	} else if (parsedOp instanceof ParsedGraphQuery) {
		callOp = new ParsedGraphTemplate(this, args);
	} else if (parsedOp instanceof ParsedUpdate) {
		callOp = new ParsedUpdateTemplate(this, args);
	} else {
		throw new AssertionError("Unrecognised ParsedOperation: " + parsedOp.getClass());
	}
	return callOp;
}
 
Example #11
Source File: Query.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Object execute() throws Exception {
    // Get Query String
    String queryString;
    if (queryFileParam != null) {
        try {
            queryString = new String(Files.readAllBytes(Paths.get(queryFileParam)));
        } catch (IOException e) {
            throw new MobiException(e);
        }
    } else {
        queryString = queryParam;
    }

    // Get Repo
    if (StringUtils.isEmpty(repositoryParam)) {
        repositoryParam = "system";
    }

    Optional<Repository> repoOpt = repoManager.getRepository(repositoryParam);

    if (!repoOpt.isPresent()) {
        System.out.println("ERROR: Repository not found.");
        return null;
    }

    // Parse Query
    ParsedOperation parsedOperation = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, queryString, null);

    // Execute Query
    if (parsedOperation instanceof ParsedQuery) {
        if (parsedOperation instanceof ParsedTupleQuery) {
            executeTupleQuery(repoOpt.get(), queryString);
        } else if (parsedOperation instanceof ParsedGraphQuery) {
            executeGraphQuery(repoOpt.get(), queryString);
        } else {
            System.out.println("Query type not supported.");
        }
    } else {
        System.out.println("Update queries not supported.");
    }

    return null;
}
 
Example #12
Source File: SPARQLParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void main(String[] args) throws java.io.IOException {
	System.out.println("Your SPARQL query:");

	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

	StringBuilder buf = new StringBuilder();
	String line = null;

	int emptyLineCount = 0;
	while ((line = in.readLine()) != null) {
		if (line.length() > 0) {
			emptyLineCount = 0;
			buf.append(' ').append(line).append('\n');
		} else {
			emptyLineCount++;
		}

		if (emptyLineCount == 2) {
			emptyLineCount = 0;
			String queryStr = buf.toString().trim();
			if (queryStr.length() > 0) {
				try {
					long start = System.currentTimeMillis();
					ParsedOperation parsedQuery = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, queryStr,
							null);
					long finish = System.currentTimeMillis();

					System.out.println("Parsed query: ");
					System.out.println(parsedQuery.toString());
					System.out.println();
					System.out.println("parsed in " + (finish - start) + " ms.");

				} catch (Exception e) {
					System.err.println(e.getMessage());
					e.printStackTrace();
				}
			}
			buf.setLength(0);
		}
	}
}
 
Example #13
Source File: Template.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public ParsedOperation getParsedOperation() {
	return parsedOp;
}
 
Example #14
Source File: Template.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void setParsedOperation(ParsedOperation op) {
	this.parsedOp = op;
}
 
Example #15
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected ParsedOperation parse(Resource queryResource, IRI queryClass, TripleSource store) throws RDF4JException {
	Boolean isQueryElseTemplate = null;
	Set<IRI> possibleQueryTypes = new HashSet<>();
	Set<IRI> possibleTemplates = new HashSet<>();
	try (CloseableIteration<IRI, QueryEvaluationException> typeIter = TripleSources
			.getObjectURIs(queryResource, RDF.TYPE, store)) {
		while (typeIter.hasNext()) {
			IRI type = typeIter.next();
			if (isQueryElseTemplate == null && SPIN.TEMPLATES_CLASS.equals(type)) {
				isQueryElseTemplate = Boolean.FALSE;
			} else if ((isQueryElseTemplate == null || isQueryElseTemplate == Boolean.TRUE)
					&& COMMAND_TYPES.contains(type)) {
				isQueryElseTemplate = Boolean.TRUE;
				possibleQueryTypes.add(type);
			} else if ((isQueryElseTemplate == null || isQueryElseTemplate == Boolean.FALSE)
					&& !NON_TEMPLATES.contains(type)) {
				possibleTemplates.add(type);
			}
		}
	}

	ParsedOperation parsedOp;
	if (isQueryElseTemplate == null) {
		throw new MalformedSpinException(String.format("Missing RDF type: %s", queryResource));
	} else if (isQueryElseTemplate == Boolean.TRUE) {
		// command (query or update)
		if (possibleQueryTypes.size() > 1) {
			throw new MalformedSpinException(
					"Incompatible RDF types for command: " + queryResource + " has types " + possibleQueryTypes);
		}

		IRI queryType = possibleQueryTypes.iterator().next();

		if (input.textFirst) {
			parsedOp = parseText(queryResource, queryType, store);
			if (parsedOp == null && input.canFallback) {
				parsedOp = parseRDF(queryResource, queryType, store);
			}
		} else {
			parsedOp = parseRDF(queryResource, queryType, store);
			if (parsedOp == null && input.canFallback) {
				parsedOp = parseText(queryResource, queryType, store);
			}
		}

		if (parsedOp == null) {
			throw new MalformedSpinException(String.format("Command is not parsable: %s", queryResource));
		}
	} else {
		// template
		Set<IRI> abstractTemplates;
		if (possibleTemplates.size() > 1) {
			abstractTemplates = new HashSet<>();
			for (Iterator<IRI> iter = possibleTemplates.iterator(); iter.hasNext();) {
				IRI t = iter.next();
				boolean isAbstract = TripleSources.booleanValue(t, SPIN.ABSTRACT_PROPERTY, store);
				if (isAbstract) {
					abstractTemplates.add(t);
					iter.remove();
				}
			}
		} else {
			abstractTemplates = Collections.emptySet();
		}

		if (possibleTemplates.isEmpty()) {
			throw new MalformedSpinException(String.format("Template missing RDF type: %s", queryResource));
		}
		if (possibleTemplates.size() > 1) {
			throw new MalformedSpinException("Template has unexpected RDF types: " + queryResource
					+ " has non-abstract types " + possibleTemplates);
		}

		IRI templateResource = (IRI) possibleTemplates.iterator().next();
		Template tmpl = getTemplate(templateResource, queryClass, abstractTemplates, store);
		Map<IRI, Value> argValues = new HashMap<>(2 * tmpl.getArguments().size());
		for (Argument arg : tmpl.getArguments()) {
			IRI argPred = (IRI) arg.getPredicate();
			Value argValue = TripleSources.singleValue(queryResource, argPred, store);
			argValues.put(argPred, argValue);
		}
		parsedOp = tmpl.call(argValues);
	}

	return parsedOp;
}
 
Example #16
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public ParsedOperation parse(Resource queryResource, TripleSource store) throws RDF4JException {
	return parse(queryResource, SP.COMMAND_CLASS, store);
}
 
Example #17
Source File: SPARQL11SyntaxComplianceTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected abstract ParsedOperation parseOperation(String operation, String fileURL) throws MalformedQueryException;
 
Example #18
Source File: W3CApprovedSPARQL11SyntaxTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected ParsedOperation parseOperation(String operation, String fileURL) throws MalformedQueryException {
	return QueryParserUtil.parseOperation(QueryLanguage.SPARQL, operation, fileURL);
}
 
Example #19
Source File: SPARQLSyntaxComplianceTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License votes vote down vote up
protected abstract ParsedOperation parseOperation(String operation, String fileURL) throws MalformedQueryException; 
Example #20
Source File: SPARQL11SyntaxTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License votes vote down vote up
protected abstract ParsedOperation parseOperation(String operation, String fileURL) throws MalformedQueryException;