Example usage for java.math BigInteger compareTo

List of usage examples for java.math BigInteger compareTo

Introduction

In this page you can find the example usage for java.math BigInteger compareTo.

Prototype

public int compareTo(BigInteger val) 

Source Link

Document

Compares this BigInteger with the specified BigInteger.

Usage

From source file:com.google.bitcoin.core.Wallet.java

private boolean adjustOutputDownwardsForFee(Transaction tx, CoinSelection coinSelection, BigInteger baseFee,
        BigInteger feePerKb, BigInteger minFee) {
    TransactionOutput output = tx.getOutput(0);
    // Check if we need additional fee due to the transaction's size
    int size = tx.bitcoinSerialize().length;
    size += estimateBytesForSigning(coinSelection);
    BigInteger fee = baseFee.add(BigInteger.valueOf((size / 1000) + 1).multiply(feePerKb));
    if (fee.compareTo(minFee) < 0) {
        fee = minFee;//  ww  w. jav a  2s  .  c o m
    }
    output.setValue(output.getValue().subtract(fee));
    // Check if we need additional fee due to the output's value
    if (output.getValue().compareTo(Utils.CENT) < 0
            && fee.compareTo(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE) < 0) {
        output.setValue(output.getValue().subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.subtract(fee)));
    }
    return output.getMinNonDustValue().compareTo(output.getValue()) <= 0;
}

From source file:com.google.bitcoin.core.Wallet.java

/**
 * Calls {@link Wallet#commitTx} if tx is not already in the pending pool
 *
 * @return true if the tx was added to the wallet, or false if it was already in the pending pool
 *///w ww .  j  a v a 2 s  .c om
public boolean maybeCommitTx(Transaction tx) throws VerificationException {
    tx.verify();
    lock.lock();
    try {
        log.info("!!!! commit START!!! " + tx.getHashAsString());
        if (pending.containsKey(tx.getHash()))
            return false;
        log.info("commitTx of {}", tx.getHashAsString());
        BigInteger balance = getBalance();
        tx.setUpdateTime(Utils.now());
        // Mark the outputs we're spending as spent so we won't try and use them in future creations. This will also
        // move any transactions that are now fully spent to the spent map so we can skip them when creating future
        // spends.
        updateForSpends(tx, false);
        // Add to the pending pool. It'll be moved out once we receive this transaction on the best chain.
        // This also registers txConfidenceListener so wallet listeners get informed.
        log.info("->pending: {}", tx.getHashAsString());
        tx.getConfidence().setConfidenceType(ConfidenceType.PENDING);
        confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE);
        addWalletTransaction(Pool.PENDING, tx);

        /* CSPK-mike START */

        // Looking for assets in pending transaction
        CS.log.info("New tx " + tx.getHash().toString() + " in memory pool");

        log.info("!!!! commit HIT!!! " + tx.getHashAsString());
        CSTransactionAssets txAssets = new CSTransactionAssets(tx);
        txAssets.updateAssetBalances(this, 0, CS.getInputAssetBalances(tx));
        CS.addToRecentSends(tx);

        /* CSPK-mike END */

        try {
            BigInteger valueSentFromMe = tx.getValueSentFromMe(this);
            BigInteger valueSentToMe = tx.getValueSentToMe(this);
            BigInteger newBalance = balance.add(valueSentToMe).subtract(valueSentFromMe);
            if (valueSentToMe.compareTo(BigInteger.ZERO) > 0) {
                checkBalanceFuturesLocked(null);
                queueOnCoinsReceived(tx, balance, newBalance);
            }
            if (valueSentFromMe.compareTo(BigInteger.ZERO) > 0)
                queueOnCoinsSent(tx, balance, newBalance);

            maybeQueueOnWalletChanged();
        } catch (ScriptException e) {
            // Cannot happen as we just created this transaction ourselves.
            throw new RuntimeException(e);
        }

        checkState(isConsistent());
        informConfidenceListenersIfNotReorganizing();
        //saveNow();
    } finally {
        lock.unlock();
    }
    return true;
}

From source file:com.google.bitcoin.core.Wallet.java

