List of usage examples for java.math BigDecimal stripTrailingZeros
public BigDecimal stripTrailingZeros()
From source file:org.kuali.ole.module.purap.service.impl.PurapAccountingServiceImpl.java
/** * @see org.kuali.ole.module.purap.service.PurapAccountingService#generateAccountDistributionForProration(java.util.List, * org.kuali.rice.kns.util.KualiDecimal, java.lang.Integer) */// w ww. j av a 2s .c o m @Override public List<PurApAccountingLine> generateAccountDistributionForProration(List<SourceAccountingLine> accounts, KualiDecimal totalAmount, Integer percentScale, Class clazz) { String methodName = "generateAccountDistributionForProration()"; if (LOG.isDebugEnabled()) { LOG.debug(methodName + " started"); } List<PurApAccountingLine> newAccounts = new ArrayList(); if (totalAmount.isZero()) { throwRuntimeException(methodName, "Purchasing/Accounts Payable account distribution for proration does not allow zero dollar total."); } BigDecimal percentTotal = BigDecimal.ZERO; BigDecimal totalAmountBigDecimal = totalAmount.bigDecimalValue(); for (SourceAccountingLine accountingLine : accounts) { KualiDecimal amt = KualiDecimal.ZERO; if (ObjectUtils.isNotNull(accountingLine.getAmount())) { amt = accountingLine.getAmount(); } if (LOG.isDebugEnabled()) { LOG.debug(methodName + " " + accountingLine.getAccountNumber() + " " + amt + "/" + totalAmountBigDecimal); } BigDecimal pct = amt.bigDecimalValue().divide(totalAmountBigDecimal, percentScale, BIG_DECIMAL_ROUNDING_MODE); pct = pct.stripTrailingZeros().multiply(ONE_HUNDRED); if (LOG.isDebugEnabled()) { LOG.debug(methodName + " pct = " + pct + " (trailing zeros removed)"); } BigDecimal lowestPossible = this.getLowestPossibleRoundUpNumber(); if (lowestPossible.compareTo(pct) <= 0) { PurApAccountingLine newAccountingLine; newAccountingLine = null; try { newAccountingLine = (PurApAccountingLine) clazz.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } PurApObjectUtils.populateFromBaseClass(AccountingLineBase.class, accountingLine, newAccountingLine); newAccountingLine.setAccountLinePercent(pct); if (LOG.isDebugEnabled()) { LOG.debug(methodName + " adding " + newAccountingLine.getAccountLinePercent()); } newAccounts.add(newAccountingLine); percentTotal = percentTotal.add(newAccountingLine.getAccountLinePercent()); if (LOG.isDebugEnabled()) { LOG.debug(methodName + " total = " + percentTotal); } } } if ((percentTotal.compareTo(BigDecimal.ZERO)) == 0) { /* * This means there are so many accounts or so strange a distribution that we can't round properly... not sure of viable * solution */ throwRuntimeException(methodName, "Can't round properly due to number of accounts"); } // Now deal with rounding if ((ONE_HUNDRED.compareTo(percentTotal)) < 0) { /* * The total percent is greater than one hundred Here we find the account that occurs latest in our list with a percent * that is higher than the difference and we subtract off the difference */ BigDecimal difference = percentTotal.subtract(ONE_HUNDRED); if (LOG.isDebugEnabled()) { LOG.debug(methodName + " Rounding up by " + difference); } boolean foundAccountToUse = false; int currentNbr = newAccounts.size() - 1; while (currentNbr >= 0) { PurApAccountingLine potentialSlushAccount = newAccounts.get(currentNbr); BigDecimal linePercent = BigDecimal.ZERO; if (ObjectUtils.isNotNull(potentialSlushAccount.getAccountLinePercent())) { linePercent = potentialSlushAccount.getAccountLinePercent(); } if ((difference.compareTo(linePercent)) < 0) { // the difference amount is less than the current accounts percent... use this account // the 'potentialSlushAccount' technically is now the true 'Slush Account' potentialSlushAccount.setAccountLinePercent(linePercent.subtract(difference).movePointLeft(2) .stripTrailingZeros().movePointRight(2)); foundAccountToUse = true; break; } currentNbr--; } if (!foundAccountToUse) { /* * We could not find any account in our list where the percent of that account was greater than that of the * difference... doing so on just any account could result in a negative percent value */ throwRuntimeException(methodName, "Can't round properly due to math calculation error"); } } else if ((ONE_HUNDRED.compareTo(percentTotal)) > 0) { /* * The total percent is less than one hundred Here we find the last account in our list and add the remaining required * percent to its already calculated percent */ BigDecimal difference = ONE_HUNDRED.subtract(percentTotal); if (LOG.isDebugEnabled()) { LOG.debug(methodName + " Rounding down by " + difference); } PurApAccountingLine slushAccount = newAccounts.get(newAccounts.size() - 1); BigDecimal slushLinePercent = BigDecimal.ZERO; if (ObjectUtils.isNotNull(slushAccount.getAccountLinePercent())) { slushLinePercent = slushAccount.getAccountLinePercent(); } slushAccount.setAccountLinePercent( slushLinePercent.add(difference).movePointLeft(2).stripTrailingZeros().movePointRight(2)); } if (LOG.isDebugEnabled()) { LOG.debug(methodName + " ended"); } return newAccounts; }
From source file:org.marketcetera.trade.Option.java
/** * Constructor. Note that trailing zeros are stripped from strikePrice. * /*from ww w. j ava 2 s . com*/ * @param symbol * the option root symbol * @param expiry * the option expiry * @param strikePrice * the option strike price * @param type * the option type * @throws IllegalArgumentException * if any argument is null, or if symbol or expiry is whitespace */ public Option(String symbol, String expiry, BigDecimal strikePrice, OptionType type) { symbol = StringUtils.trimToNull(symbol); expiry = StringUtils.trimToNull(expiry); Validate.notNull(symbol); Validate.notNull(type); Validate.notNull(expiry); Validate.notNull(strikePrice); mSymbol = symbol; mType = type; mExpiry = expiry; mAugmentedExpiry = OptionUtils.normalizeEquityOptionExpiry(mExpiry); strikePrice = strikePrice.stripTrailingZeros(); if (strikePrice.scale() < 0) { //reset the scale if the number is a multiple of 10 strikePrice = strikePrice.setScale(0); } mStrikePrice = strikePrice; }
From source file:org.moqui.impl.entity.EntityJavaUtil.java
public static Object convertFromString(String value, FieldInfo fi, L10nFacade l10n) { Object outValue;/*from w w w .ja v a 2s .co m*/ boolean isEmpty = value.length() == 0; try { switch (fi.typeValue) { case 1: outValue = value; break; case 2: // outValue = java.sql.Timestamp.valueOf(value); if (isEmpty) { outValue = null; break; } outValue = l10n.parseTimestamp(value, null); if (outValue == null) throw new BaseException("The value [" + value + "] is not a valid date/time for field " + fi.entityName + "." + fi.name); break; case 3: // outValue = java.sql.Time.valueOf(value); if (isEmpty) { outValue = null; break; } outValue = l10n.parseTime(value, null); if (outValue == null) throw new BaseException("The value [" + value + "] is not a valid time for field " + fi.entityName + "." + fi.name); break; case 4: // outValue = java.sql.Date.valueOf(value); if (isEmpty) { outValue = null; break; } outValue = l10n.parseDate(value, null); if (outValue == null) throw new BaseException("The value [" + value + "] is not a valid date for field " + fi.entityName + "." + fi.name); break; case 5: // outValue = Integer.valueOf(value); break case 6: // outValue = Long.valueOf(value); break case 7: // outValue = Float.valueOf(value); break case 8: // outValue = Double.valueOf(value); break case 9: // outValue = new BigDecimal(value); break if (isEmpty) { outValue = null; break; } BigDecimal bdVal = l10n.parseNumber(value, null); if (bdVal == null) { throw new BaseException("The value [" + value + "] is not valid for type [" + fi.javaType + "] for field " + fi.entityName + "." + fi.name); } else { bdVal = bdVal.stripTrailingZeros(); switch (fi.typeValue) { case 5: outValue = bdVal.intValue(); break; case 6: outValue = bdVal.longValue(); break; case 7: outValue = bdVal.floatValue(); break; case 8: outValue = bdVal.doubleValue(); break; default: outValue = bdVal; break; } } break; case 10: if (isEmpty) { outValue = null; break; } outValue = Boolean.valueOf(value); break; case 11: outValue = value; break; case 12: try { outValue = new SerialBlob(value.getBytes()); } catch (SQLException e) { throw new BaseException("Error creating SerialBlob for value [" + value + "] for field " + fi.entityName + "." + fi.name); } break; case 13: outValue = value; break; case 14: if (isEmpty) { outValue = null; break; } Timestamp ts = l10n.parseTimestamp(value, null); outValue = new java.util.Date(ts.getTime()); break; // better way for Collection (15)? maybe parse comma separated, but probably doesn't make sense in the first place case 15: outValue = value; break; default: outValue = value; break; } } catch (IllegalArgumentException e) { throw new BaseException("The value [" + value + "] is not valid for type [" + fi.javaType + "] for field " + fi.entityName + "." + fi.name, e); } return outValue; }
From source file:org.moqui.impl.entity.EntityJavaUtil.java
public static Object getResultSetValue(ResultSet rs, int index, FieldInfo fi, EntityFacade efi) throws EntityException { if (fi.typeValue == -1) throw new EntityException("No typeValue found for " + fi.entityName + "." + fi.name); Object value = null;//from w ww. j a v a2s. c o m try { switch (fi.typeValue) { case 1: // getMetaData and the column type are somewhat slow (based on profiling), and String values are VERY // common, so only do for text-very-long if (fi.isTextVeryLong) { ResultSetMetaData rsmd = rs.getMetaData(); if (Types.CLOB == rsmd.getColumnType(index)) { // if the String is empty, try to get a text input stream, this is required for some databases // for larger fields, like CLOBs Clob valueClob = rs.getClob(index); Reader valueReader = null; if (valueClob != null) valueReader = valueClob.getCharacterStream(); if (valueReader != null) { // read up to 4096 at a time char[] inCharBuffer = new char[4096]; StringBuilder strBuf = new StringBuilder(); try { int charsRead; while ((charsRead = valueReader.read(inCharBuffer, 0, 4096)) > 0) { strBuf.append(inCharBuffer, 0, charsRead); } valueReader.close(); } catch (IOException e) { throw new EntityException("Error reading long character stream for field [" + fi.name + "] of entity [" + fi.entityName + "]", e); } value = strBuf.toString(); } } else { value = rs.getString(index); } } else { value = rs.getString(index); } break; case 2: try { value = rs.getTimestamp(index, efi.getCalendarForTzLc()); } catch (SQLException e) { if (logger.isTraceEnabled()) logger.trace( "Ignoring SQLException for getTimestamp(), leaving null (found this in MySQL with a date/time value of [0000-00-00 00:00:00]): " + e.toString()); } break; case 3: value = rs.getTime(index, efi.getCalendarForTzLc()); break; case 4: value = rs.getDate(index, efi.getCalendarForTzLc()); break; case 5: int intValue = rs.getInt(index); if (!rs.wasNull()) value = intValue; break; case 6: long longValue = rs.getLong(index); if (!rs.wasNull()) value = longValue; break; case 7: float floatValue = rs.getFloat(index); if (!rs.wasNull()) value = floatValue; break; case 8: double doubleValue = rs.getDouble(index); if (!rs.wasNull()) value = doubleValue; break; case 9: BigDecimal bigDecimalValue = rs.getBigDecimal(index); if (!rs.wasNull()) value = bigDecimalValue != null ? bigDecimalValue.stripTrailingZeros() : null; break; case 10: boolean booleanValue = rs.getBoolean(index); if (!rs.wasNull()) value = booleanValue; break; case 11: Object obj = null; byte[] originalBytes = rs.getBytes(index); InputStream binaryInput = null; if (originalBytes != null && originalBytes.length > 0) { binaryInput = new ByteArrayInputStream(originalBytes); } if (originalBytes != null && originalBytes.length <= 0) { logger.warn("Got byte array back empty for serialized Object with length [" + originalBytes.length + "] for field [" + fi.name + "] (" + index + ")"); } if (binaryInput != null) { ObjectInputStream inStream = null; try { inStream = new ObjectInputStream(binaryInput); obj = inStream.readObject(); } catch (IOException ex) { if (logger.isTraceEnabled()) logger.trace("Unable to read BLOB from input stream for field [" + fi.name + "] (" + index + "): " + ex.toString()); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) logger.trace("Class not found: Unable to cast BLOB data to an Java object for field [" + fi.name + "] (" + index + "); most likely because it is a straight byte[], so just using the raw bytes: " + ex.toString()); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { throw new EntityException("Unable to close binary input stream for field [" + fi.name + "] (" + index + "): " + e.toString(), e); } } } } if (obj != null) { value = obj; } else { value = originalBytes; } break; case 12: SerialBlob sblob = null; try { // NOTE: changed to try getBytes first because Derby blows up on getBlob and on then calling getBytes for the same field, complains about getting value twice byte[] fieldBytes = rs.getBytes(index); if (!rs.wasNull()) sblob = new SerialBlob(fieldBytes); // fieldBytes = theBlob != null ? theBlob.getBytes(1, (int) theBlob.length()) : null } catch (SQLException e) { if (logger.isTraceEnabled()) logger.trace("Ignoring exception trying getBytes(), trying getBlob(): " + e.toString()); Blob theBlob = rs.getBlob(index); if (!rs.wasNull()) sblob = new SerialBlob(theBlob); } value = sblob; break; case 13: value = new SerialClob(rs.getClob(index)); break; case 14: case 15: value = rs.getObject(index); break; } } catch (SQLException sqle) { logger.error("SQL Exception while getting value for field: [" + fi.name + "] (" + index + ")", sqle); throw new EntityException( "SQL Exception while getting value for field: [" + fi.name + "] (" + index + ")", sqle); } return value; }
From source file:org.multibit.utils.CSMiscUtils.java
public static BigDecimal getDisplayUnitsForRawUnits(CSAsset asset, BigInteger rawQuantity) { if (asset == null) return BigDecimal.ZERO; CoinSparkGenesis genesis = asset.getGenesis(); if (genesis == null) return BigDecimal.ZERO; // This can happen with brand new Manually transferred asset which has not yet been validated. int chargeBasisPoints = genesis.getChargeBasisPoints(); int chargeExponent = genesis.getChargeFlatExponent(); int chargeMantissa = genesis.getChargeFlatMantissa(); int qtyExponent = genesis.getQtyExponent(); int qtyMantissa = genesis.getQtyMantissa(); double interestRate = asset.getInterestRate(); Date issueDate = asset.getIssueDate(); BigDecimal result = new BigDecimal(rawQuantity.toString()); //System.out.println("interest rate = " + interestRate); //System.out.println("issue date = " + issueDate); //System.out.println("raw units =" + result); // 1. Compute interest if (issueDate != null && interestRate != 0.0) { BigDecimal rate = new BigDecimal(String.valueOf(interestRate)); rate = rate.divide(new BigDecimal(100)); rate = rate.add(BigDecimal.ONE); //interestRate = interestRate / 100; //System.out.println("interest rate 1 + ir/100 = " + rate.toPlainString()); // get years elapsed DateTime d1 = new DateTime(issueDate); DateTime d2 = new DateTime(); //System.out.println("Issue: " + d1 + " Now: " + d2); int seconds = Math.abs(Seconds.secondsBetween(d1, d2).getSeconds()); //System.out.println("...Number of seconds difference: " + seconds); BigDecimal elapsedSeconds = new BigDecimal(seconds); //System.out.println("...Number of seconds difference: " + elapsedSeconds.toPlainString()); // To avoid exception, we need to set a precision. // java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. // http://stackoverflow.com/questions/4591206/arithmeticexception-non-terminating-decimal-expansion-no-exact-representable BigDecimal elapsedYears = elapsedSeconds.divide(new BigDecimal(COINSPARK_SECONDS_IN_YEAR), MathContext.DECIMAL32); //System.out.println("...Number of years difference: " + elapsedYears.toPlainString()); double base = elapsedSeconds.doubleValue(); double exp = elapsedYears.doubleValue(); //System.out.println("...base=" + base + " exponent=" + exp); double interestMultipler = Math.pow(rate.doubleValue(), elapsedYears.doubleValue()); //System.out.println("interest multipler =" + interestMultipler); result = result.multiply(new BigDecimal(interestMultipler)); //System.out.println("raw units with interest multiplier =" + result); result = result.setScale(0, RoundingMode.DOWN); //System.out.println("raw units with interest multiplier, floored =" + result); }// ww w. j av a 2 s.co m // 2. Apply multiple int decimalPlaces = CSMiscUtils.getNumberOfDisplayDecimalPlaces(asset); BigDecimal display = result; if (decimalPlaces != 0) { // System.out.println(">>>>> display = " + display.toPlainString()); display = result.movePointLeft(decimalPlaces); // System.out.println(">>>>> display = " + display.toPlainString()); } //long qty = Utils.mantissaExponentToQty(qtyMantissa, qtyExponent); // double multiple = asset.getMultiple(); // let's just do it for now to make sure code is corret //if (multiple != 1.0) // BigDecimal m = new BigDecimal(String.valueOf(multiple)); // BigDecimal display = result.multiply(m); //System.out.println("multiplier=" + m + ", display=" + display); // Stripping zeros from internal zero with different scale does not work, so use // JDK bug still seems to exist // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6480539 // http://stackoverflow.com/questions/5239137/clarification-on-behavior-of-bigdecimal-striptrailingzeroes int cmpZeroResult = display.compareTo(BigDecimal.ZERO); if (decimalPlaces == 0) { display = display.stripTrailingZeros(); } // Stripping trailing zeros from internal zero with different scale does not work, so set to ZERO instead. if (0 == cmpZeroResult) { display = BigDecimal.ZERO; } return display; }
From source file:org.multibit.utils.CSMiscUtils.java
public static BigInteger getRawUnitsFromDisplayString(CSAsset asset, String display) { BigDecimal result = null; try {//from ww w . j a v a2s.co m //System.out.println("Start to get raw units from: " + display); result = new BigDecimal(display); } catch (NumberFormatException nfe) { nfe.printStackTrace(); return null; } // Reverse apply the multiple int decimalPlaces = CSMiscUtils.getNumberOfDisplayDecimalPlaces(asset); if (decimalPlaces != 0) { result = result.movePointRight(decimalPlaces); } // FIXME: what if multiple is 0.0? ignore? error? // double multiple = asset.getMultiple(); // BigDecimal m = new BigDecimal(String.valueOf(multiple)); // result = result.divide(m, MathContext.DECIMAL32); //System.out.println("multiplier=" + m + ", removed multiplier =" + display); double interestRate = asset.getInterestRate(); BigDecimal rate = new BigDecimal(String.valueOf(interestRate)); rate = rate.divide(new BigDecimal(100)); rate = rate.add(BigDecimal.ONE); Date issueDate = asset.getIssueDate(); DateTime d1 = new DateTime(issueDate); DateTime d2 = new DateTime(); int seconds = Math.abs(Seconds.secondsBetween(d1, d2).getSeconds()); //System.out.println("...Number of seconds difference: " + seconds); BigDecimal elapsedSeconds = new BigDecimal(seconds); BigDecimal elapsedYears = elapsedSeconds.divide(new BigDecimal(COINSPARK_SECONDS_IN_YEAR), MathContext.DECIMAL32); //System.out.println("...Number of years difference: " + elapsedYears.toPlainString()); double base = elapsedSeconds.doubleValue(); double exp = elapsedYears.doubleValue(); //System.out.println("...base=" + base + " exponent=" + exp); double interestMultipler = Math.pow(rate.doubleValue(), elapsedYears.doubleValue()); //System.out.println("interest multipler =" + interestMultipler); result = result.divide(new BigDecimal(String.valueOf(interestMultipler)), MathContext.DECIMAL32); //System.out.println("result = " + result.toPlainString()); result = result.setScale(0, RoundingMode.DOWN); result = result.stripTrailingZeros(); //System.out.println("result floored = " + result.toPlainString()); String resultString = result.toPlainString(); return new BigInteger(resultString); }
From source file:org.multibit.utils.CSMiscUtils.java
public static int getNumberOfDecimalPlaces(BigDecimal bigDecimal) { String string = bigDecimal.stripTrailingZeros().toPlainString(); int index = string.indexOf("."); return index < 0 ? 0 : string.length() - index - 1; }
From source file:org.multibit.viewsystem.swing.action.SendAssetConfirmAction.java
/** * Complete the transaction to work out the fee) and then show the send bitcoin confirm dialog. *//*from w ww . j a va 2 s .c o m*/ @Override public void actionPerformed(ActionEvent e) { if (abort()) { return; } // SendAssetConfirmDialog sendAssetConfirmDialog = null; AssetValidationErrorDialog validationErrorDialog = null; try { String sendAddress = dataProvider.getAddress(); String sendAmount = Utils.bitcoinValueToPlainString(BitcoinModel.COINSPARK_SEND_MINIMUM_AMOUNT); String sendMessage = null; boolean canSendMessage = false; final int assetId = dataProvider.getAssetId(); String assetAmount = dataProvider.getAssetAmount(); boolean isSenderPays = dataProvider.isSenderPays(); /* Is there a payment charge? If yes, the asset amount will change */ CSAsset asset = bitcoinController.getModel().getActiveWallet().CS.getAsset(assetId); CoinSparkGenesis genesis = asset.getGenesis(); BigInteger assetAmountRawUnits = CSMiscUtils.getRawUnitsFromDisplayString(asset, assetAmount); // Was there any rounding, which the user did not see because they clicked on send first, // without losing focus to any other widget which corrects field? String typedAmount = dataProvider.getAssetAmountText(); BigDecimal bd1 = new BigDecimal(typedAmount); BigDecimal bd2 = new BigDecimal(assetAmount); bd1 = bd1.stripTrailingZeros(); bd2 = bd2.stripTrailingZeros(); if (bd1.equals(bd2) == false) { String displayUnit = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, BigInteger.ONE); String s = "The smallest transactable unit is " + displayUnit + ", so we have rounded the sum down.\nPlease confirm the final amount and click 'Send' again."; JOptionPane.showMessageDialog(mainFrame, s); return; } // End rounding check/warning long desiredRawUnits = assetAmountRawUnits.longValue(); short chargeBasisPoints = genesis.getChargeBasisPoints(); long rawFlatChargeAmount = genesis.getChargeFlat(); boolean chargeExists = (rawFlatChargeAmount > 0 || chargeBasisPoints > 0); if (chargeExists) { if (isSenderPays) { long x = genesis.calcGross(desiredRawUnits); assetAmountRawUnits = new BigInteger(String.valueOf(x)); } else { // We don't have to do anything if recipient pays, just send gross amount. // calcNet() returns what the recipient will receive, but it's not what we send. // long x = genesis.calcNet(desiredRawUnits); // assetAmountRawUnits = new BigInteger(String.valueOf(x)); } } // Todo: Allow invalid assets to be sent even if spendable balance is 0 //if (CSMiscUtils.canSendInvalidAsset(bitcoinController) final AssetValidator validator = new AssetValidator(super.bitcoinController); if (validator.validate(sendAddress, sendAmount, assetId, assetAmountRawUnits.toString())) { /* CoinSpark START */ CoinSparkPaymentRef paymentRef = null; // We have already validated that the coinspark address and underlying bitcoin are good // and that the transfer flag is set on the coinspark address. We just want the actual // underlying bitcoin address to send assets to, which is used to create SendRequest object. CoinSparkAddress csa = CSMiscUtils.decodeCoinSparkAddress(sendAddress); String btcAddress = CSMiscUtils.getBitcoinAddressStringFromCoinSparkAddress(csa); sendAddress = btcAddress; // Does a payment ref exist? int flags = csa.getAddressFlags(); if ((flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_PAYMENT_REFS) > 0) { paymentRef = csa.getPaymentRef(); log.debug(">>>> CoinSpark address has payment refs flag set: " + paymentRef.toString()); } // Messages - can send message and BTC to CoinSpark address, without any assets. sendMessage = dataProvider.getMessage(); canSendMessage = (flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_TEXT_MESSAGES) > 0; /* CoinSpark END */ // Create a SendRequest. Address sendAddressObject; sendAddressObject = new Address(bitcoinController.getModel().getNetworkParameters(), sendAddress); //SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount)); //public static SendRequest to(Address destination,BigInteger value,int assetID, BigInteger assetValue,int split) { //BigInteger assetAmountRawUnits = new BigInteger(assetAmount); BigInteger bitcoinAmountSatoshis = Utils.toNanoCoins(sendAmount); final SendRequest sendRequest = SendRequest.to(sendAddressObject, bitcoinAmountSatoshis, assetId, assetAmountRawUnits, 1); sendRequest.ensureMinRequiredFee = true; sendRequest.fee = BigInteger.ZERO; sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT; // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form. // Send with payment ref - if it exists and is not 0 which SparkBit treats semantically as null if (paymentRef != null && paymentRef.getRef() != 0) { sendRequest.setPaymentRef(paymentRef); } // Send a message if the address will take it and message is not empty boolean willSendMessage = false; if (canSendMessage) { boolean isEmptyMessage = false; if (sendMessage == null || sendMessage.isEmpty() || sendMessage.trim().length() == 0) { isEmptyMessage = true; } if (!isEmptyMessage) { willSendMessage = true; //int numParts = 1; CoinSparkMessagePart[] parts = { CSMiscUtils.createPlainTextCoinSparkMessagePart(sendMessage) }; String[] serverURLs = CSMiscUtils.getMessageDeliveryServersArray(bitcoinController); sendRequest.setMessage(parts, serverURLs); log.debug(">>>> Messaging servers = " + ArrayUtils.toString(serverURLs)); log.debug(">>>> parts[0] = " + parts[0]); log.debug(">>>> parts[0].fileName = " + parts[0].fileName); log.debug(">>>> parts[0].mimeType = " + parts[0].mimeType); log.debug(">>>> parts[0].content = " + new String(parts[0].content, "UTF-8")); //String message = "Hello, the time is now..." + DateTime.now().toString(); // parts[2].fileName = imagePath; // parts[2].mimeType = "image/png"; // byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath)); // parts[2].content = imageBytes; } } // // When sending a message, show a modal dialog. // CompleteTX now occurs in background thread so UI does not block // when "Send" is clicked with widget updates frozen. // // Show dialog with indeterminate progress bar final JDialog dialog = CSMiscUtils.createModalMessageDialogWithIndeterminateProgress(mainFrame, "SparkBit", "Contacting message delivery servers..."); // Dialog is made visible after futures have been set up ListeningExecutorService service = MoreExecutors .listeningDecorator(Executors.newSingleThreadExecutor()); //newFixedThreadPool(10)); ListenableFuture<Boolean> future = service.submit(new Callable<Boolean>() { public Boolean call() throws Exception { try { // Complete it (which works out the fee) but do not sign it yet. log.debug("Just about to complete the tx (and calculate the fee)..."); bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false); log.debug("The fee after completing the transaction was " + sendRequest.fee); } catch (Exception e) { throw e; } return true; } }); final BigInteger myAssetAmountRawUnits = assetAmountRawUnits; Futures.addCallback(future, new FutureCallback<Boolean>() { public void onSuccess(Boolean b) { // There is enough money. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { dialog.dispose(); SendAssetConfirmDialog mySendAssetConfirmDialog = new SendAssetConfirmDialog( bitcoinController, mainFrame, sendRequest, assetId, myAssetAmountRawUnits, validator); mySendAssetConfirmDialog.setVisible(true); } }); } public void onFailure(Throwable thrown) { final String failureReason = thrown.getMessage(); final boolean isCSException = thrown instanceof org.coinspark.core.CSExceptions.CannotEncode; final boolean isInsufficientMoney = thrown instanceof com.google.bitcoin.core.InsufficientMoneyException; // There is not enough money. // TODO setup validation parameters accordingly so that it displays ok. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { dialog.dispose(); if (isCSException) { JOptionPane .showMessageDialog(mainFrame, "SparkBit is unable to proceed with this transaction:\n\n" + failureReason, "SparkBit Error", JOptionPane.ERROR_MESSAGE); } else if (isInsufficientMoney) { // Try to show a human friendly message, need to pass the missing satoshis from failure reason. try { String numberOnly = failureReason.replaceAll("[^0-9]", ""); BigInteger needed = new BigInteger(numberOnly); JOptionPane.showMessageDialog(mainFrame, "SparkBit is unable to proceed with this transaction.\n\nInsufficient money in wallet, require " + Utils.bitcoinValueToFriendlyString(needed) + " BTC more.", "SparkBit Error", JOptionPane.ERROR_MESSAGE); } catch (NumberFormatException e) { AssetValidationErrorDialog myValidationErrorDialog = new AssetValidationErrorDialog( bitcoinController, mainFrame, sendRequest, true, validator); myValidationErrorDialog.setVisible(true); } } else { AssetValidationErrorDialog myValidationErrorDialog = new AssetValidationErrorDialog( bitcoinController, mainFrame, sendRequest, true, validator); myValidationErrorDialog.setVisible(true); } } }); } }); // Show message server dialog only if we are going to send if (willSendMessage) { dialog.setVisible(true); } /* // Complete it (which works out the fee) but do not sign it yet. log.debug("Just about to complete the tx (and calculate the fee)..."); boolean completedOk; try { bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false); completedOk = true; log.debug("The fee after completing the transaction was " + sendRequest.fee); } catch (InsufficientMoneyException ime) { completedOk = false; } if (completedOk) { // There is enough money. sendAssetConfirmDialog = new SendAssetConfirmDialog(super.bitcoinController, mainFrame, sendRequest, assetId, assetAmountRawUnits, validator); sendAssetConfirmDialog.setVisible(true); } else { // There is not enough money. // TODO setup validation parameters accordingly so that it displays ok. validationErrorDialog = new AssetValidationErrorDialog(super.bitcoinController, mainFrame, sendRequest, true, validator); validationErrorDialog.setVisible(true); } */ } else { validationErrorDialog = new AssetValidationErrorDialog(super.bitcoinController, mainFrame, null, false, validator); validationErrorDialog.setVisible(true); } } catch (WrongNetworkException e1) { logMessage(e1); } catch (AddressFormatException e1) { logMessage(e1); } catch (KeyCrypterException e1) { logMessage(e1); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(mainFrame, "Please enter a valid amount."); } catch (Exception e1) { logMessage(e1); } }
From source file:org.projectforge.business.fibu.AbstractRechnungsPositionDO.java
public AbstractRechnungsPositionDO setVat(final BigDecimal vat) { if (vat != null) { this.vat = vat.stripTrailingZeros(); } else {/* w w w .j a v a2 s. c o m*/ this.vat = vat; } return this; }
From source file:org.talend.dataprep.transformation.actions.math.ExtractNumber.java
/** * @param value the value to parse./* w w w .j av a 2 s.co m*/ * @param defaultValue the value to return when no number can be extracted * @return the number extracted out of the given value. */ protected static String extractNumber(String value, String defaultValue) { // easy case if (StringUtils.isEmpty(value)) { return defaultValue; } // Test if the input value is a valid number before removing any characters: if (NumericHelper.isBigDecimal(value)) { // If yes (no exception thrown), return the value as it, no change required: return String.valueOf(BigDecimalParser.toBigDecimal(value)); } StringCharacterIterator iter = new StringCharacterIterator(value); MetricPrefix metricPrefixBefore = null, metricPrefixAfter = null; boolean numberFound = false; // we build a new value including only number or separator as , or . StringBuilder reducedValue = new StringBuilder(value.length()); for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) { // we remove all non numeric characters but keep separators if (NumberUtils.isNumber(String.valueOf(c)) || SEPARATORS.contains(c)) { reducedValue.append(c); numberFound = true; } else { // we take the first metric prefix found before and after a number found if (metricPrefixBefore == null) { MetricPrefix found = METRICPREFIXES.get(String.valueOf(c)); if (found != null && !numberFound) { metricPrefixBefore = found; } } if (metricPrefixAfter == null) { MetricPrefix found = METRICPREFIXES.get(String.valueOf(c)); if (found != null && numberFound) { metricPrefixAfter = found; } } } } if (!NumericHelper.isBigDecimal(reducedValue.toString())) { return defaultValue; } BigDecimal bigDecimal = BigDecimalParser.toBigDecimal(reducedValue.toString()); if (metricPrefixBefore != null || metricPrefixAfter != null) { // the metrix found after use first MetricPrefix metricPrefix = metricPrefixAfter != null ? metricPrefixAfter : metricPrefixBefore; bigDecimal = bigDecimal.multiply(metricPrefix.getMultiply()); } DecimalFormat decimalFormat = new DecimalFormat("0.#"); decimalFormat.setMaximumFractionDigits(MAX_FRACTION_DIGITS_DISPLAY); return decimalFormat.format(bigDecimal.stripTrailingZeros()); }