Search in sources :

Example 6 with RefactoringException

use of org.apache.stanbol.rules.refactor.api.RefactoringException in project stanbol by apache.

the class RefactorResource method performRefactoring.

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(value = { TURTLE, RDF_XML, MANCHESTER_OWL, FUNCTIONAL_OWL, OWL_XML, RDF_JSON, X_TURTLE })
public Response performRefactoring(MultiPartBody data, @Context HttpHeaders headers) {
    String recipe = null;
    InputStream input = null;
    if (data.getTextParameterValues("recipe") != null) {
        recipe = data.getTextParameterValues("recipe")[0];
    }
    if (data.getFormFileParameterValues("input") != null) {
        input = new ByteArrayInputStream(data.getFormFileParameterValues("input")[0].getContent());
    }
    if (recipe == null || input == null) {
        throw new WebApplicationException(BAD_REQUEST);
    }
    // Refactorer semionRefactorer = semionManager.getRegisteredRefactorer();
    ResponseBuilder rb;
    Recipe rcp;
    try {
        URI uri = new URI(recipe);
        if (uri != null && uri.getScheme() == null) {
            recipe = "urn:" + recipe;
            log.info("The recipe ID is a URI without scheme. The ID is set to " + recipe);
        }
        IRI recipeID = new IRI(recipe);
        rcp = ruleStore.getRecipe(recipeID);
        OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
        OWLOntology inputOntology = manager.loadOntologyFromOntologyDocument(input);
        Graph tripleCollection = refactorer.graphRefactoring(OWLAPIToClerezzaConverter.owlOntologyToClerezzaGraph(inputOntology), rcp);
        OWLOntology outputOntology = OWLAPIToClerezzaConverter.clerezzaGraphToOWLOntology(tripleCollection);
        rb = Response.ok(outputOntology);
        MediaType mediaType = MediaTypeUtil.getAcceptableMediaType(headers, null);
        if (mediaType != null)
            rb.header(HttpHeaders.CONTENT_TYPE, mediaType);
    } catch (NoSuchRecipeException e) {
        rb = Response.status(NOT_FOUND);
        log.error(e.getMessage(), e);
    } catch (RecipeConstructionException e) {
        rb = Response.status(NO_CONTENT);
        log.error(e.getMessage(), e);
    } catch (OWLOntologyCreationException e) {
        rb = Response.status(PRECONDITION_FAILED);
        log.error(e.getMessage(), e);
    } catch (RefactoringException e) {
        rb = Response.status(INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (URISyntaxException e) {
        rb = Response.status(NOT_ACCEPTABLE);
        log.error(e.getMessage(), e);
    }
    //        addCORSOrigin(servletContext, rb, headers);
    return rb.build();
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) WebApplicationException(javax.ws.rs.WebApplicationException) Recipe(org.apache.stanbol.rules.base.api.Recipe) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) NoSuchRecipeException(org.apache.stanbol.rules.base.api.NoSuchRecipeException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) RecipeConstructionException(org.apache.stanbol.rules.base.api.RecipeConstructionException) Graph(org.apache.clerezza.commons.rdf.Graph) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) ByteArrayInputStream(java.io.ByteArrayInputStream) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) MediaType(javax.ws.rs.core.MediaType) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) RefactoringException(org.apache.stanbol.rules.refactor.api.RefactoringException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 7 with RefactoringException

use of org.apache.stanbol.rules.refactor.api.RefactoringException in project stanbol by apache.

the class RefactoringTest method easyRefactoringTest.

@Test
public void easyRefactoringTest() throws Exception {
    Recipe recipe = store.getRecipe(new IRI("http://incubator.apache.com/stanbol/rules/refactor/test/recipeA"));
    try {
        Graph tc = refactorer.graphRefactoring(tripleCollection, recipe);
        Assert.assertNotNull(tc);
    } catch (RefactoringException e) {
        fail("Error while refactoring.");
    }
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) Graph(org.apache.clerezza.commons.rdf.Graph) Recipe(org.apache.stanbol.rules.base.api.Recipe) RefactoringException(org.apache.stanbol.rules.refactor.api.RefactoringException) Test(org.junit.Test)

Example 8 with RefactoringException

use of org.apache.stanbol.rules.refactor.api.RefactoringException in project stanbol by apache.

the class RefactoringTest method refactoringWithARecipeWithNotSupportedAtoms.

@Test
public void refactoringWithARecipeWithNotSupportedAtoms() {
    String separator = System.getProperty("line.separator");
    // the localname atom is not supported by the clerezza adapter and should throw an exception.
    String rule = "kres = <http://kres.iks-project.eu/ontology.owl#> . " + separator + "foaf = <http://xmlns.com/foaf/0.1/> . " + separator + "rule2[ is(kres:Person, ?x) . same(localname(?y), \"text\") -> is(foaf:Person, ?x) ]";
    try {
        Recipe recipe = store.getRecipe(new IRI("http://incubator.apache.com/stanbol/rules/refactor/test/recipeA"));
        recipe = store.addRulesToRecipe(recipe, rule, "Test");
        refactorer.graphRefactoring(new IRI("http://incubator.apache.com/stanbol/rules/refactor/test/refactoredGraph"), new IRI("http://incubator.apache.com/stanbol/rules/refactor/test/graph"), new IRI("http://incubator.apache.com/stanbol/rules/refactor/test/recipeA"));
    } catch (NoSuchRecipeException e) {
        Assert.fail();
    } catch (RecipeConstructionException e) {
        Assert.fail();
    } catch (RefactoringException e) {
        Assert.assertTrue(e.getMessage(), true);
    }
}
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) RefactoringException(org.apache.stanbol.rules.refactor.api.RefactoringException) RecipeConstructionException(org.apache.stanbol.rules.base.api.RecipeConstructionException) Test(org.junit.Test)