/**
 * Given a spend request containing an incomplete transaction, makes it valid by adding outputs and signed inputs
 * according to the instructions in the request. The transaction in the request is modified by this method, as is
 * the fee parameter.//w ww.  j a  va2  s .c  om
 *
 * @param req a SendRequest that contains the incomplete transaction and details for how to make it valid.
 * @throws InsufficientMoneyException if the request could not be completed due to not enough balance.
 * @throws IllegalArgumentException if you try and complete the same SendRequest twice, or if the given send request
 *         cannot be completed without violating the protocol rules.
 */
public void completeTx(SendRequest req, boolean sign)
        throws InsufficientMoneyException, CSExceptions.CannotEncode {
    lock.lock();
    try {
        checkArgument(!req.completed, "Given SendRequest has already been completed.");
        // Calculate the amount of value we need to import.
        BigInteger value = BigInteger.ZERO;
        for (TransactionOutput output : req.tx.getOutputs()) {
            value = value.add(output.getValue());
        }
        BigInteger totalOutput = value;

        log.info("Completing send tx with {} outputs totalling {} satoshis (not including fees)",
                req.tx.getOutputs().size(), value);

        // If any inputs have already been added, we don't need to get their value from wallet
        BigInteger totalInput = BigInteger.ZERO;

        /* CSPK-mike START */
        /* Code commented out, input value is calculated after asset inputs were added            
                    for (TransactionInput input : req.tx.getInputs())
        if (input.getConnectedOutput() != null)
            totalInput = totalInput.add(input.getConnectedOutput().getValue());
        else
            log.warn("SendRequest transaction already has inputs but we don't know how much they are worth - they will be added to fee.");
                    value = value.subtract(totalInput);
        */
        /* CSPK-mike START */

        List<TransactionInput> originalInputs = new ArrayList<TransactionInput>(req.tx.getInputs());

        // We need to know if we need to add an additional fee because one of our values are smaller than 0.01 BTC
        boolean needAtLeastReferenceFee = false;
        if (req.ensureMinRequiredFee && !req.emptyWallet) { // min fee checking is handled later for emptyWallet
            for (TransactionOutput output : req.tx.getOutputs())
                if (output.getValue().compareTo(Utils.CENT) < 0) {
                    if (output.getValue().compareTo(output.getMinNonDustValue()) < 0)
                        throw new IllegalArgumentException(
                                "Tried to send dust with ensureMinRequiredFee set - no way to complete this");
                    needAtLeastReferenceFee = true;
                    break;
                }
        }

        // Calculate a list of ALL potential candidates for spending and then ask a coin selector to provide us
        // with the actual outputs that'll be used to gather the required amount of value. In this way, users
        // can customize coin selection policies.
        //
        // Note that this code is poorly optimized: the spend candidates only alter when transactions in the wallet
        // change - it could be pre-calculated and held in RAM, and this is probably an optimization worth doing.
        // Note that output.isMine(this) needs to test the keychain which is currently an array, so it's
        // O(candidate outputs ^ keychain.size())! There's lots of low hanging fruit here.
        LinkedList<TransactionOutput> candidates = calculateAllSpendCandidates(true);

        CoinSelection bestCoinSelection;
        TransactionOutput bestChangeOutput = null;
        if (!req.emptyWallet) {
            // This can throw InsufficientMoneyException.
            FeeCalculation feeCalculation;
            /* CSPK-mike START */
            //                feeCalculation = new FeeCalculation(req, value, originalInputs, needAtLeastReferenceFee, candidates);
            // Fee and inputs calculation

            /*               
                            CoinSparkMessagePart [] MessageParts=new CoinSparkMessagePart[1];
                            MessageParts[0]=new CoinSparkMessagePart();
                            MessageParts[0].mimeType="text/plain";
                            MessageParts[0].fileName=null;
                            MessageParts[0].content="Hello World!".getBytes();
                            String [] DeliveryServers=new String [] {"assets1.coinspark.org/","assets1.coinspark.org/abc"};//,"144.76.175.228/" };
                            req.setMessage(MessageParts, DeliveryServers);
                    
                            CoinSparkPaymentRef paymentRef=new CoinSparkPaymentRef(125);
                            req.setPaymentRef(paymentRef);
            */

            if (CS.createAssetTransfers(req, originalInputs, candidates)) {
                totalInput = BigInteger.ZERO;
                for (TransactionInput input : req.tx.getInputs()) {
                    if (input.getConnectedOutput() != null) {
                        totalInput = totalInput.add(input.getConnectedOutput().getValue());
                    } else {
                        log.warn(
                                "SendRequest transaction already has inputs but we don't know how much they are worth - they will be added to fee.");
                    }
                }
                value = totalOutput;
                value = value.subtract(totalInput);

                originalInputs = new ArrayList<TransactionInput>(req.tx.getInputs());
                // Coinspark transaction has to have change output even if there are no explicit transfers.
                feeCalculation = new FeeCalculation(req, value, originalInputs, needAtLeastReferenceFee,
                        candidates, Transaction.MIN_NONDUST_OUTPUT);
            } else {
                throw new InsufficientMoneyException.CouldNotAdjustDownwards();
            }

            /* CSPK-mike END */
            bestCoinSelection = feeCalculation.bestCoinSelection;
            bestChangeOutput = feeCalculation.bestChangeOutput;
        } else {
            // We're being asked to empty the wallet. What this means is ensuring "tx" has only a single output
            // of the total value we can currently spend as determined by the selector, and then subtracting the fee.
            checkState(req.tx.getOutputs().size() == 1, "Empty wallet TX must have a single output only.");
            CoinSelector selector = req.coinSelector == null ? coinSelector : req.coinSelector;
            bestCoinSelection = selector.select(NetworkParameters.MAX_MONEY, candidates);
            req.tx.getOutput(0).setValue(bestCoinSelection.valueGathered);

            totalOutput = bestCoinSelection.valueGathered;
        }

        for (TransactionOutput output : bestCoinSelection.gathered)
            req.tx.addInput(output);

        /* CSPK-mike START */
        if (!CS.preparePaymentRef(req)) {
            throw new CSExceptions.CannotEncode("Cannot prepare payment reference");
        }
        if (!CS.prepareMessage(req)) {
            throw new CSExceptions.CannotEncode("Cannot prepare message");
        }
        /* CSPK-mike END */

        if (req.ensureMinRequiredFee && req.emptyWallet) {
            final BigInteger baseFee = req.fee == null ? BigInteger.ZERO : req.fee;
            final BigInteger feePerKb = req.feePerKb == null ? BigInteger.ZERO : req.feePerKb;
            Transaction tx = req.tx;
            if (!adjustOutputDownwardsForFee(tx, bestCoinSelection, baseFee, feePerKb))
                throw new InsufficientMoneyException.CouldNotAdjustDownwards();
        }

        /* CSPK-mike START */
        // Input calculation for "Empty wallet" request
        if (req.emptyWallet) {
            Transaction tx = req.tx;
            TransactionOutput output = tx.getOutput(0);
            if (CS.createAssetTransfersForEmptyWallet(req,
                    output.getValue().subtract(output.getMinNonDustValue()))) {
                if (req.ensureMinRequiredFee) {
                    final BigInteger baseFee = req.fee == null ? BigInteger.ZERO : req.fee;
                    final BigInteger feePerKb = req.feePerKb == null ? BigInteger.ZERO : req.feePerKb;
                    totalOutput = bestCoinSelection.valueGathered;
                    output.setValue(totalOutput);
                    if (!adjustOutputDownwardsForFee(tx, bestCoinSelection, baseFee, feePerKb, req.assetFee)) {
                        CS.log.warning("Empty wallet: not enough bitcoins to transfer assets.");
                        tx.getOutputs().clear();
                        output.setValue(totalOutput);
                        tx.addOutput(output);
                        req.assetsEncoded = null;
                        req.assetFee = BigInteger.ZERO;
                        if (!adjustOutputDownwardsForFee(tx, bestCoinSelection, baseFee, feePerKb)) {
                            throw new InsufficientMoneyException.CouldNotAdjustDownwards();
                        }
                    }
                    totalOutput = output.getValue();
                    bestChangeOutput = null;
                }
            }
            totalOutput = output.getValue();
            bestChangeOutput = null;
        }
        /* CSPK-mike END */

        totalInput = totalInput.add(bestCoinSelection.valueGathered);

        if (bestChangeOutput != null) {
            req.tx.addOutput(bestChangeOutput);
            totalOutput = totalOutput.add(bestChangeOutput.getValue());
            log.info("  with {} coins change", bitcoinValueToFriendlyString(bestChangeOutput.getValue()));
        }
        final BigInteger calculatedFee = totalInput.subtract(totalOutput);
        if (calculatedFee.compareTo(BigInteger.ZERO) > 0) {
            log.info("  with a fee of {}", bitcoinValueToFriendlyString(calculatedFee));
        }

        // Now sign the inputs, thus proving that we are entitled to redeem the connected outputs.
        if (sign) {
            sign(req);
        }

        // Check size.
        int size = req.tx.bitcoinSerialize().length;
        if (size > Transaction.MAX_STANDARD_TX_SIZE) {
            throw new IllegalArgumentException(
                    String.format("Transaction could not be created without exceeding max size: %d vs %d", size,
                            Transaction.MAX_STANDARD_TX_SIZE));
        }

        // Label the transaction as being self created. We can use this later to spend its change output even before
        // the transaction is confirmed. We deliberately won't bother notifying listeners here as there's not much
        // point - the user isn't interested in a confidence transition they made themselves.
        req.tx.getConfidence().setSource(TransactionConfidence.Source.SELF);

        // Keep a track of the date the tx was created (used in MultiBitService
        // to work out the block it appears in).
        req.tx.setUpdateTime(new Date());

        // Label the transaction as being a user requested payment. This can be used to render GUI wallet
        // transaction lists more appropriately, especially when the wallet starts to generate transactions itself
        // for internal purposes.
        req.tx.setPurpose(Transaction.Purpose.USER_PAYMENT);
        req.completed = true;
        req.fee = calculatedFee;
        log.info("  completed: {}", req.tx);
    } finally {
        lock.unlock();
    }
}

