Search in sources :

Example 1 with ParseException

use of org.apache.clerezza.rdf.core.sparql.ParseException in project stanbol by apache.

the class SparqlEndpointResource method sparql.

//TODO re-enable
/*@OPTIONS
    public Response handleCorsPreflight(@Context HttpHeaders headers) {
        ResponseBuilder res = Response.ok();
        enableCORS(servletContext, res, headers);
        return res.build();
    }*/
/**
     * HTTP GET service to execute SPARQL queries on {@link Graph}s registered to OSGi environment.
     * If a <code>null</code>, it is assumed that the request is coming from the HTML interface of SPARQL
     * endpoint. Otherwise the query is executed on the triple collection specified by <code>graphUri</code>.
     * But, if no graph uri is passed, then the triple collection having highest service.ranking value is
     * chosen.
     * 
     * Type of the result is determined according to type of the query such that if the specified query is
     * either a <b>describe query</b> or <b>construct query</b>, results are returned in
     * <b>application/rdf+xml</b> format, otherwise in <b>pplication/sparql-results+xml</b> format.
     * 
     * @param graphUri
     *            the URI of the graph on which the SPARQL query will be executed.
     * @param sparqlQuery
     *            SPARQL query to be executed
     * @param headers
     *            HTTP request Headers
     * @throws InvalidSyntaxException Invalid SPARQL Syntax Exception
     * @return Http Response 
     */
