Example usage for java.math BigInteger subtract

List of usage examples for java.math BigInteger subtract

Introduction

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

Prototype

public BigInteger subtract(BigInteger val) 

Source Link

Document

Returns a BigInteger whose value is (this - val) .

Usage

From source file:com.blu3f1re.reddwallet.ui.SendCoinsFragment.java

private void handleGo() {
    state = State.PREPARATION;/*w ww. j av  a 2  s.c  o  m*/
    updateView();

    // final payment intent
    final PaymentIntent finalPaymentIntent = paymentIntent.mergeWithEditedValues(
            amountCalculatorLink.getAmount(), validatedAddress != null ? validatedAddress.address : null);
    final BigInteger finalAmount = finalPaymentIntent.getAmount();

    // prepare send request
    final SendRequest sendRequest = finalPaymentIntent.toSendRequest();
    final Address returnAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS);
    sendRequest.changeAddress = returnAddress;
    sendRequest.emptyWallet = paymentIntent.mayEditAmount()
            && finalAmount.equals(wallet.getBalance(BalanceType.AVAILABLE));

    //Emptying a wallet with less than 2 RDD can't be possible due to min fee 2 RDD of such a tx.
    /*        if (amount.compareTo(BigInteger.valueOf(200000000)) < 0 && sendRequest.emptyWallet)
            {
    AlertDialog.Builder bld = new AlertDialog.Builder(activity);
        bld.setTitle(R.string.send_coins_error_msg);
        bld.setMessage(R.string.send_coins_error_desc);
        bld.setNeutralButton(activity.getResources().getString(android.R.string.ok), null);
        bld.setCancelable(false);
        bld.create().show();
    state = State.FAILED;
    updateView();
    return;
            }*/

    new SendCoinsOfflineTask(wallet, backgroundHandler) {
        @Override
        protected void onSuccess(final Transaction transaction) {
            sentTransaction = transaction;

            state = State.SENDING;
            updateView();

            sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener);

            final Payment payment = createPaymentMessage(sentTransaction, returnAddress, finalAmount, null,
                    paymentIntent.payeeData);

            directPay(payment);

            application.broadcastTransaction(sentTransaction);

            final ComponentName callingActivity = activity.getCallingActivity();
            if (callingActivity != null) {
                log.info("returning result to calling activity: {}", callingActivity.flattenToString());

                final Intent result = new Intent();
                BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString());
                if (paymentIntent.standard == Standard.BIP70)
                    BitcoinIntegration.paymentToResult(result, payment.toByteArray());
                activity.setResult(Activity.RESULT_OK, result);
            }
        }

        private void directPay(final Payment payment) {
            if (directPaymentEnableView.isChecked()) {
                final DirectPaymentTask.ResultCallback callback = new DirectPaymentTask.ResultCallback() {
                    @Override
                    public void onResult(final boolean ack) {
                        directPaymentAck = ack;

                        if (state == State.SENDING)
                            state = State.SENT;

                        updateView();
                    }

                    @Override
                    public void onFail(final int messageResId, final Object... messageArgs) {
                        final DialogBuilder dialog = DialogBuilder.warn(activity,
                                R.string.send_coins_fragment_direct_payment_failed_title);
                        dialog.setMessage(paymentIntent.paymentUrl + "\n" + getString(messageResId, messageArgs)
                                + "\n\n" + getString(R.string.send_coins_fragment_direct_payment_failed_msg));
                        dialog.setPositiveButton(R.string.button_retry, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, final int which) {
                                directPay(payment);
                            }
                        });
                        dialog.setNegativeButton(R.string.button_dismiss, null);
                        dialog.show();
                    }
                };

                if (paymentIntent.isHttpPaymentUrl()) {
                    new DirectPaymentTask.HttpPaymentTask(backgroundHandler, callback, paymentIntent.paymentUrl,
                            application.httpUserAgent()).send(paymentIntent.standard, payment);
                } else if (paymentIntent.isBluetoothPaymentUrl() && bluetoothAdapter != null
                        && bluetoothAdapter.isEnabled()) {
                    new DirectPaymentTask.BluetoothPaymentTask(backgroundHandler, callback, bluetoothAdapter,
                            paymentIntent.getBluetoothMac()).send(paymentIntent.standard, payment);
                }
            }
        }

        @Override
        protected void onInsufficientMoney(@Nullable final BigInteger missing) {
            state = State.INPUT;
            updateView();

            final BigInteger estimated = wallet.getBalance(BalanceType.ESTIMATED);
            final BigInteger available = wallet.getBalance(BalanceType.AVAILABLE);
            final BigInteger pending = estimated.subtract(available);

            final int btcShift = config.getBtcShift();
            final int btcPrecision = config.getBtcMaxPrecision();
            final String btcPrefix = config.getBtcPrefix();

            final DialogBuilder dialog = DialogBuilder.warn(activity,
                    R.string.send_coins_fragment_insufficient_money_title);
            final StringBuilder msg = new StringBuilder();
            if (missing != null)
                msg.append(String.format(getString(R.string.send_coins_fragment_insufficient_money_msg1),
                        btcPrefix + ' ' + GenericUtils.formatValue(missing, btcPrecision, btcShift)))
                        .append("\n\n");
            if (pending.signum() > 0)
                msg.append(getString(R.string.send_coins_fragment_pending,
                        GenericUtils.formatValue(pending, btcPrecision, btcShift))).append("\n\n");
            msg.append(getString(R.string.send_coins_fragment_insufficient_money_msg2));
            dialog.setMessage(msg);
            dialog.setPositiveButton(R.string.send_coins_options_empty, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    handleEmpty();
                }
            });
            dialog.setNegativeButton(R.string.button_cancel, null);
            dialog.show();
        }

        @Override
        protected void onFailure() {
            state = State.FAILED;
            updateView();

            activity.longToast(R.string.send_coins_error_msg);
        }
    }.sendCoinsOffline(sendRequest); // send asynchronously
}

