Example usage for org.hibernate ScrollMode FORWARD_ONLY

List of usage examples for org.hibernate ScrollMode FORWARD_ONLY

Introduction

In this page you can find the example usage for org.hibernate ScrollMode FORWARD_ONLY.

Prototype

ScrollMode FORWARD_ONLY

To view the source code for org.hibernate ScrollMode FORWARD_ONLY.

Click Source Link

Document

Requests a scrollable result that is only scrollable forwards.

Usage

From source file:org.openbravo.advpaymentmngt.process.FIN_PaymentMonitorProcess.java

License:Open Source License

public void doExecute(ProcessBundle bundle) throws Exception {
    logger = bundle.getLogger();/*from   w ww. j a va  2 s . com*/
    // Check to know if PaymentMonitor property is set in the system.
    try {
        Preferences.getPreferenceValue("PaymentMonitor", true, null, null, OBContext.getOBContext().getUser(),
                null, null);
    } catch (PropertyNotFoundException e) {
        logger.log("Property not found \n");
        return;
    } catch (PropertyException e) {
        logger.log("PropertyException, there is a conflict for PaymentMonitor property\n");
        return;
    }
    // Check to know that this APR is the module implementing the PaymentMonitor property
    if (isPreferenceOfModule("PaymentMonitor", "A918E3331C404B889D69AA9BFAFB23AC")) {
        logger.log("Starting Update Paid Amount for Invoices Background Process.\n");
    } else {
        logger.log("Payment Monitor active for other module.\n");
        logger.log("Core's background process is executed.\n");
        return;
    }

    ScrollableResults invoiceScroller = null;
    try {
        int counter = 0;
        final Module migration = OBDal.getInstance().get(Module.class, "4BD3D4B262B048518FE62496EF09D549");

        StringBuilder whereClause = new StringBuilder();
        whereClause.append(" as i");
        whereClause.append("   left join i.fINPaymentScheduleList fps ");
        whereClause.append(" where i.processed=true");
        whereClause.append(" and (i.paymentComplete=false ");
        whereClause.append("      or fps.updated >= i.lastCalculatedOnDate ");
        whereClause.append("      or i.outstandingAmount <> 0");
        if (migration != null) {
            whereClause.append("  or (i.finalSettlementDate is null");
            whereClause.append(" and fps.id is not null");
            whereClause.append(" and i.aprmtIsmigrated = 'N'))");
        } else {
            whereClause.append(" or i.finalSettlementDate is null)");
        }

        final OBQuery<Invoice> obc = OBDal.getInstance().createQuery(Invoice.class, whereClause.toString());

        // For Background process execution at system level
        if (OBContext.getOBContext().isInAdministratorMode()) {
            obc.setFilterOnReadableClients(false);
            obc.setFilterOnReadableOrganization(false);
        }

        invoiceScroller = obc.scroll(ScrollMode.FORWARD_ONLY);
        while (invoiceScroller.next()) {
            final Invoice invoice = (Invoice) invoiceScroller.get()[0];
            updateInvoice(invoice);
            counter++;
            if (counter % 100 == 0) {
                OBDal.getInstance().getSession().flush();
                OBDal.getInstance().getSession().clear();
                logger.log("Invoices updated: " + counter + "\n");
            }
        }
        if (counter % 100 != 0)
            logger.log("Invoices updated: " + counter + "\n");
    } catch (Exception e) {
        // catch any possible exception and throw it as a Quartz
        // JobExecutionException
        throw new JobExecutionException(e.getMessage(), e);
    } finally {
        if (invoiceScroller != null) {
            invoiceScroller.close();
        }
    }
}

From source file:org.openbravo.advpaymentmngt.utility.APRM_MatchingUtility.java

License:Open Source License

/**
 * Get the bank statement lines that are not yet matched to a transaction for the given financial
 * account. If the reconciliation passed as parameter is the last one, the method filters by the
 * bank statement lines with transaction date less or equal than the reconciliation's ending date
 *///from   ww  w. ja  va  2s.  co m
