org.apache.jena.query.QueryParseException Java Examples

The following examples show how to use org.apache.jena.query.QueryParseException. 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: ParserSPARQLStarTest.java    From RDFstarTools with Apache License 2.0 6 votes vote down vote up
@Test
public void registrationOK() {
	assertTrue( SPARQLParserRegistry.containsParserFactory(SPARQLStar.syntax) );
	assertTrue( SPARQLParserRegistry.parser(SPARQLStar.syntax) instanceof ParserSPARQLStar );

	final String queryString = "SELECT * WHERE { <<?s ?p ?o>> ?p2 ?o2 }";
	QueryFactory.create(queryString, SPARQLStar.syntax);

	try {
		QueryFactory.create(queryString); // This should fail with the
	}                                     // default SPARQL parser.
	catch ( QueryParseException e ) {  // Hence, this exception 
		return;                        // is expected.
	}
	fail( "Expected exception not thrown." );
}
 
Example #2
Source File: Qald7CreationTool.java    From NLIWOD with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean checkIsOnlydbo(final String sparqlQuery) throws QueryParseException {
	if (sparqlQuery == null) {
		return false;
	}
	Query q = QueryFactory.create(sparqlQuery);
	PrefixMapping prefixMap = q.getPrefixMapping();
	Map<String, String> map = new HashMap<>(prefixMap.getNsPrefixMap());

	Set<Entry<String, String>> remove = new HashSet<>();
	for (Entry<String, String> it : map.entrySet()) {
		if (it.getKey().equals("rdf") || it.getKey().equals("rdfs") || it.getValue().equals(DBO_URI) || it.getValue().equals(RES_URI)) {
			remove.add(it);
		}
	}
	map.entrySet().removeAll(remove);
	return map.isEmpty();
}
 
Example #3
Source File: PlanFactory.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
/**
 * A factory that creates a {@link RootPlan} from a query.
 *
 * @param queryStr the string representation of the SPARQL-Generate or
 * SPARQL-Template Query.
 * @param base the base URI, if not set explicitly in the query string
 * @return the RootPlan that may be used to execute the query.
 */
public static final RootPlan create(final String queryStr, String base) {
    Objects.requireNonNull(queryStr, "Parameter string must not be null");
    SPARQLExtQuery query;
    try {
        query = (SPARQLExtQuery) QueryFactory.create(queryStr, base,
                SPARQLExt.SYNTAX);
        if(!query.explicitlySetBaseURI()) {
        	query.setBaseURI(base);
        }
    } catch (QueryParseException ex) {
        throw new SPARQLExtException(
                "Error while parsing the query \n" + queryStr, ex);
    }
    LOG.trace("Creating plan for query: \n" + query);
    return create(query);
}
 
Example #4
Source File: AbstractSPARQLExecutor.java    From shacl with Apache License 2.0 6 votes vote down vote up
protected AbstractSPARQLExecutor(Constraint constraint) {
	this.queryString = getSPARQL(constraint);
	try {
		this.query = ARQFactory.get().createQuery(queryString);
		Resource path = constraint.getShapeResource().getPath();
		if(path != null && path.isAnon()) {
			String pathString = SHACLPaths.getPathString(constraint.getShapeResource().getPropertyResourceValue(SH.path));
			query = SPARQLSubstitutions.substitutePaths(query, pathString, constraint.getShapeResource().getModel());
		}
	}
	catch(QueryParseException ex) {
		throw new SHACLException("Invalid SPARQL constraint (" + ex.getLocalizedMessage() + "):\n" + queryString);
	}

	if(!query.isSelectType()) {
		throw new IllegalArgumentException("SHACL constraints must be SELECT queries");
	}
}
 
