Example usage for java.math BigDecimal negate

List of usage examples for java.math BigDecimal negate

Introduction

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

Prototype

public BigDecimal negate() 

Source Link

Document

Returns a BigDecimal whose value is (-this) , and whose scale is this.scale() .

Usage

From source file:org.kuali.kfs.module.endow.document.validation.impl.EndowmentTransactionLinesDocumentBaseRules.java

/**
 * Checks that the transaction line units match the tax lot lines total number of units.
 *
 * @param document//w  ww .  java2  s . c om
 * @param transactionLine
 * @param index
 * @return true if valid, false otherwise
 */
protected boolean validateTotalUnits(EndowmentTransactionalDocument document,
        EndowmentTransactionLine transactionLine, int index) {
    boolean isValid = true;

    BigDecimal transactionLineUnits = transactionLine.getTransactionUnits().bigDecimalValue();
    BigDecimal taxLotLinesTotalUnits = BigDecimal.ZERO;

    if (transactionLine.getTaxLotLines() != null && transactionLine.getTaxLotLines().size() > 0) {

        for (EndowmentTransactionTaxLotLine taxLotLine : transactionLine.getTaxLotLines()) {
            taxLotLinesTotalUnits = taxLotLinesTotalUnits.add(taxLotLine.getLotUnits());
        }
    }

    if (transactionLine instanceof EndowmentSourceTransactionLine) {
        taxLotLinesTotalUnits = taxLotLinesTotalUnits.negate();
    }

    if (transactionLineUnits.compareTo(taxLotLinesTotalUnits) != 0) {
        isValid = false;

        putFieldError(
                getErrorPrefix(transactionLine, index)
                        + EndowPropertyConstants.TRANSACTION_LINE_TRANSACTION_UNITS,
                EndowKeyConstants.EndowmentTransactionDocumentConstants.ERROR_TRANSACTION_LINE_TAX_LOT_UNITS_DONT_CORRESPOND);
    }

    return isValid;
}

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

/**
 * Create a position. The type is given with the properties of the calling
 * command./* w  w w .j ava 2 s .  c o m*/
 *
 * @param _parameter Parameter as passed from the eFaps API
 * @return new Return
 * @throws EFapsException on error
 */
public Return createPosition(final Parameter _parameter) throws EFapsException {
    final Instance parent = _parameter.getCallInstance();
    final String amountStr = _parameter.getParameterValue("rateAmount");
    final String account = _parameter.getParameterValue("accountLink");
    final String rateCurrencyLink = _parameter.getParameterValue("rateCurrencyLink");

    final Map<?, ?> properties = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES);
    final String typeName = (String) properties.get("Type");
    final Instance curInstance;
    if (parent.getType().isKindOf(CIAccounting.TransactionAbstract.getType())) {
        final PrintQuery print = new PrintQuery(parent);
        final SelectBuilder sel = new SelectBuilder().linkto(CIAccounting.TransactionAbstract.PeriodLink).oid();
        print.addSelect(sel);
        print.execute();
        final Instance periodInst = Instance.get(print.<String>getSelect(sel));
        curInstance = new Period().getCurrency(periodInst).getInstance();
    } else {
        curInstance = new Period().getCurrency(_parameter.getCallInstance()).getInstance();
    }
    BigDecimal amount = DecimalType.parseLocalized(amountStr);
    final Type type = Type.get(typeName);
    if (!type.getUUID().equals(CIAccounting.TransactionPositionCredit.uuid)) {
        amount = amount.negate();
    }
    final Object[] rateObj = new Transaction().getRateObject(_parameter, "", 0);
    final BigDecimal rate = ((BigDecimal) rateObj[0]).divide((BigDecimal) rateObj[1], 12,
            BigDecimal.ROUND_HALF_UP);
    final Insert insert = new Insert(type);
    insert.add(CIAccounting.TransactionPositionAbstract.TransactionLink, parent.getId());
    insert.add(CIAccounting.TransactionPositionAbstract.AccountLink, Instance.get(account).getId());
    insert.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, curInstance.getId());
    insert.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, rateCurrencyLink);
    insert.add(CIAccounting.TransactionPositionAbstract.Rate, rateObj);
    insert.add(CIAccounting.TransactionPositionAbstract.Amount,
            amount.divide(rate, 12, BigDecimal.ROUND_HALF_UP));
    insert.add(CIAccounting.TransactionPositionAbstract.RateAmount, amount);
    insert.execute();
    return new Return();
}

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

/**
 * @param _parameter Parameter as passed from the eFaps API
 * @param _doc          Document/*w w w  .  ja v a  2  s .  co  m*/
 * @param _transInst    Transaction Instance
 * @param _type         CITYpe
 * @param _account      TargetAccount
 * @return Instance of the new position
 * @throws EFapsException   on error
 */
