Example usage for java.math BigDecimal scale

List of usage examples for java.math BigDecimal scale

Introduction

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

Prototype

int scale

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

Click Source Link

Document

The scale of this BigDecimal, as returned by #scale .

Usage

From source file:net.pms.util.Rational.java

/**
 * Returns an instance with the given {@code numerator} and
 * {@code denominator}.//from w  ww  .j a v a  2  s.  c  o m
 *
 * @param numerator the numerator.
 * @param denominator the denominator.
 * @return An instance that represents the value of {@code numerator}/
 *         {@code denominator}.
 */
@Nullable
public static Rational valueOf(@Nullable BigDecimal numerator, @Nullable BigDecimal denominator) {
    if (numerator == null || denominator == null) {
        return null;
    }
    if (numerator.signum() == 0 && denominator.signum() == 0) {
        return NaN;
    }
    if (denominator.signum() == 0) {
        return numerator.signum() > 0 ? POSITIVE_INFINITY : NEGATIVE_INFINITY;
    }
    if (numerator.signum() == 0) {
        return ZERO;
    }
    if (numerator.equals(denominator)) {
        return ONE;
    }
    if (denominator.signum() < 0) {
        numerator = numerator.negate();
        denominator = denominator.negate();
    }

    int scale = Math.max(numerator.scale(), denominator.scale());
    if (scale > 0) {
        numerator = numerator.scaleByPowerOfTen(scale);
        denominator = denominator.scaleByPowerOfTen(scale);
    }
    BigInteger biNumerator = numerator.toBigIntegerExact();
    BigInteger biDenominator = denominator.toBigIntegerExact();

    BigInteger reducedNumerator;
    BigInteger reducedDenominator;
    BigInteger greatestCommonDivisor = calculateGreatestCommonDivisor(biNumerator, biDenominator);
    if (BigInteger.ONE.equals(greatestCommonDivisor)) {
        reducedNumerator = biNumerator;
        reducedDenominator = biDenominator;
    } else {
        reducedNumerator = biNumerator.divide(greatestCommonDivisor);
        reducedDenominator = biDenominator.divide(greatestCommonDivisor);
    }
    return new Rational(biNumerator, biDenominator, greatestCommonDivisor, reducedNumerator,
            reducedDenominator);
}

From source file:helma.objectmodel.db.NodeManager.java

/**
 *  Create a new Node from a ResultSet./*from ww w  . jav  a2 s.  c om*/
 */
