Example usage for java.math BigDecimal divide

List of usage examples for java.math BigDecimal divide

Introduction

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

Prototype

public BigDecimal divide(BigDecimal divisor, MathContext mc) 

Source Link

Document

Returns a BigDecimal whose value is (this / divisor) , with rounding according to the context settings.

Usage

From source file:org.kuali.coeus.common.budget.impl.personnel.BudgetPersonnelBudgetServiceImpl.java

public List<BudgetPersonSalaryDetails> calculatePersonSalary(Budget budget, int personIndex) {

    List<BudgetPersonSalaryDetails> budgetPersonSalaryDetails = new ArrayList<BudgetPersonSalaryDetails>();
    String rate = getParameterService().getParameterValueAsString(ProposalDevelopmentDocument.class,
            Constants.DEFAULT_INFLATION_RATE_FOR_SALARY);
    List<BudgetPeriod> budgetPeriodList = null;
    BigDecimal actualPersonSalary = ScaleTwoDecimal.ZERO.bigDecimalValue();
    BigDecimal personSalary = ScaleTwoDecimal.ZERO.bigDecimalValue();
    BigDecimal newRate = new ScaleTwoDecimal(rate).bigDecimalValue();
    budgetPeriodList = budget.getBudgetPeriods();

    BudgetPerson budgetPerson = budget.getBudgetPerson(personIndex);
    for (BudgetPeriod budgetPeriodData : budgetPeriodList) {
        BudgetPersonSalaryDetails personSalaryDetails = new BudgetPersonSalaryDetails();

        personSalaryDetails.setBudgetPerson(budgetPerson);
        personSalaryDetails.setBudgetId(budget.getBudgetId());
        personSalaryDetails.setPersonSequenceNumber(budgetPerson.getPersonSequenceNumber());
        personSalaryDetails.setBudgetPeriod(budgetPeriodData.getBudgetPeriod());
        personSalaryDetails.setPersonId(budgetPerson.getPersonId());
        if (budgetPeriodData.getBudgetPeriod() == BUDGET_PERIOD_1) {
            if (budgetPerson.getEffectiveDate().equals(budgetPerson.getStartDate())) {

                personSalaryDetails.setBaseSalary(budgetPerson.getCalculationBase());
                actualPersonSalary = budgetPerson.getCalculationBase().bigDecimalValue();

            } else {

                actualPersonSalary = budgetPerson
                        .getCalculationBase().add(new ScaleTwoDecimal(budgetPerson.getCalculationBase()
                                .bigDecimalValue().multiply(newRate.divide(
                                        new ScaleTwoDecimal(100).bigDecimalValue(), RoundingMode.HALF_UP))))
                        .bigDecimalValue();

            }/*from   w ww.j av  a2s.  c o m*/

        } else {

            personSalary = actualPersonSalary.add(actualPersonSalary.multiply(
                    newRate.divide(new ScaleTwoDecimal(100).bigDecimalValue(), RoundingMode.HALF_UP)));
            personSalaryDetails.setBaseSalary(new ScaleTwoDecimal(personSalary));
            actualPersonSalary = personSalary;
        }
        budgetPersonSalaryDetails.add(personSalaryDetails);
    }
    return budgetPersonSalaryDetails;
}

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

@Override
public LoanRepaymentAmountsDTO getLoanPaymentAmount(final LoanPaymentDTO dto) {
    final LoanRepaymentAmountsDTO ret = new LoanRepaymentAmountsDTO();
    Calendar date = dto.getDate();
    if (date == null) {
        date = Calendar.getInstance();
    }//www.  jav a  2 s .co m
    final Loan loan = fetchService.fetch(dto.getLoan(), Loan.Relationships.TRANSFER,
            Loan.Relationships.PAYMENTS);
    LoanPayment payment = fetchService.fetch(dto.getLoanPayment());
    if (payment == null) {
        payment = loan.getFirstOpenPayment();
    }
    ret.setLoanPayment(payment);

    // Update the dto with fetched values
    dto.setLoan(loan);
    dto.setLoanPayment(payment);

    if (payment != null) {
        payment = fetchService.fetch(payment, LoanPayment.Relationships.TRANSFERS);
        final BigDecimal paymentAmount = payment.getAmount();
        BigDecimal remainingAmount = paymentAmount;
        Calendar expirationDate = payment.getExpirationDate();
        Calendar lastPaymentDate = (Calendar) expirationDate.clone();
        expirationDate = DateUtils.truncate(expirationDate, Calendar.DATE);
        final LoanParameters parameters = loan.getParameters();
        Collection<Transfer> transfers = payment.getTransfers();
        if (transfers == null) {
            transfers = Collections.emptyList();
        }
        final BigDecimal expirationDailyInterest = CoercionHelper.coerce(BigDecimal.class,
                parameters.getExpirationDailyInterest());
        final LocalSettings localSettings = settingsService.getLocalSettings();
        final MathContext mathContext = localSettings.getMathContext();
        for (final Transfer transfer : transfers) {
            Calendar trfDate = transfer.getDate();
            trfDate = DateUtils.truncate(trfDate, Calendar.DATE);
            final BigDecimal trfAmount = transfer.getAmount();
            BigDecimal actualAmount = trfAmount;
            final int diffDays = (int) ((trfDate.getTimeInMillis() - expirationDate.getTimeInMillis())
                    / DateUtils.MILLIS_PER_DAY);
            if (diffDays > 0 && expirationDailyInterest != null) {
                // Apply interest
                actualAmount = actualAmount.subtract(remainingAmount.multiply(new BigDecimal(diffDays))
                        .multiply(expirationDailyInterest.divide(new BigDecimal(100), mathContext)));
            }
            remainingAmount = remainingAmount.subtract(actualAmount);
            lastPaymentDate = (Calendar) trfDate.clone();
        }
        date = DateHelper.truncate(date);
        BigDecimal remainingAmountAtDate = remainingAmount;
        final int diffDays = (int) ((date.getTimeInMillis()
                - (expirationDate.before(lastPaymentDate) ? lastPaymentDate.getTimeInMillis()
                        : expirationDate.getTimeInMillis()))
                / DateUtils.MILLIS_PER_DAY);
        if (diffDays > 0 && expirationDailyInterest != null) {
            // Apply interest
            remainingAmountAtDate = remainingAmountAtDate.add(remainingAmount.multiply(new BigDecimal(diffDays))
                    .multiply(expirationDailyInterest.divide(new BigDecimal(100), mathContext)));
        }
        final Amount expirationFee = parameters.getExpirationFee();
        if (expirationFee != null && (remainingAmountAtDate.compareTo(BigDecimal.ZERO) == 1)
                && expirationDate.before(date) && (expirationFee.getValue().compareTo(BigDecimal.ZERO) == 1)) {
            // Apply expiration fee
            remainingAmountAtDate = remainingAmountAtDate.add(expirationFee.apply(remainingAmount));
        }
        // Round the result
        ret.setRemainingAmountAtExpirationDate(localSettings.round(remainingAmount));
        ret.setRemainingAmountAtDate(localSettings.round(remainingAmountAtDate));
    }
    return ret;
}

