Example usage for java.math BigInteger equals

List of usage examples for java.math BigInteger equals

Introduction

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

Prototype

public boolean equals(Object x) 

Source Link

Document

Compares this BigInteger with the specified Object for equality.

Usage

From source file:ja.ohac.wallet.ui.send.SendCoinsFragment.java

private void handleGo() {
    state = State.PREPARATION;/*  w  w  w  . ja  v 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));

    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 Coin estimated = wallet.getBalance(BalanceType.ESTIMATED);
            final Coin available = wallet.getBalance(BalanceType.AVAILABLE);
            final Coin 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(
                                        BigInteger.valueOf(pending.longValue()), 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:be.apsu.extremon.probes.tsp.TSPProbe.java

public void probe_forever() {
    double start = 0, end = 0;
    BigInteger requestNonce;/*from   w w  w . j  av a 2 s .  c o  m*/
    byte[] requestHashedMessage = new byte[20];
    List<String> comments = new ArrayList<String>();
    STATE result = STATE.OK;

    log("running");

    this.running = true;
    while (this.running) {
        comments.clear();
        this.random.nextBytes(requestHashedMessage);
        requestNonce = new BigInteger(512, this.random);
        TimeStampRequest request = requestGenerator.generate(TSPAlgorithms.SHA1, requestHashedMessage,
                requestNonce);

        end = 0;
        start = System.currentTimeMillis();

        try {
            TimeStampResponse response = probe(request);

            switch (response.getStatus()) {
            case PKIStatus.GRANTED:
                comments.add("granted");
                result = STATE.OK;
                break;
            case PKIStatus.GRANTED_WITH_MODS:
                comments.add("granted with modifications");
                result = STATE.WARNING;
                break;
            case PKIStatus.REJECTION:
                comments.add("rejected");
                result = STATE.ALERT;
                break;
            case PKIStatus.WAITING:
                comments.add("waiting");
                result = STATE.ALERT;
                break;
            case PKIStatus.REVOCATION_WARNING:
                comments.add("revocation warning");
                result = STATE.WARNING;
                break;
            case PKIStatus.REVOCATION_NOTIFICATION:
                comments.add("revocation notification");
                result = STATE.ALERT;
                break;
            default:
                comments.add("response outside RFC3161");
                result = STATE.ALERT;
                break;
            }

            if (response.getStatus() >= 2)
                comments.add(response.getFailInfo() != null ? response.getFailInfo().getString()
                        : "(missing failinfo)");

            if (response.getStatusString() != null)
                comments.add(response.getStatusString());

            end = System.currentTimeMillis();
            TimeStampToken timestampToken = response.getTimeStampToken();

            timestampToken.validate(this.signerVerifier);
            comments.add("validated");

            AttributeTable table = timestampToken.getSignedAttributes();
            TimeStampTokenInfo tokenInfo = timestampToken.getTimeStampInfo();
            BigInteger responseNonce = tokenInfo.getNonce();
            byte[] responseHashedMessage = tokenInfo.getMessageImprintDigest();
            long genTimeSeconds = (tokenInfo.getGenTime().getTime()) / 1000;
            long currentTimeSeconds = (long) (start + ((end - start) / 2)) / 1000;

            put("clockskew", (genTimeSeconds - currentTimeSeconds) * 1000);

            if (Math.abs((genTimeSeconds - currentTimeSeconds)) > 1) {
                comments.add("clock skew > 1s");
                result = STATE.ALERT;
            }

            Store responseCertificatesStore = timestampToken.toCMSSignedData().getCertificates();
            @SuppressWarnings("unchecked")
            Collection<X509CertificateHolder> certs = responseCertificatesStore.getMatches(null);
            for (X509CertificateHolder certificate : certs) {
                AlgorithmIdentifier sigalg = certificate.getSignatureAlgorithm();
                if (!(oidsAllowed.contains(sigalg.getAlgorithm().getId()))) {
                    String cleanDn = certificate.getSubject().toString().replace("=", ":");
                    comments.add("signature cert \"" + cleanDn + "\" signed using "
                            + getName(sigalg.getAlgorithm().getId()));
                    result = STATE.ALERT;
                }
            }

            if (!responseNonce.equals(requestNonce)) {
                comments.add("nonce modified");
                result = STATE.ALERT;
            }

            if (!Arrays.equals(responseHashedMessage, requestHashedMessage)) {
                comments.add("hashed message modified");
                result = STATE.ALERT;
            }

            if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificate) == null) {
                comments.add("signingcertificate missing");
                result = STATE.ALERT;
            }
        } catch (TSPException tspEx) {
            comments.add("validation failed");
            comments.add("tspexception-" + tspEx.getMessage().toLowerCase());
            result = STATE.ALERT;
        } catch (IOException iox) {
            comments.add("unable to obtain response");
            comments.add("ioexception-" + iox.getMessage().toLowerCase());
            result = STATE.ALERT;
        } catch (Exception ex) {
            comments.add("unhandled exception");
            result = STATE.ALERT;
        } finally {
            if (end == 0)
                end = System.currentTimeMillis();
        }

        put(RESULT_SUFFIX, result);
        put(RESULT_COMMENT_SUFFIX, StringUtils.join(comments, "|"));
        put("responsetime", (end - start));

        try {
            Thread.sleep(this.delay);
        } catch (InterruptedException ex) {
            log("interrupted");
        }
    }
}

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

