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:com.prowidesoftware.swift.model.CurrencyAmount.java

/**
 * Creates a currency amount from an MT field.<br />
 * The field must at least implement the {@linkplain AmountContainer} interface and 
 * either have a currency component or implements the {@linkplain CurrencyContainer}
 * For some fields like the signed 19A or the 62[F,M] which have a debit/credit mark
 * component, the amount will be positive or negative accordingly.
 * /*from ww  w .j  a  v a2s . c  o  m*/
 * @param field a field with currency and amount components
 * @return the created currency amount object or null if field is null or invalid.
 */
/*
 * Do not use API from MTs and Field classes here to avoid cyclic dependency in code generation
 * Component numbers do not normally change, although keep code below in sync with fields 62FM, 19A and 33B. 
 */
static CurrencyAmount of(Field field) {
    if (field != null && field instanceof AmountContainer) {
        /*
         * amount from interface
         */
        BigDecimal amount = ((AmountContainer) field).amount();
        if (amount == null) {
            log.warning(
                    "cannot extract amount component from field " + field.getName() + ":" + field.getValue());
            return null;
        }

        /*
         * special cases
         */
        String currency = null;
        boolean negative = false;
        if ("62F".equals(field.getName()) || "62M".equals(field.getName())) {
            currency = field.getComponent(3);
            negative = StringUtils.equals("D", field.getComponent(1));
        } else if ("19A".equals(field.getName())) {
            negative = StringUtils.equals("N", field.getComponent(2));
        } else if ("33B".equals(field.getName())) {
            currency = field.getComponent(1);
        }

        /*
         * currency from interface
         */
        if (currency == null && field instanceof CurrencyContainer) {
            currency = ((CurrencyContainer) field).currencyString();
        }

        if (currency == null) {
            log.warning(
                    "cannot extract currency component from field " + field.getName() + ":" + field.getValue());
            return null;
        }

        if (negative) {
            amount = amount.negate();
        }
        return new CurrencyAmount(currency, amount);
    }
    return null;
}

From source file:net.sf.morph.transform.converters.TextToNumberConverter.java

/**
 * Negate if necessary//  www . ja va 2  s .  c  o  m
 * @param returnVal
 * @param negate
 * @param locale
 * @return negated value if negate, else returnValue
 */
private Object negateIfNecessary(Number returnVal, boolean negate, Locale locale) {
    if (negate) {
        BigDecimal bd = (BigDecimal) getNumberConverter().convert(BigDecimal.class, returnVal, locale);
        return bd.negate();
    }
    return returnVal;
}

From source file:org.openvpms.archetype.rules.stock.ChargeStockUpdater.java

/**
 * Updates stock quantities.//from   w  w w.  ja va 2 s . co  m
 *
 * @param stock    the product and location state
 * @param quantity the quantity to add/remove
 * @param credit   determines if the act is a credit
 */
private void updateStockQuantities(StockQty stock, BigDecimal quantity, boolean credit) {
    Party location = stock.getLocation();
    Product product = stock.getProduct();
    if (location != null && product != null
            && TypeHelper.isA(product, ProductArchetypes.MEDICATION, ProductArchetypes.MERCHANDISE)) {
        if (!credit) {
            quantity = quantity.negate();
        }
        EntityRelationship relationship = rules.getStockRelationship(product, location);
        if (relationship == null) {
            List<IMObject> objects = rules.calcStock(product, location, quantity);
            toSave.addAll(objects);
        } else {
            rules.calcStock(relationship, quantity);
            toSave.add(relationship);
        }
    }
}

