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 015package org.apache.tapestry.contrib.table.model.sql; 016 017import java.sql.ResultSet; 018import java.sql.SQLException; 019import java.util.Iterator; 020 021import org.apache.commons.logging.Log; 022import org.apache.commons.logging.LogFactory; 023 024/** 025 * 026 * @author mindbridge 027 */ 028public class ResultSetIterator implements Iterator 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( 060 "SQLException while testing for end of the ResultSet", 061 e); 062 m_bAvailable = false; 063 } 064 065 if (!m_bAvailable) 066 notifyEnd(); 067 } 068 069 return m_bAvailable; 070 } 071 072 /** 073 * @see java.util.Iterator#next() 074 */ 075 public synchronized Object next() 076 { 077 ResultSet objResultSet = getResultSet(); 078 079 try 080 { 081 if (!objResultSet.next()) 082 return null; 083 } 084 catch (SQLException e) 085 { 086 LOG.warn("SQLException while iterating over the ResultSet", e); 087 return null; 088 } 089 090 m_bFetched = false; 091 return objResultSet; 092 } 093 094 /** 095 * @see java.util.Iterator#remove() 096 */ 097 public void remove() 098 { 099 try 100 { 101 getResultSet().deleteRow(); 102 } 103 catch (SQLException e) 104 { 105 LOG.error("Cannot delete record", e); 106 } 107 } 108 109 /** 110 * Returns the resultSet. 111 * @return ResultSet 112 */ 113 public ResultSet getResultSet() 114 { 115 return m_objResultSet; 116 } 117 118 protected void notifyEnd() 119 { 120 } 121 122}