public Node createNode(DbMapping dbm, ResultSet rs, DbColumn[] columns, int offset)
        throws SQLException, IOException, ClassNotFoundException {
    HashMap propBuffer = new HashMap();
    String id = null;
    String name = null;
    String protoName = dbm.getTypeName();
    DbMapping dbmap = dbm;

    Node node = new Node(safe);

    for (int i = 0; i < columns.length; i++) {

        int columnNumber = i + 1 + offset;

        // set prototype?
        if (columns[i].isPrototypeField()) {
            String protoId = rs.getString(columnNumber);
            protoName = dbm.getPrototypeName(protoId);

            if (protoName != null) {
                dbmap = getDbMapping(protoName);

                if (dbmap == null) {
                    // invalid prototype name!
                    app.logError("No prototype defined for prototype mapping \"" + protoName
                            + "\" - Using default prototype \"" + dbm.getTypeName() + "\".");
                    dbmap = dbm;
                    protoName = dbmap.getTypeName();
                }
            }
        }

        // set id?
        if (columns[i].isIdField()) {
            id = rs.getString(columnNumber);
            // if id == null, the object doesn't actually exist - return null
            if (id == null) {
                return null;
            }
        }

        // set name?
        if (columns[i].isNameField()) {
            name = rs.getString(columnNumber);
        }

        Property newprop = new Property(node);

        switch (columns[i].getType()) {
        case Types.BIT:
        case Types.BOOLEAN:
            newprop.setBooleanValue(rs.getBoolean(columnNumber));

            break;

        case Types.TINYINT:
        case Types.BIGINT:
        case Types.SMALLINT:
        case Types.INTEGER:
            newprop.setIntegerValue(rs.getLong(columnNumber));

            break;

        case Types.REAL:
        case Types.FLOAT:
        case Types.DOUBLE:
            newprop.setFloatValue(rs.getDouble(columnNumber));

            break;

        case Types.DECIMAL:
        case Types.NUMERIC:

            BigDecimal num = rs.getBigDecimal(columnNumber);
            if (num == null) {
                break;
            }
            if (num.scale() > 0) {
                newprop.setFloatValue(num.doubleValue());
            } else {
                newprop.setIntegerValue(num.longValue());
            }

            break;

        case Types.VARBINARY:
        case Types.BINARY:
            newprop.setJavaObjectValue(rs.getBytes(columnNumber));

            break;

        case Types.BLOB:
        case Types.LONGVARBINARY: {
            InputStream in = rs.getBinaryStream(columnNumber);
            if (in == null) {
                break;
            }
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int read;
            while ((read = in.read(buffer)) > -1) {
                bout.write(buffer, 0, read);
            }
            newprop.setJavaObjectValue(bout.toByteArray());
        }

            break;

        case Types.LONGVARCHAR:
            try {
                newprop.setStringValue(rs.getString(columnNumber));
            } catch (SQLException x) {
                Reader in = rs.getCharacterStream(columnNumber);
                if (in == null) {
                    newprop.setStringValue(null);
                    break;
                }
                StringBuffer out = new StringBuffer();
                char[] buffer = new char[2048];
                int read;
                while ((read = in.read(buffer)) > -1) {
                    out.append(buffer, 0, read);
                }
                newprop.setStringValue(out.toString());
            }

            break;

        case Types.CHAR:
        case Types.VARCHAR:
        case Types.OTHER:
            newprop.setStringValue(rs.getString(columnNumber));

            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            newprop.setDateValue(rs.getTimestamp(columnNumber));

            break;

        case Types.NULL:
            newprop.setStringValue(null);

            break;

        case Types.CLOB:
            Clob cl = rs.getClob(columnNumber);
            if (cl == null) {
                newprop.setStringValue(null);
                break;
            }
            char[] c = new char[(int) cl.length()];
            Reader isr = cl.getCharacterStream();
            isr.read(c);
            newprop.setStringValue(String.copyValueOf(c));
            break;

        default:
            newprop.setStringValue(rs.getString(columnNumber));

            break;
        }

        if (rs.wasNull()) {
            newprop.setStringValue(null);
        }

        propBuffer.put(columns[i].getName(), newprop);

        // mark property as clean, since it's fresh from the db
        newprop.dirty = false;
    }

    if (id == null) {
        return null;
    } else {
        Transactor tx = Transactor.getInstance();
        if (tx != null) {
            // Check if the node is already registered with the transactor -
            // it may be in the process of being DELETED, but do return the
            // new node if the old one has been marked as INVALID.
            DbKey key = new DbKey(dbmap, id);
            Node dirtyNode = tx.getDirtyNode(key);
            if (dirtyNode != null && dirtyNode.getState() != Node.INVALID) {
                return dirtyNode;
            }
        }
    }

    Hashtable propMap = new Hashtable();
    DbColumn[] columns2 = dbmap.getColumns();
    for (int i = 0; i < columns2.length; i++) {
        Relation rel = columns2[i].getRelation();
        if (rel != null && rel.isPrimitiveOrReference()) {
            Property prop = (Property) propBuffer.get(columns2[i].getName());

            if (prop == null) {
                continue;
            }

            prop.setName(rel.propName);

            // if the property is a pointer to another node, change the property type to NODE
            if (rel.isReference() && rel.usesPrimaryKey()) {
                // FIXME: References to anything other than the primary key are not supported
                prop.convertToNodeReference(rel);
            }
            propMap.put(rel.propName, prop);
        }
    }

    node.init(dbmap, id, name, protoName, propMap);
    return node;
}

From source file:mx.edu.um.mateo.activos.dao.impl.ActivoDaoHibernate.java

private BigDecimal stripTrailingZeros(BigDecimal value) {
    if (value.scale() <= 0) {
        return value;
    }//from w w w . j a va 2  s . c  o m

    String valueAsString = String.valueOf(value);
    int idx = valueAsString.indexOf(".");
    if (idx == -1) {
        return value;
    }

    for (int i = valueAsString.length() - 1; i > idx; i--) {
        if (valueAsString.charAt(i) == '0') {
            valueAsString = valueAsString.substring(0, i);
        } else if (valueAsString.charAt(i) == '.') {
            valueAsString = valueAsString.substring(0, i);
            // Stop when decimal point is reached
            break;
        } else {
            break;
        }
    }
    BigDecimal result = new BigDecimal(valueAsString);
    return result;
}

