01: /**
02: * An object for iterating a {@link JavaSource} object by getting connected pieces of Java source
03: * code having the same type. Line breaks are omitted, but empty lines will be covered.
04: *
05: * @see JavaSourceRun
06: */package de.java2html.javasource;
07:
08: import java.util.Iterator;
09: import java.util.NoSuchElementException;
10:
11: public class JavaSourceIterator implements Iterator {
12: private int startIndex;
13: private int endIndex;
14: private JavaSource javaSource;
15: private boolean finished;
16: private boolean isNewLine;
17:
18: public JavaSourceIterator(JavaSource javaSource) {
19: this .javaSource = javaSource;
20: finished = false;
21: isNewLine = false;
22: startIndex = 0;
23: endIndex = 0;
24: if (javaSource.getCode().length() == 0) {
25: finished = true;
26: }
27: }
28:
29: private void seekToNext() {
30: if (isNewLine) {
31: startIndex = endIndex + 2;
32: endIndex = startIndex + 1;
33: isNewLine = false;
34: } else {
35: startIndex = endIndex;
36: endIndex = startIndex + 1;
37: }
38:
39: if (endIndex > javaSource.getCode().length()) {
40: --endIndex;
41: }
42:
43: // System.out.println(startIndex+".."+endIndex);
44:
45: while (true) {
46: if (endIndex == javaSource.getCode().length()) {
47: //System.out.println("1");
48: break;
49: }
50: if (endIndex <= javaSource.getCode().length() - 1
51: && javaSource.getCode().charAt(endIndex) == '\n') {
52: --endIndex;
53:
54: isNewLine = true;
55: //System.out.println("2");
56: break;
57: }
58: if (javaSource.getClassification()[endIndex] != javaSource
59: .getClassification()[startIndex]
60: && javaSource.getClassification()[endIndex] != JavaSourceType.BACKGROUND) {
61: //System.out.println("3");
62: break;
63: }
64: //System.out.println("+");
65:
66: ++endIndex;
67: }
68: // System.out.println("=>"+startIndex+".."+endIndex);
69: }
70:
71: public boolean hasNext() {
72: return !finished;
73: }
74:
75: public JavaSourceRun getNext() throws NoSuchElementException {
76: if (finished) {
77: throw new NoSuchElementException();
78: }
79: seekToNext();
80:
81: //Sonderfall: Hinter abschliessendem Newline in letzer Zeile ("\r\n")
82: if (startIndex >= javaSource.getCode().length()) {
83: --startIndex;
84: --endIndex;
85: }
86: JavaSourceRun run = new JavaSourceRun(javaSource, startIndex,
87: endIndex);
88: finished = endIndex == javaSource.getCode().length();
89: return run;
90: }
91:
92: public Object next() throws NoSuchElementException {
93: return getNext();
94: }
95:
96: public void remove() {
97: //nothing to do
98: }
99: }
|