Example usage for org.hibernate ScrollableResults get

List of usage examples for org.hibernate ScrollableResults get

Introduction

In this page you can find the example usage for org.hibernate ScrollableResults get.

Prototype

Object get(int i);

Source Link

Document

Get the ith object in the current row of results, without initializing any other results in the row.

Usage

From source file:org.openbravo.costing.CostingMigrationProcess.java

License:Open Source License

private void updateLegacyCosts() {
    log4j.debug("UpdateLegacyCosts");
    // Reset costs in m_transaction and m_transaction_cost.
    Query queryDelete = OBDal.getInstance().getSession()
            .createQuery("delete from " + TransactionCost.ENTITY_NAME);
    queryDelete.executeUpdate();/*from ww  w.  j  av  a  2 s  . co  m*/

    // FIXME: Update should be done with a loop based on scroll.
    StringBuffer update = new StringBuffer();
    update.append("update " + MaterialTransaction.ENTITY_NAME);
    update.append(" set " + MaterialTransaction.PROPERTY_ISCOSTCALCULATED + " = false,");
    update.append("     " + MaterialTransaction.PROPERTY_TRANSACTIONCOST + " = null");
    update.append(" where " + MaterialTransaction.PROPERTY_TRANSACTIONCOST + " <> 0");
    update.append("   or " + MaterialTransaction.PROPERTY_ISCOSTCALCULATED + " = true");
    Query updateQry = OBDal.getInstance().getSession().createQuery(update.toString());
    updateQry.executeUpdate();
    OBDal.getInstance().flush();
    fixLegacyCostingCurrency();

    for (Client client : getClients()) {
        OrganizationStructureProvider osp = OBContext.getOBContext()
                .getOrganizationStructureProvider(client.getId());
        String clientId = client.getId();
        // Reload client entity after session cleared to avoid No Session error.
        client = OBDal.getInstance().get(Client.class, clientId);
        Currency clientCur = client.getCurrency();
        int stdPrecission = clientCur.getStandardPrecision().intValue();
        log4j.debug("** Processing client: " + client.getIdentifier() + " with currency: "
                + clientCur.getIdentifier());
        for (Organization legalEntity : osp.getLegalEntitiesList()) {
            log4j.debug("** Processing organization: " + legalEntity.getIdentifier());
            Set<String> naturalTree = osp.getNaturalTree(legalEntity.getId());
            ScrollableResults legacyCosts = getLegacyCostScroll(clientId, naturalTree);
            int i = 0;
            try {
                while (legacyCosts.next()) {
                    Costing cost = (Costing) legacyCosts.get(0);

                    updateTrxLegacyCosts(cost, stdPrecission, naturalTree);

                    if ((i % 100) == 0) {
                        OBDal.getInstance().flush();
                        OBDal.getInstance().getSession().clear();
                    }
                }
            } finally {
                legacyCosts.close();
            }
            SessionHandler.getInstance().commitAndStart();
        }
    }

    updateWithZeroCostRemainingTrx();

    insertTrxCosts();
    insertStandardCosts();
}

From source file:org.openbravo.costing.CostingMigrationProcess.java

License:Open Source License

private void fixLegacyCostingCurrency() {
    StringBuffer where = new StringBuffer();
    where.append(" as c");
    where.append("   join c." + Costing.PROPERTY_CLIENT + " as cl");
    where.append(" where c." + Costing.PROPERTY_CURRENCY + " <> cl." + Client.PROPERTY_CURRENCY);
    final OBQuery<Costing> costQry = OBDal.getInstance().createQuery(Costing.class, where.toString());
    costQry.setFilterOnActive(false);/*from  w ww .j  ava  2s .com*/
    costQry.setFilterOnReadableClients(false);
    costQry.setFilterOnReadableOrganization(false);
    costQry.setFetchSize(1000);

    final ScrollableResults costs = costQry.scroll(ScrollMode.FORWARD_ONLY);
    int i = 0;
    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++;
        }
    } finally {
        costs.close();
    }
}

From source file:org.openbravo.costing.CostingMigrationProcess.java

License:Open Source License