From source file:org.voltdb.TestParameterSet.java

public void testRoundtrip() throws IOException {
    Byte byteparam = new Byte((byte) 2);
    Short shortparam = new Short(Short.MAX_VALUE);
    Integer intparam = new Integer(Integer.MIN_VALUE);
    Long longparam = new Long(Long.MAX_VALUE - 1);
    Double doubleparam = new Double(Double.MAX_VALUE - 1);
    String stringparam = new String("ABCDE");
    TimestampType dateparam = new TimestampType(); // current time
    BigDecimal bigdecimalparam = new BigDecimal(7654321).setScale(VoltDecimalHelper.kDefaultScale);
    VoltTable volttableparam = new VoltTable(new VoltTable.ColumnInfo("foo", VoltType.INTEGER));
    volttableparam.addRow(Integer.MAX_VALUE);

    byte[] bytearray = new byte[] { (byte) 'f', (byte) 'o', (byte) 'o' };
    short[] shortarray = new short[] { Short.MAX_VALUE, Short.MIN_VALUE, (short) 5 };
    int[] intarray = new int[] { Integer.MAX_VALUE, Integer.MIN_VALUE, 5 };
    double[] doublearray = new double[] { Double.MAX_VALUE, Double.MIN_VALUE, 5.5 };
    String[] stringarray = new String[] { "ABC", "DEF", "HIJ" };
    TimestampType[] datearray = new TimestampType[] { new TimestampType(), new TimestampType(),
            new TimestampType() };

    BigDecimal bdtmp1 = new BigDecimal(7654321).setScale(VoltDecimalHelper.kDefaultScale);
    BigDecimal bdtmp2 = new BigDecimal(654321).setScale(VoltDecimalHelper.kDefaultScale);
    BigDecimal bdtmp3 = new BigDecimal(54321).setScale(VoltDecimalHelper.kDefaultScale);
    BigDecimal[] bigdecimalarray = new BigDecimal[] { bdtmp1, bdtmp2, bdtmp3 };

    VoltTable vttmp1 = new VoltTable(new VoltTable.ColumnInfo("foo", VoltType.INTEGER),
            new VoltTable.ColumnInfo("bar", VoltType.STRING));
    vttmp1.addRow(Integer.MAX_VALUE, "ry@nlikestheyankees");
    VoltTable vttmp2 = new VoltTable(new VoltTable.ColumnInfo("bar", VoltType.INTEGER),
            new VoltTable.ColumnInfo("bar", VoltType.STRING));
    vttmp2.addRow(Integer.MIN_VALUE, null);
    VoltTable vttmp3 = new VoltTable(new VoltTable.ColumnInfo("far", VoltType.INTEGER),
            new VoltTable.ColumnInfo("bar", VoltType.STRING));
    vttmp3.addRow(new Integer(5), "");
    VoltTable[] volttablearray = new VoltTable[] { vttmp1, vttmp2, vttmp3 };

    assertTrue(bigdecimalparam.scale() == VoltDecimalHelper.kDefaultScale);
    assertTrue(bdtmp1.scale() == VoltDecimalHelper.kDefaultScale);
    assertTrue(bdtmp2.scale() == VoltDecimalHelper.kDefaultScale);
    assertTrue(bdtmp3.scale() == VoltDecimalHelper.kDefaultScale);

    ParameterSet pset = ParameterSet.fromArrayNoCopy(byteparam, shortparam, intparam, longparam, doubleparam,
            stringparam, dateparam, bigdecimalparam, volttableparam, bytearray, shortarray, intarray,
            doublearray, stringarray, datearray, bigdecimalarray, volttablearray);

    ByteBuffer buf = ByteBuffer.allocate(pset.getSerializedSize());
    pset.flattenToBuffer(buf);/*  w  w w. ja  v a2s .c  o  m*/
    buf.flip();
    ParameterSet pset2 = ParameterSet.fromByteBuffer(buf);

    Object[] pset1array = pset.toArray();
    Object[] pset2array = pset2.toArray();

    assertTrue(Arrays.deepEquals(pset1array, pset2array));
}

From source file:net.groupbuy.controller.shop.PaymentController.java