public static ScrollableResults getPendingToBeMatchedBankStatementLines(String strFinancialAccountId,
        String strReconciliationId) {
    try {
        OBContext.setAdminMode(true);
        FIN_Reconciliation reconciliation = OBDal.getInstance().get(FIN_Reconciliation.class,
                strReconciliationId);
        boolean isLastReconciliation = MatchTransactionDao.islastreconciliation(reconciliation);
        final StringBuilder whereClause = new StringBuilder();
        whereClause.append(" as bsl ");
        whereClause.append(" where bsl.").append(FIN_BankStatementLine.PROPERTY_BANKSTATEMENT);
        whereClause.append(".").append(FIN_BankStatement.PROPERTY_ACCOUNT).append(".id = :account");
        whereClause.append(" and bsl.bankStatement.processed = 'Y'");
        if (!isLastReconciliation) {
            whereClause.append(" and  bsl.").append(FIN_BankStatementLine.PROPERTY_TRANSACTIONDATE)
                    .append(" <= :endingdate");
        }
        whereClause.append("   and bsl.financialAccountTransaction is null");
        whereClause.append(" order by bsl.").append(FIN_BankStatementLine.PROPERTY_TRANSACTIONDATE);
        whereClause.append(", bsl.").append(FIN_BankStatementLine.PROPERTY_LINENO);
        whereClause.append(", bsl.").append(FIN_BankStatementLine.PROPERTY_BPARTNERNAME);
        final OBQuery<FIN_BankStatementLine> obData = OBDal.getInstance()
                .createQuery(FIN_BankStatementLine.class, whereClause.toString());
        obData.setNamedParameter("account", strFinancialAccountId);
        if (!isLastReconciliation) {
            obData.setNamedParameter("endingdate", reconciliation.getEndingDate());
        }
        return obData.scroll(ScrollMode.FORWARD_ONLY);
    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.openbravo.client.application.event.AcctSchemaEventHandler.java

License:Open Source License

private void updateElementValues(Element _element, AcctSchema acctSchema, boolean assetPositive,
        boolean liabilityPositive, boolean ownersEquityPositive, boolean expensePositive,
        boolean revenuePositive) {
    StringBuffer where = new StringBuffer();
    final String ACCOUNTSIGN_CREDIT = "C";
    final String ACCOUNTSIGN_DEBIT = "D";
    final String ACCOUNTTYPE_MEMO = "M";
    Element element = OBDal.getInstance().get(Element.class, _element.getId());
    where.append(ElementValue.PROPERTY_ACCOUNTINGELEMENT + ".id = :element");
    OBQuery<ElementValue> elementValueQry = OBDal.getInstance().createQuery(ElementValue.class,
            where.toString());/*from w  w  w. j a v a  2  s  .c o m*/
    elementValueQry.setFilterOnActive(false);
    elementValueQry.setFilterOnReadableClients(false);
    elementValueQry.setFilterOnReadableOrganization(false);
    elementValueQry.setNamedParameter("element", element.getId());
    elementValueQry.setFetchSize(1000);

    ScrollableResults elementvalues = elementValueQry.scroll(ScrollMode.FORWARD_ONLY);
    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++;
        }
    } finally {
        elementvalues.close();
    }
}

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

License:Open Source License

