001: /*
002: * Licensed to the Apache Software Foundation (ASF) under one
003: * or more contributor license agreements. See the NOTICE file
004: * distributed with this work for additional information
005: * regarding copyright ownership. The ASF licenses this file
006: * to you under the Apache License, Version 2.0 (the
007: * "License"); you may not use this file except in compliance
008: * with the License. You may obtain a copy of the License at
009: *
010: * http://www.apache.org/licenses/LICENSE-2.0
011: *
012: * Unless required by applicable law or agreed to in writing,
013: * software distributed under the License is distributed on an
014: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015: * KIND, either express or implied. See the License for the
016: * specific language governing permissions and limitations
017: * under the License.
018: */
019: package org.apache.openjpa.lib.rop;
020:
021: import java.util.Iterator;
022: import java.util.NoSuchElementException;
023:
024: import org.apache.openjpa.lib.util.Closeable;
025:
026: /**
027: * Iterator wrapped around a {@link ResultObjectProvider}.
028: *
029: * @author Abe White
030: * @nojavadoc
031: */
032: public class ResultObjectProviderIterator implements Iterator,
033: Closeable {
034:
035: private final ResultObjectProvider _rop;
036: private Boolean _hasNext = null;
037: private Boolean _open = null;
038:
039: /**
040: * Constructor. Supply object provider.
041: */
042: public ResultObjectProviderIterator(ResultObjectProvider rop) {
043: _rop = rop;
044: }
045:
046: /**
047: * Close the underlying result object provider.
048: */
049: public void close() {
050: if (_open == Boolean.TRUE) {
051: try {
052: _rop.close();
053: } catch (Exception e) {
054: }
055: _open = Boolean.FALSE;
056: }
057: }
058:
059: public void remove() {
060: throw new UnsupportedOperationException();
061: }
062:
063: public boolean hasNext() {
064: if (_open == Boolean.FALSE)
065: return false;
066:
067: if (_hasNext == null) {
068: try {
069: if (_open == null) {
070: _rop.open();
071: _open = Boolean.TRUE;
072: }
073: _hasNext = (_rop.next()) ? Boolean.TRUE : Boolean.FALSE;
074: } catch (RuntimeException re) {
075: close();
076: throw re;
077: } catch (Exception e) {
078: close();
079: _rop.handleCheckedException(e);
080: return false;
081: }
082: }
083:
084: // close if we reach the end of the list
085: if (!_hasNext.booleanValue()) {
086: close();
087: return false;
088: }
089: return true;
090: }
091:
092: public Object next() {
093: if (!hasNext())
094: throw new NoSuchElementException();
095: try {
096: Object ret = _rop.getResultObject();
097: _hasNext = null;
098: return ret;
099: } catch (RuntimeException re) {
100: close();
101: throw re;
102: } catch (Exception e) {
103: close();
104: _rop.handleCheckedException(e);
105: return null;
106: }
107: }
108:
109: protected void finalize() {
110: close();
111: }
112: }
|