protected Instance insertPosition4Massiv(final Parameter _parameter, final DocumentInfo _doc,
        final Instance _transInst, final CIType _type, final AccountInfo _account) throws EFapsException {
    final boolean isDebitTrans = _type.equals(CIAccounting.TransactionPositionDebit);
    final Instance accInst = _account.getInstance();
    Instance periodInst = _parameter.getCallInstance();
    if (_parameter.getCallInstance().getType().isKindOf(CIAccounting.SubPeriod.getType())) {
        final PrintQuery print = new CachedPrintQuery(_parameter.getCallInstance(), SubPeriod_Base.CACHEKEY);
        final SelectBuilder selPeriodInst = SelectBuilder.get().linkto(CIAccounting.SubPeriod.PeriodLink)
                .instance();
        print.addSelect(selPeriodInst);
        print.execute();
        periodInst = print.<Instance>getSelect(selPeriodInst);
    }
    final Instance curInstance = new Period().getCurrency(periodInst).getInstance();
    final Insert insert = new Insert(_type);
    insert.add(CIAccounting.TransactionPositionAbstract.TransactionLink, _transInst.getId());
    insert.add(CIAccounting.TransactionPositionAbstract.AccountLink, accInst.getId());
    insert.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, curInstance);
    insert.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink,
            _account.getRateInfo().getCurrencyInstance());
    insert.add(CIAccounting.TransactionPositionAbstract.Rate,
            new Object[] { _doc.getRateInfo().getRate(), _account.getRateInfo().getRate() });
    final BigDecimal rateAmount = _account.getAmount();
    insert.add(CIAccounting.TransactionPositionAbstract.RateAmount,
            isDebitTrans ? rateAmount.negate() : rateAmount);
    final BigDecimal amount = _account.getAmountRate(_parameter).setScale(2, BigDecimal.ROUND_HALF_UP);
    insert.add(CIAccounting.TransactionPositionAbstract.Amount, isDebitTrans ? amount.negate() : amount);
    insert.execute();

    final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.Account2AccountAbstract);
    queryBldr.addWhereAttrEqValue(CIAccounting.Account2AccountAbstract.FromAccountLink, accInst.getId());
    final MultiPrintQuery multi = queryBldr.getPrint();
    multi.addAttribute(CIAccounting.Account2AccountAbstract.Numerator,
            CIAccounting.Account2AccountAbstract.Denominator,
            CIAccounting.Account2AccountAbstract.ToAccountLink, CIAccounting.Account2AccountAbstract.Config);
    multi.execute();
    while (multi.next()) {
        final Instance instance = multi.getCurrentInstance();
        boolean add = false;
        Insert insert3 = null;
        BigDecimal amount2 = amount.multiply(
                new BigDecimal(multi.<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Numerator))
                        .divide(new BigDecimal(
                                multi.<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Denominator)),
                                BigDecimal.ROUND_HALF_UP));
        BigDecimal rateAmount2 = rateAmount.multiply(
                new BigDecimal(multi.<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Numerator))
                        .divide(new BigDecimal(
                                multi.<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Denominator)),
                                BigDecimal.ROUND_HALF_UP));
        if (instance.getType().getUUID().equals(CIAccounting.Account2AccountCosting.uuid)) {
            add = true;
            insert3 = new Insert(_type);
        } else if (instance.getType().getUUID().equals(CIAccounting.Account2AccountCostingInverse.uuid)) {
            if (_type.equals(CIAccounting.TransactionPositionDebit)) {
                insert3 = new Insert(CIAccounting.TransactionPositionCredit);
            } else {
                insert3 = new Insert(CIAccounting.TransactionPositionDebit);
            }
            amount2 = amount2.negate();
            rateAmount2 = rateAmount2.negate();
            add = true;
        } else if (instance.getType().getUUID().equals(CIAccounting.Account2AccountCredit.uuid)) {
            if (isDebitTrans) {
                insert3 = new Insert(CIAccounting.TransactionPositionCredit);
            } else {
                insert3 = new Insert(CIAccounting.TransactionPositionDebit);
                amount2 = amount2.negate();
                rateAmount2 = rateAmount2.negate();
            }
            add = true;
        } else if (instance.getType().getUUID().equals(CIAccounting.Account2AccountDebit.uuid)) {
            if (isDebitTrans) {
                insert3 = new Insert(CIAccounting.TransactionPositionDebit);
                amount2 = amount2.negate();
                rateAmount2 = rateAmount2.negate();
            } else {
                insert3 = new Insert(CIAccounting.TransactionPositionCredit);
            }
            add = true;
        }
        final Collection<Accounting.Account2AccountConfig> configs = multi
                .getAttribute(CIAccounting.Account2AccountAbstract.Config);

        add = add && (isDebitTrans && configs != null
                && configs.contains(Accounting.Account2AccountConfig.APPLY4DEBIT)
                || !isDebitTrans && configs != null
                        && configs.contains(Accounting.Account2AccountConfig.APPLY4CREDIT));

        if (add) {
            insert3.add(CIAccounting.TransactionPositionAbstract.TransactionLink, _transInst.getId());
            insert3.add(CIAccounting.TransactionPositionAbstract.AccountLink,
                    multi.<Long>getAttribute(CIAccounting.Account2AccountAbstract.ToAccountLink));
            insert3.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, curInstance);
            insert3.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink,
                    _account.getRateInfo().getCurrencyInstance());
            insert3.add(CIAccounting.TransactionPositionAbstract.Rate,
                    new Object[] { _doc.getRateInfo().getRate(), _account.getRateInfo().getRate() });
            insert3.add(CIAccounting.TransactionPositionAbstract.Amount, amount2);
            insert3.add(CIAccounting.TransactionPositionAbstract.RateAmount, rateAmount2);
            insert3.execute();
        }
    }
    return insert.getInstance();
}

From source file:com.ibm.soatf.component.soap.builder.SampleXmlUtil.java

private String formatDecimal(String start, SchemaType sType) {
    BigDecimal result = new BigDecimal(start);
    XmlDecimal xmlD;/*  w  w w  . j  ava 2  s. c om*/
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
    BigDecimal min = xmlD != null ? xmlD.getBigDecimalValue() : null;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
    BigDecimal max = xmlD != null ? xmlD.getBigDecimalValue() : null;
    boolean minInclusive = true, maxInclusive = true;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
    if (xmlD != null) {
        BigDecimal minExcl = xmlD.getBigDecimalValue();
        if (min == null || min.compareTo(minExcl) < 0) {
            min = minExcl;
            minInclusive = false;
        }
    }
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
    if (xmlD != null) {
        BigDecimal maxExcl = xmlD.getBigDecimalValue();
        if (max == null || max.compareTo(maxExcl) > 0) {
            max = maxExcl;
            maxInclusive = false;
        }
    }
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_TOTAL_DIGITS);
    int totalDigits = -1;
    if (xmlD != null) {
        totalDigits = xmlD.getBigDecimalValue().intValue();

        StringBuilder sb = new StringBuilder(totalDigits);
        for (int i = 0; i < totalDigits; i++)
            sb.append('9');
        BigDecimal digitsLimit = new BigDecimal(sb.toString());
        if (max != null && max.compareTo(digitsLimit) > 0) {
            max = digitsLimit;
            maxInclusive = true;
        }
        digitsLimit = digitsLimit.negate();
        if (min != null && min.compareTo(digitsLimit) < 0) {
            min = digitsLimit;
            minInclusive = true;
        }
    }

    int sigMin = min == null ? 1 : result.compareTo(min);
    int sigMax = max == null ? -1 : result.compareTo(max);
    boolean minOk = sigMin > 0 || sigMin == 0 && minInclusive;
    boolean maxOk = sigMax < 0 || sigMax == 0 && maxInclusive;

    // Compute the minimum increment
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_FRACTION_DIGITS);
    int fractionDigits = -1;
    BigDecimal increment;
    if (xmlD == null)
        increment = new BigDecimal(1);
    else {
        fractionDigits = xmlD.getBigDecimalValue().intValue();
        if (fractionDigits > 0) {
            StringBuilder sb = new StringBuilder("0.");
            for (int i = 1; i < fractionDigits; i++)
                sb.append('0');
            sb.append('1');
            increment = new BigDecimal(sb.toString());
        } else
            increment = new BigDecimal(1);
    }

    if (minOk && maxOk) {
        // OK
    } else if (minOk && !maxOk) {
        // TOO BIG
        if (maxInclusive)
            result = max;
        else
            result = max.subtract(increment);
    } else if (!minOk && maxOk) {
        // TOO SMALL
        if (minInclusive)
            result = min;
        else
            result = min.add(increment);
    } else {
        // MIN > MAX!!
    }

    // We have the number
    // Adjust the scale according to the totalDigits and fractionDigits
    int digits = 0;
    BigDecimal ONE = new BigDecimal(BigInteger.ONE);
    for (BigDecimal n = result; n.abs().compareTo(ONE) >= 0; digits++)
        n = n.movePointLeft(1);

    if (fractionDigits > 0)
        if (totalDigits >= 0)
            result.setScale(Math.max(fractionDigits, totalDigits - digits));
        else
            result.setScale(fractionDigits);
    else if (fractionDigits == 0)
        result.setScale(0);

    return result.toString();
}

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