From source file:com.dopecoin.wallet.ui.SendCoinsFragment.java

private void handleGo() {
    state = State.PREPARATION;//from  www.j a va  2  s  .  c  o m
    updateView();

    // final payment intent
    final PaymentIntent finalPaymentIntent = paymentIntent.mergeWithEditedValues(
            amountCalculatorLink.getAmount(), validatedAddress != null ? validatedAddress.address : null);
    final BigInteger finalAmount = finalPaymentIntent.getAmount();

    // prepare send request
    final SendRequest sendRequest = finalPaymentIntent.toSendRequest();
    final Address returnAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS);
    sendRequest.changeAddress = returnAddress;
    sendRequest.emptyWallet = paymentIntent.mayEditAmount()
            && finalAmount.equals(wallet.getBalance(BalanceType.AVAILABLE));

    //Emptying a wallet with less than 2 DOPE can't be possible due to min fee 2 DOPE of such a tx.
    /*        if (amount.compareTo(BigInteger.valueOf(200000000)) < 0 && sendRequest.emptyWallet)
            {
    AlertDialog.Builder bld = new AlertDialog.Builder(activity);
        bld.setTitle(R.string.send_coins_error_msg);
        bld.setMessage(R.string.send_coins_error_desc);
        bld.setNeutralButton(activity.getResources().getString(android.R.string.ok), null);
        bld.setCancelable(false);
        bld.create().show();
    state = State.FAILED;
    updateView();
    return;
            }*/

    new SendCoinsOfflineTask(wallet, backgroundHandler) {
        @Override
        protected void onSuccess(final Transaction transaction) {
            sentTransaction = transaction;

            state = State.SENDING;
            updateView();

            sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener);

            final Payment payment = createPaymentMessage(sentTransaction, returnAddress, finalAmount, null,
                    paymentIntent.payeeData);

            directPay(payment);

            application.broadcastTransaction(sentTransaction);

            final ComponentName callingActivity = activity.getCallingActivity();
            if (callingActivity != null) {
                log.info("returning result to calling activity: {}", callingActivity.flattenToString());

                final Intent result = new Intent();
                BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString());
                if (paymentIntent.standard == Standard.BIP70)
                    BitcoinIntegration.paymentToResult(result, payment.toByteArray());
                activity.setResult(Activity.RESULT_OK, result);
            }
        }

        private void directPay(final Payment payment) {
            if (directPaymentEnableView.isChecked()) {
                final DirectPaymentTask.ResultCallback callback = new DirectPaymentTask.ResultCallback() {
                    @Override
                    public void onResult(final boolean ack) {
                        directPaymentAck = ack;

                        if (state == State.SENDING)
                            state = State.SENT;

                        updateView();
                    }

                    @Override
                    public void onFail(final int messageResId, final Object... messageArgs) {
                        final DialogBuilder dialog = DialogBuilder.warn(activity,
                                R.string.send_coins_fragment_direct_payment_failed_title);
                        dialog.setMessage(paymentIntent.paymentUrl + "\n" + getString(messageResId, messageArgs)
                                + "\n\n" + getString(R.string.send_coins_fragment_direct_payment_failed_msg));
                        dialog.setPositiveButton(R.string.button_retry, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, final int which) {
                                directPay(payment);
                            }
                        });
                        dialog.setNegativeButton(R.string.button_dismiss, null);
                        dialog.show();
                    }
                };

                if (paymentIntent.isHttpPaymentUrl()) {
                    new DirectPaymentTask.HttpPaymentTask(backgroundHandler, callback, paymentIntent.paymentUrl,
                            application.httpUserAgent()).send(paymentIntent.standard, payment);
                } else if (paymentIntent.isBluetoothPaymentUrl() && bluetoothAdapter != null
                        && bluetoothAdapter.isEnabled()) {
                    new DirectPaymentTask.BluetoothPaymentTask(backgroundHandler, callback, bluetoothAdapter,
                            paymentIntent.getBluetoothMac()).send(paymentIntent.standard, payment);
                }
            }
        }

        @Override
        protected void onInsufficientMoney(@Nullable final BigInteger missing) {
            state = State.INPUT;
            updateView();

            final BigInteger estimated = wallet.getBalance(BalanceType.ESTIMATED);
            final BigInteger available = wallet.getBalance(BalanceType.AVAILABLE);
            final BigInteger pending = estimated.subtract(available);

            final int btcShift = config.getBtcShift();
            final int btcPrecision = config.getBtcMaxPrecision();
            final String btcPrefix = config.getBtcPrefix();

            final DialogBuilder dialog = DialogBuilder.warn(activity,
                    R.string.send_coins_fragment_insufficient_money_title);
            final StringBuilder msg = new StringBuilder();
            if (missing != null)
                msg.append(String.format(getString(R.string.send_coins_fragment_insufficient_money_msg1),
                        btcPrefix + ' ' + GenericUtils.formatValue(missing, btcPrecision, btcShift)))
                        .append("\n\n");
            if (pending.signum() > 0)
                msg.append(getString(R.string.send_coins_fragment_pending,
                        GenericUtils.formatValue(pending, btcPrecision, btcShift))).append("\n\n");
            msg.append(getString(R.string.send_coins_fragment_insufficient_money_msg2));
            dialog.setMessage(msg);
            dialog.setPositiveButton(R.string.send_coins_options_empty, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    handleEmpty();
                }
            });
            dialog.setNegativeButton(R.string.button_cancel, null);
            dialog.show();
        }

        @Override
        protected void onFailure() {
            state = State.FAILED;
            updateView();

            activity.longToast(R.string.send_coins_error_msg);
        }
    }.sendCoinsOffline(sendRequest); // send asynchronously
}