private void calculateCosts(Organization org) {
    Currency cur = FinancialUtils.getLegalEntityCurrency(org);
    String curId = cur.getId();/*from  w w w  . java  2 s  .c  o  m*/
    Set<String> orgs = OBContext.getOBContext().getOrganizationStructureProvider(org.getClient().getId())
            .getChildTree(org.getId(), true);
    String orgId = org.getId();

    int costPrecision = cur.getCostingPrecision().intValue();
    int stdPrecision = cur.getStandardPrecision().intValue();
    CostingRuleProcess crp = new CostingRuleProcess();
    // Update cost of inventories and process starting physical inventories.
    ScrollableResults icls = getCloseInventoryLines(orgs);
    String productId = "";
    BigDecimal totalCost = BigDecimal.ZERO;
    BigDecimal totalStock = BigDecimal.ZERO;
    int i = 0;
    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 = BigDecimal.ZERO;
            if (BigDecimal.ZERO.compareTo(trx.getMovementQuantity()) != 0) {
                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);
            }

            InventoryCountLine initICL = icl.getRelatedInventory();
            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();
    }

    OBDal.getInstance().flush();
    insertTrxCosts();

}

From source file:org.openbravo.costing.CostingMigrationProcess.java

License:Open Source License

private void updateTrxLegacyCosts(Costing _cost, int standardPrecision, Set<String> naturalTree) {
    log4j.debug("****** UpdateTrxLegacyCosts");
    Costing cost = OBDal.getInstance().get(Costing.class, _cost.getId());

    StringBuffer where = new StringBuffer();
    where.append(MaterialTransaction.PROPERTY_PRODUCT + ".id = :product");
    where.append("   and " + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
    where.append("   and " + MaterialTransaction.PROPERTY_MOVEMENTDATE + " >= :dateFrom");
    where.append("   and " + MaterialTransaction.PROPERTY_MOVEMENTDATE + " < :dateTo");
    OBQuery<MaterialTransaction> trxQry = OBDal.getInstance().createQuery(MaterialTransaction.class,
            where.toString());/*ww w. j av a2 s  .  c o  m*/
    trxQry.setFilterOnActive(false);
    trxQry.setFilterOnReadableClients(false);
    trxQry.setFilterOnReadableOrganization(false);
    trxQry.setNamedParameter("product", DalUtil.getId(cost.getProduct()));
    trxQry.setNamedParameter("orgs", naturalTree);
    trxQry.setNamedParameter("dateFrom", cost.getStartingDate());
    trxQry.setNamedParameter("dateTo", cost.getEndingDate());
    trxQry.setFetchSize(1000);

    ScrollableResults trxs = trxQry.scroll(ScrollMode.FORWARD_ONLY);
    int i = 0;
    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);

                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++;
        }
    } finally {
        trxs.close();
    }

    log4j.debug("****** UpdateTrxLegacyCosts updated:" + i);
}

From source file:org.openbravo.costing.CostingMigrationProcess.java

License:Open Source License

/**
 * Initializes with zero cost those transactions that haven't been calculated by previous methods
 * because they don't have any cost available. This transactions are checked by the alert rule.
 * But if this alert is deactivated the process continues forcing to initialize the transactions
 * with zero cost./*from  w w  w.j  a  v  a  2  s  . c  om*/
 */
private void updateWithZeroCostRemainingTrx() {
    log4j.debug("****** updateWithCeroRemainingTrx");
    StringBuffer where = new StringBuffer();
    where.append(MaterialTransaction.PROPERTY_TRANSACTIONCOST + " is null");
    where.append(" order by " + MaterialTransaction.PROPERTY_ORGANIZATION);
    OBQuery<MaterialTransaction> trxsQry = OBDal.getInstance().createQuery(MaterialTransaction.class,
            where.toString());
    trxsQry.setFilterOnActive(false);
    trxsQry.setFilterOnReadableClients(false);
    trxsQry.setFilterOnReadableOrganization(false);
    trxsQry.setFetchSize(1000);
    ScrollableResults trxs = trxsQry.scroll(ScrollMode.FORWARD_ONLY);
    int i = 0;
    String orgId = "";
    String curId = "";
    try {
        while (trxs.next()) {
            MaterialTransaction trx = (MaterialTransaction) trxs.get(0);
            if (!orgId.equals(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++;
        }
    } finally {
        trxs.close();
    }
    log4j.debug("****** updateWithCeroRemainingTrx updated:" + i);
}

From source file:org.openbravo.costing.CostingRuleProcess.java

License:Open Source License

private void initializeOldTrx(Set<String> childOrgs, Date date) {
    StringBuffer where = new StringBuffer();
    where.append(" where " + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
    where.append("   and " + MaterialTransaction.PROPERTY_MOVEMENTDATE + " < :date");
    OBQuery<MaterialTransaction> trxQry = OBDal.getInstance().createQuery(MaterialTransaction.class,
            where.toString());//from ww  w .  j a v  a  2s  . com
    trxQry.setFilterOnReadableOrganization(false);
    trxQry.setNamedParameter("orgs", childOrgs);
    trxQry.setNamedParameter("date", date);
    trxQry.setFetchSize(1000);
    ScrollableResults trxs = trxQry.scroll(ScrollMode.FORWARD_ONLY);
    int i = 1;
    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());
            transactionCost.setAccountingDate(trx.getGoodsShipmentLine() != null
                    ? trx.getGoodsShipmentLine().getShipmentReceipt().getAccountingDate()
                    : trx.getMovementDate());
            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);

            if ((i % 100) == 0) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
            }
            i++;
        }
    } finally {
        trxs.close();
    }
}

