1 25 26 package net.killingar.wiki.parser; 27 28 import net.killingar.EscapedString; 29 import net.killingar.wiki.Node; 30 import net.killingar.wiki.Parser; 31 import net.killingar.wiki.impl.AbstractNode; 32 import net.killingar.wiki.impl.LineNode; 33 import net.killingar.wiki.impl.SimpleNode; 34 35 public abstract class BeginEndTagParser implements Parser 36 { 37 private String parsableString; 38 private EscapedString data; 39 private int currentOffset = 0; 40 private int line = -1; 41 42 String startKeyword, endKeyword; 43 44 private boolean started = false; 45 46 49 public BeginEndTagParser(String startKeyword, String endKeyword) 50 { 51 this.startKeyword = startKeyword; 52 this.endKeyword = endKeyword; 53 } 54 55 59 60 private void setParsableString(String inParsableString) 61 { 62 parsableString = inParsableString; 63 data = new EscapedString(parsableString); 64 currentOffset = 0; 65 } 66 67 public void setSource(Object o) 68 { 69 if (o instanceof String ) 70 setParsableString((String )o); 71 else if (o.getClass() == SimpleNode.class || o.getClass() == LineNode.class) 72 { 73 setParsableString(((AbstractNode)o).getText()); 74 line = ((AbstractNode)o).getLineNumber(); 75 } 76 else 77 throw new IllegalArgumentException ("unsupported type "+o.getClass()); 78 } 79 80 public boolean hasMore() 81 { 82 if (parsableString == null) 83 return false; 84 85 return currentOffset < parsableString.length(); 86 } 87 88 public Node next() 89 { 90 if (currentOffset >= data.length()) 91 throw new IllegalStateException ("past end"); 92 93 Node n = null; 94 95 int foo = -1; 96 foo = data.indexOf(started? endKeyword : startKeyword, currentOffset); 97 98 99 if (foo != -1) 100 { 101 if (started) 102 n = createNode(parsableString.substring(currentOffset+startKeyword.length()-1, foo), line, currentOffset, foo-1); 103 else 104 n = new SimpleNode(parsableString.substring(currentOffset, foo), line, currentOffset, foo); 105 106 started = !started; 107 } 108 else 109 { 110 foo = parsableString.length(); 112 n = new SimpleNode(parsableString.substring(currentOffset, foo), -1, currentOffset, foo); 113 } 114 115 currentOffset = foo+1; 116 117 return n; 118 } 119 120 protected abstract Node createNode(String contents, int line, int startIndex, int endIndex); 121 122 public static void main(String args[]) 123 { 124 WikiLinkParser parser = new WikiLinkParser(); 125 parser.setSource("hafaaj[fja][\\]\\]]]]"); 126 127 while (parser.hasMore() == true) 128 { 129 Node n = parser.next(); 130 System.out.println(n.getClass().toString()+": "+n.toString()); 131 } 132 } 133 } 134 | Popular Tags |