Search in sources :

Example 16 with NoSuchRecipeException

use of org.apache.stanbol.rules.base.api.NoSuchRecipeException in project stanbol by apache.

the class ClerezzaRuleStore method findRulesByDescription.

@Override
public RuleList findRulesByDescription(String term) {
    String sparql = "SELECT ?recipe ?rule ?description " + "WHERE { " + "?recipe " + Symbols.hasRule + " ?rule . " + "?rule " + Symbols.description + " ?description . " + "FILTER (regex(?description, \"" + 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 17 with NoSuchRecipeException

use of org.apache.stanbol.rules.base.api.NoSuchRecipeException in project stanbol by apache.

the class ClerezzaRuleStore method getRecipe.

@Override
public Recipe getRecipe(IRI recipeID) throws NoSuchRecipeException, RecipeConstructionException {
    log.info("Called get recipe for id: " + recipeID);
    Graph recipeGraph = null;
    /**
         * Throw a NoSuchRecipeException in case of the TcManager throws a NoSuchEntityException with respect
         * to IRI representing the recipe.
         */
    try {
        recipeGraph = tcManager.getGraph(recipeID);
    } catch (NoSuchEntityException e) {
        throw new NoSuchRecipeException(recipeID.toString());
    }
    Iterator<Triple> descriptions = recipeGraph.filter(null, Symbols.description, null);
    String recipeDescription = null;
    if (descriptions != null && descriptions.hasNext()) {
        recipeDescription = descriptions.next().getObject().toString();
    }
    String query = "SELECT ?rule ?ruleName ?ruleBody ?ruleHead " + "WHERE { " + "	" + recipeID.toString() + " " + Symbols.hasRule.toString() + " ?rule . " + "	?rule " + Symbols.ruleName.toString() + " ?ruleName . " + "	?rule " + Symbols.ruleBody.toString() + " ?ruleBody . " + "	?rule " + Symbols.ruleHead.toString() + " ?ruleHead . " + "}";
    Query sparql;
    try {
        sparql = QueryParser.getInstance().parse(query);
        ResultSet resultSet = tcManager.executeSparqlQuery((SelectQuery) sparql, recipeGraph);
        StringBuilder stanbolRulesBuilder = new StringBuilder();
        boolean firstIteration = true;
        while (resultSet.hasNext()) {
            SolutionMapping solutionMapping = resultSet.next();
            RDFTerm nameResource = solutionMapping.get("ruleName");
            RDFTerm bodyResource = solutionMapping.get("ruleBody");
            RDFTerm headResource = solutionMapping.get("ruleHead");
            StringBuilder stanbolRuleBuilder = new StringBuilder();
            stanbolRuleBuilder.append(((Literal) nameResource).getLexicalForm());
            stanbolRuleBuilder.append("[");
            stanbolRuleBuilder.append(((Literal) bodyResource).getLexicalForm());
            stanbolRuleBuilder.append(" -> ");
            stanbolRuleBuilder.append(((Literal) headResource).getLexicalForm());
            stanbolRuleBuilder.append("]");
            if (!firstIteration) {
                stanbolRulesBuilder.append(" . ");
            } else {
                firstIteration = false;
            }
            String stanbolSyntax = stanbolRuleBuilder.toString();
            log.info("Rule content {}", stanbolSyntax);
            stanbolRulesBuilder.append(stanbolSyntax);
        }
        String stanbolSyntax = stanbolRulesBuilder.toString();
        RuleList ruleList = null;
        if (!stanbolSyntax.isEmpty()) {
            String namespace = recipeID.toString().substring(1, recipeID.toString().length() - 1) + "/";
            ruleList = RuleParserImpl.parse(namespace, stanbolSyntax).getRuleList();
        }
        return new RecipeImpl(recipeID, recipeDescription, ruleList);
    } catch (ParseException e) {
        throw new RecipeConstructionException(e);
    }
}
Also used : SolutionMapping(org.apache.clerezza.rdf.core.sparql.SolutionMapping) RuleList(org.apache.stanbol.rules.base.api.util.RuleList) Query(org.apache.clerezza.rdf.core.sparql.query.Query) SelectQuery(org.apache.clerezza.rdf.core.sparql.query.SelectQuery) NoSuchRecipeException(org.apache.stanbol.rules.base.api.NoSuchRecipeException) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm) NoSuchEntityException(org.apache.clerezza.rdf.core.access.NoSuchEntityException) RecipeConstructionException(org.apache.stanbol.rules.base.api.RecipeConstructionException) Triple(org.apache.clerezza.commons.rdf.Triple) UnionGraph(org.apache.clerezza.rdf.utils.UnionGraph) Graph(org.apache.clerezza.commons.rdf.Graph) ResultSet(org.apache.clerezza.rdf.core.sparql.ResultSet) ParseException(org.apache.clerezza.rdf.core.sparql.ParseException)