/**
 * ??// w w  w  .j  av  a  2  s  . co m
 */
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public String submit(Type type, String paymentPluginId, String sn, BigDecimal amount,
        HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    Member member = memberService.getCurrent();
    if (member == null) {
        return ERROR_VIEW;
    }
    PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin(paymentPluginId);
    if (paymentPlugin == null || !paymentPlugin.getIsEnabled()) {
        return ERROR_VIEW;
    }
    Payment payment = new Payment();
    String description = null;
    if (type == Type.payment) {
        Order order = orderService.findBySn(sn);
        if (order == null || !member.equals(order.getMember()) || order.isExpired() || order.isLocked(null)) {
            return ERROR_VIEW;
        }
        if (order.getPaymentMethod() == null
                || order.getPaymentMethod().getMethod() != PaymentMethod.Method.online) {
            return ERROR_VIEW;
        }
        if (order.getPaymentStatus() != PaymentStatus.unpaid
                && order.getPaymentStatus() != PaymentStatus.partialPayment) {
            return ERROR_VIEW;
        }
        if (order.getAmountPayable().compareTo(new BigDecimal(0)) <= 0) {
            return ERROR_VIEW;
        }
        payment.setSn(snService.generate(Sn.Type.payment));
        payment.setType(Type.payment);
        payment.setMethod(Method.online);
        payment.setStatus(Status.wait);
        payment.setPaymentMethod(order.getPaymentMethodName() + Payment.PAYMENT_METHOD_SEPARATOR
                + paymentPlugin.getPaymentName());
        payment.setFee(paymentPlugin.calculateFee(order.getAmountPayable()));
        payment.setAmount(paymentPlugin.calculateAmount(order.getAmountPayable()));
        payment.setPaymentPluginId(paymentPluginId);
        payment.setExpire(paymentPlugin.getTimeout() != null
                ? DateUtils.addMinutes(new Date(), paymentPlugin.getTimeout())
                : null);
        payment.setOrder(order);
        paymentService.save(payment);
        description = order.getName();
    } else if (type == Type.recharge) {
        Setting setting = SettingUtils.get();
        if (amount == null || amount.compareTo(new BigDecimal(0)) <= 0 || amount.precision() > 15
                || amount.scale() > setting.getPriceScale()) {
            return ERROR_VIEW;
        }
        payment.setSn(snService.generate(Sn.Type.payment));
        payment.setType(Type.recharge);
        payment.setMethod(Method.online);
        payment.setStatus(Status.wait);
        payment.setPaymentMethod(paymentPlugin.getPaymentName());
        payment.setFee(paymentPlugin.calculateFee(amount));
        payment.setAmount(paymentPlugin.calculateAmount(amount));
        payment.setPaymentPluginId(paymentPluginId);
        payment.setExpire(paymentPlugin.getTimeout() != null
                ? DateUtils.addMinutes(new Date(), paymentPlugin.getTimeout())
                : null);
        payment.setMember(member);
        paymentService.save(payment);
        description = message("shop.member.deposit.recharge");
    } else {
        return ERROR_VIEW;
    }
    model.addAttribute("requestUrl", paymentPlugin.getRequestUrl());
    model.addAttribute("requestMethod", paymentPlugin.getRequestMethod());
    model.addAttribute("requestCharset", paymentPlugin.getRequestCharset());
    model.addAttribute("parameterMap", paymentPlugin.getParameterMap(payment.getSn(), description, request));
    if (StringUtils.isNotEmpty(paymentPlugin.getRequestCharset())) {
        response.setContentType("text/html; charset=" + paymentPlugin.getRequestCharset());
    }
    return "shop/payment/submit";
}

From source file:jp.terasoluna.fw.web.struts.form.FieldChecksEx.java

