001: /*
002: * Copyright (c) 2001 The Open For Business Project - www.ofbiz.org
003: *
004: * Permission is hereby granted, free of charge, to any person obtaining a
005: * copy of this software and associated documentation files (the "Software"),
006: * to deal in the Software without restriction, including without limitation
007: * the rights to use, copy, modify, merge, publish, distribute, sublicense,
008: * and/or sell copies of the Software, and to permit persons to whom the
009: * Software is furnished to do so, subject to the following conditions:
010: *
011: * The above copyright notice and this permission notice shall be included
012: * in all copies or substantial portions of the Software.
013: *
014: * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
015: * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
016: * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
017: * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
018: * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
019: * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
020: * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
021: */
022:
023: package org.ofbiz.entity.util;
024:
025: import java.sql.ResultSet;
026: import java.sql.SQLException;
027: import java.util.ArrayList;
028: import java.util.LinkedList;
029: import java.util.List;
030: import java.util.ListIterator;
031:
032: import org.ofbiz.base.util.Debug;
033: import org.ofbiz.base.util.GeneralRuntimeException;
034: import org.ofbiz.entity.GenericDelegator;
035: import org.ofbiz.entity.GenericEntityException;
036: import org.ofbiz.entity.GenericResultSetClosedException;
037: import org.ofbiz.entity.GenericValue;
038: import org.ofbiz.entity.jdbc.SQLProcessor;
039: import org.ofbiz.entity.jdbc.SqlJdbcUtil;
040: import org.ofbiz.entity.model.ModelEntity;
041: import org.ofbiz.entity.model.ModelField;
042: import org.ofbiz.entity.model.ModelFieldTypeReader;
043:
044: /**
045: * Generic Entity Cursor List Iterator for Handling Cursored DB Results
046: *
047: *@author <a href="mailto:jonesde@ofbiz.org">David E. Jones</a>
048: *@version $Revision: 1.5 $
049: *@since 2.0
050: */
051: public class EntityListIterator implements ListIterator {
052:
053: /** Module Name Used for debugging */
054: public static final String module = EntityListIterator.class
055: .getName();
056:
057: protected SQLProcessor sqlp;
058: protected ResultSet resultSet;
059: protected ModelEntity modelEntity;
060: protected List selectFields;
061: protected ModelFieldTypeReader modelFieldTypeReader;
062: protected boolean closed = false;
063: protected boolean haveMadeValue = false;
064: protected GenericDelegator delegator = null;
065:
066: public EntityListIterator(SQLProcessor sqlp,
067: ModelEntity modelEntity, List selectFields,
068: ModelFieldTypeReader modelFieldTypeReader) {
069: this .sqlp = sqlp;
070: this .resultSet = sqlp.getResultSet();
071: this .modelEntity = modelEntity;
072: this .selectFields = selectFields;
073: this .modelFieldTypeReader = modelFieldTypeReader;
074: }
075:
076: public void setDelegator(GenericDelegator delegator) {
077: this .delegator = delegator;
078: }
079:
080: /** Sets the cursor position to just after the last result so that previous() will return the last result */
081: public void afterLast() throws GenericEntityException {
082: try {
083: resultSet.afterLast();
084: } catch (SQLException e) {
085: if (!closed) {
086: this .close();
087: Debug.logWarning(
088: "Warning: auto-closed EntityListIterator because of exception: "
089: + e.toString(), module);
090: }
091: throw new GenericEntityException(
092: "Error setting the cursor to afterLast", e);
093: }
094: }
095:
096: /** Sets the cursor position to just before the first result so that next() will return the first result */
097: public void beforeFirst() throws GenericEntityException {
098: try {
099: resultSet.beforeFirst();
100: } catch (SQLException e) {
101: if (!closed) {
102: this .close();
103: Debug.logWarning(
104: "Warning: auto-closed EntityListIterator because of exception: "
105: + e.toString(), module);
106: }
107: throw new GenericEntityException(
108: "Error setting the cursor to beforeFirst", e);
109: }
110: }
111:
112: /** Sets the cursor position to last result; if result set is empty returns false */
113: public boolean last() throws GenericEntityException {
114: try {
115: return resultSet.last();
116: } catch (SQLException e) {
117: if (!closed) {
118: this .close();
119: Debug.logWarning(
120: "Warning: auto-closed EntityListIterator because of exception: "
121: + e.toString(), module);
122: }
123: throw new GenericEntityException(
124: "Error setting the cursor to last", e);
125: }
126: }
127:
128: /** Sets the cursor position to last result; if result set is empty returns false */
129: public boolean first() throws GenericEntityException {
130: try {
131: return resultSet.first();
132: } catch (SQLException e) {
133: if (!closed) {
134: this .close();
135: Debug.logWarning(
136: "Warning: auto-closed EntityListIterator because of exception: "
137: + e.toString(), module);
138: }
139: throw new GenericEntityException(
140: "Error setting the cursor to first", e);
141: }
142: }
143:
144: public void close() throws GenericEntityException {
145: if (closed) {
146: //maybe not the best way: throw new GenericResultSetClosedException("This EntityListIterator has been closed, this operation cannot be performed");
147: Debug.logWarning("This EntityListIterator for Entity ["
148: + modelEntity == null ? "" : modelEntity
149: .getEntityName()
150: + "] has already been closed, not closing again.",
151: module);
152: } else {
153: sqlp.close();
154: closed = true;
155: }
156: }
157:
158: /** NOTE: Calling this method does return the current value, but so does calling next() or previous(), so calling one of those AND this method will cause the value to be created twice */
159: public GenericValue currentGenericValue()
160: throws GenericEntityException {
161: if (closed)
162: throw new GenericResultSetClosedException(
163: "This EntityListIterator has been closed, this operation cannot be performed");
164:
165: GenericValue value = new GenericValue(modelEntity);
166:
167: for (int j = 0; j < selectFields.size(); j++) {
168: ModelField curField = (ModelField) selectFields.get(j);
169:
170: SqlJdbcUtil.getValue(resultSet, j + 1, curField, value,
171: modelFieldTypeReader);
172: }
173:
174: value.setDelegator(this .delegator);
175: value.synchronizedWithDatasource();
176: this .haveMadeValue = true;
177: return value;
178: }
179:
180: public int currentIndex() throws GenericEntityException {
181: if (closed)
182: throw new GenericResultSetClosedException(
183: "This EntityListIterator has been closed, this operation cannot be performed");
184:
185: try {
186: return resultSet.getRow();
187: } catch (SQLException e) {
188: if (!closed) {
189: this .close();
190: Debug.logWarning(
191: "Warning: auto-closed EntityListIterator because of exception: "
192: + e.toString(), module);
193: }
194: throw new GenericEntityException(
195: "Error getting the current index", e);
196: }
197: }
198:
199: /** performs the same function as the ResultSet.absolute method;
200: * if rowNum is positive, goes to that position relative to the beginning of the list;
201: * if rowNum is negative, goes to that position relative to the end of the list;
202: * a rowNum of 1 is the same as first(); a rowNum of -1 is the same as last()
203: */
204: public boolean absolute(int rowNum) throws GenericEntityException {
205: if (closed)
206: throw new GenericResultSetClosedException(
207: "This EntityListIterator has been closed, this operation cannot be performed");
208:
209: try {
210: return resultSet.absolute(rowNum);
211: } catch (SQLException e) {
212: if (!closed) {
213: this .close();
214: Debug.logWarning(
215: "Warning: auto-closed EntityListIterator because of exception: "
216: + e.toString(), module);
217: }
218: throw new GenericEntityException(
219: "Error setting the absolute index to " + rowNum, e);
220: }
221: }
222:
223: /** performs the same function as the ResultSet.relative method;
224: * if rows is positive, goes forward relative to the current position;
225: * if rows is negative, goes backward relative to the current position;
226: */
227: public boolean relative(int rows) throws GenericEntityException {
228: if (closed)
229: throw new GenericResultSetClosedException(
230: "This EntityListIterator has been closed, this operation cannot be performed");
231:
232: try {
233: return resultSet.relative(rows);
234: } catch (SQLException e) {
235: if (!closed) {
236: this .close();
237: Debug.logWarning(
238: "Warning: auto-closed EntityListIterator because of exception: "
239: + e.toString(), module);
240: }
241: throw new GenericEntityException(
242: "Error going to the relative index " + rows, e);
243: }
244: }
245:
246: /** PLEASE NOTE: Because of the nature of the JDBC ResultSet interface this method can be very inefficient; it is much better to just use next() until it returns null */
247: public boolean hasNext() {
248: try {
249: if (resultSet.isLast() || resultSet.isAfterLast()) {
250: return false;
251: } else {
252: // do a quick game to see if the resultSet is empty:
253: // if we are not in the first or beforeFirst positions and we haven't made any values yet, the result set is empty so return false
254: if (!haveMadeValue && !resultSet.isBeforeFirst()
255: && !resultSet.isFirst()) {
256: return false;
257: } else {
258: return true;
259: }
260: }
261: } catch (SQLException e) {
262: if (!closed) {
263: try {
264: this .close();
265: } catch (GenericEntityException e1) {
266: Debug
267: .logError(
268: e1,
269: "Error auto-closing EntityListIterator on error, so info below for more info on original error; close error: "
270: + e1.toString(), module);
271: }
272: Debug.logWarning(
273: "Warning: auto-closed EntityListIterator because of exception: "
274: + e.toString(), module);
275: }
276: throw new GeneralRuntimeException(
277: "Error while checking to see if this is the last result",
278: e);
279: }
280: }
281:
282: /** PLEASE NOTE: Because of the nature of the JDBC ResultSet interface this method can be very inefficient; it is much better to just use previous() until it returns null */
283: public boolean hasPrevious() {
284: try {
285: if (resultSet.isFirst() || resultSet.isBeforeFirst()) {
286: return false;
287: } else {
288: // do a quick game to see if the resultSet is empty:
289: // if we are not in the last or afterLast positions and we haven't made any values yet, the result set is empty so return false
290: if (!haveMadeValue && !resultSet.isAfterLast()
291: && !resultSet.isLast()) {
292: return false;
293: } else {
294: return true;
295: }
296: }
297: } catch (SQLException e) {
298: if (!closed) {
299: try {
300: this .close();
301: } catch (GenericEntityException e1) {
302: Debug
303: .logError(
304: e1,
305: "Error auto-closing EntityListIterator on error, so info below for more info on original error; close error: "
306: + e1.toString(), module);
307: }
308: Debug.logWarning(
309: "Warning: auto-closed EntityListIterator because of exception: "
310: + e.toString(), module);
311: }
312: throw new GeneralRuntimeException(
313: "Error while checking to see if this is the first result",
314: e);
315: }
316: }
317:
318: /** Moves the cursor to the next position and returns the GenericValue object for that position; if there is no next, returns null */
319: public Object next() {
320: try {
321: if (resultSet.next()) {
322: return currentGenericValue();
323: } else {
324: return null;
325: }
326: } catch (SQLException e) {
327: if (!closed) {
328: try {
329: this .close();
330: } catch (GenericEntityException e1) {
331: Debug
332: .logError(
333: e1,
334: "Error auto-closing EntityListIterator on error, so info below for more info on original error; close error: "
335: + e1.toString(), module);
336: }
337: Debug.logWarning(
338: "Warning: auto-closed EntityListIterator because of exception: "
339: + e.toString(), module);
340: }
341: throw new GeneralRuntimeException(
342: "Error getting the next result", e);
343: } catch (GenericEntityException e) {
344: if (!closed) {
345: try {
346: this .close();
347: } catch (GenericEntityException e1) {
348: Debug
349: .logError(
350: e1,
351: "Error auto-closing EntityListIterator on error, so info below for more info on original error; close error: "
352: + e1.toString(), module);
353: }
354: Debug.logWarning(
355: "Warning: auto-closed EntityListIterator because of exception: "
356: + e.toString(), module);
357: }
358: throw new GeneralRuntimeException(
359: "Error creating GenericValue", e);
360: }
361: }
362:
363: /** Returns the index of the next result, but does not guarantee that there will be a next result */
364: public int nextIndex() {
365: try {
366: return currentIndex() + 1;
367: } catch (GenericEntityException e) {
368: if (!closed) {
369: try {
370: this .close();
371: } catch (GenericEntityException e1) {
372: Debug
373: .logError(
374: e1,
375: "Error auto-closing EntityListIterator on error, so info below for more info on original error; close error: "
376: + e1.toString(), module);
377: }
378: Debug.logWarning(
379: "Warning: auto-closed EntityListIterator because of exception: "
380: + e.toString(), module);
381: }
382: throw new GeneralRuntimeException(e.getNonNestedMessage(),
383: e.getNested());
384: }
385: }
386:
387: /** Moves the cursor to the previous position and returns the GenericValue object for that position; if there is no previous, returns null */
388: public Object previous() {
389: try {
390: if (resultSet.previous()) {
391: return currentGenericValue();
392: } else {
393: return null;
394: }
395: } catch (SQLException e) {
396: if (!closed) {
397: try {
398: this .close();
399: } catch (GenericEntityException e1) {
400: Debug
401: .logError(
402: e1,
403: "Error auto-closing EntityListIterator on error, so info below for more info on original error; close error: "
404: + e1.toString(), module);
405: }
406: Debug.logWarning(
407: "Warning: auto-closed EntityListIterator because of exception: "
408: + e.toString(), module);
409: }
410: throw new GeneralRuntimeException(
411: "Error getting the previous result", e);
412: } catch (GenericEntityException e) {
413: if (!closed) {
414: try {
415: this .close();
416: } catch (GenericEntityException e1) {
417: Debug
418: .logError(
419: e1,
420: "Error auto-closing EntityListIterator on error, so info below for more info on original error; close error: "
421: + e1.toString(), module);
422: }
423: Debug.logWarning(
424: "Warning: auto-closed EntityListIterator because of exception: "
425: + e.toString(), module);
426: }
427: throw new GeneralRuntimeException(
428: "Error creating GenericValue", e);
429: }
430: }
431:
432: /** Returns the index of the previous result, but does not guarantee that there will be a previous result */
433: public int previousIndex() {
434: try {
435: return currentIndex() - 1;
436: } catch (GenericEntityException e) {
437: if (!closed) {
438: try {
439: this .close();
440: } catch (GenericEntityException e1) {
441: Debug
442: .logError(
443: e1,
444: "Error auto-closing EntityListIterator on error, so info below for more info on original error; close error: "
445: + e1.toString(), module);
446: }
447: Debug.logWarning(
448: "Warning: auto-closed EntityListIterator because of exception: "
449: + e.toString(), module);
450: }
451: throw new GeneralRuntimeException(
452: "Error getting the current index", e);
453: }
454: }
455:
456: public void setFetchSize(int rows) throws GenericEntityException {
457: try {
458: resultSet.setFetchSize(rows);
459: } catch (SQLException e) {
460: if (!closed) {
461: this .close();
462: Debug.logWarning(
463: "Warning: auto-closed EntityListIterator because of exception: "
464: + e.toString(), module);
465: }
466: throw new GenericEntityException(
467: "Error getting the next result", e);
468: }
469: }
470:
471: public List getCompleteList() throws GenericEntityException {
472: try {
473: // if the resultSet has been moved forward at all, move back to the beginning
474: if (haveMadeValue && !resultSet.isBeforeFirst()) {
475: // do a quick check to see if the ResultSet is empty
476: resultSet.beforeFirst();
477: }
478: List list = new LinkedList();
479: Object nextValue = null;
480:
481: while ((nextValue = this .next()) != null) {
482: list.add(nextValue);
483: }
484: return list;
485: } catch (SQLException e) {
486: if (!closed) {
487: this .close();
488: Debug.logWarning(
489: "Warning: auto-closed EntityListIterator because of exception: "
490: + e.toString(), module);
491: }
492: throw new GeneralRuntimeException("Error getting results",
493: e);
494: } catch (GeneralRuntimeException e) {
495: if (!closed) {
496: this .close();
497: Debug.logWarning(
498: "Warning: auto-closed EntityListIterator because of exception: "
499: + e.toString(), module);
500: }
501: throw new GenericEntityException(e.getNonNestedMessage(), e
502: .getNested());
503: }
504: }
505:
506: /** Gets a partial list of results starting at start and containing at most number elements.
507: * Start is a one based value, ie 1 is the first element.
508: */
509: public List getPartialList(int start, int number)
510: throws GenericEntityException {
511: try {
512: if (number == 0)
513: return new ArrayList();
514: List list = new ArrayList(number);
515:
516: // if can't reposition to desired index, throw exception
517: if (!resultSet.absolute(start)) {
518: // maybe better to just return an empty list here...
519: return list;
520: //throw new GenericEntityException("Could not move to the start position of " + start + ", there are probably not that many results for this find.");
521: }
522:
523: // get the first as the current one
524: list.add(this .currentGenericValue());
525:
526: Object nextValue = null;
527: // init numRetreived to one since we have already grabbed the initial one
528: int numRetreived = 1;
529:
530: //number > numRetreived comparison goes first to avoid the unwanted call to next
531: while (number > numRetreived
532: && (nextValue = this .next()) != null) {
533: list.add(nextValue);
534: numRetreived++;
535: }
536: return list;
537: } catch (SQLException e) {
538: if (!closed) {
539: this .close();
540: Debug.logWarning(
541: "Warning: auto-closed EntityListIterator because of exception: "
542: + e.toString(), module);
543: }
544: throw new GeneralRuntimeException("Error getting results",
545: e);
546: } catch (GeneralRuntimeException e) {
547: if (!closed) {
548: this .close();
549: Debug.logWarning(
550: "Warning: auto-closed EntityListIterator because of exception: "
551: + e.toString(), module);
552: }
553: throw new GenericEntityException(e.getNonNestedMessage(), e
554: .getNested());
555: }
556: }
557:
558: public void add(Object obj) {
559: throw new GeneralRuntimeException(
560: "CursorListIterator currently only supports read-only access");
561: }
562:
563: public void remove() {
564: throw new GeneralRuntimeException(
565: "CursorListIterator currently only supports read-only access");
566: }
567:
568: public void set(Object obj) {
569: throw new GeneralRuntimeException(
570: "CursorListIterator currently only supports read-only access");
571: }
572:
573: protected void finalize() throws Throwable {
574: try {
575: if (!closed) {
576: this .close();
577: Debug
578: .logError(
579: "====================================================================\n ERROR: EntityListIterator Not Closed for Entity ["
580: + modelEntity == null ? ""
581: : modelEntity.getEntityName()
582: + "], caught in Finalize\n ====================================================================\n",
583: module);
584: }
585: } catch (Exception e) {
586: Debug
587: .logError(
588: e,
589: "Error closing the SQLProcessor in finalize EntityListIterator",
590: module);
591: }
592: super.finalize();
593: }
594: }
|