Example #5
Source File: SPARQLTarget.java    From shacl with Apache License 2.0 6 votes vote down vote up
SPARQLTarget(Resource executable, SHParameterizableTarget parameterizableTarget) {
	
	this.parameterizableTarget = parameterizableTarget;

	String sparql = JenaUtil.getStringProperty(executable, SH.select);
	if(sparql == null) {
		throw new SHACLException("Missing sh:select at " + executable);
	}
	try {
		query = ARQFactory.get().createQuery(SPARQLSubstitutions.withPrefixes(sparql, executable));
	}
	catch(Exception ex) {
		try {
			query = ARQFactory.get().createQuery(SPARQLSubstitutions.withPrefixes("SELECT ?this WHERE {" + sparql + "}", executable));
		}
		catch(QueryParseException ex2) {
			throw new SHACLException("Invalid SPARQL target (" + ex2.getLocalizedMessage() + ")");
		}
	}
}
 
Example #6
Source File: SHACLPaths.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to parse a given string into a Jena Path.
 * Throws an Exception if the string cannot be parsed.
 * @param string  the string to parse
 * @param model  the Model to operate on (for prefixes)
 * @return a Path or a Resource if this is a URI
 */
public static Object getJenaPath(String string, Model model) throws QueryParseException {
	Query query = ARQFactory.get().createQuery(model, "ASK { ?a \n" + string + "\n ?b }");
	Element element = query.getQueryPattern();
	if(element instanceof ElementGroup) {
		Element e = ((ElementGroup)element).getElements().get(0);
		if(e instanceof ElementPathBlock) {
			Path path = ((ElementPathBlock) e).getPattern().get(0).getPath();
			if(path instanceof P_Link && ((P_Link)path).isForward()) {
				return model.asRDFNode(((P_Link)path).getNode());
			}
			else {
				return path;
			}
		}
		else if(e instanceof ElementTriplesBlock) {
			return model.asRDFNode(((ElementTriplesBlock) e).getPattern().get(0).getPredicate());
		}
	}
	throw new QueryParseException("Not a SPARQL 1.1 Path expression", 2, 1);
}
 
Example #7
Source File: SPARQLExtSyntaxVarScope.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private static void checkVarsInExpr(Expr expr, List<Var> signature, String message) {
    Set<Var> vars = ExprVars.getVarsMentioned(expr);
    vars.removeAll(signature);
    if (!vars.isEmpty()) {
        throw new QueryParseException(message, -1, -1);
    }
}
 
Example #8
Source File: SHACLPaths.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static Object getJenaPath(Resource path) throws QueryParseException {
	if(path.isURIResource()) {
		return path;
	}
	else {
		String pathString = SHACLPaths.getPathString(path);
		return SHACLPaths.getJenaPath(pathString, path.getModel());
	}
}
 
Example #9
Source File: QueryParseExceptionMapper.java    From Processor with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(QueryParseException ex)
{
    return getResponseBuilder(DatasetFactory.create(toResource(ex, Response.Status.INTERNAL_SERVER_ERROR,
                    ResourceFactory.createResource("http://www.w3.org/2011/http-statusCodes#InternalServerError")).
                getModel())).
            status(Response.Status.INTERNAL_SERVER_ERROR).
            build();
}
 
Example #10
Source File: DBpediaToWikiId.java    From gerbil with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * The Wikipedia Id or -1 if the Id couldn't be retrieved.
 * 
 * FIXME The method throws an exception for "http://DBpedia.org/resource/Origin_of_the_name_"Empire_State"". this
 * might be happen because of the quotes inside the URI.
 * 
 * @param dbpediaUri
 * @return
 */
