You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stanbol.apache.org by en...@apache.org on 2011/08/24 09:27:57 UTC

svn commit: r1160991 - in /incubator/stanbol/branches/jena-reasoners/reasoners/web: README src/main/java/org/apache/stanbol/reasoners/web/resources/ReasoningServiceTaskResource.java

Author: enridaga
Date: Wed Aug 24 07:27:56 2011
New Revision: 1160991

URL: http://svn.apache.org/viewvc?rev=1160991&view=rev
Log:
STANBOL-185
* Reasoning services now support a 'target' parameter, to save output in a triple store graph
* Some examples added in the README

Modified:
    incubator/stanbol/branches/jena-reasoners/reasoners/web/README
    incubator/stanbol/branches/jena-reasoners/reasoners/web/src/main/java/org/apache/stanbol/reasoners/web/resources/ReasoningServiceTaskResource.java

Modified: incubator/stanbol/branches/jena-reasoners/reasoners/web/README
URL: http://svn.apache.org/viewvc/incubator/stanbol/branches/jena-reasoners/reasoners/web/README?rev=1160991&r1=1160990&r2=1160991&view=diff
==============================================================================
--- incubator/stanbol/branches/jena-reasoners/reasoners/web/README (original)
+++ incubator/stanbol/branches/jena-reasoners/reasoners/web/README Wed Aug 24 07:27:56 2011
@@ -1,6 +1,9 @@
 
 Examples:
-
+#
+# Basic GET calls to the reasoning services.
+# Send a URL and the service will return the inferred triples
+#
 # Classify the FOAF ontology, getting it from the web using the Jena OWL reasoner, result in turtle
 curl -v -H "Accept: application/turtle" "http://localhost:8080/reasoners/services/owl/classify?url=http://xmlns.com/foaf/0.1/"
 
@@ -14,9 +17,25 @@ curl -v -H "Accept: application/rdf+xml"
 curl -v "http://localhost:8080/reasoners/services/owl/check?url=http://xmlns.com/foaf/0.1/"
 
 # Check consistency of the FOAF ontology, getting it from the web using the Hermit OWL2 reasoner, result in turtle
-curl -v "http://localhost:8080/reasoners/services/hermit/check?url=http://xmlns.com/foaf/0.1/"
+curl -v "http://localhost:8080/reasoners/services/owl2/check?url=http://xmlns.com/foaf/0.1/"
 
 # Trying with an ontology network (large ontology composed by a set of little ontologies connected through owl:import statements)
-curl -v "http://localhost:8080/reasoners/services/hermit/check?url=http://www.cnr.it/ontology/cnr/cnr.owl"
-or
-curl -v "http://localhost:8080/reasoners/services/hermit/enrich?url=http://www.cnr.it/ontology/cnr/cnr.owl"
+curl -v "http://localhost:8080/reasoners/services/owl2/check?url=http://www.cnr.it/ontology/cnr/cnr.owl"
+# or
+curl -v "http://localhost:8080/reasoners/services/owl2/enrich?url=http://www.cnr.it/ontology/cnr/cnr.owl"
+
+#
+# POST calls (send a file)
+#
+# Send the foaf.rdf file to a reasoning service and see the output
+# (get it with 
+curl -H "Accept: application/rdf+xml"  http://xmlns.com/foaf/0.1/ > foaf.rdf 
+# )
+curl -X POST -H "Content-type: multipart/form-data" -H "Accept: text/turtle" -F file=@foaf.rdf "http://localhost:8080/reasoners/services/rdfs/enrich"
+
+
+# Save output in the triple store instead of return
+# >> Add the "target" parameter, with the graph identifier
+curl "http://localhost:8080/reasoners/services/owl/classify?url=http://xmlns.com/foaf/0.1/&target=example-foaf-inferred"
+# or, posting a file
+curl -X POST -H "Content-type: multipart/form-data" -F file=@foaf.rdf -F target=example-rdfs-inferences "http://localhost:8080/reasoners/services/rdfs/enrich"