@GET
@Consumes(APPLICATION_FORM_URLENCODED)
@Produces({ TEXT_HTML + ";qs=2", "application/sparql-results+xml", "application/rdf+xml" })
public Response sparql(@QueryParam(value = "graphuri") String graphUri, @QueryParam(value = "query") String sparqlQuery, @Context HttpHeaders headers) throws InvalidSyntaxException {
    if (sparqlQuery == null) {
        populateGraphList(getServices(null));
        return Response.ok(new Viewable("index", this), TEXT_HTML).build();
    }
    String mediaType = "application/sparql-results+xml";
    Graph tripleCollection = getGraph(graphUri);
    ResponseBuilder rb;
    if (tripleCollection != null) {
        Object result;
        try {
            result = tcManager.executeSparqlQuery(sparqlQuery, tripleCollection);
            if (result instanceof Graph) {
                mediaType = "application/rdf+xml";
            }
            rb = Response.ok(result, mediaType);
        } catch (ParseException e) {
            rb = Response.status(Status.BAD_REQUEST).entity(e.getMessage());
        }
    } else {
        rb = Response.status(Status.NOT_FOUND).entity(String.format("There is no registered graph with given uri: %s", graphUri));
    }
    //addCORSOrigin(servletContext, rb, headers);
    return rb.build();
}
Also used : Graph(org.apache.clerezza.commons.rdf.Graph) Viewable(org.apache.stanbol.commons.web.viewable.Viewable) ParseException(org.apache.clerezza.rdf.core.sparql.ParseException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 2 with ParseException

use of org.apache.clerezza.rdf.core.sparql.ParseException in project stanbol by apache.

the class ClerezzaRuleStore method findRecipesByDescription.

@Override
public RecipeList findRecipesByDescription(String term) {
    String sparql = "SELECT ?recipe " + "WHERE { ?recipe a " + Symbols.Recipe.toString() + " . " + "?recipe " + Symbols.description + " ?description . " + "FILTER (regex(?description, \"" + term + "\", \"i\"))" + "}";
    Graph tripleCollection = tcManager.getGraph(new IRI(recipeIndexLocation));
    RecipeList matchingRecipes = new RecipeList();
    try {
        SelectQuery query = (SelectQuery) QueryParser.getInstance().parse(sparql);
        ResultSet resultSet = tcManager.executeSparqlQuery(query, tripleCollection);
        while (resultSet.hasNext()) {
            SolutionMapping solutionMapping = resultSet.next();
            IRI recipeID = (IRI) solutionMapping.get("recipe");
            try {
                Recipe recipe = getRecipe(recipeID);
                log.info("Found recipe {}.", recipeID.toString());
                matchingRecipes.add(recipe);
                log.info("Found {} matching recipes.", matchingRecipes.size());
            } catch (NoSuchRecipeException e) {
            // in this case go on in the iteration by fetching other matching recipes
            } catch (RecipeConstructionException e) {
            // in this case go on in the iteration by fetching other matching recipes
            }
        }
    } catch (ParseException e) {
        log.error("The sparql query contains errors: ", e);
    }
    return matchingRecipes;
}
Also used : SelectQuery(org.apache.clerezza.rdf.core.sparql.query.SelectQuery) IRI(org.apache.clerezza.commons.rdf.IRI) SolutionMapping(org.apache.clerezza.rdf.core.sparql.SolutionMapping) UnionGraph(org.apache.clerezza.rdf.utils.UnionGraph) Graph(org.apache.clerezza.commons.rdf.Graph) Recipe(org.apache.stanbol.rules.base.api.Recipe) RecipeList(org.apache.stanbol.rules.base.api.util.RecipeList) NoSuchRecipeException(org.apache.stanbol.rules.base.api.NoSuchRecipeException) ResultSet(org.apache.clerezza.rdf.core.sparql.ResultSet) ParseException(org.apache.clerezza.rdf.core.sparql.ParseException) RecipeConstructionException(org.apache.stanbol.rules.base.api.RecipeConstructionException)

Example 3 with ParseException

use of org.apache.clerezza.rdf.core.sparql.ParseException in project stanbol by apache.

the class ClerezzaRuleStore method findRulesByName.

@Override
public RuleList findRulesByName(String term) {
    String sparql = "SELECT ?recipe ?rule ?description " + "WHERE { " + "?recipe " + Symbols.hasRule + " ?rule . " + "?rule " + Symbols.ruleName + " ?name . " + "?rule " + Symbols.description + " ?description . " + "FILTER (regex(?name, \"" + term + "\", \"i\"))" + "}";
    List<IRI> recipeIDs = listRecipeIDs();
    Graph[] tripleCollections = new Graph[recipeIDs.size()];
    for (int i = 0; i < tripleCollections.length; i++) {
        tripleCollections[i] = tcManager.getGraph(recipeIDs.get(i));
    }
    UnionGraph unionGraph = new UnionGraph(tripleCollections);
    RuleList matchingRules = new RuleList();
    try {
        SelectQuery query = (SelectQuery) QueryParser.getInstance().parse(sparql);
        ResultSet resultSet = tcManager.executeSparqlQuery(query, unionGraph);
        while (resultSet.hasNext()) {
            SolutionMapping solutionMapping = resultSet.next();
            IRI recipeID = (IRI) solutionMapping.get("recipe");
            IRI ruleID = (IRI) solutionMapping.get("rule");
            Literal description = (Literal) solutionMapping.get("description");
            try {
                Recipe recipe = getRecipe(recipeID);
                Rule rule = new RecipeRule(recipe, getRule(recipe, ruleID));
                if (description != null) {
                    rule.setDescription(description.getLexicalForm());
                }
                matchingRules.add(rule);
            } catch (NoSuchRecipeException e) {
            // in this case go on in the iteration by fetching other matching recipes
            } catch (RecipeConstructionException e) {
            // in this case go on in the iteration by fetching other matching recipes
            } catch (NoSuchRuleInRecipeException e) {
            // in this case go on in the iteration by fetching other matching recipes
            }
        }
    } catch (ParseException e) {
        log.error("The sparql query contains errors: ", e);
    }
    return matchingRules;
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) RuleList(org.apache.stanbol.rules.base.api.util.RuleList) SolutionMapping(org.apache.clerezza.rdf.core.sparql.SolutionMapping) Recipe(org.apache.stanbol.rules.base.api.Recipe) NoSuchRecipeException(org.apache.stanbol.rules.base.api.NoSuchRecipeException) RecipeConstructionException(org.apache.stanbol.rules.base.api.RecipeConstructionException) SelectQuery(org.apache.clerezza.rdf.core.sparql.query.SelectQuery) UnionGraph(org.apache.clerezza.rdf.utils.UnionGraph) Graph(org.apache.clerezza.commons.rdf.Graph) UnionGraph(org.apache.clerezza.rdf.utils.UnionGraph) NoSuchRuleInRecipeException(org.apache.stanbol.rules.base.api.NoSuchRuleInRecipeException) Literal(org.apache.clerezza.commons.rdf.Literal) ResultSet(org.apache.clerezza.rdf.core.sparql.ResultSet) Rule(org.apache.stanbol.rules.base.api.Rule) ParseException(org.apache.clerezza.rdf.core.sparql.ParseException)

Example 4 with ParseException

use of org.apache.clerezza.rdf.core.sparql.ParseException in project stanbol by apache.

the class OpenCalaisEngine method queryModel.

/**
     * Extracts the relevant entity information from the Calais RDF data.
     * The entities and the relted information is extracted by a Sparql query.
     *
     * @param model the Graph representing the Calais data
     *
     * @return a Collection of entity information
     * @throws EngineException on a {@link ParseException} while processing the
     * Sparql query.
     */
public Collection<CalaisEntityOccurrence> queryModel(Graph model) throws EngineException {
    //TODO extract also Geo info (latitude/longitude)?
    String query = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " + "PREFIX p: <http://s.opencalais.com/1/pred/> " + "PREFIX t: <http://s.opencalais.com/1/type/em/e/> " + "SELECT DISTINCT ?id ?did ?name ?type ?dtype ?offset ?length ?exact ?context ?score WHERE { " + "?id p:name ?name ." + "?id rdf:type ?type ." + "?y p:subject ?id ." + "?y p:offset ?offset ." + "?y p:length ?length ." + "?y p:exact ?exact ." + "?y p:detection ?context ." + " OPTIONAL { ?z p:subject ?id . ?z p:relevance ?score . } " + // get disambiguated entity references if available
    " OPTIONAL { ?did p:subject ?id . ?did p:name ?name . ?did rdf:type ?dtype . } " + "FILTER (" + "?type = t:Person || " + "?type = t:City || " + "?type = t:Continent || " + "?type = t:Country || " + "?type = t:ProvinceOrState || " + "?type = t:Region || " + "?type = t:Company || " + "?type = t:Facility || " + "?type = t:Organization " + ")" + "} ";
    Collection<CalaisEntityOccurrence> result = new ArrayList<CalaisEntityOccurrence>();
    try {
        SelectQuery sQuery = (SelectQuery) QueryParser.getInstance().parse(query);
        ResultSet rs = tcManager.executeSparqlQuery(sQuery, model);
        while (rs.hasNext()) {
            SolutionMapping row = rs.next();
            CalaisEntityOccurrence occ = new CalaisEntityOccurrence();
            RDFTerm disambiguated = row.get("did");
            occ.id = (disambiguated == null ? row.get("id") : disambiguated);
            if (onlyNERMode) {
                occ.type = row.get("type");
            } else {
                occ.type = (disambiguated == null ? row.get("type") : row.get("dtype"));
            }
            if (calaisTypeMap != null) {
                IRI mappedType = calaisTypeMap.get(occ.type);
                if (mappedType != null) {
                    occ.type = mappedType;
                }
            }
            occ.name = ((Literal) row.get("name")).getLexicalForm();
            occ.exact = ((Literal) row.get("exact")).getLexicalForm();
            //TODO for html the offsets might not be those of the original document but refer to a cleaned up version?
            occ.offset = Integer.valueOf(((Literal) row.get("offset")).getLexicalForm());
            // remove brackets
            occ.context = ((Literal) row.get("context")).getLexicalForm().replaceAll("[\\[\\]]", "");
            occ.length = Integer.valueOf(((Literal) row.get("length")).getLexicalForm());
            if (row.get("score") != null) {
                occ.relevance = Double.valueOf(((Literal) row.get("score")).getLexicalForm());
            }
            result.add(occ);
        }
    } catch (ParseException e) {
        throw new EngineException("Unable to parse SPARQL query for processing OpenCalais results", e);
    }
    log.info("Found {} occurences", result.size());
    return result;
}
Also used : SelectQuery(org.apache.clerezza.rdf.core.sparql.query.SelectQuery) IRI(org.apache.clerezza.commons.rdf.IRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) SolutionMapping(org.apache.clerezza.rdf.core.sparql.SolutionMapping) Literal(org.apache.clerezza.commons.rdf.Literal) ArrayList(java.util.ArrayList) ResultSet(org.apache.clerezza.rdf.core.sparql.ResultSet) EngineException(org.apache.stanbol.enhancer.servicesapi.EngineException) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm) ParseException(org.apache.clerezza.rdf.core.sparql.ParseException)

