Search in sources :

Example 1 with Scope

use of org.apache.stanbol.ontologymanager.servicesapi.scope.Scope in project stanbol by apache.

the class TestSessions method testCreateSessionSpaceAutomatic.

@Test
public void testCreateSessionSpaceAutomatic() throws Exception {
    Scope scope1 = null, scope2 = null, scope3 = null;
    scope1 = collectorfactory.createOntologyScope(scopeId1, src1, src2);
    onManager.registerScope(scope1);
    scope2 = collectorfactory.createOntologyScope(scopeId2, src2, src1);
    onManager.registerScope(scope2);
    scope3 = collectorfactory.createOntologyScope(scopeId3, src2, src2);
    onManager.registerScope(scope3);
    // We do all activations after registering, otherwise the component
    // property value will override these activations.
    onManager.setScopeActive(scopeId1, true);
    onManager.setScopeActive(scopeId2, false);
    onManager.setScopeActive(scopeId3, true);
// Session ses = sesmgr.createSession();
// String sesid = ses.getID();
// TODO replace with proper tests
// assertFalse(scope1.getSessionSpaces().isEmpty());
// assertNotNull(scope1.getSessionSpace(sesid));
// assertFalse(scope3.getSessionSpaces().isEmpty());
// assertNull(scope2.getSessionSpace(sesid));
// assertNotNull(scope3.getSessionSpace(sesid));
}
Also used : Scope(org.apache.stanbol.ontologymanager.servicesapi.scope.Scope) Test(org.junit.Test)

Example 2 with Scope

use of org.apache.stanbol.ontologymanager.servicesapi.scope.Scope in project stanbol by apache.

the class OntologyManagerInputProvider method getFromOntoMgr.

private OWLOntology getFromOntoMgr() throws IOException {
    try {
        Scope scope = null;
        synchronized (onManager) {
            scope = onManager.getScope(this.scopeId);
        }
        if (scope == null) {
            log.error("Scope {} cannot be retrieved", this.scopeId);
            throw new IOException("Scope " + this.scopeId + " cannot be retrieved");
        }
        Session session = null;
        if (sessionManager != null)
            synchronized (sessionManager) {
                session = sessionManager.getSession(sessionId);
            }
        if (session == null)
            log.warn("Session {} cannot be retrieved. Ignoring.", this.sessionId);
        final Set<OWLOntology> set = new HashSet<OWLOntology>();
        set.add(scope.export(OWLOntology.class, true));
        if (session != null)
            set.add(session.export(OWLOntology.class, true));
        if (set.size() == 1)
            return set.iterator().next();
        OWLOntologyMerger merger = new OWLOntologyMerger(new OWLOntologySetProvider() {

            @Override
            public Set<OWLOntology> getOntologies() {
                return set;
            }
        });
        return merger.createMergedOntology(createOWLOntologyManager(), IRI.create("reasoners:input-" + System.currentTimeMillis()));
    } catch (OWLOntologyCreationException e) {
        String message = "The network for scope/session cannot be retrieved";
        log.error(message + ":", e);
        throw new IllegalArgumentException(message);
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) OWLOntologyMerger(org.semanticweb.owlapi.util.OWLOntologyMerger) IOException(java.io.IOException) OWLOntologySetProvider(org.semanticweb.owlapi.model.OWLOntologySetProvider) Scope(org.apache.stanbol.ontologymanager.servicesapi.scope.Scope) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) Session(org.apache.stanbol.ontologymanager.servicesapi.session.Session) HashSet(java.util.HashSet)

Example 3 with Scope

use of org.apache.stanbol.ontologymanager.servicesapi.scope.Scope in project stanbol by apache.

the class SessionResource method postOntology.

