001: package com.bostechcorp.cbesb.common.util.macro;
002:
003: import java.util.Vector;
004:
005: public class MacroScanner {
006: Vector<String> macroList = new Vector<String>();
007:
008: /**
009: * @param arg0
010: * @return
011: * @see java.util.Vector#add(java.lang.Object)
012: */
013: public boolean add(String arg0) {
014: return macroList.add(arg0);
015: }
016:
017: public MacroScanner(String data) {
018: super ();
019: scan(new StringBuffer(data));
020: }
021:
022: /**
023: * @return the macroList
024: */
025: public Vector<String> getMacroList() {
026: return macroList;
027: }
028:
029: protected int scan(StringBuffer data) {
030: int elemStart = -1; // offset to start of discovered element
031: boolean firstStart = false;
032: boolean braceQuoted = false; // Was element quoted by braces
033: int limit = data.length();
034: int nelems = 0;
035: int pos = 0;
036:
037: while (pos < limit) {
038: // Skim off leading white space and check for opening brace or quote
039: while ((pos < limit)
040: && (Character.isWhitespace(data.charAt(pos)))) {
041: pos++;
042: }
043:
044: if (pos == limit) { // no more elements found
045: return nelems;
046: }
047:
048: char cp = data.charAt(pos);
049: braceQuoted = false;
050:
051: if (cp == '$') {
052: firstStart = true;
053: }
054: pos++;
055:
056: if (pos == limit) { // no more elements found
057: return nelems;
058: }
059: cp = data.charAt(pos);
060:
061: if (firstStart && cp == '{') {
062: braceQuoted = true;
063: firstStart = false;
064: }
065: pos++;
066:
067: elemStart = pos; // Start of the element
068:
069: // Find element's end (space, close brace, or end of the string).
070: boolean elemFound = false;
071:
072: while (braceQuoted && !elemFound && pos < limit) {
073: cp = data.charAt(pos);
074:
075: switch (cp) {
076:
077: case '}': // Deal with nesting
078:
079: // This is the closing brace, we found an element
080: elemFound = true;
081: braceQuoted = false;
082:
083: break;
084: }
085:
086: if (elemFound) {
087: // Found an element, update count, store element, and test
088: // for end of list.
089: // Note: If the element was not brace quoted, then we do
090: // one level of backslash interpolation.
091:
092: String elemVal = data.toString().substring(
093: elemStart, pos);
094:
095: add(elemVal);
096: nelems++;
097:
098: }
099: pos++;
100: }
101: }
102:
103: // Falling through to here means that we are scanning a simple string
104: // (i.e. no reader was given) and we hit the end of the string. We
105: // need to process the residual element at the end of the string.
106:
107: return nelems;
108: }
109:
110: // Test method
111: static public void main(String args[]) {
112:
113: MacroScanner scanner = new MacroScanner(
114: "${cbesb_home}::src/format/${jsa_proj}{c.mdl}");
115: Vector<String> list = scanner.getMacroList();
116: System.out.println(list.size());
117: for (String string : list) {
118: System.out.println(string);
119: }
120:
121: }
122: }
|