From source file:in.leafco.wallet.ui.SendCoinsFragment.java

private void handleGo() {
    state = State.PREPARATION;//from   w  ww.  j a va  2s  .co  m
    updateView();

    // final payment intent
    final PaymentIntent finalPaymentIntent = paymentIntent.mergeWithEditedValues(
            amountCalculatorLink.getAmount(), validatedAddress != null ? validatedAddress.address : null);
    final BigInteger finalAmount = finalPaymentIntent.getAmount();

    // prepare send request
    final SendRequest sendRequest = finalPaymentIntent.toSendRequest();
    final Address returnAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS);
    sendRequest.changeAddress = returnAddress;
    sendRequest.emptyWallet = paymentIntent.mayEditAmount()
            && finalAmount.equals(wallet.getBalance(BalanceType.AVAILABLE));

    //Emptying a wallet with less than 2 LEAF can't be possible due to min fee 2 LEAF of such a tx.
    /*        if (amount.compareTo(BigInteger.valueOf(200000000)) < 0 && sendRequest.emptyWallet)
            {
    AlertDialog.Builder bld = new AlertDialog.Builder(activity);
        bld.setTitle(R.string.send_coins_error_msg);
        bld.setMessage(R.string.send_coins_error_desc);
        bld.setNeutralButton(activity.getResources().getString(android.R.string.ok), null);
        bld.setCancelable(false);
        bld.create().show();
    state = State.FAILED;
    updateView();
    return;
            }*/

    new SendCoinsOfflineTask(wallet, backgroundHandler) {
        @Override
        protected void onSuccess(final Transaction transaction) {
            sentTransaction = transaction;

            state = State.SENDING;
            updateView();

            sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener);

            final Payment payment = createPaymentMessage(sentTransaction, returnAddress, finalAmount, null,
                    paymentIntent.payeeData);

            directPay(payment);

            application.broadcastTransaction(sentTransaction);

            final ComponentName callingActivity = activity.getCallingActivity();
            if (callingActivity != null) {
                log.info("returning result to calling activity: {}", callingActivity.flattenToString());

                final Intent result = new Intent();
                BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString());
                if (paymentIntent.standard == Standard.BIP70)
                    BitcoinIntegration.paymentToResult(result, payment.toByteArray());
                activity.setResult(Activity.RESULT_OK, result);
            }
        }

        private void directPay(final Payment payment) {
            if (directPaymentEnableView.isChecked()) {
                final DirectPaymentTask.ResultCallback callback = new DirectPaymentTask.ResultCallback() {
                    @Override
                    public void onResult(final boolean ack) {
                        directPaymentAck = ack;

                        if (state == State.SENDING)
                            state = State.SENT;

                        updateView();
                    }

                    @Override
                    public void onFail(final int messageResId, final Object... messageArgs) {
                        final DialogBuilder dialog = DialogBuilder.warn(activity,
                                R.string.send_coins_fragment_direct_payment_failed_title);
                        dialog.setMessage(paymentIntent.paymentUrl + "\n" + getString(messageResId, messageArgs)
                                + "\n\n" + getString(R.string.send_coins_fragment_direct_payment_failed_msg));
                        dialog.setPositiveButton(R.string.button_retry, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, final int which) {
                                directPay(payment);
                            }
                        });
                        dialog.setNegativeButton(R.string.button_dismiss, null);
                        dialog.show();
                    }
                };

                if (paymentIntent.isHttpPaymentUrl()) {
                    new DirectPaymentTask.HttpPaymentTask(backgroundHandler, callback, paymentIntent.paymentUrl,
                            application.httpUserAgent()).send(paymentIntent.standard, payment);
                } else if (paymentIntent.isBluetoothPaymentUrl() && bluetoothAdapter != null
                        && bluetoothAdapter.isEnabled()) {
                    new DirectPaymentTask.BluetoothPaymentTask(backgroundHandler, callback, bluetoothAdapter,
                            paymentIntent.getBluetoothMac()).send(paymentIntent.standard, payment);
                }
            }
        }

        @Override
        protected void onInsufficientMoney(@Nullable final BigInteger missing) {
            state = State.INPUT;
            updateView();

            final BigInteger estimated = wallet.getBalance(BalanceType.ESTIMATED);
            final BigInteger available = wallet.getBalance(BalanceType.AVAILABLE);
            final BigInteger pending = estimated.subtract(available);

            final int btcShift = config.getBtcShift();
            final int btcPrecision = config.getBtcMaxPrecision();
            final String btcPrefix = config.getBtcPrefix();

            final DialogBuilder dialog = DialogBuilder.warn(activity,
                    R.string.send_coins_fragment_insufficient_money_title);
            final StringBuilder msg = new StringBuilder();
            if (missing != null)
                msg.append(String.format(getString(R.string.send_coins_fragment_insufficient_money_msg1),
                        btcPrefix + ' ' + GenericUtils.formatValue(missing, btcPrecision, btcShift)))
                        .append("\n\n");
            if (pending.signum() > 0)
                msg.append(getString(R.string.send_coins_fragment_pending,
                        GenericUtils.formatValue(pending, btcPrecision, btcShift))).append("\n\n");
            msg.append(getString(R.string.send_coins_fragment_insufficient_money_msg2));
            dialog.setMessage(msg);
            dialog.setPositiveButton(R.string.send_coins_options_empty, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    handleEmpty();
                }
            });
            dialog.setNegativeButton(R.string.button_cancel, null);
            dialog.show();
        }

        @Override
        protected void onFailure() {
            state = State.FAILED;
            updateView();

            activity.longToast(R.string.send_coins_error_msg);
        }
    }.sendCoinsOffline(sendRequest); // send asynchronously
}

