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