001 // Copyright 2004, 2005 The Apache Software Foundation
002 //
003 // Licensed under the Apache License, Version 2.0 (the "License");
004 // you may not use this file except in compliance with the License.
005 // You may obtain a copy of the License at
006 //
007 // http://www.apache.org/licenses/LICENSE-2.0
008 //
009 // Unless required by applicable law or agreed to in writing, software
010 // distributed under the License is distributed on an "AS IS" BASIS,
011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012 // See the License for the specific language governing permissions and
013 // limitations under the License.
014
015 package org.apache.tapestry.contrib.table.model.sql;
016
017 import java.sql.ResultSet;
018 import java.sql.SQLException;
019 import java.util.Iterator;
020
021 import org.apache.commons.logging.Log;
022 import org.apache.commons.logging.LogFactory;
023
024 /**
025 * @author mindbridge
026 */
027 public class ResultSetIterator implements Iterator
028 {
029
030 private static final Log LOG = LogFactory.getLog(ResultSetIterator.class);
031
032 private ResultSet m_objResultSet;
033 private boolean m_bFetched;
034 private boolean m_bAvailable;
035
036 public ResultSetIterator(ResultSet objResultSet)
037 {
038 m_objResultSet = objResultSet;
039 m_bFetched = false;
040 }
041
042 /**
043 * @see java.util.Iterator#hasNext()
044 */
045 public synchronized boolean hasNext()
046 {
047 if (getResultSet() == null) return false;
048
049 if (!m_bFetched)
050 {
051 m_bFetched = true;
052
053 try
054 {
055 m_bAvailable = !getResultSet().isLast();
056 }
057 catch (SQLException e)
058 {
059 LOG.warn("SQLException while testing for end of the ResultSet",
060 e);
061 m_bAvailable = false;
062 }
063
064 if (!m_bAvailable) notifyEnd();
065 }
066
067 return m_bAvailable;
068 }
069
070 /**
071 * @see java.util.Iterator#next()
072 */
073 public synchronized Object next()
074 {
075 ResultSet objResultSet = getResultSet();
076
077 try
078 {
079 if (!objResultSet.next()) return null;
080 }
081 catch (SQLException e)
082 {
083 LOG.warn("SQLException while iterating over the ResultSet", e);
084 return null;
085 }
086
087 m_bFetched = false;
088 return objResultSet;
089 }
090
091 /**
092 * @see java.util.Iterator#remove()
093 */
094 public void remove()
095 {
096 try
097 {
098 getResultSet().deleteRow();
099 }
100 catch (SQLException e)
101 {
102 LOG.error("Cannot delete record", e);
103 }
104 }
105
106 /**
107 * Returns the resultSet.
108 *
109 * @return ResultSet
110 */
111 public ResultSet getResultSet()
112 {
113 return m_objResultSet;
114 }
115
116 protected void notifyEnd()
117 {
118 }
119
120 }