Example usage for java.math BigDecimal toPlainString

List of usage examples for java.math BigDecimal toPlainString

Introduction

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

Prototype

public String toPlainString() 

Source Link

Document

Returns a string representation of this BigDecimal without an exponent field.

Usage

From source file:com.streamsets.pipeline.stage.origin.salesforce.ForceSource.java

private String fixOffset(String offsetColumn, String offset) {
    com.sforce.soap.partner.Field sfdcField = ((SobjectRecordCreator) recordCreator)
            .getFieldMetadata(sobjectType, offsetColumn);
    if (SobjectRecordCreator.DECIMAL_TYPES.contains(sfdcField.getType().toString()) && offset.contains("E")) {
        BigDecimal val = new BigDecimal(offset);
        offset = val.toPlainString();
        if (val.compareTo(MAX_OFFSET_INT) > 0 && !offset.contains(".")) {
            // We need the ".0" suffix since Salesforce doesn't like integer
            // bigger than 2147483647
            offset += ".0";
        }/*from   w  w w  .  ja  v  a2  s.c  o m*/
    }
    return offset;
}

From source file:org.broadleafcommerce.core.search.service.solr.SolrHelperServiceImpl.java

@Override
public String getSolrRangeString(String fieldName, BigDecimal minValue, BigDecimal maxValue) {
    StringBuilder sb = new StringBuilder();

    sb.append(fieldName).append(":[");
    if (minValue == null) {
        sb.append("*");
    } else {/*  www  . j a  v  a2  s  .  c  o m*/
        sb.append(minValue.toPlainString());
    }

    sb.append(" TO ");

    if (maxValue == null) {
        sb.append("*");
    } else {
        sb.append(maxValue.toPlainString());
    }

    sb.append(']');

    return sb.toString();
}

From source file:de.topicmapslab.couchtm.core.OccurrenceImpl.java

