Example usage for java.math BigInteger longValue

List of usage examples for java.math BigInteger longValue

Introduction

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

Prototype

public long longValue() 

Source Link

Document

Converts this BigInteger to a long .

Usage

From source file:at.treedb.db.Base.java

/**
 * Counts the entries/table rows - DB related operation.
 * /*  ww  w  .j a v  a2 s.  c o m*/
 * @param clazz
 *            class of the entity
 * @param status
 *            historisation status of the entity
 * @param where
 *            optional where clause (single statement)
 * @return entity count
 * @throws Exception
 */
// TODO: Fix ugly where clause
public static long countRow(DAOiface dao, Class<?> clazz, HistorizationIface.STATUS stat, String where)
        throws Exception {
    long size = 0;
    boolean localDAO = false;
    if (dao == null) {
        dao = DAO.getDAO();
        localDAO = true;
    }
    try {
        if (localDAO) {
            dao.beginTransaction();
        }
        StringBuffer buf = new StringBuffer("SELECT count(c) FROM ");
        buf.append(clazz.getSimpleName());
        buf.append(" c");
        HashMap<String, Object> map = null;
        if (stat != null) {
            map = new HashMap<String, Object>();
            map.put("status", stat);
            buf.append(" where c.status = :status");
        }
        if (where != null) {
            buf.append(" AND c." + where);
        }

        Object s = dao.query(buf.toString(), map).get(0);
        if (s instanceof BigInteger) {
            BigInteger bi = (BigInteger) s;
            size = bi.longValue();
        } else {
            size = (Long) s;
        }
        if (localDAO) {
            dao.endTransaction();
        }
    } catch (Exception e) {
        if (localDAO) {
            dao.rollback();
        }
        throw e;
    }
    return size;
}

From source file:com.aegiswallet.actions.MainActivity.java

private void updateMainViews() {
    walletBalanceView.setText(BasicUtils.satoshiToBTC(wallet.getBalance(Wallet.BalanceType.ESTIMATED)));
    balanceInCurrencyView = (TextView) findViewById(R.id.wallet_balance_in_currency);
    balanceInCurrencyView.setTypeface(BasicUtils.getCustomTypeFace(getBaseContext()));

    String currencyValue = WalletUtils.getWalletCurrencyValue(getApplicationContext(), prefs,
            wallet.getBalance(Wallet.BalanceType.ESTIMATED));

    getBalanceInCurrencyViewType = (TextView) findViewById(R.id.wallet_balance_currency_type);
    getBalanceInCurrencyViewType.setTypeface(BasicUtils.getCustomTypeFace(getBaseContext()));

    if (currencyValue.length() >= 10) {
        balanceInCurrencyView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 32);
        getBalanceInCurrencyViewType.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
    } else if (currencyValue.length() >= 6) {
        balanceInCurrencyView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40);
        getBalanceInCurrencyViewType.setTextSize(TypedValue.COMPLEX_UNIT_SP, 28);
    }/*from   ww w  .ja  va2 s . c om*/

    balanceInCurrencyView.setText(currencyValue);
    getBalanceInCurrencyViewType.setText(" " + prefs.getString(Constants.CURRENCY_PREF_KEY, null));

    BigInteger watchedBalance = wallet.getWatchedBalance();

    if (watchedBalance != null && watchedBalance.longValue() > 0) {
        watchedBalanceLinearLayout.setVisibility(View.VISIBLE);
        walletWatchAddressBalanceView.setText(getString(R.string.watched_balance_string) + " "
                + BasicUtils.satoshiToBTC(wallet.getWatchedBalance()));
    } else {
        watchedBalanceLinearLayout.setVisibility(View.GONE);
    }

    checkWalletEncryptionStatus();

    recentTransactions = (ArrayList<Transaction>) wallet.getRecentTransactions(50, true);

    if (transactionListAdapter != null) {
        transactionListAdapter.clear();
        transactionListAdapter.notifyDataSetInvalidated();
        //transactionListAdapter.addAll(WalletUtils.getRelevantTransactions(recentTransactions, wallet));
        transactionListAdapter.addAll(recentTransactions);
        transactionListAdapter.notifyDataSetChanged();
    }

    //Update the last view update time here.
    lastViewUpdateTime.set(System.currentTimeMillis());
    sendMessagesToWear();
}

From source file:com.bonsai.wallet32.SendBitcoinActivity.java

