diff --git a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityListIterator.java b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityListIterator.java index dd7a66207f..ea4e53ae5b 100644 --- a/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityListIterator.java +++ b/framework/entity/src/main/java/org/apache/ofbiz/entity/util/EntityListIterator.java @@ -19,10 +19,9 @@ package org.apache.ofbiz.entity.util; - import java.sql.ResultSet; import java.sql.SQLException; -import java.util.LinkedList; +import java.util.ArrayList; import java.util.List; import java.util.ListIterator; @@ -40,7 +39,6 @@ import org.apache.ofbiz.entity.model.ModelEntity; import org.apache.ofbiz.entity.model.ModelField; import org.apache.ofbiz.entity.model.ModelFieldTypeReader; - /** * Generic Entity Cursor List Iterator for Handling Cursored DB Results */ @@ -69,12 +67,10 @@ public class EntityListIterator implements AutoCloseable, ListIterator selectFields, ModelFieldTypeReader modelFieldTypeReader, GenericDAO genericDAO, EntityCondition whereCondition, EntityCondition havingCondition, boolean distinctQuery) { + public EntityListIterator(SQLProcessor sqlp, ModelEntity modelEntity, List selectFields, ModelFieldTypeReader modelFieldTypeReader, GenericDAO genericDAO, + EntityCondition whereCondition, EntityCondition havingCondition, boolean distinctQuery) { + this(sqlp.getResultSet(), modelEntity, selectFields, modelFieldTypeReader); this.sqlp = sqlp; - this.resultSet = sqlp.getResultSet(); - this.modelEntity = modelEntity; - this.selectFields = selectFields; - this.modelFieldTypeReader = modelFieldTypeReader; this.genericDAO = genericDAO; this.whereCondition = whereCondition; this.havingCondition = havingCondition; @@ -93,82 +89,101 @@ public class EntityListIterator implements AutoCloseable, ListIterator getCompleteList() throws GenericEntityException { try { // if the resultSet has been moved forward at all, move back to the beginning @@ -432,35 +414,39 @@ public class EntityListIterator implements AutoCloseable, ListIterator list = new LinkedList(); - GenericValue nextValue = null; + List list = new ArrayList<>((int) this.getResultSize()); + GenericValue nextValue; while ((nextValue = this.next()) != null) { list.add(nextValue); } return list; } catch (SQLException e) { - if (!closed) { - this.close(); - Debug.logWarning("Warning: auto-closed EntityListIterator because of exception: " + e.toString(), module); - } + closeWithWarning("Warning: auto-closed EntityListIterator because of exception: " + e.toString()); throw new GeneralRuntimeException("Error getting results", e); } catch (GeneralRuntimeException e) { - if (!closed) { - this.close(); - Debug.logWarning("Warning: auto-closed EntityListIterator because of exception: " + e.toString(), module); - } + closeWithWarning("Warning: auto-closed EntityListIterator because of exception: " + e.toString()); throw new GenericEntityException(e.getNonNestedMessage(), e.getNested()); } } - /** Gets a partial list of results starting at start and containing at most number elements. - * Start is a one based value, ie 1 is the first element. + /** + * Gets a partial list of results starting at start and containing at most number elements. + * Start is a one based value, i.e. 1 is the first element. + * + * @param start + * the index from which on the elements should be retrieved. Is one based. + * @param number + * the maximum number of elements to get after the start index. + * @return A list with the retrieved elements, with the size of number or less if the result set does not contain enough values. + * Empty list in case of no values or an invalid start index. + * @throws GenericEntityException + * if there is an issue with the database. */ public List getPartialList(int start, int number) throws GenericEntityException { try { - if (number == 0) return new LinkedList(); - List list = new LinkedList(); + if (number == 0) + return new ArrayList<>(0); // just in case the caller missed the 1 based thingy if (start == 0) start = 1; @@ -468,69 +454,136 @@ public class EntityListIterator implements AutoCloseable, ListIterator(0); } + List list = new ArrayList<>(this.getResultsSizeAfterPartialList()); GenericValue nextValue = null; - - //number > 0 comparison goes first to avoid the unwanted call to next + // number > 0 comparison goes first to avoid the unwanted call to next while (number > 0 && (nextValue = this.next()) != null) { list.add(nextValue); number--; } return list; } catch (GeneralRuntimeException e) { - if (!closed) { - this.close(); - Debug.logWarning("Warning: auto-closed EntityListIterator because of exception: " + e.toString(), module); - } + closeWithWarning("Warning: auto-closed EntityListIterator because of exception: " + e.toString()); throw new GenericEntityException(e.getNonNestedMessage(), e.getNested()); } } + /** + * Determines the possible result size. + * + * If a {@link GenericDAO} is known, the result size will be counted by the + * database. Otherwise the result size is the last index of the + * {@link EntityListIterator}. + * + * @return the result size or 0 if the result set is empty. + * @throws GenericEntityException + * if there is an issue with the call to the database. + */ public int getResultsSizeAfterPartialList() throws GenericEntityException { if (genericDAO != null) { if (resultSize == null) { - EntityFindOptions efo = null; - if (distinctQuery) { - efo = new EntityFindOptions(); - efo.setDistinct(distinctQuery); - } - resultSize = (int) genericDAO.selectCountByCondition(sqlp.getDelegator(), modelEntity, whereCondition, havingCondition, selectFields, efo); + resultSize = (int) getResultSize(); } - return resultSize; - } else if (this.last()) { - return this.currentIndex(); - } else { - // evidently no valid rows in the ResultSet, so return 0 - return 0; + return resultSize.intValue(); } + return this.last() ? this.currentIndex() : 0; } + /** + * Finds the size of the result. + * + * @return count of elements returned by a query. + * @throws GenericEntityException + * if there is an issue with the call to the database. + */ + private long getResultSize() throws GenericEntityException { + EntityFindOptions efo = null; + if (distinctQuery) { + efo = new EntityFindOptions(); + efo.setDistinct(distinctQuery); + } + return genericDAO.selectCountByCondition(sqlp.getDelegator(), modelEntity, whereCondition, + havingCondition, selectFields, efo); + } + + /** + * Unsupported {@link ListIterator#add(Object)} method. + */ public void add(GenericValue obj) { throw new GeneralRuntimeException("CursorListIterator currently only supports read-only access"); } + /** + * Unsupported {@link ListIterator#remove()} method. + */ public void remove() { throw new GeneralRuntimeException("CursorListIterator currently only supports read-only access"); } + /** + * Unsupported {@link ListIterator#set(Object)} method. + */ public void set(GenericValue obj) { throw new GeneralRuntimeException("CursorListIterator currently only supports read-only access"); } + /** + * Extends {@link Object#finalize()} to make sure that the {@link EntityListIterator} is closed when it is garbage collected. + * + * {@inheritDoc} + */ @Override protected void finalize() throws Throwable { try { if (!closed) { this.close(); - Debug.logError("\n==============================================================================\n EntityListIterator Not Closed for Entity [" + (modelEntity==null ? "" : modelEntity.getEntityName()) - + "], caught in Finalize\n Please report by creating an OFBIZ-9297 subtask, thanks\n==============================================================================\n", module); + Debug.logError("\n==============================================================================\n" + + "EntityListIterator Not Closed for Entity [%s], caught in Finalize\n" + + "\n==============================================================================\n", + module, modelEntity == null ? "" : modelEntity.getEntityName()); } } catch (Exception e) { Debug.logError(e, "Error closing the SQLProcessor in finalize EntityListIterator", module); } super.finalize(); } + + /** + * Closes the {@link EntityListIterator} and logs a warning if it isn't already closed. + * + * If you don't want to handle the {@link GenericEntityException} thrown by {@link #close()}, use {@link #tryCloseWithWarning()}. + * + * @param warningMessage + * the warning to be logged. + * @throws GenericEntityException + * when the closing of the {@link EntityListIterator} fails. Thrown by {@link #close()}. + */ + private void closeWithWarning(String warningMessage) throws GenericEntityException { + if (!closed) { + this.close(); + Debug.logWarning(warningMessage, module); + } + } + + /** + * Tries to close the {@link EntityListIterator} and logs a warning if it isn't already closed. + * + * Catches the {@link GenericEntityException} thrown by {@link #close()} and logs it. If you want to handle the exception yourself, use {@link #closeWithWarning()}. + * + * @param warningMessage + * the warning to be logged. + */ + private void tryCloseWithWarning(String warningMessage) { + if (!closed) { + try { + this.close(); + } catch (GenericEntityException e) { + Debug.logError(e, "Error auto-closing EntityListIterator on error, so info below for more info on original error; close error: %s", module, e.toString()); + } + Debug.logWarning(warningMessage, module); + } + } }