@Override
public void setValue(BigDecimal value) {
    if (!loaded)/*from   w w w.j  a va 2  s  .co m*/
        load();
    if (mergedIn != null) {
        mergedIn.setValue(value);
        return;
    }
    Check.valueNotNull(this, value);
    datatype = new LocatorImpl(IConstant.XSD_DECIMAL);
    this.value = value.toPlainString();
    try {
        _fireEvent(Event.VALUE_CHANGED, null, value);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.dotmarketing.portlets.cmsmaintenance.action.ViewCMSMaintenanceAction.java

/**
 * Retrieves the basic information of the contents in the
 * {@code dist_reindex_journal} table that could not be re-indexed and sends
 * it back to the user as a CSV file. This way users can keep track of them
 * and check the logs to get more information about the failure.
 * // w  w  w . j a v  a  2 s  .  co  m
 * @param response
 *            - The {@link HttpServletResponse} object that allows to send
 *            the CSV file to the user.
 */
private void downloadRemainingRecordsAsCsv(HttpServletResponse response) {
    String fileName = "failed_reindex_records" + new java.util.Date().getTime();
    String[] fileColumns = new String[] { "ID", "Identifier To Index", "Inode To Index", "Priority" };
    PrintWriter pr = null;
    try {
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".csv\"");
        pr = response.getWriter();
        pr.print(StringUtils.join(fileColumns, ","));
        pr.print("\r\n");
        DotConnect dc = new DotConnect();
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT drj.id, drj.ident_to_index, drj.inode_to_index, drj.priority ")
                .append("FROM dist_reindex_journal drj WHERE drj.priority >= ")
                .append(DistributedJournalFactory.REINDEX_JOURNAL_PRIORITY_FAILED_FIRST_ATTEMPT);
        dc.setSQL(sql.toString());
        List<Map<String, Object>> failedRecords = dc.loadObjectResults();
        if (!failedRecords.isEmpty()) {
            for (Map<String, Object> row : failedRecords) {
                StringBuilder entry = new StringBuilder();
                String id = null;
                String priority = null;
                if (DbConnectionFactory.isOracle()) {
                    BigDecimal rowVal = (BigDecimal) row.get("id");
                    id = new Long(rowVal.toPlainString()).toString();
                    rowVal = (BigDecimal) row.get("priority");
                    priority = new Long(rowVal.toPlainString()).toString();
                } else {
                    Long rowVal = (Long) row.get("id");
                    id = rowVal.toString();
                    priority = String.valueOf((Integer) row.get("priority"));
                }
                entry.append(id).append(", ");
                entry.append(row.get("ident_to_index").toString()).append(", ");
                entry.append(row.get("inode_to_index").toString()).append(", ");
                entry.append(priority);
                pr.print(entry.toString());
                pr.print("\r\n");
            }
        } else {
            Logger.debug(this,
                    "Re-index table contained zero failed records. The CSV file will not be created.");
        }
    } catch (Exception e) {
        Logger.error(this, "Download of CSV file with remaining non-indexed records failed.", e);
    } finally {
        pr.flush();
        pr.close();
    }
}

From source file:au.org.ala.delta.editor.slotfile.directive.DirOutDefault.java

private void writeKeyStates(MutableDeltaDataSet dataSet, DirectiveArguments directiveArgs) {
    int prevNo;/*  w w w .j av  a  2  s  .c o  m*/
    int curNo;
    List<DirectiveArgument<?>> args;
    List<Integer> data;
    // The comparison function will sort all the key states, grouping
    // all those belonging to a single character, sorted in order by
    // there pseudo-value.
    args = directiveArgs.getDirectiveArguments();
    Collections.sort(args);
    prevNo = 0;
    for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) {
        au.org.ala.delta.model.Character charBase = dataSet.getCharacter((Integer) vectIter.getId());
        CharacterType charType = charBase.getCharacterType();
        curNo = charBase.getCharacterId();
        if (curNo != prevNo) {
            _textBuffer.append(" ").append(curNo).append(",");
            prevNo = curNo;
        } else
            _textBuffer.append('/');

        switch (charType) {
        case UnorderedMultiState:
            data = vectIter.getDataList();
            Collections.sort(data);
            for (int j = 0; j < data.size(); j++) {
                if (j != 0)
                    _textBuffer.append('&');
                _textBuffer.append(data.get(j));
            }
            break;

        case OrderedMultiState:

        {
            data = vectIter.getDataList();
            int loState, hiState, aState;

            if (data.size() < 2)
                throw new RuntimeException("ED_INTERNAL_ERROR");
            aState = data.get(0);
            hiState = data.get(1);
            loState = Math.min(aState, hiState);
            hiState = Math.max(aState, hiState);
            _textBuffer.append(loState);
            if (hiState > loState) {
                _textBuffer.append('-');
                _textBuffer.append(hiState);
            }
        }
            break;

        case IntegerNumeric:
        case RealNumeric: {
            List<BigDecimal> bigDecimals = vectIter.getData();
            BigDecimal loNumb, hiNumb;
            if (bigDecimals.size() < 2)
                throw new RuntimeException("ED_INTERNAL_ERROR");
            loNumb = bigDecimals.get(0);
            hiNumb = bigDecimals.get(1);
            if (loNumb.floatValue() == -Float.MAX_VALUE)
                _textBuffer.append('~');
            else {
                _textBuffer.append(loNumb.toPlainString());
            }
            if (hiNumb.floatValue() == Float.MAX_VALUE)
                _textBuffer.append('~');
            else if (loNumb.compareTo(hiNumb) < 0) {
                if (!(loNumb.floatValue() == -Float.MAX_VALUE))
                    _textBuffer.append('-');

                _textBuffer.append(hiNumb.toPlainString());
            }
        }
            break;

        default:
            throw new RuntimeException("ED_INAPPROPRIATE_TYPE");
            // break;
        }
    }
}

From source file:org.finra.herd.service.impl.TagServiceImpl.java

