001: package com.jamonapi.utils;
002:
003: /** Used with the Command interface to implement the Gang of 4 Command pattern to execute some logic for
004:
005: * every entry of various iterators. This class allows a Command object to be passed to various iterators.
006:
007: * This capability is also similar to function pointers in C.
008:
009: **/
010:
011: import java.util.*;
012:
013: public class CommandIterator extends java.lang.Object {
014:
015: private CommandIterator() {
016:
017: }
018:
019: /** Iterate through a ResultSet passing in a Command object. The command object will be passed an Object[]
020:
021: * representing 1 row of the result set
022:
023: **/
024:
025: /* public static void iterate(ResultSet resultSet, Command command)throws Exception {
026:
027: ResultSetUtils rsu = ResultSetUtils.createInstance();
028:
029: ArrayList arrayList = new ArrayList();
030:
031: rsu.resultSetToArrayList(arrayList,resultSet);
032:
033: iterate(arrayList, command);
034:
035: }
036:
037: */
038:
039: /** Iterate through a Map passing Command object a Map.Entry.
040:
041: * Command code would look something like:
042:
043: * entry = (Map.Entry) object;
044:
045: * entry.getKey(), entry.getValue();
046:
047: **/
048:
049: public static void iterate(Map map, Command command)
050: throws Exception {
051:
052: iterate(map.entrySet().iterator(), command);
053:
054: }
055:
056: /** Iterate through a Collection passing the Command object each element in the collection. **/
057:
058: public static void iterate(Collection collection, Command command)
059: throws Exception {
060:
061: iterate(collection.iterator(), command);
062:
063: }
064:
065: /** Iterate through an Enumeration passing the Command object each element in the Collection **/
066:
067: public static void iterate(Enumeration enumer, Command command)
068: throws Exception {
069:
070: iterate(new EnumIterator(enumer), command);
071:
072: }
073:
074: /** Iterate passing each Command each Object that is being iterated **/
075:
076: public static void iterate(Iterator iterator, Command command)
077: throws Exception {
078:
079: while (iterator.hasNext()) {
080:
081: command.execute(iterator.next());
082:
083: }
084:
085: }
086:
087: /** Test code for this class **/
088:
089: public static void main(String argv[]) throws Exception {
090:
091: ArrayList arrayList = new ArrayList();
092:
093: Vector vector = new Vector();
094:
095: class TestCommand implements Command {
096:
097: public void execute(Object value) throws Exception {
098:
099: System.out.println("command" + value);
100:
101: }
102:
103: }
104: ;
105:
106: TestCommand testCommand = new TestCommand();
107:
108: arrayList.add("1");
109:
110: arrayList.add("2");
111:
112: arrayList.add("3");
113:
114: vector.addElement("4");
115:
116: vector.addElement("5");
117:
118: vector.addElement("6");
119:
120: iterate(arrayList, testCommand);
121:
122: iterate(vector.elements(), testCommand);
123:
124: }
125:
126: }
|