/**
 * Reduce value to the interval [-Pi/2,Pi/2].
 *
 * @param x The original value/*from   ww  w . j av  a 2  s  .  c  om*/
 * @return The value modulo pi, shifted to the interval from -Pi/2 to Pi/2.
 */
static public BigDecimal modpi(BigDecimal x) {
    /* write x= pi*k+r with the precision in r defined by the precision of x and not
     * compromised by the precision of pi, so the ulp of pi*k should match the ulp of x.
     * First getFloat a guess of k to figure out how many digits of pi are needed.
     */
    int k = (int) (x.doubleValue() / Math.PI);
    /* want to have err(pi*k)< err(x)=x.ulp/2, so err(pi) = err(x)/(2k) with two safety digits
     */

    double errpi;

    if (k != 0) {
        errpi = 0.5 * Math.abs(x.ulp().doubleValue() / k);
    } else {
        errpi = 0.5 * Math.abs(x.ulp().doubleValue());
    }
    MathContext mc = new MathContext(2 + err2prec(3.1416, errpi));
    BigDecimal onepi = pi(mc);
    BigDecimal pihalf = onepi.divide(new BigDecimal(2));
    /* Delegate the actual operation to the BigDecimal class, which may return
     * a negative value of x was negative .
     */
    BigDecimal res = x.remainder(onepi);

    if (res.compareTo(pihalf) > 0) {
        res = res.subtract(onepi);
    } else if (res.compareTo(pihalf.negate()) < 0) {
        res = res.add(onepi);
    }
    /* The actual precision is set by the input value, its absolute value of x.ulp()/2.
     */
    mc = new MathContext(err2prec(res.doubleValue(), x.ulp().doubleValue() / 2.));

    return res.round(mc);

}

From source file:com.centeractive.ws.builder.soap.SampleXmlUtil.java

private String formatDecimal(String start, SchemaType sType) {
    BigDecimal result = new BigDecimal(start);
    XmlDecimal xmlD;//  w  w  w. j a  v  a2s .  com
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
    BigDecimal min = xmlD != null ? xmlD.getBigDecimalValue() : null;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
    BigDecimal max = xmlD != null ? xmlD.getBigDecimalValue() : null;
    boolean minInclusive = true, maxInclusive = true;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
    if (xmlD != null) {
        BigDecimal minExcl = xmlD.getBigDecimalValue();
        if (min == null || min.compareTo(minExcl) < 0) {
            min = minExcl;
            minInclusive = false;
        }
    }
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
    if (xmlD != null) {
        BigDecimal maxExcl = xmlD.getBigDecimalValue();
        if (max == null || max.compareTo(maxExcl) > 0) {
            max = maxExcl;
            maxInclusive = false;
        }
    }
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_TOTAL_DIGITS);
    int totalDigits = -1;
    if (xmlD != null) {
        totalDigits = xmlD.getBigDecimalValue().intValue();

        StringBuffer sb = new StringBuffer(totalDigits);
        for (int i = 0; i < totalDigits; i++)
            sb.append('9');
        BigDecimal digitsLimit = new BigDecimal(sb.toString());
        if (max != null && max.compareTo(digitsLimit) > 0) {
            max = digitsLimit;
            maxInclusive = true;
        }
        digitsLimit = digitsLimit.negate();
        if (min != null && min.compareTo(digitsLimit) < 0) {
            min = digitsLimit;
            minInclusive = true;
        }
    }

    int sigMin = min == null ? 1 : result.compareTo(min);
    int sigMax = max == null ? -1 : result.compareTo(max);
    boolean minOk = sigMin > 0 || sigMin == 0 && minInclusive;
    boolean maxOk = sigMax < 0 || sigMax == 0 && maxInclusive;

    // Compute the minimum increment
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_FRACTION_DIGITS);
    int fractionDigits = -1;
    BigDecimal increment;
    if (xmlD == null)
        increment = new BigDecimal(1);
    else {
        fractionDigits = xmlD.getBigDecimalValue().intValue();
        if (fractionDigits > 0) {
            StringBuffer sb = new StringBuffer("0.");
            for (int i = 1; i < fractionDigits; i++)
                sb.append('0');
            sb.append('1');
            increment = new BigDecimal(sb.toString());
        } else
            increment = new BigDecimal(1);
    }

    if (minOk && maxOk) {
        // OK
    } else if (minOk && !maxOk) {
        // TOO BIG
        if (maxInclusive)
            result = max;
        else
            result = max.subtract(increment);
    } else if (!minOk && maxOk) {
        // TOO SMALL
        if (minInclusive)
            result = min;
        else
            result = min.add(increment);
    } else {
        // MIN > MAX!!
    }

    // We have the number
    // Adjust the scale according to the totalDigits and fractionDigits
    int digits = 0;
    BigDecimal ONE = new BigDecimal(BigInteger.ONE);
    for (BigDecimal n = result; n.abs().compareTo(ONE) >= 0; digits++)
        n = n.movePointLeft(1);

    if (fractionDigits > 0)
        if (totalDigits >= 0)
            result.setScale(Math.max(fractionDigits, totalDigits - digits));
        else
            result.setScale(fractionDigits);
    else if (fractionDigits == 0)
        result.setScale(0);

    return result.toString();
}

