1   package debugger.resources.pr;
2   
3   import debugger.resources.ResourcesFactory;
4   import gate.Annotation;
5   import gate.AnnotationSet;
6   import gate.jape.RightHandSide;
7   
8   import java.util.ArrayList;
9   import java.util.HashMap;
10  import java.util.Iterator;
11  import java.util.StringTokenizer;
12  
13  /**
14   * Copyright (c) Ontos AG (http://www.ontosearch.com).
15   * This class is part of JAPE Debugger component for
16   * GATE (Copyright (c) "The University of Sheffield" see http://gate.ac.uk/) <br>
17   * @author Andrey Shafirin
18   */
19  
20  public class RuleModel //extends DefaultMutableTreeNode
21  {
22      private HashMap bindings;
23      /** Reference to {@link gate.jape.RightHandSide} of this rule */
24      private final RightHandSide rhs;
25      /** Represents this rule name */
26      private final RuleName ruleName;
27      /** Annotation history for this rule */
28      private final RuleAnnotationHistory annotationHistory;
29      /** Designates if this rule marked as breakpoint */
30      private boolean stopOnMatch = false;
31  
32      /** Constructs RuleModel from given {@link gate.jape.RightHandSide}
33       *  @param rhs {@link gate.jape.RightHandSide} to construct this RuleModel. */
34      public RuleModel(RightHandSide rhs) {
35          this.rhs = rhs;
36          this.annotationHistory = new RuleAnnotationHistory();
37          this.ruleName = new RuleName(this.rhs);
38          //setUserObject(ruleName);
39          //setAllowsChildren(false);
40      }
41  
42      /** @return String representation of this rule name based on {@link #ruleName}.
43       * Simply {@link debugger.resources.pr.RuleModel.RuleName#toString()}
44       * */
45      public String getName() {
46          return ruleName.toString();
47      }
48  
49      /** @return {@link #rhs} for this rule */
50      public RightHandSide getRHS() {
51          return rhs;
52      }
53  
54      /** @return {@link #annotationHistory} for this rule */
55      public RuleAnnotationHistory getAnnotationHistory() {
56          return annotationHistory;
57      }
58  
59      /** @return true if this rule marked as breakpoint */
60      public boolean isStopOnMatch() {
61          return stopOnMatch;
62      }
63  
64      /** @param stopOnMatch set true to set breakpoint for this rule */
65      public void setStopOnMatch(boolean stopOnMatch) {
66          this.stopOnMatch = stopOnMatch;
67      }
68  
69      public boolean equals(Object obj) {
70          if (obj instanceof RuleModel) {
71              return this.rhs.equals(((RuleModel) obj).rhs);
72          }
73          return super.equals(obj);
74      }
75  
76      public void setBindings(HashMap bindings) {
77          this.bindings = bindings;
78      }
79  
80      public HashMap getBindings() {
81          return bindings;
82      }
83  
84      class RuleName {
85          private final RightHandSide rhs;
86  
87          public RuleName(RightHandSide rhs) {
88              this.rhs = rhs;
89          }
90  
91          /** @return String representation of this rule name */
92          public String toString() {
93              if (null == rhs) {
94                  return "RHS is null!";
95              }
96              if (null == this.rhs.getRuleName() || this.rhs.getRuleName().length() == 0) {
97                  return "Unnamed Rule";
98              }
99              return this.rhs.getRuleName();
100         }
101 
102         /**
103          * Compares this RuleName to another RuleName or String.
104          * Assumes null != null.
105          * */
106         public boolean equals(Object obj) {
107             if (null == obj || null == rhs || null == rhs.getRuleName()) {
108                 return false;
109             }
110             if (obj instanceof String) {
111                 return rhs.getRuleName().equals(obj);
112             }
113             if (obj instanceof RuleName) {
114                 return rhs.getRuleName().equals(((RuleName) obj).rhs.getRuleName());
115             }
116             return false;
117         }
118     }
119 
120     public ArrayList getMatshedRuleTable() {
121         ArrayList tm = new ArrayList();
122         HashMap hm = getBindings();
123         if (null == hm) return tm;
124         Iterator iter = hm.keySet().iterator();
125         while (iter.hasNext()) {
126             String label = (String) iter.next();
127             if (label.startsWith("(")) {
128                 StringTokenizer st = new StringTokenizer(label, "\n");
129                 while (st.hasMoreTokens()) {
130                     tm.add(st.nextToken());
131                 }
132             }
133         }
134         return tm;
135     }
136 
137     public ArrayList getMatchedText() {
138         ArrayList alCPE = getMatshedRuleTable();
139         ArrayList result = new ArrayList();
140         HashMap bindHashMap = getBindings();
141         for (int i = 0; i < alCPE.size(); i++) {
142             String currStr = ((String) alCPE.get(i)).trim();
143             Iterator bindIter = bindHashMap.keySet().iterator();
144             String currText = "";
145             while (bindIter.hasNext()) {
146                 String s = (String) bindIter.next();
147                 if (s.startsWith("{")) {
148                     if (s.equals(currStr)) {
149                         //currText = s;
150                         AnnotationSet as = (AnnotationSet) bindHashMap.get(s);
151                         try {
152                             Annotation rightAnn = neededAnnotation(as, s);
153                             if (null != rightAnn)
154                                 currText = as.getDocument().getContent().getContent(rightAnn.getStartNode().getOffset(), rightAnn.getEndNode().getOffset()).toString();
155                         } catch (Exception e) {
156                             e.printStackTrace();
157                         }
158                         break;
159                     }
160                 }
161             }
162             result.add(currText);
163         }
164         return result;
165     }
166 
167     private Annotation neededAnnotation(AnnotationSet annSet, String target) {
168 
169         ArrayList containedFeatures = new ArrayList();
170         StringTokenizer st = new StringTokenizer(target, "==");
171         if (st.countTokens() == 1) {
172         } else {
173             for (String currToken = st.nextToken(); st.hasMoreTokens(); currToken = st.nextToken()) {
174                 int point = currToken.indexOf(".");
175                 if (point != -1) {
176                     if (!currToken.substring(0, point).endsWith("Lookup"))
177                         if (!currToken.substring(0, point).endsWith("Token")) {
178                             currToken = currToken.substring(point + 1);
179                             containedFeatures.add(currToken);
180                         }
181                 }
182             }
183         }
184         boolean isEqual = true;
185         Iterator iterSet = annSet.iterator();
186         while (iterSet.hasNext()) {
187             Annotation ann = (Annotation) iterSet.next();
188             String annType = ann.getType();
189             if (target.indexOf(annType) != -1) {
190                 gate.FeatureMap fm = ann.getFeatures();
191                 for (int i = 0; i < containedFeatures.size(); i++) {
192                     String s = (String) containedFeatures.get(i);
193                     if (!fm.containsKey(s)) {
194                         isEqual = false;
195                         break;
196                     }
197                 }
198                 Iterator iter = fm.keySet().iterator();
199                 while (iter.hasNext()) {
200                     String key = (String) iter.next();
201                     if (target.indexOf(annType + "." + key) != -1) {
202                         if (target.indexOf(annType + "." + key + "==\"" + fm.get(key) + "\"") == -1) {
203                             isEqual = false;
204                         }
205                     }
206                 }
207                 if (isEqual)
208                     return ann;
209                 else
210                     isEqual = true;
211             }
212         }
213         return null;
214     }
215 
216     public ArrayList getMatchedAnnotations() {
217         ArrayList alCPE = getMatshedRuleTable();
218         ArrayList result = new ArrayList();
219         HashMap bindHashMap = getBindings();
220         for (int i = 0; i < alCPE.size(); i++) {
221             String currStr = ((String) alCPE.get(i)).trim();
222             Iterator bindIter = bindHashMap.keySet().iterator();
223             Annotation rightAnn = null;
224             while (bindIter.hasNext()) {
225                 String s = (String) bindIter.next();
226                 if (s.startsWith("{")) {
227                     if (s.equals(currStr)) {
228                         AnnotationSet as = (AnnotationSet) bindHashMap.get(s);
229                         try {
230                             rightAnn = neededAnnotation(as, s);
231                         } catch (Exception e) {
232                             e.printStackTrace();
233                         }
234                         break;
235                     }
236                 }
237             }
238             result.add(rightAnn);
239         }
240         return result;
241     }
242 
243     public PhaseModel getParentPhase() {
244         ArrayList prs = ResourcesFactory.getPrRoot().getPRs();
245         for (int i = 0; i < prs.size(); i++) {
246             PrModel prModel = (PrModel) prs.get(i);
247             ArrayList phases = prModel.getPhases();
248             for (int j = 0; j < phases.size(); j++) {
249                 PhaseModel phaseModel = (PhaseModel) phases.get(j);
250                 ArrayList rules = phaseModel.getRules();
251                 for (int k = 0; k < rules.size(); k++) {
252                     RuleModel ruleModel = (RuleModel) rules.get(k);
253                     if (ruleModel == this) return phaseModel;
254                 }
255             }
256 
257         }
258         return null;
259 
260     }
261 
262     public String getRuleText() {
263         String result = "";
264         String all = ResourcesFactory.getCurrentJapeText();
265         if (all == null) return "";
266         all = all.substring(all.toLowerCase().indexOf("rule"));
267         int commentMLIndex = 0;
268         int commentSLIndex = 0;
269         int startIndex = 0;
270         int endIndex = 0;
271         while (result.equals("")) {
272             endIndex = all.indexOf(" " + getName() + "\n");
273             if (endIndex == -1) endIndex = all.indexOf(" " + getName() + " ");
274             if (endIndex == -1) endIndex = all.indexOf("\t" + getName() + " ");
275             if (endIndex == -1) endIndex = all.indexOf("\t" + getName() + "\n");
276 
277             if (endIndex == -1) {
278                 return "Unknoun text";
279             }
280             //procesing multiline comments
281             commentMLIndex = all.substring(0, endIndex).lastIndexOf("/*");
282             if ((commentMLIndex != -1) && (all.substring(commentMLIndex, endIndex).indexOf("*/") == -1)) {
283                 all = all.substring(endIndex + 2);
284                 continue;
285             }
286             //procesing singleline comments
287             commentSLIndex = all.substring(0, endIndex).lastIndexOf("//");
288             if ((commentSLIndex != -1) && (all.substring(commentSLIndex, endIndex).indexOf("\n") == -1)) {
289                 all = all.substring(endIndex + 2);
290                 continue;
291             }
292             startIndex = all.substring(0, endIndex).toLowerCase().lastIndexOf("rule");
293             endIndex = all.substring(startIndex + 1).toLowerCase().indexOf("Rule") + startIndex + 1;
294             if (startIndex == endIndex) endIndex = all.length();
295             //System.out.println("Rule "+getName()+"("+startIndex+","+endIndex+") is:\n "+result);
296             result = all.substring(startIndex, endIndex);
297         }
298         return result;
299     }
300 }
301