Search in sources :

Example 21 with OWLOntologyID

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

the class ScopeResource method managedOntologyGetGraph.

/**
 * Gets the ontology with the given identifier in its version managed by the session.
 *
 * @param sessionId
 *            the session identifier.
 * @param ontologyId
 *            the ontology identifier.
 * @param uriInfo
 * @param headers
 * @return the requested managed ontology, or {@link Status#NOT_FOUND} if either the sessionn does not
 *         exist, or the if the ontology either does not exist or is not managed.
 */
@GET
@Path("/{ontologyId:.+}")
@Produces(value = { APPLICATION_JSON, N3, N_TRIPLE, RDF_JSON })
public Response managedOntologyGetGraph(@PathParam("scopeid") String scopeid, @PathParam("ontologyId") String ontologyId, @DefaultValue("false") @QueryParam("merge") boolean merge, @Context UriInfo uriInfo, @Context HttpHeaders headers) {
    log.debug("Absolute URL Path {}", uriInfo.getRequestUri());
    log.debug("Ontology ID {}", ontologyId);
    ResponseBuilder rb;
    scope = onm.getScope(scopeid);
    if (scope == null)
        rb = Response.status(NOT_FOUND);
    else {
        IRI prefix = IRI.create(getPublicBaseUri() + "ontonet/ontology/");
        ImmutableGraph o = null;
        OWLOntologyID id = OntologyUtils.decode(ontologyId);
        OntologySpace spc = scope.getCustomSpace();
        if (spc != null && spc.hasOntology(id)) {
            o = spc.getOntology(id, ImmutableGraph.class, merge, prefix);
        } else {
            spc = scope.getCoreSpace();
            if (spc != null && spc.hasOntology(id))
                o = spc.getOntology(id, ImmutableGraph.class, merge, prefix);
        }
        if (o == null)
            rb = Response.status(NOT_FOUND);
        else
            rb = Response.ok(o);
    }
    // addCORSOrigin(servletContext, rb, headers);
    return rb.build();
}
Also used : IRI(org.semanticweb.owlapi.model.IRI) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) OntologySpace(org.apache.stanbol.ontologymanager.servicesapi.scope.OntologySpace) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 22 with OWLOntologyID

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

the class ScopeResource method manageOntology.

/**
 * Tells the scope that it should manage the ontology obtained by parsing the supplied content.<br>
 * <br>
 * Note that the PUT method cannot be used, as it is not possible to predict what ID the ontology will
 * have until it is parsed.
 *
 * @param content
 *            the ontology content
 * @return {@link Status#OK} if the addition was successful, {@link Status#NOT_FOUND} if there is no such
 *         session at all, {@link Status#FORBIDDEN} if the session is locked or cannot modified for some
 *         other reason, {@link Status#INTERNAL_SERVER_ERROR} if some other error occurs.
 */
