Fixes issue 23841: Fixed duplicated close, close are done in finally blocks
authorAugusto Mauch <augusto.mauch@openbravo.com>
Thu, 30 May 2013 11:45:18 +0200
changeset 20495 8a7979c5a247
parent 20494 c7f57f178baf
child 20496 ff813ef90a4e
Fixes issue 23841: Fixed duplicated close, close are done in finally blocks
modules/org.openbravo.client.application/src/org/openbravo/client/application/event/AcctSchemaEventHandler.java
modules/org.openbravo.service.json/src/org/openbravo/service/json/DefaultJsonDataService.java
modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/CustomQuerySelectorDatasource.java
src/org/openbravo/costing/CostingMigrationProcess.java
src/org/openbravo/costing/CostingRuleProcess.java
src/org/openbravo/erpCommon/ad_actionButton/MRPManufacturingPlanProcess.java
src/org/openbravo/erpCommon/ad_process/MRPPurchaseCreateReservations.java
src/org/openbravo/erpCommon/utility/WindowTree.java
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/event/AcctSchemaEventHandler.java	Thu May 30 10:08:15 2013 +0530
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/event/AcctSchemaEventHandler.java	Thu May 30 11:45:18 2013 +0200
@@ -153,23 +153,26 @@
     elementValueQry.setFetchSize(1000);
 
     ScrollableResults elementvalues = elementValueQry.scroll(ScrollMode.FORWARD_ONLY);