private ScrollableResults getRelatedTransactions() {
    CostingRule costingRule = getCostingRule();
    HashMap<CostDimension, BaseOBObject> costDimensions = getCostDimensions();
    OrganizationStructureProvider osp = OBContext.getOBContext()
            .getOrganizationStructureProvider(costingRule.getClient().getId());
    Set<String> orgs = osp.getChildTree(strCostOrgId, true);
    if (isManufacturingProduct) {
        orgs = osp.getChildTree("0", false);
        costDimensions = CostingUtils.getEmptyDimensions();
    }//from w  ww .j  a  v a 2  s  . c o m
    Warehouse warehouse = (Warehouse) costDimensions.get(CostDimension.Warehouse);
    MaterialTransaction trx = getTransaction();

    StringBuffer wh = new StringBuffer();
    wh.append(" as trx");
    wh.append("\n join trx." + Product.PROPERTY_ORGANIZATION + " as org");
    wh.append("\n join trx." + Product.PROPERTY_STORAGEBIN + " as loc");
    wh.append("\n , " + org.openbravo.model.ad.domain.List.ENTITY_NAME + " as trxtype");
    wh.append("\n where trxtype." + CostAdjustmentUtils.propADListReference + ".id = :refid");
    wh.append("  and trxtype." + CostAdjustmentUtils.propADListValue + " = trx."
            + MaterialTransaction.PROPERTY_MOVEMENTTYPE);

    wh.append("  and trx." + MaterialTransaction.PROPERTY_ISCOSTCALCULATED + " = true");
    wh.append("  and trx." + MaterialTransaction.PROPERTY_PRODUCT + " = :product");
    // Consider only transactions with movement date equal or later than the movement date of the
    // adjusted transaction. But for transactions with the same movement date only those with a
    // transaction date after the process date of the adjusted transaction.
    wh.append(" and (");

    if (costingRule.isBackdatedTransactionsFixed()) {
        wh.append("  (trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " < :fixbdt");
        wh.append("  and (");
    }

    wh.append("   trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " > :trxdate");
    wh.append("   or (");
    wh.append("    trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " = :trxdate");
    wh.append("    and (");
    wh.append("     trxtype." + CostAdjustmentUtils.propADListPriority + " > :trxtypeprio");
    wh.append("     or (");
    wh.append("      trxtype." + CostAdjustmentUtils.propADListPriority + " = :trxtypeprio");
    wh.append("      and trx." + MaterialTransaction.PROPERTY_MOVEMENTQUANTITY + " < :trxqty");
    wh.append("      or (");
    wh.append("        trx." + MaterialTransaction.PROPERTY_MOVEMENTQUANTITY + " = :trxqty");
    wh.append("        and trx." + MaterialTransaction.PROPERTY_ID + " > :trxid");
    wh.append("  )))))");

    if (costingRule.isBackdatedTransactionsFixed()) {
        wh.append(" ) or (");

        wh.append("  trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " >= :fixbdt");
        wh.append("  and (");
        wh.append("   trx." + MaterialTransaction.PROPERTY_MOVEMENTDATE + " > :mvtdate");
        wh.append("   or (");
        wh.append("    trx." + MaterialTransaction.PROPERTY_MOVEMENTDATE + " = :mvtdate");
        // If there are more than one trx on the same trx process date filter out those types with
        // less
        // priority and / or higher quantity.
        wh.append("    and (");
        wh.append("     trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " > :trxdate");
        wh.append("     or (");
        wh.append("      trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " = :trxdate");
        wh.append("      and (");
        wh.append("       trxtype." + CostAdjustmentUtils.propADListPriority + " > :trxtypeprio");
        wh.append("       or (");
        wh.append("        trxtype." + CostAdjustmentUtils.propADListPriority + " = :trxtypeprio");
        wh.append("        and trx." + MaterialTransaction.PROPERTY_MOVEMENTQUANTITY + " < :trxqty");
        wh.append("         or (");
        wh.append("          trx." + MaterialTransaction.PROPERTY_MOVEMENTQUANTITY + " = :trxqty");
        wh.append("          and trx." + MaterialTransaction.PROPERTY_ID + " > :trxid");
        wh.append("    )))))");
        wh.append(" )))");
    }
    wh.append(")");
    wh.append("  and org.id in (:orgs)");
    if (warehouse != null) {
        wh.append("  and loc." + Locator.PROPERTY_WAREHOUSE + " = :warehouse");
    }
    if (costingRule.getEndingDate() != null) {
        wh.append("  and trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " <= :enddate");
    }
    wh.append("  and trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " > :startdate ");
    wh.append("\n order by ");
    if (areBackdatedTrxFixed) {
        // CASE WHEN trx.trxprocessdate < :fixfrom THEN 1-1-1900
        // ELSE trx.movmenetdate END
        wh.append(" trx." + MaterialTransaction.PROPERTY_MOVEMENTDATE + ", ");
    }
    wh.append(" trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE);
    wh.append(" , trxtype." + CostAdjustmentUtils.propADListPriority);
    wh.append(" , trx." + MaterialTransaction.PROPERTY_MOVEMENTQUANTITY + " desc");
    wh.append(" , trx." + MaterialTransaction.PROPERTY_ID);

    OBQuery<MaterialTransaction> trxQry = OBDal.getInstance().createQuery(MaterialTransaction.class,
            wh.toString());
    trxQry.setFilterOnReadableOrganization(false);
    trxQry.setFilterOnReadableClients(false);
    trxQry.setNamedParameter("refid", CostAdjustmentUtils.MovementTypeRefID);
    trxQry.setNamedParameter("product", trx.getProduct());
    if (costingRule.isBackdatedTransactionsFixed()) {
        trxQry.setNamedParameter("mvtdate", trx.getMovementDate());
        trxQry.setNamedParameter("fixbdt", CostingUtils.getCostingRuleFixBackdatedFrom(costingRule));
    }
    trxQry.setNamedParameter("trxtypeprio", CostAdjustmentUtils.getTrxTypePrio(trx.getMovementType()));
    trxQry.setNamedParameter("trxdate", trx.getTransactionProcessDate());
    trxQry.setNamedParameter("trxqty", trx.getMovementQuantity());
    trxQry.setNamedParameter("trxid", trx.getId());
    trxQry.setNamedParameter("orgs", orgs);
    if (warehouse != null) {
        trxQry.setNamedParameter("warehouse", warehouse);
    }
    if (costingRule.getEndingDate() != null) {
        trxQry.setNamedParameter("enddate", costingRule.getEndingDate());
    }
    trxQry.setNamedParameter("startdate", CostingUtils.getCostingRuleStartingDate(costingRule));

    return trxQry.scroll(ScrollMode.FORWARD_ONLY);
}

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

License:Open Source License

public static JSONObject doCancelCostAdjustment(CostAdjustment costAdjustmentOrig)
        throws OBException, JSONException {
    CostAdjustment costAdjustmentCancel = (CostAdjustment) DalUtil.copy(costAdjustmentOrig, false);

    final DocumentType docType = FIN_Utility.getDocumentType(costAdjustmentOrig.getOrganization(),
            strCategoryCostAdj);/*from w ww .j  a v  a  2 s  . c om*/
    final String docNo = FIN_Utility.getDocumentNo(docType, strTableCostAdj);
    costAdjustmentCancel.setDocumentNo(docNo);
    costAdjustmentCancel.setUpdated(new Date());
    costAdjustmentCancel.setUpdatedBy(OBContext.getOBContext().getUser());
    costAdjustmentCancel.setCreationDate(new Date());
    costAdjustmentCancel.setCreatedBy(OBContext.getOBContext().getUser());
    costAdjustmentCancel.setProcessed(false);
    costAdjustmentCancel.setPosted("N");
    OBDal.getInstance().save(costAdjustmentOrig);

    costAdjustmentOrig.setCostAdjustmentCancel(costAdjustmentCancel);
    costAdjustmentOrig.setDocumentStatus("VO");
    OBDal.getInstance().save(costAdjustmentCancel);
    OBDal.getInstance().flush();

    CostAdjustment cacProxy = (CostAdjustment) OBDal.getInstance().getProxy(CostAdjustment.ENTITY_NAME,
            costAdjustmentCancel.getId());
    // Call cost
    OBCriteria<CostAdjustmentLine> qLines = OBDal.getInstance().createCriteria(CostAdjustmentLine.class);
    qLines.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_COSTADJUSTMENT, costAdjustmentOrig));
    qLines.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_ISSOURCE, true));
    ScrollableResults scrollLines = qLines.scroll(ScrollMode.FORWARD_ONLY);
    try {
        int cnt = 0;
        while (scrollLines.next()) {
            final CostAdjustmentLine lineOrig = (CostAdjustmentLine) scrollLines.get()[0];
            CostAdjustmentLine lineCancel = (CostAdjustmentLine) DalUtil.copy(lineOrig, false);
            lineCancel.setUpdated(new Date());
            lineCancel.setUpdatedBy(OBContext.getOBContext().getUser());
            lineCancel.setCreationDate(new Date());
            lineCancel.setCreatedBy(OBContext.getOBContext().getUser());
            lineCancel.setCostAdjustment(cacProxy);
            lineCancel.setAdjustmentAmount(lineOrig.getAdjustmentAmount().negate());
            lineCancel.setBackdatedTrx(Boolean.FALSE);
            lineCancel.setNegativeStockCorrection(Boolean.FALSE);
            if (lineOrig.getInventoryTransaction().isCostPermanent()) {
                lineOrig.getInventoryTransaction().setCostPermanent(Boolean.FALSE);
                OBDal.getInstance().save(lineOrig.getInventoryTransaction());
            }
            OBDal.getInstance().save(lineCancel);
            if ((cnt++ % 10) == 0) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
            }
        }
    } finally {
        scrollLines.close();
    }
    OBDal.getInstance().flush();
    JSONObject message = new JSONObject();
    message.put("severity", "success");
    String strResult = OBMessageUtils.messageBD("CostAdjustmentCanceled");
    Map<String, String> map = new HashMap<String, String>();
    map.put("documentNo", docNo);
    message.put("title", OBMessageUtils.messageBD("Success"));
    message.put("text", OBMessageUtils.parseTranslation(strResult, map));

    CostAdjustmentProcess.doProcessCostAdjustment(costAdjustmentCancel);
    CostAdjustment costAdjCancel = OBDal.getInstance().get(CostAdjustment.class, costAdjustmentCancel.getId());
    costAdjCancel.setDocumentStatus("VO");
    costAdjCancel.setPosted("N");
    OBDal.getInstance().save(costAdjCancel);
    OBDal.getInstance().flush();
    return message;
}

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

License:Open Source License

private void checkPermanentelyAdjustedTrx(String strCostAdjId) throws OBException {
    OBCriteria<CostAdjustmentLine> critLines = OBDal.getInstance().createCriteria(CostAdjustmentLine.class);
    critLines.createAlias(CostAdjustmentLine.PROPERTY_INVENTORYTRANSACTION, "trx");
    critLines.createAlias(CostAdjustmentLine.PROPERTY_COSTADJUSTMENT, "ca");
    critLines.add(Restrictions.eq("ca.id", strCostAdjId));
    critLines.add(Restrictions.eq("trx." + MaterialTransaction.PROPERTY_ISCOSTPERMANENT, Boolean.TRUE));
    critLines.add(Restrictions.ne(CostAdjustmentLine.PROPERTY_ADJUSTMENTAMOUNT, BigDecimal.ZERO));
    critLines.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_UNITCOST, Boolean.TRUE));
    critLines.addOrder(Order.asc(CostAdjustmentLine.PROPERTY_LINENO));

    ScrollableResults lines = critLines.scroll(ScrollMode.FORWARD_ONLY);
    long count = 1L;
    try {/*from w  w  w. j a  v a  2 s.  c o m*/
        String strLines = "";
        while (lines.next()) {
            CostAdjustmentLine line = (CostAdjustmentLine) lines.get()[0];
            strLines += line.getLineNo() + ", ";

            if (count % 10000 == 0) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
            }
            count++;
        }
        if (!strLines.isEmpty()) {
            strLines = strLines.substring(0, strLines.length() - 2);
            String errorMessage = OBMessageUtils.messageBD("CostAdjustmentWithPermanentLines");
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("lines", strLines);
            throw new OBException(OBMessageUtils.parseTranslation(errorMessage, map));
        }
        OBDal.getInstance().flush();
        OBDal.getInstance().getSession().clear();
    } finally {
        lines.close();
    }
}

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

License:Open Source License

private void initializeLines(CostAdjustment costAdjustment) {
    // initialize is related transaction adjusted flag to false
    OBCriteria<CostAdjustmentLine> critLines = OBDal.getInstance().createCriteria(CostAdjustmentLine.class);
    critLines.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_COSTADJUSTMENT, costAdjustment));
    critLines.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_ISRELATEDTRANSACTIONADJUSTED, true));
    ScrollableResults lines = critLines.scroll(ScrollMode.FORWARD_ONLY);
    long count = 1L;
    try {//from   w w w  .  ja v a  2 s.com
        while (lines.next()) {
            CostAdjustmentLine line = (CostAdjustmentLine) lines.get(0);
            line.setRelatedTransactionAdjusted(false);
            OBDal.getInstance().save(line);

            if (count % 1000 == 0) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
            }
            count++;
        }
        OBDal.getInstance().flush();
        OBDal.getInstance().getSession().clear();
    } finally {
        lines.close();
    }
}

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