Modified: incubator/stanbol/branches/jena-reasoners/reasoners/web/src/main/java/org/apache/stanbol/reasoners/web/resources/ReasoningServiceTaskResource.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/branches/jena-reasoners/reasoners/web/src/main/java/org/apache/stanbol/reasoners/web/resources/ReasoningServiceTaskResource.java?rev=1160991&r1=1160990&r2=1160991&view=diff
==============================================================================
--- incubator/stanbol/branches/jena-reasoners/reasoners/web/src/main/java/org/apache/stanbol/reasoners/web/resources/ReasoningServiceTaskResource.java (original)
+++ incubator/stanbol/branches/jena-reasoners/reasoners/web/src/main/java/org/apache/stanbol/reasoners/web/resources/ReasoningServiceTaskResource.java Wed Aug 24 07:27:56 2011
@@ -5,11 +5,13 @@ import static javax.ws.rs.core.MediaType
 
 import java.io.ByteArrayOutputStream;
 import java.io.File;
+import java.io.IOException;
 import java.net.MalformedURLException;
 import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
+import java.util.concurrent.locks.Lock;
 
 import javax.servlet.ServletContext;
 import javax.ws.rs.Consumes;
@@ -26,14 +28,17 @@ import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.Response.Status;
 
+import org.apache.clerezza.rdf.core.MGraph;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.access.LockableMGraph;
+import org.apache.clerezza.rdf.core.access.NoSuchEntityException;
+import org.apache.clerezza.rdf.core.access.TcManager;
 import org.apache.stanbol.commons.web.base.ContextHelper;
 import org.apache.stanbol.commons.web.base.format.KRFormat;
 import org.apache.stanbol.commons.web.base.resource.BaseStanbolResource;
 import org.apache.stanbol.ontologymanager.ontonet.api.ONManager;
-import org.apache.stanbol.ontologymanager.ontonet.api.ontology.OntologyScope;
-import org.apache.stanbol.ontologymanager.ontonet.api.ontology.SessionOntologySpace;
-import org.apache.stanbol.ontologymanager.ontonet.api.session.Session;
-import org.apache.stanbol.owl.transformation.JenaToOwlConvert;
+import org.apache.stanbol.owl.transformation.JenaToClerezzaConverter;
+import org.apache.stanbol.owl.transformation.OWLAPIToClerezzaConverter;
 import org.apache.stanbol.reasoners.jena.JenaReasoningService;
 import org.apache.stanbol.reasoners.owlapi.OWLApiReasoningService;
 import org.apache.stanbol.reasoners.servicesapi.InconsistentInputException;
@@ -78,13 +83,14 @@ public class ReasoningServiceTaskResourc
     private String taskID;
     private RuleStore ruleStore;
     private ONManager onManager;
+    private TcManager tcManager;
 
     public ReasoningServiceTaskResource(@PathParam(value = "service") String serviceID,
                                         @PathParam(value = "task") String taskID,
                                         @Context ServletContext servletContext,
                                         @Context HttpHeaders headers) {
         super();
-
+        log.info("Called service {} to perform task {}", service, taskID);
         // ServletContext
         this.context = servletContext;
 
@@ -97,6 +103,9 @@ public class ReasoningServiceTaskResourc
         // Retrieve the ontology network manager
         this.onManager = (ONManager) ContextHelper.getServiceFromContext(ONManager.class, servletContext);
 
+        // Clerezza storage
+        this.tcManager = (TcManager) ContextHelper.getServiceFromContext(TcManager.class, servletContext);
+
         // Retrieve the service
         try {
             service = getService(serviceID);
@@ -124,73 +133,112 @@ public class ReasoningServiceTaskResourc
         }
     }
 
