You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stanbol.apache.org by al...@apache.org on 2011/03/16 16:31:11 UTC

svn commit: r1082166 [4/7] - in /incubator/stanbol/trunk/kres/rules/manager: ./ src/ src/main/ src/main/java/ src/main/java/org/ src/main/java/org/apache/ src/main/java/org/apache/stanbol/ src/main/java/org/apache/stanbol/rules/ src/main/java/org/apach...

Added: incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSRemoveRecipe.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSRemoveRecipe.java?rev=1082166&view=auto
==============================================================================
--- incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSRemoveRecipe.java (added)
+++ incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSRemoveRecipe.java Wed Mar 16 15:31:08 2011
@@ -0,0 +1,297 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package org.apache.stanbol.rules.manager.changes;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Vector;
+
+import org.apache.stanbol.rules.base.api.RuleStore;
+import org.semanticweb.owlapi.apibinding.OWLManager;
+import org.semanticweb.owlapi.model.AddImport;
+import org.semanticweb.owlapi.model.IRI;
+import org.semanticweb.owlapi.model.OWLClass;
+import org.semanticweb.owlapi.model.OWLDataFactory;
+import org.semanticweb.owlapi.model.OWLImportsDeclaration;
+import org.semanticweb.owlapi.model.OWLNamedIndividual;
+import org.semanticweb.owlapi.model.OWLObjectProperty;
+import org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom;
+import org.semanticweb.owlapi.model.OWLOntology;
+import org.semanticweb.owlapi.model.OWLOntologyChange;
+import org.semanticweb.owlapi.model.OWLOntologyCreationException;
+import org.semanticweb.owlapi.model.OWLOntologyManager;
+import org.semanticweb.owlapi.util.OWLEntityRemover;
+
+/**
+ * This class will remove a recipe from the KReSRuleStore used as input.<br/>
+ * The KReSRuleStore object used as input is not changed and to get the new modified KReSRuleStore there is the method getStore().<br/>
+ * If the recipe name or IRI is not already inside the KReSRuleStore an error is lunched and the process stopped.
+ *
+ */
+public class KReSRemoveRecipe {
+
+
+   private OWLOntology owlmodel;
+   private OWLOntologyManager owlmanager;
+   private OWLDataFactory factory;
+   private String owlIDrmi;
+   private String owlID;
+   public RuleStore storeaux;
+
+   /**
+     * To create a list of imported ontlogy to be added as import declarations
+     *
+     * @param inowl {Input ontology where to get the import declarations}
+     * @return {A list of declarations}
+     */
+	private List<OWLOntologyChange> createImportList(OWLOntology inowl,OWLOntology toadd){
+		
+        Iterator<OWLOntology> importedonto = inowl.getDirectImports().iterator();
+        List<OWLOntologyChange> additions = new LinkedList<OWLOntologyChange>();
+        OWLDataFactory auxfactory = inowl.getOWLOntologyManager().getOWLDataFactory();
+		
+        while(importedonto.hasNext()){
+            OWLOntology auxonto = importedonto.next();
+            additions.add(new AddImport(toadd,auxfactory.getOWLImportsDeclaration(auxonto.getOWLOntologyManager().getOntologyDocumentIRI(auxonto))));
+        }
+		
+        if(additions.size()==0){
+            Iterator<OWLImportsDeclaration> importedontob = inowl.getImportsDeclarations().iterator();
+            additions = new LinkedList<OWLOntologyChange>();
+            auxfactory = inowl.getOWLOntologyManager().getOWLDataFactory();
+			
+            while(importedontob.hasNext()){
+                OWLImportsDeclaration  auxontob = importedontob.next();
+                additions.add(new AddImport(toadd,auxontob));
+            }
+        }
+		
+        return additions;
+    }
+
+   /**
+     * To clone ontology with all its axioms and imports declaration
+     *
+     * @param inowl {The onotlogy to be cloned}
+     * @return {An ontology with the same characteristics}
+     */
+    private void cloneOntology(OWLOntology inowl){
+
+        //Clone the targetontology
+        try {
+            this.owlmodel = OWLManager.createOWLOntologyManager().createOntology(inowl.getOntologyID().getOntologyIRI());
+            this.owlmanager = owlmodel.getOWLOntologyManager();
+            //Add axioms
+            owlmanager.addAxioms(owlmodel,inowl.getAxioms());
+            //Add import declaration
+            List<OWLOntologyChange> additions = createImportList(inowl,owlmodel);
+            if(additions.size()>0)
+                owlmanager.applyChanges(additions);
+           
+        } catch (OWLOntologyCreationException ex) {
+            ex.printStackTrace();
+        }
+
+    }
+
+   /**
+    * Constructor, the input is a KReSRuleStore object.<br/>
+    * N.B. To get the new KReSRuleStore object there is the method getStore().
+    * @param store {The KReSRuleStore where there are the added rules and recipes.}
+    */
+   public KReSRemoveRecipe(RuleStore store){
+       this.storeaux = store;
+       cloneOntology(store.getOntology());
+       this.factory = owlmanager.getOWLDataFactory();
+       this.owlIDrmi="http://kres.iks-project.eu/ontology/meta/rmi.owl#";
+       this.owlID = owlmodel.getOntologyID().getOntologyIRI().toString()+"#";
+   }
+
+    /**
+    * Constructor, the input is a KReSRuleStore object and a string contains the base iri of the resource.<br/>
+    *
+    * @param store {The KReSRuleStore where there are the added rules and recipes.}
+    * @param owlid {The base iri of resource}
+    */
+   public KReSRemoveRecipe(RuleStore store, String owlid){
+       this.storeaux = store;
+       cloneOntology(storeaux.getOntology());
+       this.factory = owlmanager.getOWLDataFactory();
+       this.owlIDrmi="http://kres.iks-project.eu/ontology/meta/rmi.owl#";
+       this.owlID = owlid;
+   }
+
+   /**
+    * To remove a recipe with a given name.
+    *
+    * @param recipeName {The recipe string name.}
+    * @return {Return true is the process finished without errors.}
+    */
+   public boolean removeRecipe(String recipeName){
+       boolean ok = false;
+       OWLClass ontocls = factory.getOWLClass(IRI.create(owlIDrmi+"Recipe"));
+       OWLNamedIndividual ontoind = factory.getOWLNamedIndividual(IRI.create(owlID+recipeName));
+       OWLEntityRemover remover = new OWLEntityRemover(owlmanager, Collections.singleton(owlmodel));
+       OWLObjectProperty precedes = factory.getOWLObjectProperty(IRI.create("http://www.ontologydesignpatterns.org/cp/owl/sequence.owl#directlyPrecedes"));
+       OWLObjectPropertyAssertionAxiom objectPropAssertion;
+
+        KReSGetRecipe getrecipe = new KReSGetRecipe(storeaux);
+        HashMap<IRI, String> map = getrecipe.getRecipe(recipeName);
+        
+        String[] sequence = map.get(IRI.create(owlID+recipeName)).split(",");
+        Vector<IRI> ruleseq = new Vector();
+        for(String seq : sequence){
+            if(!seq.replace(" ","").trim().isEmpty())
+                ruleseq.add(IRI.create(seq.replace(" ","").trim()));
+        }
+        HashMap<String, Integer> count = getrecipe.getBinSequenceRecipeCount();
+        Vector<String> binseq = new Vector();
+        String bs="";
+        for(int i = 0; i<ruleseq.size()-1;i++){
+            bs=ruleseq.get(i).toString()+" precedes "+ruleseq.get(i+1).toString();
+            if(count.containsKey(bs)){
+                if(count.get(bs)==1){
+                    binseq.add(bs);
+                }
+            }
+        }
+
+       if(owlmodel.containsAxiom(factory.getOWLClassAssertionAxiom(ontocls, ontoind))){
+
+            ontoind.accept(remover);
+            owlmanager.applyChanges(remover.getChanges());
+            remover.reset();
+
+           if(owlmodel.containsAxiom(factory.getOWLClassAssertionAxiom(ontocls, ontoind))){
+               System.err.println("Some error occurs during deletion.");
+               ok = false;
+               return(ok);
+           }else{
+
+                for(int i = 0; i<binseq.size(); i++){
+                    String[] iris = binseq.get(i).split(" precedes ");
+                    OWLNamedIndividual ontoindA = factory.getOWLNamedIndividual(IRI.create(iris[0].replace(" ","").trim()));
+                    OWLNamedIndividual ontoindB = factory.getOWLNamedIndividual(IRI.create(iris[1].replace(" ","").trim()));
+                    objectPropAssertion = factory.getOWLObjectPropertyAssertionAxiom(precedes,ontoindA, ontoindB);
+                    if(owlmodel.containsAxiom(objectPropAssertion)){
+                        owlmanager.removeAxiom(owlmodel, objectPropAssertion);
+                        if(!owlmodel.containsAxiom(objectPropAssertion)){
+                            ok = true;
+                        }else{
+                            System.err.println("Some error occurs during deletion.");
+                            ok = false;
+                            return(ok);
+                        }
+                    }
+                }
+           }
+
+       }else{
+           System.err.println("The rule with name "+recipeName+" is not inside the ontology. Pleas check the name.");
+           ok =false;
+           return(ok);
+       }
+
+       if(ok)
+           this.storeaux.setStore(owlmodel);
+       
+       return ok;
+   }
+
+   /**
+    * To remove a recipe with a given IRI.
+    *
+    * @param recipeName {The complete recipe IRI.}
+    * @return {Return true is the process finished without errors.}
+    */
+   public boolean removeRecipe(IRI recipeName){
+       boolean ok = false;
+       OWLClass ontocls = factory.getOWLClass(IRI.create(owlIDrmi+"Recipe"));
+       OWLNamedIndividual ontoind = factory.getOWLNamedIndividual(recipeName);
+       OWLEntityRemover remover = new OWLEntityRemover(owlmanager, Collections.singleton(owlmodel));
+       OWLObjectProperty precedes = factory.getOWLObjectProperty(IRI.create("http://www.ontologydesignpatterns.org/cp/owl/sequence.owl#directlyPrecedes"));
+       OWLObjectPropertyAssertionAxiom objectPropAssertion;
+
+        KReSGetRecipe getrecipe = new KReSGetRecipe(storeaux);
+        HashMap<IRI, String> map = getrecipe.getRecipe(recipeName);
+        
+        String[] sequence = map.get(recipeName).split(",");
+        Vector<IRI> ruleseq = new Vector();
+        for(String seq : sequence){
+            if(!seq.replace(" ","").trim().isEmpty())
+                ruleseq.add(IRI.create(seq.replace(" ","").trim()));
+        }
+        HashMap<String, Integer> count = getrecipe.getBinSequenceRecipeCount();
+       
+        Vector<String> binseq = new Vector();
+        String bs="";
+        for(int i = 0; i<ruleseq.size()-1;i++){
+            bs=ruleseq.get(i).toString()+" precedes "+ruleseq.get(i+1).toString();
+            if(count.containsKey(bs)){
+                if(count.get(bs)==1){
+                    binseq.add(bs);
+                }
+            }
+        }
+   
+       if(owlmodel.containsAxiom(factory.getOWLClassAssertionAxiom(ontocls, ontoind))){
+
+            ontoind.accept(remover);
+            owlmanager.applyChanges(remover.getChanges());
+            remover.reset();
+
+           if(owlmodel.containsAxiom(factory.getOWLClassAssertionAxiom(ontocls, ontoind))){
+               System.err.println("Some error occurs during deletion.");
+               ok = false;
+               return(ok);
+           }else{
+                if(binseq.size()>0){
+                for(int i = 0; i<binseq.size(); i++){
+                    String[] iris = binseq.get(i).split(" precedes ");
+                    OWLNamedIndividual ontoindA = factory.getOWLNamedIndividual(IRI.create(iris[0].replace(" ","").trim()));
+                    OWLNamedIndividual ontoindB = factory.getOWLNamedIndividual(IRI.create(iris[1].replace(" ","").trim()));
+                    objectPropAssertion = factory.getOWLObjectPropertyAssertionAxiom(precedes,ontoindA, ontoindB);
+                    if(owlmodel.containsAxiom(objectPropAssertion)){
+                        owlmanager.removeAxiom(owlmodel, objectPropAssertion);
+                        if(!owlmodel.containsAxiom(objectPropAssertion)){
+                            ok = true;
+                        }else{
+                            System.err.println("Some error occurs during deletion.");
+                            ok = false;
+                            return(ok);
+                        }
+                    }
+                }
+                }else{
+                    ok = true;
+                }
+           }
+
+       }else{
+           System.err.println("The rule with name "+recipeName+" is not inside the ontology. Pleas check the name.");
+           ok =false;
+           return(ok);
+       }
+
+       if(ok){
+           this.storeaux.setStore(owlmodel);
+       }
+       return ok;
+   }
+
+   /**
+     * Get the KReSRuleStore filled with rules and recipes
+    *
+     * @return {A KReSRuleStore object with the stored rules and recipes.}
+     */
+     public RuleStore getStore(){
+         return this.storeaux;
+     }
+
+}