From source file:com.google.bitcoin.core.Wallet.java

/** Reduce the value of the first output of a transaction to pay the given feePerKb as appropriate for its size. */
private boolean adjustOutputDownwardsForFee(Transaction tx, CoinSelection coinSelection, BigInteger baseFee,
        BigInteger feePerKb) {//from w w w  .j  av a 2  s.  c o m
    TransactionOutput output = tx.getOutput(0);
    // Check if we need additional fee due to the transaction's size
    int size = tx.bitcoinSerialize().length;
    size += estimateBytesForSigning(coinSelection);
    BigInteger fee = baseFee.add(BigInteger.valueOf((size / 1000) + 1).multiply(feePerKb));
    output.setValue(output.getValue().subtract(fee));
    // Check if we need additional fee due to the output's value
    if (output.getValue().compareTo(Utils.CENT) < 0
            && fee.compareTo(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE) < 0)
        output.setValue(output.getValue().subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.subtract(fee)));
    return output.getMinNonDustValue().compareTo(output.getValue()) <= 0;
}

From source file:com.google.bitcoin.core.Wallet.java

private void checkBalanceFuturesLocked(@Nullable BigInteger avail) {
    checkState(lock.isHeldByCurrentThread());
    BigInteger estimated = null;//ww w .  ja v  a2  s  . c  o m
    final ListIterator<BalanceFutureRequest> it = balanceFutureRequests.listIterator();
    while (it.hasNext()) {
        final BalanceFutureRequest req = it.next();
        BigInteger val = null;
        if (req.type == BalanceType.AVAILABLE) {
            if (avail == null)
                avail = getBalance(BalanceType.AVAILABLE);
            if (avail.compareTo(req.value) < 0)
                continue;
            val = avail;
        } else if (req.type == BalanceType.ESTIMATED) {
            if (estimated == null)
                estimated = getBalance(BalanceType.ESTIMATED);
            if (estimated.compareTo(req.value) < 0)
                continue;
            val = estimated;
        }
        // Found one that's finished.
        it.remove();
        final BigInteger v = checkNotNull(val);
        // Don't run any user-provided future listeners with our lock held.
        Threading.USER_THREAD.execute(new Runnable() {
            @Override
            public void run() {
                req.future.set(v);
            }
        });
    }
}