From source file:com.repay.android.frienddetails.FriendDetailsActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (data != null && requestCode == PICK_CONTACT_REQUEST) {
        try {/*from   w w  w  .  j a v a  2  s.  co m*/
            Uri contactUri = data.getData();
            String[] cols = { ContactsContract.Contacts.DISPLAY_NAME };
            Cursor cursor = getContentResolver().query(contactUri, cols, null, null, null);
            cursor.moveToFirst();
            String result = cursor.getString(0).replaceAll("[-+.^:,']", "");
            Friend pickerResult = new Friend(mFriend.getRepayID(), contactUri, result, mFriend.getDebt());
            mDB.updateFriendRecord(pickerResult);
            requestBackup();
        } catch (IndexOutOfBoundsException e) {
            Toast.makeText(this, "Problem in getting result from your contacts", Toast.LENGTH_SHORT).show();
        } catch (SQLException e) {
            e.printStackTrace();
            Toast.makeText(this, "Unable to add this person to the database", Toast.LENGTH_SHORT).show();
        }
    } else if (data != null && requestCode == AMOUNT_ENTER_REQUEST) {
        try {
            Bundle b = data.getExtras();
            // Get the amount sent back from the activity
            BigDecimal amount = new BigDecimal(b.getString(AddDebtActivity.AMOUNT));
            // Make the amount negative if their debt is negative
            if (mFriend.getDebt().compareTo(BigDecimal.ZERO) > 0) {
                amount = amount.negate();
            }
            mDB.addDebt(mFriend.getRepayID(), amount, "Repaid");
            mFriend.setDebt(mFriend.getDebt().add(amount));
            mDB.updateFriendRecord(mFriend);
            requestBackup();
        } catch (Exception e) {

        }
    }
}

From source file:org.openvpms.archetype.rules.supplier.DeliveryProcessor.java

/**
 * Processes a delivery/return item./*  w  w w  . j  a  v a 2s. co m*/
 *
 * @param item the delivery/return item
 * @throws ArchetypeServiceException  for any archetype service error
 * @throws DeliveryProcessorException if the item is missing a product
 */
private void processItem(Act item) {
    ActBean itemBean = new ActBean(item, service);
    BigDecimal receivedQuantity = itemBean.getBigDecimal("quantity");
    int receivedPackSize = itemBean.getInt("packageSize");
    boolean delivery = TypeHelper.isA(act, SupplierArchetypes.DELIVERY);
    if (!delivery) {
        receivedQuantity = receivedQuantity.negate();
    }
    Product product = (Product) itemBean.getNodeParticipant("product");
    if (product == null) {
        throw new DeliveryProcessorException(DeliveryProcessorException.ErrorCode.NoProduct,
                DescriptorHelper.getDisplayName(item, service), item.getId(),
                DescriptorHelper.getDisplayName(act, service), act.getId());
    }

    // update the associated order's received quantity
    for (Act orderItem : itemBean.getNodeActs("order")) {
        updateReceivedQuantity((FinancialAct) orderItem, receivedQuantity, receivedPackSize);
    }

    if (delivery) {
        // update the product-supplier relationship
        if (supplier != null) {
            updateProductSupplier(product, itemBean);
        }
        String batchNumber = StringUtils.trimToNull(itemBean.getString("batchNumber"));
        Date expiryDate = itemBean.getDate("expiryDate");
        IMObjectReference manufacturer = itemBean.getNodeParticipantRef("manufacturer");
        if (batchNumber != null || expiryDate != null) {
            updateBatch(product, batchNumber, expiryDate, manufacturer);
        }
    }

    // update the stock quantity for the product at the stock location
    if (stockLocation != null) {
        updateStockQuantity(product, stockLocation, receivedQuantity, receivedPackSize);
    }
}

From source file:org.kuali.kpme.tklm.leave.accrual.service.AccrualCategoryMaxCarryOverServiceImpl.java

private void calculateMaxCarryOverForLeavePlan(String documentId, String principalId,
        CalendarEntry calendarEntry, String leavePlan, LocalDate asOfDate) {
    List<? extends AccrualCategoryContract> accrualCategories = getAccrualCategoryService()
            .getActiveAccrualCategoriesForLeavePlan(leavePlan, asOfDate);

    for (AccrualCategoryContract accrualCategory : accrualCategories) {
        BigDecimal adjustmentAmount = getAccrualCategoryCarryOverAdjustment(
                accrualCategory.getAccrualCategory(), principalId, calendarEntry, asOfDate);

        if (adjustmentAmount.compareTo(BigDecimal.ZERO) > 0) {
            LocalDate LeaveDate = calendarEntry.getEndPeriodFullDateTime().toLocalDate().minusDays(1);

            addAdjustmentLeaveBlock(documentId, principalId, LeaveDate, accrualCategory,
                    adjustmentAmount.negate());
        }/* ww w  . ja v a 2 s .  c  o m*/
    }
}