@POST
@Consumes({ MULTIPART_FORM_DATA })
@Produces({ WILDCARD })
public Response postOntology(MultiPartBody data, @Context HttpHeaders headers) {
    log.debug(" post(FormDataMultiPart data)");
    long before = System.currentTimeMillis();
    ResponseBuilder rb;
    // TODO remove and make sure it is set across the method
    rb = Response.status(BAD_REQUEST);
    IRI location = null, library = null;
    // If found, it takes precedence over location.
    FormFile file = null;
    String format = null;
    Set<String> toAppend = null;
    Set<String> keys = new HashSet<String>();
    // }
    if (data.getFormFileParameterValues("file").length > 0) {
        file = data.getFormFileParameterValues("file")[0];
    }
    // else {
    if (data.getTextParameterValues("format").length > 0) {
        String value = data.getTextParameterValues("format")[0];
        if (!value.equals("auto")) {
            format = value;
        }
    }
    if (data.getTextParameterValues("url").length > 0) {
        String value = data.getTextParameterValues("url")[0];
        try {
            // To throw 400 if malformed.
            URI.create(value);
            location = IRI.create(value);
        } catch (Exception ex) {
            log.error("Malformed IRI for param url " + value, ex);
            throw new WebApplicationException(ex, BAD_REQUEST);
        }
    }
    if (data.getTextParameterValues("library").length > 0) {
        String value = data.getTextParameterValues("library")[0];
        try {
            // To throw 400 if malformed.
            URI.create(value);
            library = IRI.create(value);
        } catch (Exception ex) {
            log.error("Malformed IRI for param library " + value, ex);
            throw new WebApplicationException(ex, BAD_REQUEST);
        }
    }
    if (data.getTextParameterValues("stored").length > 0) {
        String value = data.getTextParameterValues("stored")[0];
        keys.add(value);
    }
    if (data.getTextParameterValues("scope").length > 0) {
        String value = data.getTextParameterValues("scope")[0];
        log.info("Request to append scope \"{}\".", value);
        if (toAppend == null) {
            toAppend = new HashSet<String>();
        }
        toAppend.add(value);
    }
    boolean fileOk = file != null;
    if (fileOk || location != null || library != null) {
        // File and location take precedence
        // Then add the file
        OntologyInputSource<?> src = null;
        if (fileOk) {
            // File first
            Collection<String> formats;
            if (format == null || "".equals(format.trim()))
                formats = OntologyUtils.getPreferredFormats();
            else
                formats = Collections.singleton(format);
            for (String f : formats) try {
                log.debug("Trying format {}.", f);
                long b4buf = System.currentTimeMillis();
                // Recreate the stream on each attempt
                InputStream content = new BufferedInputStream(new ByteArrayInputStream(file.getContent()));
                log.debug("Streams created in {} ms", System.currentTimeMillis() - b4buf);
                log.debug("Creating ontology input source...");
                b4buf = System.currentTimeMillis();
                OWLOntologyID guessed = OWLUtils.guessOntologyID(content, Parser.getInstance(), f);
                if (guessed != null && !guessed.isAnonymous() && ontologyProvider.hasOntology(guessed)) {
                    rb = Response.status(Status.CONFLICT);
                    this.submitted = guessed;
                    if (headers.getAcceptableMediaTypes().contains(MediaType.TEXT_HTML_TYPE)) {
                        rb.entity(new Viewable("/imports/409", this));
                        rb.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML + "; charset=utf-8");
                    }
                } else {
                    content = new BufferedInputStream(new ByteArrayInputStream(file.getContent()));
                    src = new GraphContentInputSource(content, f, ontologyProvider.getStore());
                }
                log.debug("Done in {} ms", System.currentTimeMillis() - b4buf);
                log.info("SUCCESS parse with format {}.", f);
                break;
            } catch (OntologyLoadingException e) {
                log.debug("FAILURE parse with format {}.", f);
                continue;
            } catch (IOException e) {
                log.debug("FAILURE parse with format {} (I/O error).", f);
                continue;
            }
            log.debug("No more formats to try.");
        } else if (location != null) {
            try {
                src = new RootOntologySource(location);
            } catch (Exception e) {
                log.error("Failed to load ontology from " + location, e);
                throw new WebApplicationException(e, BAD_REQUEST);
            }
        } else if (library != null) {
            // This comes last, since it will most likely have a value.
            try {
                long beforeLib = System.currentTimeMillis();
                log.debug("Creating library source for {}", library);
                src = new LibrarySource(library, regMgr);
                log.debug("Library source created in {} ms.", System.currentTimeMillis() - beforeLib);
            } catch (Exception e) {
                log.error("Failed to load ontology library " + library, e);
                throw new WebApplicationException(e, INTERNAL_SERVER_ERROR);
            }
        } else {
            log.error("Bad request");
            log.error(" file is: {}", file);
            throw new WebApplicationException(BAD_REQUEST);
        }
        if (src != null) {
            log.debug("Adding ontology from input source {}", src);
            long b4add = System.currentTimeMillis();
            OWLOntologyID key = session.addOntology(src);
            if (key == null || key.isAnonymous())
                throw new WebApplicationException(INTERNAL_SERVER_ERROR);
            // FIXME ugly but will have to do for the time being
            log.debug("Addition done in {} ms.", System.currentTimeMillis() - b4add);
            log.debug("Storage key : {}", key);
            // key.split("::")[1];
            String uri = OntologyUtils.encode(key);
            // uri = uri.substring((ontologyProvider.getGraphPrefix() + "::").length());
            if (uri != null && !uri.isEmpty())
                rb = Response.seeOther(URI.create("/ontonet/session/" + session.getID() + "/" + uri));
            else
                rb = Response.seeOther(URI.create("/ontonet/session/" + session.getID()));
        } else if (rb == null)
            rb = Response.status(INTERNAL_SERVER_ERROR);
    }
    if (!keys.isEmpty()) {
        for (String key : keys) session.addOntology(new StoredOntologySource(OntologyUtils.decode(key)));
        rb = Response.seeOther(URI.create("/ontonet/session/" + session.getID()));
    }
    // Now check scopes
    if (toAppend != null && (!toAppend.isEmpty() || (toAppend.isEmpty() && !getAppendedScopes().isEmpty()))) {
        for (Scope sc : getAllScopes()) {
            // First remove appended scopes not in the list
            String scid = sc.getID();
            if (!toAppend.contains(scid) && getAppendedScopes().contains(scid)) {
                session.detachScope(scid);
                log.info("Removed scope \"{}\".", scid);
            }
        }
        for (String scid : toAppend) {
            // Then add all the scopes in the list
            if (!getAppendedScopes().contains(scid)) {
                log.info("Appending scope \"{}\" to session \"{}\".", scid, session.getID());
                session.attachScope(scid);
                log.info("Appended scope \"{}\".", scid);
            }
        }
        rb = Response.seeOther(URI.create("/ontonet/session/" + session.getID()));
    }
    // else {
    // log.error("Nothing to do with session {}.", session.getID());
    // throw new WebApplicationException(BAD_REQUEST);
    // }
    // rb.header(HttpHeaders.CONTENT_TYPE, TEXT_HTML + "; charset=utf-8");
    // addCORSOrigin(servletContext, rb, headers);
    log.info("POST ontology completed in {} ms.", System.currentTimeMillis() - before);
    return rb.build();
}
Also used : IRI(org.semanticweb.owlapi.model.IRI) WebApplicationException(javax.ws.rs.WebApplicationException) FormFile(org.apache.clerezza.jaxrs.utils.form.FormFile) BufferedInputStream(java.io.BufferedInputStream) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) RootOntologySource(org.apache.stanbol.ontologymanager.sources.owlapi.RootOntologySource) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) HashSet(java.util.HashSet) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) LibrarySource(org.apache.stanbol.ontologymanager.registry.io.LibrarySource) IOException(java.io.IOException) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) IrremovableOntologyException(org.apache.stanbol.ontologymanager.servicesapi.collector.IrremovableOntologyException) WebApplicationException(javax.ws.rs.WebApplicationException) SessionLimitException(org.apache.stanbol.ontologymanager.servicesapi.session.SessionLimitException) UnmodifiableOntologyCollectorException(org.apache.stanbol.ontologymanager.servicesapi.collector.UnmodifiableOntologyCollectorException) OWLOntologyStorageException(org.semanticweb.owlapi.model.OWLOntologyStorageException) IOException(java.io.IOException) OntologyLoadingException(org.apache.stanbol.ontologymanager.servicesapi.ontology.OntologyLoadingException) OntologyCollectorModificationException(org.apache.stanbol.ontologymanager.servicesapi.collector.OntologyCollectorModificationException) DuplicateSessionIDException(org.apache.stanbol.ontologymanager.servicesapi.session.DuplicateSessionIDException) StoredOntologySource(org.apache.stanbol.ontologymanager.servicesapi.io.StoredOntologySource) OntologyLoadingException(org.apache.stanbol.ontologymanager.servicesapi.ontology.OntologyLoadingException) Scope(org.apache.stanbol.ontologymanager.servicesapi.scope.Scope) ByteArrayInputStream(java.io.ByteArrayInputStream) GraphContentInputSource(org.apache.stanbol.ontologymanager.sources.clerezza.GraphContentInputSource) Viewable(org.apache.stanbol.commons.web.viewable.Viewable) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 4 with Scope