From source file:org.openbravo.costing.CostingRuleProcess.java

License:Open Source License

private void updateInitInventoriesTrxDate(Date startingDate, String ruleId) {
    StringBuffer where = new StringBuffer();
    where.append(" as trx");
    where.append("   join trx." + MaterialTransaction.PROPERTY_PHYSICALINVENTORYLINE + " as il");
    where.append(" where il." + InventoryCountLine.PROPERTY_PHYSINVENTORY + ".id IN (");
    where.append("    select cri." + CostingRuleInit.PROPERTY_INITINVENTORY + ".id");
    where.append("    from " + CostingRuleInit.ENTITY_NAME + " as cri");
    where.append("    where cri." + CostingRuleInit.PROPERTY_COSTINGRULE + ".id = :cr");
    where.append("    )");
    OBQuery<MaterialTransaction> trxQry = OBDal.getInstance().createQuery(MaterialTransaction.class,
            where.toString());/*w  ww . ja v a  2  s .  c  o  m*/
    trxQry.setNamedParameter("cr", ruleId);
    trxQry.setFetchSize(1000);
    ScrollableResults trxs = trxQry.scroll(ScrollMode.FORWARD_ONLY);
    int i = 0;
    while (trxs.next()) {
        MaterialTransaction trx = (MaterialTransaction) trxs.get(0);
        trx.setTransactionProcessDate(startingDate);
        OBDal.getInstance().save(trx);
        if ((i % 100) == 0) {
            OBDal.getInstance().flush();
            OBDal.getInstance().getSession().clear();
        }
    }
    trxs.close();
}

From source file:org.openbravo.costing.PriceDifferenceProcess.java

License:Open Source License

/**
 * @return the message to be shown to the user properly formatted and translated to the user
 *         language./*from w ww . jav  a2s.  c o m*/
 * @throws OBException
 *           when there is an error that prevents the cost adjustment to be processed.
 * @throws OBException
 */
public static JSONObject processPriceDifference(Date date, Product product) throws OBException {

    JSONObject message = null;
    costAdjHeader = null;
    boolean costAdjCreated = false;
    int count = 0;
    OBCriteria<MaterialTransaction> mTrxs = OBDal.getInstance().createCriteria(MaterialTransaction.class);
    if (date != null) {
        mTrxs.add(Restrictions.le(MaterialTransaction.PROPERTY_MOVEMENTDATE, date));
    }
    if (product != null) {
        mTrxs.add(Restrictions.eq(MaterialTransaction.PROPERTY_PRODUCT, product));
    }
    mTrxs.add(Restrictions.eq(MaterialTransaction.PROPERTY_CHECKPRICEDIFFERENCE, true));
    mTrxs.add(Restrictions.eq(MaterialTransaction.PROPERTY_ISCOSTCALCULATED, true));
    mTrxs.addOrderBy(MaterialTransaction.PROPERTY_MOVEMENTDATE, true);
    mTrxs.addOrderBy(MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE, true);
    ScrollableResults lines = mTrxs.scroll(ScrollMode.FORWARD_ONLY);

    try {
        while (lines.next()) {
            MaterialTransaction line = (MaterialTransaction) lines.get(0);
            costAdjCreated = calculateTransactionPriceDifference(line);
            if (costAdjCreated) {
                count++;
            }

        }
    } finally {
        lines.close();
    }

    Map<String, String> map = new HashMap<String, String>();
    map.put("trxsNumber", Integer.toString(count));
    String messageText = OBMessageUtils.messageBD("PriceDifferenceChecked");

    if (costAdjHeader != null) {
        OBDal.getInstance().flush();
        message = CostAdjustmentProcess.doProcessCostAdjustment(costAdjHeader);
        try {
            if (message.get("severity") != "success") {
                throw new OBException(OBMessageUtils.parseTranslation("@ErrorProcessingCostAdj@") + ": "
                        + costAdjHeader.getDocumentNo() + " - " + message.getString("text"));
            } else {
                message.put("title", OBMessageUtils.messageBD("Success"));
                message.put("text", OBMessageUtils.parseTranslation(messageText, map));
            }
        } catch (JSONException e) {
            throw new OBException(OBMessageUtils.parseTranslation("@ErrorProcessingCostAdj@"));
        }
        return message;
    } else {
        try {
            message = new JSONObject();
            message.put("severity", "success");
            message.put("title", OBMessageUtils.messageBD("Success"));
            message.put("text", OBMessageUtils.parseTranslation(messageText, map));
        } catch (JSONException ignore) {
        }
        return message;
    }
}