From source file:com.hivewallet.androidclient.wallet.ui.send.SendCoinsFragment.java

private void handleGo() {
    state = State.PREPARATION;//from w w  w  .  j a v  a2s .co  m
    updateView();

    // final payment intent
    final PaymentIntent finalPaymentIntent = paymentIntent.mergeWithEditedValues(
            amountCalculatorLink.getAmount(), validatedAddress != null ? validatedAddress.address : null);
    final BigInteger finalAmount = finalPaymentIntent.getAmount();

    // prepare send request
    final SendRequest sendRequest = finalPaymentIntent.toSendRequest();
    final Address returnAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS);
    sendRequest.changeAddress = returnAddress;
    sendRequest.emptyWallet = paymentIntent.mayEditAmount()
            && finalAmount.equals(wallet.getBalance(BalanceType.AVAILABLE));

    new SendCoinsOfflineTask(wallet, backgroundHandler) {
        @Override
        protected void onSuccess(final Transaction transaction) {
            sentTransaction = transaction;

            state = State.SENDING;
            updateView();

            sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener);

            final Payment payment = PaymentProtocol.createPaymentMessage(sentTransaction, returnAddress,
                    finalAmount, null, paymentIntent.payeeData);

            directPay(payment);

            application.broadcastTransaction(sentTransaction);

            final ComponentName callingActivity = activity.getCallingActivity();
            if (callingActivity != null) {
                log.info("returning result to calling activity: {}", callingActivity.flattenToString());

                final Intent result = new Intent();
                BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString());
                if (paymentIntent.standard == Standard.BIP70)
                    BitcoinIntegration.paymentToResult(result, payment.toByteArray());
                activity.setResult(Activity.RESULT_OK, result);
            }
        }

        private void directPay(final Payment payment) {
            if (directPaymentEnableView.isChecked()) {
                final DirectPaymentTask.ResultCallback callback = new DirectPaymentTask.ResultCallback() {
                    @Override
                    public void onResult(final boolean ack) {
                        directPaymentAck = ack;

                        if (state == State.SENDING)
                            state = State.SENT;

                        updateView();
                    }

                    @Override
                    public void onFail(final int messageResId, final Object... messageArgs) {
                        final DialogBuilder dialog = DialogBuilder.warn(activity,
                                R.string.send_coins_fragment_direct_payment_failed_title);
                        dialog.setMessage(paymentIntent.paymentUrl + "\n" + getString(messageResId, messageArgs)
                                + "\n\n" + getString(R.string.send_coins_fragment_direct_payment_failed_msg));
                        dialog.setPositiveButton(R.string.button_retry, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, final int which) {
                                directPay(payment);
                            }
                        });
                        dialog.setNegativeButton(R.string.button_dismiss, null);
                        dialog.show();
                    }
                };

                if (paymentIntent.isHttpPaymentUrl()) {
                    new DirectPaymentTask.HttpPaymentTask(backgroundHandler, callback, paymentIntent.paymentUrl,
                            application.httpUserAgent()).send(payment);
                } else if (paymentIntent.isBluetoothPaymentUrl() && bluetoothAdapter != null
                        && bluetoothAdapter.isEnabled()) {
                    new DirectPaymentTask.BluetoothPaymentTask(backgroundHandler, callback, bluetoothAdapter,
                            Bluetooth.getBluetoothMac(paymentIntent.paymentUrl)).send(payment);
                }
            }
        }

        @Override
        protected void onInsufficientMoney(@Nullable final BigInteger missing) {
            state = State.INPUT;
            updateView();

            final BigInteger estimated = wallet.getBalance(BalanceType.ESTIMATED);
            final BigInteger available = wallet.getBalance(BalanceType.AVAILABLE);
            final BigInteger pending = estimated.subtract(available);

            final int btcShift = config.getBtcShift();
            final int btcPrecision = config.getBtcMaxPrecision();
            final String btcPrefix = config.getBtcPrefix();

            final DialogBuilder dialog = DialogBuilder.warn(activity,
                    R.string.send_coins_fragment_insufficient_money_title);
            final StringBuilder msg = new StringBuilder();
            if (missing != null)
                msg.append(getString(R.string.send_coins_fragment_insufficient_money_msg1,
                        btcPrefix + ' ' + GenericUtils.formatValue(missing, btcPrecision, btcShift)))
                        .append("\n\n");
            if (pending.signum() > 0)
                msg.append(getString(R.string.send_coins_fragment_pending,
                        btcPrefix + ' ' + GenericUtils.formatValue(pending, btcPrecision, btcShift)))
                        .append("\n\n");
            msg.append(getString(R.string.send_coins_fragment_insufficient_money_msg2));
            dialog.setMessage(msg);
            dialog.setPositiveButton(R.string.send_coins_options_empty, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    handleEmpty();
                }
            });
            dialog.setNegativeButton(R.string.button_cancel, null);
            dialog.show();
        }

        @Override
        protected void onFailure(@Nonnull Exception exception) {
            state = State.FAILED;
            updateView();

            final DialogBuilder dialog = DialogBuilder.warn(activity, R.string.send_coins_error_msg);
            dialog.setMessage(exception.toString());
            dialog.setNeutralButton(R.string.button_dismiss, null);
            dialog.show();
        }
    }.sendCoinsOffline(sendRequest); // send asynchronously
}