From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java

private void prepareCollectionIndexDetails(final WaterChargeDashBoardResponse collectionIndexDetails,
        final BigDecimal totalDemand, final int noOfMonths) {
    final BigDecimal proportionalDemand = totalDemand.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
            .multiply(BigDecimal.valueOf(noOfMonths));
    if (proportionalDemand.compareTo(BigDecimal.ZERO) > 0)
        collectionIndexDetails/* w w  w .j  a  v a  2 s  .  c  o  m*/
                .setCurrentYearTillDateDmd(proportionalDemand.setScale(0, BigDecimal.ROUND_HALF_UP));
    // performance = (current year tilldate collection * 100)/(proportional
    // demand)
    if (proportionalDemand.compareTo(BigDecimal.ZERO) > 0)
        collectionIndexDetails.setPerformance(
                collectionIndexDetails.getCurrentYearTillDateColl().multiply(WaterTaxConstants.BIGDECIMAL_100)
                        .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP));
    // variance = ((currentYearCollection -
    // lastYearCollection)*100)/lastYearCollection
    BigDecimal variation;
    if (collectionIndexDetails.getLastYearTillDateColl().compareTo(BigDecimal.ZERO) == 0)
        variation = WaterTaxConstants.BIGDECIMAL_100;
    else
        variation = collectionIndexDetails.getCurrentYearTillDateColl()
                .subtract(collectionIndexDetails.getLastYearTillDateColl())
                .multiply(WaterTaxConstants.BIGDECIMAL_100)
                .divide(collectionIndexDetails.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP);
    collectionIndexDetails.setLastYearVar(variation);
}

From source file:org.efaps.esjp.accounting.transaction.Recalculate_Base.java

/**
 * Method for recalculate and return string.
 *
 * @param _parameter Parameter as passed from the eFaps API.
 * @param _docInst Instance of the document selected.
 * @return String./*from   w w  w .  jav a  2s.  com*/
 * @throws EFapsException on error.
 */