/**
 * Validate an optional tag's search score multiplier value.
 *
 * @param searchScoreMultiplier the tag's search score multiplier value
 *///  w w w .ja va2  s  .  c  o  m
private void validateTagSearchScoreMultiplier(BigDecimal searchScoreMultiplier) {
    if (searchScoreMultiplier != null && searchScoreMultiplier.compareTo(BigDecimal.ZERO) < 0) {
        throw new IllegalArgumentException(String.format(
                "The searchScoreMultiplier can not have a negative value. searchScoreMultiplier=%s",
                searchScoreMultiplier.toPlainString()));
    }
}

From source file:de.betterform.xml.xforms.ui.AbstractFormControl.java

/**
 * convert a localized value into its XML Schema datatype representation. If the value given cannot be parsed with
 * the locale in betterForm context the default locale (US) will be used as fallback. This can be convenient for
 * user-agents that do not pass a localized value back.
 *
 * @param value the value to convert/*from w w  w .  j  ava  2 s.c  o  m*/
 * @return converted value that can be used to update instance data and match the Schema datatype lexical space
 * @throws java.text.ParseException in case the incoming string cannot be converted into a Schema datatype representation
 */
protected String delocaliseValue(String value) throws XFormsException, ParseException {
    if (value == null || value.equals("")) {
        return value;
    }
    if (Config.getInstance().getProperty(XFormsProcessorImpl.BETTERFORM_ENABLE_L10N).equals("true")) {
        Locale locale = (Locale) getModel().getContainer().getProcessor().getContext()
                .get(XFormsProcessorImpl.BETTERFORM_LOCALE);
        XFormsProcessorImpl processor = this.model.getContainer().getProcessor();

        if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":float")
                || processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":decimal")
                || processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":double")) {

            NumberFormat formatter = NumberFormat.getNumberInstance(locale);
            formatter.setMaximumFractionDigits(Double.SIZE);
            BigDecimal number;

            try {
                number = strictParse(value, locale);
            } catch (ParseException e) {
                LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale);
                return value;
            } catch (NumberFormatException nfe) {
                LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale);
                return value;
            } catch (InputMismatchException ime) {
                LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale);
                return value;
            }
            return number.toPlainString();
        } else if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":date")) {
            DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
            Date d = null;
            try {
                d = df.parse(value);
            } catch (ParseException e) {
                //try the default locale - else fail with ParseException
                df = new SimpleDateFormat("yyyy-MM-dd");
                df.setLenient(false);
                d = df.parse(value);
            }
            df = new SimpleDateFormat("yyyy-MM-dd");
            return df.format(d);
        } else if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":dateTime")) {
            String timezone = "";
            // int position = ;
            if (value.contains("GMT")) {
                timezone = value.substring(value.indexOf("GMT") + 3, value.length());
            } else if (value.contains("+")) {
                timezone = value.substring(value.indexOf("+"), value.length());

            } else if (value.contains("Z")) {
                timezone = "Z";
            }

            DateFormat sf = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
            Date d = null;
            try {
                d = sf.parse(value);
            } catch (ParseException e) {
                //try the default locale - else fail with ParseException
                sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                d = null;
                d = sf.parse(value);
            }
            sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            String converted = sf.format(d);
            if (!timezone.equals("")) {
                return converted + timezone;
            }
            return converted;
        }
    }
    return value;
}

From source file:com.heliumv.api.production.ProductionApi.java