From source file:com.hamradiocoin.wallet.ui.send.SendCoinsFragment.java

private void handleGo() {
    state = State.PREPARATION;// w w w. j  av  a2 s  . c  om
    updateView();

    // final payment intent
    final PaymentIntent finalPaymentIntent = paymentIntent.mergeWithEditedValues(
            amountCalculatorLink.getAmount(), validatedAddress != null ? validatedAddress.address : null);
    final BigInteger finalAmount = finalPaymentIntent.getAmount();

    // prepare send request
    final SendRequest sendRequest = finalPaymentIntent.toSendRequest();
    final Address returnAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS);
    sendRequest.changeAddress = returnAddress;
    sendRequest.emptyWallet = paymentIntent.mayEditAmount()
            && finalAmount.equals(wallet.getBalance(BalanceType.AVAILABLE));

    new SendCoinsOfflineTask(wallet, backgroundHandler) {
        @Override
        protected void onSuccess(final Transaction transaction) {
            sentTransaction = transaction;

            state = State.SENDING;
            updateView();

            sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener);

            final Payment payment = PaymentProtocol.createPaymentMessage(sentTransaction, returnAddress,
                    finalAmount, null, paymentIntent.payeeData);

            directPay(payment);

            application.broadcastTransaction(sentTransaction);

            final ComponentName callingActivity = activity.getCallingActivity();
            if (callingActivity != null) {
                log.info("returning result to calling activity: {}", callingActivity.flattenToString());

                final Intent result = new Intent();
                BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString());
                if (paymentIntent.standard == PaymentIntent.Standard.BIP70)
                    BitcoinIntegration.paymentToResult(result, payment.toByteArray());
                activity.setResult(Activity.RESULT_OK, result);
            }
        }

        private void directPay(final Payment payment) {
            if (directPaymentEnableView.isChecked()) {
                final DirectPaymentTask.ResultCallback callback = new DirectPaymentTask.ResultCallback() {
                    @Override
                    public void onResult(final boolean ack) {
                        directPaymentAck = ack;

                        if (state == State.SENDING)
                            state = State.SENT;

                        updateView();
                    }

                    @Override
                    public void onFail(final int messageResId, final Object... messageArgs) {
                        final DialogBuilder dialog = DialogBuilder.warn(activity,
                                R.string.send_coins_fragment_direct_payment_failed_title);
                        dialog.setMessage(paymentIntent.paymentUrl + "\n" + getString(messageResId, messageArgs)
                                + "\n\n" + getString(R.string.send_coins_fragment_direct_payment_failed_msg));
                        dialog.setPositiveButton(R.string.button_retry, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, final int which) {
                                directPay(payment);
                            }
                        });
                        dialog.setNegativeButton(R.string.button_dismiss, null);
                        dialog.show();
                    }
                };

                if (paymentIntent.isHttpPaymentUrl()) {
                    new DirectPaymentTask.HttpPaymentTask(backgroundHandler, callback, paymentIntent.paymentUrl,
                            application.httpUserAgent()).send(payment);
                } else if (paymentIntent.isBluetoothPaymentUrl() && bluetoothAdapter != null
                        && bluetoothAdapter.isEnabled()) {
                    new DirectPaymentTask.BluetoothPaymentTask(backgroundHandler, callback, bluetoothAdapter,
                            Bluetooth.getBluetoothMac(paymentIntent.paymentUrl)).send(payment);
                }
            }
        }

        @Override
        protected void onInsufficientMoney(@Nullable final BigInteger missing) {
            state = State.INPUT;
            updateView();

            final BigInteger estimated = wallet.getBalance(BalanceType.ESTIMATED);
            final BigInteger available = wallet.getBalance(BalanceType.AVAILABLE);
            final BigInteger pending = estimated.subtract(available);

            final int btcShift = config.getBtcShift();
            final int btcPrecision = config.getBtcMaxPrecision();
            final String btcPrefix = config.getBtcPrefix();

            final DialogBuilder dialog = DialogBuilder.warn(activity,
                    R.string.send_coins_fragment_insufficient_money_title);
            final StringBuilder msg = new StringBuilder();
            if (missing != null)
                msg.append(getString(R.string.send_coins_fragment_insufficient_money_msg1,
                        btcPrefix + ' ' + GenericUtils.formatValue(missing, btcPrecision, btcShift)))
                        .append("\n\n");
            if (pending.signum() > 0)
                msg.append(getString(R.string.send_coins_fragment_pending,
                        btcPrefix + ' ' + GenericUtils.formatValue(pending, btcPrecision, btcShift)))
                        .append("\n\n");
            msg.append(getString(R.string.send_coins_fragment_insufficient_money_msg2));
            dialog.setMessage(msg);
            dialog.setPositiveButton(R.string.send_coins_options_empty, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    handleEmpty();
                }
            });
            dialog.setNegativeButton(R.string.button_cancel, null);
            dialog.show();
        }

        @Override
        protected void onFailure(@Nonnull Exception exception) {
            state = State.FAILED;
            updateView();

            final DialogBuilder dialog = DialogBuilder.warn(activity, R.string.send_coins_error_msg);
            dialog.setMessage(exception.toString());
            dialog.setNeutralButton(R.string.button_dismiss, null);
            dialog.show();
        }
    }.sendCoinsOffline(sendRequest); // send asynchronously
}