@POST
@Consumes(value = { RDF_XML, OWL_XML, N_TRIPLE, N3, TURTLE, X_TURTLE, FUNCTIONAL_OWL, MANCHESTER_OWL, RDF_JSON })
public Response manageOntology(InputStream content, @PathParam("scopeid") String scopeid, @Context HttpHeaders headers) {
    long before = System.currentTimeMillis();
    ResponseBuilder rb;
    scope = onm.getScope(scopeid);
    if (// Always check session first
    scope == null)
        // Always check session first
        rb = Response.status(NOT_FOUND);
    else
        try {
            MediaType mt = headers.getMediaType();
            log.debug("POST content claimed to be of type {}.", mt);
            OWLOntologyID key = scope.getCustomSpace().addOntology(/*
             * For the time being, REST services operate in-memory (i.e. no TcProvider is supplied to the
             * input source). This means that only the final processed graph is stored.
             * 
             * TODO : we might find a reason to change that in the future.
             */
            new GraphContentInputSource(content, mt.toString(), ontologyProvider.getStore()));
            if (key == null || key.isAnonymous()) {
                log.error("FAILED parse with media type {}.", mt);
                throw new WebApplicationException(INTERNAL_SERVER_ERROR);
            }
            // FIXME ugly but will have to do for the time being
            log.debug("SUCCESS parse with media type {}.", mt);
            // key.split("::")[1];
            String uri = OntologyUtils.encode(key);
            // uri = uri.substring((ontologyProvider.getGraphPrefix() + "::").length());
            URI created = null;
            if (uri != null && !uri.isEmpty()) {
                created = getCreatedResource(uri);
                rb = Response.created(created);
            } else
                rb = Response.ok();
            log.info("POST request for ontology addition completed in {} ms.", (System.currentTimeMillis() - before));
            log.info("New resource URL is {}", created);
        } catch (UnmodifiableOntologyCollectorException e) {
            throw new WebApplicationException(e, FORBIDDEN);
        }
    // addCORSOrigin(servletContext, rb, headers);
    return rb.build();
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) UnmodifiableOntologyCollectorException(org.apache.stanbol.ontologymanager.servicesapi.collector.UnmodifiableOntologyCollectorException) GraphContentInputSource(org.apache.stanbol.ontologymanager.sources.clerezza.GraphContentInputSource) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) MediaType(javax.ws.rs.core.MediaType) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) URI(java.net.URI) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 23 with OWLOntologyID

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

the class ClerezzaOntologyProvider method fillImportsReverse.

/**
 * Fills a reverse stack of import targets for the graph identified by key <tt>importing</tt>. The import
 * tree is visited in <i>pre-order</i> and the stack is filled accordingly. Optionally, a second stack can
 * be supplied to store only the level 1 imports. This can be used for preserving the original import tree
 * structure.<br>
 * <br>
 * TODO there should be a more space-efficient implementation.
 *
 * @param importing
 *            the key of the root graph, which will be at the bottom of every list.
 * @param reverseImports
 *            the list that will store all import target keys in pre-order.
 * @param level1Imports
 *            a second list that will store the level 1 import target keys, and is not passed to recursive
 *            calls. Will be ignored if null.
 */
private void fillImportsReverse(OWLOntologyID importing, List<OWLOntologyID> reverseImports, List<OWLOntologyID> level1Imports) {
    log.debug("Filling reverse imports for {}", importing);
    // Add the importing ontology first
    reverseImports.add(importing);
    if (level1Imports != null)
        level1Imports.add(importing);
    // Get the graph and explore its imports
    // store.getTriples(importing);
    Graph graph = getStoredOntology(/* getPublicKey */
    (importing), Graph.class, false);
    Iterator<Triple> it = graph.filter(null, RDF.type, OWL.Ontology);
    if (!it.hasNext())
        return;
    Iterator<Triple> it2 = graph.filter(it.next().getSubject(), OWL.imports, null);
    while (it2.hasNext()) {
        // obj is the *original* import target
        RDFTerm obj = it2.next().getObject();
        if (obj instanceof IRI) {
            // Right now getKey() is returning the "private" storage ID
            String key = getKey(org.semanticweb.owlapi.model.IRI.create(((IRI) obj).getUnicodeString()));
            // TODO this will not be needed when getKey() and getPublicKey() return the proper public key.
            OWLOntologyID oid = keymap.getReverseMapping(new IRI(key));
            // (Unoptimized, should not use contains() for stacks.)
            if (!reverseImports.contains(oid)) {
                if (level1Imports != null)
                    level1Imports.add(oid);
                fillImportsReverse(oid, reverseImports, null);
            }
        }
    }
}
Also used : Triple(org.apache.clerezza.commons.rdf.Triple) IRI(org.apache.clerezza.commons.rdf.IRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm)

Example 24 with OWLOntologyID

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

the class ClerezzaOntologyProvider method getOntologyNetworkConfiguration.