From source file:org.openvpms.archetype.rules.finance.till.TillRulesTestCase.java

private BigDecimal checkBalance(BigDecimal initialCashFloat, BigDecimal newCashFloat, FinancialAct balance,
        String status) {/*  w w w  . j  a v  a2s.  co  m*/
    // make sure the balance is updated
    assertEquals(status, balance.getStatus());
    // end time should be > startTime < now
    Date startTime = balance.getActivityStartTime();
    Date endTime = balance.getActivityEndTime();
    if (TillBalanceStatus.CLEARED.equals(status)) {
        // CLEARED balances have an end time
        assertEquals(1, endTime.compareTo(startTime));
        assertEquals(-1, endTime.compareTo(new Date()));
    } else {
        // IN_PROGRESS balances do not
        assertNull(endTime);
    }

    BigDecimal total = newCashFloat.subtract(initialCashFloat);

    if (initialCashFloat.compareTo(newCashFloat) != 0) {
        // expect a till balance adjustment to have been made
        Set<ActRelationship> rels = balance.getSourceActRelationships();
        assertEquals(1, rels.size());
        ActRelationship r = rels.toArray(new ActRelationship[rels.size()])[0];
        Act target = (Act) get(r.getTarget());
        assertTrue(TypeHelper.isA(target, "act.tillBalanceAdjustment"));
        ActBean adjBean = new ActBean(target);
        BigDecimal amount = adjBean.getBigDecimal("amount");

        boolean credit = (newCashFloat.compareTo(initialCashFloat) < 0);
        BigDecimal adjustmentTotal = total.abs();
        assertTrue(adjustmentTotal.compareTo(amount) == 0);
        assertEquals(credit, adjBean.getBoolean("credit"));
    } else {
        // no till balance adjustment should have been generated
        assertTrue(balance.getSourceActRelationships().isEmpty());
    }

    // check the till balance.
    BigDecimal expectedBalance = total.negate();
    assertTrue(expectedBalance.compareTo(balance.getTotal()) == 0);

    // make sure the till is updated
    Party till = (Party) get(this.till.getObjectReference());
    IMObjectBean bean = new IMObjectBean(till);
    BigDecimal currentFloat = bean.getBigDecimal("tillFloat");
    Date lastCleared = bean.getDate("lastCleared");
    Date now = new Date();

    assertTrue(currentFloat.compareTo(newCashFloat) == 0);
    assertTrue(now.compareTo(lastCleared) == 1); // expect now > lastCleared
    return expectedBalance;
}

From source file:uk.ac.leeds.ccg.andyt.generic.visualisation.charts.Generic_ScatterPlotAndLinearRegression.java

/**
 * @param regressionParameters regressionParameters[0] is the y axis
 * intercept; regressionParameters[1] is the change in y relative to x
 * (gradient or slope); regressionParameters[2] is the rank correlation
 * coefficient (RSquare); regressionParameters[3] is data[0].length.
 *//*from ww  w  . j a v a2s  . c  o m*/