use of org.apache.stanbol.ontologymanager.servicesapi.scope.Scope in project stanbol by apache.

the class SessionResource method emptyPost.

@POST
@Produces({ WILDCARD })
public Response emptyPost(@PathParam("id") String sessionId, @Context HttpHeaders headers) {
    log.debug(" post(no data)");
    session = sesMgr.getSession(sessionId);
    for (Scope sc : getAllScopes()) {
        // First remove appended scopes not in the list
        String scid = sc.getID();
        if (getAppendedScopes().contains(scid)) {
            session.detachScope(scid);
            log.info("Removed scope \"{]\".", scid);
        }
    }
    ResponseBuilder rb = Response.ok();
    // addCORSOrigin(servletContext, rb, headers);
    return rb.build();
}
Also used : Scope(org.apache.stanbol.ontologymanager.servicesapi.scope.Scope) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 5 with Scope

use of org.apache.stanbol.ontologymanager.servicesapi.scope.Scope in project stanbol by apache.

the class TestStorage method storageOnScopeCreation.

@Test
public void storageOnScopeCreation() throws Exception {
    assertEquals(1, ontologyProvider.getStore().listGraphs().size());
    // This one has an import that we want to hijack locally, so we use the ParentPathInputSource.
    OntologyInputSource<?> ois = new ParentPathInputSource(new File(getClass().getResource("/ontologies/minorcharacters.owl").toURI()));
    Scope sc = onManager.createOntologyScope(scopeId, ois);
    Set<Triple> triples = new HashSet<Triple>();
    for (IRI iri : ontologyProvider.getStore().listGraphs()) {
        log.info("{}", iri.toString());
        IRI entity = new IRI(Constants.PEANUTS_MINOR_BASE + "#" + Constants.truffles);
        ImmutableGraph ctx = new GraphNode(entity, ontologyProvider.getStore().getGraph(iri)).getNodeContext();
        Iterator<Triple> it = ctx.iterator();
        while (it.hasNext()) triples.add(it.next());
    }
    assertFalse(ontologyProvider.getStore().listGraphs().isEmpty());
    assertEquals(3, triples.size());
}
Also used : Triple(org.apache.clerezza.commons.rdf.Triple) IRI(org.apache.clerezza.commons.rdf.IRI) Scope(org.apache.stanbol.ontologymanager.servicesapi.scope.Scope) ParentPathInputSource(org.apache.stanbol.ontologymanager.sources.owlapi.ParentPathInputSource) GraphNode(org.apache.clerezza.rdf.utils.GraphNode) File(java.io.File) ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

