Example usage for java.math BigDecimal ROUND_HALF_EVEN

List of usage examples for java.math BigDecimal ROUND_HALF_EVEN

Introduction

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

Prototype

int ROUND_HALF_EVEN

To view the source code for java.math BigDecimal ROUND_HALF_EVEN.

Click Source Link

Document

Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

Usage

From source file:com.lp.server.lieferschein.ejbfac.LieferscheinFacBean.java

public BigDecimal berechneOffenenLieferscheinwert(Integer kundeIId, TheClientDto theClientDto) {
    String queryString = "SELECT ls FROM FLRLieferschein AS ls WHERE ls.b_verrechenbar=1 AND ls.lieferscheinstatus_status_c_nr IN ('"
            + LocaleFac.STATUS_OFFEN + "','" + LocaleFac.STATUS_GELIEFERT + "') ";

    if (kundeIId != null) {
        queryString += " AND ls.kunde_i_id_rechnungsadresse=" + kundeIId;
    }//from   www.j av a2 s  .c om

    Session session = FLRSessionFactory.getFactory().openSession();
    org.hibernate.Query query = session.createQuery(queryString);
    List<?> results = query.list();
    Iterator<?> resultListIterator = results.iterator();

    BigDecimal wert = new BigDecimal(0);
    while (resultListIterator.hasNext()) {
        FLRLieferschein ls = (FLRLieferschein) resultListIterator.next();

        if (ls.getN_gesamtwertinlieferscheinwaehrung() != null) {
            wert = wert.add(ls.getN_gesamtwertinlieferscheinwaehrung().divide(
                    new BigDecimal(ls.getF_wechselkursmandantwaehrungzulieferscheinwaehrung()), 4,
                    BigDecimal.ROUND_HALF_EVEN));
        }

    }
    return wert;

}

From source file:org.pentaho.di.core.ConstTest.java

