Java Code Examples for org.eclipse.rdf4j.query.parser.QueryParserUtil#parseOperation()

The following examples show how to use org.eclipse.rdf4j.query.parser.QueryParserUtil#parseOperation() . 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: 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 2
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 3
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 4
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 5
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 6
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;
}