Example usage for java.math BigInteger compareTo

List of usage examples for java.math BigInteger compareTo

Introduction

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

Prototype

public int compareTo(BigInteger val) 

Source Link

Document

Compares this BigInteger with the specified BigInteger.

Usage

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

/**
 * Reads the current board directory and constructs the list of available boards
 *//*w  w w  .j a  v a2  s  .c  om*/
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:piuk.blockchain.android.MyRemoteWallet.java

public Pair<Transaction, Long> makeTransaction(boolean isSimpleSend, List<MyTransactionOutPoint> unspent,
        HashMap<String, BigInteger> receivingAddresses, BigInteger fee, final String changeAddress)
        throws Exception {

    long priority = 0;

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

    if (fee == null)
        fee = BigInteger.ZERO;//from  w  ww . j  a  v  a 2  s . co m

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

    BigInteger outputValueSum = BigInteger.ZERO;

    for (Iterator<Entry<String, BigInteger>> iterator = receivingAddresses.entrySet().iterator(); iterator
            .hasNext();) {
        Map.Entry<String, BigInteger> mapEntry = iterator.next();
        String toAddress = mapEntry.getKey();
        BigInteger amount = mapEntry.getValue();

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

        outputValueSum = outputValueSum.add(amount);
        //Add the output
        BitcoinScript toOutputScript = BitcoinScript.createSimpleOutBitoinScript(new BitcoinAddress(toAddress));
        //         Log.d("MyRemoteWallet", "MyRemoteWallet makeTransaction toAddress: " + toAddress + "amount: " + amount);

        TransactionOutput output = new TransactionOutput(getParams(), null, amount,
                toOutputScript.getProgram());

        tx.addOutput(output);
    }

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

    MyTransactionOutPoint changeOutPoint = null;

    for (MyTransactionOutPoint outPoint : unspent) {

        BitcoinScript script = new BitcoinScript(outPoint.getScriptBytes());

        if (script.getOutType() == BitcoinScript.ScriptOutTypeStrange)
            continue;

        BitcoinScript inputScript = new BitcoinScript(outPoint.getConnectedPubKeyScript());
        String address = inputScript.getAddress().toString();

        //if isSimpleSend don't use address as input if is output 
        if (isSimpleSend && receivingAddresses.get(address) != null)
            continue;

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

        input.outpoint = outPoint;
        //         Log.d("MyRemoteWallet", "MyRemoteWallet makeTransaction fromAddress: " + address + "amount: " + outPoint.value);

        tx.addInput(input);

        valueSelected = valueSelected.add(outPoint.value);

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

        if (changeAddress == null)
            changeOutPoint = outPoint;

        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");
    }

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

    //Now add the change if there is any
    if (change.compareTo(BigInteger.ZERO) > 0) {
        BitcoinScript change_script;
        if (changeAddress != null) {
            change_script = BitcoinScript.createSimpleOutBitoinScript(new BitcoinAddress(changeAddress));
            //            Log.d("MyRemoteWallet", "MyRemoteWallet makeTransaction changeAddress != null: " + changeAddress + "change: " + change);
        } else if (changeOutPoint != null) {
            BitcoinScript inputScript = new BitcoinScript(changeOutPoint.getConnectedPubKeyScript());
            //             Log.d("MyRemoteWallet", "MyRemoteWallet makeTransaction changeAddress == null: " + inputScript.getAddress() + "change: " + change);

            //Return change to the first address
            change_script = BitcoinScript.createSimpleOutBitoinScript(inputScript.getAddress());
        } else {
            throw new Exception("Invalid transaction attempt");
        }
        TransactionOutput change_output = new TransactionOutput(getParams(), null, change,
                change_script.getProgram());

        tx.addOutput(change_output);
    }

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

    priority /= estimatedSize;

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

From source file:piuk.blockchain.android.MyRemoteWallet.java

private void sendCoinsAsync(final boolean isSimpleSend, final HashMap<String, BigInteger> sendingAddresses,
        final HashMap<String, BigInteger> receivingAddresses, final FeePolicy feePolicy, final BigInteger fee,
        final String changeAddress, final SendProgress progress) {

    new Thread() {
        @Override//from   www.jav  a 2  s  . co  m
        public void run() {
            progress.onStart();

            final BigInteger feeAmount;
            if (fee == null)
                feeAmount = BigInteger.ZERO;
            else
                feeAmount = fee;

            final List<ECKey> tempKeys = new ArrayList<ECKey>();

            try {

                //Construct a new transaction
                progress.onProgress("Getting Unspent Outputs");

                List<String> from = new ArrayList<String>(sendingAddresses.keySet());
                List<MyTransactionOutPoint> allUnspent = getUnspentOutputPoints(
                        from.toArray(new String[from.size()]));

                Pair<Transaction, Long> pair = null;

                progress.onProgress("Constructing Transaction");

                try {
                    //Try without asking for watch only addresses
                    List<MyTransactionOutPoint> unspent = filter(allUnspent, tempKeys, false, progress);

                    if (isSimpleSend) {
                        pair = makeTransaction(isSimpleSend, unspent, receivingAddresses, feeAmount,
                                changeAddress);
                    } else {
                        pair = makeTransactionCustom(sendingAddresses, unspent, receivingAddresses, feeAmount,
                                changeAddress);
                    }

                    //Transaction cancelled
                    if (pair == null)
                        return;
                } catch (InsufficientFundsException e) {

                    //Try with asking for watch only
                    List<MyTransactionOutPoint> unspent = filter(allUnspent, tempKeys, true, progress);

                    if (isSimpleSend) {
                        pair = makeTransaction(isSimpleSend, unspent, receivingAddresses, feeAmount,
                                changeAddress);
                    } else {
                        pair = makeTransactionCustom(sendingAddresses, unspent, receivingAddresses, feeAmount,
                                changeAddress);
                    }

                    //Transaction cancelled
                    if (pair == null)
                        return;
                }

                Transaction tx = pair.first;
                Long priority = pair.second;

                if (isSimpleSend) {
                    //If returns false user cancelled
                    //Probably because they want to recreate the transaction with different fees
                    if (!progress.onReady(tx, feeAmount, feePolicy, priority))
                        return;
                }

                progress.onProgress("Signing Inputs");

                Wallet wallet = new Wallet(MainNetParams.get());
                for (TransactionInput input : tx.getInputs()) {
                    byte[] scriptBytes = input.getOutpoint().getConnectedPubKeyScript();
                    String address = new BitcoinScript(scriptBytes).getAddress().toString();
                    final ECKey walletKey;
                    try {
                        walletKey = getECKey(address);
                    } catch (Exception e) {
                        // skip add Watch Only Bitcoin Address key because already accounted for  later with tempKeys
                        continue;
                    }
                    ECKey keyCompressed;
                    ECKey keyUnCompressed;
                    BigInteger priv = new BigInteger(walletKey.getPrivKeyBytes());
                    if (priv.compareTo(BigInteger.ZERO) >= 0) {
                        keyCompressed = new ECKey(priv, null, true);
                        keyUnCompressed = new ECKey(priv, null, false);
                    } else {
                        byte[] appendZeroByte = ArrayUtils.addAll(new byte[1], walletKey.getPrivKeyBytes());
                        BigInteger priv2 = new BigInteger(appendZeroByte);
                        keyCompressed = new ECKey(priv2, null, true);
                        keyUnCompressed = new ECKey(priv2, null, false);
                    }

                    if (keyCompressed != null) {
                        wallet.addKey(keyCompressed);
                    }

                    if (keyUnCompressed != null) {
                        wallet.addKey(keyUnCompressed);
                    }
                }

                wallet.addKeys(tempKeys);

                //Now sign the inputs
                tx.signInputs(SigHash.ALL, wallet);

                progress.onProgress("Broadcasting Transaction");

                String response = pushTx(tx);

                progress.onSend(tx, response);

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

                progress.onError(e.getLocalizedMessage());

            }
        }
    }.start();
}

From source file:piuk.blockchain.android.MyRemoteWallet.java

public Pair<Transaction, Long> makeTransactionCustom(final HashMap<String, BigInteger> sendingAddresses,
        List<MyTransactionOutPoint> unspent, HashMap<String, BigInteger> receivingAddresses, BigInteger fee,
        final String changeAddress) throws Exception {

    long priority = 0;

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

    if (fee == null)
        fee = BigInteger.ZERO;//  w  w w  .  java 2  s. c om

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

    BigInteger outputValueSum = BigInteger.ZERO;

    for (Iterator<Entry<String, BigInteger>> iterator = receivingAddresses.entrySet().iterator(); iterator
            .hasNext();) {
        Map.Entry<String, BigInteger> mapEntry = iterator.next();
        String toAddress = mapEntry.getKey();
        BigInteger amount = mapEntry.getValue();

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

        outputValueSum = outputValueSum.add(amount);
        //Add the output
        BitcoinScript toOutputScript = BitcoinScript.createSimpleOutBitoinScript(new BitcoinAddress(toAddress));
        //         Log.d("MyRemoteWallet", "MyRemoteWallet makeTransactionCustom toAddress: " + toAddress + "amount: " + amount);

        TransactionOutput output = new TransactionOutput(getParams(), null, amount,
                toOutputScript.getProgram());
        tx.addOutput(output);
    }

    //Now select the appropriate inputs
    BigInteger valueSelected = BigInteger.ZERO;
    BigInteger valueNeeded = outputValueSum.add(fee);

    Map<String, BigInteger> addressTotalUnspentValues = new HashMap<String, BigInteger>();

    for (MyTransactionOutPoint outPoint : unspent) {

        BitcoinScript script = new BitcoinScript(outPoint.getScriptBytes());

        if (script.getOutType() == BitcoinScript.ScriptOutTypeStrange)
            continue;

        BitcoinScript inputScript = new BitcoinScript(outPoint.getConnectedPubKeyScript());
        String address = inputScript.getAddress().toString();

        BigInteger addressSendAmount = sendingAddresses.get(address);
        if (addressSendAmount == null) {
            throw new Exception("Invalid transaction address send amount is null");
        }

        final BigInteger addressTotalUnspentValue = addressTotalUnspentValues.get(address);

        if (addressTotalUnspentValue == null) {
            addressTotalUnspentValues.put(address, outPoint.value);
        } else {
            addressTotalUnspentValues.put(address, addressTotalUnspentValue.add(outPoint.value));
        }

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

        input.outpoint = outPoint;
        //         Log.d("MyRemoteWallet", "MyRemoteWallet makeTransactionCustom fromAddress: " + address + "amount: " + outPoint.value);

        tx.addInput(input);

        valueSelected = valueSelected.add(outPoint.value);

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

        //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");
    }

    //decide change
    if (changeAddress == null) {
        BigInteger feeAmountLeftToAccountedFor = fee;

        for (Iterator<Entry<String, BigInteger>> iterator = addressTotalUnspentValues.entrySet()
                .iterator(); iterator.hasNext();) {
            final Entry<String, BigInteger> entry = iterator.next();
            final String address = entry.getKey();
            final BigInteger addressTotalUnspentValue = entry.getValue();
            final BigInteger addressSendAmount = sendingAddresses.get(address);
            BigInteger addressChangeAmount = addressTotalUnspentValue.subtract(addressSendAmount);

            if (feeAmountLeftToAccountedFor.compareTo(BigInteger.ZERO) > 0) {

                if (addressChangeAmount.compareTo(feeAmountLeftToAccountedFor) >= 0) {
                    //have enough to fill fee
                    addressChangeAmount = addressChangeAmount.subtract(feeAmountLeftToAccountedFor);
                    feeAmountLeftToAccountedFor = BigInteger.ZERO;
                } else {
                    // do not have enough to fill fee
                    feeAmountLeftToAccountedFor = feeAmountLeftToAccountedFor.subtract(addressChangeAmount);
                    addressChangeAmount = BigInteger.ZERO;
                }
            }

            if (addressChangeAmount.compareTo(BigInteger.ZERO) > 0) {
                //Add the output
                BitcoinScript toOutputScript = BitcoinScript
                        .createSimpleOutBitoinScript(new BitcoinAddress(address));
                //                Log.d("MyRemoteWallet", "MyRemoteWallet makeTransactionCustom changeAddress == null: " + address + "addressChangeAmount: " + addressChangeAmount);

                TransactionOutput output = new TransactionOutput(getParams(), null, addressChangeAmount,
                        toOutputScript.getProgram());

                tx.addOutput(output);
            }
        }
    } else {
        BigInteger addressChangeAmountSum = BigInteger.ZERO;
        for (Iterator<Entry<String, BigInteger>> iterator = addressTotalUnspentValues.entrySet()
                .iterator(); iterator.hasNext();) {
            final Entry<String, BigInteger> entry = iterator.next();
            final String address = entry.getKey();
            final BigInteger addressTotalUnspentValue = entry.getValue();
            final BigInteger addressSendAmount = sendingAddresses.get(address);
            final BigInteger addressChangeAmount = addressTotalUnspentValue.subtract(addressSendAmount);
            addressChangeAmountSum = addressChangeAmountSum.add(addressChangeAmount);
        }

        if (addressChangeAmountSum.compareTo(BigInteger.ZERO) > 0) {
            //Add the output
            BitcoinScript toOutputScript = BitcoinScript
                    .createSimpleOutBitoinScript(new BitcoinAddress(changeAddress));

            TransactionOutput output = new TransactionOutput(getParams(), null,
                    addressChangeAmountSum.subtract(fee), toOutputScript.getProgram());
            //             Log.d("MyRemoteWallet", "MyRemoteWallet makeTransactionCustom changeAddress != null: " + changeAddress + "addressChangeAmount: " + output.getValue());
            tx.addOutput(output);
        }
    }

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

    priority /= estimatedSize;

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

From source file:piuk.blockchain.android.MyRemoteWallet.java

private void sendCoinsToFriend(final String sendType, final String emailOrNumber, final BigInteger amount,
        final FeePolicy feePolicy, final BigInteger fee, final SendProgress progress) throws Exception {

    new Thread() {
        @Override//ww w.j  av  a  2  s .  c  o  m
        public void run() {
            progress.onStart();
            final List<ECKey> tempKeys = new ArrayList<ECKey>();

            try {
                final String[] from = getActiveAddresses();
                final ECKey key;
                Pair<ECKey, String> keyAndMiniKey = null;
                /*
                if (sendType == "sms") {
                   keyAndMiniKey = generateNewMiniPrivateKey();
                   key = keyAndMiniKey.first;                     
                } else {
                   key = generateECKey();
                }
                */
                keyAndMiniKey = generateNewMiniPrivateKey();
                key = keyAndMiniKey.first;

                //Construct a new transaction
                progress.onProgress("Getting Unspent Outputs");

                List<MyTransactionOutPoint> allUnspent = getUnspentOutputPoints(from);

                Pair<Transaction, Long> pair = null;

                progress.onProgress("Constructing Transaction");

                final DumpedPrivateKey dumpedPrivateKey = key.getPrivateKeyEncoded(getParams());
                String privateKey = Base58.encode(dumpedPrivateKey.bytes);

                final String toAddress = key.toAddress(getParams()).toString();
                /*
                Log.d("sendCoinsToFriend", "sendCoinsToFriend: privateKey: " + privateKey);
                Log.d("sendCoinsToFriend", "sendCoinsToFriend: toAddress: " + toAddress);
                */

                try {
                    //Try without asking for watch only addresses
                    List<MyTransactionOutPoint> unspent = filter(allUnspent, tempKeys, false, progress);
                    HashMap<String, BigInteger> receivingAddresses = new HashMap<String, BigInteger>();
                    receivingAddresses.put(toAddress, amount);
                    pair = makeTransaction(false, unspent, receivingAddresses, fee, null);

                    //Transaction cancelled
                    if (pair == null)
                        return;
                } catch (InsufficientFundsException e) {

                    //Try with asking for watch only
                    List<MyTransactionOutPoint> unspent = filter(allUnspent, tempKeys, true, progress);
                    HashMap<String, BigInteger> receivingAddresses = new HashMap<String, BigInteger>();
                    receivingAddresses.put(toAddress, amount);
                    pair = makeTransaction(false, unspent, receivingAddresses, fee, null);

                    //Transaction cancelled
                    if (pair == null)
                        return;
                }

                if (allUnspent != null) {
                    Transaction tx = pair.first;

                    progress.onProgress("Signing Inputs");

                    Wallet wallet = new Wallet(MainNetParams.get());
                    for (TransactionInput input : tx.getInputs()) {
                        byte[] scriptBytes = input.getOutpoint().getConnectedPubKeyScript();
                        String address = new BitcoinScript(scriptBytes).getAddress().toString();
                        final ECKey walletKey;
                        try {
                            walletKey = getECKey(address);
                        } catch (Exception e) {
                            // skip add Watch Only Bitcoin Address key because already accounted for  later with tempKeys
                            continue;
                        }
                        ECKey keyCompressed;
                        ECKey keyUnCompressed;
                        BigInteger priv = new BigInteger(walletKey.getPrivKeyBytes());
                        if (priv.compareTo(BigInteger.ZERO) >= 0) {
                            keyCompressed = new ECKey(priv, null, true);
                            keyUnCompressed = new ECKey(priv, null, false);
                        } else {
                            byte[] appendZeroByte = ArrayUtils.addAll(new byte[1], walletKey.getPrivKeyBytes());
                            BigInteger priv2 = new BigInteger(appendZeroByte);
                            keyCompressed = new ECKey(priv2, null, true);
                            keyUnCompressed = new ECKey(priv2, null, false);
                        }

                        if (keyCompressed != null) {
                            wallet.addKey(keyCompressed);
                        }

                        if (keyUnCompressed != null) {
                            wallet.addKey(keyUnCompressed);
                        }
                    }

                    wallet.addKeys(tempKeys);

                    //Now sign the inputs
                    tx.signInputs(SigHash.ALL, wallet);

                    progress.onProgress("Broadcasting Transaction");

                    final String txHash = tx.getHashAsString();

                    /*
                    Log.d("sendCoinsToFriend", "sendCoinsToFriend: txHash: " + txHash);                  
                    Log.d("sendCoinsToFriend", "sendCoinsToFriend: emailOrNumber: " + emailOrNumber);
                    */

                    Map<Object, Object> params = new HashMap<Object, Object>();
                    params.put("type", sendType);
                    //                  Log.d("sendCoinsToFriend", "type:" + sendType);
                    String privParameter = (sendType == "sms") ? keyAndMiniKey.second : privateKey;
                    params.put("priv", privParameter);
                    params.put("hash", txHash);
                    params.put("to", emailOrNumber);
                    //                  Log.d("sendCoinsToFriend", "to:" + emailOrNumber);
                    params.put("guid", getGUID());
                    params.put("sharedKey", getSharedKey());

                    try {
                        String response = WalletUtils.postURLWithParams(WebROOT + "send-via", params);
                        if (response != null && response.length() > 0) {
                            progress.onProgress("Send Transaction");
                            //                        Log.d("sendCoinsToFriend", "sendCoinsToFriend: send-via response: " + response);
                            String response2 = pushTx(tx);
                            if (response2 != null && response2.length() > 0) {
                                //                           Log.d("sendCoinsToFriend", "sendCoinsToFriend: pushTx response: " + response2);
                                progress.onSend(tx, response2);

                                String label = sendType == "email" ? emailOrNumber + " Sent Via Email"
                                        : emailOrNumber + " Sent Via SMS";
                                addKey(key, toAddress, label);
                                setTag(toAddress, 2);
                            }
                        }
                    } catch (Exception e) {
                        progress.onError(e.getMessage());
                        e.printStackTrace();
                    }
                }

            } catch (Exception e) {
                progress.onError(e.getMessage());
                e.printStackTrace();
            }

        }
    }.start();

}

From source file:piuk.blockchain.android.MyRemoteWallet.java

public void sendCoinsAsync(final HashMap<String, BigInteger> sendingAddresses, final String toAddress,
        final BigInteger amount, final FeePolicy feePolicy, final BigInteger fee, final String changeAddress,
        final SendProgress progress) {
    BigInteger sum = BigInteger.ZERO;
    for (Iterator<Entry<String, BigInteger>> iterator = sendingAddresses.entrySet().iterator(); iterator
            .hasNext();) {// w ww .j ava  2 s  .  c om
        Entry<String, BigInteger> entry = iterator.next();
        sum = sum.add(entry.getValue());
    }

    if (sum.compareTo(amount) != 0) {
        progress.onError("Internal error input amounts not validating correctly");
        return;
    }

    HashMap<String, BigInteger> receivingAddresses = new HashMap<String, BigInteger>();
    receivingAddresses.put(toAddress, amount);

    sendCoinsAsync(false, sendingAddresses, receivingAddresses, feePolicy, fee, changeAddress, progress);
}

From source file:com.cisco.dvbu.ps.common.util.CommonUtils.java

/**
 * compareFiles - compare two files based on checksum.
 * @modified Jan. 15 2014 by SST. //from  w  ww. java2s  .co  m
 * @comment    before the change on Jan.15 this method returned false when both files being compared are empty;
 *           so it was decided to change that initial approach, because having both files 0 length is a valid 
 *           scenario.
 *           another change is to use row-based checksums instead of checksum of the whole file; so now instead of 
 *           fileChecksum, method fileChecksumByRow is used.  
 * 
 * @param filePath1 - file path for file1
 * @param filePath2 - file path for file2
 * @return result - comparison: true=files are the same, false=files are different
 */
public static boolean compareFiles(String filePath1, String filePath2) throws CompositeException {
    boolean result = false;

    BigInteger sum1 = new BigInteger("0");
    BigInteger sum2 = new BigInteger("0");

    try {
        if (fileExists(filePath1))
            sum1 = fileChecksumByRow(filePath1);
        else
            throw new ApplicationException("File not found at path: " + filePath1);
        if (fileExists(filePath1))
            sum2 = fileChecksumByRow(filePath2);
        else
            throw new ApplicationException("File not found at path: " + filePath2);

        if (sum1 != null && // object sum1 is not null 
                sum2 != null && // object sum2 is not null 
                (sum1.compareTo(sum2) == 0) // sum1 and sum2 contain the same value. 
        ) {
            result = true;
        }
    } catch (Exception e) {
        throw new CompositeException(e);
    }
    return result;
}

From source file:com.cisco.dvbu.ps.deploytool.services.DataSourceManagerImpl.java

private void populateAttributesFromRelationalDataSource(DataSourceChoiceType datasource,
        AttributeList dsAttributeList) {

    String defaultPropertyFile = CommonConstants.propertyFile;
    /*  Determine the property file name for this environment
     *    1. Start with default file CommonConstants.propertyFile
     *    2. Get Java Environment variables
     *    3. Get OS System Environment variables
     *///from  w w  w. ja  v a2s  . c o  m
    String propertyFile = CommonUtils.getFileOrSystemPropertyValue(defaultPropertyFile, "CONFIG_PROPERTY_FILE");
    // Set a default value if not found
    if (propertyFile == null || propertyFile.trim().length() == 0) {
        propertyFile = defaultPropertyFile;
    }
    String prefix = "DataSourcemanagerImpl.populateAttributesFromRelationalDataSource";

    // Add attribute if not null and empty
    if (datasource.getRelationalDataSource().getHostname() != null
            && datasource.getRelationalDataSource().getHostname().length() > 0) {
        Attribute attrHost = new Attribute();
        attrHost.setName("urlIP");
        attrHost.setType(AttributeType.STRING);
        // Extract and resolve variables used in the value attribute
        String value = CommonUtils.extractVariable(prefix, datasource.getRelationalDataSource().getHostname(),
                propertyFile, false);
        attrHost.setValue(value);
        dsAttributeList.getAttribute().add(attrHost);
    }

    // Add attribute if not null and greater than 0
    if (datasource.getRelationalDataSource().getPort() != null) {
        Attribute attrUrlPort = new Attribute();
        attrUrlPort.setName("urlPort");
        attrUrlPort.setType(AttributeType.INTEGER);
        // Extract and resolve variables used in the value attribute
        String value = CommonUtils.extractVariable(prefix,
                datasource.getRelationalDataSource().getPort().toString(), propertyFile, false);
        // Convert the resolved string value to big integer to verify that it is an integer value.
        BigInteger intPort = new BigInteger(value);
        // Only set the value if the port number is greater than 0
        if (intPort.compareTo(BigInteger.ZERO) == 1) {
            attrUrlPort.setValue(value);
            dsAttributeList.getAttribute().add(attrUrlPort);
        }
    }

    // Add attribute if not null and empty
    if (datasource.getRelationalDataSource().getDatabaseName() != null
            && datasource.getRelationalDataSource().getDatabaseName().length() > 0) {
        Attribute attrDbName = new Attribute();
        attrDbName.setName("urlDatabaseName");
        attrDbName.setType(AttributeType.STRING);
        // Extract and resolve variables used in the value attribute
        String value = CommonUtils.extractVariable(prefix,
                datasource.getRelationalDataSource().getDatabaseName(), propertyFile, false);
        attrDbName.setValue(value);
        dsAttributeList.getAttribute().add(attrDbName);
    }

    // Add attribute if not null and empty
    if (datasource.getRelationalDataSource().getLogin() != null
            && datasource.getRelationalDataSource().getLogin().length() > 0) {
        Attribute attrLogin = new Attribute();
        attrLogin.setName("login");
        attrLogin.setType(AttributeType.STRING);
        // Extract and resolve variables used in the value attribute
        String value = CommonUtils.extractVariable(prefix, datasource.getRelationalDataSource().getLogin(),
                propertyFile, false);
        attrLogin.setValue(value);
        dsAttributeList.getAttribute().add(attrLogin);
    }

    // Add attribute if not null and empty
    if (datasource.getRelationalDataSource().getEncryptedPassword() != null
            && datasource.getRelationalDataSource().getEncryptedPassword().length() > 0) {
        Attribute attrPassword = new Attribute();
        attrPassword.setName("password");
        attrPassword.setType(AttributeType.PASSWORD_STRING);
        attrPassword.setValue(CommonUtils.decrypt(datasource.getRelationalDataSource().getEncryptedPassword()));
        dsAttributeList.getAttribute().add(attrPassword);
    }

    // Add attribute if not null and empty
    if (datasource.getRelationalDataSource().getValQuery() != null
            && datasource.getRelationalDataSource().getValQuery().length() > 0) {
        Attribute attrValQuery = new Attribute();
        attrValQuery.setName("connValidateQuery");
        attrValQuery.setType(AttributeType.STRING);
        // Extract and resolve variables used in the value attribute
        String value = CommonUtils.extractVariable(prefix, datasource.getRelationalDataSource().getValQuery(),
                propertyFile, false);
        attrValQuery.setValue(value);
        dsAttributeList.getAttribute().add(attrValQuery);
    }
}

From source file:piuk.MyBlockChain.java

@SuppressWarnings("unchecked")
public void onMessage(WebSocketMessage wmessage) {

    System.out.println("OnMessage()");

    try {/*from  w  ww .jav a  2 s  .co m*/
        String message = wmessage.getText();

        System.out.println("Websocket() onMessage() " + message);

        Map<String, Object> top = (Map<String, Object>) JSONValue.parse(message);

        if (top == null)
            return;

        String op = (String) top.get("op");

        if (op.equals("block")) {
            Map<String, Object> x = (Map<String, Object>) top.get("x");

            Sha256Hash hash = new Sha256Hash(Hex.decode((String) x.get("hash")));
            int blockIndex = ((Number) x.get("blockIndex")).intValue();
            int blockHeight = ((Number) x.get("height")).intValue();
            long time = ((Number) x.get("time")).longValue();

            MyBlock block = new MyBlock(Constants.NETWORK_PARAMETERS);
            block.hash = hash;
            block.blockIndex = blockIndex;
            block.time = time;

            this.latestBlock = new StoredBlock(block, BigInteger.ZERO, blockHeight);

            List<MyTransaction> transactions = remoteWallet.getMyTransactions();
            List<Number> txIndexes = (List<Number>) x.get("txIndexes");
            for (Number txIndex : txIndexes) {
                for (MyTransaction tx : transactions) {

                    MyTransactionConfidence confidence = (MyTransactionConfidence) tx.getConfidence();

                    if (tx.txIndex == txIndex.intValue() && confidence.height != blockHeight) {
                        confidence.height = blockHeight;
                        confidence.runListeners();
                    }
                }
            }

            for (PeerEventListener listener : listeners) {
                listener.onBlocksDownloaded(null, block, 0);
            }

        } else if (op.equals("utx")) {
            Map<String, Object> x = (Map<String, Object>) top.get("x");

            WalletTransaction tx = MyTransaction.fromJSONDict(x);

            BigInteger result = BigInteger.ZERO;

            BigInteger previousBalance = remoteWallet.getBitcoinJWallet().final_balance;

            for (TransactionInput input : tx.getTransaction().getInputs()) {
                //if the input is from me subtract the value
                MyTransactionInput myinput = (MyTransactionInput) input;

                if (remoteWallet.isAddressMine(input.getFromAddress().toString())) {
                    result = result.subtract(myinput.value);

                    remoteWallet
                            .getBitcoinJWallet().final_balance = remoteWallet.getBitcoinJWallet().final_balance
                                    .subtract(myinput.value);
                    remoteWallet.getBitcoinJWallet().total_sent = remoteWallet.getBitcoinJWallet().total_sent
                            .add(myinput.value);
                }
            }

            for (TransactionOutput output : tx.getTransaction().getOutputs()) {
                //if the input is from me subtract the value
                MyTransactionOutput myoutput = (MyTransactionOutput) output;

                if (remoteWallet.isAddressMine(myoutput.getToAddress().toString())) {
                    result = result.add(myoutput.getValue());

                    remoteWallet
                            .getBitcoinJWallet().final_balance = remoteWallet.getBitcoinJWallet().final_balance
                                    .add(myoutput.getValue());
                    remoteWallet
                            .getBitcoinJWallet().total_received = remoteWallet.getBitcoinJWallet().total_sent
                                    .add(myoutput.getValue());
                }
            }

            MyTransaction mytx = (MyTransaction) tx.getTransaction();

            mytx.result = result;

            remoteWallet.getBitcoinJWallet().addWalletTransaction(tx);

            if (result.compareTo(BigInteger.ZERO) >= 0) {
                System.out.println("On Received");

                remoteWallet.getBitcoinJWallet().invokeOnCoinsReceived(tx.getTransaction(), previousBalance,
                        remoteWallet.getBitcoinJWallet().final_balance);
            } else {
                remoteWallet.getBitcoinJWallet().invokeOnCoinsSent(tx.getTransaction(), previousBalance,
                        remoteWallet.getBitcoinJWallet().final_balance);
            }
        } else if (op.equals("on_change")) {
            String newChecksum = (String) top.get("checksum");
            String oldChecksum = remoteWallet.getChecksum();

            System.out.println("On change " + newChecksum + " " + oldChecksum);

            if (!newChecksum.equals(oldChecksum)) {
                try {
                    String newPayload = MyRemoteWallet.getWalletPayload(remoteWallet.getGUID(),
                            remoteWallet.getSharedKey(), oldChecksum);

                    if (newPayload == null)
                        return;

                    remoteWallet.setPayload(newPayload);

                    remoteWallet.getBitcoinJWallet().invokeOnChange();

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

            }

        }

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

From source file:com.cloud.network.NetworkModelImpl.java

@Override
public boolean isIP6AddressAvailableInVlan(long vlanId) {
    VlanVO vlan = _vlanDao.findById(vlanId);
    if (vlan.getIp6Range() == null) {
        return false;
    }//from w  w w  .j a  v a  2  s  .c o  m
    long existedCount = _ipv6Dao.countExistedIpsInVlan(vlanId);
    BigInteger existedInt = BigInteger.valueOf(existedCount);
    BigInteger rangeInt = NetUtils.countIp6InRange(vlan.getIp6Range());
    return (existedInt.compareTo(rangeInt) < 0);
}