public OntologyNetworkConfiguration getOntologyNetworkConfiguration() {
    Map<String, Collection<OWLOntologyID>> coreOntologies = new HashMap<String, Collection<OWLOntologyID>>(), customOntologies = new HashMap<String, Collection<OWLOntologyID>>();
    Map<String, Collection<String>> attachedScopes = new HashMap<String, Collection<String>>();
    final Graph meta = store.getGraph(new IRI(metaGraphId));
    // Scopes first
    for (Iterator<Triple> it = meta.filter(null, RDF.type, SCOPE_URIREF); it.hasNext(); ) {
        // for each
        // scope
        Triple ta = it.next();
        BlankNodeOrIRI sub = ta.getSubject();
        if (sub instanceof IRI) {
            String s = ((IRI) sub).getUnicodeString(), prefix = _NS_STANBOL_INTERNAL + Scope.shortName + "/";
            if (s.startsWith(prefix)) {
                String scopeId = s.substring(prefix.length());
                log.info("Rebuilding scope \"{}\".", scopeId);
                coreOntologies.put(scopeId, new TreeSet<OWLOntologyID>());
                customOntologies.put(scopeId, new TreeSet<OWLOntologyID>());
                IRI core_ur = null, custom_ur = null;
                RDFTerm r;
                // Check core space
                Iterator<Triple> it2 = meta.filter(sub, HAS_SPACE_CORE_URIREF, null);
                if (it2.hasNext()) {
                    r = it2.next().getObject();
                    if (r instanceof IRI)
                        core_ur = (IRI) r;
                } else {
                    it2 = meta.filter(null, IS_SPACE_CORE_OF_URIREF, sub);
                    if (it2.hasNext()) {
                        r = it2.next().getSubject();
                        if (r instanceof IRI)
                            core_ur = (IRI) r;
                    }
                }
                // Check custom space
                it2 = meta.filter(sub, HAS_SPACE_CUSTOM_URIREF, null);
                if (it2.hasNext()) {
                    r = it2.next().getObject();
                    if (r instanceof IRI)
                        custom_ur = (IRI) r;
                } else {
                    it2 = meta.filter(null, IS_SPACE_CUSTOM_OF_URIREF, sub);
                    if (it2.hasNext()) {
                        r = it2.next().getSubject();
                        if (r instanceof IRI)
                            custom_ur = (IRI) r;
                    }
                }
                // retrieve the ontologies
                if (core_ur != null) {
                    for (it2 = meta.filter(core_ur, null, null); it2.hasNext(); ) {
                        Triple t = it2.next();
                        IRI predicate = t.getPredicate();
                        if (predicate.equals(MANAGES_URIREF)) {
                            if (t.getObject() instanceof IRI)
                                coreOntologies.get(scopeId).add(// FIXME must be very
                                keymap.buildPublicKey((IRI) t.getObject()));
                        }
                    }
                    for (it2 = meta.filter(null, null, core_ur); it2.hasNext(); ) {
                        Triple t = it2.next();
                        IRI predicate = t.getPredicate();
                        if (predicate.equals(IS_MANAGED_BY_URIREF)) {
                            if (t.getSubject() instanceof IRI)
                                coreOntologies.get(scopeId).add(// FIXME must be very
                                keymap.buildPublicKey((IRI) t.getSubject()));
                        }
                    }
                }
                if (custom_ur != null) {
                    for (it2 = meta.filter(custom_ur, null, null); it2.hasNext(); ) {
                        Triple t = it2.next();
                        IRI predicate = t.getPredicate();
                        if (predicate.equals(MANAGES_URIREF)) {
                            if (t.getObject() instanceof IRI)
                                customOntologies.get(scopeId).add(// FIXME must be very
                                keymap.buildPublicKey((IRI) t.getObject()));
                        }
                    }
                    for (it2 = meta.filter(null, null, custom_ur); it2.hasNext(); ) {
                        Triple t = it2.next();
                        IRI predicate = t.getPredicate();
                        if (predicate.equals(IS_MANAGED_BY_URIREF)) {
                            if (t.getSubject() instanceof IRI)
                                customOntologies.get(scopeId).add(// FIXME must be very
                                keymap.buildPublicKey((IRI) t.getSubject()));
                        }
                    }
                }
            }
        }
    }
    // Sessions next
    Map<String, Collection<OWLOntologyID>> sessionOntologies = new HashMap<String, Collection<OWLOntologyID>>();
    for (Iterator<Triple> it = meta.filter(null, RDF.type, SESSION_URIREF); it.hasNext(); ) {
        // for each
        // scope
        Triple ta = it.next();
        BlankNodeOrIRI sub = ta.getSubject();
        if (sub instanceof IRI) {
            IRI ses_ur = (IRI) sub;
            String s = ((IRI) sub).getUnicodeString();
            String prefix = _NS_STANBOL_INTERNAL + Session.shortName + "/";
            if (s.startsWith(prefix)) {
                String sessionId = s.substring(prefix.length());
                log.info("Rebuilding session \"{}\".", sessionId);
                sessionOntologies.put(sessionId, new TreeSet<OWLOntologyID>());
                attachedScopes.put(sessionId, new TreeSet<String>());
                // retrieve the ontologies
                if (ses_ur != null) {
                    for (Iterator<Triple> it2 = meta.filter(ses_ur, MANAGES_URIREF, null); it2.hasNext(); ) {
                        RDFTerm obj = it2.next().getObject();
                        if (obj instanceof IRI)
                            sessionOntologies.get(sessionId).add(// FIXME must be very temporary!
                            keymap.buildPublicKey((IRI) obj));
                    }
                    for (Iterator<Triple> it2 = meta.filter(null, IS_MANAGED_BY_URIREF, ses_ur); it2.hasNext(); ) {
                        RDFTerm subj = it2.next().getSubject();
                        if (subj instanceof IRI)
                            sessionOntologies.get(sessionId).add(// FIXME must be very temporary!
                            keymap.buildPublicKey((IRI) subj));
                    }
                    for (Iterator<Triple> it2 = meta.filter(null, APPENDED_TO_URIREF, ses_ur); it2.hasNext(); ) {
                        RDFTerm subj = it2.next().getSubject();
                        if (subj instanceof IRI) {
                            String s1 = ((IRI) subj).getUnicodeString();
                            String prefix1 = _NS_STANBOL_INTERNAL + Scope.shortName + "/";
                            if (s1.startsWith(prefix1)) {
                                String scopeId = s1.substring(prefix1.length());
                                attachedScopes.get(sessionId).add(scopeId);
                            }
                        }
                    }
                    for (Iterator<Triple> it2 = meta.filter(ses_ur, HAS_APPENDED_URIREF, null); it2.hasNext(); ) {
                        RDFTerm obj = it2.next().getObject();
                        if (obj instanceof IRI) {
                            String s1 = ((IRI) obj).getUnicodeString();
                            String prefix1 = _NS_STANBOL_INTERNAL + Scope.shortName + "/";
                            if (s1.startsWith(prefix1)) {
                                String scopeId = s1.substring(prefix1.length());
                                attachedScopes.get(sessionId).add(scopeId);
                            }
                        }
                    }
                }
            }
        }
    }
    return new OntologyNetworkConfiguration(coreOntologies, customOntologies, sessionOntologies, attachedScopes);
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) HashMap(java.util.HashMap) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm) OntologyNetworkConfiguration(org.apache.stanbol.ontologymanager.ontonet.api.OntologyNetworkConfiguration) Triple(org.apache.clerezza.commons.rdf.Triple) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) Graph(org.apache.clerezza.commons.rdf.Graph) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) Collection(java.util.Collection)

