01:package com.jamonapi.utils;
02:
03:
04:import java.util.*;
05:import java.sql.*;
06:
07:/** Used with the Command interface to implement the Gang of 4 Command pattern to execute some logic for
08: * every entry of various iterators. This class allows a Command object to be passed to various iterators.
09: * This capability is also similar to function pointers in C.
10: **/
11:public class CommandIterator extends java.lang.Object {
12: private CommandIterator() {
13: }
14:
15: /** Iterate through a ResultSet passing in a Command object. The command object will be passed an Object[]
16: * representing 1 row of the result set
17: **/
18: public static void iterate(ResultSet resultSet, Command command)throws Exception {
19: ResultSetUtils rsu = ResultSetUtils.createInstance();
20: ArrayList arrayList = new ArrayList();
21: rsu.resultSetToArrayList(arrayList,resultSet);
22: iterate(arrayList, command);
23: }
24:
25: /** Iterate through a Map passing Command object a Map.Entry.
26: * Command code would look something like:
27: * entry = (Map.Entry) object;
28: * entry.getKey(), entry.getValue();
29: **/
30: public static void iterate(Map map, Command command)throws Exception {
31: iterate(map.entrySet().iterator() , command);
32: }
33:
34: /** Iterate through a Collection passing the Command object each element in the collection. **/
35: public static void iterate(Collection collection, Command command)throws Exception {
36: iterate(collection.iterator() , command);
37: }
38:
39:
40: /** Iterate through an Enumeration passing the Command object each element in the Collection **/
41: public static void iterate(Enumeration enum, Command command)throws Exception {
42: iterate(new EnumIterator(enum) , command);
43: }
44:
45: /** Iterate passing each Command each Object that is being iterated **/
46: public static void iterate(Iterator iterator, Command command)throws Exception {
47: while (iterator.hasNext()) {
48: command.execute(iterator.next());
49: }
50: }
51:
52: /** Test code for this class **/
53: public static void main(String argv[]) throws Exception {
54: ArrayList arrayList = new ArrayList();
55: Vector vector = new Vector();
56:
57: class TestCommand implements Command {
58: public void execute(Object value) throws Exception {
59: System.out.println("command"+value);
60: }
61:
62: };
63:
64: TestCommand testCommand = new TestCommand();
65:
66: arrayList.add("1");
67: arrayList.add("2");
68: arrayList.add("3");
69:
70: vector.addElement("4");
71: vector.addElement("5");
72: vector.addElement("6");
73:
74: iterate(arrayList, testCommand);
75: iterate(vector.elements(), testCommand);
76: }
77:
78:
79:}
|