-//    @GET
-//    @Path("/ontonet/session")
-//    @Produces({TEXT_HTML, "text/plain", KRFormat.RDF_XML, KRFormat.TURTLE, "text/turtle", "text/n3"})
-//    public Response getOntonetSession(@QueryParam("session") String sessionID,
-//                                      @QueryParam("target") String targetGraphID) {
-//        log.info("Called /ontonet/session with session={} and target={}", sessionID, targetGraphID);
-//        // If session is null, describe the service
-//        if (sessionID == null) {
-//            return Response.ok(new Viewable("ontonet-session", this)).build();
-//        }
-//        // Get the session
-//        log.info("Session requested is {}", sessionID);
-//        Set<OntologyScope> scopes = this.onManager.getScopeRegistry().getRegisteredScopes();
-//        log.info("Registered scopes are {}", scopes.size());
-//        OntologyScope scope = null;
-//        SessionOntologySpace sspace = null;
-//        for (OntologyScope sc : scopes) {
-//            log.info("Lookup for session space in scope {}", sc);
-//            if (sc == null) {
-//                log.warn("A Scope is null! Why it's in the registry!?");
-//                continue;
-//            } else {
-//                sspace = sc.getSessionSpace(IRI.create(sessionID));
-//                if (sspace != null) {
-//                    scope = sc;
-//                    break;
-//                } 
-//            }
-//        }
-//        log.info("Found scope: {}", scope);
-//        log.info("Found session space: {}", sspace);
-//
-//        // If session cannot be retrieved, return 404
-//        if (sspace == null) {
-//            log.error("Session space does not exists!: {}", sessionID);
-//            throw new WebApplicationException(new IllegalArgumentException("Session does not exists!"),
-//                    Response.Status.NOT_FOUND);
-//        }
-//
-//        // Get the session as OWLOntology
-//        OWLOntology input = sspace.asOWLOntology();
-//        log.info("Session ontology is: {}", input);
-//
-//        // Now we select the service type
-//        if (service instanceof JenaReasoningService) {
-//            Model inputModel = new JenaToOwlConvert().ModelOwlToJenaConvert(input, "TURTLE");
-//            return executeJenaReasoningService((JenaReasoningService) service, inputModel, null,
-//                targetGraphID);
-//        } else if (service instanceof OWLApiReasoningService) {
-//            return executeOWLApiReasoningService((OWLApiReasoningService) service, input, null, targetGraphID);
-//        } else {
-//            throw new WebApplicationException(new Exception("Unsupported implementation"),
-//                    Response.Status.INTERNAL_SERVER_ERROR);
-//        }
-//
-//    }
-
-//    @GET
-//    @Path("/ontonet/scope")
-//    @Produces({TEXT_HTML, "text/plain", KRFormat.RDF_XML, KRFormat.TURTLE, "text/turtle", "text/n3"})
-//    public Response getOntonetScope(@QueryParam("scope") String scopeID,
-//                                    @QueryParam("recipe") String recipeID,
-//                                    @QueryParam("target") String targetGraph) {
-//        // If session is null, describe the service
-//        // If target is null, then get back results, elsewhere put it in target graph
-//        return null;
-//    }
+    // @GET
+    // @Path("/ontonet/session")
+    // @Produces({TEXT_HTML, "text/plain", KRFormat.RDF_XML, KRFormat.TURTLE, "text/turtle", "text/n3"})
+    // public Response getOntonetSession(@QueryParam("session") String sessionID,
+    // @QueryParam("target") String targetGraphID) {
+    // log.info("Called /ontonet/session with session={} and target={}", sessionID, targetGraphID);
+    // // If session is null, describe the service
+    // if (sessionID == null) {
+    // return Response.ok(new Viewable("ontonet-session", this)).build();
+    // }
+    // // Get the session
+    // log.info("Session requested is {}", sessionID);
+    // Set<OntologyScope> scopes = this.onManager.getScopeRegistry().getRegisteredScopes();
+    // log.info("Registered scopes are {}", scopes.size());
+    // OntologyScope scope = null;
+    // SessionOntologySpace sspace = null;
+    // for (OntologyScope sc : scopes) {
+    // log.info("Lookup for session space in scope {}", sc);
+    // if (sc == null) {
+    // log.warn("A Scope is null! Why it's in the registry!?");
+    // continue;
+    // } else {
+    // sspace = sc.getSessionSpace(IRI.create(sessionID));
+    // if (sspace != null) {
+    // scope = sc;
+    // break;
+    // }
+    // }
+    // }
+    // log.info("Found scope: {}", scope);
+    // log.info("Found session space: {}", sspace);
+    //
+    // // If session cannot be retrieved, return 404
+    // if (sspace == null) {
+    // log.error("Session space does not exists!: {}", sessionID);
+    // throw new WebApplicationException(new IllegalArgumentException("Session does not exists!"),
+    // Response.Status.NOT_FOUND);
+    // }
+    //
+    // // Get the session as OWLOntology
+    // OWLOntology input = sspace.asOWLOntology();
+    // log.info("Session ontology is: {}", input);
+    //
+    // // Now we select the service type
+    // if (service instanceof JenaReasoningService) {
+    // Model inputModel = new JenaToOwlConvert().ModelOwlToJenaConvert(input, "TURTLE");
+    // return executeJenaReasoningService((JenaReasoningService) service, inputModel, null,
+    // targetGraphID);
+    // } else if (service instanceof OWLApiReasoningService) {
+    // return executeOWLApiReasoningService((OWLApiReasoningService) service, input, null, targetGraphID);
+    // } else {
+    // throw new WebApplicationException(new Exception("Unsupported implementation"),
+    // Response.Status.INTERNAL_SERVER_ERROR);
+    // }
+    //
+    // }
+
+    // @GET
+    // @Path("/ontonet/scope")
+    // @Produces({TEXT_HTML, "text/plain", KRFormat.RDF_XML, KRFormat.TURTLE, "text/turtle", "text/n3"})
+    // public Response getOntonetScope(@QueryParam("scope") String scopeID,
+    // @QueryParam("recipe") String recipeID,
+    // @QueryParam("target") String targetGraph) {
+    // // If session is null, describe the service
+    // // If target is null, then get back results, elsewhere put it in target graph
+    // return null;
+    // }
+
+    /**
+     * Get the inferences from input URL. If url param is null, get the HTML description of this service/task
+     * 
+     * @param url
+     * @return
+     */
+    @GET
+    @Produces({TEXT_HTML, "text/plain", KRFormat.RDF_XML, KRFormat.TURTLE, "text/turtle", "text/n3"})
+    public Response get(@QueryParam("url") String url, @QueryParam("target") String targetGraphID) {
+        // If url param is missing, we produce the service/task welcome page
+        if (url == null) {
+            return Response.ok(new Viewable("index", this)).build();
+        }
+        log.info("Called GET with input url: {} and target {}", url, targetGraphID);
+
+        /**
+         * Select the service implementation
+         */
+        if (getCurrentService() instanceof JenaReasoningService) {
+            // Prepare input data
+            Model input = ModelFactory.createDefaultModel().read(url);
+            return executeJenaReasoningService((JenaReasoningService) getCurrentService(), input, null,
+                targetGraphID);
+        } else if (getCurrentService() instanceof OWLApiReasoningService) {
+            OWLOntology input = null;
+            try {
+                input = createOWLOntologyManager().loadOntologyFromOntologyDocument(IRI.create(url));
+            } catch (OWLOntologyCreationIOException e) {
+                throw new WebApplicationException(e, Response.Status.NOT_FOUND);
+            } catch (OWLOntologyCreationException e) {
+                throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
+            }
+            return executeOWLApiReasoningService((OWLApiReasoningService) getCurrentService(), input, null,
+                targetGraphID);
+        }
+        throw new WebApplicationException(new Exception("Unsupported implementation"),
+                Response.Status.INTERNAL_SERVER_ERROR);
+    }
 
     /**
      * Generate inferences from the input file. Output comes back to the client.
@@ -201,9 +249,8 @@ public class ReasoningServiceTaskResourc
     @POST
     @Consumes({MULTIPART_FORM_DATA})
     @Produces({TEXT_HTML, "text/plain", KRFormat.RDF_XML, KRFormat.TURTLE, "text/turtle", "text/n3"})
-    public Response postData(@FormDataParam("file") File file) {
-        log.info("Called POST on service {} to perform task {}", service, taskID);
-        log.info("on input file: {}", file);
+    public Response postData(@FormDataParam("file") File file, @FormDataParam("target") String targetGraphID) {
+        log.info("Called POST with input file: {} and target: {}", file, targetGraphID);
         if (file.exists() && file.canRead()) {
             // Select the service implementation
             if (getCurrentService() instanceof JenaReasoningService) {
@@ -216,7 +263,7 @@ public class ReasoningServiceTaskResourc
                             Response.Status.INTERNAL_SERVER_ERROR);
                 }
                 return executeJenaReasoningService((JenaReasoningService) getCurrentService(), input, null,
-                    null);
+                    targetGraphID);
             } else if (getCurrentService() instanceof OWLApiReasoningService) {
                 OWLOntology input = null;
                 try {
@@ -227,7 +274,7 @@ public class ReasoningServiceTaskResourc
                     throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
                 }
                 return executeOWLApiReasoningService((OWLApiReasoningService) getCurrentService(), input,
-                    null, null);
+                    null, targetGraphID);
             }
             throw new WebApplicationException(new Exception("Unsupported implementation"),
                     Response.Status.INTERNAL_SERVER_ERROR);
@@ -272,6 +319,8 @@ public class ReasoningServiceTaskResourc
     /**
      * Execute the JenaReasoningService
      * 
+     * TODO: Add parameter to decide if the graph must be deleted if exists
+     * 
      * @param s
      * @param input
      * @param rules
@@ -312,11 +361,11 @@ public class ReasoningServiceTaskResourc
                 log.error("Result is null");
                 throw new WebApplicationException();
             }
-            log.info("Returning {} statements", result.size());
             Model outputModel = ModelFactory.createDefaultModel();
             outputModel.add(result.toArray(new Statement[result.size()]));
             // If target is null, then get back results, elsewhere put it in target graph
             if (targetGraphID == null) {
+                log.info("Returning {} statements", result.size());
                 if (isHTML()) {
                     ByteArrayOutputStream out = new ByteArrayOutputStream();
                     outputModel.write(out, "TURTLE");
@@ -327,8 +376,8 @@ public class ReasoningServiceTaskResourc
                     return Response.ok(outputModel).build();
                 }
             } else {
-                log.error("Not implemented yet! :(");
-                throw new WebApplicationException(501);
+                save(outputModel, targetGraphID);
+                return Response.ok().build();
             }
         } catch (ReasoningServiceException e) {
             log.error("Error thrown: {}", e);
@@ -390,10 +439,9 @@ public class ReasoningServiceTaskResourc
                 } else {
                     return Response.ok(output).build();
                 }
-
             } else {
-                log.error("Not implemented yet! :(");
-                throw new WebApplicationException(501);
+                save(output, targetGraphID);
+                return Response.ok().build();
             }
         } catch (ReasoningServiceException e) {
             throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
@@ -407,43 +455,35 @@ public class ReasoningServiceTaskResourc
         }
     }
 
-    /**
-     * Get the inferences from input URL. If url param is null, get the HTML description of this service/task
-     * 
-     * @param url
-     * @return
-     */
-    @GET
-    @Produces({TEXT_HTML, "text/plain", KRFormat.RDF_XML, KRFormat.TURTLE, "text/turtle", "text/n3"})
-    public Response get(@QueryParam("url") String url) {
-        // If url param is missing, we produce the service/task welcome page
-        if (url == null) {
-            return Response.ok(new Viewable("index", this)).build();
-        }
-        log.info("Called GET on service {} to perform task {}", service, taskID);
-        log.info("on input url: {}", url);
-
-        /**
-         * Select the service implementation
-         */
-        if (getCurrentService() instanceof JenaReasoningService) {
-            // Prepare input data
-            Model input = ModelFactory.createDefaultModel().read(url);
-            return executeJenaReasoningService((JenaReasoningService) getCurrentService(), input, null, null);
-        } else if (getCurrentService() instanceof OWLApiReasoningService) {
-            OWLOntology input = null;
-            try {
-                input = createOWLOntologyManager().loadOntologyFromOntologyDocument(IRI.create(url));
-            } catch (OWLOntologyCreationIOException e) {
-                throw new WebApplicationException(e, Response.Status.NOT_FOUND);
-            } catch (OWLOntologyCreationException e) {
-                throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
-            }
-            return executeOWLApiReasoningService((OWLApiReasoningService) getCurrentService(), input, null,
-                null);
+    private void save(Object data, String targetGraphID) {
+        log.info("Attempt saving in target graph {}", targetGraphID);
+        final long startSave = System.currentTimeMillis();
+        LockableMGraph mGraph;
+        UriRef graphUriRef = new UriRef(targetGraphID);
+        try {
+            // Check whether the graph already exists
+            mGraph = this.tcManager.getMGraph(graphUriRef);
+        } catch (NoSuchEntityException e) {
+            mGraph = this.tcManager.createMGraph(graphUriRef);
+        }
+        // We lock the graph before proceed
+        Lock writeLock = mGraph.getLock().writeLock();
+        boolean saved = false;
+        if (data instanceof Model) {
+            MGraph m = JenaToClerezzaConverter.jenaModelToClerezzaMGraph((Model) data);
+            writeLock.lock();
+            saved = mGraph.addAll(m);
+            writeLock.unlock();
+        } else if (data instanceof OWLOntology) {
+            MGraph m = OWLAPIToClerezzaConverter.owlOntologyToClerezzaMGraph((OWLOntology) data);
+            writeLock.lock();
+            saved = mGraph.addAll(m);
+            writeLock.unlock();
         }
-        throw new WebApplicationException(new Exception("Unsupported implementation"),
+        if (!saved) throw new WebApplicationException(new IOException("Cannot save model!"),
                 Response.Status.INTERNAL_SERVER_ERROR);
+        final long endSave = System.currentTimeMillis();
+        log.info("Save time: {}", (endSave - startSave));
     }
 
     private OWLOntologyManager createOWLOntologyManager() {