From source file:org.openvpms.archetype.rules.finance.account.CustomerAccountRules.java

/**
 * Calculates a new balance for a customer from the current outstanding
 * balance and a running total./*from w w  w . j  a  v a2 s.co  m*/
 * If the new balance is:
 * <ul>
 * <li>&lt; 0 returns 0.00 for payments, or -balance for refunds</li>
 * <li>&gt; 0 returns 0.00 for refunds</li>
 * </ul>
 *
 * @param customer the customer
 * @param total    the running total
 * @param payment  if {@code true} indicates the total is for a payment,
 *                 if {@code false} indicates it is for a refund
 * @return the new balance
 * @throws ArchetypeServiceException for any archetype service error
 */
public BigDecimal getBalance(Party customer, BigDecimal total, boolean payment) {
    BigDecimal balance = getBalance(customer);
    BigDecimal result;
    if (payment) {
        result = balance.subtract(total);
    } else {
        result = balance.add(total);
    }
    if (result.signum() == -1) {
        result = (payment) ? BigDecimal.ZERO : result.negate();
    } else if (result.signum() == 1 && !payment) {
        result = BigDecimal.ZERO;
    }
    return result;
}

From source file:org.kuali.kpme.tklm.leave.block.service.LeaveBlockServiceImpl.java

private BigDecimal negateHoursIfNecessary(String leaveBlockType, BigDecimal hours) {
    if ((leaveBlockType.equals(LMConstants.LEAVE_BLOCK_TYPE.LEAVE_CALENDAR)
            || leaveBlockType.equals((LMConstants.LEAVE_BLOCK_TYPE.TIME_CALENDAR)))
            && BigDecimal.ZERO.compareTo(hours) < 0) {
        hours = hours.negate();
    }/*w ww  .  ja  v  a 2  s  .c o m*/
    return hours;
}

From source file:org.openbravo.erpCommon.ad_reports.MInOutTraceReports.java