Example 5 with ParseException

use of org.apache.clerezza.rdf.core.sparql.ParseException in project stanbol by apache.

the class ClerezzaYard method executeSparqlFieldQuery.

/**
     * Returns the SPARQL result set for a given {@link SparqlFieldQuery} that
     * was executed on this yard
     * @param query the SparqlFieldQuery instance
     * @return the results of the SPARQL query in the yard
     * @throws YardException in case the generated SPARQL query could not be parsed
     * or the generated Query is not an SPARQL SELECT query.
     */
private ResultSet executeSparqlFieldQuery(final SparqlFieldQuery query) throws YardException {
    int limit = QueryUtils.getLimit(query, getConfig().getDefaultQueryResultNumber(), getConfig().getMaxQueryResultNumber());
    SelectQuery sparqlQuery;
    String sparqlQueryString = SparqlQueryUtils.createSparqlSelectQuery(query, false, limit, EndpointTypeEnum.Standard);
    try {
        sparqlQuery = (SelectQuery) QueryParser.getInstance().parse(sparqlQueryString);
    } catch (ParseException e) {
        log.error("ParseException for SPARQL Query in findRepresentation");
        log.error("FieldQuery: " + query);
        log.error("SPARQL Query: " + sparqlQueryString);
        throw new YardException("Unable to parse SPARQL query generated for the parse FieldQuery", e);
    } catch (ClassCastException e) {
        log.error("ClassCastExeption because parsed SPARQL Query is not of Type " + SelectQuery.class);
        log.error("FieldQuery: " + query);
        log.error("SPARQL Query: " + sparqlQueryString);
        throw new YardException("Unable to parse SPARQL SELECT query generated for the parse FieldQuery", e);
    }
    return tcManager.executeSparqlQuery(sparqlQuery, graph);
}
Also used : SelectQuery(org.apache.clerezza.rdf.core.sparql.query.SelectQuery) YardException(org.apache.stanbol.entityhub.servicesapi.yard.YardException) ParseException(org.apache.clerezza.rdf.core.sparql.ParseException)