Added: incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSRemoveRule.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSRemoveRule.java?rev=1082166&view=auto
==============================================================================
--- incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSRemoveRule.java (added)
+++ incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSRemoveRule.java Wed Mar 16 15:31:08 2011
@@ -0,0 +1,329 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package org.apache.stanbol.rules.manager.changes;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Vector;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.apache.stanbol.rules.base.api.RuleStore;
+import org.semanticweb.owlapi.apibinding.OWLManager;
+import org.semanticweb.owlapi.model.AddImport;
+import org.semanticweb.owlapi.model.IRI;
+import org.semanticweb.owlapi.model.OWLAxiom;
+import org.semanticweb.owlapi.model.OWLClass;
+import org.semanticweb.owlapi.model.OWLDataFactory;
+import org.semanticweb.owlapi.model.OWLImportsDeclaration;
+import org.semanticweb.owlapi.model.OWLNamedIndividual;
+import org.semanticweb.owlapi.model.OWLObjectProperty;
+import org.semanticweb.owlapi.model.OWLOntology;
+import org.semanticweb.owlapi.model.OWLOntologyChange;
+import org.semanticweb.owlapi.model.OWLOntologyCreationException;
+import org.semanticweb.owlapi.model.OWLOntologyManager;
+import org.semanticweb.owlapi.util.OWLEntityRemover;
+
+/**
+ * This class will remove a rule from the KReSRuleStore used as input.<br/>
+ * The KReSRuleStore object used as input is not changed and to get the new modified KReSRuleStore there is the method getStore().<br/>
+ * If the rule name or IRI is not already inside the KReSRuleStore an error is lunched and the process stopped.
+ *
+ */
+public class KReSRemoveRule {
+   private OWLOntology owlmodel;
+   private OWLOntologyManager owlmanager;
+   private OWLDataFactory factory;
+   private String owlIDrmi;
+   private String owlID;
+   private RuleStore storeaux;
+
+   /**
+     * To create a list of imported ontlogy to be added as import declarations
+     *
+     * @param inowl {Input ontology where to get the import declarations}
+     * @return {A list of declarations}
+     */
+    private List<OWLOntologyChange> createImportList(OWLOntology inowl,OWLOntology toadd){
+
+        Iterator<OWLOntology> importedonto = inowl.getDirectImports().iterator();
+        List<OWLOntologyChange> additions = new LinkedList<OWLOntologyChange>();
+        OWLDataFactory auxfactory = inowl.getOWLOntologyManager().getOWLDataFactory();
+
+        while(importedonto.hasNext()){
+            OWLOntology auxonto = importedonto.next();
+            additions.add(new AddImport(toadd,auxfactory.getOWLImportsDeclaration(auxonto.getOWLOntologyManager().getOntologyDocumentIRI(auxonto))));
+        }
+
+        if(additions.size()==0){
+            Iterator<OWLImportsDeclaration> importedontob = inowl.getImportsDeclarations().iterator();
+            additions = new LinkedList<OWLOntologyChange>();
+            auxfactory = inowl.getOWLOntologyManager().getOWLDataFactory();
+
+            while(importedontob.hasNext()){
+                OWLImportsDeclaration  auxontob = importedontob.next();
+                additions.add(new AddImport(toadd,auxontob));
+            }
+        }
+
+        return additions;
+    }
+
+   /**
+     * To clone ontology with all its axioms and imports declaration
+     *
+     * @param inowl {The onotlogy to be cloned}
+     * @return {An ontology with the same characteristics}
+     */
+    private void cloneOntology(OWLOntology inowl){
+
+        //Clone the targetontology
+        try {
+            this.owlmodel = OWLManager.createOWLOntologyManager().createOntology(inowl.getOntologyID().getOntologyIRI());
+            this.owlmanager = owlmodel.getOWLOntologyManager();
+            //Add axioms
+            owlmanager.addAxioms(owlmodel,inowl.getAxioms());
+            //Add import declaration
+            List<OWLOntologyChange> additions = createImportList(inowl,owlmodel);
+            if(additions.size()>0)
+                owlmanager.applyChanges(additions);
+        } catch (OWLOntologyCreationException ex) {
+            ex.printStackTrace();
+        }
+
+    }
+
+  /**
+    * Constructor, the input is a KReSRuleStore object.<br/>
+    * N.B. To get the new KReSRuleStore object there is the method getStore();
+    * @param store {The KReSRuleStore where there are the added rules and recipes.}
+    */
+   public KReSRemoveRule(RuleStore store){
+       this.storeaux = store;
+       cloneOntology(storeaux.getOntology());
+       this.factory = owlmanager.getOWLDataFactory();
+       this.owlIDrmi ="http://kres.iks-project.eu/ontology/meta/rmi.owl#";
+       this.owlID = owlmodel.getOntologyID().getOntologyIRI()+"#";
+   }
+
+   /**
+    * Constructor, the input is a KReSRuleStore object.<br/>
+    * N.B. To get the new KReSRuleStore object there is the method getStore();
+    * @param store {The KReSRuleStore where there are the added rules and recipes.}
+    */
+   public KReSRemoveRule(RuleStore store,String owlid){
+       this.storeaux = store;
+       cloneOntology(storeaux.getOntology());
+       this.factory = owlmanager.getOWLDataFactory();
+       this.owlID = owlid;
+       this.owlIDrmi = "http://kres.iks-project.eu/ontology/meta/rmi.owl#";
+   }
+
+   /**
+    * To remove a rule with a given name.
+    *
+    * @param ruleName {The rule string name.}
+    * @return {Return true is the process finished without errors.}
+    */
+   public boolean removeRule(String ruleName){
+       boolean ok = false;
+       OWLClass ontocls = factory.getOWLClass(IRI.create(owlIDrmi+"KReSRule"));
+       OWLNamedIndividual ontoind = factory.getOWLNamedIndividual(IRI.create(owlID+ruleName));
+       OWLObjectProperty hasrule = factory.getOWLObjectProperty(IRI.create(owlIDrmi+"hasRule"));
+       OWLEntityRemover remover = new OWLEntityRemover(owlmanager, Collections.singleton(owlmodel));
+
+       if(owlmodel.containsAxiom(factory.getOWLClassAssertionAxiom(ontocls, ontoind))){
+           
+            ontoind.accept(remover);
+            List<OWLOntologyChange> list = remover.getChanges();
+            Iterator<OWLOntologyChange> iter = list.iterator();
+            Vector<String> usage = new Vector();
+
+            while(iter.hasNext()){
+                OWLAxiom ax =iter.next().getAxiom();
+                if(ax.getObjectPropertiesInSignature().contains(hasrule)){
+                    usage.add(Arrays.toString(ax.getIndividualsInSignature().toArray()));
+              
+                }
+            }
+
+            if(usage.isEmpty()){
+                        ok = true;
+                        owlmanager.applyChanges(remover.getChanges());
+                        remover.reset();
+                    }else{
+                         System.err.println("The rule cannot be deleted because is used by some recipes. Pleas check the following recipes:");
+                         System.err.println(usage.toString());
+                         ok = false;
+                         return(ok);
+                 }
+
+           if(owlmodel.containsAxiom(factory.getOWLClassAssertionAxiom(ontocls, ontoind))){
+               System.err.println("Some error occurs during deletion.");
+               ok = false;
+               return(ok);
+           }else{
+                ok = true;
+           }
+
+       }else{
+           System.err.println("The rule with name "+ruleName+" is not inside the ontology. Pleas check the name.");
+           ok =false;
+           return(ok);
+       }
+
+       if(ok)
+           this.storeaux.setStore(owlmodel);
+
+       return ok;
+   }
+
+   /**
+    * To remove a rule with a given IRI.
+    *
+    * @param ruleName {The rule complete IRI.}
+    * @return {Return true is the process finished without errors.}
+    */
+   public boolean removeRule(IRI ruleName){
+       boolean ok = false;
+       OWLClass ontocls = factory.getOWLClass(IRI.create(owlIDrmi+"KReSRule"));
+       OWLNamedIndividual ontoind = factory.getOWLNamedIndividual(ruleName);
+       OWLObjectProperty hasrule = factory.getOWLObjectProperty(IRI.create(owlIDrmi+"hasRule"));
+       OWLEntityRemover remover = new OWLEntityRemover(owlmanager, Collections.singleton(owlmodel));
+
+       if(owlmodel.containsAxiom(factory.getOWLClassAssertionAxiom(ontocls, ontoind))){
+
+            ontoind.accept(remover);
+            List<OWLOntologyChange> list = remover.getChanges();
+            Iterator<OWLOntologyChange> iter = list.iterator();
+            Vector<String> usage = new Vector();
+
+            while(iter.hasNext()){
+                OWLAxiom ax =iter.next().getAxiom();
+                if(ax.getObjectPropertiesInSignature().contains(hasrule)){
+                    usage.add(Arrays.toString(ax.getIndividualsInSignature().toArray()));
+
+                }
+            }
+
+            if(usage.isEmpty()){
+                        ok = true;
+                        owlmanager.applyChanges(remover.getChanges());
+                        remover.reset();
+                    }else{
+                         System.err.println("The rule cannot be deleted because is used by some recipes. Pleas check the following recipes:");
+                         System.err.println(usage.toString());
+                         ok = false;
+                         return(ok);
+                 }
+
+           if(owlmodel.containsAxiom(factory.getOWLClassAssertionAxiom(ontocls, ontoind))){
+               System.err.println("Some error occurs during deletion.");
+               ok = false;
+               return(ok);
+           }else{
+                ok = true;
+           }
+
+       }else{
+           System.err.println("The rule with name "+ruleName+" is not inside the ontology. Pleas check the name.");
+           ok =false;
+           return(ok);
+       }
+
+       if(ok)
+           this.storeaux.setStore(owlmodel);
+
+       return ok;
+
+   }
+
+    /**
+     * Get the KReSRuleStore filled with rules and recipes
+    *
+     * @return {A KReSRuleStore object with the stored rules and recipes.}
+     */
+     public RuleStore getStore(){
+         return this.storeaux;
+     }
+
+   /**
+      * Delete a single rule from a recipe
+      * @param ruleName {The IRI of the rule}
+      * @param recipeName {The IRI of the recipe}
+      * @return {True if the operation works.}
+      */
+     public boolean removeRuleFromRecipe(IRI ruleName, IRI recipeName){
+         boolean ok = false;
+         OWLClass ontoclsrule = factory.getOWLClass(IRI.create(owlIDrmi+"KReSRule"));
+         OWLClass ontoclsrecipe = factory.getOWLClass(IRI.create(owlIDrmi+"Recipe"));
+         OWLNamedIndividual rule = factory.getOWLNamedIndividual(ruleName);
+         OWLNamedIndividual recipe = factory.getOWLNamedIndividual(recipeName);
+
+         if(!owlmodel.containsAxiom(factory.getOWLClassAssertionAxiom(ontoclsrule, rule))){
+              System.err.println("The rule with name "+ruleName+" is not inside the ontology. Pleas check the name.");
+              if(!owlmodel.containsAxiom(factory.getOWLClassAssertionAxiom(ontoclsrecipe, recipe))){
+                System.err.println("The rule with name "+recipeName+" is not inside the ontology. Pleas check the name.");
+                return false;
+              }
+              return false;
+         }
+
+        //Get the recipe
+        KReSGetRecipe getrecipe = new KReSGetRecipe(storeaux);
+        HashMap<IRI, String> map = getrecipe.getRecipe(recipeName);
+
+        String[] sequence = map.get(recipeName).split(",");
+        Vector<IRI> ruleseq = new Vector();
+        for(String seq : sequence)
+            ruleseq.add(IRI.create(seq.replace(" ","").trim()));
+
+        String desc = getrecipe.getDescription(recipeName);
+        if(desc.isEmpty()){
+            System.err.println("Description for "+recipeName+" not found");
+                return false;
+        }
+
+        if(ruleseq.contains(ruleName))
+            ruleseq.remove(ruleseq.indexOf(ruleName));
+        else{
+            System.err.println("The rule with name "+ruleName+" is not inside the ontology. Pleas check the name.");
+            return false;
+        }
+
+            //Remove the old recipe
+            KReSRemoveRecipe remove;
+            try {
+            remove = new KReSRemoveRecipe(storeaux);
+                ok = remove.removeRecipe(recipeName);
+            } catch (Exception ex) {
+                Logger.getLogger(KReSRemoveRule.class.getName()).log(Level.SEVERE, null, ex);
+            }
+            
+            if(!ok){
+                System.err.println("Some errors occured when delete "+ruleName+" in recipe "+recipeName);
+                return false;
+            }
+
+            //Add the recipe with without the specified rule
+            KReSAddRecipe newadd = new KReSAddRecipe(storeaux);
+            if(ruleseq.isEmpty())
+                ok = newadd.addSimpleRecipe(recipeName, desc);
+            else
+                ok = newadd.addRecipe(recipeName, ruleseq, desc);
+            if(ok){
+                return true;
+            }else{
+                return false;
+            }
+     }
+
+
+}