From source file:de.langerhans.wallet.ui.SendCoinsFragment.java

private void handleGo() {
    state = State.PREPARATION;/*from w w  w .  j a  va2 s .c  om*/
    updateView();

    // final payment intent
    final PaymentIntent finalPaymentIntent = paymentIntent.mergeWithEditedValues(
            amountCalculatorLink.getAmount(), validatedAddress != null ? validatedAddress.address : null);
    final BigInteger finalAmount = finalPaymentIntent.getAmount();

    // prepare send request
    final SendRequest sendRequest = finalPaymentIntent.toSendRequest();
    final Address returnAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS);
    sendRequest.changeAddress = returnAddress;
    sendRequest.emptyWallet = paymentIntent.mayEditAmount()
            && finalAmount.equals(wallet.getBalance(BalanceType.AVAILABLE));

    //Emptying a wallet with less than 2 DOGE can't be possible due to min fee 2 DOGE of such a tx.
    /*        if (amount.compareTo(BigInteger.valueOf(200000000)) < 0 && sendRequest.emptyWallet)
            {
    AlertDialog.Builder bld = new AlertDialog.Builder(activity);
        bld.setTitle(R.string.send_coins_error_msg);
        bld.setMessage(R.string.send_coins_error_desc);
        bld.setNeutralButton(activity.getResources().getString(android.R.string.ok), null);
        bld.setCancelable(false);
        bld.create().show();
    state = State.FAILED;
    updateView();
    return;
            }*/

    new SendCoinsOfflineTask(wallet, backgroundHandler) {
        @Override
        protected void onSuccess(final Transaction transaction) {
            sentTransaction = transaction;

            state = State.SENDING;
            updateView();

            sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener);

            final Payment payment = PaymentProtocol.createPaymentMessage(sentTransaction, returnAddress,
                    finalAmount, null, paymentIntent.payeeData);

            directPay(payment);

            application.broadcastTransaction(sentTransaction);

            final ComponentName callingActivity = activity.getCallingActivity();
            if (callingActivity != null) {
                log.info("returning result to calling activity: {}", callingActivity.flattenToString());

                final Intent result = new Intent();
                BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString());
                if (paymentIntent.standard == Standard.BIP70)
                    BitcoinIntegration.paymentToResult(result, payment.toByteArray());
                activity.setResult(Activity.RESULT_OK, result);
            }
        }

        private void directPay(final Payment payment) {
            if (directPaymentEnableView.isChecked()) {
                final DirectPaymentTask.ResultCallback callback = new DirectPaymentTask.ResultCallback() {
                    @Override
                    public void onResult(final boolean ack) {
                        directPaymentAck = ack;

                        if (state == State.SENDING)
                            state = State.SENT;

                        updateView();
                    }

                    @Override
                    public void onFail(final int messageResId, final Object... messageArgs) {
                        final DialogBuilder dialog = DialogBuilder.warn(activity,
                                R.string.send_coins_fragment_direct_payment_failed_title);
                        dialog.setMessage(paymentIntent.paymentUrl + "\n" + getString(messageResId, messageArgs)
                                + "\n\n" + getString(R.string.send_coins_fragment_direct_payment_failed_msg));
                        dialog.setPositiveButton(R.string.button_retry, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, final int which) {
                                directPay(payment);
                            }
                        });
                        dialog.setNegativeButton(R.string.button_dismiss, null);
                        dialog.show();
                    }
                };

                if (paymentIntent.isHttpPaymentUrl()) {
                    new DirectPaymentTask.HttpPaymentTask(backgroundHandler, callback, paymentIntent.paymentUrl,
                            application.httpUserAgent()).send(payment);
                } else if (paymentIntent.isBluetoothPaymentUrl() && bluetoothAdapter != null
                        && bluetoothAdapter.isEnabled()) {
                    new DirectPaymentTask.BluetoothPaymentTask(backgroundHandler, callback, bluetoothAdapter,
                            Bluetooth.getBluetoothMac(paymentIntent.paymentUrl)).send(payment);
                }
            }
        }

        @Override
        protected void onInsufficientMoney(@Nullable final BigInteger missing) {
            state = State.INPUT;
            updateView();

            final BigInteger estimated = wallet.getBalance(BalanceType.ESTIMATED);
            final BigInteger available = wallet.getBalance(BalanceType.AVAILABLE);
            final BigInteger pending = estimated.subtract(available);

            final int btcShift = config.getBtcShift();
            final int btcPrecision = config.getBtcMaxPrecision();
            final String btcPrefix = config.getBtcPrefix();

            final DialogBuilder dialog = DialogBuilder.warn(activity,
                    R.string.send_coins_fragment_insufficient_money_title);
            final StringBuilder msg = new StringBuilder();
            if (missing != null)
                msg.append(String.format(getString(R.string.send_coins_fragment_insufficient_money_msg1),
                        btcPrefix + ' ' + GenericUtils.formatValue(missing, btcPrecision, btcShift)))
                        .append("\n\n");
            if (pending.signum() > 0)
                msg.append(getString(R.string.send_coins_fragment_pending,
                        GenericUtils.formatValue(pending, btcPrecision, btcShift))).append("\n\n");
            msg.append(getString(R.string.send_coins_fragment_insufficient_money_msg2));
            dialog.setMessage(msg);
            dialog.setPositiveButton(R.string.send_coins_options_empty, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    handleEmpty();
                }
            });
            dialog.setNegativeButton(R.string.button_cancel, null);
            dialog.show();
        }

        @Override
        protected void onFailure() {
            state = State.FAILED;
            updateView();

            activity.longToast(R.string.send_coins_error_msg);
        }
    }.sendCoinsOffline(sendRequest); // send asynchronously
}