private void updateToAddress(String toval) {

    // Avoid recursion by removing the field listener while
    // we possibly update the field value.
    mToAddressEditText.removeTextChangedListener(mToAddressWatcher);

    NetworkParameters params = mWalletService == null ? null : mWalletService.getParams();

    // Is this a bitcoin URI?
    try {//from ww  w  .j  a  va 2  s.  c  o  m
        BitcoinURI uri = new BitcoinURI(params, toval);
        Address addr = uri.getAddress();
        BigInteger amt = uri.getAmount();

        mToAddressEditText.setText(addr.toString(), TextView.BufferType.EDITABLE);

        if (amt != null) {
            long amtval = amt.longValue();
            String amtstr = mBTCFmt.format(amtval);
            mBTCAmountEditText.setText(amtstr, TextView.BufferType.EDITABLE);
        }
    } catch (BitcoinURIParseException ex) {

        // Is it just a plain address?
        try {
            Address addr = new Address(params, toval);

            mToAddressEditText.setText(addr.toString(), TextView.BufferType.EDITABLE);

        } catch (WrongNetworkException ex2) {
            String msg = mRes.getString(R.string.send_error_wrongnw);
            mLogger.warn(msg);
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        } catch (AddressFormatException ex2) {
            String msg = mRes.getString(R.string.send_error_badqr);
            mLogger.warn(msg);
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }
    }

    // Restore the field changed listener.
    mToAddressEditText.addTextChangedListener(mToAddressWatcher);
}

From source file:org.opendaylight.vpnservice.dhcpservice.DhcpExternalTunnelManager.java

public void writeDesignatedSwitchForExternalTunnel(BigInteger dpnId, IpAddress tunnelIp,
        String elanInstanceName) {
    DesignatedSwitchForTunnelKey designatedSwitchForTunnelKey = new DesignatedSwitchForTunnelKey(
            elanInstanceName, tunnelIp);
    InstanceIdentifier<DesignatedSwitchForTunnel> instanceIdentifier = InstanceIdentifier
            .builder(DesignatedSwitchesForExternalTunnels.class)
            .child(DesignatedSwitchForTunnel.class, designatedSwitchForTunnelKey).build();
    DesignatedSwitchForTunnel designatedSwitchForTunnel = new DesignatedSwitchForTunnelBuilder()
            .setDpId(dpnId.longValue()).setElanInstanceName(elanInstanceName).setTunnelRemoteIpAddress(tunnelIp)
            .setKey(designatedSwitchForTunnelKey).build();
    logger.trace("Writing into CONFIG DS tunnelIp {}, elanInstanceName {}, dpnId {}", tunnelIp,
            elanInstanceName, dpnId);/*from  w  w w . j ava2s.  c om*/
    MDSALDataStoreUtils.asyncUpdate(broker, LogicalDatastoreType.CONFIGURATION, instanceIdentifier,
            designatedSwitchForTunnel, DEFAULT_CALLBACK);
}

From source file:piuk.blockchain.android.ui.AbstractWalletActivity.java