Added: incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSRuleStore.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSRuleStore.java?rev=1082166&view=auto
==============================================================================
--- incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSRuleStore.java (added)
+++ incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSRuleStore.java Wed Mar 16 15:31:08 2011
@@ -0,0 +1,698 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package org.apache.stanbol.rules.manager.changes;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URL;
+import java.util.Collections;
+import java.util.Dictionary;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+import java.util.Vector;
+
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Property;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.Service;
+import org.apache.stanbol.ontologymanager.ontonet.api.KReSONManager;
+import org.apache.stanbol.rules.base.api.KReSRule;
+import org.apache.stanbol.rules.base.api.NoSuchRecipeException;
+import org.apache.stanbol.rules.base.api.Recipe;
+import org.apache.stanbol.rules.base.api.RuleStore;
+import org.apache.stanbol.rules.base.api.util.KReSRuleList;
+import org.apache.stanbol.rules.base.api.util.RecipeList;
+import org.apache.stanbol.rules.manager.KReSKB;
+import org.apache.stanbol.rules.manager.parse.KReSRuleParser;
+import org.osgi.service.component.ComponentContext;
+import org.semanticweb.owlapi.apibinding.OWLManager;
+import org.semanticweb.owlapi.model.IRI;
+import org.semanticweb.owlapi.model.OWLAxiom;
+import org.semanticweb.owlapi.model.OWLClass;
+import org.semanticweb.owlapi.model.OWLClassAssertionAxiom;
+import org.semanticweb.owlapi.model.OWLDataFactory;
+import org.semanticweb.owlapi.model.OWLDataProperty;
+import org.semanticweb.owlapi.model.OWLDataPropertyAssertionAxiom;
+import org.semanticweb.owlapi.model.OWLIndividual;
+import org.semanticweb.owlapi.model.OWLLiteral;
+import org.semanticweb.owlapi.model.OWLNamedIndividual;
+import org.semanticweb.owlapi.model.OWLObjectProperty;
+import org.semanticweb.owlapi.model.OWLOntology;
+import org.semanticweb.owlapi.model.OWLOntologyCreationException;
+import org.semanticweb.owlapi.model.OWLOntologyManager;
+import org.semanticweb.owlapi.model.OWLOntologyStorageException;
+import org.semanticweb.owlapi.util.OWLEntityRemover;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class creates an OWLOntology object where to store rules and recipes.
+ * 
+ * @author elvio
+ * @author andrea.nuzzolese
+ * 
+ */
+
+@Component(immediate = true, metatype = true)
+@Service(RuleStore.class)
+public class KReSRuleStore implements RuleStore {
+
+    @Reference
+    KReSONManager onManager;
+
+    @Property(value = "")
+    public static final String RULE_ONTOLOGY = "rule.ontology";
+
+    @Property(value = "http://kres.iks-project.eu/ontology/meta/rmi.owl#")
+    public static final String RULE_ONTOLOGY_NAMESPACE = "rule.ontology.namespace";
+
+    private final Logger log = LoggerFactory.getLogger(getClass());
+    private OWLOntology owlmodel;
+    private String file;
+    private String alias;
+    private RuleStore ruleStore;
+    private File owlfile;
+    private String ruleOntologyNS;
+
+    private KReSRuleParser kReSRuleParser;
+
+    /**
+     * This construct returns KReSRuleStore object with inside an ontology where to store the rules.
+     * 
+     * This default constructor is <b>only</b> intended to be used by the OSGI environment with Service
+     * Component Runtime support.
+     * <p>
+     * DO NOT USE to manually create instances - the KReSRuleStore instances do need to be configured! YOU
+     * NEED TO USE {@link #KReSRuleStore(KReSONManager, Dictionary)} or its overloads, to parse the
+     * configuration and then initialise the rule store if running outside a OSGI environment.
+     */
+    public KReSRuleStore() {
+
+    /*
+     * The constructor should be empty as some issue derives from a filled one. The old version can be invoked
+     * with KReSRuleStore(null)
+     */
+    }
+
+    public KReSRuleStore(KReSONManager onm, Dictionary<String,Object> configuration) {
+        this();
+        this.onManager = onm;
+        activate(configuration);
+    }
+
+    /**
+     * This construct returns an ontology where to store the rules.
+     * 
+     * @param filepath
+     *            {Ontology file path previously stored.}
+     */
+    public KReSRuleStore(KReSONManager onm, Dictionary<String,Object> configuration, String filepath) {
+        /*
+         * FIXME : This won't work if the activate() method is called at the end of the constructor, like it
+         * is for other components. Constructors should not override activate().
+         */
+        // This recursive constructor call will also invoke activate()
+        this(onm, configuration);
+
+        if (filepath.isEmpty()) {
+            try {
+
+                // Obsolete code
+                Properties configProps = System.getProperties();
+                String userdir = configProps.getProperty("user.dir");
+                
+                String respath = "src/main/resources/";
+                String filepath2 = "RuleOntology/rmi_config.owl";
+//                userdir = userdir.substring(0, userdir.lastIndexOf("kres.") + 5) + "rules/";
+             
+                userdir += "/";
+                
+                this.file = userdir + respath + filepath2;
+                this.owlfile = new File(file);
+                owlfile.setWritable(true);
+
+//                InputStream is = this.getClass().getResourceAsStream("/RuleOntology/rmi_config.owl");
+//                URL url = this.getClass().getResource("/RuleOntology/rmi_config.owl");
+//                System.err.println("DIOCANE "+url.toURI());
+//               this.owlfile = new File(url.toURI());
+//               owlfile.setWritable(true);
+                
+                OWLOntologyManager owlmanager = OWLManager.createOWLOntologyManager();
+                this.owlmodel = owlmanager.loadOntologyFromOntologyDocument(IRI.create(owlfile));
+
+            } catch (Exception io) {
+                log.error(io.getLocalizedMessage(), io);
+                this.owlmodel = null;
+            }
+        } else {
+            this.file = filepath;
+            this.owlfile = new File(file);
+            owlfile.setWritable(true);
+            OWLOntologyManager owlmanager = OWLManager.createOWLOntologyManager();
+            try {
+                this.owlmodel = owlmanager.loadOntologyFromOntologyDocument(owlfile);
+            } catch (OWLOntologyCreationException oce) {
+                log.error(oce.getLocalizedMessage(), oce);
+                this.owlmodel = null;
+            }
+
+        }
+        // activate(configuration);
+
+    }
+
+    /**
+     * This construct returns an ontology where to store the rules.
+     * 
+     * @param owl
+     *            {OWLOntology object contains rules and recipe}
+     */
+    public KReSRuleStore(KReSONManager onm, Dictionary<String,Object> configuration, OWLOntology owl) {
+        /*
+         * FIXME : This won't work if the activate() method is called at the end of the constructor, like it
+         * is for other components. Constructors should not override activate().
+         */
+        // This recursive constructor call will also invoke activate()
+        this(onm, configuration);
+
+        try {
+            this.owlmodel = owl;
+        } catch (Exception e) {
+            log.error(e.getLocalizedMessage(), e);
+            this.owlmodel = null;
+        }
+        // activate(configuration);
+    }
+
+    /**
+     * Get the owl ontology model.
+     * 
+     * @return {An OWLOntology object where to store the rules and the recipes.}
+     */
+    @Override
+    public OWLOntology getOntology() {
+        return this.owlmodel;
+    }
+
+    /**
+     * To set new OWLOntology with stored rules and recipes.
+     * 
+     * @param owl
+     *            {OWLOntology with new changes.}
+     */
+    @Override
+    public void setStore(OWLOntology owl) {
+
+        this.owlmodel = owl;
+    }
+
+    /**
+     * Used to configure an instance within an OSGi container.
+     * 
+     * @throws IOException
+     */
+    @SuppressWarnings("unchecked")
+    @Activate
+    protected void activate(ComponentContext context) throws IOException {
+        log.info("in " + KReSRuleStore.class + " activate with context " + context);
+        if (context == null) {
+            throw new IllegalStateException("No valid" + ComponentContext.class + " parsed in activate!");
+        }
+        activate((Dictionary<String,Object>) context.getProperties());
+    }
+
+    protected void activate(Dictionary<String,Object> configuration) {
+
+        this.file = (String) configuration.get(RULE_ONTOLOGY);
+        this.ruleOntologyNS = (String) configuration.get(RULE_ONTOLOGY_NAMESPACE);
+
+        if (file == null || file.equals("")) {
+            // InputStream ontologyStream =
+            // this.getClass().getResourceAsStream("/META-INF/conf/KReSOntologyRules.owl");
+            IRI inputontology = IRI.create("http://ontologydesignpatterns.org/ont/iks/kres/rmi_config.owl");
+            // if (inputontology == null) {
+            // log.err("Input ontology is null");
+            // }
+            try {
+                owlmodel = OWLManager.createOWLOntologyManager().loadOntologyFromOntologyDocument(
+                    inputontology);
+            } catch (OWLOntologyCreationException e) {
+                log.error("Cannot create the ontology " + inputontology.toString(), e);
+            } catch (Exception e) {
+                log.error("Rule Store: no rule ontology available.");
+            }
+
+            if (owlmodel != null) {
+
+                File dirs = new File("./KReSConf");
+                if (!dirs.exists()) dirs.mkdir();
+                file = "./KReSConf/rmi_config.owl";
+
+                FileOutputStream fos;
+                try {
+                    fos = new FileOutputStream(file);
+                    OWLManager.createOWLOntologyManager().saveOntology(owlmodel,
+                        owlmodel.getOWLOntologyManager().getOntologyFormat(owlmodel), fos);
+                } catch (FileNotFoundException e) {
+                    log.error("Cannot save the RMI configuration ontology", e);
+                } catch (OWLOntologyStorageException e) {
+                    log.error("Cannot save the RMI configuration ontology", e);
+                }
+            }
+        } else {
+            IRI pathIri = IRI.create(file);
+            try {
+                owlmodel = OWLManager.createOWLOntologyManager().loadOntologyFromOntologyDocument(pathIri);
+            } catch (OWLOntologyCreationException e) {
+                log.error("Cannot load the RMI configuration ontology", e);
+            } catch (Exception e) {
+                log.error("Rule Store: no rule ontology available.");
+            }
+        }
+
+    }
+
+    @Deactivate
+    protected void deactivate(ComponentContext context) {
+        log.info("in " + KReSRuleStore.class + " deactivate with context " + context);
+    }
+
+    @Override
+    public Set<IRI> listIRIRecipes() {
+        Set<IRI> recipeIRIs = null;
+        String ruleNS = owlmodel.getOntologyID().toString().replace("<", "").replace(">", "") + "#";
+
+        OWLDataFactory factory = onManager.getOwlFactory();
+        OWLClass recipeOWLClass = factory.getOWLClass(IRI.create(ruleNS + "Recipe"));
+        Set<OWLIndividual> recipeIndividuals = recipeOWLClass.getIndividuals(owlmodel);
+
+        if (recipeIndividuals != null && recipeIndividuals.size() > 0) {
+            recipeIRIs = new HashSet<IRI>();
+            for (OWLIndividual recipeIndividual : recipeIndividuals) {
+                if (recipeIndividual instanceof OWLNamedIndividual) {
+                    recipeIRIs.add(((OWLNamedIndividual) recipeIndividual).getIRI());
+                }
+            }
+        }
+
+        return recipeIRIs;
+    }
+
+    @Override
+    public Recipe getRecipe(IRI recipeIRI) throws NoSuchRecipeException {
+        log.debug("Called get recipe for id: " + recipeIRI.toString());
+        Recipe recipe = null;
+
+        if (onManager != null && recipeIRI != null) {
+            OWLDataFactory factory = onManager.getOwlFactory();
+            OWLIndividual recipeIndividual = factory.getOWLNamedIndividual(recipeIRI);
+            if (recipeIndividual != null) {
+                // String ruleNS =
+                // owlmodel.getOntologyID().toString().replace("<","").replace(">","")+"#";
+
+                // OWLObjectProperty objectProperty =
+                // factory.getOWLObjectProperty(IRI.create(ruleNS + "hasRule"));
+
+                String ruleNS = "http://kres.iks-project.eu/ontology/meta/rmi.owl#";
+
+                /**
+                 * First get the recipe description in the rule/recipe ontology.
+                 */
+                OWLDataProperty hasDescription = factory.getOWLDataProperty(IRI.create(ruleNS
+                                                                                       + "hasDescription"));
+
+                String recipeDescription = null;
+
+                Set<OWLLiteral> descriptions = recipeIndividual.getDataPropertyValues(hasDescription,
+                    owlmodel);
+                for (OWLLiteral description : descriptions) {
+                    recipeDescription = description.getLiteral();
+                }
+
+                /**
+                 * Then retrieve the rules associated to the recipe in the rule store.
+                 */
+                OWLObjectProperty objectProperty = factory.getOWLObjectProperty(IRI
+                        .create(ruleNS + "hasRule"));
+                Set<OWLIndividual> rules = recipeIndividual.getObjectPropertyValues(objectProperty, owlmodel);
+
+                String kReSRulesInKReSSyntax = "";
+
+                log.debug("The recipe " + recipeIRI.toString() + " has " + rules.size() + " rules.");
+
+                /**
+                 * Fetch the rule content expressed as a literal in KReSRule Syntax.
+                 */
+                boolean firstLoop = true;
+                OWLDataProperty hasBodyAndHead = factory.getOWLDataProperty(IRI.create(ruleNS
+                                                                                       + "hasBodyAndHead"));
+
+                for (OWLIndividual rule : rules) {
+                    log.debug("Getting rule : " + rule.toStringID(), this);
+
+                    Set<OWLLiteral> kReSRuleLiterals = rule.getDataPropertyValues(hasBodyAndHead, owlmodel);
+
+                    if (!firstLoop) {
+                        kReSRulesInKReSSyntax += " . ";
+                    } else {
+                        firstLoop = false;
+                    }
+
+                    for (OWLLiteral kReSRuleLiteral : kReSRuleLiterals) {
+                        String ruleTmp = kReSRuleLiteral.getLiteral().replace("&lt;", "<");
+                        ruleTmp = ruleTmp.replace("&gt;", ">");
+                        log.debug("Rule is: " + ruleTmp);
+                        kReSRulesInKReSSyntax += ruleTmp;
+                    }
+                }
+
+                /**
+                 * Create the Recipe object.
+                 */
+                log.debug("Recipe in KReS Syntax : " + kReSRulesInKReSSyntax);
+
+                KReSRuleList ruleList = null;
+
+                if (!kReSRulesInKReSSyntax.isEmpty()) {
+                    ruleList = generateKnowledgeBase(kReSRulesInKReSSyntax);
+                }
+
+                recipe = new RecipeImpl(recipeIRI, recipeDescription, ruleList);
+
+            } else {
+                throw new NoSuchRecipeException(recipeIRI);
+            }
+        }
+
+        return recipe;
+
+    }
+
+    @Override
+    public RecipeList listRecipes() {
+        RecipeList recipies = null;
+
+        Set<IRI> recipeIRIs = listIRIRecipes();
+
+        if (recipeIRIs != null && recipeIRIs.size() > 0) {
+
+            recipies = new RecipeList();
+            for (IRI recipeIRI : recipeIRIs) {
+                try {
+                    recipies.add(getRecipe(recipeIRI));
+                } catch (NoSuchRecipeException e) {
+                    log.error("Recipe missing: " + recipeIRI.toString(), e);
+                }
+            }
+        }
+        return recipies;
+    }
+
+    /**
+     * To get the file path usde to load the ontology.
+     * 
+     * @return {A string contains the complete file path.}
+     */
+    @Override
+    public String getFilePath() {
+        return this.file;
+    }
+
+    /**
+     * To save some change to the ontology loaded in the store.
+     * 
+     * FIXME: save using the Clerezza TcManager, or the KReS wrapper for it
+     */
+    @Override
+    public void saveOntology() {
+//        try {
+            FileOutputStream fos;
+//            if (this.file.isEmpty()) {
+                File dirs = new File("./KReSConf");
+                if (!dirs.exists()) dirs.mkdir();
+                file = "./KReSConf/rmi_config.owl";
+                try {
+                    fos = new FileOutputStream(file);
+                    OWLManager.createOWLOntologyManager().saveOntology(owlmodel,
+                        owlmodel.getOWLOntologyManager().getOntologyFormat(owlmodel), fos);
+                } catch (FileNotFoundException e) {
+                    log.error("Cannot store the ontology ", e);
+                } catch (OWLOntologyStorageException e) {
+                    log.error("Cannot store the ontology ", e);
+                }
+//            } else {
+//                fos = new FileOutputStream(file);
+//                this.owlmodel.getOWLOntologyManager().saveOntology(owlmodel, fos);
+//            }
+
+//        } catch (OWLOntologyStorageException ex) {
+//            log.error("Cannot store the ontology ", ex);
+//        } catch (FileNotFoundException ex) {
+//            log.error("Cannot store the ontology ", ex);
+//        }
+
+    }
+
+    @Override
+    public String getRuleStoreNamespace() {
+        return owlmodel.getOntologyID().getOntologyIRI() + "#";
+    }
+
+    /*
+     * Moved form KReSAddRecipe class. The KReSAddRecipe should not be used anymore.
+     */
+    @Override
+    public boolean addRecipe(IRI recipeIRI, String recipeDescription) {
+        boolean ok = false;
+        log.debug("Adding recipe " + recipeIRI + " [" + recipeDescription + "]", this);
+        OWLOntologyManager owlmanager = OWLManager.createOWLOntologyManager();
+        OWLDataFactory factory = OWLManager.getOWLDataFactory();
+
+        String owlIDrmi = "http://kres.iks-project.eu/ontology/meta/rmi.owl#";
+
+        OWLClass ontocls = factory.getOWLClass(IRI.create(owlIDrmi + "Recipe"));
+        OWLNamedIndividual ontoind = factory.getOWLNamedIndividual(recipeIRI);
+        OWLDataProperty description = factory.getOWLDataProperty(IRI.create(owlIDrmi + "hasDescription"));
+        OWLDataPropertyAssertionAxiom dataPropAssertion;
+
+        if ((recipeIRI != null)) {
+            if (!owlmodel.containsAxiom(factory.getOWLClassAssertionAxiom(ontocls, ontoind))) {
+
+                // Add the recipe istance
+                OWLClassAssertionAxiom classAssertion = factory.getOWLClassAssertionAxiom(ontocls, ontoind);
+                owlmanager.addAxiom(owlmodel, classAssertion);
+
+                // Add description
+                if ((recipeDescription != null) && !recipeDescription.isEmpty()) {
+                    // Add the rule description
+                    dataPropAssertion = factory.getOWLDataPropertyAssertionAxiom(description, ontoind,
+                        recipeDescription);
+                    owlmanager.addAxiom(owlmodel, dataPropAssertion);
+                    ok = true;
+                }
+            } else {
+                log.error("The recipe with name " + recipeIRI + " already exists. Please check the name.");
+                ok = false;
+                return (ok);
+            }
+
+        } else {
+            log.error("The recipe with name and the set of rules cannot be empity or null.");
+            ok = false;
+            return (ok);
+        }
+
+        if (ok) {
+            setStore(owlmodel);
+        }
+
+        return (ok);
+    }
+
+    /**
+     * 
+     * @param recipeIRI
+     *            the IRI of the recipe
+     * @param kReSRule
+     *            the rule in KReSRule syntax
+     */
+    @Override
+    public Recipe addRuleToRecipe(String recipeID, String kReSRuleInKReSSyntax) throws NoSuchRecipeException {
+
+        Recipe recipe = getRecipe(IRI.create(recipeID));
+        return addRuleToRecipe(recipe, kReSRuleInKReSSyntax);
+
+    }
+
+    /**
+     * 
+     * @param recipe
+     *            the recipe
+     * @param kReSRule
+     *            the rule in KReSRule syntax
+     * 
+     * @return the recipe we the new rule.
+     */
+    @Override
+    public Recipe addRuleToRecipe(Recipe recipe, String kReSRuleInKReSSyntax) {
+        log.debug("Adding rule to recipe " + recipe);
+
+        /**
+         * Get the OWLDataFactory.
+         */
+        OWLDataFactory factory = OWLManager.getOWLDataFactory();
+
+        /**
+         * Add the rule to the recipe in the rule ontology managed by the RuleStore. First we define the
+         * object property hasRule and then we add the literal that contains the rule in KReSRule Syntax to
+         * the recipe individual.
+         */
+        String ruleNS = "http://kres.iks-project.eu/ontology/meta/rmi.owl#";
+        OWLObjectProperty hasRule = factory.getOWLObjectProperty(IRI.create(ruleNS + "hasRule"));
+        OWLDataProperty hasBodyAndHead = factory.getOWLDataProperty(IRI.create(ruleNS + "hasBodyAndHead"));
+
+        /**
+         * The IRI of the recipe is fetched from the recipe object itself. From that IRI is obtained the
+         * recipe owl individual.
+         */
+        IRI recipeIRI = recipe.getRecipeID();
+        OWLNamedIndividual reipeIndividual = factory.getOWLNamedIndividual(recipeIRI);
+
+        OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
+
+        /**
+         * Finally also the in-memory representation of the Recipe passed as input is modified.
+         */
+        KReSKB kReSKB = KReSRuleParser.parse(kReSRuleInKReSSyntax);
+        KReSRuleList ruleList = kReSKB.getkReSRuleList();
+        for (KReSRule rule : ruleList) {
+
+            /**
+             * The rule must be added to the ontology, so 1. an IRI is created from its name 2. the KReS
+             * syntax is added to the rule as a literal through the hasBobyAndHe data property. 3. the rule is
+             * associated to the recipe by means of the hasRule object property, so that the triple <a_recipe
+             * hasRule a_rule> is added to the rule ontology.
+             * 
+             */
+            IRI ruleIRI = IRI.create(ruleNS + rule.getRuleName());
+            OWLNamedIndividual ruleIndividual = factory.getOWLNamedIndividual(ruleIRI);
+
+            OWLAxiom hasBodyAndHeadAxiom = factory.getOWLDataPropertyAssertionAxiom(hasBodyAndHead,
+                ruleIndividual, rule.toKReSSyntax());
+            manager.addAxiom(owlmodel, hasBodyAndHeadAxiom);
+
+            OWLAxiom hasRuleAxiom = factory.getOWLObjectPropertyAssertionAxiom(hasRule, reipeIndividual,
+                ruleIndividual);
+            manager.addAxiom(owlmodel, hasRuleAxiom);
+
+            /**
+             * The KReSRule is added to the Recipe in-memory object.
+             */
+            recipe.addKReSRule(rule);
+        }
+
+        return recipe;
+    }
+
+    @Override
+    public void createRecipe(String recipeID, String rulesInKReSSyntax) {
+        log.debug("Create recipe " + recipeID + " with rules in kres sytnax " + rulesInKReSSyntax, this);
+        KReSKB kb = KReSRuleParser.parse(rulesInKReSSyntax);
+        KReSRuleList rules = kb.getkReSRuleList();
+
+        KReSAddRule addRule = new KReSAddRule(this);
+
+        Vector<IRI> ruleVectorIRIs = new Vector<IRI>();
+        log.debug("Rules are " + rules.size());
+        for (KReSRule rule : rules) {
+            log.debug("Creating rule " + rule.getRuleName());
+            String kReSSyntax = rule.toKReSSyntax();
+
+            log.debug("Rule in KReS Syntax : " + kReSSyntax);
+            addRule.addRule(IRI.create(rule.getRuleName()), kReSSyntax, null);
+            ruleVectorIRIs.add(IRI.create(rule.getRuleName()));
+        }
+
+        if (ruleVectorIRIs.size() > 0) {
+            log.debug("Adding rules: " + ruleVectorIRIs.size());
+            KReSAddRecipe addRecipe = new KReSAddRecipe(this);
+            addRecipe.addRecipe(IRI.create(recipeID), ruleVectorIRIs, null);
+        }
+
+    }
+
+    private KReSRuleList generateKnowledgeBase(String kReSRulesInKReSSyntax) {
+        KReSKB kb = KReSRuleParser.parse(kReSRulesInKReSSyntax);
+        return kb.getkReSRuleList();
+    }
+
+    @Override
+    public boolean removeRecipe(Recipe recipe) {
+
+        OWLOntologyManager mng = owlmodel.getOWLOntologyManager();
+        OWLDataFactory factory = mng.getOWLDataFactory();
+
+        // Create the remover to be used to delete the recipe from the ontology.
+        OWLEntityRemover remover = new OWLEntityRemover(mng, Collections.singleton(owlmodel));
+
+        // Create the recipe axiom
+        OWLNamedIndividual ontoind = factory.getOWLNamedIndividual(recipe.getRecipeID());
+
+        // Remove the recipe
+        ontoind.accept(remover);
+        mng.applyChanges(remover.getChanges());
+        remover.reset();
+
+        // Check if the recipe ahs been removed
+        if (owlmodel.containsIndividualInSignature(recipe.getRecipeID())) return false;
+        else return true;
+
+    }
+
+    @Override
+    public boolean removeRecipe(IRI recipeIRI) {
+        Recipe recipe;
+        try {
+            recipe = getRecipe(recipeIRI);
+            return removeRecipe(recipe);
+        } catch (NoSuchRecipeException ex) {
+            log.error("Exception cougth: ", ex);
+            return false;
+        }
+    }
+
+    @Override
+    public boolean removeRule(KReSRule rule) {
+
+        OWLOntologyManager mng = owlmodel.getOWLOntologyManager();
+        OWLDataFactory factory = mng.getOWLDataFactory();
+        String ruleNS = "http://kres.iks-project.eu/ontology/meta/rmi.owl#";
+
+        // Create the remover to be used to delete the rule from the ontology.
+        OWLEntityRemover remover = new OWLEntityRemover(mng, Collections.singleton(owlmodel));
+
+        // Create the rule axiom
+        OWLNamedIndividual ontoind = factory.getOWLNamedIndividual(IRI.create((ruleNS + rule.getRuleName())));
+
+        // Remove the rule
+        ontoind.accept(remover);
+        mng.applyChanges(remover.getChanges());
+        remover.reset();
+
+        // Check if the recipe ahs been removed
+        if (owlmodel.containsIndividualInSignature(IRI.create((ruleNS + rule.getRuleName())))) return false;
+        else return true;
+
+    }
+
+}

