1 18 package org.apache.beehive.netui.util.iterator; 19 20 import java.sql.ResultSet ; 21 import java.sql.ResultSetMetaData ; 22 import java.sql.SQLException ; 23 import java.util.Iterator ; 24 import java.util.NoSuchElementException ; 25 import java.util.SortedMap ; 26 import java.util.TreeMap ; 27 28 import org.apache.beehive.netui.util.Bundle; 29 import org.apache.beehive.netui.util.logging.Logger; 30 31 36 public class ResultSetIterator 37 implements Iterator { 38 39 private static final Logger LOGGER = Logger.getInstance(ResultSetIterator.class); 40 41 private boolean _primed = false; 42 private String [] _columnNames = null; 43 private ResultSet _rs = null; 44 45 51 public ResultSetIterator(ResultSet resultSet) { 52 if(resultSet == null) 53 return; 54 55 _rs = resultSet; 56 57 try { 58 ResultSetMetaData rsmd = _rs.getMetaData(); 60 assert rsmd != null; 61 62 int cols = rsmd.getColumnCount(); 63 _columnNames = new String [cols]; 64 for(int i = 1; i <= cols; i++) { 65 _columnNames[i - 1] = rsmd.getColumnName(i); 66 LOGGER.trace("column[" + i + "]: " + _columnNames[i-1]); 67 } 68 } catch(SQLException sql) { 69 String msg = "An exception occurred reading ResultSetMetaData from a ResultSet. Cause: " + sql; 70 LOGGER.error(msg, sql); 71 throw new IllegalStateException (msg, sql); 72 } 73 } 74 75 81 public boolean hasNext() { 82 if(_rs == null) 83 return false; 84 85 if(_primed) 86 return true; 87 88 try { 89 _primed = _rs.next(); 90 return _primed; 91 } 92 catch(SQLException sql) { 93 String msg = "An exception occurred reading from the Iterator. Cause: " + sql; 94 LOGGER.error(msg, sql); 95 throw new IllegalStateException (msg, sql); 96 } 97 } 98 99 106 public Object next() { 107 if(_rs == null) 108 throw new NoSuchElementException (Bundle.getErrorString("IteratorFactory_Iterator_noSuchElement")); 109 110 try { 111 if(!_primed) { 112 _primed = _rs.next(); 113 if(!_primed) { 114 throw new NoSuchElementException (Bundle.getErrorString("IteratorFactory_Iterator_noSuchElement")); 115 } 116 } 117 118 _primed = false; 119 return convertRow(_rs, _columnNames); 120 } 121 catch(SQLException sql) { 122 String msg = "An exception occurred reading from the Iterator. Cause: " + sql; 123 LOGGER.error(msg, sql); 124 throw new IllegalStateException (msg, sql); 125 } 126 } 127 128 133 public void remove() { 134 throw new UnsupportedOperationException (Bundle.getErrorString("IteratorFactory_Iterator_removeUnsupported", 135 new Object []{this.getClass().getName()})); 136 } 137 138 private static final Object convertRow(final ResultSet resultSet, final String [] columnNames) 139 throws SQLException { 140 SortedMap map = new TreeMap (String.CASE_INSENSITIVE_ORDER); 141 for(int i = 0; i < columnNames.length; i++) { 142 Object value = resultSet.getObject(i+1); 143 if(resultSet.wasNull()) 144 value = null; 145 map.put(columnNames[i], value); 146 } 147 return map; 148 } 149 } 150 | Popular Tags |