private void handleScanPrivateKeyPair(final ECKey key) throws Exception {
    final AlertDialog.Builder b = new AlertDialog.Builder(this);

    b.setPositiveButton(R.string.sweep_text, null);

    b.setNeutralButton(R.string.import_text, null);

    b.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
        @Override/*  w  w w  .  j  a  v  a 2  s .com*/
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    b.setTitle("Scan Private Key");

    b.setMessage("Fetching Balance. Please Wait");

    final AlertDialog dialog = b.show();

    dialog.getButton(Dialog.BUTTON1).setEnabled(false);

    new Thread() {
        public void run() {
            try {
                final String address;
                if (key.isCompressed()) {
                    address = key.toAddressCompressed(MainNetParams.get()).toString();
                } else {
                    address = key.toAddressUnCompressed(MainNetParams.get()).toString();
                }

                System.out.println("Scanned PK Address " + address);

                BigInteger balance = MyRemoteWallet.getAddressBalance(address);

                final BigInteger finalBalance = balance;

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        final MyRemoteWallet remoteWallet = application.getRemoteWallet();

                        if (remoteWallet == null)
                            return;

                        dialog.getButton(Dialog.BUTTON3).setEnabled(true);

                        if (finalBalance.longValue() == 0) {
                            dialog.setMessage("The Balance of address " + address + " is zero.");
                        } else {
                            dialog.getButton(Dialog.BUTTON1).setEnabled(true);
                            dialog.setMessage(
                                    "The Balance of " + address + " is " + WalletUtils.formatValue(finalBalance)
                                            + " BTC. Would you like to sweep it?");
                        }

                        dialog.getButton(Dialog.BUTTON3).setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                if (remoteWallet.isDoubleEncrypted() == false) {
                                    reallyAddKey(dialog, key);
                                } else {
                                    if (remoteWallet.temporySecondPassword == null) {
                                        RequestPasswordDialog.show(getSupportFragmentManager(),
                                                new SuccessCallback() {

                                                    public void onSuccess() {
                                                        reallyAddKey(dialog, key);
                                                    }

                                                    public void onFail() {
                                                    }
                                                }, RequestPasswordDialog.PasswordTypeSecond);
                                    } else {
                                        reallyAddKey(dialog, key);
                                    }
                                }
                            }
                        });

                        dialog.getButton(Dialog.BUTTON1).setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                try {
                                    MyRemoteWallet wallet = new MyRemoteWallet();

                                    wallet.addKey(key, address, null);

                                    Address to = application.determineSelectedAddress();

                                    if (to == null) {
                                        handler.post(new Runnable() {
                                            public void run() {
                                                dialog.dismiss();
                                            }
                                        });

                                        return;
                                    }

                                    BigInteger baseFee = wallet.getBaseFee();

                                    wallet.simpleSendCoinsAsync(to.toString(), finalBalance.subtract(baseFee),
                                            MyRemoteWallet.FeePolicy.FeeForce, baseFee, new SendProgress() {

                                                @Override
                                                public boolean onReady(Transaction tx, BigInteger fee,
                                                        MyRemoteWallet.FeePolicy feePolicy, long priority) {
                                                    return true;
                                                }

                                                @Override
                                                public void onSend(Transaction tx, String message) {
                                                    handler.post(new Runnable() {
                                                        public void run() {
                                                            dialog.dismiss();

                                                            longToast("Private Key Successfully Swept");
                                                        }
                                                    });
                                                }

                                                @Override
                                                public ECKey onPrivateKeyMissing(String address) {
                                                    return null;
                                                }

                                                @Override
                                                public void onError(final String message) {
                                                    handler.post(new Runnable() {
                                                        public void run() {
                                                            dialog.dismiss();

                                                            longToast(message);
                                                        }
                                                    });
                                                }

                                                @Override
                                                public void onProgress(String message) {
                                                }

                                                @Override
                                                public void onStart() {
                                                }
                                            });

                                } catch (final Exception e) {
                                    e.getLocalizedMessage();

                                    handler.post(new Runnable() {
                                        public void run() {
                                            dialog.dismiss();

                                            longToast(e.getLocalizedMessage());
                                        }
                                    });
                                }
                            }
                        });
                    }
                });
            } catch (final Exception e) {
                e.printStackTrace();

                handler.post(new Runnable() {
                    public void run() {
                        dialog.dismiss();

                        longToast(e.getLocalizedMessage());
                    }
                });
            }
        }
    }.start();
}

From source file:org.opendaylight.netvirt.dhcpservice.DhcpExternalTunnelManager.java

public void writeDesignatedSwitchForExternalTunnel(BigInteger dpnId, IpAddress tunnelIp,
        String elanInstanceName) {
    DesignatedSwitchForTunnelKey designatedSwitchForTunnelKey = new DesignatedSwitchForTunnelKey(
            elanInstanceName, tunnelIp);
    InstanceIdentifier<DesignatedSwitchForTunnel> instanceIdentifier = InstanceIdentifier
            .builder(DesignatedSwitchesForExternalTunnels.class)
            .child(DesignatedSwitchForTunnel.class, designatedSwitchForTunnelKey).build();
    DesignatedSwitchForTunnel designatedSwitchForTunnel = new DesignatedSwitchForTunnelBuilder()
            .setDpId(dpnId.longValue()).setElanInstanceName(elanInstanceName).setTunnelRemoteIpAddress(tunnelIp)
            .setKey(designatedSwitchForTunnelKey).build();
    LOG.trace("Writing into CONFIG DS tunnelIp {}, elanInstanceName {}, dpnId {}", tunnelIp, elanInstanceName,
            dpnId);/*w ww . j ava  2s  .  c  o m*/
    MDSALUtil.syncUpdate(broker, LogicalDatastoreType.CONFIGURATION, instanceIdentifier,
            designatedSwitchForTunnel);
    updateLocalCache(dpnId, tunnelIp, elanInstanceName);
}