@Test
public void testRound_Long() {
    assertEquals(1L, Const.round(1L, 0, BigDecimal.ROUND_UP));
    assertEquals(1L, Const.round(1L, 0, BigDecimal.ROUND_DOWN));
    assertEquals(1L, Const.round(1L, 0, BigDecimal.ROUND_CEILING));
    assertEquals(1L, Const.round(1L, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(1L, Const.round(1L, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(1L, Const.round(1L, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(1L, Const.round(1L, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(1L, Const.round(1L, 0, Const.ROUND_HALF_CEILING));

    assertEquals(2L, Const.round(2L, 0, BigDecimal.ROUND_UP));
    assertEquals(2L, Const.round(2L, 0, BigDecimal.ROUND_DOWN));
    assertEquals(2L, Const.round(2L, 0, BigDecimal.ROUND_CEILING));
    assertEquals(2L, Const.round(2L, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(2L, Const.round(2L, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(2L, Const.round(2L, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(2L, Const.round(2L, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(2L, Const.round(2L, 0, Const.ROUND_HALF_CEILING));

    assertEquals(-1L, Const.round(-1L, 0, BigDecimal.ROUND_UP));
    assertEquals(-1L, Const.round(-1L, 0, BigDecimal.ROUND_DOWN));
    assertEquals(-1L, Const.round(-1L, 0, BigDecimal.ROUND_CEILING));
    assertEquals(-1L, Const.round(-1L, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(-1L, Const.round(-1L, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(-1L, Const.round(-1L, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-1L, Const.round(-1L, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-1L, Const.round(-1L, 0, Const.ROUND_HALF_CEILING));

    assertEquals(-2L, Const.round(-2L, 0, BigDecimal.ROUND_UP));
    assertEquals(-2L, Const.round(-2L, 0, BigDecimal.ROUND_DOWN));
    assertEquals(-2L, Const.round(-2L, 0, BigDecimal.ROUND_CEILING));
    assertEquals(-2L, Const.round(-2L, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(-2L, Const.round(-2L, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(-2L, Const.round(-2L, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-2L, Const.round(-2L, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-2L, Const.round(-2L, 0, Const.ROUND_HALF_CEILING));

    assertEquals(100L, Const.round(100L, -2, BigDecimal.ROUND_UP));
    assertEquals(100L, Const.round(100L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(100L, Const.round(100L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(100L, Const.round(100L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(100L, Const.round(100L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(100L, Const.round(100L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(100L, Const.round(100L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(100L, Const.round(100L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(200L, Const.round(120L, -2, BigDecimal.ROUND_UP));
    assertEquals(100L, Const.round(120L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(200L, Const.round(120L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(100L, Const.round(120L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(100L, Const.round(120L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(100L, Const.round(120L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(100L, Const.round(120L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(100L, Const.round(120L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(200L, Const.round(150L, -2, BigDecimal.ROUND_UP));
    assertEquals(100L, Const.round(150L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(200L, Const.round(150L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(100L, Const.round(150L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(200L, Const.round(150L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(100L, Const.round(150L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(200L, Const.round(150L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(200L, Const.round(150L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(200L, Const.round(170L, -2, BigDecimal.ROUND_UP));
    assertEquals(100L, Const.round(170L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(200L, Const.round(170L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(100L, Const.round(170L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(200L, Const.round(170L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(200L, Const.round(170L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(200L, Const.round(170L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(200L, Const.round(170L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(200L, Const.round(200L, -2, BigDecimal.ROUND_UP));
    assertEquals(200L, Const.round(200L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(200L, Const.round(200L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(200L, Const.round(200L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(200L, Const.round(200L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(200L, Const.round(200L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(200L, Const.round(200L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(200L, Const.round(200L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(300L, Const.round(220L, -2, BigDecimal.ROUND_UP));
    assertEquals(200L, Const.round(220L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(300L, Const.round(220L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(200L, Const.round(220L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(200L, Const.round(220L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(200L, Const.round(220L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(200L, Const.round(220L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(200L, Const.round(220L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(300L, Const.round(250L, -2, BigDecimal.ROUND_UP));
    assertEquals(200L, Const.round(250L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(300L, Const.round(250L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(200L, Const.round(250L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(300L, Const.round(250L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(200L, Const.round(250L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(200L, Const.round(250L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(300L, Const.round(250L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(300L, Const.round(270L, -2, BigDecimal.ROUND_UP));
    assertEquals(200L, Const.round(270L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(300L, Const.round(270L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(200L, Const.round(270L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(300L, Const.round(270L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(300L, Const.round(270L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(300L, Const.round(270L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(300L, Const.round(270L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-100L, Const.round(-100L, -2, BigDecimal.ROUND_UP));
    assertEquals(-100L, Const.round(-100L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-100L, Const.round(-100L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-100L, Const.round(-100L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-100L, Const.round(-100L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-100L, Const.round(-100L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-100L, Const.round(-100L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-100L, Const.round(-100L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-200L, Const.round(-120L, -2, BigDecimal.ROUND_UP));
    assertEquals(-100L, Const.round(-120L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-100L, Const.round(-120L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-200L, Const.round(-120L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-100L, Const.round(-120L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-100L, Const.round(-120L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-100L, Const.round(-120L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-100L, Const.round(-120L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-200L, Const.round(-150L, -2, BigDecimal.ROUND_UP));
    assertEquals(-100L, Const.round(-150L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-100L, Const.round(-150L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-200L, Const.round(-150L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-200L, Const.round(-150L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-100L, Const.round(-150L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-200L, Const.round(-150L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-100L, Const.round(-150L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-200L, Const.round(-170L, -2, BigDecimal.ROUND_UP));
    assertEquals(-100L, Const.round(-170L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-100L, Const.round(-170L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-200L, Const.round(-170L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-200L, Const.round(-170L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-200L, Const.round(-170L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-200L, Const.round(-170L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-200L, Const.round(-170L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-200L, Const.round(-200L, -2, BigDecimal.ROUND_UP));
    assertEquals(-200L, Const.round(-200L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-200L, Const.round(-200L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-200L, Const.round(-200L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-200L, Const.round(-200L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-200L, Const.round(-200L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-200L, Const.round(-200L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-200L, Const.round(-200L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-300L, Const.round(-220L, -2, BigDecimal.ROUND_UP));
    assertEquals(-200L, Const.round(-220L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-200L, Const.round(-220L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-300L, Const.round(-220L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-200L, Const.round(-220L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-200L, Const.round(-220L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-200L, Const.round(-220L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-200L, Const.round(-220L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-300L, Const.round(-250L, -2, BigDecimal.ROUND_UP));
    assertEquals(-200L, Const.round(-250L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-200L, Const.round(-250L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-300L, Const.round(-250L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-300L, Const.round(-250L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-200L, Const.round(-250L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-200L, Const.round(-250L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-200L, Const.round(-250L, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-300L, Const.round(-270L, -2, BigDecimal.ROUND_UP));
    assertEquals(-200L, Const.round(-270L, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-200L, Const.round(-270L, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-300L, Const.round(-270L, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-300L, Const.round(-270L, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-300L, Const.round(-270L, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-300L, Const.round(-270L, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-300L, Const.round(-270L, -2, Const.ROUND_HALF_CEILING));
}

From source file:com.ardhi.businessgame.services.BusinessGameService.java

public String sellStorageProduct(HttpServletRequest req) {
    String val = "0", idInc, sqls[];
    double remain, size, offer, basePrice, price, lowest, highest;
    ArrayList<String> sqlL = new ArrayList<String>();
    SqlRowSet srs1, srs2;/* ww w  .j  a  v a 2  s  .  c  o m*/

    //0 = internal error
    //1 = CBM yg ditawarkan lebih besar dari yg dimiliki
    //2 = harga melampaui 25% lebih murah dari harga jual yang disarankan
    //3 = harga melampaui 25% lebih mahal dari harga jual yang disarankan

    srs1 = db.getJdbc().queryForRowSet("select price,size from storage_product,desc_product where id='"
            + req.getParameter("productId") + "' and storage_product.[desc]=desc_product.id");
    if (srs1.next()) {
        size = srs1.getDouble("size");
        basePrice = srs1.getDouble("price");
    } else
        return "0";

    srs1 = db.getJdbc().queryForRowSet(
            "select size from market_product where storage_product_id='" + req.getParameter("productId") + "'");
    if (srs1.next())
        size -= srs1.getDouble("size");

    offer = Double.parseDouble(req.getParameter("offer"));
    price = Double.parseDouble(req.getParameter("price"));
    lowest = basePrice - (basePrice * 0.25);
    highest = basePrice + (basePrice * 0.25);

    if (size < offer)
        return "1";

    if (price < lowest)
        return "2";

    if (price > highest)
        return "3";

    srs1 = db.getJdbc()
            .queryForRowSet("select id,size from market_product where storage_product_id='"
                    + req.getParameter("productId") + "' and [zone]='" + req.getParameter("zone")
                    + "' and price='" + req.getParameter("price") + "'");
    if (srs1.next())
        sqlL.add("update market_product set size='" + (srs1.getDouble("size") + offer) + "' where id='"
                + srs1.getString("id") + "'");
    else {
        idInc = getUniqueIncrementIdNew("market_product");
        sqlL.add("insert into market_product values ('" + KEY_MARKET_PRODUCT + idInc + "','"
                + req.getParameter("productId") + "','','" + req.getParameter("zone") + "','"
                + req.getParameter("price") + "','" + offer + "')");
    }

    sqls = new String[sqlL.size()];
    sqlL.toArray(sqls);
    db.getJdbc().batchUpdate(sqls);

    val = "Ok";

    //      srs1 = db.getJdbc().queryForRowSet("select storage_product.id,product,quality,size,draw from storage_product,desc_product,info_product where storage='"+req.getParameter("storage")+"' and desc_product.id=storage_product.desc and product=name");
    //      ArrayList<StorageProduct> products = new ArrayList<StorageProduct>();
    //      while(srs1.next()){
    //         remain = srs1.getDouble("size");
    //         srs2 = db.getJdbc().queryForRowSet("select size from market_product where storage_product_id='"+srs1.getString("id")+"'");
    //         while(srs2.next()){
    //            remain -= srs2.getDouble("size");
    //         }
    //         if(remain > 0)
    //            products.add(new StorageProduct(srs1.getString("id"), srs1.getString("product"), srs1.getInt("quality"), new BigDecimal(Double.valueOf(remain)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue(), srs1.getString("draw")));
    //      }

    srs1 = db.getJdbc().queryForRowSet(
            "select storage_product.id,product,quality,size,draw from storage_product,desc_product,info_product where storage='"
                    + req.getParameter("storage")
                    + "' and desc_product.id=storage_product.[desc] and product=name");
    ArrayList<StorageProduct> storageProducts = new ArrayList<StorageProduct>();
    ArrayList<MarketProduct> marketProducts = new ArrayList<MarketProduct>();
    while (srs1.next()) {
        remain = srs1.getDouble("size");

        srs2 = db.getJdbc().queryForRowSet(
                "select market_product.id,product,market_product.price,quality,market_product.size,draw from market_product,desc_product,info_product,storage_product where storage_product_id='"
                        + srs1.getString("id")
                        + "' and storage_product_id=storage_product.id and desc_product.id=storage_product.[desc] and product=name");
        while (srs2.next()) {
            remain -= srs2.getDouble("size");
            marketProducts.add(new MarketProduct(srs2.getString("id"), "", srs2.getString("product"),
                    srs2.getDouble("price"), srs2.getInt("quality"), srs2.getDouble("size"),
                    srs2.getString("draw")));
        }
        if (remain > 0)
            storageProducts
                    .add(new StorageProduct(srs1.getString("id"), srs1.getString("product"),
                            srs1.getInt("quality"), new BigDecimal(Double.valueOf(remain))
                                    .setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue(),
                            srs1.getString("draw")));
    }

    ArrayList<String> data = new ArrayList<String>();
    data.add(gson.toJson(storageProducts));
    data.add(gson.toJson(marketProducts));
    val = gson.toJson(data);

    sqlL = null;
    storageProducts = null;
    marketProducts = null;
    sqls = null;
    srs1 = null;
    srs2 = null;
    idInc = null;

    gc();

    return val;
}

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

private static void execTypeConversionOpcodes(Strand ctx, StackFrame sf, int opcode, int[] operands) {
    int i;/*from  w ww  .java  2s .c  om*/
    int j;
    BRefType bRefType;
    String str;

    switch (opcode) {
    case InstructionCodes.I2F:
        i = operands[0];
        j = operands[1];
        sf.doubleRegs[j] = sf.longRegs[i];
        break;
    case InstructionCodes.I2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = Long.toString(sf.longRegs[i]);
        break;
    case InstructionCodes.I2B:
        i = operands[0];
        j = operands[1];
        sf.intRegs[j] = sf.longRegs[i] != 0 ? 1 : 0;
        break;
    case InstructionCodes.I2D:
        i = operands[0];
        j = operands[1];
        sf.refRegs[j] = new BDecimal((new BigDecimal(sf.longRegs[i], MathContext.DECIMAL128)).setScale(1,
                BigDecimal.ROUND_HALF_EVEN));
        break;
    case InstructionCodes.I2BI:
        i = operands[0];
        j = operands[1];
        if (!isByteLiteral(sf.longRegs[i])) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.INT_TNAME + "' value '" + sf.longRegs[i] + "' cannot be converted to '"
                            + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }
        sf.longRegs[j] = sf.longRegs[i];
        break;
    case InstructionCodes.F2BI:
        i = operands[0];
        j = operands[1];
        double floatVal = sf.doubleRegs[i];
        if (Double.isNaN(floatVal) || Double.isInfinite(floatVal)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.FLOAT_TNAME + "' value '" + floatVal + "' cannot be converted to '"
                            + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }

        long floatAsIntVal = Math.round(floatVal);
        if (!isByteLiteral(floatAsIntVal)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.FLOAT_TNAME + "' value '" + floatVal + "' cannot be converted to '"
                            + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }
        sf.longRegs[j] = floatAsIntVal;
        break;
    case InstructionCodes.D2BI:
        i = operands[0];
        j = operands[1];

        DecimalValueKind valueKind = ((BDecimal) sf.refRegs[i]).valueKind;
        if (valueKind == DecimalValueKind.NOT_A_NUMBER || valueKind == DecimalValueKind.NEGATIVE_INFINITY
                || valueKind == DecimalValueKind.POSITIVE_INFINITY) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.DECIMAL_TNAME + "' value '" + sf.refRegs[i]
                            + "' cannot be converted to '" + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }

        long doubleAsIntVal = Math.round(((BDecimal) sf.refRegs[i]).floatValue());
        if (!isByteLiteral(doubleAsIntVal)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.DECIMAL_TNAME + "' value '" + sf.refRegs[i]
                            + "' cannot be converted to '" + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }
        sf.longRegs[j] = doubleAsIntVal;
        break;
    case InstructionCodes.F2I:
        i = operands[0];
        j = operands[1];
        double valueToConvert = sf.doubleRegs[i];
        if (Double.isNaN(valueToConvert) || Double.isInfinite(valueToConvert)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.FLOAT_TNAME + "' value '" + valueToConvert
                            + "' cannot be converted to '" + TypeConstants.INT_TNAME + "'"));
            handleError(ctx);
            break;
        }

        if (!isFloatWithinIntRange(valueToConvert)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "out " + "of range '" + TypeConstants.FLOAT_TNAME + "' value '" + valueToConvert
                            + "' cannot be converted to '" + TypeConstants.INT_TNAME + "'"));
            handleError(ctx);
            break;
        }

        sf.longRegs[j] = Math.round(valueToConvert);
        break;
    case InstructionCodes.F2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = Double.toString(sf.doubleRegs[i]);
        break;
    case InstructionCodes.F2B:
        i = operands[0];
        j = operands[1];
        sf.intRegs[j] = sf.doubleRegs[i] != 0.0 ? 1 : 0;
        break;
    case InstructionCodes.F2D:
        i = operands[0];
        j = operands[1];
        sf.refRegs[j] = new BDecimal(new BigDecimal(sf.doubleRegs[i], MathContext.DECIMAL128));
        break;
    case InstructionCodes.S2I:
        i = operands[0];
        j = operands[1];

        str = sf.stringRegs[i];
        try {
            sf.refRegs[j] = new BInteger(Long.parseLong(str));
        } catch (NumberFormatException e) {
            handleTypeConversionError(ctx, sf, j, TypeConstants.STRING_TNAME, TypeConstants.INT_TNAME);
        }
        break;
    case InstructionCodes.S2F:
        i = operands[0];
        j = operands[1];

        str = sf.stringRegs[i];
        try {
            sf.refRegs[j] = new BFloat(Double.parseDouble(str));
        } catch (NumberFormatException e) {
            handleTypeConversionError(ctx, sf, j, TypeConstants.STRING_TNAME, TypeConstants.FLOAT_TNAME);
        }
        break;
    case InstructionCodes.S2B:
        i = operands[0];
        j = operands[1];
        sf.intRegs[j] = Boolean.parseBoolean(sf.stringRegs[i]) ? 1 : 0;
        break;
    case InstructionCodes.S2D:
        i = operands[0];
        j = operands[1];

        str = sf.stringRegs[i];
        try {
            sf.refRegs[j] = new BDecimal(new BigDecimal(str, MathContext.DECIMAL128));
        } catch (NumberFormatException e) {
            handleTypeConversionError(ctx, sf, j, TypeConstants.STRING_TNAME, TypeConstants.DECIMAL_TNAME);
        }
        break;
    case InstructionCodes.B2I:
        i = operands[0];
        j = operands[1];
        sf.longRegs[j] = sf.intRegs[i];
        break;
    case InstructionCodes.B2F:
        i = operands[0];
        j = operands[1];
        sf.doubleRegs[j] = sf.intRegs[i];
        break;
    case InstructionCodes.B2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = sf.intRegs[i] == 1 ? "true" : "false";
        break;
    case InstructionCodes.B2D:
        i = operands[0];
        j = operands[1];
        sf.refRegs[j] = sf.intRegs[i] == 1
                ? new BDecimal(BigDecimal.ONE.setScale(1, BigDecimal.ROUND_HALF_EVEN))
                : new BDecimal(BigDecimal.ZERO.setScale(1, BigDecimal.ROUND_HALF_EVEN));
        break;
    case InstructionCodes.D2I:
        i = operands[0];
        j = operands[1];
        BDecimal decimal = (BDecimal) sf.refRegs[i];
        DecimalValueKind decValueKind = decimal.valueKind;
        if (decValueKind == DecimalValueKind.NOT_A_NUMBER || decValueKind == DecimalValueKind.NEGATIVE_INFINITY
                || decValueKind == DecimalValueKind.POSITIVE_INFINITY) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.DECIMAL_TNAME + "' value '" + sf.refRegs[i]
                            + "' cannot be converted to '" + TypeConstants.INT_TNAME + "'"));
            handleError(ctx);
            break;
        }

        if (!isDecimalWithinIntRange((decimal.decimalValue()))) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "out of range '" + TypeConstants.DECIMAL_TNAME + "' value '" + decimal
                            + "' cannot be converted to '" + TypeConstants.INT_TNAME + "'"));
            handleError(ctx);
            break;
        }
        sf.longRegs[j] = Math.round(((BDecimal) sf.refRegs[i]).decimalValue().doubleValue());
        break;
    case InstructionCodes.D2F:
        i = operands[0];
        j = operands[1];
        sf.doubleRegs[j] = ((BDecimal) sf.refRegs[i]).floatValue();
        break;
    case InstructionCodes.D2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = sf.refRegs[i].stringValue();
        break;
    case InstructionCodes.D2B:
        i = operands[0];
        j = operands[1];
        sf.intRegs[j] = ((BDecimal) sf.refRegs[i]).decimalValue().compareTo(BigDecimal.ZERO) != 0 ? 1 : 0;
        break;
    case InstructionCodes.DT2XML:
        i = operands[0];
        j = operands[1];

        bRefType = sf.refRegs[i];
        if (bRefType == null) {
            handleTypeConversionError(ctx, sf, j, BTypes.typeNull, BTypes.typeXML);
            break;
        }

        try {
            sf.refRegs[j] = XMLUtils.tableToXML((BTable) bRefType);
        } catch (Exception e) {
            sf.refRegs[j] = null;
            handleTypeConversionError(ctx, sf, j, TypeConstants.TABLE_TNAME, TypeConstants.XML_TNAME);
        }
        break;
    case InstructionCodes.DT2JSON:
        i = operands[0];
        j = operands[1];

        bRefType = sf.refRegs[i];
        if (bRefType == null) {
            handleNullRefError(ctx);
            break;
        }

        try {
            sf.refRegs[j] = JSONUtils.toJSON((BTable) bRefType);
        } catch (Exception e) {
            handleTypeConversionError(ctx, sf, j, TypeConstants.TABLE_TNAME, TypeConstants.XML_TNAME);
        }
        break;
    case InstructionCodes.T2MAP:
        convertStructToMap(ctx, operands, sf);
        break;
    case InstructionCodes.T2JSON:
        convertStructToJSON(ctx, operands, sf);
        break;
    case InstructionCodes.MAP2JSON:
        convertMapToJSON(ctx, operands, sf);
        break;
    case InstructionCodes.JSON2MAP:
        convertJSONToMap(ctx, operands, sf);
        break;
    case InstructionCodes.MAP2T:
        convertMapToStruct(ctx, operands, sf);
        break;
    case InstructionCodes.JSON2T:
        convertJSONToStruct(ctx, operands, sf);
        break;
    case InstructionCodes.XMLATTRS2MAP:
        i = operands[0];
        j = operands[1];
        bRefType = sf.refRegs[i];
        sf.refRegs[j] = ((BXMLAttributes) sf.refRegs[i]).value();
        break;
    case InstructionCodes.XML2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = sf.refRegs[i].stringValue();
        break;
    case InstructionCodes.ANY2SCONV:
        i = operands[0];
        j = operands[1];

        bRefType = sf.refRegs[i];
        if (bRefType == null) {
            sf.stringRegs[j] = STRING_NULL_VALUE;
        } else {
            sf.stringRegs[j] = bRefType.stringValue();
        }
        break;
    default:
        throw new UnsupportedOperationException();
    }
}

From source file:osu.beatmapdownloader.JFrame.java

public boolean downloadSong(String idMap, int prio, String Directory) {
       String fileName = null;/*from   ww w .j a  v  a  2  s . c o  m*/
       try {
           String url = "";
           if (model.get(prio).toString().contains("Blood")) {
               url = "http://bloodcat.com/osu/d/" + idMap;
               L_server.setText("Bloodcat Server");
           } else {
               if (C_OsuServer.isSelected() && model.get(0).toString().contains("Osu")) {
                   if (C_noVideo.isSelected())
                       url = "http://osu.ppy.sh/d/" + idMap + "n";
                   else
                       url = "http://osu.ppy.sh/d/" + idMap;
                   L_server.setText("Osu! Server");
               }
           }
           long start = System.nanoTime();
           long totalRead = 0;
           final double NANOS_PER_SECOND = 1000000000.0;
           final double BYTES_PER_MIB = 1024 * 1024;
           URLConnection request = null;
           request = new URL(url).openConnection();
           request.setRequestProperty("Cookie", url.contains("ppy") ? Cookie : "");
           request.setRequestProperty("User-Agent",
                   "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
           InputStream in = request.getInputStream();
           String raw = request.getHeaderField("Content-Disposition");
           fileName = raw.split("=")[1].replaceAll("\"", "").replaceAll("; filename*", "");
           request.getContentLength();
           double size = request.getContentLength();
           File aux = File.createTempFile(fileName.replaceAll("\\*", "").replaceAll(";", ""), ".osz");
           L_FileName.setText(fileName.replaceAll("\\*", "").replaceAll(";", ""));
           FileOutputStream out = new FileOutputStream(aux);
           byte[] buffer = new byte[1024];
           int len = in.read(buffer);
           L_totalSize.setText((String) new DecimalFormat("#.##").format(size * 0.000001) + " Mb");
           int bytes = 0;
           Pro_ProgressBar.setMinimum(0);
           Pro_ProgressBar.setMaximum((int) (size / 1000));
           long acu = 0;
           while (len != -1) {
               bytes++;
               out.write(buffer, 0, len);
               len = in.read(buffer);
               if (len == 1024) {
                   acu += len;
                   BigDecimal a = new BigDecimal(acu * 0.000001);
                   BigDecimal roundOff = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
                   L_fileValue.setText(roundOff + "");
               }
               Pro_ProgressBar.setValue(bytes);
               totalRead += len;
               BigDecimal a = new BigDecimal(
                       ((NANOS_PER_SECOND / BYTES_PER_MIB * totalRead / (System.nanoTime() - start + 1)) * 1000));
               BigDecimal speed = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
               //String speed = new DecimalFormat("#.##").format(((NANOS_PER_SECOND / BYTES_PER_MIB * totalRead / (System.nanoTime() - start + 1)) * 1000));
               L_Second.setText(speed + "");
               BigDecimal b = new BigDecimal((((size * 0.000001) - (acu * 0.000001)) * 0.1)
                       / (((NANOS_PER_SECOND / BYTES_PER_MIB * totalRead / (System.nanoTime() - start + 1))
                               * 1000))
                       * 10000);
               BigDecimal speed_total = b.setScale(2, BigDecimal.ROUND_HALF_EVEN);
               L_seconds.setText(speed_total + "");
               if (Thread.interrupted()) {
                   in.close();
                   out.close();
                   aux.deleteOnExit();
                   throw new InterruptedException();
               }
           }
           in.close();
           out.close();
           FileUtils.copyFile(aux,
                   new File(Directory + File.separator + fileName.replaceAll("\\*", "").replaceAll(";", "")));
           aux.deleteOnExit();
           return true;
       } catch (Exception e) {
           errorFatal("DOWNLOADING");
           errorFatal(e.toString());
           errorFatal("--------------------------------------");
           prio++;
           errorConection++;
           L_Trying.setText(errorConection + "");
           int limitTry = 3;
           if (errorConection >= limitTry) {
               Errors++;
               L_Errors.setText(Errors + "");
               errorDownload("-The connection to this Beatmap was failed, '" + errorConection
                       + "' times, it was skipped.");
               errorDownload("--The filename is '" + fileName + "', with the id '" + idMap + "'. ");
               errorDownload("----------------------");
           } else {
               if (model.getSize() == prio)
                   prio = 0;
               downloadSong(idMap, prio, Directory);
           }
           return false;
       }
   }

From source file:org.openbravo.erpCommon.ad_forms.AcctServer.java

public BigDecimal convertAmount(BigDecimal _amount, boolean isReceipt, String dateAcct, String table_ID,
        String record_ID, String currencyIDFrom, String currencyIDTo, DocLine line, AcctSchema as, Fact fact,
        String Fact_Acct_Group_ID, String seqNo, ConnectionProvider conn, boolean bookDifferences)
        throws ServletException {
    BigDecimal amtDiff = BigDecimal.ZERO;
    if (_amount == null || _amount.compareTo(BigDecimal.ZERO) == 0) {
        return _amount;
    }//from   www  .j av a  2 s  .c o  m
    String conversionDate = dateAcct;
    String strDateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
            .getProperty("dateFormat.java");
    final SimpleDateFormat dateFormat = new SimpleDateFormat(strDateFormat);
    ConversionRateDoc conversionRateDoc = getConversionRateDoc(table_ID, record_ID, currencyIDFrom,
            currencyIDTo);
    BigDecimal amtFrom = BigDecimal.ZERO;
    BigDecimal amtFromSourcecurrency = BigDecimal.ZERO;
    BigDecimal amtTo = BigDecimal.ZERO;
    if (table_ID.equals(TABLEID_Invoice)) {
        Invoice invoice = OBDal.getInstance().get(Invoice.class, record_ID);
        conversionDate = dateFormat.format(invoice.getAccountingDate());
    } else if (table_ID.equals(TABLEID_Payment)) {
        FIN_Payment payment = OBDal.getInstance().get(FIN_Payment.class, record_ID);
        conversionDate = dateFormat.format(payment.getPaymentDate());
    } else if (table_ID.equals(TABLEID_Transaction)) {
        FIN_FinaccTransaction transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class, record_ID);
        conversionDate = dateFormat.format(transaction.getDateAcct());
    }
    if (conversionRateDoc != null && record_ID != null) {
        amtFrom = applyRate(_amount, conversionRateDoc, true);
    } else {
        // I try to find a reversal rate for the doc, if exists i apply it reversal as well
        conversionRateDoc = getConversionRateDoc(table_ID, record_ID, currencyIDTo, currencyIDFrom);
        if (conversionRateDoc != null) {
            amtFrom = applyRate(_amount, conversionRateDoc, false);
        } else {
            String convertedAmt = getConvertedAmt(_amount.toString(), currencyIDFrom, currencyIDTo,
                    conversionDate, "", AD_Client_ID, AD_Org_ID, conn);
            if (convertedAmt != null && !"".equals(convertedAmt)) {
                amtFrom = new BigDecimal(convertedAmt);
            } else {
                throw new OBException("@NotConvertible@");
            }
        }
    }
    ConversionRateDoc conversionRateCurrentDoc = getConversionRateDoc(AD_Table_ID, Record_ID, currencyIDFrom,
            currencyIDTo);
    if (AD_Table_ID.equals(TABLEID_Invoice)) {
        Invoice invoice = OBDal.getInstance().get(Invoice.class, Record_ID);
        conversionDate = dateFormat.format(invoice.getAccountingDate());
    } else if (AD_Table_ID.equals(TABLEID_Payment)) {
        FIN_Payment payment = OBDal.getInstance().get(FIN_Payment.class, Record_ID);
        conversionDate = dateFormat.format(payment.getPaymentDate());
    } else if (AD_Table_ID.equals(TABLEID_Transaction) || AD_Table_ID.equals(TABLEID_Reconciliation)) {
        String transactionID = Record_ID;
        // When TableID= Reconciliation info is loaded from transaction
        if (AD_Table_ID.equals(AcctServer.TABLEID_Reconciliation)
                && line instanceof DocLine_FINReconciliation) {
            transactionID = ((DocLine_FINReconciliation) line).getFinFinAccTransactionId();
        }
        FIN_FinaccTransaction transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class, transactionID);
        conversionDate = dateFormat.format(transaction.getDateAcct());
        conversionRateCurrentDoc = getConversionRateDoc(TABLEID_Transaction, transaction.getId(),
                currencyIDFrom, currencyIDTo);
    } else {
        conversionDate = dateAcct;
    }
    if (conversionRateCurrentDoc != null) {
        amtTo = applyRate(_amount, conversionRateCurrentDoc, true);
        amtFromSourcecurrency = applyRate(amtFrom, conversionRateCurrentDoc, false);
    } else {
        // I try to find a reversal rate for the doc, if exists i apply it reversal as well
        if (AD_Table_ID.equals(AcctServer.TABLEID_Reconciliation)
                && line instanceof DocLine_FINReconciliation) {
            String transactionID = ((DocLine_FINReconciliation) line).getFinFinAccTransactionId();
            conversionRateCurrentDoc = getConversionRateDoc(TABLEID_Transaction, transactionID, currencyIDTo,
                    currencyIDFrom);
        } else {
            conversionRateCurrentDoc = getConversionRateDoc(AD_Table_ID, Record_ID, currencyIDTo,
                    currencyIDFrom);
        }
        if (conversionRateCurrentDoc != null) {
            amtTo = applyRate(_amount, conversionRateCurrentDoc, false);
            amtFromSourcecurrency = applyRate(amtFrom, conversionRateCurrentDoc, true);
        } else {
            String convertedAmt = getConvertedAmt(_amount.toString(), currencyIDFrom, currencyIDTo,
                    conversionDate, "", AD_Client_ID, AD_Org_ID, conn);
            if (convertedAmt != null && !"".equals(convertedAmt)) {
                amtTo = new BigDecimal(convertedAmt);
            } else {
                throw new OBException("@NotConvertible@");
            }
            if (amtTo.compareTo(BigDecimal.ZERO) != 0)
                amtFromSourcecurrency = amtFrom.multiply(_amount).divide(amtTo, conversionRatePrecision,
                        BigDecimal.ROUND_HALF_EVEN);
            else
                amtFromSourcecurrency = amtFrom;
        }
    }
    amtDiff = (amtTo).subtract(amtFrom);
    // Add differences related to Different rates for accounting among currencies
    // _amount * ((TrxRate *
    // AccountingRateCurrencyFromCurrencyTo)-AccountingRateCurrencyDocCurrencyTo)
    amtDiff = amtDiff.add(calculateMultipleRatesDifferences(_amount, currencyIDFrom, currencyIDTo, line, conn));
    Currency currencyTo = OBDal.getInstance().get(Currency.class, currencyIDTo);
    amtDiff = amtDiff.setScale(currencyTo.getStandardPrecision().intValue(), BigDecimal.ROUND_HALF_EVEN);
    if (bookDifferences) {
        if ((!isReceipt && amtDiff.compareTo(BigDecimal.ZERO) == 1)
                || (isReceipt && amtDiff.compareTo(BigDecimal.ZERO) == -1)) {
            fact.createLine(line, getAccount(AcctServer.ACCTTYPE_ConvertGainDefaultAmt, as, conn), currencyIDTo,
                    "", amtDiff.abs().toString(), Fact_Acct_Group_ID, seqNo, DocumentType, conn);
        } else if (amtDiff.compareTo(BigDecimal.ZERO) != 0) {
            fact.createLine(line, getAccount(AcctServer.ACCTTYPE_ConvertChargeDefaultAmt, as, conn),
                    currencyIDTo, amtDiff.abs().toString(), "", Fact_Acct_Group_ID, seqNo, DocumentType, conn);
        } else {
            return amtFromSourcecurrency;
        }
    }
    if (log4j.isDebugEnabled())
        log4j.debug("Amt from: " + amtFrom + "[" + currencyIDFrom + "]" + " Amt to: " + amtTo + "["
                + currencyIDTo + "] - amtFromSourcecurrency: " + amtFromSourcecurrency);
    // return value in original currency
    return amtFromSourcecurrency;
}

From source file:org.sakaiproject.tool.assessment.services.GradingService.java

/**
 * CALCULATED_QUESTION/*from w w  w . j  av a2s.  c  o m*/
 * applyPrecisionToNumberString() takes a string representation of a number and returns
 * a string representation of that number, rounded to the specified number of
 * decimal places, including trimming decimal places if needed.
 * Will also throw away the extra trailing zeros as well as removing a trailing decimal point.
 * @param numberStr
 * @param decimalPlaces
 * @return processed number string (will never be null or empty string)
 */
public String applyPrecisionToNumberString(String numberStr, int decimalPlaces) {
    // Trim off excess decimal points based on decimalPlaces value
    BigDecimal bd = new BigDecimal(numberStr);
    bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_EVEN);

    String decimal = ".";
    // TODO handle localized decimal separator?
    //DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale);
    //char dec = dfs.getDecimalFormatSymbols().getDecimalSeparator();

    String displayAnswer = bd.toString();
    if (displayAnswer.length() > 2 && displayAnswer.contains(decimal)) {
        if (decimalPlaces == 0) { // Remove ".0" if decimalPlaces == 0
            displayAnswer = displayAnswer.replace(decimal + "0", "");
        } else {
            // trim away all the extra 0s from the end of the number
            if (displayAnswer.endsWith("0")) {
                displayAnswer = StringUtils.stripEnd(displayAnswer, "0");
            }
            if (displayAnswer.endsWith(decimal)) {
                displayAnswer = displayAnswer.substring(0, displayAnswer.length() - 1);
            }
        }
    }
    return displayAnswer;
}

From source file:com.lp.server.fertigung.ejbfac.FertigungFacBean.java

public BigDecimal wievileTOPSArtikelWurdenBereitsZugebucht(Integer losIId, TheClientDto theClientDto) {
    LossollmaterialDto[] dtos = lossollmaterialFindByLosIId(losIId);
    try {//from   w w w.j  a v  a  2 s. c om
        LosDto losDto = losFindByPrimaryKey(losIId);

        for (int i = 0; i < dtos.length; i++) {
            Integer artklaIId = null;

            ArtikelDto artikelDto = getArtikelFac().artikelFindByPrimaryKeySmall(dtos[i].getArtikelIId(),
                    theClientDto);
            artklaIId = artikelDto.getArtklaIId();

            if (artklaIId != null) {
                boolean bTops = Helper.short2boolean(
                        getArtikelFac().artklaFindByPrimaryKey(artklaIId, theClientDto).getBTops());

                if (bTops == true) {

                    BigDecimal sollsatzgroesse = dtos[i].getNMenge().divide(losDto.getNLosgroesse(), 4,
                            BigDecimal.ROUND_HALF_EVEN);
                    BigDecimal ausgegeben = getAusgegebeneMenge(dtos[i].getIId(), null, theClientDto);
                    return ausgegeben.divide(sollsatzgroesse, 4, BigDecimal.ROUND_HALF_EVEN);
                }
            }
        }

    } catch (RemoteException ex) {
        throwEJBExceptionLPRespectOld(ex);
    }
    return new BigDecimal(0);
}

From source file:org.egov.billsaccounting.services.CreateVoucher.java

/**
 * HashMap<String, Object> voucher details to reverse a voucher
 * <p>//from   w ww  .j  a v a  2  s .  com
 * Original voucher header id -long- is the voucher header id of the voucher
 * to be reversed later callled originalvoucher
 * <p>
 * Reversal voucher name -String - name of the reversal voucher (mandatory)
 * <p>
 * Reversal voucher type -String - type of the reversal voucher (mandatory)
 * <p>
 * Reversal voucher date - Date('dd/MM/yyyy') date of the reversal vocuher
 * <p>
 * Reversal voucher number - String - voucher number of reversal voucher
 * Newly created voucher is called reversal voucher
 * 
 * @param paramList
 * @return
 */
@Transactional
public CVoucherHeader reverseVoucher(final List<HashMap<String, Object>> paramList)
        throws ApplicationRuntimeException, ParseException {
    // -- Reversal Voucher date check ----
    CVoucherHeader reversalVoucherObj = new CVoucherHeader();
    CVoucherHeader originalVocher = null;
    for (final HashMap<String, Object> paramMap : paramList) {

        if (paramMap.get(VOUCHER_HEADER_ID) == null)
            throw new IllegalArgumentException(VOUCHER_HEADER_ID + IS_MISSING);
        else {
            try {
                originalVocher = voucherService.find("from CVoucherHeader where id=?",
                        (Long) paramMap.get(VOUCHER_HEADER_ID));

            } catch (final Exception e) {
                throw new ApplicationRuntimeException("cannot find " + VOUCHER_HEADER_ID + "in the system");
            }
            reversalVoucherObj.setOriginalvcId(originalVocher.getId());
        }

        if (paramMap.get(REVERSAL_VOUCHER_DATE) == null) {
            final SimpleDateFormat sdf = new SimpleDateFormat(DD_MM_YYYY);
            final Date reversalVoucherDate = sdf.parse(sdf.format(originalVocher.getVoucherDate()));
            reversalVoucherObj.setVoucherDate(reversalVoucherDate);
        } else {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Voucher  end REVERSAL_VOUCHER_DAT :" + paramMap.get(REVERSAL_VOUCHER_DATE));
            final Date reversalVoucherDate = sdf.parse(sdf.format(paramMap.get(REVERSAL_VOUCHER_DATE)));
            reversalVoucherObj.setVoucherDate(reversalVoucherDate);
        }
    }
    originalVocher = (CVoucherHeader) persistenceService.find("from CVoucherHeader where id=?",
            reversalVoucherObj.getOriginalvcId());
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("original voucher is " + reversalVoucherObj.getOriginalvcId());
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("reversalVoucherObj getVoucherDate is " + reversalVoucherObj.getVoucherDate());
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("originalVocher getVoucherDate is " + originalVocher.getVoucherDate());
    if (reversalVoucherObj.getVoucherDate().before(originalVocher.getVoucherDate())) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Reversal Voucher Date should be greater than the Origianal Voucher Date");
        throw new ValidationException(Arrays.asList(new ValidationError("reversal.voucher.date.validate",
                "Reversal Voucher Date should be greater than the Original Voucher Date")));
    }

    reversalVoucherObj.setName(originalVocher.getName());
    reversalVoucherObj.setType(originalVocher.getType());
    reversalVoucherObj.setVoucherSubType(originalVocher.getVoucherSubType());

    reversalVoucherObj.setVoucherNumber("");

    reversalVoucherObj.setDescription(originalVocher.getDescription());
    reversalVoucherObj.setVouchermis(originalVocher.getVouchermis());
    reversalVoucherObj.setFundId(originalVocher.getFundId());

    final HashMap<String, Object> headerDetails = createHeaderAndMisDetails(reversalVoucherObj);

    List<CGeneralLedger> orginalLedgerEntries = generalLedgerService
            .findAllBy("from CGeneralLedger where voucherHeaderId=?", originalVocher);
    HashMap<String, Object> detailMap = null;
    HashMap<String, Object> subledgerMap = null;
    final List<HashMap<String, Object>> accountdetails = new ArrayList<HashMap<String, Object>>();
    final List<HashMap<String, Object>> subledgerdetails = new ArrayList<HashMap<String, Object>>();

    CFunction function = null;
    for (final CGeneralLedger ledger : orginalLedgerEntries) {
        detailMap = new HashMap<String, Object>();
        detailMap.put(VoucherConstant.GLCODE, ledger.getGlcode());
        //debit becomes credit ,credit becomes debit
        detailMap.put(VoucherConstant.DEBITAMOUNT, ledger.getCreditAmount());
        detailMap.put(VoucherConstant.CREDITAMOUNT, ledger.getDebitAmount());

        if (ledger.getFunctionId() != null) {
            function = functionDAO.getFunctionById(ledger.getFunctionId().longValue());
            detailMap.put(VoucherConstant.FUNCTIONCODE, function.getCode());
        }
        List<CGeneralLedgerDetail> ledgerDetailSet = generalLedgerDetailService
                .findAllBy("from CGeneralLedgerDetail where generalLedgerId.id=?", ledger.getId());
        for (final CGeneralLedgerDetail ledgerDetail : ledgerDetailSet) {
            subledgerMap = new HashMap<String, Object>();
            subledgerMap.put(VoucherConstant.GLCODE, ledger.getGlcode());
            subledgerMap.put(VoucherConstant.DETAILTYPEID, ledgerDetail.getDetailTypeId().getId());
            subledgerMap.put(VoucherConstant.DETAILKEYID, ledgerDetail.getDetailKeyId());
            //even for subledger debit becomes credit ,credit becomes debit
            if (BigDecimal.valueOf(ledger.getDebitAmount()).compareTo(BigDecimal.ZERO) != 0)
                subledgerMap.put(VoucherConstant.CREDITAMOUNT, ledgerDetail.getAmount());
            else
                subledgerMap.put(VoucherConstant.DEBITAMOUNT,
                        ledgerDetail.getAmount().setScale(2, BigDecimal.ROUND_HALF_EVEN));

            subledgerdetails.add(subledgerMap);
        }
        accountdetails.add(detailMap);
    }
    try {
        reversalVoucherObj = createVoucher(headerDetails, accountdetails, subledgerdetails);
    } catch (final HibernateException e) {
        LOGGER.error(e.getMessage(), e);
        throw new ValidationException(Arrays.asList(new ValidationError(EXCEPTION_WHILE_SAVING_DATA, FAILED)));
    } catch (final ApplicationRuntimeException e) {
        LOGGER.error(e.getMessage(), e);
        throw new ValidationException(Arrays.asList(new ValidationError(e.getMessage(), e.getMessage())));
    } catch (final ValidationException e) {
        LOGGER.error(e.getMessage(), e);
        throw e;
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new ValidationException(Arrays.asList(new ValidationError(e.getMessage(), e.getMessage())));
    }

    originalVocher.setStatus(1);
    originalVocher.setEffectiveDate(new Date());
    voucherService.applyAuditing(originalVocher);
    voucherService.update(originalVocher);

    reversalVoucherObj.setOriginalvcId(originalVocher.getId());
    reversalVoucherObj.setStatus(2);
    voucherService.applyAuditing(reversalVoucherObj);
    voucherService.persist(reversalVoucherObj);

    return reversalVoucherObj;
}

From source file:org.openbravo.erpCommon.ad_forms.AcctServer.java

public static BigDecimal applyRate(BigDecimal _amount, ConversionRateDoc conversionRateDoc, boolean multiply) {
    BigDecimal amount = _amount;//from  ww w  . j a  va  2  s. c o m
    if (multiply) {
        return amount.multiply(conversionRateDoc.getRate());
    } else {
        return amount.divide(conversionRateDoc.getRate(), 6, BigDecimal.ROUND_HALF_EVEN);
    }
}