Example 9 with RefactoringException

use of org.apache.stanbol.rules.refactor.api.RefactoringException 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 10 with RefactoringException

use of org.apache.stanbol.rules.refactor.api.RefactoringException in project stanbol by apache.

the class RefactorResource method applyRefactoring.

//    public RefactorResource(@Context ServletContext servletContext) {
//        refactorer = (Refactorer) ContextHelper.getServiceFromContext(Refactorer.class, servletContext);
//        if (refactorer == null) throw new IllegalStateException("Refactorer missing in ServletContext");
//        ruleStore = (RuleStore) ContextHelper.getServiceFromContext(RuleStore.class, servletContext);
//        if (ruleStore == null) throw new IllegalStateException("RuleStore missing in ServletContext");
//    }
/**
     * The apply mode allows the client to compose a recipe, by mean of string containg the rules, and apply
     * it "on the fly" to the graph in input.
     * 
     * @param recipe
     *            String
     * @param input
     *            InputStream
     * @return a Response containing the transformed graph
     */
@POST
@Path("/apply")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(value = { TURTLE, RDF_XML, MANCHESTER_OWL, FUNCTIONAL_OWL, OWL_XML, RDF_JSON, X_TURTLE })
public Response applyRefactoring(MultiPartBody data, @Context HttpHeaders headers) {
    String recipe = null;
    InputStream input = null;
    if (data.getTextParameterValues(recipe) != null) {
        recipe = data.getTextParameterValues(recipe)[0];
    }
    if (data.getFormFileParameterValues("input") != null) {
        input = new ByteArrayInputStream(data.getFormFileParameterValues("input")[0].getContent());
    }
    if (recipe == null || input == null) {
        throw new WebApplicationException(BAD_REQUEST);
    }
    ResponseBuilder rb;
    OWLOntology output = null;
    try {
        output = doRefactoring(input, RuleParserImpl.parse("http://incubator.apache.com/stanbol/rules/refactor/", recipe));
    } catch (OWLOntologyCreationException e1) {
        throw new WebApplicationException(e1, INTERNAL_SERVER_ERROR);
    } catch (RefactoringException e1) {
        throw new WebApplicationException(e1, BAD_REQUEST);
    }
    if (output != null) {
        rb = Response.ok(output);
        MediaType mediaType = MediaTypeUtil.getAcceptableMediaType(headers, null);
        if (mediaType != null)
            rb.header(HttpHeaders.CONTENT_TYPE, mediaType);
    } else
        rb = Response.status(NOT_FOUND);
    //        addCORSOrigin(servletContext, rb, headers);
    return rb.build();
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) MediaType(javax.ws.rs.core.MediaType) RefactoringException(org.apache.stanbol.rules.refactor.api.RefactoringException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Aggregations

RefactoringException (org.apache.stanbol.rules.refactor.api.RefactoringException)10 Graph (org.apache.clerezza.commons.rdf.Graph)6 IRI (org.apache.clerezza.commons.rdf.IRI)6 NoSuchRecipeException (org.apache.stanbol.rules.base.api.NoSuchRecipeException)5 Recipe (org.apache.stanbol.rules.base.api.Recipe)5 WebApplicationException (javax.ws.rs.WebApplicationException)4 MediaType (javax.ws.rs.core.MediaType)4 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)4 RecipeConstructionException (org.apache.stanbol.rules.base.api.RecipeConstructionException)4 OWLOntology (org.semanticweb.owlapi.model.OWLOntology)4 OWLOntologyCreationException (org.semanticweb.owlapi.model.OWLOntologyCreationException)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 InputStream (java.io.InputStream)3 Consumes (javax.ws.rs.Consumes)3 POST (javax.ws.rs.POST)3 Produces (javax.ws.rs.Produces)3 Test (org.junit.Test)3 List (java.util.List)2 Path (javax.ws.rs.Path)2 ImmutableGraph (org.apache.clerezza.commons.rdf.ImmutableGraph)2