From source file:org.lwes.db.EventTemplateDB.java

/**
 * This method checks the type and range of a default value (from the ESF).
 * It returns the desired form, if allowed.
 *
 * @param type     which controls the desired object type of the value
 * @param esfValue which should be converted to fit 'type'
 * @return a value suitable for storing in a BaseType of this 'type'
 * @throws EventSystemException if the value is not acceptable for the type.
 *//*from www.  ja v  a 2  s .com*/
@SuppressWarnings("cast")
private Object canonicalizeDefaultValue(String eventName, String attributeName, FieldType type, Object esfValue)
        throws EventSystemException {
    try {
        switch (type) {
        case BOOLEAN:
            return (Boolean) esfValue;
        case BYTE:
            checkRange(eventName, attributeName, esfValue, Byte.MIN_VALUE, Byte.MAX_VALUE);
            return ((Number) esfValue).byteValue();
        case INT16:
            checkRange(eventName, attributeName, esfValue, Short.MIN_VALUE, Short.MAX_VALUE);
            return ((Number) esfValue).shortValue();
        case INT32:
            checkRange(eventName, attributeName, esfValue, Integer.MIN_VALUE, Integer.MAX_VALUE);
            return ((Number) esfValue).intValue();
        case UINT16:
            checkRange(eventName, attributeName, esfValue, 0, 0x10000);
            return ((Number) esfValue).intValue() & 0xffff;
        case UINT32:
            checkRange(eventName, attributeName, esfValue, 0, 0x100000000L);
            return ((Number) esfValue).longValue() & 0xffffffff;
        case FLOAT:
            return ((Number) esfValue).floatValue();
        case DOUBLE:
            return ((Number) esfValue).doubleValue();
        case STRING:
            return ((String) esfValue);
        case INT64: {
            if (esfValue instanceof Long) {
                return esfValue;
            }
            final BigInteger bi = (BigInteger) esfValue;
            if (bi.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0
                    || bi.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
                throw new EventSystemException(
                        String.format("Field %s.%s value %s outside allowed range [%d,%d]", eventName,
                                attributeName, esfValue, Long.MIN_VALUE, Long.MAX_VALUE));
            }
            return bi.longValue();
        }
        case UINT64: {
            if (esfValue instanceof BigInteger) {
                return esfValue;
            }
            return BigInteger.valueOf(((Number) esfValue).longValue());
        }
        case IPADDR:
            return ((IPAddress) esfValue);
        case BOOLEAN_ARRAY:
        case BYTE_ARRAY:
        case DOUBLE_ARRAY:
        case FLOAT_ARRAY:
        case INT16_ARRAY:
        case INT32_ARRAY:
        case INT64_ARRAY:
        case IP_ADDR_ARRAY:
        case STRING_ARRAY:
        case UINT16_ARRAY:
        case UINT32_ARRAY:
        case UINT64_ARRAY:
        case NBOOLEAN_ARRAY:
        case NBYTE_ARRAY:
        case NDOUBLE_ARRAY:
        case NFLOAT_ARRAY:
        case NINT16_ARRAY:
        case NINT32_ARRAY:
        case NINT64_ARRAY:
        case NSTRING_ARRAY:
        case NUINT16_ARRAY:
        case NUINT32_ARRAY:
        case NUINT64_ARRAY:
            throw new EventSystemException("Unsupported default value type " + type);
        }
        throw new EventSystemException("Unrecognized type " + type + " for value " + esfValue);
    } catch (ClassCastException e) {
        throw new EventSystemException("Type " + type + " had an inappropriate default value " + esfValue);
    }
}

From source file:org.tvheadend.tvhclient.htsp.HTSService.java

private void onQueueStatus(HTSMessage msg) {
    TVHClientApplication app = (TVHClientApplication) getApplication();
    Subscription sub = app.getSubscription(msg.getLong("subscriptionId"));
    if (sub == null) {
        return;/*from   www  .  j a  va  2 s .  co  m*/
    }
    if (msg.containsField("delay")) {
        BigInteger delay = msg.getBigInteger("delay");
        delay = delay.divide(BigInteger.valueOf((1000)));
        sub.delay = delay.longValue();
    }
    sub.droppedBFrames = msg.getLong("Bdrops", sub.droppedBFrames);
    sub.droppedIFrames = msg.getLong("Idrops", sub.droppedIFrames);
    sub.droppedPFrames = msg.getLong("Pdrops", sub.droppedPFrames);
    sub.packetCount = msg.getLong("packets", sub.packetCount);
    sub.queSize = msg.getLong("bytes", sub.queSize);

    app.updateSubscription(sub);
}