@POST
@Path("/materialwithdrawal/")
@Consumes({ "application/json", "application/xml" })
public void bucheMaterialNachtraeglichVomLagerAb(@HeaderParam(ParamInHeader.TOKEN) String headerUserId,
        MaterialWithdrawalEntry materialEntry, @QueryParam("userId") String userId) {

    ArtikelDto itemDto = null;//from w ww.  ja v a  2  s. c om
    LagerDto lagerDto = null;

    try {
        if (materialEntry == null) {
            respondBadRequestValueMissing("materialwithdrawal");
            return;
        }

        if (StringHelper.isEmpty(materialEntry.getLotCnr())) {
            respondBadRequestValueMissing("lotCnr");
            return;
        }
        if (StringHelper.isEmpty(materialEntry.getItemCnr())) {
            respondBadRequestValueMissing("itemCnr");
            return;
        }
        if (materialEntry.getAmount() == null || materialEntry.getAmount().signum() == 0) {
            respondBadRequest("amount", "null/0");
            return;
        }

        if (connectClient(headerUserId, userId) == null)
            return;
        //         if(!judgeCall.hasFertLosCUD()) {
        if (!mandantCall.hasModulLos()) {
            respondNotFound();
            return;
        }

        if (!fertigungCall.darfGebeMaterialNachtraeglichAus()) {
            respondUnauthorized();
            return;
        }

        LosDto losDto = findLosByCnr(materialEntry.getLotCnr());
        if (losDto == null) {
            respondNotFound("lotCnr", materialEntry.getLotCnr());
            return;
        }

        if (!isValidLosState(losDto))
            return;

        itemDto = findItemByCnr(materialEntry.getItemCnr());
        if (itemDto == null) {
            respondNotFound("itemCnr", materialEntry.getItemCnr());
            return;
        }

        MontageartDto montageartDto = getMontageart();
        if (montageartDto == null) {
            respondBadRequest("montageart", "no value defined");
            return;
        }

        lagerDto = getLager(materialEntry.getStockCnr(), materialEntry.getStockId());
        if (lagerDto == null) {
            return;
        }

        if (materialEntry.getAmount().signum() > 0) {
            MaterialRuecknahme ausgabe = new MaterialRuecknahme(losDto.getIId(), lagerDto.getIId(), itemDto);
            if (!ausgabe.verifyAmounts(materialEntry.getAmount(), materialEntry.getIdentities())) {
                return;
            }

            gebeMaterialNachtraeglichAus(lagerDto.getIId(), losDto, itemDto, montageartDto,
                    materialEntry.getAmount(), materialEntry.getIdentities());
        } else {
            BigDecimal amountToReturn = materialEntry.getAmount().abs();

            MaterialRuecknahme ruecknahme = new MaterialRuecknahme(losDto.getIId(), lagerDto.getIId(), itemDto);
            ruecknahme.setReturn(materialEntry.getReturn());
            if (!ruecknahme.verifyAmounts(amountToReturn, materialEntry.getIdentities())) {
                return;
            }

            BigDecimal amountNotReturned = ruecknahme.returnItem(amountToReturn, materialEntry.getIdentities(),
                    false);
            if (amountNotReturned.signum() == 0) {
                amountNotReturned = ruecknahme.returnItem(amountToReturn, materialEntry.getIdentities(), true);
            }

            if (amountNotReturned.signum() != 0) {
                respondBadRequest(EJBExceptionLP.FEHLER_ZUWENIG_AUF_LAGER);
                appendBadRequestData("stock-available",
                        amountToReturn.subtract(amountNotReturned).toPlainString());
            }
        }
    } catch (NamingException e) {
        respondUnavailable(e);
    } catch (RemoteException e) {
        respondUnavailable(e);
    } catch (EJBExceptionLP e) {
        respondBadRequest(e);
        if (e.getCode() == EJBExceptionLP.FEHLER_ZUWENIG_AUF_LAGER) {
            try {
                BigDecimal lagerStand = getLagerCall().getLagerstandOhneExc(itemDto.getIId(),
                        lagerDto.getIId());
                appendBadRequestData("stock-available", lagerStand.toPlainString());
            } catch (NamingException n) {
                respondUnavailable(n);
            } catch (RemoteException r) {
                respondUnavailable(r);
            }
        }
    }
}

From source file:org.jasig.ssp.service.impl.EvaluatedSuccessIndicatorServiceImpl.java

