Search in sources :

Example 61 with OWLOntologyID

use of org.semanticweb.owlapi.model.OWLOntologyID in project stanbol by apache.

the class TestOntologyReconciliation method namedFromStream.

/*
     * Named ontologies loaded from a data stream should have no aliases and directly reconcile with the
     * ontology IRI.
     */
@Test
public void namedFromStream() throws Exception {
    String location = "/ontologies/naming/named-2.owl";
    OWLOntologyID expectedId = new OWLOntologyID(IRI.create("http://stanbol.apache.org/ontologies/test/naming/named-2"));
    InputStream in = getClass().getResourceAsStream(location);
    in.mark(Integer.MAX_VALUE);
    OWLOntologyManager onMgr = OWLManager.createOWLOntologyManager();
    OWLOntology o1 = onMgr.loadOntologyFromOntologyDocument(in);
    assertFalse(o1.isAnonymous());
    in.reset();
    assertEquals(expectedId, o1.getOntologyID());
    // in = getClass().getResourceAsStream(location); // use if stream cannot be reset
    OWLOntologyID key = ontologyProvider.loadInStore(in, RDF_XML, false);
    assertNotNull(key);
    assertFalse(key.isAnonymous());
    log.info("Named ontology loaded with public key {}", key);
    assertEquals(expectedId, key);
    log.info(" -- (matches actual ontology ID).");
    OWLOntology o1_1 = ontologyProvider.getStoredOntology(key, OWLOntology.class, false);
    assertFalse(o1_1.isAnonymous());
    // Cannot equal OWLOntology objects
    assertEquals(expectedId, o1_1.getOntologyID());
    // Check that axioms match
    log.warn("Plain OWL API seems to be failing to preserve owl:versionInfo. Will test non-annotation axioms only.");
    assertEquals(o1.getTBoxAxioms(false), o1_1.getTBoxAxioms(false));
    log.info(" -- TBox axiom check successful.");
    assertEquals(o1.getABoxAxioms(false), o1_1.getABoxAxioms(false));
    log.info(" -- ABox axiom check successful.");
    // Now check there are no aliases.
    assertSame(0, ontologyProvider.listAliases(expectedId).size());
}
Also used : InputStream(java.io.InputStream) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) Test(org.junit.Test)

Example 62 with OWLOntologyID

use of org.semanticweb.owlapi.model.OWLOntologyID in project stanbol by apache.

the class TestOntologyReconciliation method anonymousFromURL.

/*
     * Anonymous ontologies loaded from a URL must reconcile with a public key that matches the resource URL
     * in its ontology IRI.
     */
@Test
public void anonymousFromURL() throws Exception {
    URL in = getClass().getResource(location_nameless);
    OWLOntologyManager onMgr = OWLManager.createOWLOntologyManager();
    OWLOntology o1 = onMgr.loadOntologyFromOntologyDocument(IRI.create(in));
    assertTrue(o1.isAnonymous());
    // in = getClass().getResourceAsStream(location); // use if stream cannot be reset
    OWLOntologyID key = ontologyProvider.loadInStore(IRI.create(in), RDF_XML, false);
    assertNotNull(key);
    assertFalse(key.isAnonymous());
    log.info("Anonymous ontology loaded with non-anonymous public key {}", key);
    OWLOntology o2 = ontologyProvider.getStoredOntology(key, OWLOntology.class, false);
    assertTrue(o2.isAnonymous());
    // Cannot equal OWLOntology objects
    assertEquals(o1.getAxioms(), o2.getAxioms());
}
Also used : OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) URL(java.net.URL) Test(org.junit.Test)

Example 63 with OWLOntologyID

use of org.semanticweb.owlapi.model.OWLOntologyID in project stanbol by apache.

the class TestOntologyReconciliation method namedFromURL.

/*
     * Named ontologies loaded from an URL must reconcile with both their logical ID and their resource URL
     * (through aliasing).
     */
@Test
public void namedFromURL() throws Exception {
    String location = "/ontologies/naming/named-1.owl";
    OWLOntologyID expectedId = new OWLOntologyID(IRI.create("http://stanbol.apache.org/ontologies/test/naming/named-1"));
    URL url = getClass().getResource(location);
    OWLOntologyManager onMgr = OWLManager.createOWLOntologyManager();
    OWLOntology o1 = onMgr.loadOntologyFromOntologyDocument(IRI.create(url));
    assertFalse(o1.isAnonymous());
    assertEquals(expectedId, o1.getOntologyID());
    // in = getClass().getResourceAsStream(location); // use if stream cannot be reset
    OWLOntologyID key = ontologyProvider.loadInStore(IRI.create(url), RDF_XML, false);
    assertNotNull(key);
    assertFalse(key.isAnonymous());
    log.info("Named ontology loaded with public key {}", key);
    assertEquals(expectedId, key);
    log.info(" -- (matches actual ontology ID).");
    OWLOntology o1_1 = ontologyProvider.getStoredOntology(key, OWLOntology.class, false);
    assertFalse(o1_1.isAnonymous());
    // Cannot equal OWLOntology objects
    assertEquals(expectedId, o1_1.getOntologyID());
    // Check that axioms match
    log.warn("Plain OWL API seems to be failing to preserve owl:versionInfo. Will test non-annotation axioms only.");
    assertEquals(o1.getTBoxAxioms(false), o1_1.getTBoxAxioms(false));
    log.info(" -- TBox axiom check successful.");
    assertEquals(o1.getABoxAxioms(false), o1_1.getABoxAxioms(false));
    log.info(" -- ABox axiom check successful.");
    // Now check the alias from the physical URL
    OWLOntologyID aliasId = new OWLOntologyID(IRI.create(url));
    Set<OWLOntologyID> aliases = ontologyProvider.listAliases(expectedId);
    assertSame(1, aliases.size());
    assertTrue(aliases.contains(aliasId));
    // Check that it actually *is* an alias
    OWLOntology alias = ontologyProvider.getStoredOntology(aliasId, OWLOntology.class);
    assertNotNull(alias);
    assertEquals(expectedId, alias.getOntologyID());
    // Both ontologies come from the ontology provider and should have preserved ontology annotations.
    // Therefore ass axioms should match safely.
    assertEquals(o1_1.getAxioms(), alias.getAxioms());
}
Also used : OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) URL(java.net.URL) Test(org.junit.Test)