Example 25 with OWLOntologyID

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

the class ClerezzaOntologyProvider method loadInStore.

@Override
public OWLOntologyID loadInStore(final org.semanticweb.owlapi.model.IRI ontologyIri, String formatIdentifier, boolean force, Origin<?>... origins) throws IOException {
    log.debug("Loading {}", ontologyIri);
    if (ontologyIri == null)
        throw new IllegalArgumentException("Ontology IRI cannot be null.");
    org.semanticweb.owlapi.model.IRI location = null;
    if (force)
        location = null;
    else
        for (OWLOntologyIRIMapper mapper : mappers) {
            location = mapper.getDocumentIRI(ontologyIri);
            if (location != null)
                break;
        }
    if (location == null) {
        if (isOfflineMode())
            throw new IllegalStateException("Cannot retrieve " + ontologyIri + " while Stanbol is in offline mode. " + "No resource with that identifier was found locally.");
        else
            location = ontologyIri;
    }
    log.info("found {} in {}", ontologyIri, location);
    // Add the physical IRI to the origins.
    origins = Arrays.copyOf(origins, origins.length + 1);
    origins[origins.length - 1] = Origin.create(ontologyIri);
    checkReplaceability(origins);
    // Get ordered list of preferred/supported formats, or use the specified one.
    List<String> supported = OntologyUtils.getPreferredSupportedFormats(parser.getSupportedFormats());
    List<String> formats;
    if (formatIdentifier == null || "".equals(formatIdentifier.trim()))
        formats = supported;
    else {
        formats = new LinkedList<String>();
        // Pre-check supported format
        if (supported.contains(formatIdentifier))
            formats.add(formatIdentifier);
        for (String sup : supported) if (sup != null && !formats.contains(sup))
            formats.add(sup);
    }
    for (String currentFormat : formats) {
        try {
            final URLConnection con = location.toURI().toURL().openConnection();
            con.setRequestProperty("Accept", currentFormat);
            final InputStream is = con.getInputStream();
            if (is != null) {
                /*
                     * We provide the current format, so the recursive call won't be trying to sort preferred
                     * formats again. Also, we provide the ontologyIRI as the preferred key, since we already
                     * know it.
                     */
                OWLOntologyID key = loadInStore(is, currentFormat, force, origins);
                // if (key != null && !key.isEmpty()) setLocatorMapping(ontologyIri, key);
                return key;
            }
        } catch (UnsupportedFormatException e) {
            log.debug("FAILURE format {} (unsupported). Trying next one.", currentFormat);
            continue;
        } catch (Exception e) {
            log.debug("FAILURE format {} (parse error). Will try next one.", currentFormat);
            continue;
        }
    }
    // No parser worked, return null.
    log.error("All parsers failed, giving up.");
    return null;
}
Also used : InputStream(java.io.InputStream) URLConnection(java.net.URLConnection) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) UnsupportedFormatException(org.apache.clerezza.rdf.core.serializedform.UnsupportedFormatException) EntityAlreadyExistsException(org.apache.clerezza.rdf.core.access.EntityAlreadyExistsException) OntologyHandleException(org.apache.stanbol.ontologymanager.servicesapi.ontology.OntologyHandleException) IOException(java.io.IOException) OrphanOntologyKeyException(org.apache.stanbol.ontologymanager.servicesapi.ontology.OrphanOntologyKeyException) UnsupportedFormatException(org.apache.clerezza.rdf.core.serializedform.UnsupportedFormatException) OWLOntologyIRIMapper(org.semanticweb.owlapi.model.OWLOntologyIRIMapper) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID)

Aggregations

OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)101 Test (org.junit.Test)32 OWLOntology (org.semanticweb.owlapi.model.OWLOntology)32 OWLOntologyCreationException (org.semanticweb.owlapi.model.OWLOntologyCreationException)23 HashSet (java.util.HashSet)22 OWLOntologyManager (org.semanticweb.owlapi.model.OWLOntologyManager)21 InputStream (java.io.InputStream)20 BlankNodeOrIRI (org.apache.clerezza.commons.rdf.BlankNodeOrIRI)19 Triple (org.apache.clerezza.commons.rdf.Triple)19 IRI (org.semanticweb.owlapi.model.IRI)18 IRI (org.apache.clerezza.commons.rdf.IRI)17 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)16 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