Example 18 with NoSuchRecipeException

use of org.apache.stanbol.rules.base.api.NoSuchRecipeException in project stanbol by apache.

the class RefactorEnhancementEngine method computeEnhancements.

@Override
public void computeEnhancements(ContentItem ci) throws EngineException {
    // Prepare the OntoNet environment. First we create the OntoNet session in which run the whole
    final Session session;
    try {
        session = sessionManager.createSession();
    } catch (SessionLimitException e1) {
        throw new EngineException("OntoNet session quota reached. The Refactor Engine requires its own new session to execute.");
    }
    if (session == null)
        throw new EngineException("Failed to create OntoNet session. The Refactor Engine requires its own new session to execute.");
    log.debug("Refactor enhancement job will run in session '{}'.", session.getID());
    // Retrieve and filter the metadata graph for entities recognized by the engines.
    final Graph metadataGraph = ci.getMetadata(), signaturesGraph = new IndexedGraph();
    // FIXME the Stanbol Enhancer vocabulary should be retrieved from somewhere in the enhancer API.
    final IRI ENHANCER_ENTITY_REFERENCE = new IRI("http://fise.iks-project.eu/ontology/entity-reference");
    Iterator<Triple> tripleIt = metadataGraph.filter(null, ENHANCER_ENTITY_REFERENCE, null);
    while (tripleIt.hasNext()) {
        // Get the entity URI
        RDFTerm obj = tripleIt.next().getObject();
        if (!(obj instanceof IRI)) {
            log.warn("Invalid IRI for entity reference {}. Skipping.", obj);
            continue;
        }
        final String entityReference = ((IRI) obj).getUnicodeString();
        log.debug("Trying to resolve entity {}", entityReference);
        // Populate the entity signatures graph, by querying either the Entity Hub or the dereferencer.
        if (engineConfiguration.isEntityHubUsed()) {
            Graph result = populateWithEntity(entityReference, signaturesGraph);
            if (result != signaturesGraph && result != null) {
                log.warn("Entity Hub query added triples to a new graph instead of populating the supplied one!" + " New signatures will be discarded.");
            }
        } else
            try {
                OntologyInputSource<Graph> source = new GraphContentSourceWithPhysicalIRI(dereferencer.resolve(entityReference), org.semanticweb.owlapi.model.IRI.create(entityReference));
                signaturesGraph.addAll(source.getRootOntology());
            } catch (FileNotFoundException e) {
                log.error("Failed to dereference entity " + entityReference + ". Skipping.", e);
                continue;
            }
    }
    try {
        /*
             * The dedicated session for this job will store the following: (1) all the (merged) signatures
             * for all detected entities; (2) the original content metadata graph returned earlier in the
             * chain.
             * 
             * There is no chance that (2) could be null, as it was previously controlled by the JobManager
             * through the canEnhance() method and the computeEnhancement is always called iff the former
             * returns true.
             */
        session.addOntology(new GraphSource(signaturesGraph));
        session.addOntology(new GraphSource(metadataGraph));
    } catch (UnmodifiableOntologyCollectorException e1) {
        throw new EngineException("Cannot add enhancement graph to OntoNet session for refactoring", e1);
    }
    try {
        /*
             * Export the entire session (incl. entities and enhancement graph) as a single merged ontology.
             * 
             * TODO the refactorer should have methods to accommodate an OntologyCollector directly instead.
             */
        OWLOntology ontology = session.export(OWLOntology.class, true);
        log.debug("Refactoring recipe IRI is : " + engineConfiguration.getRecipeId());
        /*
             * We pass the ontology and the recipe IRI to the Refactor that returns the refactored graph
             * expressed by using the given vocabulary.
             * 
             * To perform the refactoring of the ontology to a given vocabulary we use the Stanbol Refactor.
             */
        Recipe recipe = ruleStore.getRecipe(new IRI(engineConfiguration.getRecipeId()));
        log.debug("Recipe {} contains {} rules.", recipe, recipe.getRuleList().size());
        log.debug("The ontology to be refactor is {}", ontology);
        Graph tc = refactorer.graphRefactoring(OWLAPIToClerezzaConverter.owlOntologyToClerezzaGraph(ontology), recipe);
        /*
             * The newly generated ontology is converted to Clarezza format and then added os substitued to
             * the old mGraph.
             */
        if (engineConfiguration.isInGraphAppendMode()) {
            log.debug("Metadata of the content will replace old ones.", this);
        } else {
            metadataGraph.clear();
            log.debug("Content metadata will be appended to the existing ones.", this);
        }
        metadataGraph.addAll(tc);
    } catch (RefactoringException e) {
        String msg = "Refactor engine execution failed on content item " + ci + ".";
        log.error(msg, e);
        throw new EngineException(msg, e);
    } catch (NoSuchRecipeException e) {
        String msg = "Refactor engine could not find recipe " + engineConfiguration.getRecipeId() + " to refactor content item " + ci + ".";
        log.error(msg, e);
        throw new EngineException(msg, e);
    } catch (Exception e) {
        throw new EngineException("Refactor Engine has failed.", e);
    } finally {
        /*
             * The session needs to be destroyed anyhow.
             * 
             * Clear contents before destroying (FIXME only do this until this is implemented in the
             * destroySession() method).
             */
        for (OWLOntologyID id : session.listManagedOntologies()) {
            try {
                String key = ontologyProvider.getKey(id.getOntologyIRI());
                ontologyProvider.getStore().deleteGraph(new IRI(key));
            } catch (Exception ex) {
                log.error("Failed to delete triple collection " + id, ex);
                continue;
            }
        }
        sessionManager.destroySession(session.getID());
    }
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) Recipe(org.apache.stanbol.rules.base.api.Recipe) NoSuchRecipeException(org.apache.stanbol.rules.base.api.NoSuchRecipeException) EngineException(org.apache.stanbol.enhancer.servicesapi.EngineException) FileNotFoundException(java.io.FileNotFoundException) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm) SessionLimitException(org.apache.stanbol.ontologymanager.servicesapi.session.SessionLimitException) EngineException(org.apache.stanbol.enhancer.servicesapi.EngineException) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) RecipeConstructionException(org.apache.stanbol.rules.base.api.RecipeConstructionException) ConfigurationException(org.osgi.service.cm.ConfigurationException) RefactoringException(org.apache.stanbol.rules.refactor.api.RefactoringException) FileNotFoundException(java.io.FileNotFoundException) RecipeEliminationException(org.apache.stanbol.rules.base.api.RecipeEliminationException) NoSuchRecipeException(org.apache.stanbol.rules.base.api.NoSuchRecipeException) SessionLimitException(org.apache.stanbol.ontologymanager.servicesapi.session.SessionLimitException) UnmodifiableOntologyCollectorException(org.apache.stanbol.ontologymanager.servicesapi.collector.UnmodifiableOntologyCollectorException) AlreadyExistingRecipeException(org.apache.stanbol.rules.base.api.AlreadyExistingRecipeException) DuplicateIDException(org.apache.stanbol.ontologymanager.servicesapi.collector.DuplicateIDException) IOException(java.io.IOException) Triple(org.apache.clerezza.commons.rdf.Triple) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) Graph(org.apache.clerezza.commons.rdf.Graph) UnmodifiableOntologyCollectorException(org.apache.stanbol.ontologymanager.servicesapi.collector.UnmodifiableOntologyCollectorException) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) GraphSource(org.apache.stanbol.ontologymanager.sources.clerezza.GraphSource) OntologyInputSource(org.apache.stanbol.ontologymanager.servicesapi.io.OntologyInputSource) RefactoringException(org.apache.stanbol.rules.refactor.api.RefactoringException) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) Session(org.apache.stanbol.ontologymanager.servicesapi.session.Session)