private void handleGo() {
    state = State.PREPARATION;/*from  www.  j a v  a2  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));

    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;//w w  w.  java  2  s .  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 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:org.opendaylight.netvirt.elan.internal.ElanInterfaceManager.java

private void deleteAllRemoteMacsInADpn(String elanName, BigInteger dpId, long elanTag) {
    List<DpnInterfaces> dpnInterfaces = elanUtils.getInvolvedDpnsInElan(elanName);
    for (DpnInterfaces dpnInterface : dpnInterfaces) {
        BigInteger currentDpId = dpnInterface.getDpId();
        if (!currentDpId.equals(dpId)) {
            for (String elanInterface : dpnInterface.getInterfaces()) {
                ElanInterfaceMac macs = elanUtils.getElanInterfaceMacByInterfaceName(elanInterface);
                if (macs == null || macs.getMacEntry() == null) {
                    continue;
                }//from w  w w. j  a  v a  2 s .  c om
                for (MacEntry mac : macs.getMacEntry()) {
                    removeTheMacFlowInTheDPN(dpId, elanTag, currentDpId, mac);
                    removeEtreeMacFlowInTheDPN(dpId, elanTag, currentDpId, mac);
                }
            }
        }
    }
}

From source file:com.facebook.infrastructure.service.StorageService.java

/**
 * Called when there is a change in application state. In particular we are
 * interested in new tokens as a result of a new node or an existing node
 * moving to a new location on the ring.
 *//*from   www  . j av  a2s .c o m*/
public void onChange(EndPoint endpoint, EndPointState epState) {
    EndPoint ep = new EndPoint(endpoint.getHost(), DatabaseDescriptor.getStoragePort());
    /* node identifier for this endpoint on the identifier space */
    ApplicationState nodeIdState = epState.getApplicationState(StorageService.nodeId_);
    if (nodeIdState != null) {
        BigInteger newToken = new BigInteger(nodeIdState.getState());
        logger_.debug("CHANGE IN STATE FOR " + endpoint + " - has token " + nodeIdState.getState());
        BigInteger oldToken = tokenMetadata_.getToken(ep);

        if (oldToken != null) {
            /*
             * If oldToken equals the newToken then the node had crashed and is
             * coming back up again. If oldToken is not equal to the newToken this
             * means that the node is being relocated to another position in the
             * ring.
             */
            if (!oldToken.equals(newToken)) {
                logger_.debug("Relocation for endpoint " + ep);
                tokenMetadata_.update(newToken, ep);
            } else {
                /*
                 * This means the node crashed and is coming back up. Deliver the
                 * hints that we have for this endpoint.
                 */
                logger_.debug("Sending hinted data to " + ep);
                doBootstrap(endpoint, BootstrapMode.HINT);
            }
        } else {
            /*
             * This is a new node and we just update the token map.
             */
            tokenMetadata_.update(newToken, ep);
        }
    } else {
        /*
         * If we are here and if this node is UP and already has an entry in the
         * token map. It means that the node was behind a network partition.
         */
        if (epState.isAlive() && tokenMetadata_.isKnownEndPoint(endpoint)) {
            logger_.debug("EndPoint " + ep + " just recovered from a partition. Sending hinted data.");
            doBootstrap(ep, BootstrapMode.HINT);
        }
    }

    /* Check if a bootstrap is in order */
    ApplicationState loadAllState = epState.getApplicationState(StorageService.loadAll_);
    if (loadAllState != null) {
        String nodes = loadAllState.getState();
        if (nodes != null) {
            doBootstrap(ep, BootstrapMode.FULL);
        }
    }
}

From source file:VASL.build.module.map.ASLBoardPicker.java

/**
 * Reads the current board directory and constructs the list of available boards
 *//*from   w  w  w.j  a v  a2s .  c o  m*/
public void refreshPossibleBoards() {
    String files[] = boardDir == null ? new String[0] : boardDir.list();
    List<String> sorted = new ArrayList<String>();
    for (int i = 0; i < files.length; ++i) {
        if (files[i].startsWith("bd") && !(new File(boardDir, files[i])).isDirectory()) {
            String name = files[i].substring(2);
            if (name.endsWith(".gif")) {
                name = name.substring(0, name.indexOf(".gif"));
            } else if (name.indexOf(".") >= 0) {
                name = null;
            }
            if (name != null && !sorted.contains(name)) {
                sorted.add(name);
            }
        }
    }

    //
    // * Strings with leading zeros sort ahead of those without.
    // * Strings with leading integer parts sort ahead of those without.
    // * Strings with lesser leading integer parts sort ahead of those with
    //   greater leading integer parts.
    // * Strings which are otherwise equal are sorted lexicographically by
    //   their trailing noninteger parts.
    //

    final Comparator<Object> alpha = Collator.getInstance();
    final Pattern pat = Pattern.compile("((0*)\\d*)(.*)");

    Comparator<String> comp = new Comparator<String>() {
        public int compare(String o1, String o2) {
            final Matcher m1 = pat.matcher(o1);
            final Matcher m2 = pat.matcher(o2);

            if (!m1.matches()) {
                // impossible
                throw new IllegalStateException();
            }

            if (!m2.matches()) {
                // impossible
                throw new IllegalStateException();
            }

            // count leading zeros
            final int z1 = m1.group(2).length();
            final int z2 = m2.group(2).length();

            // more leading zeros comes first
            if (z1 < z2) {
                return 1;
            } else if (z1 > z2) {
                return -1;
            }

            // same number of leading zeros
            final String o1IntStr = m1.group(1);
            final String o2IntStr = m2.group(1);
            if (o1IntStr.length() > 0) {
                if (o2IntStr.length() > 0) {
                    try {
                        // both strings have integer parts
                        final BigInteger o1Int = new BigInteger(o1IntStr);
                        final BigInteger o2Int = new BigInteger(o2IntStr);

                        if (!o1Int.equals(o2Int)) {
                            // one integer part is smaller than the other
                            return o1Int.compareTo(o2Int);

                        }
                    } catch (NumberFormatException e) {
                        // impossible
                        throw new IllegalStateException(e);
                    }
                } else {
                    // only o1 has an integer part
                    return -1;
                }
            } else if (o2IntStr.length() > 0) {
                // only o2 has an integer part
                return 1;
            }

            // the traling string part is decisive
            return alpha.compare(m1.group(3), m2.group(3));
        }
    };

    Collections.sort(sorted, comp);
    possibleBoards.clear();
    for (int i = 0; i < sorted.size(); ++i) {
        addBoard((String) sorted.get(i));
    }
}

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

private void handleGo() {
    state = State.PREPARATION;/*w  w  w  .j  a  v  a2 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();
    log.info("amountCalculatorLink.getAmount() is :" + amountCalculatorLink.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, paymentIntent.getBluetoothMac())
                .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:org.opendaylight.netvirt.elan.internal.ElanInterfaceManager.java

public void handleInternalTunnelStateEvent(BigInteger srcDpId, BigInteger dstDpId) throws ElanException {
    ElanDpnInterfaces dpnInterfaceLists = elanUtils.getElanDpnInterfacesList();
    LOG.trace("processing tunnel state event for srcDpId {} dstDpId {}" + " and dpnInterfaceList {}", srcDpId,
            dstDpId, dpnInterfaceLists);
    if (dpnInterfaceLists == null) {
        return;//from  w w w .  j  av a2s  .c  o  m
    }
    List<ElanDpnInterfacesList> elanDpnIf = dpnInterfaceLists.getElanDpnInterfacesList();
    for (ElanDpnInterfacesList elanDpns : elanDpnIf) {
        int cnt = 0;
        String elanName = elanDpns.getElanInstanceName();
        ElanInstance elanInfo = ElanUtils.getElanInstanceByName(broker, elanName);
        if (elanInfo == null) {
            LOG.warn("ELAN Info is null for elanName {} that does exist in elanDpnInterfaceList, "
                    + "skipping this ELAN for tunnel handling", elanName);
            continue;
        }
        if (ElanUtils.isFlat(elanInfo) || ElanUtils.isVlan(elanInfo)) {
            LOG.debug("Ignoring internal tunnel state event for Flat/Vlan elan {}", elanName);
            continue;
        }
        List<DpnInterfaces> dpnInterfaces = elanDpns.getDpnInterfaces();
        if (dpnInterfaces == null) {
            continue;
        }
        DpnInterfaces dstDpnIf = null;
        for (DpnInterfaces dpnIf : dpnInterfaces) {
            BigInteger dpnIfDpId = dpnIf.getDpId();
            if (dpnIfDpId.equals(srcDpId)) {
                cnt++;
            } else if (dpnIfDpId.equals(dstDpId)) {
                cnt++;
                dstDpnIf = dpnIf;
            }
        }
        if (cnt == 2) {
            LOG.info("Elan instance:{} is present b/w srcDpn:{} and dstDpn:{}", elanName, srcDpId, dstDpId);
            DataStoreJobCoordinator dataStoreCoordinator = DataStoreJobCoordinator.getInstance();
            final DpnInterfaces finalDstDpnIf = dstDpnIf; // var needs to be final so it can be accessed in lambda
            dataStoreCoordinator.enqueueJob(elanName, () -> {
                // update Remote BC Group
                LOG.trace("procesing elan remote bc group for tunnel event {}", elanInfo);
                setupElanBroadcastGroups(elanInfo, srcDpId);

                Set<String> interfaceLists = new HashSet<>();
                interfaceLists.addAll(finalDstDpnIf.getInterfaces());
                for (String ifName : interfaceLists) {
                    dataStoreCoordinator.enqueueJob(ifName, () -> {
                        LOG.info("Processing tunnel up event for elan {} and interface {}", elanName, ifName);
                        InterfaceInfo interfaceInfo = interfaceManager.getInterfaceInfo(ifName);
                        if (isOperational(interfaceInfo)) {
                            installDMacAddressTables(elanInfo, interfaceInfo, srcDpId);
                        }
                        return null;
                    });
                }
                return null;
            });
        }

    }
}

From source file:net.pms.util.Rational.java

/**
 * Returns an instance with the given {@code numerator} and
 * {@code denominator}.//w  ww . j  a v  a 2  s.c  om
 *
 * @param numerator the numerator.
 * @param denominator the denominator.
 * @return An instance that represents the value of {@code numerator}/
 *         {@code denominator}.
 */
@Nullable
public static Rational valueOf(@Nullable BigInteger numerator, @Nullable BigInteger denominator) {
    if (numerator == null || denominator == null) {
        return null;
    }
    if (numerator.signum() == 0 && denominator.signum() == 0) {
        return NaN;
    }
    if (denominator.signum() == 0) {
        return numerator.signum() > 0 ? POSITIVE_INFINITY : NEGATIVE_INFINITY;
    }
    if (numerator.signum() == 0) {
        return ZERO;
    }
    if (numerator.equals(denominator)) {
        return ONE;
    }
    if (denominator.signum() < 0) {
        numerator = numerator.negate();
        denominator = denominator.negate();
    }

    BigInteger reducedNumerator;
    BigInteger reducedDenominator;
    BigInteger greatestCommonDivisor = calculateGreatestCommonDivisor(numerator, denominator);
    if (BigInteger.ONE.equals(greatestCommonDivisor)) {
        reducedNumerator = numerator;
        reducedDenominator = denominator;
    } else {
        reducedNumerator = numerator.divide(greatestCommonDivisor);
        reducedDenominator = denominator.divide(greatestCommonDivisor);
    }
    return new Rational(numerator, denominator, greatestCommonDivisor, reducedNumerator, reducedDenominator);
}