1 package jester; 2 3 import java.io.IOException ; 4 import java.io.Writer ; 5 import java.util.*; 6 7 public class IgnoreListDocument { 8 public static final String FILE_NAME = "ignorelist.cfg"; 9 private IgnoreList ignoreList; 10 private String source; 11 private List ignoreRegions = new ArrayList(); 12 13 public IgnoreListDocument(String source, IgnoreList ignoreList) throws ConfigurationException { 14 this.ignoreList = ignoreList; 15 this.source = source; 16 calculateIgnoreRegions(); 17 } 18 19 public String toString() { 20 StringBuffer result = new StringBuffer (); 21 result.append("IgnoreListDocument"); 22 if(ignoreRegions.size()>0){ 23 result.append(" with ignoreRegions:\n"); 24 } 25 for (Iterator ignoreRegionIter = ignoreRegions.iterator(); ignoreRegionIter.hasNext();) { 26 IgnoreRegion ignoreRegion = (IgnoreRegion) ignoreRegionIter.next(); 27 result.append(ignoreRegion.within(source)+"\n"); 28 } 29 return result.toString(); 30 } 31 32 public int length(){ 33 return source.length(); 34 } 35 public char charAt(int index){ 36 char spaceWhenInsideIgnoreRegionToAvoidMisuse = ' '; 37 return isInIgnoreRegion(index) ? spaceWhenInsideIgnoreRegionToAvoidMisuse : source.charAt(index); 38 } 39 public String substring(int start, int end){ 41 return source.substring(start, end); 42 } 43 44 public void writeOnto(Writer writer, int start, int end) throws IOException { 45 writer.write(source, start, end); 46 } 47 48 private void calculateIgnoreRegions() throws ConfigurationException { 49 List ignorePairs = ignoreList.ignorePairs(); 50 for (Iterator iter = ignorePairs.iterator(); iter.hasNext();) { 51 IgnorePair ignorePair = (IgnorePair) iter.next(); 52 calculateIgnoreRegions(ignorePair); 53 } 54 } 55 56 private void calculateIgnoreRegions(IgnorePair ignorePair) { 57 String start = ignorePair.getStart(); 58 String end = ignorePair.getEnd(); 59 60 int previousEndIndex = 0; 61 while(true){ 62 int indexOfStart = source.indexOf(start, previousEndIndex); 63 if (indexOfStart==-1){ 64 return; 65 } 66 int indexOfEnd = source.indexOf(end, indexOfStart); 67 if (indexOfEnd==-1){ 68 return; 69 } 70 ignoreRegions.add(new IgnoreRegion(indexOfStart, indexOfEnd)); 71 previousEndIndex = indexOfEnd; 72 } 73 } 74 75 public int indexOf(String string, int startIndex) { 76 int index = source.indexOf(string, startIndex); 77 if (index==-1){ 78 return index; 79 } 80 if (isInIgnoreRegion(index)){ 81 return indexOf(string, index+1); 82 }else{ 83 return index; 84 } 85 } 86 87 private boolean isInIgnoreRegion(int index) { 88 for (Iterator iter = ignoreRegions.iterator(); iter.hasNext();) { 89 IgnoreRegion ignoreRegion = (IgnoreRegion) iter.next(); 90 if (ignoreRegion.includes(index)){ 91 return true; 92 } 93 } 94 return false; 95 } 96 } 97 | Popular Tags |