protected String getRecalculateInfo(final Parameter _parameter, final Instance _docInst) throws EFapsException {
    final StringBuilder html = new StringBuilder();
    final PrintQuery print = new PrintQuery(_docInst);
    print.addAttribute(CISales.DocumentSumAbstract.RateCrossTotal, CISales.DocumentSumAbstract.CrossTotal,
            CISales.DocumentSumAbstract.RateCurrencyId, CISales.DocumentSumAbstract.CurrencyId,
            CISales.DocumentSumAbstract.Date, CISales.DocumentSumAbstract.Name);
    print.execute();

    final BigDecimal rateCross = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.RateCrossTotal);
    final BigDecimal crossTotal = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.CrossTotal);
    final String nameDoc = print.<String>getAttribute(CISales.DocumentSumAbstract.Name);
    final Instance targetCurrInst = Instance.get(CIERP.Currency.getType(),
            print.<Long>getAttribute(CISales.DocumentSumAbstract.RateCurrencyId));
    final Instance currentInst = Instance.get(CIERP.Currency.getType(),
            print.<Long>getAttribute(CISales.DocumentSumAbstract.CurrencyId));
    final CurrencyInst tarCurr = new CurrencyInst(targetCurrInst);
    final CurrencyInst curr = new CurrencyInst(currentInst);

    final PriceUtil priceUtil = new PriceUtil();
    final BigDecimal[] rates = priceUtil.getRates(_parameter, targetCurrInst, currentInst);
    final BigDecimal rate = rates[2];

    final BigDecimal newCrossTotal = rateCross.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO
            : rateCross.divide(rate, BigDecimal.ROUND_HALF_UP);
    final BigDecimal gainloss = newCrossTotal.subtract(crossTotal);

    final Map<String, String[]> map = validateInfo(_parameter, gainloss);
    final String[] accs = map.get("accs");
    final String[] check = map.get("check");

    html.append("<table>").append("<tr>").append("<td>").append(DBProperties.getProperty("Sales_Invoice.Label"))
            .append("</td>").append("<td colspan=\"2\">").append(nameDoc).append("</td>").append("</tr>")
            .append("<td>").append(DBProperties.getProperty("Sales_DocumentAbstract/RateCrossTotal.Label"))
            .append("</td>").append("<td>").append(rateCross).append(" ").append(tarCurr.getSymbol())
            .append("</td>").append("<td>").append(crossTotal).append(" ").append(curr.getSymbol())
            .append("</td>").append("</tr>").append("<tr>").append("<td>")
            .append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.newTotal.Label"))
            .append("</td>").append("<td colspan=\"2\" align=\"right\">").append(newCrossTotal).append(" ")
            .append(curr.getSymbol()).append("</td>").append("</tr>").append("<tr>").append("<td>");
    if (gainloss.compareTo(BigDecimal.ZERO) == -1) {
        html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.loss.Label"));
    } else {
        html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.gain.Label"));
    }
    html.append("</td>").append("<td colspan=\"2\" align=\"right\">").append(gainloss.abs()).append(" ")
            .append(curr.getSymbol()).append("</td>").append("</tr>").append("<tr>").append("<td>")
            .append(DBProperties.getProperty("Accounting_TransactionPositionDebit.Label")).append("</td>")
            .append("<td colspan=\"2\" align=\"right\">");
    if (checkAccounts(accs, 0, check).length() > 0) {
        html.append(checkAccounts(accs, 0, check));
    } else {
        html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.reviseConfig.Label"));
    }
    html.append("</td>").append("</tr>").append("<tr>").append("<td>")
            .append(DBProperties.getProperty("Accounting_TransactionPositionCredit.Label")).append("</td>")
            .append("<td colspan=\"2\" align=\"right\">");
    if (checkAccounts(accs, 1, check).length() > 0) {
        html.append(checkAccounts(accs, 1, check));
    } else {
        html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.reviseConfig.Label"));
    }
    html.append("</td>").append("</tr>").append("</table>");
    return html.toString();
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The exponential function./* w  ww . j  av  a 2 s  .  co  m*/
 *
 * @param x the argument.
 * @return exp(x).
 * The precision of the result is implicitly defined by the precision in the argument.
 * 16
 * In particular this means that "Invalid Operation" errors are thrown if catastrophic
 * cancellation of digits causes the result to have no valid digits left.
 */
static public BigDecimal exp(BigDecimal x) {
    /* To calculate the value if x is negative, use exp(-x) = 1/exp(x)
     */
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        final BigDecimal invx = exp(x.negate());
        /* Relative error in inverse of invx is the same as the relative errror in invx.
         * This is used to define the precision of the result.
         */
        MathContext mc = new MathContext(invx.precision());
        return BigDecimal.ONE.divide(invx, mc);
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        /* recover the valid number of digits from x.ulp(), if x hits the
         * zero. The x.precision() is 1 then, and does not provide this information.
         */
        return scalePrec(BigDecimal.ONE, -(int) (Math.log10(x.ulp().doubleValue())));
    } else {
        /* Push the number in the Taylor expansion down to a small
         * value where TAYLOR_NTERM terms will do. If x<1, the n-th term is of the order
         * x^n/n!, and equal to both the absolute and relative error of the result
         * since the result is close to 1. The x.ulp() sets the relative and absolute error
         * of the result, as estimated from the first Taylor term.
         * We want x^TAYLOR_NTERM/TAYLOR_NTERM! < x.ulp, which is guaranteed if
         * x^TAYLOR_NTERM < TAYLOR_NTERM*(TAYLOR_NTERM-1)*...*x.ulp.
         */
        final double xDbl = x.doubleValue();
        final double xUlpDbl = x.ulp().doubleValue();
        if (Math.pow(xDbl, TAYLOR_NTERM) < TAYLOR_NTERM * (TAYLOR_NTERM - 1.0) * (TAYLOR_NTERM - 2.0)
                * xUlpDbl) {
            /* Add TAYLOR_NTERM terms of the Taylor expansion (Eulers sum formula)
             */
            BigDecimal resul = BigDecimal.ONE;
            /* x^i */
            BigDecimal xpowi = BigDecimal.ONE;
            /* i factorial */
            BigInteger ifac = BigInteger.ONE;
            /* TAYLOR_NTERM terms to be added means we move x.ulp() to the right
             * for each power of 10 in TAYLOR_NTERM, so the addition wont add noise beyond
             * whats already in x.
             */
            MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / TAYLOR_NTERM));
            for (int i = 1; i <= TAYLOR_NTERM; i++) {
                ifac = ifac.multiply(new BigInteger("" + i));
                xpowi = xpowi.multiply(x);
                final BigDecimal c = xpowi.divide(new BigDecimal(ifac), mcTay);
                resul = resul.add(c);
                if (Math.abs(xpowi.doubleValue()) < i && Math.abs(c.doubleValue()) < 0.5 * xUlpDbl) {
                    break;
                }
            }
            /* exp(x+deltax) = exp(x)(1+deltax) if deltax is <<1. So the relative error
             * in the result equals the absolute error in the argument.
             */
            MathContext mc = new MathContext(err2prec(xUlpDbl / 2.));
            return resul.round(mc);
        } else {
            /* Compute exp(x) = (exp(0.1*x))^10. Division by 10 does not lead
             * to loss of accuracy.
             */
            int exSc = (int) (1.0 - Math.log10(TAYLOR_NTERM * (TAYLOR_NTERM - 1.0) * (TAYLOR_NTERM - 2.0)
                    * xUlpDbl / Math.pow(xDbl, TAYLOR_NTERM)) / (TAYLOR_NTERM - 1.0));
            BigDecimal xby10 = x.scaleByPowerOfTen(-exSc);
            BigDecimal expxby10 = exp(xby10);
            /* Final powering by 10 means that the relative error of the result
             * is 10 times the relative error of the base (First order binomial expansion).
             * This looses one digit.
             */
            MathContext mc = new MathContext(expxby10.precision() - exSc);
            /* Rescaling the powers of 10 is done in chunks of a maximum of 8 to avoid an invalid operation
            17
             * response by the BigDecimal.pow library or integer overflow.
             */
            while (exSc > 0) {
                int exsub = Math.min(8, exSc);
                exSc -= exsub;
                MathContext mctmp = new MathContext(expxby10.precision() - exsub + 2);
                int pex = 1;
                while (exsub-- > 0) {
                    pex *= 10;
                }
                expxby10 = expxby10.pow(pex, mctmp);
            }
            return expxby10.round(mc);
        }
    }
}