protected void drawLegend(double[] regressionParameters) {
    //        int[] result = new int[3];

    int newLegendWidth = 0;
    int newLegendHeight = 0;
    //        int legendExtraWidthLeft = 0;
    //        int legendExtraWidthRight = 0;
    int textHeight = getTextHeight();
    int legendExtraHeightBottom = textHeight;

    int legendStartRow = getDataEndRow() + getxAxisHeight();
    //        int legendStartRow = this.dataEndRow + this.xAxisHeight / 2;
    int symbolRow;
    int row;
    int symbolCol;
    int col;
    int symbolWidth = 10;
    // Legend Title
    setPaint(Color.DARK_GRAY);
    int legendItemWidth = 0;

    String text = "Legend";
    int textWidth = getTextWidth(text);
    newLegendHeight += textHeight;
    row = legendStartRow + newLegendHeight;
    //col = dataStartCol - yAxisWidth;
    col = textHeight;
    legendItemWidth += textWidth;
    newLegendWidth = Math.max(newLegendWidth, legendItemWidth);
    drawString(text, col, row);
    Point2D.Double point = new Point2D.Double();

    // Point marker
    legendItemWidth = 0;
    newLegendHeight += textHeight;
    symbolRow = legendStartRow + newLegendHeight;
    legendItemWidth += symbolWidth;
    symbolCol = col + symbolWidth / 2;
    point.setLocation(symbolCol, symbolRow);
    setPaint(Color.DARK_GRAY);
    draw(point);
    row += ((3 * textHeight) / 2) - 2;
    newLegendHeight += (textHeight / 2) - 2;
    col += symbolWidth + 4;
    setPaint(Color.GRAY);
    text = "Data Point";
    textWidth = getTextWidth(text);
    legendItemWidth += textWidth;
    newLegendWidth = Math.max(newLegendWidth, legendItemWidth);
    drawString(text, col, row);
    // Y = X line
    setPaint(Color.LIGHT_GRAY);
    //int itemSymbolWidth = (symbolCol + symbolWidth / 2) - (symbolCol - symbolWidth / 2);
    //legendItemWidth = itemSymbolWidth;        
    //legendItemWidth = symbolWidth + 4;
    symbolRow += textHeight;
    draw(new Line2D.Double(symbolCol - symbolWidth / 2, (symbolRow + textHeight / 2) - 2,
            symbolCol + symbolWidth / 2, (symbolRow - textHeight / 2) + 2));
    setPaint(Color.GRAY);
    row += textHeight;
    text = "Y = X";
    textWidth = getTextWidth(text);
    drawString(text, col, row);
    legendItemWidth = textWidth;
    newLegendWidth = Math.max(newLegendWidth, legendItemWidth);
    newLegendHeight += textHeight + 4;

    // Regression line
    setPaint(Color.DARK_GRAY);
    legendItemWidth = symbolWidth + 4;
    symbolRow += textHeight;
    row += textHeight;
    draw(new Line2D.Double(symbolCol - symbolWidth / 2, (symbolRow + textHeight / 2) - 2,
            symbolCol + symbolWidth / 2, (symbolRow - textHeight / 2) + 2));
    setPaint(Color.GRAY);
    // Y = mX + c
    // generalise m
    int scale = 4;
    BigDecimal m;
    if (Double.isNaN(regressionParameters[1])) {
        m = BigDecimal.ZERO;
    } else {
        m = BigDecimal.valueOf(regressionParameters[1]);
    }
    RoundingMode roundingMode = getRoundingMode();
    m = m.setScale(scale, roundingMode);
    m = m.stripTrailingZeros();
    //        m = Generic_BigDecimal.roundStrippingTrailingZeros(
    //                m, 
    //                decimalPlacePrecision,
    //                _RoundingMode);
    BigDecimal c;
    if (Double.isNaN(regressionParameters[0])) {
        c = BigDecimal.ZERO;
    } else {
        c = BigDecimal.valueOf(regressionParameters[0]);
    }
    c = c.setScale(scale, roundingMode);
    c = c.stripTrailingZeros();
    BigDecimal rsquare;
    if (Double.isNaN(regressionParameters[2])) {
        rsquare = BigDecimal.ZERO;
    } else {
        rsquare = BigDecimal.valueOf(regressionParameters[2]);
    }
    rsquare = rsquare.setScale(3, roundingMode);
    rsquare = rsquare.stripTrailingZeros();
    String equation;
    if (c.compareTo(BigDecimal.ZERO) != -1) {
        equation = "Y = (" + m + " * X) + " + c + "";
    } else {
        equation = "Y = (" + m + " * X) - " + c.negate() + "";
    }
    drawString(equation, col, row);
    textWidth = getTextWidth(equation);
    legendItemWidth += textWidth;
    newLegendWidth = Math.max(newLegendWidth, legendItemWidth);
    newLegendHeight += textHeight;

    // Rsquare component
    String rsquare_String = "RSquare = " + rsquare;
    textWidth = getTextWidth(rsquare_String);
    legendItemWidth = textWidth;
    row += textHeight;
    drawString(rsquare_String, col, row);
    //setLegendHeight(row - legendStartRow);
    newLegendWidth = Math.max(newLegendWidth, legendItemWidth);
    newLegendHeight += (2 * textHeight);

    int imageWidth = getImageWidth();
    int dataWidth = getDataWidth();
    int extraWidthLeft = getExtraWidthLeft();
    if (newLegendWidth > getLegendWidth()) {
        //int diff = newLegendWidth - legendWidth;
        if (newLegendWidth > imageWidth) {
            setImageWidth(newLegendWidth);
            setExtraWidthRight(newLegendWidth - extraWidthLeft - dataWidth);
        }
        setLegendWidth(newLegendWidth);
    }
    int extraHeightBottom = getExtraHeightBottom();
    if (newLegendHeight > getLegendHeight()) {
        //int diff = newLegendHeight - legendHeight;
        //int heightForLegend = legendStartRow - dataStartRow + newLegendHeight;
        int newExtraHeightBottom = newLegendHeight + getxAxisHeight();
        if (newExtraHeightBottom > extraHeightBottom) {
            int diff2 = newExtraHeightBottom - extraHeightBottom;
            setExtraHeightBottom(newExtraHeightBottom);
            setImageHeight(getImageHeight() + diff2);
        }
        setLegendHeight(newLegendHeight);
    }
    //        result[0] = legendExtraWidthLeft;
    //        result[1] = legendExtraWidthRight;
    //        result[2] = legendExtraHeightBottom;

    //        return result;

}

From source file:org.efaps.esjp.accounting.report.PurchaseRecordReport_Base.java