License:Open Source License

private void generateTransactionCosts(CostAdjustmentLine costAdjustmentLine) {
    log.debug("Generate transaction costs of line: {}", costAdjustmentLine.getLineNo());
    long t1 = System.currentTimeMillis();
    OBCriteria<CostAdjustmentLine> critLines = OBDal.getInstance().createCriteria(CostAdjustmentLine.class);
    Date referenceDate = costAdjustmentLine.getCostAdjustment().getReferenceDate();
    critLines.add(Restrictions.or(//ww w  .  ja v a  2 s. c  om
            Restrictions.eq(CostAdjustmentLine.PROPERTY_PARENTCOSTADJUSTMENTLINE, costAdjustmentLine),
            Restrictions.eq("id", costAdjustmentLine.getId())));
    ScrollableResults lines = critLines.scroll(ScrollMode.FORWARD_ONLY);

    try {
        while (lines.next()) {
            CostAdjustmentLine line = (CostAdjustmentLine) lines.get(0);
            if (!line.getTransactionCostList().isEmpty()) {
                continue;
            }
            TransactionCost trxCost = OBProvider.getInstance().get(TransactionCost.class);
            // TODO: Review this
            // trxCost.setNewOBObject(true);
            MaterialTransaction trx = line.getInventoryTransaction();
            trxCost.setInventoryTransaction(trx);
            trxCost.setOrganization(trx.getOrganization());
            trxCost.setCostDate(referenceDate);
            trxCost.setCostAdjustmentLine(line);
            trxCost.setUnitCost(line.isUnitCost());
            Date accountingDate = line.getAccountingDate();
            if (accountingDate == null) {
                accountingDate = trx.getMovementDate();
            }
            trxCost.setAccountingDate(accountingDate);
            BigDecimal convertedAmt = line.getAdjustmentAmount();
            if (!line.getCurrency().getId().equals(trx.getCurrency().getId())) {
                convertedAmt = FinancialUtils.getConvertedAmount(convertedAmt, line.getCurrency(),
                        trx.getCurrency(), accountingDate, trx.getOrganization(), "C");
            }
            trxCost.setCost(convertedAmt);
            trxCost.setCurrency(trx.getCurrency());

            OBDal.getInstance().save(trxCost);
            OBDal.getInstance().flush();
            OBDal.getInstance().getSession().clear();
        }
    } finally {
        lines.close();
    }
    log.debug("Transaction costs created. Time {}", System.currentTimeMillis() - t1);
}

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