Scope (org.apache.stanbol.ontologymanager.servicesapi.scope.Scope)22 Test (org.junit.Test)7 OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)7 OWLOntologyCreationException (org.semanticweb.owlapi.model.OWLOntologyCreationException)6 HashSet (java.util.HashSet)5 IRI (org.apache.clerezza.commons.rdf.IRI)5 OWLOntology (org.semanticweb.owlapi.model.OWLOntology)5 IOException (java.io.IOException)4 Triple (org.apache.clerezza.commons.rdf.Triple)4 TripleImpl (org.apache.clerezza.commons.rdf.impl.utils.TripleImpl)4 OntologySpace (org.apache.stanbol.ontologymanager.servicesapi.scope.OntologySpace)4 GraphContentInputSource (org.apache.stanbol.ontologymanager.sources.clerezza.GraphContentInputSource)4 Produces (javax.ws.rs.Produces)3 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)3 BlankNodeOrIRI (org.apache.clerezza.commons.rdf.BlankNodeOrIRI)3 UnmodifiableOntologyCollectorException (org.apache.stanbol.ontologymanager.servicesapi.collector.UnmodifiableOntologyCollectorException)3 NoSuchScopeException (org.apache.stanbol.ontologymanager.servicesapi.scope.NoSuchScopeException)3 Session (org.apache.stanbol.ontologymanager.servicesapi.session.Session)3 InputStream (java.io.InputStream)2 POST (javax.ws.rs.POST)2