@Deprecated
public static int getIdFromDBpedia(String dbpediaUri) {
    int id = -1;
    ParameterizedSparqlString query = new ParameterizedSparqlString(
            "SELECT ?id WHERE { ?dbpedia dbo:wikiPageID ?id .}", prefixes);
    query.setIri("dbpedia", dbpediaUri);
    QueryExecution qexec = null;
    try {
        qexec = QueryExecutionFactory.create(query.asQuery(),
                model);
    } catch (QueryParseException e) {
        LOGGER.error("Got a bad dbpediaUri \"" + dbpediaUri
                + "\" which couldn't be parse inside of a SPARQL query. Returning -1.", e);
        return id;
    }
    ResultSet result = qexec.execSelect();
    if (result.hasNext()) {
        id = result.next().get("id").asLiteral().getInt();
        return id;
    }
    qexec = QueryExecutionFactory.sparqlService(
            "http://dbpedia.org/sparql", query.asQuery());
    result = qexec.execSelect();
    if (result.hasNext()) {
        id = result.next().get("id").asLiteral().getInt();
        model.add(new StatementImpl(model.createResource(dbpediaUri), model
                .createProperty("http://dbpedia.org/ontology/wikiPageID"),
                model.createTypedLiteral(id)));
        return id;
    }

    model.add(new StatementImpl(model.createResource(dbpediaUri), model
            .createProperty("http://dbpedia.org/ontology/wikiPageID"),
            model.createTypedLiteral(id)));
    return id;
}
 
Example #11
Source File: QueryGenerationSelectFactory.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
@Override
public Query getSparqlQuery(TestCase testCase) {
    String query = this.getSparqlQueryAsString(testCase);
    try {
        return QueryFactory.create(query);
    } catch (QueryParseException e) {
        throw new IllegalArgumentException("Illegal query: \n" + query, e);
    }
}
 
Example #12
Source File: TestCaseValidator.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
private void validateSPARQL(String sparql, String type)  {
    try {
        QueryFactory.create(sparql);
    } catch (QueryParseException e) {
        String message = "QueryParseException in " + type + " query (line " + e.getLine() + ", column " + e.getColumn() + " for Test: " + testCase.getTestURI() + "\n" + PrefixNSService.getSparqlPrefixDecl() + sparql;
        //throw new TestCaseInstantiationException(message, e);
        log.warn(message,e);
    }
}
 
Example #13
Source File: TarqlParser.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void parseDo(SPARQLParser11 parser) throws ParseException {
	do {
		int beginLine = parser.getToken(1).beginLine;
		int beginColumn = parser.getToken(1).beginColumn;

		Query query = new Query(result.getPrologue());

		// You'd assume that a query initialized via "new Query(prologue)"
		// has the IRI resolver from prologue.getResolver(), but that doesn't
		// appear to be the case in Jena 2.12.0, so we set it manually
		query.getPrologue().setResolver(result.getPrologue().getResolver());

		result.addQuery(query);
		parser.setQuery(query);
		parser.Query();

		if (query.isSelectType() || query.isAskType()) {
			seenSelectOrAsk = true;
		}
		if (seenSelectOrAsk && result.getQueries().size() > 1) {
			throw new QueryParseException("" +
					"Multiple queries per file are only supported for CONSTRUCT", 
					beginLine, beginColumn);
		}
		
		// From Parser.validateParsedQuery, which we can't call directly
		SyntaxVarScope.check(query);
		
		result.getPrologue().usePrologueFrom(query);
		if (log.isDebugEnabled()) {
			log.debug(query.toString());
		}
	} while (parser.getToken(1).kind != SPARQLParser11.EOF);
	removeBuiltInPrefixes();
}
 
Example #14
Source File: TarqlParserTest.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testMultipleSELECT() throws Exception {
	try {
		String s = "SELECT * {} SELECT * {}";
		TarqlParser x = new TarqlParser(new StringReader(s));
		x.getResult().getQueries();
		fail("Expected exception due to multiple queries");
	} catch (QueryParseException ex) {
		// Expected
	}
}
 
Example #15
Source File: TarqlParserTest.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testSELECTAndCONSTRUCT() throws Exception {
	try {
		String s = "CONSTRUCT { [] a [] } WHERE {} SELECT * {}";
		TarqlParser x = new TarqlParser(new StringReader(s));
		x.getResult().getQueries();
		fail("Expected exception due to multiple queries");
	} catch (QueryParseException ex) {
		// Expected
	}
}
 
Example #16
Source File: SPARQLExtSyntaxVarScope.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
private static void checkVarsInList(List<Var> vars, List<Var> signature, String message) {
    if (!signature.containsAll(vars)) {
        throw new QueryParseException(message, -1, -1);
    }
}