From source file:ca.oson.json.Oson.java

private <E, R> BigInteger json2BigIntegerDefault(FieldData objectDTO) {
    E value = (E) objectDTO.valueToProcess;
    Class<R> returnType = objectDTO.returnType;
    boolean required = objectDTO.required();

    Long min = objectDTO.getMin();
    Long max = objectDTO.getMax();

    if (getDefaultType() == JSON_INCLUDE.DEFAULT || required) {
        BigInteger defaultValue = (BigInteger) objectDTO.getDefaultValue();
        if (defaultValue != null) {
            if (min != null && min > defaultValue.longValue()) {
                return BigInteger.valueOf(min);
            }//from w  ww.  j a v a  2  s  .c  om

            if (max != null && defaultValue.compareTo(BigInteger.valueOf(max)) > 0) {
                return BigInteger.valueOf(max);
            }

            return defaultValue;
        }

        if (min != null && DefaultValue.bigInteger.compareTo(BigInteger.valueOf(min)) < 0) {
            return BigInteger.valueOf(min);
        }

        return DefaultValue.bigInteger;
    }

    return null;
}

From source file:com.google.bitcoin.core.Wallet.java

private void receive(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset)
        throws VerificationException {
    // Runs in a peer thread.
    checkState(lock.isHeldByCurrentThread());
    BigInteger prevBalance = getBalance();
    Sha256Hash txHash = tx.getHash();//from  w ww.  j  a  va2s .  com
    boolean bestChain = blockType == BlockChain.NewBlockType.BEST_CHAIN;
    boolean sideChain = blockType == BlockChain.NewBlockType.SIDE_CHAIN;

    BigInteger valueSentFromMe = tx.getValueSentFromMe(this);
    BigInteger valueSentToMe = tx.getValueSentToMe(this);
    BigInteger valueDifference = valueSentToMe.subtract(valueSentFromMe);

    log.info("!!!! receive START " + tx.getHashAsString());

    log.info("Received tx{} for {} BTC: {} [{}] in block {}", sideChain ? " on a side chain" : "",
            bitcoinValueToFriendlyString(valueDifference), tx.getHashAsString(), relativityOffset,
            block != null ? block.getHeader().getHash() : "(unit test)");

    /* CSPK-mike START */
    // Looking for CoinSpark assets in the transaction
    if (bestChain) {

        int blockHeight = 0;
        if (block != null) {
            blockHeight = block.getHeight();
            CS.log.info("New tx " + tx.getHash().toString() + " in block " + blockHeight);
        }
        log.info("!!!! receive HIT!!! " + tx.getHashAsString());

        CSTransactionAssets txAssets = new CSTransactionAssets(tx);
        txAssets.updateAssetBalances(this, blockHeight, CS.getInputAssetBalances(tx));

        /*
        Look for payment reference and post CSEvent if found
        */
        final int FBHCHAIN_START_BLOCK = 312500; // July 26th 2014
        // optimise, only check from period when assets were first being created
        if (blockHeight > FBHCHAIN_START_BLOCK) {
            log.info("!!!! Extracting CoinSpark payment reference from a transaction...");

            byte[] txnMetaData = null;
            //int metadataOutput=0;
            //int count=0;
            for (TransactionOutput output : tx.getOutputs()) {

                // TRANSACTION_PAYMENT_REFERENCE_DETECTED
                byte[] scriptBytes = output.getScriptBytes();
                if (!CoinSparkBase.scriptIsRegular(scriptBytes)) {
                    txnMetaData = CoinSparkBase.scriptToMetadata(scriptBytes);
                    break;
                }
            }

            if (txnMetaData != null) {
                CoinSparkPaymentRef paymentRef = new CoinSparkPaymentRef();
                if (paymentRef.decode(txnMetaData)) {
                    log.info("!!!! Found Payment Ref: " + paymentRef.toString());
                    HashMap<String, Long> map = new HashMap<String, Long>();
                    map.put(tx.getHashAsString(), paymentRef.getRef());
                    CSEventBus.INSTANCE.postAsyncEvent(CSEventType.TRANSACTION_PAYMENT_REFERENCE_RECEIVED, map);
                }
            }
        }
    }
    /* CSPK-mike END */

    // If the transaction is being replayed no need to add it to the wallet again.
    Transaction diagnosticTx = tx;
    if (spent.containsKey(txHash)) {
        diagnosticTx = spent.get(txHash);
    }
    if (unspent.containsKey(txHash)) {
        diagnosticTx = unspent.get(txHash);
    }

    if (dead.containsKey(txHash)) {
        diagnosticTx = dead.get(txHash);
    }

    boolean isReplay = ((spent.containsKey(txHash) || unspent.containsKey(txHash) || dead.containsKey(txHash))
            && bestChain) && diagnosticTx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING
            && (diagnosticTx.getConfidence().getAppearedAtChainHeight() > lastBlockSeenHeight);

    if (isReplay) {
        log.debug("Replay diagnostic for tx = " + txHash);
        log.debug("  spent.containsKey(txHash) = " + spent.containsKey(txHash));
        log.debug("  unspent.containsKey(txHash) = " + unspent.containsKey(txHash));
        log.debug("  dead.containsKey(txHash) = " + dead.containsKey(txHash));
        log.debug("  diagnosticTx.getConfidence().getConfidenceType() = "
                + diagnosticTx.getConfidence().getConfidenceType());
        if (diagnosticTx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING) {
            log.debug("  diagnosticTx.getConfidence().getAppearedAtChainHeight() = "
                    + diagnosticTx.getConfidence().getAppearedAtChainHeight());
        }
        log.debug("  lastBlockSeenHeight = " + lastBlockSeenHeight);
        log.debug("  bestChain = " + bestChain);

        // We know the tx appears in the chain in the future (compared to
        // now) and it is not a reorg so can ignore it.
        // This happens on replay.
        log.debug("Received a tx '" + txHash.toString() + "' which is a replay so ignoring.");
        return;
    }
    onWalletChangedSuppressions++;

    // If this transaction is already in the wallet we may need to move it into a different pool. At the very
    // least we need to ensure we're manipulating the canonical object rather than a duplicate.
    {
        Transaction tmp = transactions.get(tx.getHash());
        if (tmp != null)
            tx = tmp;
    }

    boolean wasPending = pending.remove(txHash) != null;
    if (wasPending)
        log.info("  <-pending");

    if (bestChain) {
        if (wasPending) {
            // Was pending and is now confirmed. Disconnect the outputs in case we spent any already: they will be
            // re-connected by processTxFromBestChain below.
            for (TransactionOutput output : tx.getOutputs()) {
                final TransactionInput spentBy = output.getSpentBy();
                if (spentBy != null)
                    spentBy.disconnect();
            }
        }

        processTxFromBestChain(tx, wasPending);
    } else {
        checkState(sideChain);
        // Transactions that appear in a side chain will have that appearance recorded below - we assume that
        // some miners are also trying to include the transaction into the current best chain too, so let's treat
        // it as pending, except we don't need to do any risk analysis on it.
        if (wasPending) {
            // Just put it back in without touching the connections or confidence.
            addWalletTransaction(Pool.PENDING, tx);
            log.info("  ->pending");
        } else {
            // Ignore the case where a tx appears on a side chain at the same time as the best chain (this is
            // quite normal and expected).
            Sha256Hash hash = tx.getHash();
            if (!unspent.containsKey(hash) && !spent.containsKey(hash)) {
                // Otherwise put it (possibly back) into pending.
                // Committing it updates the spent flags and inserts into the pool as well.
                commitTx(tx);
            }
        }
    }

    if (block != null) {
        // Mark the tx as appearing in this block so we can find it later after a re-org. This also tells the tx
        // confidence object about the block and sets its work done/depth appropriately.
        tx.setBlockAppearance(block, bestChain, relativityOffset);
        if (bestChain) {
            // Don't notify this tx of work done in notifyNewBestBlock which will be called immediately after
            // this method has been called by BlockChain for all relevant transactions. Otherwise we'd double
            // count.
            ignoreNextNewBlock.add(txHash);
        }
    }

    onWalletChangedSuppressions--;

    // Side chains don't affect confidence.
    if (bestChain) {
        // notifyNewBestBlock will be invoked next and will then call maybeQueueOnWalletChanged for us.
        confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE);
    } else {
        maybeQueueOnWalletChanged();
    }

    // Inform anyone interested that we have received or sent coins but only if:
    //  - This is not due to a re-org.
    //  - The coins appeared on the best chain.
    //  - We did in fact receive some new money.
    //  - We have not already informed the user about the coins when we received the tx broadcast, or for our
    //    own spends. If users want to know when a broadcast tx becomes confirmed, they need to use tx confidence
    //    listeners.
    if (!insideReorg && bestChain) {
        BigInteger newBalance = getBalance(); // This is slow.
        log.info("Balance is now: " + bitcoinValueToFriendlyString(newBalance));
        if (!wasPending) {
            int diff = valueDifference.compareTo(BigInteger.ZERO);
            // We pick one callback based on the value difference, though a tx can of course both send and receive
            // coins from the wallet.
            if (diff > 0) {
                queueOnCoinsReceived(tx, prevBalance, newBalance);
            } else if (diff < 0) {
                queueOnCoinsSent(tx, prevBalance, newBalance);
            }
        }
        checkBalanceFuturesLocked(newBalance);
    }

    informConfidenceListenersIfNotReorganizing();
    checkState(isConsistent());

    //saveNow();
}