From source file:org.egov.ptis.actions.common.AjaxCommonAction.java

/**
 * API to calculate Mutation Fee dynamically
 *
 * @return/*  w  w  w . jav a 2s  . c o  m*/
 */
@Action(value = "/ajaxCommon-calculateMutationFee")
public String calculateMutationFee() {
    // Maximum among partyValue and departmentValue will be considered as
    // the documentValue
    final BigDecimal documentValue = partyValue.compareTo(departmentValue) > 0 ? partyValue : departmentValue;

    if (documentValue.compareTo(ZERO) > 0) {
        BigDecimal excessDocValue;
        BigDecimal multiplicationFactor;
        final MutationFeeDetails mutationFeeDetails = (MutationFeeDetails) getPersistenceService().find(
                "from MutationFeeDetails where lowLimit <= ? and (highLimit is null OR highLimit >= ?) and toDate > now()",
                documentValue, documentValue);
        if (mutationFeeDetails != null) {
            if (mutationFeeDetails.getFlatAmount() != null
                    && mutationFeeDetails.getFlatAmount().compareTo(ZERO) > 0)
                if (mutationFeeDetails.getIsRecursive().toString().equalsIgnoreCase(RECURSIVEFACTOR_N))
                    mutationFee = mutationFeeDetails.getFlatAmount();
                else {
                    excessDocValue = documentValue.subtract(mutationFeeDetails.getLowLimit())
                            .add(BigDecimal.ONE);
                    multiplicationFactor = excessDocValue.divide(mutationFeeDetails.getRecursiveAmount(),
                            BigDecimal.ROUND_CEILING);
                    mutationFee = mutationFeeDetails.getFlatAmount()
                            .add(multiplicationFactor.multiply(mutationFeeDetails.getRecursiveFactor()));
                }
            if (mutationFeeDetails.getPercentage() != null
                    && mutationFeeDetails.getPercentage().compareTo(ZERO) > 0)
                if (mutationFeeDetails.getIsRecursive().toString().equalsIgnoreCase(RECURSIVEFACTOR_N))
                    mutationFee = documentValue.multiply(mutationFeeDetails.getPercentage())
                            .divide(PropertyTaxConstants.BIGDECIMAL_100);
            mutationFee = mutationFee.setScale(0, BigDecimal.ROUND_HALF_UP);
        }
    }
    return RESULT_MUTATION_FEE;
}

From source file:org.sakaiproject.tool.gradebook.Category.java

public void calculateStatistics(final List<GradebookAssignment> assignmentsWithStats) {
    int numScored = 0;
    int numOfAssignments = 0;
    BigDecimal total = new BigDecimal("0");
    BigDecimal totalPossible = new BigDecimal("0");

    for (final GradebookAssignment assign : assignmentsWithStats) {
        final Double score = assign.getAverageTotal();

        if (assign.isCounted() && !assign.getUngraded() && assign.getPointsPossible() != null
                && assign.getPointsPossible().doubleValue() > 0.0) {
            if (score != null) {
                total = total.add(new BigDecimal(score.toString()));
                if (assign.getPointsPossible() != null && !assign.isExtraCredit()) {
                    totalPossible = totalPossible.add(new BigDecimal(assign.getPointsPossible().toString()));
                    numOfAssignments++;/*from  ww w . j  ava 2  s  .c  o m*/
                }
                if (!assign.isExtraCredit()) {
                    numScored++;
                }
            }
        }
    }

    if (numScored == 0 || numOfAssignments == 0) {
        this.averageScore = null;
        this.averageTotalPoints = null;
        this.mean = null;
        this.totalPointsEarned = null;
        this.totalPointsPossible = null;
    } else {
        final BigDecimal bdNumScored = new BigDecimal(numScored);
        final BigDecimal bdNumAssign = new BigDecimal(numOfAssignments);
        this.averageScore = Double
                .valueOf(total.divide(bdNumScored, GradebookService.MATH_CONTEXT).doubleValue());
        this.averageTotalPoints = Double
                .valueOf(totalPossible.divide(bdNumAssign, GradebookService.MATH_CONTEXT).doubleValue());
        final BigDecimal value = total.divide(bdNumScored, GradebookService.MATH_CONTEXT)
                .divide(new BigDecimal(this.averageTotalPoints.doubleValue()), GradebookService.MATH_CONTEXT)
                .multiply(new BigDecimal("100"));
        this.mean = Double.valueOf(value.doubleValue());
    }
}

From source file:org.efaps.esjp.accounting.transaction.Recalculate_Base.java

/**
 * Creates the gain loss4 document account.
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @return the return/*from  w w  w .  j a  v  a 2  s  . c  o  m*/
 * @throws EFapsException on error
 */