From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java

/**
 * Helper function to create a new node.
 *
 * @param con             an open and valid connection
 * @param seq             reference to a sequencer
 * @param ce              reference to the content engine
 * @param mode            Live or Edit mode
 * @param parentNodeId    the parent node (1=root)
 * @param name            the name of the new node (only informative value)
 * @param label           label for Caption property (only used if new reference is created)
 * @param position        the position within the childs (0 based, Integer.MAX_VALUE may be used to
 *                        append to the end)
 * @param reference       a reference to an existing content (must exist!)
 * @param data            the optional data
 * @param nodeId          the id to use or create a new one if < 0
 * @param activateContent change the step of contents that have no live step to live in the max version?
 * @return the used or created node id//from www .j  a  v a2 s  .c o  m
 * @throws FxTreeException if the function fails
 */
private long _createNode(Connection con, SequencerEngine seq, ContentEngine ce, FxTreeMode mode,
        long parentNodeId, String name, FxString label, int position, FxPK reference, String data, long nodeId,
        boolean activateContent) throws FxApplicationException {

    // acquire exclusive lock for parent node
    acquireLocksForUpdate(con, mode, Arrays.asList(parentNodeId));

    //        makeSpace(con, seq/*irrelevant*/, mode, parentNodeId, position/*irrelevant*/, 1);
    FxTreeNodeInfoSpreaded parentNode = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, mode, parentNodeId);
    BigInteger boundaries[] = getBoundaries(con, parentNode, position);
    BigInteger leftBoundary = boundaries[0]; //== left border
    BigInteger rightBoundary = boundaries[1]; //== right border

    // Node has to be inserted between the left and right boundary and needs 2 slots for its left and right border
    BigInteger spacing = rightBoundary.subtract(leftBoundary).subtract(TWO);
    // Compute spacing for left,inner and right part
    spacing = spacing.divide(THREE);

    // We need at least 2 open slots (for the left and right boundary of the new node)
    //if the spacing is <= 0 we need more space
    if (spacing.compareTo(BigInteger.ZERO) <= 0/*less than*/) {
        throw new FxTreeException("ex.tree.create.noSpace", parentNodeId);
    }

    // try to use space more efficiently for flat structures, otherwise the first node of a folder
    // will get a third of the subtree space, the second one ninth, and so on.
    // Maxspacing indicates the number of nodes (*2) we expect to put in this node before space reorg
    spacing = spacing.compareTo(DEFAULT_NODE_SPACING) > 0 ? DEFAULT_NODE_SPACING : spacing;

    //        final BigInteger left = leftBoundary.add(spacing).add(BigInteger.ONE);
    // don't add gap to left boundary (doesn't seem to have any benefits since that space is lost
    // unless the tree is reorganized anyway
    final BigInteger left = leftBoundary.add(BigInteger.ONE);
    final BigInteger right = left.add(spacing).add(BigInteger.ONE);

    NodeCreateInfo nci = getNodeCreateInfo(mode, seq, ce, nodeId, name, label, reference, activateContent);

    // Create the node
    PreparedStatement ps = null;
    try {
        ps = con.prepareStatement("INSERT INTO " + getTable(mode) + " (ID,PARENT,DEPTH,DIRTY,REF,LFT,RGT,"
                + "CHILDCOUNT,NAME,MODIFIED_AT,TEMPLATE) VALUES " + "(" + nci.id + "," + parentNodeId + ","
                + (parentNode.getDepth() + 1) + ",?," + nci.reference.getId() + ",?,?,0,?,"
                + StorageManager.getTimestampFunction() + ",?)");
        ps.setBoolean(1, mode != FxTreeMode.Live);
        setNodeBounds(ps, 2, left);
        setNodeBounds(ps, 3, right);
        ps.setString(4, FxFormatUtils.escapeTreePath(nci.name));
        if (StringUtils.isEmpty(data)) {
            ps.setNull(5, java.sql.Types.VARCHAR);
        } else {
            ps.setString(6, data);
        }
        ps.executeUpdate();
        ps.close();

        //update the parents childcount
        ps = con.prepareStatement(
                "UPDATE " + getTable(mode) + " SET CHILDCOUNT=CHILDCOUNT+1 WHERE ID=" + parentNodeId);
        ps.executeUpdate();
    } catch (SQLException e) {
        throw new FxTreeException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        try {
            if (ps != null)
                ps.close();
        } catch (Throwable t) {
            /*ignore*/
        }
    }
    return nci.id;
}