Example 19 with NoSuchRecipeException

use of org.apache.stanbol.rules.base.api.NoSuchRecipeException in project stanbol by apache.

the class RulesResource method getRule.

/**
     * Get a recipe from the rule base (that is the ontology that contains the rules and the recipe). <br/>
     * If the second parameter is not null then the method returns the rule in the recipe identified by that
     * parameter. <br/>
     * 
     * curl -v -X GET http://localhost:8080/kres/rule/http
     * ://kres.iks-project.eu/ontology/meta/rmi.owl#ProvaParentRule
     * 
     * @param uri
     *            {A string contains the IRI full name of the rule.}
     * @return Return: <br/>
     *         200 The rule is retrieved (import declarations point to KReS Services) <br/>
     *         404 The rule does not exists in the manager <br/>
     *         500 Some error occurred
     * 
     */
@GET
@Path("/recipe/{recipe:.+}")
@Produces(value = { KRFormat.RDF_XML, KRFormat.TURTLE, KRFormat.OWL_XML, KRFormat.RDF_JSON, KRFormat.FUNCTIONAL_OWL, KRFormat.MANCHESTER_OWL, MediaType.TEXT_PLAIN })
public Response getRule(@PathParam("recipe") String recipeID, @QueryParam("rule") String ruleID, @Context HttpHeaders headers) {
    Recipe recipe;
    Rule rule;
    ResponseBuilder responseBuilder;
    try {
        URI uri = new URI(recipeID);
        if (uri.getScheme() == null) {
            recipeID = "urn:" + recipeID;
            log.info("The recipe ID is a URI without scheme. The ID is set to " + recipeID);
        }
        recipe = ruleStore.getRecipe(new IRI(recipeID));
        if (ruleID != null && !ruleID.isEmpty()) {
            rule = ruleStore.getRule(recipe, new IRI(ruleID));
            RuleList ruleList = new RuleList();
            ruleList.add(rule);
            recipe = new RecipeImpl(recipe.getRecipeID(), recipe.getRecipeDescription(), ruleList);
        }
        responseBuilder = Response.ok(recipe);
    } catch (NoSuchRecipeException e) {
        log.error(e.getMessage(), e);
        responseBuilder = Response.status(Status.NOT_FOUND);
    } catch (RecipeConstructionException e) {
        log.error(e.getMessage(), e);
        responseBuilder = Response.status(Status.NO_CONTENT);
    } catch (NoSuchRuleInRecipeException e) {
        log.error(e.getMessage(), e);
        responseBuilder = Response.status(Status.NOT_FOUND);
    } catch (URISyntaxException e) {
        log.error(e.getMessage(), e);
        responseBuilder = Response.status(Status.NOT_ACCEPTABLE);
    }
    //        addCORSOrigin(servletContext, responseBuilder, headers);
    return responseBuilder.build();
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) RuleList(org.apache.stanbol.rules.base.api.util.RuleList) NoSuchRuleInRecipeException(org.apache.stanbol.rules.base.api.NoSuchRuleInRecipeException) Recipe(org.apache.stanbol.rules.base.api.Recipe) RecipeImpl(org.apache.stanbol.rules.manager.RecipeImpl) NoSuchRecipeException(org.apache.stanbol.rules.base.api.NoSuchRecipeException) Rule(org.apache.stanbol.rules.base.api.Rule) URISyntaxException(java.net.URISyntaxException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) URI(java.net.URI) RecipeConstructionException(org.apache.stanbol.rules.base.api.RecipeConstructionException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

NoSuchRecipeException (org.apache.stanbol.rules.base.api.NoSuchRecipeException)19 RecipeConstructionException (org.apache.stanbol.rules.base.api.RecipeConstructionException)17 IRI (org.apache.clerezza.commons.rdf.IRI)16 Recipe (org.apache.stanbol.rules.base.api.Recipe)15 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)8 Graph (org.apache.clerezza.commons.rdf.Graph)7 URI (java.net.URI)6 URISyntaxException (java.net.URISyntaxException)6 Path (javax.ws.rs.Path)6 Produces (javax.ws.rs.Produces)6 GET (javax.ws.rs.GET)5 NoSuchRuleInRecipeException (org.apache.stanbol.rules.base.api.NoSuchRuleInRecipeException)5 Rule (org.apache.stanbol.rules.base.api.Rule)5 RuleList (org.apache.stanbol.rules.base.api.util.RuleList)5 RefactoringException (org.apache.stanbol.rules.refactor.api.RefactoringException)5 ParseException (org.apache.clerezza.rdf.core.sparql.ParseException)4 ResultSet (org.apache.clerezza.rdf.core.sparql.ResultSet)4 SolutionMapping (org.apache.clerezza.rdf.core.sparql.SolutionMapping)4 SelectQuery (org.apache.clerezza.rdf.core.sparql.query.SelectQuery)4 UnionGraph (org.apache.clerezza.rdf.utils.UnionGraph)4