Aggregations

ParseException (org.apache.clerezza.rdf.core.sparql.ParseException)9 SelectQuery (org.apache.clerezza.rdf.core.sparql.query.SelectQuery)7 Graph (org.apache.clerezza.commons.rdf.Graph)6 ResultSet (org.apache.clerezza.rdf.core.sparql.ResultSet)5 SolutionMapping (org.apache.clerezza.rdf.core.sparql.SolutionMapping)5 IRI (org.apache.clerezza.commons.rdf.IRI)4 UnionGraph (org.apache.clerezza.rdf.utils.UnionGraph)4 NoSuchRecipeException (org.apache.stanbol.rules.base.api.NoSuchRecipeException)4 RecipeConstructionException (org.apache.stanbol.rules.base.api.RecipeConstructionException)4 Literal (org.apache.clerezza.commons.rdf.Literal)3 Recipe (org.apache.stanbol.rules.base.api.Recipe)3 RuleList (org.apache.stanbol.rules.base.api.util.RuleList)3 RDFTerm (org.apache.clerezza.commons.rdf.RDFTerm)2 Query (org.apache.clerezza.rdf.core.sparql.query.Query)2 YardException (org.apache.stanbol.entityhub.servicesapi.yard.YardException)2 NoSuchRuleInRecipeException (org.apache.stanbol.rules.base.api.NoSuchRuleInRecipeException)2 Rule (org.apache.stanbol.rules.base.api.Rule)2 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Consumes (javax.ws.rs.Consumes)1