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();

Source Link

Document

Get the current row of results.

Usage

From source file:org.glite.security.voms.admin.persistence.tools.DeleteRecordsCommand.java

License:Apache License

@Override
public void execute(CommandLine line) {

    AuditSearchDAO dao = DAOFactory.instance().getAuditSearchDAO();
    AuditLogSearchParams params = addConstraintsFromCommandLine(line);

    ScrollableAuditLogSearchResults results = dao.scrollEventsMatchingParams(params,
            ScrollMode.SCROLL_INSENSITIVE);

    int count = 0;
    ScrollableResults scroll = results.getResults();

    scroll.last();//from www .jav a2 s . com
    count = scroll.getRowNumber();

    if (count + 1 == 0) {
        System.out.println("No events found");
        return;
    }

    System.out.format("%d records will be deleted. Type 'yes' if you want to continue\n", count + 1);

    try {
        if (!getConfirmationFromUser()) {
            System.out.println("Aborting on user's request.");
            return;
        }
    } catch (IOException e) {
        throw new AuditLogCommandError(e);
    }

    scroll.beforeFirst();
    System.out.println("Deleting events:");

    count = 0;

    while (scroll.next()) {
        count++;
        AuditEvent event = (AuditEvent) scroll.get()[0];

        printAuditLogEvent(event);
        dao.makeTransient(event);
        dao.flush();
        HibernateFactory.getSession().evict(event);
    }

    System.out.format("%d events deleted.\n", count);

}

From source file:org.glite.security.voms.admin.persistence.tools.Print.java

License:Apache License

@Override
public void execute(CommandLine line) {

    AuditSearchDAO dao = DAOFactory.instance().getAuditSearchDAO();
    AuditLogSearchParams params = addConstraintsFromCommandLine(line);

    Integer maxResults = params.getMaxResults();
    if (maxResults == null) {
        maxResults = DEFAULT_MAX_RESULTS;
    }//from  w w  w. j  a  va 2  s  .  c om

    ScrollableAuditLogSearchResults results = dao.scrollEventsMatchingParams(params, ScrollMode.FORWARD_ONLY);

    ScrollableResults scroll = results.getResults();

    int count = 0;

    while (scroll.next()) {
        count++;

        AuditEvent e = (AuditEvent) scroll.get()[0];
        printAuditLogEvent(e);
        HibernateFactory.getSession().evict(e);

    }

    if (count == 0) {
        System.out.println("No events found.");
    } else {
        System.out.format("%d events printed\n", count);
    }

}

From source file:org.jasig.ssp.util.csvwriter.AbstractCsvWriterHelper.java

License:Apache License