private String processExternalChilds(VariablesSecureApp vars, MInOutTraceReportsData dataChild, String strIn,
        boolean colorbg, String strmProductIdGlobal, Hashtable<String, Integer> calculated,
        Vector<Integer> count) throws ServletException {
    StringBuffer strHtml = new StringBuffer();
    BigDecimal movementQty = new BigDecimal(dataChild.movementqty);
    // if (log4j.isDebugEnabled()) log4j.debug("****PROCESSING EXTERNAL 1: "
    // + movementQty.toString() + " and strIn: " + strIn);
    if (strIn.equals("Y"))
        movementQty = movementQty.negate();
    if (log4j.isDebugEnabled())
        log4j.debug("****PROCESSING EXTERNAL 2: " + movementQty.toString() + " and movementType:"
                + dataChild.movementtype);

    if (dataChild.movementtype.startsWith("P") && (movementQty.compareTo(BigDecimal.ZERO) > 0)) {
        String strNewId = dataChild.mProductionlineId;
        MInOutTraceReportsData[] dataProduction;
        if (log4j.isDebugEnabled())
            log4j.debug("****PROCESSING PRODUCTIONLINE: " + strNewId + " " + strIn);
        if (strIn.equals("Y")) {
            dataProduction = MInOutTraceReportsData.selectProductionOut(this, vars.getLanguage(), strNewId);
        } else {//  w w w  .  j a v a 2  s  .c  om
            dataProduction = MInOutTraceReportsData.selectProductionIn(this, vars.getLanguage(), strNewId);
        }
        if (dataProduction != null && dataProduction.length > 0) {
            strHtml.append("  <tr>\n");
            strHtml.append("    <td colspan=\"3\">\n");
            strHtml.append(insertHeaderHtml(false, "0"));
            for (int j = 0; j < dataProduction.length; j++) {
                strHtml.append("  <tr style=\"background: ").append((colorbg ? "#CCCCCC" : "#AAAAAA"))
                        .append("\">\n");
                strHtml.append(insertTabHtml(true));
                strHtml.append("    <td >\n");

                String resultado2 = "";
                strHtml.append("<table border=\"0\" cellspacing=0 cellpadding=0 width=\"100%\">\n");
                strHtml.append("  <tr>\n");
                strHtml.append("    <td class=\"DataGrid_Body_Cell\" width=\"70\">")
                        .append(dataProduction[j].movementdate).append("</td>\n");
                strHtml.append("    <td class=\"DataGrid_Body_Cell\" width=\"100\">")
                        .append(StringEscapeUtils.escapeHtml(dataProduction[j].movementtypeName))
                        .append("</td>\n");
                strHtml.append("    <td class=\"DataGrid_Body_Cell\" width=\"100\">")
                        .append(dataProduction[j].locatorName).append("</td>\n");
                strHtml.append("    <td class=\"DataGrid_Body_Cell_Amount\" width=\"90\">")
                        .append(dataProduction[j].movementqty).append("&nbsp;")
                        .append(StringEscapeUtils.escapeHtml(dataProduction[j].uomName)).append("</td>\n");
                strHtml.append("    <td class=\"DataGrid_Body_Cell\" width=\"90\">")
                        .append(dataProduction[j].quantityorder).append("&nbsp;")
                        .append(StringEscapeUtils.escapeHtml(dataProduction[j].productUomName))
                        .append("</td>\n");
                resultado2 = dataProduction[j].productName;
                strHtml.append(
                        "    <td class=\"DataGrid_Body_Cell\"><a href=\"#\" onclick=\"submitCommandForm('INVERSE', true, null, 'MInOutTraceReports.html?inpmProductId2="
                                + dataProduction[j].mProductId + "&inpmAttributeSetInstanceId2="
                                + dataProduction[j].mAttributesetinstanceId + "&inpIn2="
                                + (strIn.equals("Y") ? "N" : "Y")
                                + "', '_self');return true;\" class=\"LabelLink\">");
                if (!resultado2.equals(""))
                    strHtml.append(StringEscapeUtils.escapeHtml(resultado2));
                strHtml.append("&nbsp;</a></td>\n");
                resultado2 = dataProduction[j].attributeName;
                strHtml.append("    <td class=\"DataGrid_Body_Cell\" width=\"120\">");
                if (!resultado2.equals(""))
                    strHtml.append(StringEscapeUtils.escapeHtml(resultado2));
                strHtml.append("&nbsp;</td>\n");
                strHtml.append("</tr></table>");

                strHtml.append("  </td></tr>\n");
                if (!dataProduction[j].mAttributesetinstanceId.equals("0")) {
                    String strCalculate = dataProduction[j].mProductId + "&"
                            + dataProduction[j].mAttributesetinstanceId + "&" + dataProduction[j].mLocatorId;
                    if (log4j.isDebugEnabled())
                        log4j.debug("******** Hashtable.production: " + strCalculate);
                    if (log4j.isDebugEnabled())
                        log4j.debug(
                                "******** Production, hashtable calculated: " + calculated.get(strCalculate));
                    Integer isnull = calculated.get(strCalculate);
                    if (isnull == null) {
                        String strPartial = processChilds(vars, dataProduction[j].mAttributesetinstanceId,
                                dataProduction[j].mProductId, dataProduction[j].mLocatorId, strIn, !colorbg,
                                strmProductIdGlobal, calculated, count);
                        if (!strPartial.equals("")) {
                            strHtml.append("  <tr style=\"background: ")
                                    .append((colorbg ? "#CCCCCC" : "#AAAAAA")).append("\">\n");
                            strHtml.append(insertTabHtml(false));
                            strHtml.append("    <td>\n");
                            strHtml.append(strPartial);
                            strHtml.append("    </td>\n");
                            strHtml.append("  </tr>\n");
                        }
                    }
                }
            }
            strHtml.append(insertHeaderHtml(true, ""));
            strHtml.append("</td></tr>\n");
        }
    }

    if (dataChild.movementtype.startsWith("M") && (movementQty.compareTo(BigDecimal.ZERO) > 0)) {
        String strNewId = dataChild.mMovementlineId;
        MInOutTraceReportsData[] dataMovement;
        if (log4j.isDebugEnabled())
            log4j.debug("****PROCESSING MOVEMENTLINE: " + strNewId + " " + strIn);
        dataMovement = MInOutTraceReportsData.selectMovement(this, vars.getLanguage(),
                strIn.equals("Y") ? "M+" : "M-", strNewId);
        if (dataMovement != null && dataMovement.length > 0) {
            strHtml.append("  <tr>\n");
            strHtml.append("    <td colspan=\"3\">\n");
            strHtml.append(insertHeaderHtml(false, "1"));
            for (int j = 0; j < dataMovement.length; j++) {
                strHtml.append("  <tr style=\"background: ").append((colorbg ? "#CCCCCC" : "#AAAAAA"))
                        .append("\">\n");
                strHtml.append(insertTabHtml(true));
                strHtml.append("    <td >\n");

                String resultado2 = "";
                strHtml.append("<table border=\"0\" cellspacing=0 cellpadding=0 width=\"100%\">\n");
                strHtml.append("  <tr>\n");
                strHtml.append("    <td class=\"DataGrid_Body_Cell\" width=\"70\">")
                        .append(dataMovement[j].movementdate).append("</td>\n");
                strHtml.append("    <td class=\"DataGrid_Body_Cell\" width=\"100\">")
                        .append(dataMovement[j].movementtypeName).append("</td>\n");
                strHtml.append("    <td class=\"DataGrid_Body_Cell\" width=\"100\">")
                        .append(dataMovement[j].locatorName).append("</td>\n");
                strHtml.append("    <td class=\"DataGrid_Body_Cell_Amount\" width=\"90\">")
                        .append(dataMovement[j].movementqty).append("&nbsp;").append(dataMovement[j].uomName)
                        .append("</td>\n");
                strHtml.append("    <td class=\"DataGrid_Body_Cell\" width=\"90\">")
                        .append(dataMovement[j].quantityorder).append("&nbsp;")
                        .append(dataMovement[j].productUomName).append("</td>\n");
                resultado2 = dataMovement[j].productName;
                strHtml.append("    <td class=\"DataGrid_Body_Cell\">");
                if (!resultado2.equals(""))
                    strHtml.append(resultado2);
                strHtml.append("&nbsp;</td>\n");
                resultado2 = dataMovement[j].attributeName;
                strHtml.append("    <td class=\"DataGrid_Body_Cell\" width=\"120\">");
                if (!resultado2.equals(""))
                    strHtml.append(resultado2);
                strHtml.append("&nbsp;</td>\n");
                strHtml.append("</tr></table>");

                // strHtml.append(getData(dataProduction[j], "Bordes"));
                strHtml.append("  </td></tr>\n");
                if (!dataMovement[j].mAttributesetinstanceId.equals("0")) {
                    String strPartial = "";
                    if (!dataMovement[j].mProductId.equals(strmProductIdGlobal)) {
                        if (log4j.isDebugEnabled())
                            log4j.debug("******** hashtable.production: Prod: " + dataMovement[j].mProductId
                                    + " Attr " + dataMovement[j].mAttributesetinstanceId + " Loc: "
                                    + dataMovement[j].mLocatorId);
                        String strCalculate = dataMovement[j].mProductId + "&"
                                + dataMovement[j].mAttributesetinstanceId + "&" + dataMovement[j].mLocatorId;
                        if (log4j.isDebugEnabled())
                            log4j.debug(
                                    "******** Movement, hashtable calculated: " + calculated.get(strCalculate));
                        if (calculated.get(strCalculate) == null) {
                            strPartial = processChilds(vars, dataMovement[j].mAttributesetinstanceId,
                                    dataMovement[j].mProductId, dataMovement[j].mLocatorId, strIn, !colorbg,
                                    strmProductIdGlobal, calculated, count);
                        }
                    }
                    if (!strPartial.equals("")) {
                        strHtml.append("  <tr style=\"background: ").append((colorbg ? "#CCCCCC" : "#AAAAAA"))
                                .append("\">\n");
                        strHtml.append(insertTabHtml(false));
                        strHtml.append("    <td>\n");
                        strHtml.append(strPartial);
                        strHtml.append("    </td>\n");
                        strHtml.append("  </tr>\n");
                    }
                }
            }
            strHtml.append(insertHeaderHtml(true, ""));
            strHtml.append("</td></tr>\n");
        }
    }
    return strHtml.toString();
}