Added: incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSSetRuleStore.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSSetRuleStore.java?rev=1082166&view=auto
==============================================================================
--- incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSSetRuleStore.java (added)
+++ incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/KReSSetRuleStore.java Wed Mar 16 15:31:08 2011
@@ -0,0 +1,138 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package org.apache.stanbol.rules.manager.changes;
+
+import java.io.File;
+import java.util.Dictionary;
+import java.util.Hashtable;
+
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Service;
+import org.apache.stanbol.ontologymanager.ontonet.api.KReSONManager;
+import org.apache.stanbol.rules.base.api.RuleStore;
+import org.apache.stanbol.rules.base.api.SetRuleStore;
+import org.osgi.service.component.ComponentContext;
+import org.semanticweb.owlapi.apibinding.OWLManager;
+import org.semanticweb.owlapi.model.OWLOntology;
+import org.semanticweb.owlapi.model.OWLOntologyCreationException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ *
+ * @author elvio
+ */
+//@Component(immediate = true, metatype = true)
+@Service(SetRuleStore.class)
+public class KReSSetRuleStore implements SetRuleStore{
+
+	private static Logger log = LoggerFactory.getLogger(KReSSetRuleStore.class);
+    private String file;
+    private KReSLoadRuleFile load;
+    private OWLOntology ont;
+    private SetRuleStore setRuleStore;
+	private RuleStore store;
+
+   /**
+	 * Private constructor used only for not repeating some code on other
+	 * constructors. For this purpose, this does NOT call the
+	 * <code>activate()</code> method, therefore should ONLY be invoked if
+	 * <code>activate()</code> is invoked afterwards.
+	 * 
+	 * @param onm
+	 *            the KReS ontology manager to be used by the rule store.
+     */
+	private KReSSetRuleStore(KReSONManager onm) {
+		// Since the configuration dictionary is empty, default values will be
+		// used instead.
+		this.store = new KReSRuleStore(onm, new Hashtable<String, Object>());
+    }
+
+   /**
+	 * To directly set the store with an ontology already contains rules and
+	 * recipe
+	 * 
+     * @param ontology
+     * @throws OWLOntologyCreationException
+     */
+	public KReSSetRuleStore(KReSONManager onm, File ontology) {
+		this(onm);
+        try{
+			this.ont = OWLManager.createOWLOntologyManager()
+					.loadOntologyFromOntologyDocument(ontology);
+            this.store.setStore(ont);
+        }catch(OWLOntologyCreationException e){
+			log.error(e.getMessage(), e);
+        }
+		// Won't do anything in this case, but is invoked as a good practice.
+		activate(new Hashtable<String, Object>());
+    }
+
+   /**
+	 * To directly set the store with a file contains the rules and the recipe
+	 * 
+	 * @param filepath
+	 *            the string containing the file path.
+     */
+	public KReSSetRuleStore(KReSONManager onm, String filepath) {
+		this(onm);
+		this.file = filepath;
+		this.load = new KReSLoadRuleFile(file, store);
+		// Won't do anything in this case, but is invoked as a good practice.
+		activate(new Hashtable<String, Object>());
+    }
+
+	/**
+	 * Used to configure an instance within an OSGi container.
+	 */
+	@SuppressWarnings("unchecked")
+	@Activate
+    protected void activate(ComponentContext context,String filepath){
+		log.info("in " + KReSSetRuleStore.class + " activate with context "
+				+ context);
+		if (context == null) {
+			throw new IllegalStateException("No valid" + ComponentContext.class
+					+ " parsed in activate!");
+		}
+		// Won't do anything in this case, but is invoked as a good practice.
+		activate((Dictionary<String, Object>) context.getProperties());
+	}
+
+	/**
+	 * Internally used to configure an instance (within and without an OSGi
+	 * container.
+	 * 
+	 * @param configuration
+	 */
+	protected void activate(Dictionary<String, Object> configuration) {
+		// There is no configuration for this component, so do nothing.
+    }
+
+	/**
+	 * Deactivation of the KreSRuleStore resets all its resources.
+	 */
+	@Deactivate
+    protected void deactivate(ComponentContext context){
+		log.info("in " + KReSSetRuleStore.class + " deactivate with context "
+				+ context);
+		file = null;
+		store = null;
+		load = null;
+		ont = null;
+		setRuleStore = null;
+    }
+
+	/**
+	 * To get the rule store;
+	 * 
+	 * @return {A RuleStore object.}
+	 */
+	public RuleStore returnStore() {
+		return this.load.getStore();
+}
+
+}