License:Open Source License

protected void searchReturnShipments(CostAdjustmentLine _costAdjLine) {
    CostAdjustmentLine costAdjLine;//from ww w .ja  v a2s. c o  m
    if (_costAdjLine != null) {
        costAdjLine = _costAdjLine;
    } else {
        costAdjLine = getCostAdjLine();
    }
    ShipmentInOutLine inoutline = costAdjLine.getInventoryTransaction().getGoodsShipmentLine();
    BigDecimal costAdjAmt = costAdjLine.getAdjustmentAmount().negate();
    int precission = getCostCurrency().getStandardPrecision().intValue();
    StringBuffer where = new StringBuffer();
    where.append(" as trx");
    where.append(" join trx." + MaterialTransaction.PROPERTY_GOODSSHIPMENTLINE + " as iol");
    where.append(" join iol." + ShipmentInOutLine.PROPERTY_SALESORDERLINE + " as ol");
    where.append(" where ol." + OrderLine.PROPERTY_GOODSSHIPMENTLINE + " = :shipment");
    OBQuery<MaterialTransaction> qryTrx = OBDal.getInstance().createQuery(MaterialTransaction.class,
            where.toString());
    qryTrx.setFilterOnReadableOrganization(false);
    qryTrx.setNamedParameter("shipment", inoutline);
    ScrollableResults trxs = qryTrx.scroll(ScrollMode.FORWARD_ONLY);
    try {
        int counter = 0;
        while (trxs.next()) {
            counter++;

            MaterialTransaction trx = (MaterialTransaction) trxs.get()[0];
            if (trx.isCostCalculated()) {
                BigDecimal adjAmt = costAdjAmt.multiply(trx.getMovementQuantity().abs())
                        .divide(inoutline.getMovementQuantity().abs(), precission, RoundingMode.HALF_UP);
                insertCostAdjustmentLine(trx, adjAmt, _costAdjLine);
            }

            if (counter % 1000 == 0) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
            }
        }
    } finally {
        trxs.close();
    }
}

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  w w.j  av  a  2s . co  m*/
    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();
    }
}