Skip to content

Commit d801361

Browse files
authored
Refactor Groovy EntityListIterator usage with auto-closeable handling… (#1167)
Improved : Updated Groovy files to use safer resource management patterns for EntityListIterator (OFBIZ-13399) - Replaced manual iterator close handling with try-with-resources style implementations where applicable - Used Groovy withCloseable for automatic resource cleanup - Replaced EntityListIterator usage with EntityQuery.queryPagedList() where only partial/paged results were required - Removed unnecessary manual close() calls - Reduced risk of JDBC cursor and ResultSet resource leaks - Improved readability and aligned code with modern OFBiz best practices Changes were applied to Groovy files; full regression testing has not yet been completed for all updated flows.
1 parent 2d3874b commit d801361

15 files changed

Lines changed: 220 additions & 257 deletions

File tree

applications/accounting/src/main/groovy/org/apache/ofbiz/accounting/reports/SalesInvoiceByProductCategorySummary.groovy

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -117,16 +117,17 @@ for (int currentDay = 0; currentDay <= daysInMonth; currentDay++) {
117117
productAndExprs.add(EntityCondition.makeCondition('invoiceDate', EntityOperator.GREATER_THAN_EQUAL_TO, currentDayBegin))
118118
productAndExprs.add(EntityCondition.makeCondition('invoiceDate', EntityOperator.LESS_THAN, nextDayBegin))
119119

120-
productResultListIterator = select('productId', 'quantityTotal', 'amountTotal')
121-
.from('InvoiceItemProductSummary').where(productAndExprs).cursorScrollInsensitive().cache(true).queryIterator()
120+
productResultListQuery = select('productId', 'quantityTotal', 'amountTotal')
121+
.from('InvoiceItemProductSummary').where(productAndExprs).cursorScrollInsensitive().cache(true)
122122
productResultMap = [:]
123-
while ((productResult = productResultListIterator.next()) != null) {
124-
productResultMap[productResult.productId] = productResult
125-
monthProductResult = UtilMisc.getMapFromMap(monthProductResultMap, productResult.productId)
126-
UtilMisc.addToBigDecimalInMap(monthProductResult, 'quantityTotal', productResult.getBigDecimal('quantityTotal'))
127-
UtilMisc.addToBigDecimalInMap(monthProductResult, 'amountTotal', productResult.getBigDecimal('amountTotal'))
123+
productResultListQuery.queryIterator().withCloseable { productResultListIterator ->
124+
while ((productResult = productResultListIterator.next()) != null) {
125+
productResultMap[productResult.productId] = productResult
126+
monthProductResult = UtilMisc.getMapFromMap(monthProductResultMap, productResult.productId)
127+
UtilMisc.addToBigDecimalInMap(monthProductResult, 'quantityTotal', productResult.getBigDecimal('quantityTotal'))
128+
UtilMisc.addToBigDecimalInMap(monthProductResult, 'amountTotal', productResult.getBigDecimal('amountTotal'))
129+
}
128130
}
129-
productResultListIterator.close()
130131
productResultMapByDayList.add(productResultMap)
131132

132133
// do the category find
@@ -135,16 +136,17 @@ for (int currentDay = 0; currentDay <= daysInMonth; currentDay++) {
135136
categoryAndExprs.add(EntityCondition.makeCondition('invoiceDate', EntityOperator.GREATER_THAN_EQUAL_TO, currentDayBegin))
136137
categoryAndExprs.add(EntityCondition.makeCondition('invoiceDate', EntityOperator.LESS_THAN, nextDayBegin))
137138

138-
categoryResultListIterator = select('productCategoryId', 'quantityTotal', 'amountTotal')
139-
.from('InvoiceItemCategorySummary').where(categoryAndExprs).cursorScrollInsensitive().cache(true).queryIterator()
139+
categoryResultListQuery = select('productCategoryId', 'quantityTotal', 'amountTotal')
140+
.from('InvoiceItemCategorySummary').where(categoryAndExprs).cursorScrollInsensitive().cache(true)
140141
categoryResultMap = [:]
141-
while ((categoryResult = categoryResultListIterator.next()) != null) {
142-
categoryResultMap[categoryResult.productCategoryId] = categoryResult
143-
monthCategoryResult = UtilMisc.getMapFromMap(monthCategoryResultMap, categoryResult.productCategoryId)
144-
UtilMisc.addToBigDecimalInMap(monthCategoryResult, 'quantityTotal', categoryResult.getBigDecimal('quantityTotal'))
145-
UtilMisc.addToBigDecimalInMap(monthCategoryResult, 'amountTotal', categoryResult.getBigDecimal('amountTotal'))
142+
categoryResultListQuery.queryIterator().with { categoryResultListIterator ->
143+
while ((categoryResult = categoryResultListIterator.next()) != null) {
144+
categoryResultMap[categoryResult.productCategoryId] = categoryResult
145+
monthCategoryResult = UtilMisc.getMapFromMap(monthCategoryResultMap, categoryResult.productCategoryId)
146+
UtilMisc.addToBigDecimalInMap(monthCategoryResult, 'quantityTotal', categoryResult.getBigDecimal('quantityTotal'))
147+
UtilMisc.addToBigDecimalInMap(monthCategoryResult, 'amountTotal', categoryResult.getBigDecimal('amountTotal'))
148+
}
146149
}
147-
categoryResultListIterator.close()
148150
categoryResultMapByDayList.add(categoryResultMap)
149151

150152
// do a find for InvoiceItem with a null productId
@@ -153,11 +155,8 @@ for (int currentDay = 0; currentDay <= daysInMonth; currentDay++) {
153155
productNullAndExprs.add(EntityCondition.makeCondition('productId', EntityOperator.EQUALS, null))
154156
productNullAndExprs.add(EntityCondition.makeCondition('invoiceDate', EntityOperator.GREATER_THAN_EQUAL_TO, currentDayBegin))
155157
productNullAndExprs.add(EntityCondition.makeCondition('invoiceDate', EntityOperator.LESS_THAN, nextDayBegin))
156-
productNullResultListIterator = select('productId', 'quantityTotal', 'amountTotal')
157-
.from('InvoiceItemProductSummary').where(productNullAndExprs).cursorScrollInsensitive().cache(true).queryIterator()
158-
// should just be 1 result
159-
productNullResult = productNullResultListIterator.next()
160-
productNullResultListIterator.close()
158+
productNullResult = select('productId', 'quantityTotal', 'amountTotal')
159+
.from('InvoiceItemProductSummary').where(productNullAndExprs).cursorScrollInsensitive().cache(true).queryFirst()
161160
if (productNullResult) {
162161
productNullResultByDayList.add(productNullResult)
163162
UtilMisc.addToBigDecimalInMap(monthProductNullResult, 'quantityTotal', productNullResult.getBigDecimal('quantityTotal'))

applications/content/src/main/groovy/org/apache/ofbiz/content/content/GetContentLookupList.groovy

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import org.apache.ofbiz.entity.GenericEntity
2626
import org.apache.ofbiz.entity.model.ModelField
2727
import org.apache.ofbiz.entity.model.ModelEntity
2828
import org.apache.ofbiz.entity.model.ModelReader
29+
import org.apache.ofbiz.entity.util.EntityListIterator
2930

3031
viewIndex = parameters.VIEW_INDEX ? Integer.valueOf(parameters.VIEW_INDEX) : 0
3132
viewSize = parameters.VIEW_SIZE ? Integer.valueOf(parameters.VIEW_SIZE) : 20
@@ -68,17 +69,17 @@ context.curFindString = curFindString
6869
context.viewSize = viewSize
6970
context.lowIndex = lowIndex
7071
int arraySize = 0
71-
List resultPartialList
72+
List resultPartialList = []
7273

7374
if ((highIndex - lowIndex + 1) > 0) {
7475
// get the results as an entity list iterator
7576
boolean beganTransaction = false
76-
try {
77+
entityQuery = from('ContentAssocViewTo')
78+
.where('contentIdStart', (String) parameters.get('contentId'))
79+
.orderBy('contentId ASC')
80+
.cursorScrollInsensitive().cache(true)
81+
try (EntityListIterator listIt = entityQuery.queryIterator()) {
7782
beganTransaction = TransactionUtil.begin()
78-
listIt = from('ContentAssocViewTo')
79-
.where('contentIdStart', (String) parameters.get('contentId'))
80-
.orderBy('contentId ASC')
81-
.cursorScrollInsensitive().cache(true).queryIterator()
8283
resultPartialList = listIt.getPartialList(lowIndex, highIndex - lowIndex + 1)
8384

8485
arraySize = listIt.getResultsSizeAfterPartialList()
@@ -96,7 +97,6 @@ if ((highIndex - lowIndex + 1) > 0) {
9697
// after rolling back, rethrow the exception
9798
throw e
9899
} finally {
99-
listIt.close()
100100
// only commit the transaction if we started one... this will throw an exception if it fails
101101
TransactionUtil.commit(beganTransaction)
102102
}

applications/content/src/main/groovy/org/apache/ofbiz/content/survey/EditSurveyQuestions.groovy

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,14 @@ context.lowIndex = lowIndex
4040
int listSize = 0
4141

4242
try {
43-
listIt = from('SurveyQuestionAndAppl')
43+
pagedList = from('SurveyQuestionAndAppl')
4444
.where('surveyId', surveyId)
4545
.orderBy('sequenceNum')
4646
.cursorScrollInsensitive()
4747
.cache(true)
48-
.queryIterator()
49-
surveyQuestionAndApplList = listIt.getPartialList(lowIndex, highIndex - lowIndex + 1)
50-
51-
listSize = listIt.getResultsSizeAfterPartialList()
48+
.queryPagedList(lowIndex, highIndex - lowIndex + 1)
49+
surveyQuestionAndApplList = pagedList.getData()
50+
listSize = pagedList.getSize()
5251
if (listSize < highIndex) {
5352
highIndex = listSize
5453
}
@@ -58,8 +57,6 @@ try {
5857
context.listSize = listSize
5958
} catch (GenericEntityException e) {
6059
logError(e, 'Failure in ' + module)
61-
} finally {
62-
listIt.close()
6360
}
6461
surveyPageList = from('SurveyPage').where('surveyId', surveyId).orderBy('sequenceNum').queryList()
6562
surveyMultiRespList = from('SurveyMultiResp').where('surveyId', surveyId).orderBy('multiRespTitle').queryList()

applications/order/src/main/groovy/org/apache/ofbiz/order/reports/OpenOrderItemsReport.groovy

Lines changed: 56 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -70,14 +70,13 @@ conditions.add(EntityCondition.makeCondition('orderItemStatusId', EntityOperator
7070

7171
// get the results as an entity list iterator
7272
try {
73-
listIt = select('orderId', 'orderDate', 'productId', 'quantityOrdered',
73+
listQuery = select('orderId', 'orderDate', 'productId', 'quantityOrdered',
7474
'quantityIssued', 'quantityOpen', 'shipBeforeDate', 'shipAfterDate', 'itemDescription')
7575
.from('OrderItemQuantityReportGroupByItem')
7676
.where(conditions)
7777
.orderBy('orderDate DESC')
7878
.cursorScrollInsensitive()
7979
.distinct()
80-
.queryIterator()
8180
orderItemList = []
8281
totalCostPrice = 0.0
8382
totalListPrice = 0.0
@@ -87,68 +86,68 @@ try {
8786
totalquantityOrdered = 0.0
8887
totalquantityOpen = 0.0
8988

90-
listIt.each { listValue ->
91-
orderId = listValue.orderId
92-
productId = listValue.productId
93-
orderDate = listValue.orderDate
94-
quantityOrdered = listValue.quantityOrdered
95-
quantityOpen = listValue.quantityOpen
96-
quantityIssued = listValue.quantityIssued
97-
itemDescription = listValue.itemDescription
98-
shipAfterDate = listValue.shipAfterDate
99-
shipBeforeDate = listValue.shipBeforeDate
100-
productIdCondExpr = [EntityCondition.makeCondition('productId', EntityOperator.EQUALS, productId)]
101-
productPrices = select('price', 'productPriceTypeId').from('ProductPrice').where(productIdCondExpr).queryList()
102-
costPrice = 0.0
103-
retailPrice = 0.0
104-
listPrice = 0.0
89+
listQuery.queryIterator().withCloseable { listIt ->
90+
while ((listValue = listIt.next()) != null ) {
91+
orderId = listValue.orderId
92+
productId = listValue.productId
93+
orderDate = listValue.orderDate
94+
quantityOrdered = listValue.quantityOrdered
95+
quantityOpen = listValue.quantityOpen
96+
quantityIssued = listValue.quantityIssued
97+
itemDescription = listValue.itemDescription
98+
shipAfterDate = listValue.shipAfterDate
99+
shipBeforeDate = listValue.shipBeforeDate
100+
productIdCondExpr = [EntityCondition.makeCondition('productId', EntityOperator.EQUALS, productId)]
101+
productPrices = select('price', 'productPriceTypeId').from('ProductPrice').where(productIdCondExpr).queryList()
102+
costPrice = 0.0
103+
retailPrice = 0.0
104+
listPrice = 0.0
105105

106-
productPrices.each { productPriceMap ->
107-
switch (productPriceMap.productPriceTypeId) {
108-
case 'AVERAGE_COST':
109-
costPrice = productPriceMap.price
110-
break
111-
case 'DEFAULT_PRICE':
112-
retailPrice = productPriceMap.price
113-
break
114-
case 'LIST_PRICE':
115-
listPrice = productPriceMap.price
116-
break
106+
productPrices.each { productPriceMap ->
107+
switch (productPriceMap.productPriceTypeId) {
108+
case 'AVERAGE_COST':
109+
costPrice = productPriceMap.price
110+
break
111+
case 'DEFAULT_PRICE':
112+
retailPrice = productPriceMap.price
113+
break
114+
case 'LIST_PRICE':
115+
listPrice = productPriceMap.price
116+
break
117+
}
117118
}
118-
}
119119

120-
totalListPrice += listPrice
121-
totalRetailPrice += retailPrice
122-
totalCostPrice += costPrice
123-
totalquantityOrdered += quantityOrdered
124-
totalquantityOpen += quantityOpen
125-
costPriceDividendValue = costPrice
126-
if (costPriceDividendValue) {
127-
percentMarkup = ((retailPrice - costPrice) / costPrice) * 100
128-
} else {
129-
percentMarkup = ''
120+
totalListPrice += listPrice
121+
totalRetailPrice += retailPrice
122+
totalCostPrice += costPrice
123+
totalquantityOrdered += quantityOrdered
124+
totalquantityOpen += quantityOpen
125+
costPriceDividendValue = costPrice
126+
if (costPriceDividendValue) {
127+
percentMarkup = ((retailPrice - costPrice) / costPrice) * 100
128+
} else {
129+
percentMarkup = ''
130+
}
131+
orderItemMap = [orderDate: orderDate,
132+
orderId: orderId,
133+
productId: productId,
134+
itemDescription: itemDescription,
135+
quantityOrdered: quantityOrdered,
136+
quantityIssued: quantityIssued,
137+
quantityOpen: quantityOpen,
138+
shipAfterDate: shipAfterDate,
139+
shipBeforeDate: shipBeforeDate,
140+
costPrice: costPrice,
141+
retailPrice: retailPrice,
142+
listPrice: listPrice,
143+
discount: listPrice - retailPrice,
144+
calculatedMarkup: retailPrice - costPrice,
145+
percentMarkup: percentMarkup]
146+
orderItemList.add(orderItemMap)
130147
}
131-
orderItemMap = [orderDate: orderDate,
132-
orderId: orderId,
133-
productId: productId,
134-
itemDescription: itemDescription,
135-
quantityOrdered: quantityOrdered,
136-
quantityIssued: quantityIssued,
137-
quantityOpen: quantityOpen,
138-
shipAfterDate: shipAfterDate,
139-
shipBeforeDate: shipBeforeDate,
140-
costPrice: costPrice,
141-
retailPrice: retailPrice,
142-
listPrice: listPrice,
143-
discount: listPrice - retailPrice,
144-
calculatedMarkup: retailPrice - costPrice,
145-
percentMarkup: percentMarkup]
146-
orderItemList.add(orderItemMap)
147148
}
148149
} catch (GenericEntityException e) {
149150
logError(e, 'Failure in ' + module)
150-
} finally {
151-
listIt.close()
152151
}
153152

154153
totalAmountList = []

applications/party/src/main/groovy/org/apache/ofbiz/party/party/PartyFinancialHistory.groovy

Lines changed: 34 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
package org.apache.ofbiz.party.party
2020

2121
import java.math.RoundingMode
22-
2322
import org.apache.ofbiz.accounting.invoice.InvoiceWorker
2423
import org.apache.ofbiz.accounting.payment.PaymentWorker
2524
import org.apache.ofbiz.entity.condition.EntityCondition
@@ -54,30 +53,28 @@ invExprs =
5453
], EntityOperator.OR)
5554
], EntityOperator.AND)
5655

57-
invIterator = from('InvoiceAndType').where(invExprs).cursorScrollInsensitive().distinct().queryIterator()
58-
59-
/* codenarc-disable */
60-
while (invoice = invIterator.next()) {
61-
/* codenarc-enable */
62-
Boolean isPurchaseInvoice = EntityTypeUtil.hasParentType(delegator, 'InvoiceType', 'invoiceTypeId',
63-
invoice.getString('invoiceTypeId'), 'parentTypeId', 'PURCHASE_INVOICE')
64-
Boolean isSalesInvoice = EntityTypeUtil.hasParentType(delegator, 'InvoiceType', 'invoiceTypeId', (String) invoice.getString('invoiceTypeId'),
65-
'parentTypeId', 'SALES_INVOICE')
66-
if (isPurchaseInvoice) {
67-
totalInvPuApplied += InvoiceWorker.getInvoiceApplied(invoice, actualCurrency).setScale(2, RoundingMode.HALF_UP)
68-
totalInvPuNotApplied += InvoiceWorker.getInvoiceNotApplied(invoice, actualCurrency).setScale(2, RoundingMode.HALF_UP)
69-
}
70-
else if (isSalesInvoice) {
71-
totalInvSaApplied += InvoiceWorker.getInvoiceApplied(invoice, actualCurrency).setScale(2, RoundingMode.HALF_UP)
72-
totalInvSaNotApplied += InvoiceWorker.getInvoiceNotApplied(invoice, actualCurrency).setScale(2, RoundingMode.HALF_UP)
73-
}
74-
else {
75-
logError('InvoiceType: ' + invoice.invoiceTypeId + ' without a valid parentTypeId: ' + invoice.parentTypeId
76-
+ ' !!!! Should be either PURCHASE_INVOICE or SALES_INVOICE')
56+
invQuery = from('InvoiceAndType').where(invExprs).cursorScrollInsensitive().distinct()
57+
invQuery.queryIterator().withCloseable { invIterator ->
58+
/* codenarc-disable */
59+
while (invoice = invIterator.next()) {
60+
/* codenarc-enable */
61+
Boolean isPurchaseInvoice = EntityTypeUtil.hasParentType(delegator, 'InvoiceType', 'invoiceTypeId',
62+
invoice.getString('invoiceTypeId'), 'parentTypeId', 'PURCHASE_INVOICE')
63+
Boolean isSalesInvoice = EntityTypeUtil.hasParentType(delegator, 'InvoiceType',
64+
'invoiceTypeId', (String) invoice.getString('invoiceTypeId'),
65+
'parentTypeId', 'SALES_INVOICE')
66+
if (isPurchaseInvoice) {
67+
totalInvPuApplied += InvoiceWorker.getInvoiceApplied(invoice, actualCurrency).setScale(2, RoundingMode.HALF_UP)
68+
totalInvPuNotApplied += InvoiceWorker.getInvoiceNotApplied(invoice, actualCurrency).setScale(2, RoundingMode.HALF_UP)
69+
} else if (isSalesInvoice) {
70+
totalInvSaApplied += InvoiceWorker.getInvoiceApplied(invoice, actualCurrency).setScale(2, RoundingMode.HALF_UP)
71+
totalInvSaNotApplied += InvoiceWorker.getInvoiceNotApplied(invoice, actualCurrency).setScale(2, RoundingMode.HALF_UP)
72+
} else {
73+
logError('InvoiceType: ' + invoice.invoiceTypeId + ' without a valid parentTypeId: ' + invoice.parentTypeId
74+
+ ' !!!! Should be either PURCHASE_INVOICE or SALES_INVOICE')
75+
}
76+
}
7777
}
78-
}
79-
80-
invIterator.close()
8178

8279
//get total/unapplied/applied payment in/out total amount:
8380
totalPayInApplied = BigDecimal.ZERO
@@ -101,25 +98,23 @@ payExprs =
10198
], EntityOperator.OR)
10299
], EntityOperator.AND)
103100

104-
payIterator = from('PaymentAndType').where(payExprs).cursorScrollInsensitive().distinct().queryIterator()
105-
101+
payQuery = from('PaymentAndType').where(payExprs).cursorScrollInsensitive().distinct()
102+
payQuery.queryIterator().withCloseable { payIterator ->
106103
/* codenarc-disable */
107-
while (payment = payIterator.next()) {
104+
while (payment = payIterator.next()) {
108105
/* codenarc-enable */
109-
if (payment.parentTypeId == 'DISBURSEMENT' || payment.parentTypeId == 'TAX_PAYMENT') {
110-
totalPayOutApplied += PaymentWorker.getPaymentApplied(payment, actualCurrency).setScale(2, RoundingMode.HALF_UP)
111-
totalPayOutNotApplied += PaymentWorker.getPaymentNotApplied(payment, actualCurrency).setScale(2, RoundingMode.HALF_UP)
112-
}
113-
else if (payment.parentTypeId == 'RECEIPT') {
114-
totalPayInApplied += PaymentWorker.getPaymentApplied(payment, actualCurrency).setScale(2, RoundingMode.HALF_UP)
115-
totalPayInNotApplied += PaymentWorker.getPaymentNotApplied(payment, actualCurrency).setScale(2, RoundingMode.HALF_UP)
116-
}
117-
else {
118-
logError('PaymentTypeId: ' + payment.paymentTypeId + ' without a valid parentTypeId: ' + payment.parentTypeId
119-
+ ' !!!! Should be either DISBURSEMENT, TAX_PAYMENT or RECEIPT')
106+
if (payment.parentTypeId == 'DISBURSEMENT' || payment.parentTypeId == 'TAX_PAYMENT') {
107+
totalPayOutApplied += PaymentWorker.getPaymentApplied(payment, actualCurrency).setScale(2, RoundingMode.HALF_UP)
108+
totalPayOutNotApplied += PaymentWorker.getPaymentNotApplied(payment, actualCurrency).setScale(2, RoundingMode.HALF_UP)
109+
} else if (payment.parentTypeId == 'RECEIPT') {
110+
totalPayInApplied += PaymentWorker.getPaymentApplied(payment, actualCurrency).setScale(2, RoundingMode.HALF_UP)
111+
totalPayInNotApplied += PaymentWorker.getPaymentNotApplied(payment, actualCurrency).setScale(2, RoundingMode.HALF_UP)
112+
} else {
113+
logError('PaymentTypeId: ' + payment.paymentTypeId + ' without a valid parentTypeId: ' + payment.parentTypeId
114+
+ ' !!!! Should be either DISBURSEMENT, TAX_PAYMENT or RECEIPT')
115+
}
120116
}
121117
}
122-
payIterator.close()
123118

124119
context.finanSummary = [:]
125120
context.finanSummary.totalSalesInvoice = totalSalesInvoice = totalInvSaApplied.add(totalInvSaNotApplied)

0 commit comments

Comments
 (0)