1 23 24 28 29 32 33 package com.sun.enterprise.admin.util; 34 35 import java.util.NoSuchElementException ; 36 37 public class QuotedStringTokenizer 38 { 39 private final char[] ca; 40 private String delimiters = "\t "; 41 private final int numTokens; 42 private int curToken = 0; 43 private final CharIterator iterator; 44 45 public QuotedStringTokenizer(String s) 46 { 47 this(s, null); 48 } 49 50 public QuotedStringTokenizer(String s, String delim) 51 { 52 if (null == s) 53 { 54 throw new IllegalArgumentException ("null param"); 55 } 56 ca = s.toCharArray(); 57 if (delim != null && delim.length() > 0) 58 { 59 delimiters = delim; 60 } 61 numTokens = _countTokens(); 62 iterator = new CharIterator(ca); 63 } 64 65 public int countTokens() 66 { 67 return numTokens; 68 } 69 70 public boolean hasMoreTokens() 71 { 72 return curToken < numTokens; 73 } 74 75 public String nextToken() 76 { 77 if (curToken == numTokens) 78 throw new NoSuchElementException (); 79 final StringBuffer sb = new StringBuffer (); 80 boolean bQuote = false; 81 boolean bEscaped = false; 82 char c; 83 while ((c = iterator.next()) != CharIterator.EOF) 84 { 85 boolean isDelimiter = isDelimiter(c); 86 if (!isDelimiter && !bEscaped) 87 { 88 sb.append(c); 89 if (c == '\"') 90 bQuote = !bQuote; 91 char next = iterator.peekNext(); 92 if (next == CharIterator.EOF || (isDelimiter(next) && !bQuote)) 93 break; 94 } 95 else if (bQuote || bEscaped) 96 { 97 sb.append(c); 98 } 99 if(c=='\\') 100 bEscaped = !bEscaped; 101 else 102 bEscaped = false; 103 } 104 curToken++; 105 return sb.toString(); 106 } 107 108 boolean isDelimiter(char c) 109 { 110 return delimiters.indexOf(c) >= 0; 111 } 112 113 private int _countTokens() 114 { 115 int tokens = 0; 116 boolean bQuote = false; 117 boolean bEscaped = false; 118 final CharIterator it = new CharIterator(ca); 119 char c; 120 121 while ((c = it.next()) != CharIterator.EOF) 122 { 123 char next = it.peekNext(); 124 if (!isDelimiter(c) && !bEscaped) 125 { 126 if (c == '\"') 127 bQuote = !bQuote; 128 if (next == CharIterator.EOF || (isDelimiter(next) && !bQuote)) 129 tokens++; 130 } 131 else if (next == CharIterator.EOF && bQuote) tokens++; 133 if(c=='\\') 134 bEscaped = !bEscaped; 135 else 136 bEscaped = false; 137 } 138 return tokens; 139 } 140 141 private static final class CharIterator 142 { 143 static final char EOF = '\uFFFF'; 144 145 private final char[] carr; 146 private int index = 0; 147 148 private CharIterator(char[] ca) 149 { 150 carr = ca; 151 } 152 153 char next() 154 { 155 if (index >= carr.length) 156 return EOF; 157 char c = carr[index]; 158 ++index; 159 return c; 160 } 161 162 char peekNext() 163 { 164 if (index >= carr.length) 165 return EOF; 166 return carr[index]; 167 } 168 } 169 } 170 | Popular Tags |