public Return createGainLoss4DocumentAccount(final Parameter _parameter) throws EFapsException {
    final Set<String> setAccounts = getAccounts4DocumentConfig(_parameter);

    final String[] oidsDoc = (String[]) Context.getThreadContext().getSessionAttribute(
            CIFormAccounting.Accounting_GainLoss4DocumentAccountForm.selectedDocuments.name);
    final DateTime dateTo = new DateTime(_parameter
            .getParameterValue(CIFormAccounting.Accounting_GainLoss4DocumentAccountForm.transactionDate.name));
    for (final String oid : oidsDoc) {
        final Instance instDoc = Instance.get(oid);

        final QueryBuilder attrQuerBldr = new QueryBuilder(CIAccounting.Transaction2SalesDocument);
        attrQuerBldr.addWhereAttrEqValue(CIAccounting.Transaction2SalesDocument.ToLink, instDoc);
        final AttributeQuery attrQuery = attrQuerBldr
                .getAttributeQuery(CIAccounting.Transaction2SalesDocument.FromLink);

        // filter classification Document
        final QueryBuilder attrQueryBldr2 = new QueryBuilder(CIAccounting.Transaction);
        attrQueryBldr2.addWhereAttrEqValue(CIAccounting.Transaction.PeriodLink,
                _parameter.getInstance().getId());
        attrQueryBldr2.addWhereAttrInQuery(CIAccounting.Transaction.ID, attrQuery);
        final AttributeQuery attrQuery2 = attrQuerBldr.getAttributeQuery(CIAccounting.Transaction.ID);

        final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.TransactionPositionAbstract);
        queryBldr.addWhereAttrInQuery(CIAccounting.TransactionPositionAbstract.TransactionLink, attrQuery2);
        final MultiPrintQuery multi = queryBldr.getPrint();
        multi.addAttribute(CIAccounting.TransactionPositionAbstract.Amount,
                CIAccounting.TransactionPositionAbstract.RateAmount,
                CIAccounting.TransactionPositionAbstract.CurrencyLink,
                CIAccounting.TransactionPositionAbstract.RateCurrencyLink);
        final SelectBuilder selAcc = new SelectBuilder()
                .linkto(CIAccounting.TransactionPositionAbstract.AccountLink).oid();
        multi.addSelect(selAcc);
        multi.execute();
        final Map<String, AccountInfo> map = new HashMap<>();
        while (multi.next()) {
            final Instance accountInst = Instance.get(multi.<String>getSelect(selAcc));
            if (setAccounts.contains(accountInst.getOid())) {
                final BigDecimal oldRateAmount = multi
                        .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.RateAmount);
                final BigDecimal oldAmount = multi
                        .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.Amount);
                final Instance targetCurrInst = Instance.get(CIERP.Currency.getType(),
                        multi.<Long>getAttribute(CIAccounting.TransactionPositionAbstract.RateCurrencyLink));
                final Instance currentInst = Instance.get(CIERP.Currency.getType(),
                        multi.<Long>getAttribute(CIAccounting.TransactionPositionAbstract.CurrencyLink));

                final PriceUtil priceUtil = new PriceUtil();
                final BigDecimal[] rates = priceUtil.getRates(_parameter, targetCurrInst, currentInst);
                final BigDecimal rate = rates[2];
                final BigDecimal newAmount = oldRateAmount.divide(rate, BigDecimal.ROUND_HALF_UP);

                BigDecimal gainloss = BigDecimal.ZERO;
                if (!currentInst.equals(targetCurrInst)) {
                    gainloss = newAmount.subtract(oldAmount);
                } else {
                    gainloss = newAmount;
                }
                if (map.containsKey(accountInst.getOid())) {
                    final AccountInfo tarAcc = map.get(accountInst.getOid());
                    tarAcc.addAmount(gainloss);
                } else {
                    final AccountInfo tarAcc = new AccountInfo(accountInst, gainloss);
                    tarAcc.setAmountRate(gainloss);
                    tarAcc.setCurrInstance(currentInst);
                    map.put(accountInst.getOid(), tarAcc);
                }
            }
        }

        if (!map.isEmpty()) {
            Insert insert = null;
            CurrencyInst curr = null;
            BigDecimal gainlossSum = BigDecimal.ZERO;
            for (final Entry<String, AccountInfo> entry : map.entrySet()) {
                final AccountInfo tarAcc = entry.getValue();
                final Instance instAcc = Instance.get(entry.getKey());
                final BigDecimal gainloss = tarAcc.getAmount();
                gainlossSum = gainlossSum.add(gainloss);
                final Instance currInstance = tarAcc.getCurrInstance();
                curr = new CurrencyInst(currInstance);
                final Map<String, String[]> mapVal = validateInfo(_parameter, gainloss);
                final String[] accs = mapVal.get("accs");
                final String[] check = mapVal.get("check");

                if (checkAccounts(accs, 0, check).length() > 0) {
                    if (gainloss.compareTo(BigDecimal.ZERO) != 0) {
                        final String[] accOids = mapVal.get("accountOids");
                        if (insert == null) {
                            final DateTimeFormatter formater = DateTimeFormat.mediumDate();
                            final String dateStr = dateTo
                                    .withChronology(Context.getThreadContext().getChronology())
                                    .toString(formater.withLocale(Context.getThreadContext().getLocale()));
                            final StringBuilder description = new StringBuilder();
                            description
                                    .append(DBProperties
                                            .getProperty("Accounting_DocumentAccountForm.TxnRecalculate.Label"))
                                    .append(" ").append(dateStr);
                            insert = new Insert(CIAccounting.Transaction);
                            insert.add(CIAccounting.Transaction.Description, description.toString());
                            insert.add(CIAccounting.Transaction.Date, dateTo);
                            insert.add(CIAccounting.Transaction.PeriodLink, _parameter.getInstance().getId());
                            insert.add(CIAccounting.Transaction.Status,
                                    Status.find(CIAccounting.TransactionStatus.uuid, "Open").getId());
                            insert.execute();
                        }

                        Insert insertPos = new Insert(CIAccounting.TransactionPositionCredit);
                        insertPos.add(CIAccounting.TransactionPositionCredit.TransactionLink, insert.getId());
                        if (gainloss.signum() < 0) {
                            insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink, instAcc.getId());
                        } else {
                            insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink,
                                    Instance.get(accOids[0]).getId());
                        }
                        insertPos.add(CIAccounting.TransactionPositionCredit.Amount, gainloss.abs());
                        insertPos.add(CIAccounting.TransactionPositionCredit.RateAmount, gainloss.abs());
                        insertPos.add(CIAccounting.TransactionPositionCredit.CurrencyLink,
                                currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionCredit.RateCurrencyLink,
                                currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionCredit.Rate,
                                new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                        insertPos.execute();

                        insertPos = new Insert(CIAccounting.TransactionPositionDebit);
                        insertPos.add(CIAccounting.TransactionPositionDebit.TransactionLink, insert.getId());
                        if (gainloss.signum() < 0) {
                            insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink,
                                    Instance.get(accOids[0]).getId());
                        } else {
                            insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink, instAcc.getId());
                        }
                        insertPos.add(CIAccounting.TransactionPositionDebit.Amount, gainloss.abs().negate());
                        insertPos.add(CIAccounting.TransactionPositionDebit.RateAmount,
                                gainloss.abs().negate());
                        insertPos.add(CIAccounting.TransactionPositionDebit.CurrencyLink, currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionDebit.RateCurrencyLink,
                                currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionDebit.Rate,
                                new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                        insertPos.execute();
                    }
                }
            }
            if (insert != null) {
                final Instance instance = insert.getInstance();
                // create classifications
                final Classification classification1 = (Classification) CIAccounting.TransactionClass.getType();
                final Insert relInsert1 = new Insert(classification1.getClassifyRelationType());
                relInsert1.add(classification1.getRelLinkAttributeName(), instance.getId());
                relInsert1.add(classification1.getRelTypeAttributeName(), classification1.getId());
                relInsert1.execute();

                final Insert classInsert1 = new Insert(classification1);
                classInsert1.add(classification1.getLinkAttributeName(), instance.getId());
                classInsert1.execute();

                final Classification classification = (Classification) CIAccounting.TransactionClassGainLoss
                        .getType();
                final Insert relInsert = new Insert(classification.getClassifyRelationType());
                relInsert.add(classification.getRelLinkAttributeName(), instance.getId());
                relInsert.add(classification.getRelTypeAttributeName(), classification.getId());
                relInsert.execute();

                final Insert classInsert = new Insert(classification);
                classInsert.add(classification.getLinkAttributeName(), instance.getId());
                classInsert.add(CIAccounting.TransactionClassGainLoss.Amount, gainlossSum);
                classInsert.add(CIAccounting.TransactionClassGainLoss.RateAmount, gainlossSum);
                classInsert.add(CIAccounting.TransactionClassGainLoss.CurrencyLink, curr.getInstance().getId());
                classInsert.add(CIAccounting.TransactionClassGainLoss.RateCurrencyLink,
                        curr.getInstance().getId());
                classInsert.add(CIAccounting.TransactionClassGainLoss.Rate,
                        new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                classInsert.execute();

                new Create().connectDocs2Transaction(_parameter, instance, instDoc);
            }
        }
    }

    return new Return();
}