From source file:com.amazonaws.services.kinesis.clientlibrary.lib.worker.WorkerTest.java

private void verifyRecordsProcessedByEachProcessorWereOrdered(TestStreamletFactory recordProcessorFactory) {
    for (TestStreamlet processor : recordProcessorFactory.getTestStreamlets()) {
        List<Record> processedRecords = processor.getProcessedRecords();
        for (int i = 0; i < processedRecords.size() - 1; i++) {
            BigInteger sequenceNumberOfcurrentRecord = new BigInteger(
                    processedRecords.get(i).getSequenceNumber());
            BigInteger sequenceNumberOfNextRecord = new BigInteger(
                    processedRecords.get(i + 1).getSequenceNumber());
            Assert.assertTrue(/*  w  ww  . j a v a  2  s  .c o  m*/
                    sequenceNumberOfcurrentRecord.subtract(sequenceNumberOfNextRecord).signum() == -1);
        }
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The trigonometric tangent.//ww  w .  j a v  a 2 s  .  c  o  m
 *
 * @param x the argument in radians.
 * @return the tan(x)
 */
static public BigDecimal tan(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else if (x.compareTo(BigDecimal.ZERO) < 0) {
        return tan(x.negate()).negate();
    } else {
        /* reduce modulo pi
         */
        BigDecimal res = modpi(x);
        /* absolute error in the result is err(x)/cos^2(x) to lowest order
         */
        final double xDbl = res.doubleValue();
        final double xUlpDbl = x.ulp().doubleValue() / 2.;
        final double eps = xUlpDbl / 2. / Math.pow(Math.cos(xDbl), 2.);
        if (xDbl > 0.8) {
            /* tan(x) = 1/cot(x) */
            BigDecimal co = cot(x);
            MathContext mc = new MathContext(err2prec(1. / co.doubleValue(), eps));
            return BigDecimal.ONE.divide(co, mc);
        } else {
            final BigDecimal xhighpr = scalePrec(res, 2);
            final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr);
            BigDecimal resul = xhighpr.plus();
            /* x^(2i+1) */
            BigDecimal xpowi = xhighpr;
            Bernoulli b = new Bernoulli();
            /* 2^(2i) */
            BigInteger fourn = new BigInteger("4");
            /* (2i)! */
            BigInteger fac = new BigInteger("2");
            for (int i = 2;; i++) {
                Rational f = b.at(2 * i).abs();
                fourn = fourn.shiftLeft(2);
                fac = fac.multiply(new BigInteger("" + (2 * i))).multiply(new BigInteger("" + (2 * i - 1)));
                f = f.multiply(fourn).multiply(fourn.subtract(BigInteger.ONE)).divide(fac);
                xpowi = multiplyRound(xpowi, xhighprSq);
                BigDecimal c = multiplyRound(xpowi, f);
                resul = resul.add(c);
                if (Math.abs(c.doubleValue()) < 0.1 * eps) {
                    break;
                }
            }
            MathContext mc = new MathContext(err2prec(resul.doubleValue(), eps));
            return resul.round(mc);
        }
    }
}

From source file:mitm.common.security.crl.PKIXRevocationChecker.java

private DeltaCRLStatus getDeltaCRLStatus(X509Certificate targetCertificate, X509CRL deltaCRL,
        PublicKey issuerPublicKey, Date now) throws NoSuchProviderException {
    DeltaCRLStatus status = DeltaCRLStatus.UNKNOWN;

    BigInteger baseCRLNumber;//from  w w  w.ja v a 2s  .  c  o  m

    try {
        baseCRLNumber = X509CRLInspector.getDeltaIndicator(deltaCRL);
    } catch (IOException e) {
        logger.error("Error getting base CRL number", e);

        return DeltaCRLStatus.UNKNOWN;
    }

    X509CRLSelector crlSelector = new X509CRLSelector();

    /* We need to find a valid base CRL with the same issuer as the delta CRL */
    crlSelector.addIssuer(deltaCRL.getIssuerX500Principal());

    /*
     * we need to find a baseCRL with at least a CRL number specified by the DeltaCRLIndicator in 
     * the delta CRL
     */
    crlSelector.setMinCRLNumber(baseCRLNumber);

    BigInteger deltaCRLNumber = null;

    try {
        deltaCRLNumber = X509CRLInspector.getCRLNumber(deltaCRL);
    } catch (IOException e) {
        logger.error("Error getting CRLNumber extension from the delta CRL.", e);
    }

    if (deltaCRLNumber != null) {
        /*
         * the base CRL we need to find should have a  CRL number less than the delta CRL
         * otherwise it cannot be a base for this delta CRL
         */
        crlSelector.setMaxCRLNumber(deltaCRLNumber.subtract(BigInteger.valueOf(1)));

        List<X509CRL> crls = findCRLs(targetCertificate, crlSelector, issuerPublicKey, now);

        for (X509CRL baseCRL : crls) {
            try {
                if (checkDeltaCRL_6_3_3_b(targetCertificate, deltaCRL, baseCRL)) {
                    status = DeltaCRLStatus.OK;
                    break;
                }
            } catch (IOException e) {
                logger.error("Error executing checkDeltaCRL_6_3_3_b.", e);
                continue;
            }

            if (hasUnsupportedCriticalExtensions(baseCRL)) {
                logger.warn("The base CRL has unsupported critical extensions.");

                status = DeltaCRLStatus.UNSUPPORTED_CRITICAL_EXTENSION;

                continue;
            }
        }
    }

    return status;
}