private List<String> normalizeForStringEvaluation(@Nullable Object forStringEval,
        @Nonnull SuccessIndicator successIndicator) throws IllegalArgumentException {
    if (forStringEval == null) {
        return Lists.newArrayListWithCapacity(0);
    }/*from w ww  . ja va  2  s .  co  m*/
    // TODO fix excessive List creation
    Iterable<String> translated = null;
    if (forStringEval instanceof Boolean) {
        translated = Lists.newArrayList(translateForStringEvaluation((Boolean) forStringEval));
    } else if (forStringEval instanceof Ratio) {
        final BigDecimal divided = ((Ratio) forStringEval).ratio();
        translated = Lists.newArrayList(divided.toPlainString());
    } else if (forStringEval instanceof BigDecimal) {
        translated = Lists.newArrayList(((BigDecimal) forStringEval).toPlainString());
    } else {
        // Otherwise skipping any sort of numeric value formatting b/c it's hard to know what sort of formatting and
        // scale people might want e.g. should we *always* format to some number of decimal points, even for int types?
        // In reality you shouldnt be using string matching for numeric metrics so whatever we do here really isn't all
        // that important, but at least this way you don't have to memorize any rules about how metric values are
        // normalized before comparison other than that they're trimmed, canonicalized to lower case, and split on
        // commas.
        //
        // Fully expect this to become more sophisticated in the future, where the SuccessIndicator specifies how
        // the metric should be normalized, e.g. to turn all the behaviors listed above on/off.

        // Thanks in part to http://eclipsesource.com/blogs/2012/07/26/having-fun-with-guavas-string-helpers/
        translated = Splitter.on(",").omitEmptyStrings().trimResults().split(forStringEval.toString());
    }
    return normalizeCasingForStringEvaluation(translated);
}

From source file:org.yes.cart.payment.impl.PayPalProPaymentGatewayImpl.java

