Search in sources :

Example 6 with Session

use of org.apache.stanbol.ontologymanager.servicesapi.session.Session in project stanbol by apache.

the class SessionManagerImpl method removeSession.

protected synchronized void removeSession(Session session) {
    String id = session.getID();
    Session s2 = sessionsByID.get(id);
    if (session == s2)
        sessionsByID.remove(id);
}
Also used : Session(org.apache.stanbol.ontologymanager.servicesapi.session.Session)

Example 7 with Session

use of org.apache.stanbol.ontologymanager.servicesapi.session.Session in project stanbol by apache.

the class TestOntologyNetworkPersistence method sessionPreservesManagedOntologies.

@Test
public void sessionPreservesManagedOntologies() throws Exception {
    // The kind of thing an idiot would have on his luggage.
    String id = "12345";
    Session session = sessionManager.createSession(id);
    // Anonymous ontologies must preserve their public keys!
    session.addOntology(new GraphContentInputSource(getClass().getResourceAsStream("/ontologies/nameless_ontology.owl")));
    // Same for named ontologies...
    session.addOntology(new GraphContentInputSource(getClass().getResourceAsStream("/ontologies/nonexistentcharacters.owl")));
    // ... and versioned ontologies too.
    session.addOntology(new GraphContentInputSource(getClass().getResourceAsStream("/ontologies/versiontest_v1.owl")));
    session.addOntology(new GraphContentInputSource(getClass().getResourceAsStream("/ontologies/versiontest_v2.owl")));
    Collection<OWLOntologyID> managed = session.listManagedOntologies();
    assertEquals(4, managed.size());
    // Simulate Stanbol going down.
    log.info("Stanbol going down...");
    // but keep the TcProvider
    resetOntologyProvider();
    resetManagers();
    Session ses = sessionManager.getSession(id);
    assertNotNull(ses);
    assertEquals(managed, ses.listManagedOntologies());
    // XXX Remember that only weak equality is implemented.
    assertEquals(session, ses);
}
Also used : GraphContentInputSource(org.apache.stanbol.ontologymanager.sources.clerezza.GraphContentInputSource) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) Session(org.apache.stanbol.ontologymanager.servicesapi.session.Session) Test(org.junit.Test)

Example 8 with Session

use of org.apache.stanbol.ontologymanager.servicesapi.session.Session in project stanbol by apache.

the class TestSessions method testRegisterSession.

@Test
public void testRegisterSession() throws Exception {
    int before = sessionManager.getRegisteredSessionIDs().size();
    Session ses = sessionManager.createSession();
    assertNotNull(ses);
    assertEquals(before + 1, sessionManager.getRegisteredSessionIDs().size());
}
Also used : Session(org.apache.stanbol.ontologymanager.servicesapi.session.Session) Test(org.junit.Test)

Example 9 with Session

use of org.apache.stanbol.ontologymanager.servicesapi.session.Session in project stanbol by apache.

the class SessionManagerImpl method rebuildSessions.

