Example usage for java.math BigDecimal compareTo

List of usage examples for java.math BigDecimal compareTo

Introduction

In this page you can find the example usage for java.math BigDecimal compareTo.

Prototype

@Override
public int compareTo(BigDecimal val) 

Source Link

Document

Compares this BigDecimal with the specified BigDecimal .

Usage

From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java

public int insertDiscDettoglTranfromwritechecks(GlTransaction glTransaction, Coaccount CoAccountIdaps,
        Coledgersource aColedgersource, BigDecimal TotalAmt) throws BankingException {
    int glTransationid = 0;
    glTransaction.setCoAccountId(CoAccountIdaps.getCoAccountId());
    glTransaction.setCoAccountNumber(CoAccountIdaps.getNumber());

    glTransaction.setDebit(new BigDecimal(0));
    glTransaction.setCredit(TotalAmt);/*  www.  j  ava2 s. co m*/

    if (TotalAmt.compareTo(BigDecimal.ZERO) > 0) {
        glTransationid = gltransactionService.saveGltransactionTable(glTransaction);
    }
    return glTransationid;
}

From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java

public int insertBankDettoglTranfromwritechecks(GlTransaction glTransaction, Coaccount CoAccountIdaps,
        Coledgersource aColedgersource, BigDecimal TotalAmt) throws BankingException {
    int glTransationid = 0;
    glTransaction.setCoAccountId(CoAccountIdaps.getCoAccountId());
    glTransaction.setCoAccountNumber(CoAccountIdaps.getNumber());

    glTransaction.setDebit(new BigDecimal(0));
    glTransaction.setCredit(TotalAmt);//from w w  w  .  jav a  2s .  co  m

    if (TotalAmt.compareTo(BigDecimal.ZERO) > 0) {
        glTransationid = gltransactionService.saveGltransactionTable(glTransaction);

    }

    return glTransationid;

}

From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java

public int insertaccApDettoglTranfromwritechecks(GlTransaction glTransaction, Coaccount CoAccountIdaps,
        Coledgersource aColedgersource, BigDecimal TotalAmt) throws BankingException {
    int glTransationid = 0;
    glTransaction.setCoAccountId(CoAccountIdaps.getCoAccountId());
    glTransaction.setCoAccountNumber(CoAccountIdaps.getNumber());

    glTransaction.setDebit(TotalAmt);//from  ww w .ja  v a2 s .co m
    glTransaction.setCredit(new BigDecimal(0));

    if (TotalAmt.compareTo(BigDecimal.ZERO) > 0) {
        glTransationid = gltransactionService.saveGltransactionTable(glTransaction);

    }

    return glTransationid;

}

From source file:org.ballerinalang.bre.bvm.BVM.java

public static boolean isDecimalWithinIntRange(BigDecimal decimalValue) {
    return decimalValue.compareTo(BINT_MAX_VALUE_BIG_DECIMAL_RANGE_MAX) < 0
            && decimalValue.compareTo(BINT_MIN_VALUE_BIG_DECIMAL_RANGE_MIN) > 0;
}

From source file:gov.guilin.dao.impl.ProductDaoImpl.java