@SuppressWarnings("unchecked")
@Override/*from   w  w w  . j  a va2  s .c  om*/
public void init(final JasperReport _jasperReport, final Parameter _parameter, final JRDataSource _parentSource,
        final Map<String, Object> _jrParameters) throws EFapsException {
    QueryCache.cleanByKey(PurchaseRecordReport_Base.CACHEDQUERYKEY);

    final List<Map<String, Object>> values = new ArrayList<>();
    final List<Instance> instances = getInstances(_parameter);

    if (instances.size() > 0) {
        final Map<Instance, PosSum4Doc> posSums = getPosSums(_parameter);

        final SelectBuilder selRel = new SelectBuilder().linkto(CIAccounting.PurchaseRecord2Document.ToLink);
        final SelectBuilder selRelDocType = new SelectBuilder(selRel).type();
        final SelectBuilder selRelDocInst = new SelectBuilder(selRel).instance();
        final SelectBuilder selRelDocName = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Name);
        final SelectBuilder selRelDocRevision = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Revision);
        final SelectBuilder selRelDocDate = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Date);
        final SelectBuilder selRelDocDueDate = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.DueDate);
        final SelectBuilder selRelDocNTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.NetTotal);
        final SelectBuilder selRelDocCTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.CrossTotal);
        final SelectBuilder selRelDocRNTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.RateNetTotal);
        final SelectBuilder selRelDocRCTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.RateCrossTotal);
        final SelectBuilder selRelDocRateLabel = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Rate).label();

        final SelectBuilder selRelDocCurInst = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.CurrencyId).instance();
        final SelectBuilder selRelDocRCurInst = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.RateCurrencyId).instance();

        final SelectBuilder selRelDocContact = new SelectBuilder(selRel)
                .linkto(CISales.DocumentSumAbstract.Contact);
        final SelectBuilder selRelDocContactName = new SelectBuilder(selRelDocContact)
                .attribute(CIContacts.Contact.Name);
        final SelectBuilder selRelDocContactTax = new SelectBuilder(selRelDocContact)
                .clazz(CIContacts.ClassOrganisation).attribute(CIContacts.ClassOrganisation.TaxNumber);
        final SelectBuilder selRelDocContactIdenityCard = new SelectBuilder(selRelDocContact)
                .clazz(CIContacts.ClassPerson).attribute(CIContacts.ClassPerson.IdentityCard);
        final SelectBuilder selRelDocContactDOIType = new SelectBuilder(selRelDocContact)
                .clazz(CIContacts.ClassPerson).linkto(CIContacts.ClassPerson.DOITypeLink)
                .attribute(CIContacts.AttributeDefinitionDOIType.MappingKey);

        final SelectBuilder selRelTypeLink = new SelectBuilder()
                .linkto(CIAccounting.PurchaseRecord2Document.TypeLink);
        final SelectBuilder selRelTypeLinkName = new SelectBuilder(selRelTypeLink)
                .attribute(CIERP.DocumentType.Name);

        final MultiPrintQuery multi = new MultiPrintQuery(instances);
        multi.addSelect(selRelDocType, selRelDocInst, selRelDocName, selRelDocRevision, selRelDocDate,
                selRelDocDueDate, selRelDocNTotal, selRelDocCTotal, selRelDocRNTotal, selRelDocRCTotal,
                selRelDocRateLabel, selRelDocCurInst, selRelDocRCurInst, selRelDocContactName,
                selRelDocContactTax, selRelTypeLinkName, selRelDocContactIdenityCard, selRelDocContactDOIType);
        multi.addAttribute(CIAccounting.PurchaseRecord2Document.DetractionDate,
                CIAccounting.PurchaseRecord2Document.DetractionName,
                CIAccounting.PurchaseRecord2Document.DetractionAmount,
                CIAccounting.PurchaseRecord2Document.Taxed);
        multi.execute();

        while (multi.next()) {
            final Map<String, Object> map = new HashMap<>();
            final Type docType = multi.<Type>getSelect(selRelDocType);
            final Instance instDoc = multi.<Instance>getSelect(selRelDocInst);
            final String docName = multi.<String>getSelect(selRelDocName);
            final DateTime docDate = multi.<DateTime>getSelect(selRelDocDate);
            final DateTime docDueDate = multi.<DateTime>getSelect(selRelDocDueDate);
            final String contactName = multi.<String>getSelect(selRelDocContactName);
            final String contactTaxNum = multi.<String>getSelect(selRelDocContactTax);
            final BigDecimal rateTmp = multi.<BigDecimal>getSelect(selRelDocRateLabel);
            final String typeLinkName = multi.<String>getSelect(selRelTypeLinkName);
            final String docRevision = multi.<String>getSelect(selRelDocRevision);
            final String docContactIdenityCard = multi.<String>getSelect(selRelDocContactIdenityCard);
            final String docContactDOIType = multi.<String>getSelect(selRelDocContactDOIType);
            final Taxed4PurchaseRecord taxed = multi.getAttribute(CIAccounting.PurchaseRecord2Document.Taxed);

            final String detractionName = multi
                    .<String>getAttribute(CIAccounting.PurchaseRecord2Document.DetractionName);
            final BigDecimal detractionAmount = multi
                    .<BigDecimal>getAttribute(CIAccounting.PurchaseRecord2Document.DetractionAmount);
            final DateTime detractionDate = multi
                    .<DateTime>getAttribute(CIAccounting.PurchaseRecord2Document.DetractionDate);
            final Instance docDerivatedRel = getDocumentDerivated(instDoc, true) == null
                    ? getDocumentDerivated(instDoc, false)
                    : getDocumentDerivated(instDoc, true);

            BigDecimal netTotal = multi.<BigDecimal>getSelect(selRelDocNTotal);
            BigDecimal crossTotal = multi.<BigDecimal>getSelect(selRelDocCTotal);

            final PosSum4Doc posSum = posSums.get(instDoc);
            BigDecimal taxfree;
            if (posSum != null) {
                taxfree = posSum.getTaxFree(_parameter);
            } else {
                taxfree = BigDecimal.ZERO;
            }
            BigDecimal igv = crossTotal.subtract(netTotal);
            netTotal = netTotal.subtract(taxfree);

            if (crossTotal.compareTo(netTotal) == 0) {
                taxfree = netTotal;
                netTotal = BigDecimal.ZERO;
            }

            if (CISales.IncomingCreditNote.getType().equals(docType)) {
                netTotal = netTotal.negate();
                crossTotal = crossTotal.negate();
                igv = igv.negate();
                taxfree = taxfree.negate();
            }

            PurchaseRecordReport_Base.LOG.debug("Document OID '{}'", instDoc.getOid());
            PurchaseRecordReport_Base.LOG.debug("Document name '{}'", docName);

            map.put(PurchaseRecordReport_Base.Field.DOC_RATE.getKey(), rateTmp);
            map.put(PurchaseRecordReport_Base.Field.DOC_DATE.getKey(), docDate);
            map.put(PurchaseRecordReport_Base.Field.DOC_DUEDATE.getKey(), docDueDate);
            map.put(PurchaseRecordReport_Base.Field.DOC_NAME.getKey(), docName);
            map.put(PurchaseRecordReport_Base.Field.DOC_CONTACT.getKey(), contactName);
            Boolean isDOI = false;
            String taxNum = contactTaxNum;
            if (taxNum == null || taxNum != null && taxNum.isEmpty()) {
                if (docContactIdenityCard != null && !docContactIdenityCard.isEmpty()) {
                    taxNum = docContactIdenityCard;
                    isDOI = true;
                }
            }
            map.put(PurchaseRecordReport_Base.Field.DOC_TAXNUM.getKey(), taxNum);

            switch (taxed) {
            case TAXED:
                map.put(PurchaseRecordReport_Base.Field.DOC_NETTOTALTAXED.getKey(), netTotal);
                map.put(PurchaseRecordReport_Base.Field.DOC_IGVTAXED.getKey(), igv);
                break;
            case EXPORT:
                map.put(PurchaseRecordReport_Base.Field.DOC_NETTOTALEXPORT.getKey(), netTotal);
                map.put(PurchaseRecordReport_Base.Field.DOC_IGVEXPORT.getKey(), igv);
                break;
            case UNTAXED:
                map.put(PurchaseRecordReport_Base.Field.DOC_NETTOTALUNTAXED.getKey(), netTotal);
                map.put(PurchaseRecordReport_Base.Field.DOC_IGVUNTAXED.getKey(), igv);
                break;
            default:
                break;
            }

            map.put(PurchaseRecordReport_Base.Field.DOC_CROSSTOTAL.getKey(), crossTotal);
            map.put(PurchaseRecordReport_Base.Field.DOC_VALUENOTAX.getKey(), taxfree);

            final String[] nameAr = docName.split("\\W");

            if (nameAr.length == 2 && nameAr[0].length() < nameAr[1].length()) {
                map.put(PurchaseRecordReport_Base.Field.DOC_SN.getKey(), nameAr[0]);
                map.put(PurchaseRecordReport_Base.Field.DOC_NUMBER.getKey(), nameAr[1]);
            } else {
                map.put(PurchaseRecordReport_Base.Field.DOC_SN.getKey(), "");
                map.put(PurchaseRecordReport_Base.Field.DOC_NUMBER.getKey(), docName);
            }

            map.put(PurchaseRecordReport_Base.Field.DOC_DOCTYPE.getKey(), typeLinkName);
            map.put(PurchaseRecordReport_Base.Field.DOC_REVISION.getKey(), docRevision);
            map.put(PurchaseRecordReport_Base.Field.DETRACTION_NAME.getKey(), detractionName);
            map.put(PurchaseRecordReport_Base.Field.DETRACTION_AMOUNT.getKey(), detractionAmount);
            map.put(PurchaseRecordReport_Base.Field.DETRACTION_DATE.getKey(),
                    detractionAmount == null ? null : detractionDate);

            if (docDerivatedRel != null && docDerivatedRel.isValid()) {
                final SelectBuilder selLinkName = new SelectBuilder()
                        .linkfrom(CISales.Document2DocumentType, CISales.Document2DocumentType.DocumentLink)
                        .linkto(CISales.Document2DocumentType.DocumentTypeLink)
                        .attribute(CIERP.DocumentType.Name);

                final PrintQuery printDocRel = new PrintQuery(docDerivatedRel);
                printDocRel.addAttribute(CISales.DocumentSumAbstract.Date, CISales.DocumentSumAbstract.Name);
                printDocRel.addSelect(selLinkName);
                printDocRel.execute();

                final DateTime docRelDate = printDocRel
                        .<DateTime>getAttribute(CISales.DocumentSumAbstract.Date);
                final String docRelName = printDocRel.<String>getAttribute(CISales.DocumentSumAbstract.Name);

                map.put(PurchaseRecordReport_Base.Field.DOCREL_DATE.getKey(), docRelDate);
                map.put(PurchaseRecordReport_Base.Field.DOCREL_PREFNAME.getKey(),
                        docRelName.split("-").length == 2 ? docRelName.split("-")[0] : "");
                map.put(PurchaseRecordReport_Base.Field.DOCREL_SUFNAME.getKey(),
                        docRelName.split("-").length == 2 ? docRelName.split("-")[1] : docRelName);
                map.put(PurchaseRecordReport_Base.Field.DOCREL_TYPE.getKey(),
                        printDocRel.<String>getSelect(selLinkName));
            }

            // TODO falta implementar
            map.put(PurchaseRecordReport_Base.Field.DUA_YEAR.getKey(), "0");
            map.put(PurchaseRecordReport_Base.Field.RETENCION_APPLIES.getKey(), false);

            if (isDOI) {
                map.put(PurchaseRecordReport_Base.Field.DOC_CONTACTDOI.getKey(), docContactDOIType);
            } else if (contactTaxNum.length() == 11) {
                map.put(PurchaseRecordReport_Base.Field.DOC_CONTACTDOI.getKey(), "6");
            } else {
                map.put(PurchaseRecordReport_Base.Field.DOC_CONTACTDOI.getKey(), "0");
            }

            final DateTime purchaseDate = getDate4Purchase(_parameter);
            final Integer diff = purchaseDate.getMonthOfYear() - docDate.getMonthOfYear();

            if (Math.abs(diff) > 12) {
                map.put(PurchaseRecordReport_Base.Field.DOC_STATE.getKey(), DocState.OUSIDE.getKey());
            } else if (Math.abs(diff) > 0) {
                map.put(PurchaseRecordReport_Base.Field.DOC_STATE.getKey(), DocState.INSIDE.getKey());
            } else {
                map.put(PurchaseRecordReport_Base.Field.DOC_STATE.getKey(), DocState.NORMAL.getKey());
            }

            values.add(map);
        }
    }
    final ComparatorChain chain = new ComparatorChain();
    chain.addComparator(new Comparator<Map<String, Object>>() {

        @Override
        public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) {
            final String val1 = (String) _o1.get(PurchaseRecordReport_Base.Field.DOC_DOCTYPE.getKey());
            final String val2 = (String) _o2.get(PurchaseRecordReport_Base.Field.DOC_DOCTYPE.getKey());
            return val1.compareTo(val2);
        }
    });
    chain.addComparator(new Comparator<Map<String, Object>>() {

        @Override
        public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) {
            final DateTime date1 = (DateTime) _o1.get(PurchaseRecordReport_Base.Field.DOC_DATE.getKey());
            final DateTime date2 = (DateTime) _o2.get(PurchaseRecordReport_Base.Field.DOC_DATE.getKey());
            return date1.compareTo(date2);
        }
    });
    chain.addComparator(new Comparator<Map<String, Object>>() {

        @Override
        public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) {
            final String val1 = (String) _o1.get(PurchaseRecordReport_Base.Field.DOC_NAME.getKey());
            final String val2 = (String) _o2.get(PurchaseRecordReport_Base.Field.DOC_NAME.getKey());
            return val1.compareTo(val2);
        }
    });

    Collections.sort(values, chain);
    getValues().addAll(values);
}