/**
 * wtB?[h?l`FbN?B/* www.j  a v a 2  s .  c  o  m*/
 * 
 * ?Ap?A<code>BigDecimal</code> ^??
 * ??s\G?[pActionMessage???A<code>false</code> p?B
 * 
 * ???w???A?mF?s?B <code>validation.xml</code> 
 * <code>isAccordedInteger()</code>  <code>"true"</code> w??
 * ???`FbN?s?B `FbN???AG?[pActionMessage???Afalsep?B
 * 
 * ????w???A?mF?s?B
 * validation.xmlisAccordedScale"true"?? ???`FbN?s?B
 * 
 * <p>
 * G?[???AG?[????A wG?[?Xg?B G?[?bZ?[WtH?[}bg?A<code>validation-rules.xml</code>
 * L?q?B<br>
 * L?A??3?A??2?l??B
 * </p>
 * 
 * <h5>validation.xmlL?q</h5>
 * <code><pre>
 * &lt;form name=&quot;/sample&quot;&gt;
 *  ?E?E?E
 *  &lt;field property=&quot;escape&quot;
 *      depends=&quot;number&quot;&gt;
 *    &lt;arg0 key=&quot;sample.escape&quot;/&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;integerLength&lt;/var-name&gt;
 *      &lt;var-value&gt;3&lt;/var-value&gt;
 *    &lt;/var&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;scale&lt;/var-name&gt;
 *      &lt;var-value&gt;2&lt;/var-value&gt;
 *    &lt;/var&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;isAccordedInteger&lt;/var-name&gt;
 *      &lt;var-value&gt;true&lt;/var-value&gt;
 *    &lt;/var&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;isAccordedScale&lt;/var-name&gt;
 *      &lt;var-value&gt;true&lt;/var-value&gt;
 *    &lt;/var&gt;
 *  &lt;/field&gt;
 *  ?E?E?E
 * &lt;/form&gt;
 * </pre></code>
 * <h5>validation.xml?v&lt;var&gt;vf</h5>
 * <table border="1">
 * <tr>
 * <td><center><b><code>var-name</code></b></center></td>
 * <td><center><b><code>var-value</code></b></center></td>
 * <td><center><b>K?{?</b></center></td>
 * <td><center><b>Tv</b></center></td>
 * </tr>
 * <tr>
 * <td> <code>integerLength</code> </td>
 * <td> ??? </td>
 * <td> <code>false</code> </td>
 * <td>?????A<code>isAccordedInteger</code>w
 * ?Aw???s?B??A?l ??A??s?B</td>
 * </tr>
 * <tr>
 * <td> <code>scale</code> </td>
 * <td> ??? </td>
 * <td> <code>false</code> </td>
 * <td>??l???A<code>isAccordedScale</code>w
 * ?Aw???s?B??A?l ??A??s?B</td>
 * </tr>
 * <tr>
 * <td> <code>isAccordedInteger</code> </td>
 * <td> ???v`FbN </td>
 * <td> <code>false</code> </td>
 * <td> <code>true</code>w?A???v`FbN ?s?B??A<code>true</code>O?
 * ?`FbN?B</td>
 * </tr>
 * <tr>
 * <td> <code>isAccordedScale</code> </td>
 * <td> ???v`FbN </td>
 * <td> <code>false</code> </td>
 * <td> <code>true</code>w?A???v`FbN ?s?B??A<code>true</code>O?
 * ?`FbN?B</td>
 * </tr>
 * </table>
 * 
 * @param bean
 *            ??IuWFNg
 * @param va
 *            StrutspValidatorAction
 * @param field
 *            tB?[hIuWFNg
 * @param errors
 *            ActionMessages ANVG?[
 * @param validator
 *            ValidatorCX^X
 * @param request
 *            HTTPNGXg
 * @return l? <code>true</code>
 */
public static boolean validateNumber(Object bean, ValidatorAction va, Field field, ActionMessages errors,
        Validator validator, HttpServletRequest request) {

    // beannull?AG?[?O?o?Atruep?B
    if (bean == null) {
        log.error("bean is null.");
        return true;
    }
    // ???
    String integerLength = field.getVarValue("integerLength");
    // ???
    String scaleStr = field.getVarValue("scale");
    // ???v`FbN
    String isAccordedInteger = field.getVarValue("isAccordedInteger");
    // ???v`FbN
    String isAccordedScale = field.getVarValue("isAccordedScale");

    String value = null;
    if (isString(bean)) {
        value = (String) bean;
    } else {
        value = ValidatorUtils.getValueAsString(bean, field.getProperty());
    }
    // ?lnull?Atruep
    if (GenericValidator.isBlankOrNull(value)) {
        return true;
    }
    char[] chars = value.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (!isHankaku(chars[i])) {
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
    }
    // ???w???A??`FbN?s
    if (GenericValidator.isInt(integerLength)) {
        try {
            BigDecimal bd = new BigDecimal(value);
            // ???l?o
            BigInteger bi = bd.toBigInteger().abs();
            // ???
            int length = bi.toString().length();
            // validation.xmlw?
            int checkLength = Integer.valueOf(integerLength).intValue();
            // ?I?[o?Afalsep
            if (length > checkLength) {
                errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
                return false;
            }
            // vw
            if (isAccordedInteger != null && "true".equals(isAccordedInteger)) {
                // ?sv?Afalsep
                if (length != checkLength) {
                    errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
                    return false;
                }
            }
        } catch (NumberFormatException nfe) {
            // ?l^?Afalsep
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
    }

    // ???w???A??`FbN?s
    if (GenericValidator.isInt(scaleStr)) {
        int scale = 0;
        int checkScale = 0;
        try {
            BigDecimal bd = new BigDecimal(value);
            scale = bd.scale();
            // validation.xmlw?
            checkScale = Integer.valueOf(scaleStr).intValue();
        } catch (NumberFormatException e) {
            // ?l^?Afalsep
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
        // ?I?[o?Afalsep
        if (scale > checkScale) {
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
        // vw
        if (isAccordedScale != null && "true".equals(isAccordedScale)) {
            // ?sv?Afalsep
            if (scale != checkScale) {
                errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
                return false;
            }
        }
    }
    return true;
}

From source file:org.kuali.kfs.module.purap.service.impl.PurapAccountingServiceImpl.java

/**
 * @see org.kuali.kfs.module.purap.service.PurapAccountingService#generateAccountDistributionForProrationWithZeroTotal(java.util.List,
 *      java.lang.Integer)//from   w w  w . ja v  a 2  s  . c  o  m
 */
@Override
public List<PurApAccountingLine> generateAccountDistributionForProrationWithZeroTotal(
        PurchasingAccountsPayableDocument purapDoc) {
    String methodName = "generateAccountDistributionForProrationWithZeroTotal()";
    if (LOG.isDebugEnabled()) {
        LOG.debug(methodName + " started");
    }

    List<PurApAccountingLine> accounts = generatePercentSummary(purapDoc);

    // find the total percent and strip trailing zeros
    BigDecimal totalPercentValue = BigDecimal.ZERO;
    for (PurApAccountingLine accountingLine : accounts) {
        BigDecimal linePercent = BigDecimal.ZERO;
        if (ObjectUtils.isNotNull(accountingLine.getAccountLinePercent())) {
            linePercent = accountingLine.getAccountLinePercent();
        }

        totalPercentValue = totalPercentValue.add(linePercent).movePointLeft(2).stripTrailingZeros()
                .movePointRight(2);
    }

    if ((BigDecimal.ZERO.compareTo(totalPercentValue.remainder(ONE_HUNDRED))) != 0) {
        throwRuntimeException(methodName, "Invalid Percent Total of '" + totalPercentValue
                + "' does not allow for account distribution (must be multiple of 100)");
    }

    List newAccounts = new ArrayList();
    BigDecimal logDisplayOnlyTotal = BigDecimal.ZERO;
    BigDecimal percentUsed = BigDecimal.ZERO;
    int accountListSize = accounts.size();
    int i = 0;
    for (PurApAccountingLine accountingLine : accounts) {
        i++;
        BigDecimal percentToUse = BigDecimal.ZERO;
        KualiDecimal amt = KualiDecimal.ZERO;

        if (ObjectUtils.isNotNull(accountingLine.getAmount())) {
            amt = accountingLine.getAmount();
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " " + accountingLine.getChartOfAccountsCode() + "-"
                    + accountingLine.getAccountNumber() + " " + amt + "/" + percentToUse);
        }

        // if it's the last account make up the leftover percent
        BigDecimal acctPercent = BigDecimal.ZERO;
        if (ObjectUtils.isNotNull(accountingLine.getAccountLinePercent())) {
            acctPercent = accountingLine.getAccountLinePercent();
        }

        if ((i != accountListSize) || (accountListSize == 1)) {
            // this account is not the last account or there is only one account
            percentToUse = (acctPercent.divide(totalPercentValue, SCALE, BIG_DECIMAL_ROUNDING_MODE))
                    .multiply(ONE_HUNDRED);
            percentUsed = percentUsed
                    .add(((acctPercent.divide(totalPercentValue, SCALE, BIG_DECIMAL_ROUNDING_MODE)))
                            .multiply(ONE_HUNDRED));
        } else {
            // this account is the last account so we have to makeup whatever is left out of 100
            percentToUse = ONE_HUNDRED.subtract(percentUsed);
        }

        PurApAccountingLine newAccountingLine = accountingLine.createBlankAmountsCopy();
        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " pct = " + percentToUse);
        }
        newAccountingLine
                .setAccountLinePercent(percentToUse.setScale(acctPercent.scale(), BIG_DECIMAL_ROUNDING_MODE));
        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " adding " + newAccountingLine.getAccountLinePercent());
        }
        newAccounts.add(newAccountingLine);
        logDisplayOnlyTotal = logDisplayOnlyTotal.add(newAccountingLine.getAccountLinePercent());
        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " total = " + logDisplayOnlyTotal);
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(methodName + " ended");
    }
    return newAccounts;
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 *  Create a new Node from a ResultSet./*from  w w w. ja  v a  2 s.  c om*/
 */
