1 package net.sf.morph.reflect.support;
2
3 import java.sql.ResultSet;
4 import java.sql.SQLException;
5 import java.util.Iterator;
6 import java.util.NoSuchElementException;
7
8 import net.sf.morph.MorphException;
9
10 import org.apache.commons.logging.Log;
11 import org.apache.commons.logging.LogFactory;
12
13 /**
14 * An iterator over a ResultSet. SQLExceptions are wrapped in MorphExceptions.
15 *
16 * @author Matt Sgarlata
17 * @since Dec 20, 2004
18 */
19 public class ResultSetIterator implements Iterator {
20
21 private static final Log log = LogFactory.getLog(ResultSetIterator.class);
22 private static final String NO_MORE = "There are no more rows in the ResultSet";
23
24 private ResultSet resultSet;
25 private boolean hasNext;
26
27 private boolean hasReturnedRow;
28
29 public ResultSetIterator(ResultSet resultSet) {
30 this.resultSet = resultSet;
31
32
33
34 this.hasReturnedRow = true;
35 }
36
37 public boolean hasNext() {
38 if (hasReturnedRow) {
39 advanceToNextRow();
40 hasReturnedRow = false;
41 }
42 return hasNext;
43 }
44
45 public Object next() {
46 if (hasNext()) {
47 hasReturnedRow = true;
48 return resultSet;
49 }
50 throw new NoSuchElementException(NO_MORE);
51 }
52
53 protected void advanceToNextRow() throws MorphException {
54 try {
55 hasNext = resultSet.next();
56 }
57 catch (SQLException e) {
58 handleResultSetNextException(e);
59 }
60 }
61
62 protected void handleResultSetNextException(SQLException e)
63 throws MorphException {
64 if (log.isErrorEnabled()) {
65 log.error("Error moving to next row in resultSet", e);
66 }
67 throw new MorphException("Error moving to next row in resultSet", e);
68 }
69
70 public void remove() {
71 throw new UnsupportedOperationException();
72 }
73 }