From source file:org.openbravo.erpCommon.ad_actionButton.MRPManufacturingPlanProcess.java

License:Open Source License

@Override
protected void doExecute(ProcessBundle bundle) throws Exception {
    OBError msg = new OBError();
    msg.setType("Success");
    msg.setTitle(OBMessageUtils.messageBD("Success"));
    final String strManufacturingMRPID = (String) bundle.getParams().get("MRP_Run_Production_ID");
    final ProductionRun productionRun = OBDal.getInstance().get(ProductionRun.class, strManufacturingMRPID);
    final String userId = (String) DalUtil.getId(OBContext.getOBContext().getUser());
    final String orgId = (String) DalUtil.getId(productionRun.getOrganization());
    final String clientId = (String) DalUtil.getId(productionRun.getClient());
    final String plannerId = productionRun.getPlanner() != null
            ? (String) DalUtil.getId(productionRun.getPlanner())
            : NULL;// w  w w  .j  a v a 2  s.co m
    final String productId = productionRun.getProduct() != null
            ? (String) DalUtil.getId(productionRun.getProduct())
            : NULL;
    final String productCategoryId = productionRun.getProductCategory() != null
            ? (String) DalUtil.getId(productionRun.getProductCategory())
            : NULL;
    final String bpId = productionRun.getBusinessPartner() != null
            ? (String) DalUtil.getId(productionRun.getBusinessPartner())
            : NULL;
    final String bpCatId = productionRun.getBusinessPartnerCategory() != null
            ? (String) DalUtil.getId(productionRun.getBusinessPartnerCategory())
            : NULL;
    final long timeHorizon = productionRun.getTimeHorizon();
    final long safetyLeadTime = productionRun.getSafetyLeadTime();
    final Date docDate = productionRun.getDocumentDate();

    try {
        log4j.debug("Prepare process delete not fixed lines and set exploded to false.");

        deleteNotFixedLines(strManufacturingMRPID);

        ScrollableResults linesToUpdate = getLinesToUpdate(strManufacturingMRPID);
        int i = 0;
        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();
                }
            }
        } finally {
            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,
        // v_Product_ID,
        // v_Product_Category_ID, v_BPartner_ID, v_BP_Group_ID, NULL, v_TimeHorizon,
        // v_PlanningDate, 'Y');
        List<Object> parameters = new ArrayList<Object>();
        parameters.add(userId);
        parameters.add(orgId);
        parameters.add(clientId);
        parameters.add(strManufacturingMRPID);
        parameters.add(plannerId);
        parameters.add(productId);
        parameters.add(productCategoryId);
        parameters.add(bpId);
        parameters.add(bpCatId);
        parameters.add(NULL);
        parameters.add(timeHorizon);
        parameters.add(docDate);
        parameters.add("Y");
        CallStoredProcedure.getInstance().call("MRP_RUN_INITIALIZE", parameters, null, true, false);

        OBDal.getInstance().commitAndClose();
        OBDal.getInstance().getSession().clear();

        log4j.debug("Call MRP_Run_Explode process");
        // v_ResultStr:='Explode';
        // MRP_RUN_EXPLODE(v_User_ID, v_Org_ID, v_Client_ID, v_Record_ID, v_Planner_ID, v_TimeHorizon,
        // v_PlanningDate, v_SecurityMargin);
        parameters = new ArrayList<Object>();
        parameters.add(userId);
        parameters.add(orgId);
        parameters.add(clientId);
        parameters.add(strManufacturingMRPID);
        parameters.add(plannerId);
        parameters.add(timeHorizon);
        parameters.add(docDate);
        parameters.add(safetyLeadTime);
        CallStoredProcedure.getInstance().call("MRP_RUN_EXPLODE", parameters, null, true, false);
        OBDal.getInstance().commitAndClose();
        OBDal.getInstance().getSession().clear();

        log4j.debug("Call MRP_ProcessPlan process");
        // v_ResultStr:='ProcessPlan';
        // MRP_PROCESSPLAN(v_User_ID, v_Org_ID, v_Client_ID, v_Record_ID, v_Planner_ID, v_TimeHorizon,
        // v_PlanningDate, v_SecurityMargin);
        parameters = new ArrayList<Object>();
        parameters.add(userId);
        parameters.add(orgId);
        parameters.add(clientId);
        parameters.add(strManufacturingMRPID);
        parameters.add(plannerId);
        parameters.add(timeHorizon);
        parameters.add(docDate);
        parameters.add(safetyLeadTime);
        CallStoredProcedure.getInstance().call("MRP_PROCESSPLAN", parameters, null, true, false);

        OBDal.getInstance().commitAndClose();
        OBDal.getInstance().getSession().clear();
    } catch (final Exception e) {
        deleteNotFixedLines(strManufacturingMRPID);

        log4j.error("Exception found in MRPManufacturingProcess: ", e);
        msg = OBMessageUtils.translateError(bundle.getConnection(), bundle.getContext().toVars(),
                OBContext.getOBContext().getLanguage().getLanguage(), e.getMessage());
        msg.setTitle(OBMessageUtils.messageBD("Error"));

    } finally {
        bundle.setResult(msg);
    }

}

