001: package fit;
002:
003: // Copyright (c) 2002 Cunningham & Cunningham, Inc.
004: // Released under the terms of the GNU General Public License version 2 or later.
005:
006: public class ColumnFixture extends Fixture {
007:
008: protected TypeAdapter columnBindings[];
009: protected boolean hasExecuted = false;
010:
011: // Traversal ////////////////////////////////
012:
013: public void doRows(Parse rows) {
014: bind(rows.parts);
015: super .doRows(rows.more);
016: }
017:
018: public void doRow(Parse row) {
019: hasExecuted = false;
020: try {
021: reset();
022: super .doRow(row);
023: if (!hasExecuted) {
024: execute();
025: }
026: } catch (Exception e) {
027: exception(row.leaf(), e);
028: }
029: }
030:
031: public void doCell(Parse cell, int column) {
032: TypeAdapter a = columnBindings[column];
033: try {
034: String text = cell.text();
035: if (text.equals("")) {
036: check(cell, a);
037: } else if (a == null) {
038: ignore(cell);
039: } else if (a.field != null) {
040: a.set(a.parse(text));
041: } else if (a.method != null) {
042: check(cell, a);
043: }
044: } catch (Exception e) {
045: exception(cell, e);
046: }
047: }
048:
049: public void check(Parse cell, TypeAdapter a) {
050: if (!hasExecuted) {
051: try {
052: execute();
053: } catch (Exception e) {
054: exception(cell, e);
055: }
056: hasExecuted = true;
057: }
058: super .check(cell, a);
059: }
060:
061: public void reset() throws Exception {
062: // about to process first cell of row
063: }
064:
065: public void execute() throws Exception {
066: // about to process first method call of row
067: }
068:
069: // Utility //////////////////////////////////
070:
071: protected void bind(Parse heads) {
072: columnBindings = new TypeAdapter[heads.size()];
073: for (int i = 0; heads != null; i++, heads = heads.more) {
074: String name = heads.text();
075: String suffix = "()";
076: try {
077: if (name.equals("")) {
078: columnBindings[i] = null;
079: } else if (name.endsWith(suffix)) {
080: columnBindings[i] = bindMethod(name.substring(0,
081: name.length() - suffix.length()));
082: } else {
083: columnBindings[i] = bindField(name);
084: }
085: } catch (Exception e) {
086: exception(heads, e);
087: }
088: }
089:
090: }
091:
092: protected TypeAdapter bindMethod(String name) throws Exception {
093: return TypeAdapter.on(this , getTargetClass().getMethod(
094: camel(name), new Class[] {}));
095: }
096:
097: protected TypeAdapter bindField(String name) throws Exception {
098: return TypeAdapter.on(this , getTargetClass().getField(
099: camel(name)));
100: }
101:
102: protected Class getTargetClass() {
103: return getClass();
104: }
105: }
|