1 10 package com.hp.hpl.jena.reasoner.rulesys.impl; 11 12 import java.util.*; 13 14 import com.hp.hpl.jena.graph.*; 15 import com.hp.hpl.jena.reasoner.*; 16 import com.hp.hpl.jena.reasoner.rulesys.*; 17 import com.hp.hpl.jena.util.OneToManyMap; 18 19 31 public class RuleStore { 32 33 34 protected OneToManyMap goalMap = new OneToManyMap(); 35 36 37 protected List allRules; 38 39 40 protected Set ruleIndex = new HashSet(); 41 42 45 public RuleStore() { 46 allRules = new ArrayList(); 47 }; 48 49 52 public RuleStore(List rules) { 53 for (Iterator i = rules.iterator(); i.hasNext(); ) { 54 addRule( (Rule)i.next() ); 55 } 56 allRules = rules; 57 } 58 59 62 public void addAll(RuleStore store) { 63 for (Iterator i = store.getAllRules().iterator(); i.hasNext(); ) { 64 addRule( (Rule)i.next() ); 65 } 66 } 67 68 71 public void addRule(Rule rule) { 72 addRemoveRule(rule, true); 73 } 74 75 78 public void deleteRule(Rule rule) { 79 addRemoveRule(rule, false); 80 } 81 82 87 private void addRemoveRule(Rule rule, boolean isAdd) { 88 if (rule.headLength() != 1) { 89 for (int j = 0; j < rule.headLength(); j++) { 90 Rule newRule = new Rule(rule.getName(), 91 new ClauseEntry[] {rule.getHeadElement(j)}, 92 rule.getBody() ); 93 newRule.setNumVars(rule.getNumVars()); 94 doAddRemoveRule(newRule, isAdd); 95 } 96 97 } else { 98 doAddRemoveRule(rule, isAdd); 99 } 100 } 101 102 107 protected void doAddRemoveRule(Rule rule, boolean isAdd) { 108 if (isAdd && ruleIndex.contains(rule)) return; 109 if (isAdd) { 110 ruleIndex.add(rule); 111 if (allRules != null) allRules.add(rule); 112 } else { 113 ruleIndex.remove(rule); 114 if (allRules != null) allRules.remove(rule); 115 } 116 Object headClause = rule.getHeadElement(0); 117 if (headClause instanceof TriplePattern) { 118 TriplePattern headpattern = (TriplePattern)headClause; 119 Node predicate = headpattern.getPredicate(); 120 if (predicate.isVariable()) { 121 if (isAdd) { 122 goalMap.put(Node.ANY, rule); 123 } else { 124 goalMap.remove(Node.ANY, rule); 125 } 126 } else { 127 if (isAdd) { 128 goalMap.put(predicate, rule); 129 } else { 130 goalMap.remove(predicate, rule); 131 } 132 } 133 } 134 } 135 136 140 public List rulesFor(TriplePattern goal) { 141 List rules = new ArrayList(); 142 if (goal.getPredicate().isVariable()) { 143 checkAll(goalMap.values().iterator(), goal, rules); 144 } else { 145 checkAll(goalMap.getAll(goal.getPredicate()), goal, rules); 146 checkAll(goalMap.getAll(Node.ANY), goal, rules); 147 } 148 return rules; 149 } 150 151 154 public List getAllRules() { 155 return allRules; 156 } 157 158 161 public void deleteAllRules() { 162 allRules.clear(); 163 goalMap.clear(); 164 ruleIndex.clear(); 165 } 166 167 171 private void checkAll(Iterator candidates, TriplePattern goal, List matchingRules) { 172 while (candidates.hasNext()) { 173 Rule r = (Rule)candidates.next(); 174 if ( ((TriplePattern)r.getHeadElement(0)).compatibleWith(goal) ) { 175 matchingRules.add(r); 176 } 177 } 178 } 179 180 } 181 182 | Popular Tags |