From source file:ca.oson.json.Oson.java

private <E, R> String bigInteger2Json(FieldData objectDTO) {
    if (objectDTO == null || objectDTO.json2Java) {
        return null;
    }// w w w. j  a  v  a 2 s . c  o  m

    E value = (E) objectDTO.valueToProcess;
    Class<R> returnType = objectDTO.returnType;

    if (value != null && value.toString().trim().length() > 0) {
        BigInteger valueToProcess = null;
        String valueToReturn = null;

        if (value instanceof BigInteger) {
            valueToProcess = (BigInteger) value;
        } else {
            try {
                valueToProcess = new BigInteger(value.toString().trim());
            } catch (Exception ex) {
            }
        }

        if (valueToProcess != null) {
            try {
                Function function = objectDTO.getSerializer();
                if (function != null) {
                    try {
                        if (function instanceof DataMapper2JsonFunction) {
                            DataMapper classData = new DataMapper(returnType, value, objectDTO.classMapper,
                                    objectDTO.level, getPrettyIndentation());
                            return ((DataMapper2JsonFunction) function).apply(classData);

                        } else if (function instanceof BigInteger2JsonFunction) {
                            return ((BigInteger2JsonFunction) function).apply(valueToProcess);

                        } else {

                            Object returnedValue = null;
                            if (function instanceof FieldData2JsonFunction) {
                                FieldData2JsonFunction f = (FieldData2JsonFunction) function;
                                FieldData fieldData = objectDTO.clone();
                                returnedValue = f.apply(fieldData);
                            } else {
                                returnedValue = function.apply(value);
                            }

                            if (returnedValue instanceof Optional) {
                                returnedValue = ObjectUtil.unwrap(returnedValue);
                            }

                            if (returnedValue == null) {
                                return null;

                            } else if (returnedValue instanceof BigInteger) {
                                valueToProcess = (BigInteger) returnedValue;

                            } else {
                                objectDTO.valueToProcess = returnedValue;
                                return object2String(objectDTO);
                            }

                        }

                    } catch (Exception e) {
                    }
                }

                if (valueToProcess != null) {
                    Long min = objectDTO.getMin();
                    Long max = objectDTO.getMax();

                    if (min != null && min > valueToProcess.longValue()) {
                        valueToProcess = BigInteger.valueOf(min);
                    }

                    if (max != null && valueToProcess.compareTo(BigInteger.valueOf(max)) > 0) {
                        valueToProcess = BigInteger.valueOf(max);
                    }

                    Integer precision = objectDTO.getPrecision();
                    if (precision != null) {
                        valueToProcess = (BigInteger) NumberUtil.setPrecision(valueToProcess, precision,
                                getRoundingMode());
                    }

                    return NumberUtil.toPlainString(valueToProcess);
                }

            } catch (Exception ex) {
                //ex.printStackTrace();
            }
        }
    }

    return bigInteger2JsonDefault(objectDTO);
}