Example 64 with OWLOntologyID

use of org.semanticweb.owlapi.model.OWLOntologyID 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 65 with OWLOntologyID

use of org.semanticweb.owlapi.model.OWLOntologyID in project stanbol by apache.

the class JenaToOwlConvert method ModelOwlToJenaConvert.

// //////////////////////////////////////////////////////////////////////////////
/**
     * This function converts an ontology object from OWLapi to Jena
     * 
     * @param owlmodel
     *            {An OWLOntology object}
     * @param format
     *            {RDF/XML or TURTLE}
     * @return {An OntModel that is a Jena object}
     */
public synchronized OntModel ModelOwlToJenaConvert(OWLOntology owlmodel, String format) {
    while (availablemain == false) {
        try {
            wait();
        } catch (InterruptedException e) {
            System.err.println("ModelOwlToJenaConvert::: " + e);
        }
    }
    availablemain = false;
    OWLOntologyID id;
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        OWLOntologyManager owlmanager = owlmodel.getOWLOntologyManager();
        format = format.trim();
        if (format.equals("TURTLE") || format.equals("RDF/XML")) {
            if (format.equals("TURTLE"))
                owlmanager.setOntologyFormat(owlmodel, new TurtleOntologyFormat());
            if (format.equals("RDF/XML"))
                owlmanager.setOntologyFormat(owlmodel, new RDFXMLOntologyFormat());
            OWLOntologyFormat owlformat = owlmanager.getOntologyFormat(owlmodel);
            owlmanager.saveOntology(owlmodel, owlformat, out);
            OntModel jenamodel = ModelFactory.createOntologyModel();
            id = owlmodel.getOntologyID();
            jenamodel.read(new ByteArrayInputStream(out.toByteArray()), id.toString().replace("<", "").replace(">", ""), format);
            availablemain = true;
            notifyAll();
            return jenamodel;
        } else {
            System.err.println("The only format supported is RDF/XML or TURTLE. Please check the format!");
            availablemain = true;
            notifyAll();
            return null;
        }
    } catch (OWLOntologyStorageException eos) {
        System.err.print("ModelOwlToJenaConvert::: ");
        eos.printStackTrace();
        return null;
    }
}
Also used : TurtleOntologyFormat(org.coode.owlapi.turtle.TurtleOntologyFormat) OWLOntologyFormat(org.semanticweb.owlapi.model.OWLOntologyFormat) ByteArrayInputStream(java.io.ByteArrayInputStream) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) OntModel(com.hp.hpl.jena.ontology.OntModel) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) RDFXMLOntologyFormat(org.semanticweb.owlapi.io.RDFXMLOntologyFormat) OWLOntologyStorageException(org.semanticweb.owlapi.model.OWLOntologyStorageException)

Aggregations

OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)86 OWLOntology (org.semanticweb.owlapi.model.OWLOntology)31 Test (org.junit.Test)27 HashSet (java.util.HashSet)22 OWLOntologyCreationException (org.semanticweb.owlapi.model.OWLOntologyCreationException)22 InputStream (java.io.InputStream)20 BlankNodeOrIRI (org.apache.clerezza.commons.rdf.BlankNodeOrIRI)19 Triple (org.apache.clerezza.commons.rdf.Triple)19 OWLOntologyManager (org.semanticweb.owlapi.model.OWLOntologyManager)19 IRI (org.apache.clerezza.commons.rdf.IRI)17 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)16 IRI (org.semanticweb.owlapi.model.IRI)14 RDFTerm (org.apache.clerezza.commons.rdf.RDFTerm)13 IOException (java.io.IOException)12 UnmodifiableOntologyCollectorException (org.apache.stanbol.ontologymanager.servicesapi.collector.UnmodifiableOntologyCollectorException)12 WebApplicationException (javax.ws.rs.WebApplicationException)11 Graph (org.apache.clerezza.commons.rdf.Graph)10 AddImport (org.semanticweb.owlapi.model.AddImport)10 Path (javax.ws.rs.Path)9 OntologySpace (org.apache.stanbol.ontologymanager.servicesapi.scope.OntologySpace)8