From source file:com.opengamma.bloombergexample.loader.DemoEquityOptionCollarPortfolioLoader.java

private void addNodes(ManageablePortfolioNode rootNode, String underlying, boolean includeUnderlying,
        Period[] expiries) {/*from   www  .j a  v  a2  s . co m*/
    ExternalId ticker = ExternalSchemes.bloombergTickerSecurityId(underlying);
    ManageableSecurity underlyingSecurity = null;
    if (includeUnderlying) {
        underlyingSecurity = getOrLoadEquity(ticker);
    }

    ExternalIdBundle bundle = underlyingSecurity == null ? ExternalIdBundle.of(ticker)
            : underlyingSecurity.getExternalIdBundle();
    HistoricalTimeSeriesInfoDocument timeSeriesInfo = getOrLoadTimeSeries(ticker, bundle);
    double estimatedCurrentStrike = getOrLoadMostRecentPoint(timeSeriesInfo);
    Set<ExternalId> optionChain = getOptionChain(ticker);

    //TODO: reuse positions/nodes?
    String longName = underlyingSecurity == null ? "" : underlyingSecurity.getName();
    String formattedName = MessageFormatter.format("[{}] {}", underlying, longName);
    ManageablePortfolioNode equityNode = new ManageablePortfolioNode(formattedName);

    BigDecimal underlyingAmount = VALUE_OF_UNDERLYING.divide(BigDecimal.valueOf(estimatedCurrentStrike),
            BigDecimal.ROUND_HALF_EVEN);

    if (includeUnderlying) {
        addPosition(equityNode, underlyingAmount, ticker);
    }

    TreeMap<LocalDate, Set<BloombergTickerParserEQOption>> optionsByExpiry = new TreeMap<LocalDate, Set<BloombergTickerParserEQOption>>();
    for (ExternalId optionTicker : optionChain) {
        s_logger.debug("Got option {}", optionTicker);

        BloombergTickerParserEQOption optionInfo = BloombergTickerParserEQOption.getOptionParser(optionTicker);
        s_logger.debug("Got option info {}", optionInfo);

        LocalDate key = optionInfo.getExpiry();
        Set<BloombergTickerParserEQOption> set = optionsByExpiry.get(key);
        if (set == null) {
            set = new HashSet<BloombergTickerParserEQOption>();
            optionsByExpiry.put(key, set);
        }
        set.add(optionInfo);
    }
    Set<ExternalId> tickersToLoad = new HashSet<ExternalId>();

    BigDecimal expiryCount = BigDecimal.valueOf(expiries.length);
    BigDecimal defaultAmountAtExpiry = underlyingAmount.divide(expiryCount, BigDecimal.ROUND_DOWN);
    BigDecimal spareAmountAtExpiry = defaultAmountAtExpiry.add(BigDecimal.ONE);
    int spareCount = underlyingAmount.subtract(defaultAmountAtExpiry.multiply(expiryCount)).intValue();

    for (int i = 0; i < expiries.length; i++) {
        Period bucketPeriod = expiries[i];

        ManageablePortfolioNode bucketNode = new ManageablePortfolioNode(bucketPeriod.toString().substring(1));

        LocalDate nowish = LocalDate.now().withDayOfMonth(20); //This avoids us picking different options every time this script is run
        LocalDate targetExpiry = nowish.plus(bucketPeriod);
        LocalDate chosenExpiry = optionsByExpiry.floorKey(targetExpiry);
        if (chosenExpiry == null) {
            s_logger.warn("No options for {} on {}", targetExpiry, underlying);
            continue;
        }
        s_logger.info("Using time {} for bucket {} ({})",
                new Object[] { chosenExpiry, bucketPeriod, targetExpiry });

        Set<BloombergTickerParserEQOption> optionsAtExpiry = optionsByExpiry.get(chosenExpiry);
        TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> optionsByStrike = new TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (BloombergTickerParserEQOption option : optionsAtExpiry) {
            //        s_logger.info("option {}", option);
            double key = option.getStrike();
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(key);
            if (pair == null) {
                pair = Pair.of(null, null);
            }
            if (option.getOptionType() == OptionType.CALL) {
                pair = Pair.of(option, pair.getSecond());
            } else {
                pair = Pair.of(pair.getFirst(), option);
            }
            optionsByStrike.put(key, pair);
        }

        //cascading collar?
        BigDecimal amountAtExpiry = spareCount-- > 0 ? spareAmountAtExpiry : defaultAmountAtExpiry;

        s_logger.info(" est strike {}", estimatedCurrentStrike);
        Double[] strikes = optionsByStrike.keySet().toArray(new Double[0]);

        int strikeIndex = Arrays.binarySearch(strikes, estimatedCurrentStrike);
        if (strikeIndex < 0) {
            strikeIndex = -(1 + strikeIndex);
        }
        s_logger.info("strikes length {} index {} strike of index {}",
                new Object[] { Integer.valueOf(strikes.length), Integer.valueOf(strikeIndex),
                        Double.valueOf(strikes[strikeIndex]) });

        int minIndex = strikeIndex - _numOptions;
        minIndex = Math.max(0, minIndex);
        int maxIndex = strikeIndex + _numOptions;
        maxIndex = Math.min(strikes.length - 1, maxIndex);

        s_logger.info("min {} max {}", Integer.valueOf(minIndex), Integer.valueOf(maxIndex));
        StringBuffer sb = new StringBuffer("strikes: [");
        for (int j = minIndex; j <= maxIndex; j++) {
            sb.append(" ");
            sb.append(strikes[j]);
        }
        sb.append(" ]");
        s_logger.info(sb.toString());

        //Short Calls
        ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> calls = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (int j = minIndex; j < strikeIndex; j++) {
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike
                    .get(strikes[j]);
            if (pair == null) {
                throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]);
            }
            calls.add(pair);
        }
        spreadOptions(bucketNode, calls, OptionType.CALL, -1, tickersToLoad, amountAtExpiry, includeUnderlying,
                calls.size());

        // Long Puts
        ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> puts = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (int j = strikeIndex + 1; j <= maxIndex; j++) {
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike
                    .get(strikes[j]);
            if (pair == null) {
                throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]);
            }
            puts.add(pair);
        }
        spreadOptions(bucketNode, puts, OptionType.PUT, 1, tickersToLoad, amountAtExpiry, includeUnderlying,
                puts.size());

        if (bucketNode.getChildNodes().size() + bucketNode.getPositionIds().size() > 0) {
            equityNode.addChildNode(bucketNode); //Avoid generating empty nodes   
        }
    }

    for (ExternalId optionTicker : tickersToLoad) {
        ManageableSecurity loaded = getOrLoadSecurity(optionTicker);
        if (loaded == null) {
            throw new OpenGammaRuntimeException("Unexpected option type " + loaded);
        }

        //TODO [LAPANA-29] Should be able to do this for index options too
        if (includeUnderlying) {
            try {
                HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(optionTicker,
                        loaded.getExternalIdBundle());
                if (loadedTs == null) {
                    throw new OpenGammaRuntimeException("Failed to get time series for " + loaded);
                }
            } catch (Exception ex) {
                s_logger.error("Failed to get time series for " + loaded, ex);
            }
        }
    }

    if (equityNode.getPositionIds().size() + equityNode.getChildNodes().size() > 0) {
        rootNode.addChildNode(equityNode);
    }
}