private void rebuildSessions() {
    if (ontologyProvider == null) {
        log.warn("No ontology provider supplied. Cannot rebuild sessions");
        return;
    }
    OntologyNetworkConfiguration struct = ontologyProvider.getOntologyNetworkConfiguration();
    for (String sessionId : struct.getSessionIDs()) {
        long before = System.currentTimeMillis();
        log.debug("Rebuilding session with ID \"{}\"", sessionId);
        Session session;
        try {
            session = createSession(sessionId);
        } catch (DuplicateSessionIDException e) {
            log.warn("Session \"{}\" already exists and will be reused.", sessionId);
            session = getSession(sessionId);
        } catch (SessionLimitException e) {
            log.error("Cannot create session {}. Session limit of {} reached.", sessionId, getActiveSessionLimit());
            break;
        }
        // Register even if some ontologies were to fail to be restored afterwards.
        sessionsByID.put(sessionId, session);
        // Restored sessions are inactive at first.
        session.setActive(false);
        for (OWLOntologyID key : struct.getOntologyKeysForSession(sessionId)) try {
            session.addOntology(new StoredOntologySource(key));
        } catch (MissingOntologyException ex) {
            log.error("Could not find an ontology with public key {} to be managed by session \"{}\". Proceeding to next ontology.", key, sessionId);
            continue;
        } catch (Exception ex) {
            log.error("Exception caught while trying to add ontology with public key " + key + " to rebuilt session \"" + sessionId + "\". Proceeding to next ontology.", ex);
            continue;
        }
        for (String scopeId : struct.getAttachedScopes(sessionId)) {
            /*
                 * The scope is attached by reference, so we won't have to bother checking if the scope has
                 * been rebuilt by then (which could not happen if the SessionManager is being activated
                 * first).
                 */
            session.attachScope(scopeId);
        }
        log.info("Session \"{}\" rebuilt in {} ms.", sessionId, System.currentTimeMillis() - before);
    }
}
Also used : MissingOntologyException(org.apache.stanbol.ontologymanager.servicesapi.collector.MissingOntologyException) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) SessionLimitException(org.apache.stanbol.ontologymanager.servicesapi.session.SessionLimitException) StoredOntologySource(org.apache.stanbol.ontologymanager.servicesapi.io.StoredOntologySource) NonReferenceableSessionException(org.apache.stanbol.ontologymanager.servicesapi.session.NonReferenceableSessionException) MissingOntologyException(org.apache.stanbol.ontologymanager.servicesapi.collector.MissingOntologyException) SessionLimitException(org.apache.stanbol.ontologymanager.servicesapi.session.SessionLimitException) OWLOntologyStorageException(org.semanticweb.owlapi.model.OWLOntologyStorageException) IOException(java.io.IOException) DuplicateSessionIDException(org.apache.stanbol.ontologymanager.servicesapi.session.DuplicateSessionIDException) OntologyNetworkConfiguration(org.apache.stanbol.ontologymanager.ontonet.api.OntologyNetworkConfiguration) Session(org.apache.stanbol.ontologymanager.servicesapi.session.Session) DuplicateSessionIDException(org.apache.stanbol.ontologymanager.servicesapi.session.DuplicateSessionIDException)

Example 10 with Session

use of org.apache.stanbol.ontologymanager.servicesapi.session.Session 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)

Aggregations

Session (org.apache.stanbol.ontologymanager.servicesapi.session.Session)16 OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)5 Scope (org.apache.stanbol.ontologymanager.servicesapi.scope.Scope)4 Test (org.junit.Test)4 IOException (java.io.IOException)3 IRI (org.apache.clerezza.commons.rdf.IRI)3 Triple (org.apache.clerezza.commons.rdf.Triple)3 DuplicateSessionIDException (org.apache.stanbol.ontologymanager.servicesapi.session.DuplicateSessionIDException)3 NonReferenceableSessionException (org.apache.stanbol.ontologymanager.servicesapi.session.NonReferenceableSessionException)3 SessionLimitException (org.apache.stanbol.ontologymanager.servicesapi.session.SessionLimitException)3 HashSet (java.util.HashSet)2 BlankNodeOrIRI (org.apache.clerezza.commons.rdf.BlankNodeOrIRI)2 TripleImpl (org.apache.clerezza.commons.rdf.impl.utils.TripleImpl)2 SessionImpl (org.apache.stanbol.ontologymanager.multiplexer.clerezza.impl.SessionImpl)2 OntologySpace (org.apache.stanbol.ontologymanager.servicesapi.scope.OntologySpace)2 OWLOntology (org.semanticweb.owlapi.model.OWLOntology)2 OWLOntologyCreationException (org.semanticweb.owlapi.model.OWLOntologyCreationException)2 FileNotFoundException (java.io.FileNotFoundException)1 Set (java.util.Set)1 POST (javax.ws.rs.POST)1