public Node createNode(DbMapping dbm, ResultSet rs, DbColumn[] columns, int offset)
        throws SQLException, IOException, ClassNotFoundException {
    HashMap propBuffer = new HashMap();
    String id = null;
    String name = null;
    String protoName = dbm.getTypeName();
    DbMapping dbmap = dbm;

    Node node = new Node();

    for (int i = 0; i < columns.length; i++) {
        // set prototype?
        if (columns[i].isPrototypeField()) {
            protoName = rs.getString(i + 1 + offset);

            if (protoName != null) {
                dbmap = getDbMapping(protoName);

                if (dbmap == null) {
                    // invalid prototype name!
                    app.logError(ErrorReporter.errorMsg(this.getClass(), "createNode")
                            + "Invalid prototype name: " + protoName + " - using default");
                    dbmap = dbm;
                    protoName = dbmap.getTypeName();
                }
            }
        }

        // set id?
        if (columns[i].isIdField()) {
            id = rs.getString(i + 1 + offset);
            // if id == null, the object doesn't actually exist - return null
            if (id == null) {
                return null;
            }
        }

        // set name?
        if (columns[i].isNameField()) {
            name = rs.getString(i + 1 + offset);
        }

        Property newprop = new Property(node);

        switch (columns[i].getType()) {
        case Types.BIT:
            newprop.setBooleanValue(rs.getBoolean(i + 1 + offset));

            break;

        case Types.TINYINT:
        case Types.BIGINT:
        case Types.SMALLINT:
        case Types.INTEGER:
            newprop.setIntegerValue(rs.getLong(i + 1 + offset));

            break;

        case Types.REAL:
        case Types.FLOAT:
        case Types.DOUBLE:
            newprop.setFloatValue(rs.getDouble(i + 1 + offset));

            break;

        case Types.DECIMAL:
        case Types.NUMERIC:

            BigDecimal num = rs.getBigDecimal(i + 1 + offset);

            if (num == null) {
                break;
            }

            if (num.scale() > 0) {
                newprop.setFloatValue(num.doubleValue());
            } else {
                newprop.setIntegerValue(num.longValue());
            }

            break;

        case Types.VARBINARY:
        case Types.BINARY:
            //                    newprop.setStringValue(rs.getString(i+1+offset));
            newprop.setJavaObjectValue(rs.getBytes(i + 1 + offset));

            break;

        case Types.LONGVARBINARY: {
            InputStream in = rs.getBinaryStream(i + 1 + offset);
            if (in == null) {
                break;
            }
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int read;
            while ((read = in.read(buffer)) > -1) {
                bout.write(buffer, 0, read);
            }
            newprop.setJavaObjectValue(bout.toByteArray());
        }

            break;
        case Types.LONGVARCHAR:
            try {
                newprop.setStringValue(rs.getString(i + 1 + offset));
            } catch (SQLException x) {
                Reader in = rs.getCharacterStream(i + 1 + offset);
                char[] buffer = new char[2048];
                int read = 0;
                int r;

                while ((r = in.read(buffer, read, buffer.length - read)) > -1) {
                    read += r;

                    if (read == buffer.length) {
                        // grow input buffer
                        char[] newBuffer = new char[buffer.length * 2];

                        System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
                        buffer = newBuffer;
                    }
                }

                newprop.setStringValue(new String(buffer, 0, read));
            }

            break;

        case Types.CHAR:
        case Types.VARCHAR:
        case Types.OTHER:
            newprop.setStringValue(rs.getString(i + 1 + offset));

            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            newprop.setDateValue(rs.getTimestamp(i + 1 + offset));

            break;

        case Types.NULL:
            newprop.setStringValue(null);

            break;

        case Types.CLOB:
            Clob cl = rs.getClob(i + 1 + offset);
            if (cl == null) {
                newprop.setStringValue(null);
                break;
            }
            char[] c = new char[(int) cl.length()];
            Reader isr = cl.getCharacterStream();
            isr.read(c);
            newprop.setStringValue(String.copyValueOf(c));
            break;

        default:
            newprop.setStringValue(rs.getString(i + 1 + offset));

            break;
        }

        if (rs.wasNull()) {
            newprop.setStringValue(null);
        }

        propBuffer.put(columns[i].getName(), newprop);

        // mark property as clean, since it's fresh from the db
        newprop.dirty = false;
    }

    if (id == null) {
        return null;
    }

    Hashtable propMap = new Hashtable();
    DbColumn[] columns2 = dbmap.getColumns();
    for (int i = 0; i < columns2.length; i++) {
        Relation rel = columns2[i].getRelation();

        if (rel != null && (rel.reftype == Relation.PRIMITIVE || rel.reftype == Relation.REFERENCE)) {

            Property prop = (Property) propBuffer.get(columns2[i].getName());

            if (prop == null) {
                continue;
            }
            prop.setName(rel.propName);
            // if the property is a pointer to another node, change the property type to NODE
            if ((rel.reftype == Relation.REFERENCE) && rel.usesPrimaryKey()) {
                // FIXME: References to anything other than the primary key are not supported
                prop.convertToNodeReference(rel.otherType, this.app.getCurrentRequestEvaluator().getLayer());
            }
            propMap.put(rel.propName.toLowerCase(), prop);
        }
    }

    node.init(dbmap, id, name, protoName, propMap, safe);

    return node;
}