From source file:org.efaps.esjp.accounting.transaction.Recalculate_Base.java

/**
 * Method to recalculate rate./*from   w  w  w  .j av  a 2 s. c om*/
 *
 * @param _parameter Parameter as passed from the eFaps API.
 * @return new Return.
 * @throws EFapsException on error.
 */
public Return recalculateRate(final Parameter _parameter) throws EFapsException {
    final Instance docInst = Instance.get(_parameter.getParameterValue("docInst"));
    final PrintQuery print = new PrintQuery(docInst);
    print.addAttribute(CISales.DocumentSumAbstract.RateCrossTotal, CISales.DocumentSumAbstract.CrossTotal,
            CISales.DocumentSumAbstract.RateCurrencyId, CISales.DocumentSumAbstract.CurrencyId,
            CISales.DocumentSumAbstract.Date, CISales.DocumentSumAbstract.Name);
    print.execute();

    final BigDecimal rateCross = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.RateCrossTotal);
    final BigDecimal crossTotal = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.CrossTotal);
    final DateTime dateDoc = print.<DateTime>getAttribute(CISales.DocumentSumAbstract.Date);
    final String nameDoc = print.<String>getAttribute(CISales.DocumentSumAbstract.Name);
    final Instance targetCurrInst = Instance.get(CIERP.Currency.getType(),
            print.<Long>getAttribute(CISales.DocumentSumAbstract.RateCurrencyId));
    final Instance currentInst = Instance.get(CIERP.Currency.getType(),
            print.<Long>getAttribute(CISales.DocumentSumAbstract.CurrencyId));
    final CurrencyInst tarCurr = new CurrencyInst(targetCurrInst);
    final CurrencyInst curr = new CurrencyInst(currentInst);

    final PriceUtil priceUtil = new PriceUtil();
    final BigDecimal[] rates = priceUtil.getRates(_parameter, targetCurrInst, currentInst);
    final BigDecimal rate = rates[2];

    final BigDecimal newCrossTotal = rateCross.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO
            : rateCross.divide(rate, BigDecimal.ROUND_HALF_UP);
    final BigDecimal gainloss = newCrossTotal.subtract(crossTotal);
    final Map<String, String[]> map = validateInfo(_parameter, gainloss);
    final String[] accs = map.get("accs");
    final String[] check = map.get("check");
    if (checkAccounts(accs, 0, check).length() > 0 && checkAccounts(accs, 1, check).length() > 0) {
        if (gainloss.compareTo(BigDecimal.ZERO) != 0) {
            if (!tarCurr.equals(curr)) {
                final String[] accOids = map.get("accountOids");

                final Insert insert = new Insert(CIAccounting.Transaction);
                final StringBuilder description = new StringBuilder();
                final DateTimeFormatter formater = DateTimeFormat.mediumDate();
                final String dateStr = dateDoc.withChronology(Context.getThreadContext().getChronology())
                        .toString(formater.withLocale(Context.getThreadContext().getLocale()));
                description
                        .append(DBProperties
                                .getProperty("Accounting_TransactionRecalculateForm.TxnRecalculate.Label"))
                        .append(" ").append(nameDoc).append(" ").append(dateStr);
                insert.add(CIAccounting.Transaction.Description, description);
                insert.add(CIAccounting.Transaction.Date, _parameter.getParameterValue("date"));
                insert.add(CIAccounting.Transaction.PeriodLink, _parameter.getInstance().getId());
                insert.add(CIAccounting.Transaction.Status,
                        Status.find(CIAccounting.TransactionStatus.uuid, "Open").getId());
                insert.execute();

                final Instance instance = insert.getInstance();
                new Create().connectDocs2Transaction(_parameter, instance, docInst);

                final Insert insert2 = new Insert(CIAccounting.TransactionPositionCredit);
                insert2.add(CIAccounting.TransactionPositionCredit.TransactionLink, instance.getId());
                insert2.add(CIAccounting.TransactionPositionCredit.AccountLink,
                        Instance.get(accOids[1]).getId());
                insert2.add(CIAccounting.TransactionPositionCredit.CurrencyLink, curr.getInstance().getId());
                insert2.add(CIAccounting.TransactionPositionCredit.RateCurrencyLink,
                        curr.getInstance().getId());
                insert2.add(CIAccounting.TransactionPositionCredit.Rate, new Object[] { 1, 1 });
                insert2.add(CIAccounting.TransactionPositionCredit.RateAmount, gainloss.abs());
                insert2.add(CIAccounting.TransactionPositionCredit.Amount, gainloss.abs());
                insert2.execute();

                final Insert insert3 = new Insert(CIAccounting.TransactionPositionDebit);
                insert3.add(CIAccounting.TransactionPositionDebit.TransactionLink, instance.getId());
                insert3.add(CIAccounting.TransactionPositionDebit.AccountLink,
                        Instance.get(accOids[0]).getId());
                insert3.add(CIAccounting.TransactionPositionDebit.CurrencyLink, curr.getInstance().getId());
                insert3.add(CIAccounting.TransactionPositionDebit.RateCurrencyLink, curr.getInstance().getId());
                insert3.add(CIAccounting.TransactionPositionDebit.Rate, new Object[] { 1, 1 });
                insert3.add(CIAccounting.TransactionPositionDebit.RateAmount, gainloss.abs().negate());
                insert3.add(CIAccounting.TransactionPositionDebit.Amount, gainloss.abs().negate());
                insert3.execute();

                _parameter.put(ParameterValues.INSTANCE, docInst);
                new Accounting4DocSum().recalculateRate(_parameter);
            }
        }
    }
    return new Return();
}