From source file:ca.oson.json.Oson.java

private <E, R> BigInteger json2BigInteger(FieldData objectDTO) {
    if (objectDTO == null || !objectDTO.json2Java) {
        return null;
    }/*w  w w.  j  av  a2s. c om*/

    E value = (E) objectDTO.valueToProcess;
    Class<R> returnType = objectDTO.returnType;

    if (value != null && value.toString().trim().length() > 0) {
        String valueToProcess = value.toString().trim();
        BigInteger valueToReturn = null;

        try {
            Function function = objectDTO.getDeserializer();

            if (function != null) {
                try {
                    Object returnedValue = null;

                    if (function instanceof Json2DataMapperFunction) {
                        DataMapper classData = new DataMapper(returnType, value, objectDTO.classMapper,
                                objectDTO.level, getPrettyIndentation());
                        returnedValue = ((Json2DataMapperFunction) function).apply(classData);

                    } else if (function instanceof Json2FieldDataFunction) {
                        Json2FieldDataFunction f = (Json2FieldDataFunction) function;
                        FieldData fieldData = objectDTO.clone();

                        returnedValue = f.apply(fieldData);

                    } else if (function instanceof Json2BigIntegerFunction) {
                        return ((Json2BigIntegerFunction) function).apply(valueToProcess);
                    } else {
                        returnedValue = function.apply(valueToProcess);
                    }

                    if (returnedValue instanceof Optional) {
                        returnedValue = ObjectUtil.unwrap(returnedValue);
                    }

                    if (returnedValue == null) {
                        return null;

                    } else if (Number.class.isAssignableFrom(returnedValue.getClass())
                            || returnedValue.getClass().isPrimitive()) {

                        if (returnedValue instanceof BigInteger) {
                            valueToReturn = (BigInteger) returnedValue;
                        } else if (returnedValue instanceof String) {
                            valueToReturn = new BigInteger((String) returnedValue);

                        } else if (returnedValue instanceof Integer) {
                            valueToReturn = BigInteger.valueOf((Integer) returnedValue);
                        } else if (returnedValue instanceof Long) {
                            valueToReturn = BigInteger.valueOf((Long) returnedValue);
                        } else if (returnedValue instanceof Short) {
                            valueToReturn = BigInteger.valueOf((Short) returnedValue);
                        } else if (returnedValue instanceof Double) {
                            valueToReturn = BigInteger.valueOf(((Double) returnedValue).longValue());
                        } else if (returnedValue instanceof Float) {
                            valueToReturn = BigInteger.valueOf(((Float) returnedValue).intValue());
                        } else if (returnedValue instanceof BigDecimal) {
                            valueToReturn = BigInteger.valueOf(((BigDecimal) returnedValue).longValue());
                        } else if (returnedValue instanceof Byte) {
                            valueToReturn = BigInteger.valueOf((Byte) returnedValue);
                        } else if (returnedValue instanceof AtomicInteger) {
                            valueToReturn = BigInteger.valueOf(((AtomicInteger) returnedValue).intValue());
                        } else if (returnedValue instanceof AtomicLong) {
                            valueToReturn = BigInteger.valueOf(((AtomicLong) returnedValue).longValue());
                        } else {
                            valueToReturn = BigInteger.valueOf(((Number) returnedValue).longValue());
                        }

                    } else if (returnedValue instanceof Character) {
                        valueToReturn = BigInteger.valueOf(((Character) returnedValue));

                    } else if (returnedValue instanceof Boolean) {
                        if ((Boolean) returnedValue)
                            valueToReturn = BigInteger.valueOf(1);
                        else
                            valueToReturn = BigInteger.valueOf(0);

                    } else if (Enum.class.isAssignableFrom(returnedValue.getClass())) {
                        valueToReturn = BigInteger.valueOf(((Enum) returnedValue).ordinal());

                    } else if (Date.class.isAssignableFrom(returnedValue.getClass())) {
                        valueToReturn = BigInteger.valueOf(((Date) returnedValue).getTime());

                    } else {
                        valueToReturn = new BigInteger((returnedValue.toString()));
                    }

                    return valueToReturn;

                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                valueToReturn = new BigInteger(valueToProcess);
            }

            if (valueToReturn != null) {
                Long min = objectDTO.getMin();
                Long max = objectDTO.getMax();

                if (min != null && min > valueToReturn.longValue()) {
                    return BigInteger.valueOf(min.intValue());
                }

                if (max != null && valueToReturn.compareTo(BigInteger.valueOf(max)) > 0) {
                    valueToReturn = BigInteger.valueOf(max);
                }

                return valueToReturn;
            }

        } catch (Exception ex) {
            //ex.printStackTrace();
        }

    }

    return json2BigIntegerDefault(objectDTO);
}