-    // TODO: Review with Martin to see if flush is permitted in handlers
-    // int i = 0;
-    while (elementvalues.next()) {
-      ElementValue elementValue = (ElementValue) elementvalues.get(0);
-      boolean isCredit = getAccountSign(elementValue.getAccountType(), assetPositive,
-          liabilityPositive, ownersEquityPositive, expensePositive, revenuePositive);
-      if (!ACCOUNTTYPE_MEMO.equals(elementValue.getAccountType())) {
-        elementValue.setAccountSign(isCredit ? ACCOUNTSIGN_CREDIT : ACCOUNTSIGN_DEBIT);
+    try {
+      // TODO: Review with Martin to see if flush is permitted in handlers
+      // int i = 0;
+      while (elementvalues.next()) {
+        ElementValue elementValue = (ElementValue) elementvalues.get(0);
+        boolean isCredit = getAccountSign(elementValue.getAccountType(), assetPositive,
+            liabilityPositive, ownersEquityPositive, expensePositive, revenuePositive);
+        if (!ACCOUNTTYPE_MEMO.equals(elementValue.getAccountType())) {
+          elementValue.setAccountSign(isCredit ? ACCOUNTSIGN_CREDIT : ACCOUNTSIGN_DEBIT);
+        }
+        // if ((i % 100) == 0) {
+        // OBDal.getInstance().flush();
+        // OBDal.getInstance().getSession().clear();
+        // element = OBDal.getInstance().get(Element.class, element.getId());
+        // }
+        // i++;
       }
-      // if ((i % 100) == 0) {
-      // OBDal.getInstance().flush();
-      // OBDal.getInstance().getSession().clear();
-      // element = OBDal.getInstance().get(Element.class, element.getId());
-      // }
-      // i++;
+    } finally {
+      elementvalues.close();
     }
-    elementvalues.close();
   }
 
   private boolean getAccountSign(String accountType, boolean assetPositive,
--- a/modules/org.openbravo.service.json/src/org/openbravo/service/json/DefaultJsonDataService.java	Thu May 30 10:08:15 2013 +0530
+++ b/modules/org.openbravo.service.json/src/org/openbravo/service/json/DefaultJsonDataService.java	Thu May 30 11:45:18 2013 +0200
@@ -313,28 +313,31 @@
     toJsonConverter.setAdditionalProperties(JsonUtils.getAdditionalProperties(parameters));
 
     final ScrollableResults scrollableResults = queryService.scroll();
-    int i = 0;
-    while (scrollableResults.next()) {
-      final Object result = scrollableResults.get()[0];
-      final JSONObject json = toJsonConverter.toJsonObject((BaseOBObject) result,
-          DataResolvingMode.FULL);
+    try {
+      int i = 0;
+      while (scrollableResults.next()) {
+        final Object result = scrollableResults.get()[0];
+        final JSONObject json = toJsonConverter.toJsonObject((BaseOBObject) result,
+            DataResolvingMode.FULL);
 
-      try {
-        doPostFetch(parameters, json);
-      } catch (JSONException e) {
-        throw new OBException(e);
+        try {
+          doPostFetch(parameters, json);
+        } catch (JSONException e) {
+          throw new OBException(e);
+        }
+
+        writer.write(json);
+
+        i++;
+        // Clear session every 1000 records to prevent huge memory consumption in case of big loops
+        if (i % 1000 == 0) {
+          OBDal.getInstance().getSession().clear();
+          log.debug("clearing in record " + i + " elapsed time " + (System.currentTimeMillis() - t));
+        }
       }
-
-      writer.write(json);
-
-      i++;
-      // Clear session every 1000 records to prevent huge memory consumption in case of big loops
-      if (i % 1000 == 0) {
-        OBDal.getInstance().getSession().clear();
-        log.debug("clearing in record " + i + " elapsed time " + (System.currentTimeMillis() - t));
-      }
+    } finally {
+      scrollableResults.close();
     }
-    scrollableResults.close();
     log.debug("Fetch took " + (System.currentTimeMillis() - t) + " ms");
   }
 
--- a/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/CustomQuerySelectorDatasource.java	Thu May 30 10:08:15 2013 +0530
+++ b/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/CustomQuerySelectorDatasource.java	Thu May 30 11:45:18 2013 +0200
@@ -103,13 +103,16 @@
         // Defaulted to endRow + 2 to check for more records while scrolling.
         totalRows = endRow + 2;
         ScrollableResults queryResults = selQuery.scroll(ScrollMode.FORWARD_ONLY);
-        while (queryResults.next()) {
-          queryListSize++;
-          if (queryListSize % clearEachLoop == 0) {
-            OBDal.getInstance().getSession().clear();
+        try {
+          while (queryResults.next()) {
+            queryListSize++;
+            if (queryListSize % clearEachLoop == 0) {
+              OBDal.getInstance().getSession().clear();
+            }
           }
+        } finally {
+          queryResults.close();
         }
-        queryResults.close();
         if (startRow < endRow) {
           if (queryListSize < endRow) {
             totalRows = queryListSize;
--- a/src/org/openbravo/costing/CostingMigrationProcess.java	Thu May 30 10:08:15 2013 +0530
+++ b/src/org/openbravo/costing/CostingMigrationProcess.java	Thu May 30 11:45:18 2013 +0200
@@ -278,17 +278,20 @@
         Set<String> naturalTree = osp.getNaturalTree(legalEntity.getId());
         ScrollableResults legacyCosts = getLegacyCostScroll(clientId, naturalTree);
         int i = 0;
-        while (legacyCosts.next()) {
-          Costing cost = (Costing) legacyCosts.get(0);
+        try {
+          while (legacyCosts.next()) {
+            Costing cost = (Costing) legacyCosts.get(0);
 
-          updateTrxLegacyCosts(cost, stdPrecission, naturalTree);
+            updateTrxLegacyCosts(cost, stdPrecission, naturalTree);
 
-          if ((i % 100) == 0) {
-            OBDal.getInstance().flush();
-            OBDal.getInstance().getSession().clear();
+            if ((i % 100) == 0) {
+              OBDal.getInstance().flush();
+              OBDal.getInstance().getSession().clear();
+            }
           }
+        } finally {
+          legacyCosts.close();
         }
-        legacyCosts.close();
         SessionHandler.getInstance().commitAndStart();
       }
     }
@@ -313,17 +316,20 @@
 
     final ScrollableResults costs = costQry.scroll(ScrollMode.FORWARD_ONLY);
     int i = 0;
-    while (costs.next()) {
-      Costing cost = (Costing) costs.get(0);
-      cost.setCurrency(cost.getClient().getCurrency());
-      OBDal.getInstance().save(cost);
-      if ((i % 100) == 0) {
-        OBDal.getInstance().flush();
-        OBDal.getInstance().getSession().clear();
+    try {
+      while (costs.next()) {
+        Costing cost = (Costing) costs.get(0);
+        cost.setCurrency(cost.getClient().getCurrency());
+        OBDal.getInstance().save(cost);
+        if ((i % 100) == 0) {
+          OBDal.getInstance().flush();
+          OBDal.getInstance().getSession().clear();
+        }
+        i++;
       }
-      i++;
+    } finally {
+      costs.close();
     }
-    costs.close();
   }
 
   private void createRules() throws Exception {
@@ -378,57 +384,60 @@
     BigDecimal totalCost = BigDecimal.ZERO;
     BigDecimal totalStock = BigDecimal.ZERO;
     int i = 0;
-    while (icls.next()) {
-      InventoryCountLine icl = (InventoryCountLine) icls.get(0);
-      if (!productId.equals(icl.getProduct().getId())) {
-        productId = icl.getProduct().getId();
-        HashMap<String, BigDecimal> stock = getCurrentValuedStock(productId, curId, orgs, orgId);
-        totalCost = stock.get("cost");
-        totalStock = stock.get("stock");
+    try {
+      while (icls.next()) {
+        InventoryCountLine icl = (InventoryCountLine) icls.get(0);
+        if (!productId.equals(icl.getProduct().getId())) {
+          productId = icl.getProduct().getId();
+          HashMap<String, BigDecimal> stock = getCurrentValuedStock(productId, curId, orgs, orgId);
+          totalCost = stock.get("cost");
+          totalStock = stock.get("stock");
+        }
+
+        MaterialTransaction trx = crp.getInventoryLineTransaction(icl);
+        trx.setTransactionProcessDate(DateUtils.addSeconds(trx.getTransactionProcessDate(), -1));
+        trx.setCurrency(OBDal.getInstance().get(Currency.class, curId));
+
+        BigDecimal trxCost = BigDecimal.ZERO;
+        if (totalStock.compareTo(BigDecimal.ZERO) != 0) {
+          trxCost = totalCost.multiply(trx.getMovementQuantity().abs()).divide(totalStock,
+              stdPrecision, BigDecimal.ROUND_HALF_UP);
+        }
+        if (trx.getMovementQuantity().compareTo(totalStock) == 0) {
+          // Last transaction adjusts remaining cost amount.
+          trxCost = totalCost;
+        }
+        trx.setTransactionCost(trxCost);
+        trx.setCostCalculated(true);
+        trx.setCostingStatus("CC");
+        OBDal.getInstance().save(trx);
+        Currency legalEntityCur = FinancialUtils.getLegalEntityCurrency(trx.getOrganization());
+        BigDecimal cost = trxCost.divide(trx.getMovementQuantity().abs(), costPrecision,
+            BigDecimal.ROUND_HALF_UP);
+        if (!legalEntityCur.equals(cur)) {
+          cost = FinancialUtils.getConvertedAmount(cost, cur, legalEntityCur, new Date(),
+              icl.getOrganization(), FinancialUtils.PRECISION_COSTING);
+        }
+        OBDal.getInstance().refresh(icl.getPhysInventory());
+        CostingRuleInit cri = icl.getPhysInventory().getCostingRuleInitCloseInventoryList().get(0);
+        InventoryCountLine initICL = crp.getInitIcl(cri.getInitInventory(), icl);
+        initICL.setCost(cost);
+        OBDal.getInstance().save(initICL);
+
+        totalCost = totalCost.subtract(trxCost);
+        // MovementQty is already negative so add to totalStock to decrease it.
+        totalStock = totalStock.add(trx.getMovementQuantity());
+
+        if ((i % 100) == 0) {
+          OBDal.getInstance().flush();
+          OBDal.getInstance().getSession().clear();
+          cur = OBDal.getInstance().get(Currency.class, curId);
+        }
+        i++;
       }
-
-      MaterialTransaction trx = crp.getInventoryLineTransaction(icl);
-      trx.setTransactionProcessDate(DateUtils.addSeconds(trx.getTransactionProcessDate(), -1));
-      trx.setCurrency(OBDal.getInstance().get(Currency.class, curId));
-
-      BigDecimal trxCost = BigDecimal.ZERO;
-      if (totalStock.compareTo(BigDecimal.ZERO) != 0) {
-        trxCost = totalCost.multiply(trx.getMovementQuantity().abs()).divide(totalStock,
-            stdPrecision, BigDecimal.ROUND_HALF_UP);
-      }
-      if (trx.getMovementQuantity().compareTo(totalStock) == 0) {
-        // Last transaction adjusts remaining cost amount.
-        trxCost = totalCost;
-      }
-      trx.setTransactionCost(trxCost);
-      trx.setCostCalculated(true);
-      trx.setCostingStatus("CC");
-      OBDal.getInstance().save(trx);
-      Currency legalEntityCur = FinancialUtils.getLegalEntityCurrency(trx.getOrganization());
-      BigDecimal cost = trxCost.divide(trx.getMovementQuantity().abs(), costPrecision,
-          BigDecimal.ROUND_HALF_UP);
-      if (!legalEntityCur.equals(cur)) {
-        cost = FinancialUtils.getConvertedAmount(cost, cur, legalEntityCur, new Date(),
-            icl.getOrganization(), FinancialUtils.PRECISION_COSTING);
-      }
-      OBDal.getInstance().refresh(icl.getPhysInventory());
-      CostingRuleInit cri = icl.getPhysInventory().getCostingRuleInitCloseInventoryList().get(0);
-      InventoryCountLine initICL = crp.getInitIcl(cri.getInitInventory(), icl);
-      initICL.setCost(cost);
-      OBDal.getInstance().save(initICL);
-
-      totalCost = totalCost.subtract(trxCost);
-      // MovementQty is already negative so add to totalStock to decrease it.
-      totalStock = totalStock.add(trx.getMovementQuantity());
-
-      if ((i % 100) == 0) {
-        OBDal.getInstance().flush();
-        OBDal.getInstance().getSession().clear();
-        cur = OBDal.getInstance().get(Currency.class, curId);
-      }
-      i++;
+    } finally {
+      icls.close();
     }
-    icls.close();
 
     OBDal.getInstance().flush();
     insertTrxCosts();
@@ -579,40 +588,43 @@
 
     ScrollableResults trxs = trxQry.scroll(ScrollMode.FORWARD_ONLY);
     int i = 0;
-    while (trxs.next()) {
-      MaterialTransaction trx = (MaterialTransaction) trxs.get(0);
-      log4j.debug("********** UpdateTrxLegacyCosts process trx:" + trx.getIdentifier());
+    try {
+      while (trxs.next()) {
+        MaterialTransaction trx = (MaterialTransaction) trxs.get(0);
+        log4j.debug("********** UpdateTrxLegacyCosts process trx:" + trx.getIdentifier());
 
-      if (trx.getGoodsShipmentLine() != null
-          && trx.getGoodsShipmentLine().getShipmentReceipt().getAccountingDate()
-              .compareTo(trx.getMovementDate()) != 0) {
-        // Shipments with accounting date different than the movement date gets the cost valid on
-        // the accounting date.
-        BigDecimal unitCost = new BigDecimal(new ProductInfo(cost.getProduct().getId(),
-            new DalConnectionProvider(false)).getProductItemCost(OBDateUtils.formatDate(trx
-            .getGoodsShipmentLine().getShipmentReceipt().getAccountingDate()), null, "AV",
-            new DalConnectionProvider(false), OBDal.getInstance().getConnection()));
-        BigDecimal trxCost = unitCost.multiply(trx.getMovementQuantity().abs()).setScale(
-            standardPrecision, BigDecimal.ROUND_HALF_UP);
+        if (trx.getGoodsShipmentLine() != null
+            && trx.getGoodsShipmentLine().getShipmentReceipt().getAccountingDate()
+                .compareTo(trx.getMovementDate()) != 0) {
+          // Shipments with accounting date different than the movement date gets the cost valid on
+          // the accounting date.
+          BigDecimal unitCost = new BigDecimal(new ProductInfo(cost.getProduct().getId(),
+              new DalConnectionProvider(false)).getProductItemCost(OBDateUtils.formatDate(trx
+              .getGoodsShipmentLine().getShipmentReceipt().getAccountingDate()), null, "AV",
+              new DalConnectionProvider(false), OBDal.getInstance().getConnection()));
+          BigDecimal trxCost = unitCost.multiply(trx.getMovementQuantity().abs()).setScale(
+              standardPrecision, BigDecimal.ROUND_HALF_UP);
 
-        trx.setTransactionCost(trxCost);
-      } else {
-        trx.setTransactionCost(cost.getCost().multiply(trx.getMovementQuantity().abs())
-            .setScale(standardPrecision, BigDecimal.ROUND_HALF_UP));
+          trx.setTransactionCost(trxCost);
+        } else {
+          trx.setTransactionCost(cost.getCost().multiply(trx.getMovementQuantity().abs())
+              .setScale(standardPrecision, BigDecimal.ROUND_HALF_UP));
+        }
+
+        trx.setCurrency(cost.getCurrency());
+        trx.setCostCalculated(true);
+        trx.setCostingStatus("CC");
+
+        if ((i % 100) == 0) {
+          OBDal.getInstance().flush();
+          OBDal.getInstance().getSession().clear();
+          cost = OBDal.getInstance().get(Costing.class, cost.getId());
+        }
+        i++;
       }
-
-      trx.setCurrency(cost.getCurrency());
-      trx.setCostCalculated(true);
-      trx.setCostingStatus("CC");
-
-      if ((i % 100) == 0) {
-        OBDal.getInstance().flush();
-        OBDal.getInstance().getSession().clear();
-        cost = OBDal.getInstance().get(Costing.class, cost.getId());
-      }
-      i++;
+    } finally {
+      trxs.close();
     }
-    trxs.close();
 
     log4j.debug("****** UpdateTrxLegacyCosts updated:" + i);
   }
@@ -638,26 +650,29 @@
     int i = 0;
     String orgId = "";
     String curId = "";
-    while (trxs.next()) {
-      MaterialTransaction trx = (MaterialTransaction) trxs.get(0);
-      if (!orgId.equals((String) DalUtil.getId(trx.getOrganization()))) {
-        orgId = (String) DalUtil.getId(trx.getOrganization());
-        Currency cur = FinancialUtils.getLegalEntityCurrency(trx.getOrganization());
-        curId = cur.getId();
+    try {
+      while (trxs.next()) {
+        MaterialTransaction trx = (MaterialTransaction) trxs.get(0);
+        if (!orgId.equals((String) DalUtil.getId(trx.getOrganization()))) {
+          orgId = (String) DalUtil.getId(trx.getOrganization());
+          Currency cur = FinancialUtils.getLegalEntityCurrency(trx.getOrganization());
+          curId = cur.getId();
+        }
+        trx.setTransactionCost(BigDecimal.ZERO);
+        trx.setCurrency((Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, curId));
+        trx.setCostCalculated(true);
+        trx.setCostingStatus("CC");
+        OBDal.getInstance().save(trx);
+
+        if ((i % 100) == 0) {
+          OBDal.getInstance().flush();
+          OBDal.getInstance().getSession().clear();
+        }
+        i++;
       }
-      trx.setTransactionCost(BigDecimal.ZERO);
-      trx.setCurrency((Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, curId));
-      trx.setCostCalculated(true);
-      trx.setCostingStatus("CC");
-      OBDal.getInstance().save(trx);
-
-      if ((i % 100) == 0) {
-        OBDal.getInstance().flush();
-        OBDal.getInstance().getSession().clear();
-      }
-      i++;
+    } finally {
+      trxs.close();
     }
-    trxs.close();
     log4j.debug("****** updateWithCeroRemainingTrx updated:" + i);
   }
 
--- a/src/org/openbravo/costing/CostingRuleProcess.java	Thu May 30 10:08:15 2013 +0530
+++ b/src/org/openbravo/costing/CostingRuleProcess.java	Thu May 30 11:45:18 2013 +0200
@@ -241,33 +241,36 @@
     trxQry.setFetchSize(1000);
     ScrollableResults trxs = trxQry.scroll(ScrollMode.FORWARD_ONLY);
     int i = 1;
-    while (trxs.next()) {
-      MaterialTransaction trx = (MaterialTransaction) trxs.get(0);
+    try {
+      while (trxs.next()) {
+        MaterialTransaction trx = (MaterialTransaction) trxs.get(0);
 
-      TransactionCost transactionCost = OBProvider.getInstance().get(TransactionCost.class);
-      transactionCost.setInventoryTransaction(trx);
-      transactionCost.setCostDate(trx.getTransactionProcessDate());
-      transactionCost.setClient(trx.getClient());
-      transactionCost.setOrganization(trx.getOrganization());
-      transactionCost.setCost(BigDecimal.ZERO);
-      transactionCost.setCurrency(trx.getClient().getCurrency());
-      List<TransactionCost> trxCosts = trx.getTransactionCostList();
-      trxCosts.add(transactionCost);
-      trx.setTransactionCostList(trxCosts);
+        TransactionCost transactionCost = OBProvider.getInstance().get(TransactionCost.class);
+        transactionCost.setInventoryTransaction(trx);
+        transactionCost.setCostDate(trx.getTransactionProcessDate());
+        transactionCost.setClient(trx.getClient());
+        transactionCost.setOrganization(trx.getOrganization());
+        transactionCost.setCost(BigDecimal.ZERO);
+        transactionCost.setCurrency(trx.getClient().getCurrency());
+        List<TransactionCost> trxCosts = trx.getTransactionCostList();
+        trxCosts.add(transactionCost);
+        trx.setTransactionCostList(trxCosts);
 
-      trx.setCostCalculated(true);
-      trx.setCostingStatus("CC");
-      trx.setTransactionCost(BigDecimal.ZERO);
-      trx.setCurrency(trx.getClient().getCurrency());
-      OBDal.getInstance().save(trx);
+        trx.setCostCalculated(true);
+        trx.setCostingStatus("CC");
+        trx.setTransactionCost(BigDecimal.ZERO);
+        trx.setCurrency(trx.getClient().getCurrency());
+        OBDal.getInstance().save(trx);
 
-      if ((i % 100) == 0) {
-        OBDal.getInstance().flush();
-        OBDal.getInstance().getSession().clear();
+        if ((i % 100) == 0) {
+          OBDal.getInstance().flush();
+          OBDal.getInstance().getSession().clear();
+        }
+        i++;
       }
-      i++;
+    } finally {
+      trxs.close();
     }
-    trxs.close();
   }
 
   @Deprecated
@@ -282,43 +285,46 @@
     Map<String, String> initLines = new HashMap<String, String>();
     Map<String, Long> maxLineNumbers = new HashMap<String, Long>();
     int i = 1;
-    while (stockLines.next()) {
-      Object[] stockLine = stockLines.get();
-      String productId = (String) stockLine[0];
-      String attrSetInsId = (String) stockLine[1];
-      String uomId = (String) stockLine[2];
-      String orderUOMId = (String) stockLine[3];
-      String locatorId = (String) stockLine[4];
-      String warehouseId = (String) stockLine[5];
-      BigDecimal qty = (BigDecimal) stockLine[6];
-      BigDecimal orderQty = (BigDecimal) stockLine[7];
+    try {
+      while (stockLines.next()) {
+        Object[] stockLine = stockLines.get();
+        String productId = (String) stockLine[0];
+        String attrSetInsId = (String) stockLine[1];
+        String uomId = (String) stockLine[2];
+        String orderUOMId = (String) stockLine[3];
+        String locatorId = (String) stockLine[4];
+        String warehouseId = (String) stockLine[5];
+        BigDecimal qty = (BigDecimal) stockLine[6];
+        BigDecimal orderQty = (BigDecimal) stockLine[7];
 
-      String criId = initLines.get(warehouseId);
-      CostingRuleInit cri = null;
-      if (criId == null) {
-        cri = createCostingRuleInitLine(rule, warehouseId, date);
+        String criId = initLines.get(warehouseId);
+        CostingRuleInit cri = null;
+        if (criId == null) {
+          cri = createCostingRuleInitLine(rule, warehouseId, date);
 
-        initLines.put(warehouseId, cri.getId());
-      } else {
-        cri = OBDal.getInstance().get(CostingRuleInit.class, criId);
+          initLines.put(warehouseId, cri.getId());
+        } else {
+          cri = OBDal.getInstance().get(CostingRuleInit.class, criId);
+        }
+        Long lineNo = (maxLineNumbers.get(criId) == null ? 0L : maxLineNumbers.get(criId)) + 10L;
+        maxLineNumbers.put(criId, lineNo);
+
+        insertInventoryLine(cri.getCloseInventory(), productId, attrSetInsId, uomId, orderUOMId,
+            locatorId, BigDecimal.ZERO, qty, BigDecimal.ZERO, orderQty, lineNo);
+        insertInventoryLine(cri.getInitInventory(), productId, attrSetInsId, uomId, orderUOMId,
+            locatorId, qty, BigDecimal.ZERO, orderQty, BigDecimal.ZERO, lineNo);
+
+        if ((i % 100) == 0) {
+          OBDal.getInstance().flush();
+          OBDal.getInstance().getSession().clear();
+          // Reload rule after clear session.
+          rule = OBDal.getInstance().get(CostingRule.class, ruleId);
+        }
+        i++;
       }
-      Long lineNo = (maxLineNumbers.get(criId) == null ? 0L : maxLineNumbers.get(criId)) + 10L;
-      maxLineNumbers.put(criId, lineNo);
-
-      insertInventoryLine(cri.getCloseInventory(), productId, attrSetInsId, uomId, orderUOMId,
-          locatorId, BigDecimal.ZERO, qty, BigDecimal.ZERO, orderQty, lineNo);
-      insertInventoryLine(cri.getInitInventory(), productId, attrSetInsId, uomId, orderUOMId,
-          locatorId, qty, BigDecimal.ZERO, orderQty, BigDecimal.ZERO, lineNo);
-
-      if ((i % 100) == 0) {
-        OBDal.getInstance().flush();
-        OBDal.getInstance().getSession().clear();
-        // Reload rule after clear session.
-        rule = OBDal.getInstance().get(CostingRule.class, ruleId);
-      }
-      i++;
+    } finally {
+      stockLines.close();
     }
-    stockLines.close();
     // Process closing physical inventories.
     for (CostingRuleInit cri : rule.getCostingRuleInitList()) {
       new InventoryCountProcess().processInventory(cri.getCloseInventory());
--- a/src/org/openbravo/erpCommon/ad_actionButton/MRPManufacturingPlanProcess.java	Thu May 30 10:08:15 2013 +0530
+++ b/src/org/openbravo/erpCommon/ad_actionButton/MRPManufacturingPlanProcess.java	Thu May 30 11:45:18 2013 +0200
@@ -74,17 +74,20 @@
 
       ScrollableResults linesToUpdate = getLinesToUpdate(strManufacturingMRPID);
       int i = 0;
-      while (linesToUpdate.next()) {
-        ProductionRunLine prLine = (ProductionRunLine) linesToUpdate.get(0);
-        prLine.setInserted(false);
-        OBDal.getInstance().save(prLine);
+      try {
+        while (linesToUpdate.next()) {
+          ProductionRunLine prLine = (ProductionRunLine) linesToUpdate.get(0);
+          prLine.setInserted(false);
+          OBDal.getInstance().save(prLine);
 
-        if (i % 100 == 0) {
-          OBDal.getInstance().flush();
-          OBDal.getInstance().getSession().clear();
+          if (i % 100 == 0) {
+            OBDal.getInstance().flush();
+            OBDal.getInstance().getSession().clear();
+          }
         }
+      } finally {
+        linesToUpdate.close();
       }
-      linesToUpdate.close();
       log4j.debug("Call MRP_Run_Initialize process");
       // v_ResultStr:='Initialize';
       // MRP_RUN_INITIALIZE(v_User_ID, v_Org_ID, v_Client_ID, v_Record_ID, v_Planner_ID,
--- a/src/org/openbravo/erpCommon/ad_process/MRPPurchaseCreateReservations.java	Thu May 30 10:08:15 2013 +0530
+++ b/src/org/openbravo/erpCommon/ad_process/MRPPurchaseCreateReservations.java	Thu May 30 11:45:18 2013 +0200
@@ -94,66 +94,69 @@
 
     PurchasingRunLine incomingLine = null;
     String productID = "";
-    while (outgoingRLs.next()) {
-      PurchasingRunLine outgoingLine = (PurchasingRunLine) outgoingRLs.get(0);
-      if (!productID.equals((String) DalUtil.getId(outgoingLine.getProduct()))) {
-        productID = (String) DalUtil.getId(outgoingLine.getProduct());
-        currentStock = BigDecimal.ZERO;
-      }
-      BigDecimal quantity = outgoingLine.getQuantity().negate();
-      boolean isSalesOrderLine = outgoingLine.getSalesOrderLine() != null
-          && outgoingLine.getSalesOrderLine().getSalesOrder().isSalesTransaction();
-      while (quantity.signum() == 1) {
-        if (currentStock.signum() < 1 && incomingRLs.next()) {
-          incomingLine = (PurchasingRunLine) incomingRLs.get(0);
-          if (!productID.equals((String) DalUtil.getId(outgoingLine.getProduct()))
-              && incomingRLs.next()) {
+    try {
+      while (outgoingRLs.next()) {
+        PurchasingRunLine outgoingLine = (PurchasingRunLine) outgoingRLs.get(0);
+        if (!productID.equals((String) DalUtil.getId(outgoingLine.getProduct()))) {
+          productID = (String) DalUtil.getId(outgoingLine.getProduct());
+          currentStock = BigDecimal.ZERO;
+        }
+        BigDecimal quantity = outgoingLine.getQuantity().negate();
+        boolean isSalesOrderLine = outgoingLine.getSalesOrderLine() != null
+            && outgoingLine.getSalesOrderLine().getSalesOrder().isSalesTransaction();
+        while (quantity.signum() == 1) {
+          if (currentStock.signum() < 1 && incomingRLs.next()) {
             incomingLine = (PurchasingRunLine) incomingRLs.get(0);
-          }
-          currentStock = currentStock.add(incomingLine.getQuantity());
-          if (incomingLine.getTransactionType().equals("PP")
-              && incomingLine.getSalesOrderLine() != null) {
-            OBDal.getInstance().refresh(incomingLine.getSalesOrderLine().getSalesOrder());
-            if (!incomingLine.getSalesOrderLine().getSalesOrder().isProcessed()) {
-              try {
-                processOrder(incomingLine.getSalesOrderLine().getSalesOrder());
-              } catch (OBException e) {
-                OBDal.getInstance().rollbackAndClose();
-                OBError error = OBMessageUtils.translateError(e.getMessage());
-                bundle.setResult(error);
-                return;
+            if (!productID.equals((String) DalUtil.getId(outgoingLine.getProduct()))
+                && incomingRLs.next()) {
+              incomingLine = (PurchasingRunLine) incomingRLs.get(0);
+            }
+            currentStock = currentStock.add(incomingLine.getQuantity());
+            if (incomingLine.getTransactionType().equals("PP")
+                && incomingLine.getSalesOrderLine() != null) {
+              OBDal.getInstance().refresh(incomingLine.getSalesOrderLine().getSalesOrder());
+              if (!incomingLine.getSalesOrderLine().getSalesOrder().isProcessed()) {
+                try {
+                  processOrder(incomingLine.getSalesOrderLine().getSalesOrder());
+                } catch (OBException e) {
+                  OBDal.getInstance().rollbackAndClose();
+                  OBError error = OBMessageUtils.translateError(e.getMessage());
+                  bundle.setResult(error);
+                  return;
+                }
               }
             }
           }
+          BigDecimal consumedQuantity = currentStock.min(quantity);
+          currentStock = currentStock.subtract(consumedQuantity);
+          quantity = quantity.subtract(consumedQuantity);
+          if (isSalesOrderLine) {
+            Reservation reservation = ReservationUtils.getReservationFromOrder(outgoingLine
+                .getSalesOrderLine());
+            if (reservation.getReservedQty().compareTo(reservation.getQuantity()) == -1) {
+              if (incomingLine.getTransactionType().equals("PP")
+                  && incomingLine.getSalesOrderLine() != null) {
+                ReservationUtils.reserveStockManual(reservation, incomingLine.getSalesOrderLine(),
+                    consumedQuantity, "N");
+              }
+
+              if (quantity.signum() < 1 && reservation.getRESStatus().equals("DR")) {
+                ReservationUtils.processReserve(reservation, "PR");
+              }
+            }
+            OBDal.getInstance().save(reservation);
+            OBDal.getInstance().flush();
+          }
         }
-        BigDecimal consumedQuantity = currentStock.min(quantity);
-        currentStock = currentStock.subtract(consumedQuantity);
-        quantity = quantity.subtract(consumedQuantity);
-        if (isSalesOrderLine) {
-          Reservation reservation = ReservationUtils.getReservationFromOrder(outgoingLine
-              .getSalesOrderLine());
-          if (reservation.getReservedQty().compareTo(reservation.getQuantity()) == -1) {
-            if (incomingLine.getTransactionType().equals("PP")
-                && incomingLine.getSalesOrderLine() != null) {
-              ReservationUtils.reserveStockManual(reservation, incomingLine.getSalesOrderLine(),
-                  consumedQuantity, "N");
-            }
-
-            if (quantity.signum() < 1 && reservation.getRESStatus().equals("DR")) {
-              ReservationUtils.processReserve(reservation, "PR");
-            }
-          }
-          OBDal.getInstance().save(reservation);
-          OBDal.getInstance().flush();
+        if ((i % 100) == 0) {
+          SessionHandler.getInstance().commitAndStart();
+          OBDal.getInstance().getSession().clear();
         }
       }
-      if ((i % 100) == 0) {
-        SessionHandler.getInstance().commitAndStart();
-        OBDal.getInstance().getSession().clear();
-      }
+    } finally {
+      incomingRLs.close();
+      outgoingRLs.close();
     }
-    outgoingRLs.close();
-    outgoingRLs.close();
     OBError message = new OBError();
     message.setType("Success");
     message.setTitle(OBMessageUtils.messageBD("Success"));
--- a/src/org/openbravo/erpCommon/utility/WindowTree.java	Thu May 30 10:08:15 2013 +0530
+++ b/src/org/openbravo/erpCommon/utility/WindowTree.java	Thu May 30 11:45:18 2013 +0200
@@ -256,17 +256,20 @@
         ScrollableResults entityData = entityResults.scroll(ScrollMode.FORWARD_ONLY);
         int clearEachLoops = 100;
         int i = 0;
-        while (entityData.next()) {
-          i++;
-          BaseOBObject entity = (BaseOBObject) entityData.get()[0];
-          if (entity.getId() != null) {
-            nodeIdList.add(entity.getId().toString());
+        try {
+          while (entityData.next()) {
+            i++;
+            BaseOBObject entity = (BaseOBObject) entityData.get()[0];
+            if (entity.getId() != null) {
+              nodeIdList.add(entity.getId().toString());
+            }
+            if (i % clearEachLoops == 0) {
+              OBDal.getInstance().getSession().clear();
+            }
           }
-          if (i % clearEachLoops == 0) {
-            OBDal.getInstance().getSession().clear();
-          }
+        } finally {
+          entityData.close();
         }
-        entityData.close();
       }
 
       for (WindowTreeData elem : subList) {