From source file:piuk.MyRemoteWallet.java

public Pair<Transaction, Long> makeTransaction(KeyBag keyWallet, List<MyTransactionOutPoint> unspent,
        String toAddress, String changeAddress, BigInteger amount, BigInteger baseFee,
        boolean consumeAllOutputs) throws Exception {

    long priority = 0;

    if (unspent == null || unspent.size() == 0)
        throw new InsufficientFundsException("No free outputs to spend.");

    if (amount == null || amount.compareTo(BigInteger.ZERO) <= 0)
        throw new Exception("You must provide an amount");

    //Construct a new transaction
    Transaction tx = new Transaction(params);

    final Script toOutputScript = ScriptBuilder.createOutputScript(new Address(MainNetParams.get(), toAddress));

    final TransactionOutput output = new TransactionOutput(params, null, Coin.valueOf(amount.longValue()),
            toOutputScript.getProgram());

    tx.addOutput(output);/*  ww w.  j  av  a  2 s .c o m*/

    //Now select the appropriate inputs
    BigInteger valueSelected = BigInteger.ZERO;
    BigInteger valueNeeded = amount.add(baseFee);
    BigInteger minFreeOutputSize = BigInteger.valueOf(1000000);

    for (MyTransactionOutPoint outPoint : unspent) {

        Script scriptPubKey = outPoint.getConnectedOutput().getScriptPubKey();

        if (scriptPubKey == null) {
            throw new Exception("scriptPubKey is null");
        }

        final ECKey key = keyWallet.findKeyFromPubHash(scriptPubKey.getPubKeyHash());

        if (key == null) {
            throw new Exception("Unable to find ECKey for scriptPubKey " + scriptPubKey);
        }

        MyTransactionInput input = new MyTransactionInput(params, null, new byte[0], outPoint);

        tx.addInput(input);

        input.setScriptSig(scriptPubKey.createEmptyInputScript(key, null));

        valueSelected = valueSelected.add(BigInteger.valueOf(outPoint.getValue().longValue()));

        priority += outPoint.getValue().longValue() * outPoint.confirmations;

        if (!consumeAllOutputs) {
            if (valueSelected.compareTo(valueNeeded) == 0
                    || valueSelected.compareTo(valueNeeded.add(minFreeOutputSize)) >= 0)
                break;
        }
    }

    //Check the amount we have selected is greater than the amount we need
    if (valueSelected.compareTo(valueNeeded) < 0) {
        throw new InsufficientFundsException("Insufficient Funds");
    }

    long estimatedSize = tx.bitcoinSerialize().length + (138 * tx.getInputs().size());

    BigInteger fee = BigInteger.valueOf((int) Math.ceil(estimatedSize / 1000d)).multiply(baseFee);

    BigInteger change = valueSelected.subtract(amount).subtract(fee);

    if (change.compareTo(BigInteger.ZERO) < 0) {
        throw new Exception("Insufficient Value for Fee. Fix this lazy.");
    } else if (change.compareTo(BigInteger.ZERO) > 0) {
        //Now add the change if there is any
        final Script change_script = ScriptBuilder
                .createOutputScript(new Address(MainNetParams.get(), changeAddress));

        TransactionOutput change_output = new TransactionOutput(params, null, Coin.valueOf(change.longValue()),
                change_script.getProgram());

        tx.addOutput(change_output);
    }

    estimatedSize = tx.bitcoinSerialize().length + (138 * tx.getInputs().size());

    priority /= estimatedSize;

    return new Pair<Transaction, Long>(tx, priority);
}

From source file:com.thoughtworks.go.server.persistence.MaterialRepository.java

private long modificationAfter(final long id, final MaterialInstance materialInstance) {
    BigInteger result = (BigInteger) getHibernateTemplate().execute((HibernateCallback) session -> {
        String sql = "SELECT id " + " FROM modifications " + " WHERE materialId = ? " + "        AND id > ?"
                + " ORDER BY id" + " LIMIT 1";
        SQLQuery query = session.createSQLQuery(sql);
        query.setLong(0, materialInstance.getId());
        query.setLong(1, id);//  w w  w  . ja v  a2  s  .c  o m
        return query.uniqueResult();
    });
    return result == null ? id : result.longValue();
}