From source file:org.openbravo.erpCommon.ad_process.MRPPurchaseCreateReservations.java

License:Open Source License

@Override
public void doExecute(ProcessBundle bundle) throws Exception {
    // logger = bundle.getLogger();
    Map<String, Object> params = bundle.getParams();

    String strMRPRunId = (String) params.get("MRP_Run_Purchase_ID");
    PurchasingRun mrpPurchaseRun = OBDal.getInstance().get(PurchasingRun.class, strMRPRunId);

    String strMWarehosueID = (String) params.get("mWarehouseId");

    // Execute Create Orders process.
    OBContext.setAdminMode(true);//from  w  ww .ja va2 s . c om
    Process process = null;
    try {
        process = OBDal.getInstance().get(Process.class, "800163");
    } finally {
        OBContext.restorePreviousMode();
    }
    Map<String, String> createOrderParams = new HashMap<String, String>();
    createOrderParams.put("M_Warehouse_ID", strMWarehosueID);
    try {
        final ProcessInstance pinstance = CallProcess.getInstance().call(process, strMRPRunId,
                createOrderParams);

        if (pinstance.getResult() == 0L) {
            OBDal.getInstance().rollbackAndClose();
            OBError oberror = OBMessageUtils.getProcessInstanceMessage(pinstance);
            bundle.setResult(oberror);
            return;
        }
    } catch (Exception e) {
        OBDal.getInstance().rollbackAndClose();
        OBError messsage = OBMessageUtils.translateError(DbUtility.getUnderlyingSQLException(e).getMessage());
        bundle.setResult(messsage);
        return;
    }

    // Create reservations
    ScrollableResults outgoingRLs = getPRLinesOutgoing(mrpPurchaseRun);
    ScrollableResults incomingRLs = getPRLinesIncoming(mrpPurchaseRun);
    int i = 1;
    BigDecimal currentStock = BigDecimal.ZERO;

    PurchasingRunLine incomingLine = null;
    String productID = "";
    try {
        while (outgoingRLs.next()) {
            PurchasingRunLine outgoingLine = (PurchasingRunLine) outgoingRLs.get(0);
            if (!productID.equals(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(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, incomingLine.getSalesOrderLine().getSalesOrder()
                                            .getWarehouse().isAllocated() ? "Y" : "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();
            }
        }
    } finally {
        incomingRLs.close();
        outgoingRLs.close();
    }
    OBError message = new OBError();
    message.setType("Success");
    message.setTitle(OBMessageUtils.messageBD("Success"));
    bundle.setResult(message);
}