private NvpBuilder createAuthRequest(final Payment payment, final String paymentAction) {
    final NvpBuilder npvs = new NvpBuilder();
    npvs.addRaw("PAYMENTACTION", paymentAction);
    npvs.addRaw("INVNUM", payment.getOrderShipment());
    npvs.addRaw("CREDITCARDTYPE", payment.getCardType());
    npvs.addRaw("ACCT", payment.getCardNumber());
    npvs.addRaw("EXPDATE", payment.getCardExpireMonth() + payment.getCardExpireYear());
    npvs.addRaw("CVV2", payment.getCardCvv2Code());

    npvs.addRaw("AMT", payment.getPaymentAmount().setScale(2, RoundingMode.HALF_UP).toString());
    npvs.addRaw("CURRENCYCODE", payment.getOrderCurrency());

    int i = 0;/* w  w  w .  j  a v a  2 s. c o  m*/

    BigDecimal itemsNetTotal = Total.ZERO;
    BigDecimal ship = Total.ZERO;

    for (final PaymentLine item : payment.getOrderItems()) {

        if (item.isShipment()) {

            ship = item.getUnitPrice();

        } else {

            final BigDecimal intQty = item.getQuantity().setScale(0, RoundingMode.CEILING);

            final String skuName;
            final BigDecimal qty;
            if (MoneyUtils.isFirstEqualToSecond(intQty, item.getQuantity())) {
                // integer qty
                skuName = item.getSkuName();
                qty = intQty.stripTrailingZeros();
            } else {
                // fractional qty
                skuName = item.getQuantity().toPlainString().concat("x ").concat(item.getSkuName());
                qty = BigDecimal.ONE;
            }

            npvs.addEncoded("L_NUMBER" + i,
                    item.getSkuCode().length() > ITEMSKU ? item.getSkuCode().substring(0, ITEMSKU - 1) + "~"
                            : item.getSkuCode());
            npvs.addEncoded("L_NAME" + i,
                    skuName.length() > ITEMNAME ? skuName.substring(0, ITEMNAME - 1) + "~" : skuName);

            npvs.addRaw("L_QTY" + i, qty.stripTrailingZeros().toPlainString());

            final BigDecimal itemNetAmount = item.getUnitPrice().multiply(item.getQuantity())
                    .subtract(item.getTaxAmount()).setScale(Total.ZERO.scale(), RoundingMode.HALF_UP);
            final BigDecimal itemNetPricePerAdjustedQty = itemNetAmount.divide(qty, Total.ZERO.scale(),
                    BigDecimal.ROUND_HALF_UP);
            // Need to do this to overcome rounding
            final BigDecimal restoredNetAmount = itemNetPricePerAdjustedQty.multiply(qty)
                    .setScale(Total.ZERO.scale(), BigDecimal.ROUND_HALF_UP);

            itemsNetTotal = itemsNetTotal.add(restoredNetAmount);
            //                final BigDecimal taxUnit = MoneyUtils.isFirstBiggerThanSecond(item.getTaxAmount(), Total.ZERO) ? item.getTaxAmount().divide(qty, Total.ZERO.scale(), BigDecimal.ROUND_HALF_UP) : Total.ZERO;

            npvs.addRaw("L_AMT" + i, itemNetPricePerAdjustedQty.toPlainString());

            //                npvs.addRaw("L_TAXAMT" + i, taxUnit.toPlainString());

            i++;
        }
    }

    final BigDecimal itemsAndShipping = itemsNetTotal.add(ship);
    final BigDecimal paymentNet = payment.getPaymentAmount().subtract(payment.getTaxAmount());
    if (MoneyUtils.isFirstBiggerThanSecond(itemsAndShipping, paymentNet)) {

        npvs.addRaw("SHIPDISCAMT", paymentNet.subtract(itemsAndShipping).toPlainString());

    }

    npvs.addRaw("ITEMAMT", itemsNetTotal.toPlainString());
    npvs.addRaw("SHIPPINGAMT", ship.toPlainString());
    npvs.addRaw("TAXAMT", payment.getTaxAmount().toPlainString());

    if (payment.getBillingAddress() != null) {
        npvs.addEncoded("EMAIL", payment.getBillingEmail());
        npvs.addEncoded("FIRSTNAME", payment.getBillingAddress().getFirstname());
        npvs.addEncoded("LASTNAME", payment.getBillingAddress().getLastname());
        npvs.addEncoded("STREET", payment.getBillingAddress().getAddrline1());
        if (StringUtils.isNotBlank(payment.getBillingAddress().getAddrline2())) {
            npvs.addEncoded("STREET2", payment.getBillingAddress().getAddrline2());
        }
        npvs.addEncoded("CITY", payment.getBillingAddress().getCity());
        npvs.addEncoded("STATE", payment.getBillingAddress().getStateCode());
        npvs.addEncoded("ZIP", payment.getBillingAddress().getStateCode());
        npvs.addEncoded("COUNTRYCODE", payment.getBillingAddress().getCountryCode());
    }

    if (payment.getShippingAddress() != null) {
        npvs.addEncoded("SHIPTONAME",
                payment.getShippingAddress().getFirstname() + " " + payment.getShippingAddress().getLastname());
        npvs.addEncoded("SHIPTOSTREET", payment.getShippingAddress().getAddrline1());
        if (StringUtils.isNotBlank(payment.getShippingAddress().getAddrline2())) {
            npvs.addEncoded("SHIPTOSTREET2", payment.getShippingAddress().getAddrline2());
        }
        npvs.addEncoded("SHIPTOCITY", payment.getShippingAddress().getCity());
        npvs.addEncoded("SHIPTOSTATE", payment.getShippingAddress().getStateCode());
        npvs.addEncoded("SHIPTOZIP", payment.getShippingAddress().getStateCode());
        npvs.addEncoded("SHIPTOCOUNTRY", payment.getShippingAddress().getCountryCode());
    }

    return npvs;
}