1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package net.sf.jameleon.data;
21
22 import java.io.IOException;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.Map;
27
28 /***
29 * This DataDriver is used to iterator over a Collection of Objects.
30 * @author Andrey Chernyshov
31 * @author Christian Hargraves
32 */
33 public class CollectionDataDriver implements DataDriver {
34 protected Collection items;
35 protected String key;
36 protected Iterator iterator;
37
38 /***
39 * Creates a CollectionDataDriver
40 * You must call setKey() and setItems() in order for this DataDriver to work correctly
41 */
42 public CollectionDataDriver() {
43 }
44
45 /***
46 * Creates a CollectionDataDriver
47 * @param key - the key to store the object in the collection as
48 * @param items - the collection of items to iterator over
49 */
50 public CollectionDataDriver(String key, Collection items) {
51 this.items = items;
52 this.key = key;
53 }
54
55 public void setItems(Collection items) {
56 this.items = items;
57 }
58
59 public void setKey(String key) {
60 this.key = key;
61 }
62
63 /***
64 * Opens the handle to the data source
65 *
66 * @throws java.io.IOException when the data source can not be found.
67 */
68 public void open() throws IOException {
69 if (items != null && key != null) {
70 iterator = items.iterator();
71 }else{
72 String errorMsg = null;
73 if (items == null) {
74 errorMsg = "No Data provided!";
75 }else{
76 errorMsg = "No Key provided!";
77 }
78 throw new IOException(errorMsg);
79 }
80 }
81
82 /***
83 * Closes the handle to the data source
84 */
85 public void close() {
86 iterator = null;
87 }
88
89 /***
90 * Gets the next row from the data source
91 *
92 * @return a key-value HashMap representing the data row or null if
93 * no data row is available
94 */
95 public Map getNextRow() {
96 Map vars = null;
97 if (iterator.hasNext()) {
98 vars = new HashMap();
99 vars.put(key, iterator.next());
100 }
101 return vars;
102 }
103
104 /***
105 * Tells whether the data source has another row
106 *
107 * @return true if the data source still has more rows
108 */
109 public boolean hasMoreRows() {
110 return iterator.hasNext();
111 }
112 }
113
114