Added: incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/RecipeImpl.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/RecipeImpl.java?rev=1082166&view=auto
==============================================================================
--- incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/RecipeImpl.java (added)
+++ incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/changes/RecipeImpl.java Wed Mar 16 15:31:08 2011
@@ -0,0 +1,141 @@
+package org.apache.stanbol.rules.manager.changes;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Observable;
+import java.util.Set;
+
+import org.apache.stanbol.rules.base.api.KReSRule;
+import org.apache.stanbol.rules.base.api.Recipe;
+import org.apache.stanbol.rules.base.api.util.KReSRuleList;
+import org.semanticweb.owlapi.model.IRI;
+
+import com.hp.hpl.jena.rdf.model.Model;
+
+
+/**
+ * The RecipeImpl is a concrete implementation of the Recipe interface.
+ * A Recipe is a collection identified by an URI of rules. Each rules of the recipe is also identified by an URI.
+ * Rules are expressed both in SWRL and in KReS rules syntax.
+ * 
+ * @author andrea.nuzzolese
+ *
+ */
+
+public class RecipeImpl extends Observable implements Recipe {
+
+	
+	
+	
+	private IRI recipeID;
+	private String recipeDescription;
+	private KReSRuleList kReSRuleList;
+	
+	
+	
+	
+	/**
+	 * 
+	 * Create a new {@code RecipeImpl} from a set of rule expressed in KReS rule syntax.
+	 * 
+	 * 
+	 * @param recipeID
+	 * @param recipeDescription
+	 * @param kReSRuleList
+	 */
+	public RecipeImpl(IRI recipeID, String recipeDescription, KReSRuleList kReSRuleList) {
+		this.recipeID = recipeID;
+		this.recipeDescription = recipeDescription;
+		this.kReSRuleList = kReSRuleList;
+	}
+	
+	
+	public KReSRuleList getkReSRuleList() {
+		return kReSRuleList;
+	}
+	
+	public IRI getRecipeID() {
+		return recipeID;
+	}
+	
+	public String getRecipeDescription() {
+		return recipeDescription;
+	}
+	
+	public Model getRecipeAsRDFModel() {
+		
+		return null;
+	}
+
+	public KReSRule getRule(String ruleURI) {
+		//return new SWRLToKReSRule(ruleModel).parse(ruleURI);
+		return null;
+	}
+
+
+	private String getNSPrefixString(Model model){
+		Map<String, String> nsPrefix = model.getNsPrefixMap();
+		Set<String> prefixSet = nsPrefix.keySet();
+		Iterator<String> it = prefixSet.iterator();
+		
+		String sparqlPrefix = "";
+		
+		
+		while(it.hasNext()){
+			String prefix = it.next();
+			try {
+				String uri = nsPrefix.get(prefix);
+				uri = uri.replace("\\", "/");
+				sparqlPrefix += "PREFIX "+prefix+": <"+(new URI(uri).toString())+">"+System.getProperty("line.separator");
+			} catch (URISyntaxException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+			
+		}
+		
+		return sparqlPrefix;
+	}
+
+	
+	public String[] toSPARQL() {
+		String[] sparqlStrings = new String[kReSRuleList.size()];
+		int i=0;
+		for(KReSRule kReSRule : kReSRuleList){
+			sparqlStrings[i] = kReSRule.toSPARQL();
+			i++;
+		}
+		return sparqlStrings;
+	}
+	
+	
+	@Override
+	public String getRulesInKReSSyntax(){
+		String kReSSyntax = "";
+		
+		boolean firstLoop = true;
+		for(KReSRule kReSRule : kReSRuleList){
+			if(!firstLoop){
+				kReSSyntax += " . ";
+			}
+			else{
+				firstLoop = false;
+			}
+			kReSSyntax += kReSRule.toKReSSyntax();
+		}
+		
+		return kReSSyntax;
+	}
+
+
+	@Override
+	public void addKReSRule(KReSRule kReSRule) {
+		if(kReSRuleList == null){
+			kReSRuleList = new KReSRuleList();
+		}
+		kReSRuleList.add(kReSRule);
+		
+	}
+}

Added: incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/parse/KReSRuleGrammar.jj
URL: http://svn.apache.org/viewvc/incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/parse/KReSRuleGrammar.jj?rev=1082166&view=auto
==============================================================================
--- incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/parse/KReSRuleGrammar.jj (added)
+++ incubator/stanbol/trunk/kres/rules/manager/src/main/java/org/apache/stanbol/rules/manager/parse/KReSRuleGrammar.jj Wed Mar 16 15:31:08 2011
@@ -0,0 +1,771 @@
+/**
+ * JavaCC template file created by SF JavaCC plugin 1.5.17+ wizard for JavaCC 1.5.0+
+ */
+options
+{
+  JDK_VERSION = "1.6";
+  static = false;
+}
+
+PARSER_BEGIN(KReSRuleParser)
+package it.cnr.istc.semion.refactorer.rules.parser;
+
+import java.io.Reader;
+import java.io.StringReader;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Iterator;
+
+import com.hp.hpl.jena.rdf.model.ModelFactory;
+import com.hp.hpl.jena.rdf.model.Resource;
+
+
+import it.cnr.istc.semion.refactorer.rules.KReSRule;
+import it.cnr.istc.semion.refactorer.rules.KReSRuleAtom;
+import it.cnr.istc.semion.refactorer.rules.URIResource;
+import it.cnr.istc.semion.refactorer.rules.AtomList;
+import it.cnr.istc.semion.refactorer.rules.KReSKB;
+import it.cnr.istc.semion.refactorer.rules.KReSRuleImpl;
+import it.cnr.istc.semion.refactorer.rules.atoms.ClassAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.ComparisonAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.DatavaluedPropertyAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.EndsWithAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.IndividualPropertyAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.DifferentAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.KReSTypedLiteral;
+import it.cnr.istc.semion.refactorer.rules.atoms.LengthAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.NotAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.NumberAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.NumericFunctionAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.SPARQLddAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.SameAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.LessThanAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.GreaterThanAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.KReSResource;
+import it.cnr.istc.semion.refactorer.rules.atoms.KReSVariable;
+import it.cnr.istc.semion.refactorer.rules.atoms.LetAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.ConcatAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.StringAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.StringFunctionAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.SubstringAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.SubtractionAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.SumAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.NewNodeAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.KReSBlankNode;
+import it.cnr.istc.semion.refactorer.rules.atoms.UpperCaseAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.LowerCaseAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.NamespaceAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.LocalNameAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.StrAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.UnionAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.CreateLabelAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.PropStringAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.IsBlankAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.SPARQLcAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.SPARQLdAtom;
+import it.cnr.istc.semion.refactorer.rules.atoms.StartsWithAtom;
+import it.cnr.istc.semion.refactorer.rules.KReSRuleExpressiveness;
+
+public class KReSRuleParser
+{
+
+  static KReSKB kReSKB;
+  
+  public static KReSKB parse( String inString ) {
+  {
+  	kReSKB = new KReSKB();
+  	Reader reader = new StringReader( inString ) ;
+    KReSRuleParser parser = new KReSRuleParser(reader);
+    StringBuffer buffer = new StringBuffer() ;
+	try {
+		parser.start( ) ; 
+	} catch( TokenMgrError e ) { 
+		throw new IllegalStateException(e) ; 
+	} catch( ParseException e ) { 
+		throw new IllegalStateException(e) ; 
+	} 
+	return kReSKB ; }
+  }
+
+
+	private static URI getSWRLArgument(String argument){
+                Resource rdfNode = null;
+                String[] argumentComposition = argument.split(":");
+                if(argumentComposition.length == 2){
+                        String prefix = argumentComposition[0];
+                        String resourceName = argumentComposition[1];
+
+                        String namespaceURI = kReSKB.getPrefixURI(prefix);
+                        rdfNode = ModelFactory.createDefaultModel().createResource(namespaceURI+resourceName);
+                        try {
+							return new URI(rdfNode.getURI());
+						} catch (URISyntaxException e) {
+							// TODO Auto-generated catch block
+							e.printStackTrace();
+						}
+
+                }
+                
+                return null;
+        }
+
+        private static URI getSWRLVariable(String argument){
+                Resource variableResource = null;
+                String variableString = argument.substring(1);
+
+
+                variableResource = ModelFactory.createDefaultModel().createResource(kReSKB.getPrefixURI("var")+variableString);
+
+
+
+                try {
+					return new URI(variableResource.getURI());
+				} catch (URISyntaxException e) {
+					// TODO Auto-generated catch block
+					e.printStackTrace();
+					return null;
+				}
+        }
+}
+
+PARSER_END(KReSRuleParser)
+
+SKIP : {" "}
+SKIP : {"\r" | "\t" | "\n"}
+
+TOKEN : /* OPERATORS */
+{
+  < LARROW : "->" >
+| < COLON : ":" >
+| < EQUAL : "=" >
+| < AND : "." >
+| < COMMA : "," >
+| < REFLEXIVE : "+" >
+| < SAME : "same" >
+| < DIFFERENT : "different" >
+| < LESSTHAN : "lt" >
+| < GREATERTHAN : "gt" >
+| < IS : "is" >
+| < NEW_NODE : "newNode" >
+| < LENGTH : "length" >
+| < SUBSTRING : "substring" >
+| < UPPERCASE : "upperCase" >
+| < LOWERCASE : "lowerCase" >
+| < STARTS_WITH : "startsWith" >
+| < ENDS_WITH : "endsWith" >
+| < LET : "let" >
+| < CONCAT : "concat" >
+| < HAS : "has" >
+| < VALUES : "values" >
+| < NOTEX : "notex" >
+| < PLUS : "sum" >
+| < MINUS : "sub" >
+| < NOT : "not" >
+| < NAMESPACE : "namespace" >
+| < LOCALNAME : "localname" >
+| < STR : "str" >
+| < APOX : "^" >
+| < UNION : "union" >
+| < CREATE_LABEL : "createLabel" >
+| < SPARQL_C : "sparql-c" >
+| < SPARQL_D : "sparql-d" >
+| < SPARQL_DD : "sparql-dd" >
+| < PROP : "prop" >
+| < IS_BLANK : "isBlank" >
+| < FORWARD_CHAIN : "!" >
+}
+
+TOKEN : /* BLOCKS */
+{
+  < LPAR : "(" >
+| < RPAR : ")" >
+| < DQUOT : "\"" >
+| < LQUAD : "[" >
+| < RQUAD : "]" >
+}
+
+TOKEN :
+{
+  < NUM : ([ "0"-"9"])+ > 
+| < VAR : ([ "0"-"9","a"-"z","A"-"Z","-", "_", "."])+ >
+| < VARIABLE : "?" ([ "0"-"9","a"-"z","A"-"Z","-", "_"])+ >
+| < URI : "<" ([ "0"-"9","a"-"z","A"-"Z","-", "_", ".", "#", ":", "/", "(", ")" ])+ ">" >
+| < STRING : "\"" ([ "0"-"9","a"-"z","A"-"Z","-", "_", ".", ":", "/", "#", "\\", "?", " ", "!", "$", "%" ])+ "\"" >
+| < SPARQL_STRING : "%" ([ "0"-"9","a"-"z","A"-"Z","-", "_", ".", ":", "/", "#", "\\", "?", " ", "!", "$", "%", "{", "}", "(", ")", "\"", "<", ">", "=", "+", "\n", "\t", "&", "|", "," ])+ "%" >
+| < BNODE : "_:" ([ "0"-"9","a"-"z","A"-"Z","-", "_", "."])+ >
+}
+
+
+void start () :
+{}
+{
+	expression() expressionCont()
+}
+
+void expressionCont() :
+{}
+{
+	( < AND > expression() ) | {}
+}
+
+void expression() :
+{KReSRule kReSRule;}
+{
+	prefix() expressionCont()  
+}
+
+void prefix() :
+{String nsPrefix; Object obj;}
+{
+  nsPrefix=getVariable() (obj=equality() { String prefixURI = (String)obj;
+  										   prefixURI = prefixURI.substring(1, prefixURI.length()-1);
+  										   kReSKB.addPrefix(nsPrefix, prefixURI);  										    
+  										 } 
+  							|   obj=rule() { AtomList[] atoms = (AtomList[]) obj;
+  											 String varPrefix = kReSKB.getPrefixURI("var");
+  											 varPrefix = varPrefix.substring(0, varPrefix.length());
+  											 
+  											 if(atoms.length == 1){
+                                                            AtomList body = atoms[0];
+                                                            if(body.size() == 1){
+                                                                    Iterator<KReSRuleAtom> it = body.iterator();
+                                                                    KReSRuleAtom atom = it.next();
+                                                                    if(atom.isSPARQLConstruct()){
+                                                                            KReSRule kReSRule = new KReSRuleImpl(varPrefix+nsPrefix, atoms[0], null, KReSRuleExpressiveness.SPARQLConstruct);
+                                                                            kReSKB.addRule(kReSRule);
+                                                                    }
+                                                                    else if(atom.isSPARQLDelete()){
+                                                                            KReSRule kReSRule = new KReSRuleImpl(varPrefix+nsPrefix, atoms[0], null, KReSRuleExpressiveness.SPARQLDelete);
+                                                                            kReSKB.addRule(kReSRule);
+                                                                    }
+                                                                    else if(atom.isSPARQLDeleteData()){
+                                                                            KReSRule kReSRule = new KReSRuleImpl(varPrefix+nsPrefix, atoms[0], null, KReSRuleExpressiveness.SPARQLDeleteData);
+                                                                            kReSKB.addRule(kReSRule);
+                                                                    }
+                                                            }
+
+                                                     }
+                                                 else{
+                                                         KReSRule kReSRule = new KReSRuleImpl(varPrefix+nsPrefix, atoms[0], atoms[1], KReSRuleExpressiveness.KReSCore);
+                                                         kReSKB.addRule(kReSRule);
+                                                }
+	  									}
+  						)
+  						
+|
+
+	< FORWARD_CHAIN > nsPrefix=getVariable() obj=rule() { AtomList[] atoms = (AtomList[]) obj;
+  											 String varPrefix = kReSKB.getPrefixURI("var");
+  											 varPrefix = varPrefix.substring(0, varPrefix.length());
+  											 KReSRule kReSRule = new KReSRuleImpl(varPrefix+nsPrefix, atoms[0], atoms[1], KReSRuleExpressiveness.ForwardChaining);
+  											 kReSKB.addRule(kReSRule); }
+  											 
+|	< REFLEXIVE > nsPrefix=getVariable() obj=rule() {  	AtomList[] kReSAtoms = (AtomList[]) obj;
+														 String pref = kReSKB.getPrefixURI("var");
+                                                         pref = pref.substring(0, pref.length());
+                                                         KReSRule rule = new KReSRuleImpl(pref+nsPrefix, kReSAtoms[0], kReSAtoms[1], KReSRuleExpressiveness.Reflexive);
+                                                         kReSKB.addRule(rule); }
+}
+
+
+String equality() :
+{String nsURI;}
+{
+	< EQUAL > ( nsURI=getURI() )
+	{ return nsURI;}
+}
+
+
+
+AtomList[] rule() :
+{AtomList[] ruleAtoms;}
+{
+   < LQUAD >  ruleAtoms=ruleDefinition()  < RQUAD >
+   { return ruleAtoms; }
+  
+}
+
+AtomList[] ruleDefinition():
+{AtomList body; AtomList head; Token t;}
+{
+	body=atomList() <LARROW> head=atomList()
+	{ return new AtomList[]{body, head};}
+	
+|	
+	< SPARQL_C > < LPAR > t = < SPARQL_STRING > < RPAR >
+	{ 
+		KReSRuleAtom sparqlAtom = new SPARQLcAtom(t.image);
+		AtomList atomList = new AtomList();
+		atomList.addToHead(sparqlAtom);
+		return new AtomList[]{atomList};
+	}
+	
+|	
+	< SPARQL_D > < LPAR > t = < SPARQL_STRING > < RPAR >
+	{ 
+		KReSRuleAtom sparqlDAtom = new SPARQLdAtom(t.image);
+        AtomList atomDList = new AtomList();
+        atomDList.addToHead(sparqlDAtom);
+        return new AtomList[]{atomDList};
+	}
+
+|	
+	< SPARQL_DD > < LPAR > t = < SPARQL_STRING > < RPAR >
+	{ 
+		KReSRuleAtom sparqlDDAtom = new SPARQLddAtom(t.image);
+        AtomList atomDDList = new AtomList();
+        atomDDList.addToHead(sparqlDDAtom);
+        return new AtomList[]{atomDDList};
+	} 
+}
+
+AtomList atomList() :
+{AtomList atomList = new AtomList(); KReSRuleAtom kReSAtom;}
+{
+	kReSAtom=atom() atomList=atomListRest() 
+	{ atomList.addToHead(kReSAtom); return atomList;}
+	
+	| 
+	{}
+	{return atomList;} 
+}
+
+
+AtomList atomListRest() :
+{AtomList atomList = new AtomList(); KReSRuleAtom kReSAtom;}
+{
+	< AND > atomList=atomList() 
+	{ return atomList;}
+	| 
+	{}
+	{return atomList;} 
+}
+
+
+KReSRuleAtom atom() :
+{KReSRuleAtom kReSRuleAtom;}
+{
+   kReSRuleAtom=classAtom() {return kReSRuleAtom;}
+|  kReSRuleAtom=individualPropertyAtom() {return kReSRuleAtom;}
+|  kReSRuleAtom=datavaluedPropertyAtom() {return kReSRuleAtom;}
+|  kReSRuleAtom=letAtom() {return kReSRuleAtom;}
+|  kReSRuleAtom=newNodeAtom() {return kReSRuleAtom;}
+|  kReSRuleAtom=comparisonAtom() {return kReSRuleAtom;}
+|  kReSRuleAtom=unionAtom() {return kReSRuleAtom;}
+
+}
+
+KReSRuleAtom unionAtom() : 
+{AtomList atomList1; AtomList atomList2;}
+{
+	< UNION > < LPAR > atomList1 = atomList() < COMMA > atomList2 = atomList() < RPAR >
+	{ return new UnionAtom(atomList1, atomList2); }
+}
+
+StringFunctionAtom createLabelAtom() : 
+{StringFunctionAtom stringFunctionAtom;}
+{
+	< CREATE_LABEL > < LPAR > stringFunctionAtom = stringFunctionAtom() < RPAR >
+	{ return new CreateLabelAtom(stringFunctionAtom); }
+}
+
+
+StringFunctionAtom propStringAtom() : 
+{StringFunctionAtom stringFunctionAtom1; StringFunctionAtom stringFunctionAtom2;}
+{
+	< PROP > < LPAR > stringFunctionAtom1 = stringFunctionAtom() < COMMA > stringFunctionAtom2 = stringFunctionAtom() < RPAR >
+	{ return new PropStringAtom(stringFunctionAtom1, stringFunctionAtom2); }
+}
+
+
+
+
+ComparisonAtom endsWithAtom() : 
+{KReSRuleAtom kReSRuleAtom; StringFunctionAtom arg; StringFunctionAtom stringFunctionAtom;}
+{
+	< ENDS_WITH > < LPAR > arg=stringFunctionAtom() < COMMA > stringFunctionAtom = stringFunctionAtom()< RPAR >
+
+	{return new EndsWithAtom(arg, stringFunctionAtom);}
+}
+
+
+ComparisonAtom startsWithAtom() : 
+{KReSRuleAtom kReSRuleAtom; StringFunctionAtom arg; StringFunctionAtom stringFunctionAtom;}
+{
+	< STARTS_WITH > < LPAR > arg=stringFunctionAtom() < COMMA > stringFunctionAtom = stringFunctionAtom()< RPAR >
+
+	{return new StartsWithAtom(arg, stringFunctionAtom);}
+}
+
+StringFunctionAtom stringFunctionAtom() : 
+{Object obj; StringFunctionAtom stringFunctionAtom;}
+{
+	(
+		stringFunctionAtom=concatAtom()
+	|   stringFunctionAtom=upperCaseAtom()
+	|   stringFunctionAtom=lowerCaseAtom()
+	|   stringFunctionAtom=substringAtom()
+	|   stringFunctionAtom=namespaceAtom()
+	|   stringFunctionAtom=localnameAtom()
+	|   stringFunctionAtom=strAtom()
+	|   stringFunctionAtom=stringAtom()
+	| 	stringFunctionAtom=propStringAtom()
+	|	stringFunctionAtom=createLabelAtom()
+	)
+
+	{return stringFunctionAtom;}
+}
+
+
+StrAtom strAtom() : 
+{URIResource uri;}
+{
+	< STR > < LPAR > uri = iObject() < RPAR >
+	{return new StrAtom(uri);}
+}
+
+NamespaceAtom namespaceAtom() : 
+{URIResource uri;}
+{
+	< NAMESPACE > < LPAR > uri = iObject() < RPAR >
+	{return new NamespaceAtom(uri);}
+}
+
+LocalNameAtom localnameAtom() : 
+{URIResource uri;}
+{
+	< LOCALNAME > < LPAR > uri = iObject() < RPAR >
+	{return new LocalNameAtom(uri);}
+}
+
+StringAtom stringAtom() :
+{Object obj; StringFunctionAtom stringFunctionAtom;}
+{
+	obj = uObject() { return new StringAtom(obj.toString()); }
+}
+
+ConcatAtom concatAtom() : 
+{StringFunctionAtom arg1; StringFunctionAtom arg2;}
+{
+	< CONCAT > < LPAR > arg1=stringFunctionAtom()  < COMMA > arg2=stringFunctionAtom() < RPAR >
+	{ return new ConcatAtom(arg1, arg2);}
+}
+
+
+UpperCaseAtom upperCaseAtom() : 
+{StringFunctionAtom arg;}
+{
+	< UPPERCASE > < LPAR > arg=stringFunctionAtom() < RPAR >
+	{ return new UpperCaseAtom(arg);}
+}
+
+LowerCaseAtom lowerCaseAtom() : 
+{StringFunctionAtom arg;}
+{
+	< LOWERCASE > < LPAR > arg=stringFunctionAtom() < RPAR >
+	{ return new LowerCaseAtom(arg);}
+}
+
+SubstringAtom substringAtom() : 
+{StringFunctionAtom arg; NumericFunctionAtom start; NumericFunctionAtom length;}
+{
+	< SUBSTRING > < LPAR > arg=stringFunctionAtom() < COMMA > start=numericFunctionAtom() < COMMA > length=numericFunctionAtom() < RPAR >
+	{ return new SubstringAtom(arg, start, length);}
+}
+
+
+NumericFunctionAtom numericFunctionAtom() : 
+{NumericFunctionAtom numericFunctionAtom;}
+{
+	(
+		numericFunctionAtom = sumAtom()
+	|   numericFunctionAtom = subtractionAtom()
+	|   numericFunctionAtom = lengthAtom()
+	|   numericFunctionAtom = numberAtom()
+	)
+
+	{return numericFunctionAtom;}
+}
+
+
+LengthAtom lengthAtom() : 
+{StringFunctionAtom stringFunctionAtom;}
+{
+	< LENGTH > < LPAR > stringFunctionAtom = stringFunctionAtom() < RPAR >
+	{return new LengthAtom(stringFunctionAtom);}
+}
+
+SumAtom sumAtom() : 
+{NumericFunctionAtom numericFunctionAtom1; NumericFunctionAtom numericFunctionAtom2;}
+{
+	
+	< PLUS > < LPAR > numericFunctionAtom1 = numericFunctionAtom() < COMMA > numericFunctionAtom2 = numericFunctionAtom() < RPAR >
+
+	{return new SumAtom(numericFunctionAtom1, numericFunctionAtom2);}
+}
+
+SubtractionAtom subtractionAtom() : 
+{NumericFunctionAtom numericFunctionAtom1; NumericFunctionAtom numericFunctionAtom2;}
+{
+	
+	< MINUS > < LPAR > numericFunctionAtom1 = numericFunctionAtom() < COMMA > numericFunctionAtom2 = numericFunctionAtom() < RPAR >
+
+	{return new SubtractionAtom(numericFunctionAtom1, numericFunctionAtom2);}
+}
+
+NumericFunctionAtom numberAtom() :
+{Token t;}
+{
+	(
+		t = < NUM >	
+	|	t = < VARIABLE >
+	)
+	{ return new NumberAtom(t.image); }
+
+}
+
+
+ClassAtom classAtom() :
+{URIResource uri1; URIResource uri2;}
+{
+	< IS > < LPAR > uri1=iObject()  < COMMA > uri2=iObject() < RPAR >
+	{ return new ClassAtom(uri1, uri2);}
+}
+
+
+NewNodeAtom newNodeAtom() : 
+{URIResource arg1; Object arg2;}
+{
+	< NEW_NODE > < LPAR > arg1=iObject()  < COMMA > arg2=dObject() < RPAR >
+	{ return new NewNodeAtom(arg1, arg2);}
+}
+
+LetAtom letAtom() : 
+{URIResource uri1; StringFunctionAtom fun;}
+{
+	< LET > < LPAR > uri1=iObject()  < COMMA > fun=stringFunctionAtom() < RPAR >
+	{ return new LetAtom(uri1, fun);}
+}
+
+
+IndividualPropertyAtom individualPropertyAtom() :
+{URIResource uri1; URIResource uri2; URIResource uri3;}
+{
+	 < HAS > < LPAR > uri1=iObject() < COMMA > uri2=iObject() <COMMA> uri3=iObject() < RPAR >
+	 {return new IndividualPropertyAtom(uri1, uri2, uri3);}
+}
+
+
+DatavaluedPropertyAtom datavaluedPropertyAtom() :
+{URIResource uri1; URIResource uri2; Object obj;}
+{
+	 < VALUES > < LPAR > uri1=iObject() < COMMA > uri2=iObject() <COMMA> obj=dObject() < RPAR >
+	 { return new DatavaluedPropertyAtom(uri1, uri2, obj); }
+}
+
+
+SameAtom sameAsAtom() :
+{StringFunctionAtom stringFunctionAtom1; StringFunctionAtom stringFunctionAtom2;}
+{
+	< SAME > < LPAR > stringFunctionAtom1=stringFunctionAtom() < COMMA > stringFunctionAtom2=stringFunctionAtom() < RPAR >
+	{ return new SameAtom(stringFunctionAtom1, stringFunctionAtom2); } 
+}
+
+LessThanAtom lessThanAtom() :
+{Object obj1; Object obj2;}
+{
+	< LESSTHAN > < LPAR > obj1=iObject() < COMMA > obj2=iObject() < RPAR >
+	{ return new LessThanAtom(obj1, obj2); } 
+}
+
+GreaterThanAtom greaterThanAtom() :
+{Object obj1; Object obj2;}
+{
+	< GREATERTHAN > < LPAR > obj1=iObject() < COMMA > obj2=iObject() < RPAR >
+	{ return new GreaterThanAtom(obj1, obj2); } 
+}
+
+DifferentAtom differentFromAtom() :
+{StringFunctionAtom stringFunctionAtom1; StringFunctionAtom stringFunctionAtom2;}
+{
+	< DIFFERENT > < LPAR > stringFunctionAtom1=stringFunctionAtom() < COMMA > stringFunctionAtom2=stringFunctionAtom() < RPAR >
+	{ return new DifferentAtom(stringFunctionAtom1, stringFunctionAtom2); } 
+}
+
+URIResource reference() :
+{ String uri1;
+  Token colon;
+  String uri3; }
+{
+	 uri1=getURI() { uri1 = uri1.substring(1, uri1.length()-1);
+	 					try {
+						  return new KReSResource(new URI(uri1));
+							} catch (URISyntaxException e) {
+								e.printStackTrace();
+							} } | 
+	 uri1= getVariable() colon=< COLON > uri3=getVariable() { return new KReSResource(getSWRLArgument(uri1+colon.image+uri3)); }
+}
+
+
+
+URIResource varReference() :
+{ String uri1;
+  Token colon;
+  String uri3; }
+{
+	 uri1=getURI() { try {
+															return new KReSResource(new URI(uri1));
+														} catch (URISyntaxException e) {
+															e.printStackTrace();
+														} } | 
+	 uri1= getVariable() colon=< COLON > uri3=getVariable() { return new KReSResource(getSWRLArgument(uri1+colon.image+uri3)); }
+}
+
+
+String getURI() :
+{
+	Token t;
+}
+{
+	t = < URI > { return t.image; }
+}
+
+String getVariable() :
+{
+	Token t;
+}
+{
+	t = < VAR > { return t.image; }
+}
+
+
+String getString() :
+{
+	Token t;
+}
+{
+	t = < STRING > { return t.image; }
+}
+
+Integer getInt() :
+{
+	Token t;
+}
+{
+	t=< NUM > { return Integer.valueOf(t.image); }
+}
+
+
+Object uObject() :
+{ Object obj; }
+{
+	(
+		obj = variable() 
+		| obj = reference()
+		| obj = getString() 
+		| obj = getInt()
+	)
+	{return obj;}
+	
+}
+
+
+URIResource iObject() :
+{ URIResource uri; }
+{
+	uri = variable() {return uri;} | uri = reference() {return uri;}
+}
+
+Object dObject() :
+{ Object variable; }
+{
+	
+	(variable=literal() | variable=variable()) {return variable;}	
+}
+
+
+
+Object literal() : 
+{ Object literal; URIResource typedLiteral;}
+{
+	(
+	
+			literal=getString() typedLiteral=typedLiteral() 
+		|   literal=getInt() typedLiteral=typedLiteral()
+		
+	)
+	
+	{
+		if(typedLiteral != null){
+			return new KReSTypedLiteral(literal, typedLiteral);
+		}
+		else{
+			return literal;
+		}
+	}
+	
+}
+
+URIResource typedLiteral() :
+{ URIResource type = null; }
+{
+	(
+			< APOX > < APOX > type = reference()
+		| {}
+	)
+	{return type;}
+} 
+
+URIResource variable() :
+{ Token t; String var;}
+{
+	< NOTEX > < LPAR > t = < VARIABLE > < RPAR > {var=t.image; var=kReSKB.getPrefixURI("var") + var.substring(1);
+														try{ 
+															return new KReSVariable(new URI(var), true);
+														} catch (URISyntaxException e) {
+															e.printStackTrace();
+															return null;
+														}}
+|	t = < VARIABLE >
+	{ var=t.image; var=kReSKB.getPrefixURI("var") + var.substring(1);
+														try{ 
+															return new KReSVariable(new URI(var), false);
+														} catch (URISyntaxException e) {
+															e.printStackTrace();
+															return null;
+														} }
+|	t = < BNODE >
+	{ var=t.image; 	return new KReSBlankNode(var); }
+}
+
+ComparisonAtom notAtom() :
+{ ComparisonAtom comparisonAtom; }
+{
+	< NOT > < LPAR > comparisonAtom = comparisonAtom() < RPAR >
+	{return new NotAtom(comparisonAtom);}	
+}
+
+ComparisonAtom isBlankAtom() :
+{ URIResource uriRes; }
+{
+	< IS_BLANK > < LPAR > uriRes = iObject()  < RPAR >
+	{return new IsBlankAtom(uriRes);}	
+}
+
+ComparisonAtom comparisonAtom() :
+{ ComparisonAtom comparisonAtom; }
+{
+	(
+		comparisonAtom = sameAsAtom()
+	|	comparisonAtom = lessThanAtom()
+	|	comparisonAtom = greaterThanAtom()
+	|	comparisonAtom = differentFromAtom()
+	|   comparisonAtom = notAtom()
+	|   comparisonAtom = startsWithAtom()
+	|   comparisonAtom = endsWithAtom()
+	|   comparisonAtom = isBlankAtom()
+	) 
+	{return comparisonAtom;}
+}
+
+