public void write(final ScrollableResults model, final Long maxCount) throws IOException {
    doWrite(new Iterator<T>() {
        @Override//www . j  av a 2  s . c o m
        public boolean hasNext() {
            return !(model.isLast());
        }

        @Override
        public T next() {
            if (!(model.next())) {
                throw new NoSuchElementException(); // per Iterator interface
            }
            return (T) model.get()[0];
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }, maxCount);
}

From source file:org.jboss.aerogear.unifiedpush.jpa.dao.impl.JPAInstallationDao.java

License:Apache License

@Override
public ResultsStream.QueryBuilder<String> findAllDeviceTokenForVariantIDByCriteria(String variantID,
        List<String> categories, List<String> aliases, List<String> deviceTypes, final int maxResults,
        String lastTokenFromPreviousBatch) {
    // the required part: Join + all tokens for variantID;

    final StringBuilder jpqlString = new StringBuilder(FIND_ALL_DEVICES_FOR_VARIANT_QUERY);
    final Map<String, Object> parameters = new LinkedHashMap<String, Object>();
    parameters.put("variantID", variantID);

    // apend query conditions based on specified message parameters
    appendDynamicQuery(jpqlString, parameters, categories, aliases, deviceTypes);

    // sort on ids so that we can handle paging properly
    if (lastTokenFromPreviousBatch != null) {
        jpqlString.append(" AND installation.deviceToken > :lastTokenFromPreviousBatch");
        parameters.put("lastTokenFromPreviousBatch", lastTokenFromPreviousBatch);
    }/*from   w  w  w  . ja  v a 2  s . c o  m*/

    jpqlString.append(" ORDER BY installation.deviceToken ASC");

    return new ResultsStream.QueryBuilder<String>() {
        private Integer fetchSize = null;

        @Override
        public ResultsStream.QueryBuilder<String> fetchSize(int fetchSize) {
            this.fetchSize = fetchSize;
            return this;
        }

        @Override
        public ResultsStream<String> executeQuery() {
            Query hibernateQuery = JPAInstallationDao.this.createHibernateQuery(jpqlString.toString());
            hibernateQuery.setMaxResults(maxResults);
            for (Entry<String, Object> parameter : parameters.entrySet()) {
                Object value = parameter.getValue();
                if (value instanceof Collection<?>) {
                    hibernateQuery.setParameterList(parameter.getKey(), (Collection<?>) parameter.getValue());
                } else {
                    hibernateQuery.setParameter(parameter.getKey(), parameter.getValue());
                }

            }
            hibernateQuery.setReadOnly(true);
            if (fetchSize != null) {
                hibernateQuery.setFetchSize(fetchSize);
            }
            final ScrollableResults results = hibernateQuery.scroll(ScrollMode.FORWARD_ONLY);
            return new ResultsStream<String>() {
                @Override
                public boolean next() throws ResultStreamException {
                    return results.next();
                }

                @Override
                public String get() throws ResultStreamException {
                    return (String) results.get()[0];
                }
            };
        }

    };
}

From source file:org.n52.sos.ds.hibernate.dao.i18n.AbstractHibernateI18NDAO.java

License:Open Source License

protected void deleteOldValues(String id, Session session) {
    Criteria criteria = session.createCriteria(getHibernateEntityClass());
    criteria.createCriteria(AbstractHibernateI18NMetadata.OBJECT_ID)
            .add(Restrictions.eq(AbstractIdentifierNameDescriptionEntity.IDENTIFIER, id));
    ScrollableResults scroll = null;
    try {//w ww . j  a  v a  2 s . c  o  m
        scroll = criteria.scroll();
        while (scroll.next()) {
            @SuppressWarnings("unchecked")
            H h18n = (H) scroll.get()[0];
            session.delete(h18n);
        }
    } finally {
        if (scroll != null) {
            scroll.close();
        }
    }
    session.flush();
}

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

License:Open Source License

public void doExecute(ProcessBundle bundle) throws Exception {
    logger = bundle.getLogger();//w w  w .jav a  2  s . co m
    // 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.common.actionhandler.SetNewBPCurrency.java

License:Open Source License

@Override
protected JSONObject doExecute(Map<String, Object> parameters, String content) {

    JSONObject jsonRequest = null;// w  w w  . j  a v  a  2s .  co m
    OBContext.setAdminMode(true);
    try {
        jsonRequest = new JSONObject(content);
        JSONObject params = jsonRequest.getJSONObject("_params");
        final String strOrgId = jsonRequest.getString("inpadOrgId");
        final String strFromCurrencyId = jsonRequest.getString("inpbpCurrencyId");
        final String strToCurrencyId = params.getString("C_Currency_ID");
        final String strRate = params.getString("Rate");
        final String strAmount = params.getString("Foreign_Amount");
        final boolean strSetAmount = params.getBoolean("Amount");
        final boolean strUseDefaultConversion = params.getBoolean("Default_Conversion_Rate");
        final String strBpartnerId = jsonRequest.getString("C_BPartner_ID");
        final String glItemId = params.getString("c_glitem_id");
        BigDecimal creditUsed = BigDecimal.ZERO;
        BigDecimal rate = BigDecimal.ZERO;
        Double amount = new Double(0);
        if (strSetAmount && !"null".equals(strAmount)) {
            amount = Double.parseDouble(strAmount);
        }

        if (strUseDefaultConversion && !strSetAmount) {
            rate = getConversionRate(strOrgId, strFromCurrencyId, strToCurrencyId);
            if (rate == BigDecimal.ZERO && !strFromCurrencyId.equals(strToCurrencyId)) {
                try {
                    jsonRequest = new JSONObject();
                    String message = OBMessageUtils.messageBD("NoCurrencyConversion");
                    JSONObject errorMessage = new JSONObject();
                    errorMessage.put("severity", "error");
                    errorMessage.put("text", message);
                    jsonRequest.put("message", errorMessage);
                } catch (Exception e) {
                    OBDal.getInstance().rollbackAndClose();
                    log.error(e.getMessage(), e);
                }
                return jsonRequest;
            }
        } else {
            rate = "null".equals(strRate) ? BigDecimal.ZERO : BigDecimal.valueOf(Double.parseDouble(strRate));
        }
        BusinessPartner businessPartner = OBDal.getInstance().get(BusinessPartner.class, strBpartnerId);
        creditUsed = businessPartner.getCreditUsed();

        ScrollableResults scroll = null;
        GLItem glItem = OBDal.getInstance().get(GLItem.class, glItemId);
        Currency currency = OBDal.getInstance().get(Currency.class, strToCurrencyId);
        BigDecimal creditAmount = BigDecimal.ZERO;
        BigDecimal creditRate = BigDecimal.ONE;

        // Convert available credit automatically
        if (!StringUtils.equals(strFromCurrencyId, strToCurrencyId) && !StringUtils.isEmpty(glItemId)
                && !StringUtils.equals(glItemId, "null")) {

            // Get the rate
            if (!strSetAmount) {
                creditRate = rate;
            } else if (creditUsed.compareTo(BigDecimal.ZERO) != 0) {
                creditRate = BigDecimal.valueOf(amount).divide(creditUsed,
                        FIN_Utility.getConversionRatePrecision(RequestContext.get().getVariablesSecureApp()),
                        RoundingMode.HALF_UP);
            }

            // Loop through all payment documents which generate credit
            scroll = FinancialUtils.getPaymentsWithCredit(businessPartner.getId(), strFromCurrencyId);
            int i = 0;
            try {
                while (scroll.next()) {
                    final String paymentCreditId = (String) scroll.get()[0];
                    final FIN_Payment paymentCredit = OBDal.getInstance().get(FIN_Payment.class,
                            paymentCreditId);
                    creditAmount = paymentCredit.getGeneratedCredit().subtract(paymentCredit.getUsedCredit());

                    // Create a payment to consume the credit with a glitem
                    FIN_Payment payment1 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment1.setPaymentDate(new Date());
                    payment1.setAmount(creditAmount);
                    payment1.setDocumentNo(FIN_Utility.getDocumentNo(payment1.getOrganization(),
                            payment1.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment1.setProcessed(false);
                    payment1.setPosted("N");
                    payment1.setDescription(null);
                    payment1.setGeneratedCredit(BigDecimal.ZERO);
                    payment1.setUsedCredit(BigDecimal.ZERO);

                    // Create a payment detail to consume the credit with a glitem
                    FIN_PaymentDetail paymentDetail1 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail1.setClient(paymentCredit.getClient());
                    paymentDetail1.setOrganization(paymentCredit.getOrganization());
                    paymentDetail1.setFinPayment(payment1);
                    paymentDetail1.setAmount(creditAmount);
                    paymentDetail1.setRefund(false);
                    paymentDetail1.setGLItem(glItem);
                    paymentDetail1.setPrepayment(false);

                    // Create a payment schedule detail to consume the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail1 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail1.setClient(paymentCredit.getClient());
                    paymentScheduleDetail1.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail1.setPaymentDetails(paymentDetail1);
                    paymentScheduleDetail1.setAmount(creditAmount);

                    // Process the payment
                    paymentDetail1.getFINPaymentScheduleDetailList().add(paymentScheduleDetail1);
                    payment1.getFINPaymentDetailList().add(paymentDetail1);
                    OBDal.getInstance().save(payment1);
                    OBDal.getInstance().save(paymentDetail1);
                    OBDal.getInstance().save(paymentScheduleDetail1);
                    FIN_PaymentProcess.doProcessPayment(payment1, "D", false, null, null);

                    // Modify description of original credit payment
                    String paymentCreditDesc = paymentCredit.getDescription() + "\n" + String.format(
                            OBMessageUtils.messageBD("APRM_CreditUsedPayment"), payment1.getDocumentNo());
                    paymentCredit.setDescription((paymentCreditDesc.length() > 255)
                            ? paymentCreditDesc.substring(0, 251).concat("...").toString()
                            : paymentCreditDesc.toString());

                    // Create a payment to refund the credit
                    FIN_Payment payment2 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment2.setPaymentDate(new Date());
                    payment2.setAmount(creditAmount.negate());
                    payment2.setDocumentNo(FIN_Utility.getDocumentNo(payment2.getOrganization(),
                            payment2.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment2.setProcessed(false);
                    payment2.setPosted("N");
                    payment2.setDescription(
                            OBMessageUtils.messageBD("APRM_RefundPayment") + ": " + payment1.getDocumentNo());
                    payment2.setGeneratedCredit(BigDecimal.ZERO);
                    payment2.setUsedCredit(creditAmount);

                    // Create a payment credit to refund the credit
                    FIN_Payment_Credit paymentCredit2 = OBProvider.getInstance().get(FIN_Payment_Credit.class);
                    paymentCredit2.setClient(paymentCredit.getClient());
                    paymentCredit2.setOrganization(paymentCredit.getOrganization());
                    paymentCredit2.setPayment(payment2);
                    paymentCredit2.setCreditPaymentUsed(paymentCredit);
                    paymentCredit2.setAmount(creditAmount);
                    paymentCredit2.setCurrency(paymentCredit.getCurrency());

                    // Create a payment detail to refund the credit
                    FIN_PaymentDetail paymentDetail2 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail2.setClient(paymentCredit.getClient());
                    paymentDetail2.setOrganization(paymentCredit.getOrganization());
                    paymentDetail2.setFinPayment(payment2);
                    paymentDetail2.setAmount(creditAmount.negate());
                    paymentDetail2.setRefund(true);
                    paymentDetail2.setPrepayment(true);

                    // Create a payment schedule detail to refund the credit
                    FIN_PaymentScheduleDetail paymentScheduleDetail2 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail2.setClient(paymentCredit.getClient());
                    paymentScheduleDetail2.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail2.setPaymentDetails(paymentDetail2);
                    paymentScheduleDetail2.setAmount(creditAmount.negate());

                    // Process the payment
                    paymentDetail2.getFINPaymentScheduleDetailList().add(paymentScheduleDetail2);
                    payment2.getFINPaymentDetailList().add(paymentDetail2);
                    payment2.getFINPaymentCreditList().add(paymentCredit2);
                    paymentCredit.setUsedCredit(creditAmount);
                    OBDal.getInstance().save(paymentCredit);
                    OBDal.getInstance().save(payment2);
                    OBDal.getInstance().save(paymentCredit2);
                    OBDal.getInstance().save(paymentDetail2);
                    OBDal.getInstance().save(paymentScheduleDetail2);
                    FIN_PaymentProcess.doProcessPayment(payment2, "D", false, null, null);

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

                // Set the new currency
                businessPartner.setCurrency(currency);

                // Loop through all payment documents which generate credit
                scroll.beforeFirst();
                i = 0;
                while (scroll.next()) {
                    final String paymentCreditId = (String) scroll.get()[0];
                    final FIN_Payment paymentCredit = OBDal.getInstance().get(FIN_Payment.class,
                            paymentCreditId);

                    // Create a payment to create the credit with a glitem
                    FIN_Payment payment3 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment3.setPaymentDate(new Date());
                    payment3.setCurrency(currency);
                    payment3.setAmount(BigDecimal.ZERO);
                    payment3.setDocumentNo(FIN_Utility.getDocumentNo(payment3.getOrganization(),
                            payment3.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment3.setProcessed(false);
                    payment3.setPosted("N");
                    payment3.setDescription(null);
                    final BigDecimal generatedCredit = creditAmount.multiply(creditRate)
                            .setScale(currency.getStandardPrecision().intValue(), RoundingMode.HALF_UP);
                    payment3.setGeneratedCredit(generatedCredit);
                    payment3.setUsedCredit(BigDecimal.ZERO);

                    // Create a payment detail to create the credit with a glitem
                    FIN_PaymentDetail paymentDetail3 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail3.setClient(paymentCredit.getClient());
                    paymentDetail3.setOrganization(paymentCredit.getOrganization());
                    paymentDetail3.setFinPayment(payment3);
                    paymentDetail3.setAmount(generatedCredit);
                    paymentDetail3.setRefund(false);
                    paymentDetail3.setPrepayment(true);

                    // Create a payment detail to create the credit with a glitem
                    FIN_PaymentDetail paymentDetail4 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail4.setClient(paymentCredit.getClient());
                    paymentDetail4.setOrganization(paymentCredit.getOrganization());
                    paymentDetail4.setFinPayment(payment3);
                    paymentDetail4.setAmount(generatedCredit.negate());
                    paymentDetail4.setGLItem(glItem);
                    paymentDetail4.setRefund(false);
                    paymentDetail4.setPrepayment(false);

                    // Create a payment schedule detail to create the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail3 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail3.setClient(paymentCredit.getClient());
                    paymentScheduleDetail3.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail3.setPaymentDetails(paymentDetail3);
                    paymentScheduleDetail3.setAmount(generatedCredit);

                    // Create a payment schedule detail to create the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail4 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail4.setClient(paymentCredit.getClient());
                    paymentScheduleDetail4.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail4.setPaymentDetails(paymentDetail4);
                    paymentScheduleDetail4.setAmount(generatedCredit.negate());

                    // Process the payment
                    paymentDetail3.getFINPaymentScheduleDetailList().add(paymentScheduleDetail3);
                    paymentDetail4.getFINPaymentScheduleDetailList().add(paymentScheduleDetail4);
                    payment3.getFINPaymentDetailList().add(paymentDetail3);
                    payment3.getFINPaymentDetailList().add(paymentDetail4);
                    OBDal.getInstance().save(payment3);
                    OBDal.getInstance().save(paymentDetail3);
                    OBDal.getInstance().save(paymentDetail4);
                    OBDal.getInstance().save(paymentScheduleDetail3);
                    OBDal.getInstance().save(paymentScheduleDetail4);
                    OBDal.getInstance().save(paymentCredit);
                    FIN_PaymentProcess.doProcessPayment(payment3, "D", false, null, null);

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

        if (strSetAmount && creditUsed.compareTo(BigDecimal.valueOf(amount)) != 0) {
            businessPartner.setCreditUsed(BigDecimal.valueOf(amount));
        }
        if (!strToCurrencyId.equals(strFromCurrencyId) && strToCurrencyId != null
                && !"null".equals(strToCurrencyId)) {
            businessPartner.setCurrency(OBDal.getInstance().get(Currency.class, strToCurrencyId));
            if (rate.compareTo(BigDecimal.ZERO) != 0 && creditUsed.compareTo(BigDecimal.ZERO) != 0
                    && !strSetAmount) {
                businessPartner.setCreditUsed(creditUsed.multiply(rate));
            }
        }

        String messageText = OBMessageUtils.messageBD("CurrencyUpdated");
        JSONObject msg = new JSONObject();
        msg.put("severity", "success");
        msg.put("text", OBMessageUtils.parseTranslation(messageText));
        jsonRequest.put("message", msg);

    } catch (Exception e) {
        OBDal.getInstance().rollbackAndClose();
        log.error("Error in set new currency Action Handler", e);

        try {
            jsonRequest = new JSONObject();
            Throwable ex = DbUtility.getUnderlyingSQLException(e);
            String message = OBMessageUtils.translateError(ex.getMessage()).getMessage();
            JSONObject errorMessage = new JSONObject();
            errorMessage.put("severity", "error");
            errorMessage.put("text", message);
            jsonRequest.put("message", errorMessage);
        } catch (Exception e2) {
            log.error(e.getMessage(), e2);
            // do nothing, give up
        }
    } finally {
        OBContext.restorePreviousMode();
    }
    return jsonRequest;
}

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

License:Open Source License

@Override
protected void getRelatedTransactionsByAlgorithm() {
    // Search all transactions after the date of the adjusted line and recalculate the costs of them
    // to adjust differences
    MaterialTransaction basetrx = getTransaction();
    // Transactions of closing inventories are managed by generic CostAdjustmentProcess adjusting
    // the cost of the related opening inventory.
    if (basetrx.getPhysicalInventoryLine() != null
            && basetrx.getPhysicalInventoryLine().getRelatedInventory() != null) {
        return;// ww w.j ava  2 s  . c  o m
    }
    BigDecimal signMultiplier = new BigDecimal(basetrx.getMovementQuantity().signum());
    Date trxDate = basetrx.getTransactionProcessDate();

    BigDecimal adjustmentBalance = BigDecimal.ZERO;
    BigDecimal unitCostAdjustmentBalance = BigDecimal.ZERO;
    // Initialize adjustment balance looping through all cost adjustment lines of current
    // transaction.
    log.debug("Initialize adjustment balance");
    CostAdjustmentLine baseCAL = getCostAdjLine();
    for (CostAdjustmentLine costAdjLine : getTrxAdjustmentLines(basetrx)) {
        if (costAdjLine.isSource() && !costAdjLine.isRelatedTransactionAdjusted()
                && !costAdjLine.getId().equals(strCostAdjLineId)) {
            searchRelatedTransactionCosts(costAdjLine);
        }

        costAdjLine.setRelatedTransactionAdjusted(Boolean.TRUE);
        if (!costAdjLine.getId().equals(strCostAdjLineId)) {
            costAdjLine.setParentCostAdjustmentLine(baseCAL);
        }
        OBDal.getInstance().save(costAdjLine);
        // If the cost adjustment line has Transaction Costs those adjustment amount are included
        // in the Current Value Amount and not in the Adjustment Balance
        if (!costAdjLine.getTransactionCostList().isEmpty()) {
            continue;
        }
        BigDecimal adjustmentAmt = costAdjLine.getAdjustmentAmount();
        if (!strCostCurrencyId.equals(costAdjLine.getCurrency().getId())) {
            adjustmentAmt = FinancialUtils.getConvertedAmount(adjustmentAmt, costAdjLine.getCurrency(),
                    getCostCurrency(), costAdjLine.getAccountingDate(), getCostOrg(),
                    FinancialUtils.PRECISION_STANDARD);
        }
        adjustmentBalance = adjustmentBalance.add(adjustmentAmt.multiply(signMultiplier));
        if (costAdjLine.isUnitCost()) {
            unitCostAdjustmentBalance = unitCostAdjustmentBalance.add(adjustmentAmt);
        }
    }

    // Initialize current stock qty and value amt.
    BigDecimal currentStock = CostAdjustmentUtils.getStockOnTransactionDate(getCostOrg(), basetrx,
            getCostDimensions(), isManufacturingProduct, areBackdatedTrxFixed);
    BigDecimal currentValueAmt = CostAdjustmentUtils.getValuedStockOnTransactionDate(getCostOrg(), basetrx,
            getCostDimensions(), isManufacturingProduct, areBackdatedTrxFixed, getCostCurrency());
    log.debug(
            "Adjustment balance: " + adjustmentBalance.toPlainString() + ", current stock {}, current value {}",
            currentStock.toPlainString(), currentValueAmt.toPlainString());

    // Initialize current unit cost including the cost adjustments.
    Costing costing = AverageAlgorithm.getProductCost(trxDate, basetrx.getProduct(), getCostDimensions(),
            getCostOrg());
    if (costing == null) {
        throw new OBException("@NoAvgCostDefined@ @Organization@: " + getCostOrg().getName() + ", @Product@: "
                + basetrx.getProduct().getName() + ", @Date@: " + OBDateUtils.formatDate(trxDate));
    }
    BigDecimal cost = null;
    // If current stock is zero the cost is not modified until a related transaction that modifies
    // the stock is found.
    if (currentStock.signum() != 0) {
        cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission,
                RoundingMode.HALF_UP);
    }
    log.debug("Starting average cost {}", cost == null ? "not cost" : cost.toPlainString());
    if (cost != null && (AverageAlgorithm.modifiesAverage(trxType) || !baseCAL.isBackdatedTrx())) {
        BigDecimal trxUnitCost = CostAdjustmentUtils.getTrxCost(basetrx, true, getCostCurrency());
        BigDecimal trxPrice = null;
        if (basetrx.getMovementQuantity().signum() == 0) {
            trxPrice = BigDecimal.ZERO;
        } else {
            trxPrice = trxUnitCost.add(unitCostAdjustmentBalance).divide(basetrx.getMovementQuantity().abs(),
                    costCurPrecission, RoundingMode.HALF_UP);
        }
        if (checkNegativeStockCorrection && currentStock.compareTo(basetrx.getMovementQuantity()) < 0
                && cost.compareTo(trxPrice) != 0 && !baseCAL.isNegativeStockCorrection()
                && AverageAlgorithm.modifiesAverage(trxType)) {
            // stock was negative and cost different than trx price then Negative Stock Correction
            // is added
            BigDecimal trxSignMultiplier = new BigDecimal(basetrx.getMovementQuantity().signum());
            BigDecimal negCorrAmt = trxPrice.multiply(currentStock)
                    .setScale(stdCurPrecission, RoundingMode.HALF_UP).subtract(currentValueAmt)
                    .subtract(adjustmentBalance);
            adjustmentBalance = adjustmentBalance.add(negCorrAmt.multiply(trxSignMultiplier));
            // If there is a difference insert a cost adjustment line.
            CostAdjustmentLine newCAL = insertCostAdjustmentLine(basetrx, negCorrAmt, null);
            newCAL.setNegativeStockCorrection(Boolean.TRUE);
            newCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
            newCAL.setUnitCost(Boolean.FALSE);
            OBDal.getInstance().save(newCAL);
            cost = trxPrice;
            log.debug("Negative stock correction. Amount: {}, new cost {}", negCorrAmt.toPlainString(),
                    cost.toPlainString());
        }
        if (basetrx.getMaterialMgmtCostingList().size() == 0) {
            Date newDate = new Date();
            Date dateTo = costing.getEndingDate();
            costing.setEndingDate(newDate);
            OBDal.getInstance().save(costing);
            Costing newCosting = OBProvider.getInstance().get(Costing.class);
            newCosting.setCost(cost);
            newCosting.setCurrency(
                    (Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, strCostCurrencyId));
            newCosting.setStartingDate(newDate);
            newCosting.setEndingDate(dateTo);
            newCosting.setInventoryTransaction(basetrx);
            newCosting.setProduct(basetrx.getProduct());
            if (isManufacturingProduct) {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, "0"));
            } else {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, strCostOrgId));
            }
            newCosting.setQuantity(basetrx.getMovementQuantity());
            newCosting.setTotalMovementQuantity(currentStock);
            newCosting.setPrice(cost);
            newCosting.setCostType("AVA");
            newCosting.setManual(Boolean.FALSE);
            newCosting.setPermanent(Boolean.TRUE);
            newCosting.setProduction(trxType == TrxType.ManufacturingProduced);
            newCosting.setWarehouse((Warehouse) getCostDimensions().get(CostDimension.Warehouse));
            OBDal.getInstance().save(newCosting);
            OBDal.getInstance().flush();
        } else {
            Costing curCosting = basetrx.getMaterialMgmtCostingList().get(0);

            if (curCosting.getCost().compareTo(cost) != 0
                    || curCosting.getTotalMovementQuantity().compareTo(currentStock) != 0) {
                curCosting.setPermanent(Boolean.FALSE);
                OBDal.getInstance().save(curCosting);
                OBDal.getInstance().flush();
                // Update existing costing
                if (curCosting.getCost().compareTo(cost) != 0) {
                    if (curCosting.getOriginalCost() == null) {
                        curCosting.setOriginalCost(curCosting.getCost());
                    }
                    curCosting.setCost(cost);
                    curCosting.setPrice(trxPrice);
                }
                curCosting.setTotalMovementQuantity(currentStock);
                curCosting.setPermanent(Boolean.TRUE);
                OBDal.getInstance().flush();
                OBDal.getInstance().save(curCosting);
            }
        }
    }

    // Modify isManufacturingProduct flag in case it has changed at some point.
    isManufacturingProduct = ((String) DalUtil.getId(costing.getOrganization())).equals("0");

    ScrollableResults trxs = getRelatedTransactions();
    String strCurrentCurId = strCostCurrencyId;
    try {
        while (trxs.next()) {
            MaterialTransaction trx = (MaterialTransaction) trxs.get()[0];
            log.debug("Process related transaction {}", trx.getIdentifier());
            BigDecimal trxSignMultiplier = new BigDecimal(trx.getMovementQuantity().signum());
            BigDecimal trxAdjAmt = BigDecimal.ZERO;
            BigDecimal trxUnitCostAdjAmt = BigDecimal.ZERO;
            if (StringUtils.isNotEmpty(bdCostingId) && !isBackdatedTransaction(trx)) {
                // If there is a backdated source adjustment pending modify the dates of its m_costing.
                updateBDCostingTimeRange(trx);
                // This update is done only on the first related transaction.
                bdCostingId = "";
            }

            if (!strCurrentCurId.equals(trx.getCurrency().getId())) {
                Currency curCurrency = OBDal.getInstance().get(Currency.class, strCurrentCurId);
                Organization costOrg = getCostOrg();

                currentValueAmt = FinancialUtils.getConvertedAmount(currentValueAmt, curCurrency,
                        trx.getCurrency(), trx.getMovementDate(), costOrg, FinancialUtils.PRECISION_STANDARD);
                if (cost != null) {
                    cost = FinancialUtils.getConvertedAmount(cost, curCurrency, trx.getCurrency(),
                            trx.getMovementDate(), costOrg, FinancialUtils.PRECISION_COSTING);
                }

                strCurrentCurId = trx.getCurrency().getId();
            }

            List<CostAdjustmentLine> existingAdjLines = getTrxAdjustmentLines(trx);
            for (CostAdjustmentLine existingCAL : existingAdjLines) {
                if (existingCAL.isSource() && !existingCAL.isRelatedTransactionAdjusted()) {
                    searchRelatedTransactionCosts(existingCAL);
                }
                if (existingCAL.getTransactionCostList().isEmpty()
                        && !existingCAL.isRelatedTransactionAdjusted()) {
                    BigDecimal adjustmentAmt = existingCAL.getAdjustmentAmount();
                    if (!strCurrentCurId.equals(existingCAL.getCurrency().getId())) {
                        Currency curCurrency = OBDal.getInstance().get(Currency.class, strCurrentCurId);
                        adjustmentAmt = FinancialUtils.getConvertedAmount(adjustmentAmt,
                                existingCAL.getCurrency(), curCurrency, existingCAL.getAccountingDate(),
                                getCostOrg(), FinancialUtils.PRECISION_STANDARD);
                    }
                    trxAdjAmt = trxAdjAmt.add(adjustmentAmt);
                    adjustmentBalance = adjustmentBalance.add(adjustmentAmt.multiply(trxSignMultiplier));
                    if (existingCAL.isUnitCost()) {
                        trxUnitCostAdjAmt = trxUnitCostAdjAmt.add(adjustmentAmt);
                    }
                }

                existingCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
                existingCAL.setParentCostAdjustmentLine((CostAdjustmentLine) OBDal.getInstance()
                        .getProxy(CostAdjustmentLine.ENTITY_NAME, strCostAdjLineId));

                OBDal.getInstance().save(existingCAL);
            }
            log.debug("Current trx adj amount of existing CALs {}", trxAdjAmt.toPlainString());

            BigDecimal trxCost = CostAdjustmentUtils.getTrxCost(trx, false,
                    OBDal.getInstance().get(Currency.class, strCurrentCurId));
            BigDecimal trxUnitCost = CostAdjustmentUtils.getTrxCost(trx, true,
                    OBDal.getInstance().get(Currency.class, strCurrentCurId));
            currentValueAmt = currentValueAmt.add(trxCost.multiply(trxSignMultiplier));
            currentStock = currentStock.add(trx.getMovementQuantity());
            log.debug("Updated current stock {} and, current value {}", currentStock.toPlainString(),
                    currentValueAmt.toPlainString());

            TrxType currentTrxType = TrxType.getTrxType(trx);

            if (AverageAlgorithm.modifiesAverage(currentTrxType)) {
                // Recalculate average, if current stock is zero the average is not modified
                if (currentStock.signum() != 0) {
                    cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission,
                            RoundingMode.HALF_UP);
                }
                if (cost == null) {
                    continue;
                }
                log.debug("New average cost: {}", cost.toPlainString());
                Costing curCosting = trx.getMaterialMgmtCostingList().get(0);
                BigDecimal trxPrice = null;
                if (trx.getMovementQuantity().signum() == 0) {
                    trxPrice = BigDecimal.ZERO;
                } else {
                    trxPrice = trxUnitCost.add(trxUnitCostAdjAmt).divide(trx.getMovementQuantity().abs(),
                            costCurPrecission, RoundingMode.HALF_UP);
                }

                if (checkNegativeStockCorrection && currentStock.compareTo(trx.getMovementQuantity()) < 0
                        && cost.compareTo(trxPrice) != 0) {
                    // stock was negative and cost different than trx price then Negative Stock Correction
                    // is added
                    BigDecimal negCorrAmt = trxPrice.multiply(currentStock)
                            .setScale(stdCurPrecission, RoundingMode.HALF_UP).subtract(currentValueAmt)
                            .subtract(adjustmentBalance);
                    adjustmentBalance = adjustmentBalance.add(negCorrAmt.multiply(trxSignMultiplier));
                    trxAdjAmt = trxAdjAmt.add(negCorrAmt.multiply(trxSignMultiplier));
                    // If there is a difference insert a cost adjustment line.
                    CostAdjustmentLine newCAL = insertCostAdjustmentLine(trx, negCorrAmt, null);
                    newCAL.setNegativeStockCorrection(Boolean.TRUE);
                    newCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
                    newCAL.setUnitCost(Boolean.FALSE);
                    OBDal.getInstance().save(newCAL);
                    cost = trxPrice;
                    log.debug("Negative stock correction. Amount: {}, new cost {}", negCorrAmt.toPlainString(),
                            cost.toPlainString());
                }

                if (curCosting.getCost().compareTo(cost) == 0 && StringUtils.isEmpty(bdCostingId)
                        && curCosting.getTotalMovementQuantity().compareTo(currentStock) == 0) {
                    // new cost hasn't changed and total movement qty is equal to current stock, following
                    // transactions will have the same cost, so no more
                    // related transactions are needed to include.
                    // If bdCosting is not empty it is needed to loop through the next related transaction
                    // to set the new time ringe of the costing.
                    log.debug("New cost matches existing cost. Adjustment finished.");
                    return;
                } else {
                    // Update existing costing
                    curCosting.setPermanent(Boolean.FALSE);
                    OBDal.getInstance().save(curCosting);
                    OBDal.getInstance().flush();
                    if (curCosting.getCost().compareTo(cost) != 0) {
                        if (curCosting.getOriginalCost() == null) {
                            curCosting.setOriginalCost(curCosting.getCost());
                        }
                        curCosting.setPrice(trxPrice);
                        curCosting.setCost(cost);
                    }
                    curCosting.setTotalMovementQuantity(currentStock);
                    curCosting.setPermanent(Boolean.TRUE);
                    OBDal.getInstance().save(curCosting);
                }
            } else if (cost != null && !isVoidedTrx(trx, currentTrxType)) {
                if (!trx.isCostPermanent()) {
                    // Check current trx unit cost matches new expected cost
                    BigDecimal expectedCost = cost.multiply(trx.getMovementQuantity().abs())
                            .setScale(stdCurPrecission, RoundingMode.HALF_UP);
                    BigDecimal unitCost = CostAdjustmentUtils.getTrxCost(trx, true,
                            OBDal.getInstance().get(Currency.class, strCurrentCurId));
                    unitCost = unitCost.add(trxAdjAmt);
                    log.debug("Is adjustment needed? Expected {} vs Current {}", expectedCost.toPlainString(),
                            unitCost.toPlainString());
                    if (expectedCost.compareTo(unitCost) != 0) {
                        trxAdjAmt = trxAdjAmt.add(expectedCost.subtract(unitCost).multiply(trxSignMultiplier));
                        trxUnitCostAdjAmt = trxUnitCostAdjAmt.add(expectedCost.subtract(unitCost));
                        adjustmentBalance = adjustmentBalance
                                .add(expectedCost.subtract(unitCost).multiply(trxSignMultiplier));
                        // If there is a difference insert a cost adjustment line.
                        CostAdjustmentLine newCAL = insertCostAdjustmentLine(trx,
                                expectedCost.subtract(unitCost), null);
                        newCAL.setRelatedTransactionAdjusted(Boolean.TRUE);
                        OBDal.getInstance().save(newCAL);
                        log.debug("Adjustment added. Amount {}.",
                                expectedCost.subtract(unitCost).toPlainString());
                    }
                }
                if (trx.getMaterialMgmtCostingList().size() != 0) {
                    Costing curCosting = trx.getMaterialMgmtCostingList().get(0);
                    if (currentStock.signum() != 0) {
                        cost = currentValueAmt.add(adjustmentBalance).divide(currentStock, costCurPrecission,
                                RoundingMode.HALF_UP);
                    }
                    BigDecimal trxPrice = null;
                    if (trx.getMovementQuantity().signum() == 0) {
                        trxPrice = BigDecimal.ZERO;
                    } else {
                        trxPrice = trxUnitCost.add(trxUnitCostAdjAmt).divide(trx.getMovementQuantity().abs(),
                                costCurPrecission, RoundingMode.HALF_UP);
                    }
                    if (curCosting.getCost().compareTo(cost) != 0
                            || curCosting.getTotalMovementQuantity().compareTo(currentStock) != 0) {
                        curCosting.setPermanent(Boolean.FALSE);
                        OBDal.getInstance().save(curCosting);
                        OBDal.getInstance().flush();
                        if (curCosting.getCost().compareTo(cost) != 0) {
                            if (curCosting.getOriginalCost() == null) {
                                curCosting.setOriginalCost(curCosting.getCost());
                            }
                            curCosting.setPrice(trxPrice);
                            curCosting.setCost(cost);
                        }
                        curCosting.setTotalMovementQuantity(currentStock);
                        curCosting.setPermanent(Boolean.TRUE);
                        OBDal.getInstance().save(curCosting);
                    }
                }
            }

            OBDal.getInstance().flush();
            OBDal.getInstance().getSession().clear();
        }
    } finally {
        trxs.close();
    }

    if (getCostingRule().getEndingDate() == null && cost != null) {
        // This is the current costing rule. Check if current average cost needs to be updated.
        Costing currentCosting = AverageAlgorithm.getProductCost(new Date(), basetrx.getProduct(),
                getCostDimensions(), getCostOrg());
        if (currentCosting == null) {
            throw new OBException("@NoAvgCostDefined@ @Organization@: " + getCostOrg().getName()
                    + ", @Product@: " + basetrx.getProduct().getName() + ", @Date@: "
                    + OBDateUtils.formatDate(new Date()));
        }
        if (currentCosting.getCost().compareTo(cost) != 0) {
            basetrx = getTransaction();
            Date newDate = new Date();
            Date dateTo = currentCosting.getEndingDate();
            currentCosting.setEndingDate(newDate);
            OBDal.getInstance().save(currentCosting);
            Costing newCosting = OBProvider.getInstance().get(Costing.class);
            newCosting.setCost(cost);
            newCosting.setCurrency(
                    (Currency) OBDal.getInstance().getProxy(Currency.ENTITY_NAME, strCurrentCurId));
            newCosting.setStartingDate(newDate);
            newCosting.setEndingDate(dateTo);
            newCosting.setInventoryTransaction(null);
            newCosting.setProduct(basetrx.getProduct());
            if (isManufacturingProduct) {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, "0"));
            } else {
                newCosting.setOrganization(
                        (Organization) OBDal.getInstance().getProxy(Organization.ENTITY_NAME, strCostOrgId));
            }
            newCosting.setQuantity(null);
            newCosting.setTotalMovementQuantity(currentStock);
            newCosting.setPrice(cost);
            newCosting.setCostType("AVA");
            newCosting.setManual(Boolean.FALSE);
            newCosting.setPermanent(Boolean.TRUE);
            newCosting.setProduction(trxType == TrxType.ManufacturingProduced);
            newCosting.setWarehouse((Warehouse) getCostDimensions().get(CostDimension.Warehouse));
            OBDal.getInstance().save(newCosting);
        }
    }
}

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  .jav 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 ww  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();
    }
}