public Page<Product> findPage(ProductCategory productCategory, Brand brand, Promotion promotion, List<Tag> tags,
        Map<Attribute, String> attributeValue, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable,
        Boolean isList, Boolean isTop, Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert,
        OrderType orderType, Pageable pageable, Set<Supplier> suppliers) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);//w ww.  j  av a 2  s  . co m
    Predicate restrictions = criteriaBuilder.conjunction();
    if (productCategory != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory),
                        criteriaBuilder.like(root.get("productCategory").<String>get("treePath"),
                                "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId()
                                        + ProductCategory.TREE_PATH_SEPARATOR + "%")));
    }
    if (brand != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("brand"), brand));
    }
    if (promotion != null) {
        Subquery<Product> subquery1 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot1 = subquery1.from(Product.class);
        subquery1.select(subqueryRoot1);
        subquery1.where(criteriaBuilder.equal(subqueryRoot1, root),
                criteriaBuilder.equal(subqueryRoot1.join("promotions"), promotion));

        Subquery<Product> subquery2 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot2 = subquery2.from(Product.class);
        subquery2.select(subqueryRoot2);
        subquery2.where(criteriaBuilder.equal(subqueryRoot2, root),
                criteriaBuilder.equal(subqueryRoot2.join("productCategory").join("promotions"), promotion));

        Subquery<Product> subquery3 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot3 = subquery3.from(Product.class);
        subquery3.select(subqueryRoot3);
        subquery3.where(criteriaBuilder.equal(subqueryRoot3, root),
                criteriaBuilder.equal(subqueryRoot3.join("brand").join("promotions"), promotion));

        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.exists(subquery1),
                criteriaBuilder.exists(subquery2), criteriaBuilder.exists(subquery3)));
    }
    if (tags != null && !tags.isEmpty()) {
        Subquery<Product> subquery = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot = subquery.from(Product.class);
        subquery.select(subqueryRoot);
        subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery));
    }
    if (attributeValue != null) {
        for (Entry<Attribute, String> entry : attributeValue.entrySet()) {
            String propertyName = Product.ATTRIBUTE_VALUE_PROPERTY_NAME_PREFIX
                    + entry.getKey().getPropertyIndex();
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.equal(root.get(propertyName), entry.getValue()));
        }
    }
    if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) {
        BigDecimal temp = startPrice;
        startPrice = endPrice;
        endPrice = temp;
    }
    if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.ge(root.<Number>get("price"), startPrice));
    }
    if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.le(root.<Number>get("price"), endPrice));
    }
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isMarketable"), isMarketable));
    }
    if (isList != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList));
    }
    if (isTop != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop));
    }
    if (isGift != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift));
    }
    Path<Integer> stock = root.get("stock");
    Path<Integer> allocatedStock = root.get("allocatedStock");
    if (isOutOfStock != null) {
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (isStockAlert != null) {
        Setting setting = SettingUtils.get();
        if (isStockAlert) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))));
        }
    }

    //??ADDbyDanielChen 20140502
    if ((suppliers != null) && !(suppliers.isEmpty())) {
        Expression<Supplier> exp = root.get("supplier");
        restrictions = criteriaBuilder.and(restrictions, exp.in(suppliers));
    }

    criteriaQuery.where(restrictions);
    List<Order> orders = pageable.getOrders();
    if (orderType == OrderType.priceAsc) {
        orders.add(Order.asc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.priceDesc) {
        orders.add(Order.desc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.salesDesc) {
        orders.add(Order.desc("sales"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.scoreDesc) {
        orders.add(Order.desc("score"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.dateDesc) {
        orders.add(Order.desc("createDate"));
    } else {
        orders.add(Order.desc("isTop"));
        orders.add(Order.desc("modifyDate"));
    }
    return super.findPage(criteriaQuery, pageable);
}

From source file:com.gst.portfolio.loanproduct.serialization.LoanProductDataValidator.java

private void validateGuaranteeParams(final JsonElement element, final DataValidatorBuilder baseDataValidator,
        final LoanProduct loanProduct) {
    BigDecimal mandatoryGuarantee = BigDecimal.ZERO;
    BigDecimal minimumGuaranteeFromOwnFunds = BigDecimal.ZERO;
    BigDecimal minimumGuaranteeFromGuarantor = BigDecimal.ZERO;
    if (loanProduct != null) {
        mandatoryGuarantee = loanProduct.getLoanProductGuaranteeDetails().getMandatoryGuarantee();
        minimumGuaranteeFromOwnFunds = loanProduct.getLoanProductGuaranteeDetails()
                .getMinimumGuaranteeFromOwnFunds();
        minimumGuaranteeFromGuarantor = loanProduct.getLoanProductGuaranteeDetails()
                .getMinimumGuaranteeFromGuarantor();
    }//from  w  ww  .  j a v a 2 s  . c om

    if (loanProduct == null || this.fromApiJsonHelper
            .parameterExists(LoanProductConstants.mandatoryGuaranteeParamName, element)) {
        mandatoryGuarantee = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(LoanProductConstants.mandatoryGuaranteeParamName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.mandatoryGuaranteeParamName)
                .value(mandatoryGuarantee).notNull();
        if (mandatoryGuarantee == null) {
            mandatoryGuarantee = BigDecimal.ZERO;
        }
    }

    if (loanProduct == null || this.fromApiJsonHelper
            .parameterExists(LoanProductConstants.minimumGuaranteeFromGuarantorParamName, element)) {
        minimumGuaranteeFromGuarantor = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(
                LoanProductConstants.minimumGuaranteeFromGuarantorParamName, element);
        if (minimumGuaranteeFromGuarantor == null) {
            minimumGuaranteeFromGuarantor = BigDecimal.ZERO;
        }
    }

    if (loanProduct == null || this.fromApiJsonHelper
            .parameterExists(LoanProductConstants.minimumGuaranteeFromOwnFundsParamName, element)) {
        minimumGuaranteeFromOwnFunds = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(
                LoanProductConstants.minimumGuaranteeFromOwnFundsParamName, element);
        if (minimumGuaranteeFromOwnFunds == null) {
            minimumGuaranteeFromOwnFunds = BigDecimal.ZERO;
        }
    }

    if (mandatoryGuarantee.compareTo(minimumGuaranteeFromOwnFunds.add(minimumGuaranteeFromGuarantor)) == -1) {
        baseDataValidator.parameter(LoanProductConstants.mandatoryGuaranteeParamName)
                .failWithCode("must.be.greter.than.sum.of.min.funds");
    }

}

From source file:com.gst.portfolio.loanaccount.serialization.LoanApplicationCommandFromApiJsonHelper.java

public void validateLoanMultiDisbursementdate(final JsonElement element,
        final DataValidatorBuilder baseDataValidator, LocalDate expectedDisbursement,
        BigDecimal totalPrincipal) {

    this.validateDisbursementsAreDatewiseOrdered(element, baseDataValidator);

    final JsonObject topLevelJsonElement = element.getAsJsonObject();
    final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement);
    final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement);
    if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.disbursementDataParameterName, element)
            && expectedDisbursement != null && totalPrincipal != null) {
        BigDecimal tatalDisbursement = BigDecimal.ZERO;
        boolean isFirstinstallmentOnExpectedDisbursementDate = false;
        final JsonArray variationArray = this.fromApiJsonHelper
                .extractJsonArrayNamed(LoanApiConstants.disbursementDataParameterName, element);
        List<LocalDate> expectedDisbursementDates = new ArrayList<>();
        if (variationArray != null && variationArray.size() > 0) {
            int i = 0;
            do {/*from   ww  w. ja  v  a2 s  . co  m*/
                final JsonObject jsonObject = variationArray.get(i).getAsJsonObject();
                if (jsonObject.has(LoanApiConstants.disbursementDateParameterName)
                        && jsonObject.has(LoanApiConstants.disbursementPrincipalParameterName)) {
                    LocalDate expectedDisbursementDate = this.fromApiJsonHelper.extractLocalDateNamed(
                            LoanApiConstants.disbursementDateParameterName, jsonObject, dateFormat, locale);
                    if (expectedDisbursementDates.contains(expectedDisbursementDate)) {
                        baseDataValidator.reset().parameter(LoanApiConstants.disbursementDateParameterName)
                                .failWithCode(LoanApiConstants.DISBURSEMENT_DATE_UNIQUE_ERROR);
                    }
                    if (expectedDisbursementDate.isBefore(expectedDisbursement)) {
                        baseDataValidator.reset().parameter(LoanApiConstants.disbursementDataParameterName)
                                .failWithCode(LoanApiConstants.DISBURSEMENT_DATE_BEFORE_ERROR);
                    }
                    expectedDisbursementDates.add(expectedDisbursementDate);

                    BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalNamed(
                            LoanApiConstants.disbursementPrincipalParameterName, jsonObject, locale);
                    baseDataValidator.reset().parameter(LoanApiConstants.disbursementDataParameterName)
                            .parameterAtIndexArray(LoanApiConstants.disbursementPrincipalParameterName, i)
                            .value(principal).notBlank();
                    if (principal != null) {
                        tatalDisbursement = tatalDisbursement.add(principal);
                    }

                    baseDataValidator.reset().parameter(LoanApiConstants.disbursementDataParameterName)
                            .parameterAtIndexArray(LoanApiConstants.disbursementDateParameterName, i)
                            .value(expectedDisbursementDate).notNull();

                    if (expectedDisbursement.equals(expectedDisbursementDate)) {
                        isFirstinstallmentOnExpectedDisbursementDate = true;
                    }

                }
                i++;
            } while (i < variationArray.size());
            if (!isFirstinstallmentOnExpectedDisbursementDate) {
                baseDataValidator.reset().parameter(LoanApiConstants.disbursementDateParameterName)
                        .failWithCode(LoanApiConstants.DISBURSEMENT_DATE_START_WITH_ERROR);
            }

            if (tatalDisbursement.compareTo(totalPrincipal) == 1) {
                baseDataValidator.reset().parameter(LoanApiConstants.disbursementPrincipalParameterName)
                        .failWithCode(LoanApiConstants.APPROVED_AMOUNT_IS_LESS_THAN_SUM_OF_TRANCHES);
            }
            final String interestTypeParameterName = "interestType";
            final Integer interestType = this.fromApiJsonHelper
                    .extractIntegerSansLocaleNamed(interestTypeParameterName, element);
            baseDataValidator.reset().parameter(interestTypeParameterName).value(interestType).ignoreIfNull()
                    .integerSameAsNumber(InterestMethod.DECLINING_BALANCE.getValue());

        }

    }

}

From source file:com.nkapps.billing.dao.OverpaymentDaoImpl.java

private void returnStateRevert(Session session, BankStatement bs, BigDecimal overpaymentSum,
        Long issuerSerialNumber, String issuerIp, LocalDateTime dateTime) throws Exception {
    if (!bs.getBankStatementPayments().isEmpty()) { // if bankstatement has payments
        String q = " SELECT p.id AS id, p.tin AS tin, p.paymentNum AS paymentNum, p.paymentDate AS paymentDate,"
                + "  p.paymentSum AS paymentSum, p.sourceCode AS sourceCode,"
                + " p.state AS state, p.tinDebtor as tinDebtor,p.claim as claim, p.issuerSerialNumber as issuerSerialNumber,"
                + " p.issuerIp as issuerIp,p.dateCreated AS dateCreated, p.dateUpdated as dateUpdated, "
                + " p.paymentSum - COALESCE((SELECT SUM(paidSum) FROM KeyPayment kp WHERE kp.payment = p),0) AS overSum "
                + " FROM Payment p JOIN p.bankStatementPayment bsp " + " WHERE p.claim = 0 "
                + " AND bsp.id.bankStatement = :bs" + " ORDER BY p.paymentDate, p.paymentNum ";
        Query query = session.createQuery(q);
        query.setParameter("bs", bs);
        query.setResultTransformer(Transformers.aliasToBean(Payment.class));
        List<Payment> paymentList = query.list();

        int listSize = paymentList.size();
        int currentIndex = 0;
        BigDecimal keyCost = new BigDecimal(bankStatementDao.getKeyCost());

        for (Payment payment : paymentList) {
            currentIndex++;/*from w  w w .  j av a2s  .  c o  m*/

            overpaymentSum = overpaymentSum.subtract(payment.getOverSum());

            if (currentIndex == listSize) {
                if (payment.getState() == 3) {
                    if (payment.getPaymentSum().compareTo(BigDecimal.ZERO) > 0) {
                        payment.setState((short) 2);
                    } else {
                        payment.setState((short) 1);
                    }
                }
                payment.setPaymentSum(payment.getPaymentSum().add(overpaymentSum));
                payment.setIssuerSerialNumber(issuerSerialNumber);
                payment.setIssuerIp(issuerIp);
                payment.setDateUpdated(dateTime);

                session.update(payment);

                overpaymentSum = BigDecimal.ZERO;

            } else {
                if (payment.getPaymentSum().compareTo(keyCost) < 0) {

                    BigDecimal paymentSum = payment.getPaymentSum();

                    if (overpaymentSum.add(paymentSum).compareTo(keyCost) <= 0) {
                        if (payment.getState() == 3) {
                            if (payment.getPaymentSum().compareTo(BigDecimal.ZERO) > 0) {
                                payment.setState((short) 2);
                            } else {
                                payment.setState((short) 1);
                            }
                        }
                        payment.setPaymentSum(overpaymentSum.add(paymentSum));
                        payment.setIssuerSerialNumber(issuerSerialNumber);
                        payment.setIssuerIp(issuerIp);
                        payment.setDateUpdated(dateTime);

                        session.update(payment);

                        overpaymentSum = BigDecimal.ZERO;
                    } else {
                        if (payment.getState() == 3) {
                            if (payment.getPaymentSum().compareTo(BigDecimal.ZERO) > 0) {
                                payment.setState((short) 2);
                            } else {
                                payment.setState((short) 1);
                            }
                        }
                        payment.setPaymentSum(keyCost);
                        payment.setIssuerSerialNumber(issuerSerialNumber);
                        payment.setIssuerIp(issuerIp);
                        payment.setDateUpdated(dateTime);

                        session.update(payment);

                        overpaymentSum = overpaymentSum.add(paymentSum).subtract(keyCost);
                    }
                }
            }

            if (overpaymentSum.compareTo(BigDecimal.ZERO) <= 0) {
                break;
            }
        }
    }
}

From source file:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java

private void insertFees(final LockHandler lockHandler, final Transfer transfer, final boolean forced,
        final BigDecimal originalAmount, final boolean simulation, final Set<ChargedFee> chargedFees) {
    final TransferType transferType = transfer.getType();
    final Account from = transfer.getFrom();
    final Account to = transfer.getTo();
    final TransactionFeeQuery query = new TransactionFeeQuery();
    query.setTransferType(transferType);
    final List<? extends TransactionFee> fees = transactionFeeService.search(query);
    BigDecimal totalPercentage = BigDecimal.ZERO;
    BigDecimal feeTotalAmount = BigDecimal.ZERO;
    Transfer topMost = getTopMost(transfer);
    final Calendar date = topMost.getDate();
    transfer.setChildren(new ArrayList<Transfer>());
    for (final TransactionFee fee : fees) {
        final Account fromAccount = fetchService.fetch(from, Account.Relationships.TYPE,
                MemberAccount.Relationships.MEMBER);
        final Account toAccount = fetchService.fetch(to, Account.Relationships.TYPE,
                MemberAccount.Relationships.MEMBER);

        final ChargedFee key = new ChargedFee(fee, fromAccount, toAccount);
        if (chargedFees.contains(key)) {
            throw new ValidationException("payment.error.circularFees");
        }/*  w  w w . j a v a2  s .  co m*/
        chargedFees.add(key);

        // Build the fee transfer
        final BuildTransferWithFeesDTO params = new BuildTransferWithFeesDTO(date, fromAccount, toAccount,
                originalAmount, fee, false);
        // rate stuff; buildTransfer MUST have these set.
        params.setEmissionDate(transfer.getEmissionDate());
        params.setExpirationDate(transfer.getExpirationDate());
        final Transfer feeTransfer = transactionFeeService.buildTransfer(params);

        // If the fee transfer is null, the fee should not be applied
        if (feeTransfer == null) {
            continue;
        }
        // Ensure the last fee when 100% will be the exact amount left
        if (fee instanceof SimpleTransactionFee && fee.getAmount().isPercentage()) {
            final BigDecimal feeValue = fee.getAmount().getValue();
            // Only when it's not a single fee
            if (!(totalPercentage.equals(BigDecimal.ZERO) && feeValue.doubleValue() == 100.0)) {
                totalPercentage = totalPercentage.add(feeValue);
                // TODO: shouldn't this be >= 0 in stead of == 0 (Rinke) ?
                if (totalPercentage.compareTo(new BigDecimal(100)) == 0 && feeTransfer != null) {
                    feeTransfer.setAmount(originalAmount.subtract(feeTotalAmount));
                }
            }
        }

        // Insert the fee transfer
        if (feeTransfer != null && feeTransfer.getAmount().floatValue() > PRECISION_DELTA) {
            feeTotalAmount = feeTotalAmount.add(feeTransfer.getAmount());
            feeTransfer.setParent(transfer);
            feeTransfer.setDate(transfer.getDate());
            feeTransfer.setStatus(transfer.getStatus());
            feeTransfer.setNextAuthorizationLevel(transfer.getNextAuthorizationLevel());
            feeTransfer.setProcessDate(transfer.getProcessDate());
            feeTransfer.setExternalTransfer(transfer.getExternalTransfer());
            feeTransfer.setBy(transfer.getBy());

            // Copy custom values of common custom fields from the parent to the fee transfer
            final List<PaymentCustomField> customFields = paymentCustomFieldService.list(feeTransfer.getType(),
                    false);
            if (!CollectionUtils.isEmpty(transfer.getCustomValues())) {
                final Collection<PaymentCustomFieldValue> feeTransferCustomValues = new ArrayList<PaymentCustomFieldValue>();
                for (final PaymentCustomFieldValue fieldValue : transfer.getCustomValues()) {
                    final CustomField field = fieldValue.getField();
                    if (customFields.contains(field)) {
                        final PaymentCustomFieldValue newFieldValue = new PaymentCustomFieldValue();
                        newFieldValue.setField(field);
                        newFieldValue.setValue(fieldValue.getValue());
                        feeTransferCustomValues.add(newFieldValue);
                    }
                }
                feeTransfer.setCustomValues(feeTransferCustomValues);
            }

            insertTransferAndPayFees(lockHandler, feeTransfer, forced, simulation, chargedFees);
            transfer.getChildren().add(feeTransfer);
        }
    }
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.cdc.oracle.OracleCDCSource.java

private void generateRecords(Offset startingOffset, PreparedStatement selectChanges) {
    // When this is called the first time, Logminer was started either from SCN or from a start date, so we just keep
    // track of the start date etc.
    LOG.info("Attempting to generate records");
    boolean error;
    StringBuilder query = new StringBuilder();
    BigDecimal lastCommitSCN = new BigDecimal(startingOffset.scn);
    int sequenceNumber = startingOffset.sequence;
    LocalDateTime startTime = adjustStartTime(startingOffset.timestamp);
    String lastTxnId = startingOffset.txnId;
    LocalDateTime endTime = getEndTimeForStartTime(startTime);
    ResultSet resultSet = null;//from w  w  w  . java  2 s .c  om
    while (!getContext().isStopped()) {
        error = false;
        generationStarted = true;
        try {
            recordQueue.put(new RecordOffset(dummyRecord,
                    new Offset(version, startTime, lastCommitSCN.toPlainString(), sequenceNumber, lastTxnId)));
            selectChanges = getSelectChangesStatement();
            if (!useLocalBuffering) {
                selectChanges.setBigDecimal(1, lastCommitSCN);
                selectChanges.setInt(2, sequenceNumber);
                selectChanges.setBigDecimal(3, lastCommitSCN);
                if (shouldTrackDDL) {
                    selectChanges.setBigDecimal(4, lastCommitSCN);
                }
            }
            selectChanges.setFetchSize(configBean.jdbcFetchSize);
            resultSet = selectChanges.executeQuery();
            while (resultSet.next() && !getContext().isStopped()) {
                String queryFragment = resultSet.getString(5);
                BigDecimal scnDecimal = resultSet.getBigDecimal(1);
                String scn = scnDecimal.toPlainString();
                String xidUsn = String.valueOf(resultSet.getLong(10));
                String xidSlt = String.valueOf(resultSet.getString(11));
                String xidSqn = String.valueOf(resultSet.getString(12));
                String xid = xidUsn + "." + xidSlt + "." + xidSqn;
                // Query Fragment is not null -> we need to process
                // Query Fragment is null AND the query string buffered from previous rows due to CSF == 0 is null,
                // nothing to do, go to next row
                // Query Fragment is null, but there is previously buffered data in the query, go ahead and process.
                if (queryFragment != null) {
                    query.append(queryFragment);
                } else if (queryFragment == null && query.length() == 0) {
                    LOG.debug(READ_NULL_QUERY_FROM_ORACLE, scn, xid);
                    continue;
                }

                // CSF is 1 if the query is incomplete, so read the next row before parsing
                // CSF being 0 means query is complete, generate the record
                if (resultSet.getInt(9) == 0) {
                    if (query.length() == 0) {
                        LOG.debug(READ_NULL_QUERY_FROM_ORACLE, scn, xid);
                        continue;
                    }
                    String queryString = query.toString();
                    query.setLength(0);
                    String username = resultSet.getString(2);
                    short op = resultSet.getShort(3);
                    String timestamp = resultSet.getString(4);
                    LocalDateTime tsDate = Timestamp.valueOf(timestamp).toLocalDateTime();
                    delay.getValue().put("delay", getDelay(tsDate));
                    String table = resultSet.getString(6);
                    BigDecimal commitSCN = resultSet.getBigDecimal(7);
                    int seq = resultSet.getInt(8);

                    String rsId = resultSet.getString(13);
                    Object ssn = resultSet.getObject(14);
                    String schema = String.valueOf(resultSet.getString(15));
                    int rollback = resultSet.getInt(16);
                    String rowId = resultSet.getString(17);
                    SchemaAndTable schemaAndTable = new SchemaAndTable(schema, table);
                    TransactionIdKey key = new TransactionIdKey(xid);
                    bufferedRecordsLock.lock();
                    try {
                        if (useLocalBuffering && bufferedRecords.containsKey(key) && bufferedRecords.get(key)
                                .contains(new RecordSequence(null, null, 0, 0, rsId, ssn, null))) {
                            continue;
                        }
                    } finally {
                        bufferedRecordsLock.unlock();
                    }
                    Offset offset = null;
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(
                                "Commit SCN = {}, SCN = {}, Operation = {}, Txn Id = {}, Timestamp = {}, Row Id = {}, Redo SQL = {}",
                                commitSCN, scn, op, xid, tsDate, rowId, queryString);
                    }

                    if (op != DDL_CODE && op != COMMIT_CODE && op != ROLLBACK_CODE) {
                        if (!useLocalBuffering) {
                            offset = new Offset(version, tsDate, commitSCN.toPlainString(), seq, xid);
                        }
                        Map<String, String> attributes = new HashMap<>();
                        attributes.put(SCN, scn);
                        attributes.put(USER, username);
                        attributes.put(TIMESTAMP_HEADER, timestamp);
                        attributes.put(TABLE, table);
                        attributes.put(SEQ, String.valueOf(seq));
                        attributes.put(XID, xid);
                        attributes.put(RS_ID, rsId);
                        attributes.put(SSN, ssn.toString());
                        attributes.put(SCHEMA, schema);
                        attributes.put(ROLLBACK, String.valueOf(rollback));
                        attributes.put(ROWID_KEY, rowId);
                        if (!useLocalBuffering || getContext().isPreview()) {
                            if (commitSCN.compareTo(lastCommitSCN) < 0
                                    || (commitSCN.compareTo(lastCommitSCN) == 0 && seq < sequenceNumber)) {
                                continue;
                            }
                            lastCommitSCN = commitSCN;
                            sequenceNumber = seq;
                            if (configBean.keepOriginalQuery) {
                                attributes.put(QUERY_KEY, queryString);
                            }
                            try {
                                Record record = generateRecord(queryString, attributes, op);
                                if (record != null && record.getEscapedFieldPaths().size() > 0) {
                                    recordQueue.put(new RecordOffset(record, offset));
                                }
                            } catch (UnparseableSQLException ex) {
                                LOG.error("Parsing failed", ex);
                                unparseable.offer(queryString);
                            }
                        } else {
                            bufferedRecordsLock.lock();
                            try {
                                HashQueue<RecordSequence> records = bufferedRecords.computeIfAbsent(key, x -> {
                                    x.setTxnStartTime(tsDate);
                                    return createTransactionBuffer(key.txnId);
                                });

                                int nextSeq = records.isEmpty() ? 1 : records.tail().seq + 1;
                                RecordSequence node = new RecordSequence(attributes, queryString, nextSeq, op,
                                        rsId, ssn, tsDate);
                                records.add(node);
                            } finally {
                                bufferedRecordsLock.unlock();
                            }
                        }
                    } else if (!getContext().isPreview() && useLocalBuffering
                            && (op == COMMIT_CODE || op == ROLLBACK_CODE)) {
                        // so this commit was previously processed or it is a rollback, so don't care.
                        if (op == ROLLBACK_CODE || scnDecimal.compareTo(lastCommitSCN) < 0) {
                            bufferedRecordsLock.lock();
                            try {
                                bufferedRecords.remove(key);
                            } finally {
                                bufferedRecordsLock.unlock();
                            }
                        } else {
                            bufferedRecordsLock.lock();
                            try {
                                HashQueue<RecordSequence> records = bufferedRecords.getOrDefault(key,
                                        EMPTY_LINKED_HASHSET);
                                if (lastCommitSCN.equals(scnDecimal) && xid.equals(lastTxnId)) {
                                    removeProcessedRecords(records, sequenceNumber);
                                }
                                int bufferedRecordsToBeRemoved = records.size();
                                LOG.debug(FOUND_RECORDS_IN_TRANSACTION, bufferedRecordsToBeRemoved, xid);
                                lastCommitSCN = scnDecimal;
                                lastTxnId = xid;
                                sequenceNumber = addRecordsToQueue(tsDate, scn, xid);
                            } finally {
                                bufferedRecordsLock.unlock();
                            }
                        }
                    } else {
                        offset = new Offset(version, tsDate, scn, 0, xid);
                        boolean sendSchema = false;
                        // Commit/rollback in Preview will also end up here, so don't really do any of the following in preview
                        // Don't bother with DDL events here.
                        if (!getContext().isPreview()) {
                            // Event is sent on every DDL, but schema is not always sent.
                            // Schema sending logic:
                            // CREATE/ALTER: Schema is sent if the schema after the ALTER is newer than the cached schema
                            // (which we would have sent as an event earlier, at the last alter)
                            // DROP/TRUNCATE: Schema is not sent, since they don't change schema.
                            DDL_EVENT type = getDdlType(queryString);
                            if (type == DDL_EVENT.ALTER || type == DDL_EVENT.CREATE) {
                                sendSchema = refreshSchema(scnDecimal, new SchemaAndTable(schema, table));
                            }
                            recordQueue.put(new RecordOffset(createEventRecord(type, queryString,
                                    schemaAndTable, offset.toString(), sendSchema, timestamp), offset));
                        }
                    }
                    query.setLength(0);
                }
            }
        } catch (SQLException ex) {
            error = true;
            // force a restart from the same timestamp.
            if (ex.getErrorCode() == MISSING_LOG_FILE) {
                LOG.warn("SQL Exception while retrieving records", ex);
                addToStageExceptionsQueue(new StageException(JDBC_86, ex));
            } else if (ex.getErrorCode() != RESULTSET_CLOSED_AS_LOGMINER_SESSION_CLOSED) {
                LOG.warn("SQL Exception while retrieving records", ex);
            } else if (ex.getErrorCode() == QUERY_TIMEOUT) {
                LOG.warn("LogMiner select query timed out");
            } else if (ex.getErrorCode() == LOGMINER_START_MUST_BE_CALLED) {
                LOG.warn("Last LogMiner session did not start successfully. Will retry", ex);
            } else {
                LOG.error("Error while reading data", ex);
                addToStageExceptionsQueue(new StageException(JDBC_52, ex));
            }
        } catch (StageException e) {
            LOG.error("Error while reading data", e);
            error = true;
            addToStageExceptionsQueue(e);
        } catch (InterruptedException ex) {
            LOG.error("Interrupted while waiting to add data");
            Thread.currentThread().interrupt();
        } catch (Exception ex) {
            LOG.error("Error while reading data", ex);
            error = true;
            addToStageExceptionsQueue(new StageException(JDBC_52, ex));
        } finally {
            // If an incomplete batch is seen, it means we are going to move the window forward
            // Ending this session and starting a new one helps reduce PGA memory usage.
            try {
                if (resultSet != null && !resultSet.isClosed()) {
                    resultSet.close();
                }
                if (selectChanges != null && !selectChanges.isClosed()) {
                    selectChanges.close();
                }
            } catch (SQLException ex) {
                LOG.warn("Error while attempting to close SQL statements", ex);
            }
            try {
                endLogMnr.execute();
            } catch (SQLException ex) {
                LOG.warn("Error while trying to close logminer session", ex);
            }
            try {
                if (error) {
                    resetConnectionsQuietly();
                } else {
                    discardOldUncommitted(startTime);
                    startTime = adjustStartTime(endTime);
                    endTime = getEndTimeForStartTime(startTime);
                }
                startLogMinerUsingGivenDates(startTime.format(dateTimeColumnHandler.dateFormatter),
                        endTime.format(dateTimeColumnHandler.dateFormatter));
            } catch (SQLException ex) {
                LOG.error("Error while attempting to start LogMiner", ex);
                addToStageExceptionsQueue(new StageException(JDBC_52, ex));
            } catch (StageException ex) {
                LOG.error("Error while attempting to start logminer for redo log dictionary", ex);
                addToStageExceptionsQueue(ex);
            }
        }
    }
}