From source file:oscar.oscarBilling.ca.on.data.JdbcBillingClaimImpl.java

public boolean add3rdBillExt(Map<String, String> mVal, int id) {
    boolean retval = true;
    String[] temp = { "billTo", "remitTo", "total", "payment", "refund", "provider_no", "gst", "payDate",
            "payMethod" };
    String demoNo = mVal.get("demographic_no");
    String dateTime = UtilDateUtilities.getToday("yyyy-MM-dd HH:mm:ss");
    mVal.put("payDate", dateTime);
    String paymentSumParam = null;
    String paymentRefundParam = null;
    String paymentDateParam = null;
    String paymentTypeParam = null;
    for (int i = 0; i < temp.length; i++) {
        String sql = "insert into billing_on_ext values(\\N, " + id + "," + demoNo + ", '" + temp[i] + "', '"
                + mVal.get(temp[i]) + "', '" + dateTime + "', '1' )";
        retval = dbObj.updateDBRecord(sql);
        if (i == 3)
            paymentSumParam = mVal.get(temp[i]);
        else if (i == 4)
            paymentRefundParam = mVal.get(temp[i]);
        else if (i == 7)
            paymentDateParam = mVal.get(temp[i]);
        else if (i == 8)
            paymentTypeParam = mVal.get(temp[i]);
        if (!retval) {
            _logger.error("add3rdBillExt(sql = " + sql + ")");
            return retval;
        }/*ww  w  . java2s . c  o m*/
    }

    if (paymentRefundParam != null && !paymentRefundParam.trim().startsWith("-"))
        paymentRefundParam = paymentRefundParam.substring(1, paymentRefundParam.length());

    if (paymentSumParam != null || paymentRefundParam != null) {
        BillingONPaymentDao billingONPaymentDao = (BillingONPaymentDao) SpringUtils
                .getBean("billingONPaymentDao");
        BillingClaimDAO billingONCHeader1Dao = (BillingClaimDAO) SpringUtils.getBean("billingClaimDAO");
        BillingPaymentTypeDao billingPaymentTypeDao = (BillingPaymentTypeDao) SpringUtils
                .getBean("billingPaymentTypeDao");
        BillingClaimHeader1 ch1 = billingONCHeader1Dao.find(id);
        Date paymentDate = null;
        try {
            paymentDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(paymentDateParam);
        } catch (ParseException ex) {
            _logger.error("add3rdBillExt wrong date format " + paymentDateParam);
            return retval;
        }
        if (paymentTypeParam == null || paymentTypeParam.equals(""))
            paymentTypeParam = "1";
        BillingPaymentType type = billingPaymentTypeDao.find(Integer.parseInt(paymentTypeParam));
        BillingONPayment payment = null;
        if (paymentSumParam != null) {
            payment = new BillingONPayment();
            payment.setPayment(BigDecimal.valueOf(Double.parseDouble(paymentSumParam)));
            payment.setPaymentDate(paymentDate);
            payment.setBillingOnCheader1(ch1);
            payment.setBillingPaymentType(type);
            billingONPaymentDao.persist(payment);
        }
        if (paymentRefundParam != null) {
            BigDecimal refund = BigDecimal.valueOf(Double.parseDouble(paymentRefundParam));
            int comp = refund.compareTo(new BigDecimal(0.0));
            if (comp != 0) {
                payment = new BillingONPayment();
                if (comp < 0)
                    refund = refund.negate();
                payment.setPayment(refund);
                payment.setPaymentDate(paymentDate);
                payment.setBillingOnCheader1(ch1);
                payment.setBillingPaymentType(type);
                billingONPaymentDao.persist(payment);
            }
        }
    }
    return retval;
}