From source file:com.gst.portfolio.savings.domain.SavingsAccount.java

protected boolean createWithHoldTransaction(final BigDecimal amount, final LocalDate date) {
    boolean isTaxAdded = false;
    if (this.taxGroup != null && amount.compareTo(BigDecimal.ZERO) == 1) {
        Map<TaxComponent, BigDecimal> taxSplit = TaxUtils.splitTax(amount, date,
                this.taxGroup.getTaxGroupMappings(), amount.scale());
        BigDecimal totalTax = TaxUtils.totalTaxAmount(taxSplit);
        if (totalTax.compareTo(BigDecimal.ZERO) == 1) {
            SavingsAccountTransaction withholdTransaction = SavingsAccountTransaction.withHoldTax(this,
                    office(), date, Money.of(currency, totalTax), taxSplit);
            addTransaction(withholdTransaction);
            isTaxAdded = true;/* ww  w  . j a  va2s.com*/
        }
    }
    return isTaxAdded;
}

From source file:com.gst.portfolio.savings.domain.SavingsAccount.java

protected boolean updateWithHoldTransaction(final BigDecimal amount,
        final SavingsAccountTransaction withholdTransaction) {
    boolean isTaxAdded = false;
    if (this.taxGroup != null && amount.compareTo(BigDecimal.ZERO) == 1) {
        Map<TaxComponent, BigDecimal> taxSplit = TaxUtils.splitTax(amount,
                withholdTransaction.transactionLocalDate(), this.taxGroup.getTaxGroupMappings(),
                amount.scale());
        BigDecimal totalTax = TaxUtils.totalTaxAmount(taxSplit);
        if (totalTax.compareTo(BigDecimal.ZERO) == 1) {
            if (withholdTransaction.getId() == null) {
                withholdTransaction.updateAmount(Money.of(currency, totalTax));
                withholdTransaction.getTaxDetails().clear();
                SavingsAccountTransaction.updateTaxDetails(taxSplit, withholdTransaction);
                isTaxAdded = true;//w  ww .  j  a v  a2 s. c  om
            } else if (totalTax.compareTo(withholdTransaction.getAmount()) != 0) {
                withholdTransaction.reverse();
                SavingsAccountTransaction newWithholdTransaction = SavingsAccountTransaction.withHoldTax(this,
                        office(), withholdTransaction.transactionLocalDate(), Money.of(currency, totalTax),
                        taxSplit);
                addTransaction(newWithholdTransaction);
                isTaxAdded = true;
            }
        }
    }
    return isTaxAdded;
}