01: package com.opensymphony.module.sitemesh.html;
02:
03: import java.util.ArrayList;
04: import java.util.Iterator;
05: import java.util.List;
06:
07: public final class State {
08:
09: private TagRule[] rules = new TagRule[16]; // List is too slow, according to profiler
10: private int ruleCount = 0;
11: private List listeners = null;
12: private List textFilters = null; // lazily instantiated to reduce overhead for most cases where it's not needed.
13:
14: public void addRule(TagRule rule) {
15: if (ruleCount == rules.length) {
16: // grow array if necessary
17: TagRule[] longerArray = new TagRule[rules.length * 2];
18: System.arraycopy(rules, 0, longerArray, 0, ruleCount);
19: rules = longerArray;
20: }
21: rules[ruleCount++] = rule;
22: }
23:
24: public void addTextFilter(TextFilter textFilter) {
25: if (textFilters == null) {
26: textFilters = new ArrayList(); // lazy instantiation
27: }
28: textFilters.add(textFilter);
29: }
30:
31: public boolean shouldProcessTag(String tagName) {
32: for (int i = ruleCount - 1; i >= 0; i--) { // reverse iteration to so most recently added rule matches
33: if (rules[i].shouldProcess(tagName)) {
34: return true;
35: }
36: }
37: return false;
38: }
39:
40: public TagRule getRule(String tagName) {
41: for (int i = ruleCount - 1; i >= 0; i--) { // reverse iteration to so most recently added rule matches
42: if (rules[i].shouldProcess(tagName)) {
43: return rules[i];
44: }
45: }
46: return null;
47: }
48:
49: public void addListener(StateChangeListener listener) {
50: if (listeners == null)
51: listeners = new ArrayList();
52: listeners.add(listener);
53: }
54:
55: public void endOfState() {
56: if (listeners == null)
57: return;
58: for (Iterator iter = listeners.iterator(); iter.hasNext();) {
59: StateChangeListener listener = (StateChangeListener) iter
60: .next();
61: listener.stateFinished();
62: }
63: }
64:
65: public void handleText(Text text, HTMLProcessorContext context) {
66: if (textFilters == null) {
67: text.writeTo(context.currentBuffer());
68: } else {
69: String asString = text.getContents();
70: for (Iterator iterator = textFilters.iterator(); iterator
71: .hasNext();) {
72: TextFilter textFilter = (TextFilter) iterator.next();
73: asString = textFilter.filter(asString);
74: }
75: context.currentBuffer().append(asString);
76: }
77: }
78:
79: }
|