From source file:com.axelor.apps.account.service.MoveLineExportService.java

/**
 * Mthode ralisant l'export SI - Agresso des fichiers dtails
 * @param mlr/*from   w  w w .  j av a 2  s.  co m*/
 * @param fileName
 * @throws AxelorException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public void exportMoveLineAllTypeSelectFILE2(MoveLineReport moveLineReport, String fileName)
        throws AxelorException, IOException {

    log.info("In export service FILE 2 :");

    Company company = moveLineReport.getCompany();

    String companyCode = "";
    String moveLineQueryStr = "";

    int typeSelect = moveLineReport.getTypeSelect();

    if (company != null) {
        companyCode = company.getCode();
        moveLineQueryStr += String.format(" AND self.move.company = %s", company.getId());
    }
    if (moveLineReport.getJournal() != null) {
        moveLineQueryStr += String.format(" AND self.move.journal = %s", moveLineReport.getJournal().getId());
    } else {
        moveLineQueryStr += String.format(" AND self.move.journal.type = %s",
                moveLineReportService.getJournalType(moveLineReport).getId());
    }

    if (moveLineReport.getPeriod() != null) {
        moveLineQueryStr += String.format(" AND self.move.period = %s", moveLineReport.getPeriod().getId());
    }
    if (moveLineReport.getDateFrom() != null) {
        moveLineQueryStr += String.format(" AND self.date >= '%s'", moveLineReport.getDateFrom().toString());
    }

    if (moveLineReport.getDateTo() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDateTo().toString());
    }
    if (moveLineReport.getDate() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDate().toString());
    }
    if (typeSelect != 8) {
        moveLineQueryStr += String.format(" AND self.account.reconcileOk = false ");
    }
    moveLineQueryStr += String.format(
            "AND self.move.accountingOk = true AND self.move.ignoreInAccountingOk = false AND self.move.moveLineReport = %s",
            moveLineReport.getId());
    moveLineQueryStr += String.format(" AND self.move.statusSelect = %s ", MoveRepository.STATUS_VALIDATED);

    Query queryDate = JPA.em().createQuery(
            "SELECT self.date from MoveLine self where self.account != null AND (self.debit > 0 OR self.credit > 0) "
                    + moveLineQueryStr + " group by self.date ORDER BY self.date");

    List<LocalDate> dates = new ArrayList<LocalDate>();
    dates = queryDate.getResultList();

    log.debug("dates : {}", dates);

    List<String[]> allMoveLineData = new ArrayList<String[]>();

    for (LocalDate localDate : dates) {

        Query queryExportAgressoRef = JPA.em().createQuery(
                "SELECT DISTINCT self.move.exportNumber from MoveLine self where self.account != null "
                        + "AND (self.debit > 0 OR self.credit > 0) AND self.date = '" + localDate.toString()
                        + "'" + moveLineQueryStr);
        List<String> exportAgressoRefs = new ArrayList<String>();
        exportAgressoRefs = queryExportAgressoRef.getResultList();
        for (String exportAgressoRef : exportAgressoRefs) {

            if (exportAgressoRef != null && !exportAgressoRef.isEmpty()) {

                int sequence = 1;

                Query query = JPA.em().createQuery(
                        "SELECT self.account.id from MoveLine self where self.account != null AND (self.debit > 0 OR self.credit > 0) "
                                + "AND self.date = '" + localDate.toString()
                                + "' AND self.move.exportNumber = '" + exportAgressoRef + "'" + moveLineQueryStr
                                + " group by self.account.id");

                List<Long> accountIds = new ArrayList<Long>();
                accountIds = query.getResultList();

                log.debug("accountIds : {}", accountIds);

                for (Long accountId : accountIds) {
                    if (accountId != null) {
                        String accountCode = accountRepo.find(accountId).getCode();
                        List<MoveLine> moveLines = moveLineRepo.all().filter(
                                "self.account.id = ?1 AND (self.debit > 0 OR self.credit > 0) AND self.date = '"
                                        + localDate.toString() + "' AND self.move.exportNumber = '"
                                        + exportAgressoRef + "'" + moveLineQueryStr,
                                accountId).fetch();

                        log.debug("movelines  : {} ", moveLines);

                        if (moveLines.size() > 0) {

                            List<MoveLine> moveLineList = moveLineService.consolidateMoveLines(moveLines);

                            List<MoveLine> sortMoveLineList = this.sortMoveLineByDebitCredit(moveLineList);

                            for (MoveLine moveLine3 : sortMoveLineList) {

                                Journal journal = moveLine3.getMove().getJournal();
                                LocalDate date = moveLine3.getDate();
                                String items[] = null;

                                if (typeSelect == 9) {
                                    items = new String[13];
                                } else {
                                    items = new String[12];
                                }

                                items[0] = companyCode;
                                items[1] = journal.getExportCode();
                                items[2] = moveLine3.getMove().getExportNumber();
                                items[3] = String.format("%s", sequence);
                                sequence++;
                                items[4] = accountCode;

                                BigDecimal totAmt = moveLine3.getCredit().subtract(moveLine3.getDebit());
                                String moveLineSign = "C";
                                if (totAmt.compareTo(BigDecimal.ZERO) == -1) {
                                    moveLineSign = "D";
                                    totAmt = totAmt.negate();
                                }
                                items[5] = moveLineSign;
                                items[6] = totAmt.toString();

                                String analyticAccounts = "";
                                for (AnalyticMoveLine analyticDistributionLine : moveLine3
                                        .getAnalyticMoveLineList()) {
                                    analyticAccounts = analyticAccounts
                                            + analyticDistributionLine.getAnalyticAccount().getCode() + "/";
                                }

                                if (typeSelect == 9) {
                                    items[7] = "";
                                    items[8] = analyticAccounts;
                                    items[9] = String.format("%s DU %s", journal.getCode(),
                                            date.format(DATE_FORMAT));
                                } else {
                                    items[7] = analyticAccounts;
                                    items[8] = String.format("%s DU %s", journal.getCode(),
                                            date.format(DATE_FORMAT));
                                }

                                allMoveLineData.add(items);

                            }
                        }
                    }
                }
            }
        }
    }

    String filePath = accountConfigService.getExportPath(accountConfigService.getAccountConfig(company));
    new File(filePath).mkdirs();

    log.debug("Full path to export : {}{}", filePath, fileName);
    CsvTool.csvWriter(filePath, fileName, '|', null, allMoveLineData);
    // Utilis pour le debuggage
    //         CsvTool.csvWriter(filePath, fileName, '|',  this.createHeaderForDetailFile(typeSelect), allMoveLineData);
}