Example usage for java.math BigInteger ZERO

List of usage examples for java.math BigInteger ZERO

Introduction

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

Prototype

BigInteger ZERO

To view the source code for java.math BigInteger ZERO.

Click Source Link

Document

The BigInteger constant zero.

Usage

From source file:org.multibit.viewsystem.swing.action.SendAssetConfirmAction.java

/**
 * Complete the transaction to work out the fee) and then show the send bitcoin confirm dialog.
 *///w  ww .j  a v a2  s . c om
@Override
public void actionPerformed(ActionEvent e) {
    if (abort()) {
        return;
    }

    //        SendAssetConfirmDialog sendAssetConfirmDialog = null;
    AssetValidationErrorDialog validationErrorDialog = null;

    try {
        String sendAddress = dataProvider.getAddress();
        String sendAmount = Utils.bitcoinValueToPlainString(BitcoinModel.COINSPARK_SEND_MINIMUM_AMOUNT);
        String sendMessage = null;
        boolean canSendMessage = false;

        final int assetId = dataProvider.getAssetId();
        String assetAmount = dataProvider.getAssetAmount();
        boolean isSenderPays = dataProvider.isSenderPays();

        /* Is there a payment charge?  If yes, the asset amount will change */
        CSAsset asset = bitcoinController.getModel().getActiveWallet().CS.getAsset(assetId);
        CoinSparkGenesis genesis = asset.getGenesis();
        BigInteger assetAmountRawUnits = CSMiscUtils.getRawUnitsFromDisplayString(asset, assetAmount);
        // Was there any rounding, which the user did not see because they clicked on send first,
        // without losing focus to any other widget which corrects field?
        String typedAmount = dataProvider.getAssetAmountText();
        BigDecimal bd1 = new BigDecimal(typedAmount);
        BigDecimal bd2 = new BigDecimal(assetAmount);
        bd1 = bd1.stripTrailingZeros();
        bd2 = bd2.stripTrailingZeros();
        if (bd1.equals(bd2) == false) {
            String displayUnit = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, BigInteger.ONE);
            String s = "The smallest transactable unit is " + displayUnit
                    + ", so we have rounded the sum down.\nPlease confirm the final amount and click 'Send' again.";
            JOptionPane.showMessageDialog(mainFrame, s);
            return;
        }
        // End rounding check/warning

        long desiredRawUnits = assetAmountRawUnits.longValue();
        short chargeBasisPoints = genesis.getChargeBasisPoints();
        long rawFlatChargeAmount = genesis.getChargeFlat();
        boolean chargeExists = (rawFlatChargeAmount > 0 || chargeBasisPoints > 0);
        if (chargeExists) {
            if (isSenderPays) {
                long x = genesis.calcGross(desiredRawUnits);
                assetAmountRawUnits = new BigInteger(String.valueOf(x));
            } else {
                // We don't have to do anything if recipient pays, just send gross amount.
                // calcNet() returns what the recipient will receive, but it's not what we send.
                //          long x = genesis.calcNet(desiredRawUnits);
                //          assetAmountRawUnits = new BigInteger(String.valueOf(x));          
            }
        }

        // Todo: Allow invalid assets to be sent even if spendable balance is 0
        //if (CSMiscUtils.canSendInvalidAsset(bitcoinController) 
        final AssetValidator validator = new AssetValidator(super.bitcoinController);
        if (validator.validate(sendAddress, sendAmount, assetId, assetAmountRawUnits.toString())) {
            /* CoinSpark START */
            CoinSparkPaymentRef paymentRef = null;

            // We have already validated that the coinspark address and underlying bitcoin are good
            // and that the transfer flag is set on the coinspark address.  We just want the actual
            // underlying bitcoin address to send assets to, which is used to create SendRequest object.
            CoinSparkAddress csa = CSMiscUtils.decodeCoinSparkAddress(sendAddress);
            String btcAddress = CSMiscUtils.getBitcoinAddressStringFromCoinSparkAddress(csa);
            sendAddress = btcAddress;

            // Does a payment ref exist?
            int flags = csa.getAddressFlags();
            if ((flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_PAYMENT_REFS) > 0) {
                paymentRef = csa.getPaymentRef();
                log.debug(">>>> CoinSpark address has payment refs flag set: " + paymentRef.toString());
            }

            // Messages - can send message and BTC to CoinSpark address, without any assets.
            sendMessage = dataProvider.getMessage();
            canSendMessage = (flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_TEXT_MESSAGES) > 0;
            /* CoinSpark END */

            // Create a SendRequest.
            Address sendAddressObject;

            sendAddressObject = new Address(bitcoinController.getModel().getNetworkParameters(), sendAddress);
            //SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount));

            //public static SendRequest to(Address destination,BigInteger value,int assetID, BigInteger assetValue,int split) {
            //BigInteger assetAmountRawUnits = new BigInteger(assetAmount);
            BigInteger bitcoinAmountSatoshis = Utils.toNanoCoins(sendAmount);

            final SendRequest sendRequest = SendRequest.to(sendAddressObject, bitcoinAmountSatoshis, assetId,
                    assetAmountRawUnits, 1);
            sendRequest.ensureMinRequiredFee = true;
            sendRequest.fee = BigInteger.ZERO;
            sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT;

            // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form.

            // Send with payment ref - if it exists and is not 0 which SparkBit treats semantically as null
            if (paymentRef != null && paymentRef.getRef() != 0) {
                sendRequest.setPaymentRef(paymentRef);
            }

            // Send a message if the address will take it and message is not empty
            boolean willSendMessage = false;
            if (canSendMessage) {
                boolean isEmptyMessage = false;
                if (sendMessage == null || sendMessage.isEmpty() || sendMessage.trim().length() == 0) {
                    isEmptyMessage = true;
                }
                if (!isEmptyMessage) {
                    willSendMessage = true;
                    //int numParts = 1;
                    CoinSparkMessagePart[] parts = {
                            CSMiscUtils.createPlainTextCoinSparkMessagePart(sendMessage) };
                    String[] serverURLs = CSMiscUtils.getMessageDeliveryServersArray(bitcoinController);
                    sendRequest.setMessage(parts, serverURLs);

                    log.debug(">>>> Messaging servers = " + ArrayUtils.toString(serverURLs));
                    log.debug(">>>> parts[0] = " + parts[0]);
                    log.debug(">>>> parts[0].fileName = " + parts[0].fileName);
                    log.debug(">>>> parts[0].mimeType = " + parts[0].mimeType);
                    log.debug(">>>> parts[0].content = " + new String(parts[0].content, "UTF-8"));
                    //String message = "Hello, the time is now..." + DateTime.now().toString();
                    //      parts[2].fileName = imagePath;
                    //      parts[2].mimeType = "image/png";
                    //      byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
                    //      parts[2].content = imageBytes;

                }
            }

            //
            // When sending a message, show a modal dialog.
            // CompleteTX now occurs in background thread so UI does not block
            // when "Send" is clicked with widget updates frozen.
            //

            // Show dialog with indeterminate progress bar
            final JDialog dialog = CSMiscUtils.createModalMessageDialogWithIndeterminateProgress(mainFrame,
                    "SparkBit", "Contacting message delivery servers...");
            // Dialog is made visible after futures have been set up

            ListeningExecutorService service = MoreExecutors
                    .listeningDecorator(Executors.newSingleThreadExecutor()); //newFixedThreadPool(10));
            ListenableFuture<Boolean> future = service.submit(new Callable<Boolean>() {
                public Boolean call() throws Exception {
                    try {
                        // Complete it (which works out the fee) but do not sign it yet.
                        log.debug("Just about to complete the tx (and calculate the fee)...");
                        bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false);
                        log.debug("The fee after completing the transaction was " + sendRequest.fee);

                    } catch (Exception e) {
                        throw e;
                    }
                    return true;
                }
            });

            final BigInteger myAssetAmountRawUnits = assetAmountRawUnits;

            Futures.addCallback(future, new FutureCallback<Boolean>() {
                public void onSuccess(Boolean b) {

                    // There is enough money.
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dispose();

                            SendAssetConfirmDialog mySendAssetConfirmDialog = new SendAssetConfirmDialog(
                                    bitcoinController, mainFrame, sendRequest, assetId, myAssetAmountRawUnits,
                                    validator);
                            mySendAssetConfirmDialog.setVisible(true);
                        }
                    });

                }

                public void onFailure(Throwable thrown) {
                    final String failureReason = thrown.getMessage();
                    final boolean isCSException = thrown instanceof org.coinspark.core.CSExceptions.CannotEncode;
                    final boolean isInsufficientMoney = thrown instanceof com.google.bitcoin.core.InsufficientMoneyException;
                    // There is not enough money.
                    // TODO setup validation parameters accordingly so that it displays ok.
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dispose();

                            if (isCSException) {
                                JOptionPane
                                        .showMessageDialog(mainFrame,
                                                "SparkBit is unable to proceed with this transaction:\n\n"
                                                        + failureReason,
                                                "SparkBit Error", JOptionPane.ERROR_MESSAGE);
                            } else if (isInsufficientMoney) {
                                // Try to show a human friendly message, need to pass the missing satoshis from failure reason.
                                try {
                                    String numberOnly = failureReason.replaceAll("[^0-9]", "");
                                    BigInteger needed = new BigInteger(numberOnly);
                                    JOptionPane.showMessageDialog(mainFrame,
                                            "SparkBit is unable to proceed with this transaction.\n\nInsufficient money in wallet, require "
                                                    + Utils.bitcoinValueToFriendlyString(needed) + " BTC more.",
                                            "SparkBit Error", JOptionPane.ERROR_MESSAGE);
                                } catch (NumberFormatException e) {
                                    AssetValidationErrorDialog myValidationErrorDialog = new AssetValidationErrorDialog(
                                            bitcoinController, mainFrame, sendRequest, true, validator);
                                    myValidationErrorDialog.setVisible(true);
                                }
                            } else {

                                AssetValidationErrorDialog myValidationErrorDialog = new AssetValidationErrorDialog(
                                        bitcoinController, mainFrame, sendRequest, true, validator);
                                myValidationErrorDialog.setVisible(true);
                            }
                        }
                    });
                }
            });

            // Show message server dialog only if we are going to send
            if (willSendMessage) {
                dialog.setVisible(true);
            }

            /*      
                            // Complete it (which works out the fee) but do not sign it yet.
                            log.debug("Just about to complete the tx (and calculate the fee)...");
                            boolean completedOk;
                            try {
            bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false);
                              completedOk = true;
                              log.debug("The fee after completing the transaction was " + sendRequest.fee);
                            } catch (InsufficientMoneyException ime) {
                              completedOk = false;
                            }
                            if (completedOk) {
            // There is enough money.
                    
            sendAssetConfirmDialog = new SendAssetConfirmDialog(super.bitcoinController, mainFrame, sendRequest, assetId, assetAmountRawUnits, validator);
            sendAssetConfirmDialog.setVisible(true);
                            } else {
            // There is not enough money.
            // TODO setup validation parameters accordingly so that it displays ok.
            validationErrorDialog = new AssetValidationErrorDialog(super.bitcoinController, mainFrame, sendRequest, true, validator);
            validationErrorDialog.setVisible(true);
                            }
            */

        } else {
            validationErrorDialog = new AssetValidationErrorDialog(super.bitcoinController, mainFrame, null,
                    false, validator);
            validationErrorDialog.setVisible(true);
        }
    } catch (WrongNetworkException e1) {
        logMessage(e1);
    } catch (AddressFormatException e1) {
        logMessage(e1);
    } catch (KeyCrypterException e1) {
        logMessage(e1);
    } catch (NumberFormatException nfe) {
        JOptionPane.showMessageDialog(mainFrame, "Please enter a valid amount.");
    } catch (Exception e1) {
        logMessage(e1);
    }
}

From source file:com.buildabrand.gsb.util.URLUtils.java

private String convertIpAddress(String ipAddr) {
    String[] ipAddrSplit = StringUtils.split(ipAddr, '.');

    if (ipAddrSplit.length == 0 || ipAddrSplit.length > 4) {
        return null;
    }//from  w ww. j a v  a  2s .c o  m

    // Basically we should parse octal if we can, but if there are illegal octal
    // numbers, i.e. 08 or 09, then we should just look at decimal and hex.
    boolean allowOctal = !FIND_BAD_OCTAL_REGEXP.matcher(ipAddr).find();

    BigInteger ipNumeric = BigInteger.ZERO;
    int i = 0;
    while (i < ipAddrSplit.length - 1) {
        ipNumeric = ipNumeric.shiftLeft(8);
        BigInteger componentBigInt = convertComponent(ipAddrSplit[i], allowOctal);
        if (componentBigInt == null) {
            return null;
        }

        ipNumeric = ipNumeric.add(componentBigInt);
        i++;
    }
    while (i < 4) {
        ipNumeric = ipNumeric.shiftLeft(8);
        i++;
    }
    BigInteger componentBigInt = convertComponent(ipAddrSplit[ipAddrSplit.length - 1], allowOctal);
    if (componentBigInt == null) {
        return null;
    }
    ipNumeric = ipNumeric.add(componentBigInt);

    return InetAddresses.fromInteger((ipNumeric.intValue())).getHostAddress();
}

From source file:org.apache.cassandra.cql.jdbc.HandleObjects.java

private static final BigInteger objectToBITorTINYINTorSMALLINTorNUMERIC(Class<? extends Object> objectClass,
        Object object) {/*from w w  w . ja v a2s  .com*/
    // Strings should always work
    if (objectClass == String.class)
        return new BigInteger((String) object);

    // Booleans are either false=0 or true=1
    if (objectClass == Boolean.class)
        return ((Boolean) object) == false ? BigInteger.ZERO : BigInteger.ONE;

    // All the integer (non floating-point) are simple
    if (objectClass == Integer.class)
        return BigInteger.valueOf((Integer) object);
    else if (objectClass == BigInteger.class)
        return ((BigInteger) object);
    else if (objectClass == Long.class)
        return BigInteger.valueOf(((Long) object));
    else if (objectClass == Short.class)
        return BigInteger.valueOf(((Short) object).longValue());
    else if (objectClass == Byte.class)
        return BigInteger.valueOf(((Byte) object).longValue());

    // Floating ones need to just pass the integer part
    else if (objectClass == Double.class)
        return BigInteger.valueOf(((Double) object).longValue());
    else if (objectClass == Float.class)
        return BigInteger.valueOf(((Float) object).longValue());
    else if (objectClass == BigDecimal.class)
        return BigInteger.valueOf(((BigDecimal) object).intValue());
    else
        return null; // this should not happen
}

From source file:info.savestate.saveybot.JSONFileManipulator.java

public String lowestSlot() {
    BigInteger lowest = BigInteger.ZERO;
    JSONArray json = getJSON();//from   www . ja  va 2 s  .com
    boolean passed = false;
    while (!passed) {
        passed = true;
        for (int i = 0; i < json.length(); i++) {
            JSONObject o = json.getJSONObject(i);
            BigInteger current = o.getBigInteger("slot");
            if (current.compareTo(lowest) == 0) {
                lowest = lowest.add(BigInteger.ONE);
                passed = false;
                break;
            }
        }
    }
    return lowest.toString();
}

From source file:com.ar.dev.tierra.api.controller.DetalleFacturaController.java

@RequestMapping(value = "/delete", method = RequestMethod.POST)
public ResponseEntity<?> delete(OAuth2Authentication authentication, @RequestBody DetalleFactura detalleFactura,
        @RequestParam("dni") int dni, @RequestParam("password") String password) {
    Usuarios userAuth = facadeService.getUsuariosDAO().findUsuarioByDNI(dni);
    boolean permiso = passwordEncoder.matches(password, userAuth.getPassword());
    Usuarios user = facadeService.getUsuariosDAO().findUsuarioByUsername(authentication.getName());
    if (permiso) {
        if (userAuth.getRoles().getIdRol() == 1 || userAuth.getRoles().getIdRol() == 6) {
            detalleFactura.setEstadoDetalle(false);
            detalleFactura.setUsuarioModificacion(user.getIdUsuario());
            detalleFactura.setFechaModificacion(new Date());
            facadeService.getDetalleFacturaDAO().update(detalleFactura);
            /*Traemos lista de detalles, calculamos su nuevo total y actualizamos*/
            Factura factura = facadeService.getFacturaDAO()
                    .searchById(detalleFactura.getFactura().getIdFactura());
            List<DetalleFactura> detallesFactura = facadeService.getDetalleFacturaDAO()
                    .facturaDetalle(detalleFactura.getFactura().getIdFactura());
            BigDecimal sumMonto = new BigDecimal(BigInteger.ZERO);
            for (DetalleFactura detailList : detallesFactura) {
                sumMonto = sumMonto.add(detailList.getTotalDetalle());
            }/*from  www  .  j a  v  a  2s .  c om*/
            factura.setTotal(sumMonto);
            factura.setFechaModificacion(new Date());
            factura.setUsuarioModificacion(user.getIdUsuario());
            facadeService.getFacturaDAO().update(factura);
            @SuppressWarnings("UnusedAssignment")
            int cantidadActual = 0;
            WrapperStock stock = facadeService.getStockDAO().searchStockById(detalleFactura.getIdStock(),
                    user.getUsuarioSucursal().getIdSucursal());
            if (stock.getStockTierra() != null) {
                cantidadActual = stock.getStockTierra().getCantidad();
                stock.getStockTierra().setCantidad(cantidadActual + detalleFactura.getCantidadDetalle());
            } else if (stock.getStockBebelandia() != null) {
                cantidadActual = stock.getStockBebelandia().getCantidad();
                stock.getStockBebelandia().setCantidad(cantidadActual + detalleFactura.getCantidadDetalle());
            } else {
                cantidadActual = stock.getStockLibertador().getCantidad();
                stock.getStockLibertador().setCantidad(cantidadActual + detalleFactura.getCantidadDetalle());
            }
            facadeService.getStockDAO().update(stock);
            Producto prodRest = facadeService.getProductoDAO()
                    .findById(detalleFactura.getProducto().getIdProducto());
            int cantProd = prodRest.getCantidadTotal();
            prodRest.setCantidadTotal(cantProd + detalleFactura.getCantidadDetalle());
            facadeService.getProductoDAO().update(prodRest);
            JsonResponse msg = new JsonResponse("Success", "Detalle eliminado con exito");
            return new ResponseEntity<>(msg, HttpStatus.OK);
        } else {
            JsonResponse msg = new JsonResponse("Error",
                    "No tienes los permisos necesarios para realizar esta operacion.");
            return new ResponseEntity<>(msg, HttpStatus.BAD_REQUEST);
        }
    } else {
        JsonResponse msg = new JsonResponse("Error",
                "No tienes los permisos necesarios para realizar esta operacion.");
        return new ResponseEntity<>(msg, HttpStatus.BAD_REQUEST);
    }
}

From source file:org.jembi.rhea.transformers.XDSRegistryStoredQueryResponse.java

protected String generateATNAMessage(String request, String patientId, String uniqueId, boolean outcome)
        throws JAXBException {
    AuditMessage res = new AuditMessage();

    EventIdentificationType eid = new EventIdentificationType();
    eid.setEventID(ATNAUtil.buildCodedValueType("DCM", "110112", "Query"));
    eid.setEventActionCode("E");
    eid.setEventDateTime(ATNAUtil.newXMLGregorianCalendar());
    eid.getEventTypeCode()//from w w w . j a  v  a 2s  .  co m
            .add(ATNAUtil.buildCodedValueType("IHE Transactions", "ITI-18", "Registry Stored Query"));
    eid.setEventOutcomeIndicator(outcome ? BigInteger.ONE : BigInteger.ZERO);
    res.setEventIdentification(eid);

    res.getActiveParticipant().add(ATNAUtil.buildActiveParticipant(ATNAUtil.WSA_REPLYTO_ANON,
            ATNAUtil.getProcessID(), true, ATNAUtil.getHostIP(), (short) 2, "DCM", "110153", "Source"));
    res.getActiveParticipant().add(ATNAUtil.buildActiveParticipant(buildRegistryPath(), xdsRegistryHost, false,
            xdsRegistryHost, (short) 1, "DCM", "110152", "Destination"));

    res.getAuditSourceIdentification().add(ATNAUtil.buildAuditSource("openhie-registry"));

    res.getParticipantObjectIdentification()
            .add(ATNAUtil.buildParticipantObjectIdentificationType(
                    String.format("%s^^^&%s&ISO", patientId, requestedAssigningAuthority), (short) 1, (short) 1,
                    "RFC-3881", "2", "PatientNumber", null));

    List<ParticipantObjectDetail> pod = new ArrayList<ParticipantObjectDetail>();
    pod.add(new ParticipantObjectDetail("QueryEncoding", "UTF-8".getBytes()));
    if (homeCommunityId != null)
        pod.add(new ParticipantObjectDetail("urn:ihe:iti:xca:2010:homeCommunityId",
                homeCommunityId.getBytes()));

    res.getParticipantObjectIdentification().add(ATNAUtil.buildParticipantObjectIdentificationType(uniqueId,
            (short) 2, (short) 24, "IHE Transactions", "ITI-18", "Registry Stored Query", request, pod));

    return ATNAUtil.marshallATNAObject(res);
}

From source file:com.exilant.eGov.src.common.EGovernCommon.java

/**
 * This API returns the fiscialperiodid for the date passed
 * @param vDate//from  www.  ja  v a  2 s  . c o m
 * @param con
 * @return
 * @throws TaskFailedException
 */
public String getFiscalPeriod(final String vDate) throws TaskFailedException {
    BigInteger fiscalPeriod = null;
    final String sql = "select id from fiscalperiod  where '" + vDate + "' between startingdate and endingdate";
    try {
        final Query pst = persistenceService.getSession().createSQLQuery(sql);
        final List<BigInteger> rset = pst.list();
        fiscalPeriod = rset != null ? rset.get(0) : BigInteger.ZERO;
    } catch (final Exception e) {
        LOGGER.error("Exception..." + e.getMessage());
        throw new TaskFailedException(e.getMessage());
    }
    return fiscalPeriod.toString();
}

From source file:com.ethercamp.harmony.service.WalletService.java

public WalletInfoDTO getWalletInfo() {
    BigInteger gasPrice = BigInteger.valueOf(ethereum.getGasPrice());
    BigInteger txFee = gasLimit.multiply(gasPrice);

    List<WalletAddressDTO> list = addresses.entrySet().stream().flatMap(e -> {
        final String hexAddress = e.getKey();
        try {//w  ww.  j av  a  2s .c o m
            final byte[] address = Hex.decode(hexAddress);
            final BigInteger balance = repository.getBalance(address);
            final BigInteger sendBalance = calculatePendingChange(pendingSendTransactions, hexAddress, txFee);
            final BigInteger receiveBalance = calculatePendingChange(pendingReceiveTransactions, hexAddress,
                    BigInteger.ZERO);

            return Stream.of(new WalletAddressDTO(e.getValue(), e.getKey(), balance,
                    receiveBalance.subtract(sendBalance), keystore.hasStoredKey(e.getKey())));
        } catch (Exception exception) {
            log.error("Error in making wallet address " + hexAddress, exception);
            return Stream.empty();
        }
    }).collect(Collectors.toList());

    BigInteger totalAmount = list.stream().map(t -> t.getAmount()).reduce(BigInteger.ZERO,
            (state, amount) -> state.add(amount));

    WalletInfoDTO result = new WalletInfoDTO(totalAmount);

    result.getAddresses().addAll(list);
    return result;
}

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

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    final SendCoinsActivity activity = (SendCoinsActivity) getActivity();

    final View view = inflater.inflate(R.layout.send_coins_fragment, container);

    final MyRemoteWallet wallet = application.getRemoteWallet();

    if (wallet == null)
        return view;

    BigInteger available = null;/*ww  w.  j  a  v a 2  s .  c  o  m*/

    if (application.isInP2PFallbackMode()) {
        try {
            available = application.bitcoinjWallet.getBalance(BalanceType.ESTIMATED);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        available = wallet.getBalance();
    }

    receivingAddressView = (AutoCompleteTextView) view.findViewById(R.id.send_coins_receiving_address);
    feeContainerView = view.findViewById(R.id.send_coins_fee_container);
    sendCoinsFromContainer = view.findViewById(R.id.send_coins_from_container);
    sendCoinsFromSpinner = (Spinner) view.findViewById(R.id.send_coins_from_spinner);
    feeAmountView = (CurrencyAmountView) view.findViewById(R.id.send_coins_fee);
    sendTypeDescriptionContainer = view.findViewById(R.id.send_type_description_container);
    sendTypeDescription = (TextView) view.findViewById(R.id.send_type_description);
    sendTypeDescriptionIcon = (ImageView) view.findViewById(R.id.send_type_description_icon);

    {
        //Construct the from drop down list
        String[] activeAddresses = wallet.getActiveAddresses();
        Map<String, String> labelMap = wallet.getLabelMap();

        List<Pair<String, String>> pairs = new ArrayList<Pair<String, String>>();
        for (String address : activeAddresses) {

            String label = labelMap.get(address);

            if (label == null || label.length() == 0) {
                label = "No Label";
            }

            BigInteger balance = wallet.getBalance(address);

            if (balance.compareTo(BigInteger.ZERO) > 0) {
                label += " (" + WalletUtils.formatValue(balance) + " BTC)";

                pairs.add(new Pair<String, String>(address, label));
            }
        }

        pairs.add(0, new Pair<String, String>("Any Address", "Any Address"));

        sendCoinsFromSpinner.setAdapter(new SpinAdapter(activity, android.R.layout.simple_list_item_1, pairs));
    }

    feeAmountView.setAmount(wallet.getBaseFee());

    StringPairAdapter adapter = new StringPairAdapter(this.getLabelList());

    receivingAddressView.setAdapter(adapter);
    receivingAddressView.addTextChangedListener(textWatcher);

    receivingAddressView.setOnTouchListener(new RightDrawableOnTouchListener(receivingAddressView) {
        @Override
        public boolean onDrawableTouch(final MotionEvent event) {

            activity.showQRReader(activity.new QrCodeDelagate() {
                @Override
                public void didReadQRCode(String data) {
                    activity.handleScanURI(data);
                }
            });

            return true;
        }
    });

    receivingAddressErrorView = view.findViewById(R.id.send_coins_receiving_address_error);

    availableViewContainer = view.findViewById(R.id.send_coins_available_container);
    availableView = (CurrencyAmountView) view.findViewById(R.id.send_coins_available);
    availableView.setAmount(available);

    amountView = (CurrencyAmountView) view.findViewById(R.id.send_coins_amount);
    amountView.setListener(listener);
    amountView.setContextButton(R.drawable.ic_input_calculator, new OnClickListener() {
        public void onClick(final View v) {
            final FragmentTransaction ft = getFragmentManager().beginTransaction();
            final Fragment prev = getFragmentManager().findFragmentByTag(AmountCalculatorFragment.FRAGMENT_TAG);
            if (prev != null)
                ft.remove(prev);
            ft.addToBackStack(null);
            final DialogFragment newFragment = new AmountCalculatorFragment(
                    new AmountCalculatorFragment.Listener() {
                        public void use(final BigInteger amount) {
                            amountView.setAmount(amount);
                        }
                    });
            newFragment.show(ft, AmountCalculatorFragment.FRAGMENT_TAG);
        }
    });

    viewGo = (Button) view.findViewById(R.id.send_coins_go);
    viewGo.setOnClickListener(new OnClickListener() {
        final SendProgress progress = new SendProgress() {
            public void onSend(final Transaction tx, final String message) {
                handler.post(new Runnable() {
                    public void run() {
                        state = State.SENT;

                        activity.longToast(message);

                        Intent intent = activity.getIntent();
                        intent.putExtra("tx", tx.getHash());
                        activity.setResult(Activity.RESULT_OK, intent);

                        activity.finish();

                        updateView();
                    }
                });

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                application.doMultiAddr(true);
            }

            public void onError(final String message) {
                handler.post(new Runnable() {
                    public void run() {

                        System.out.println("On Error");

                        if (message != null)
                            activity.longToast(message);

                        state = State.INPUT;

                        updateView();
                    }
                });
            }

            public void onProgress(final String message) {
                handler.post(new Runnable() {
                    public void run() {
                        state = State.SENDING;

                        updateView();
                    }
                });
            }

            public boolean onReady(Transaction tx, BigInteger fee, FeePolicy feePolicy, long priority) {

                boolean containsOutputLessThanThreshold = false;
                for (TransactionOutput output : tx.getOutputs()) {
                    if (output.getValue().compareTo(Constants.FEE_THRESHOLD_MIN) < 0) {
                        containsOutputLessThanThreshold = true;
                        break;
                    }
                }

                if (feePolicy != FeePolicy.FeeNever && fee.compareTo(BigInteger.ZERO) == 0) {
                    if (tx.bitcoinSerialize().length > 1024 || containsOutputLessThanThreshold) {
                        makeTransaction(FeePolicy.FeeForce);
                        return false;
                    } else if (priority < 97600000L) {
                        handler.post(new Runnable() {
                            public void run() {
                                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                                builder.setMessage(R.string.ask_for_fee).setCancelable(false);

                                AlertDialog alert = builder.create();

                                alert.setButton(AlertDialog.BUTTON_NEUTRAL,
                                        getString(R.string.continue_without_fee),
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                makeTransaction(FeePolicy.FeeNever);
                                                dialog.dismiss();
                                            }
                                        });

                                alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.add_fee),
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                makeTransaction(FeePolicy.FeeForce);

                                                dialog.dismiss();
                                            }
                                        });

                                alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.cancel),
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                dialog.dismiss();
                                            }
                                        });

                                alert.show();
                            }
                        });

                        handler.post(new Runnable() {
                            public void run() {
                                state = State.INPUT;
                                updateView();
                            }
                        });
                        return false;
                    }
                }

                return true;
            }

            public ECKey onPrivateKeyMissing(final String address) {

                handler.post(new Runnable() {
                    public void run() {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setMessage(getString(R.string.ask_for_private_key, address))
                                .setCancelable(false)
                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        activity.scanPrivateKeyAddress = address;

                                        activity.showQRReader(activity.new QrCodeDelagate() {
                                            @Override
                                            public void didReadQRCode(String data) throws Exception {
                                                activity.handleScanPrivateKey(data);
                                            }
                                        });
                                    }
                                })
                                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {

                                        synchronized (activity.temporaryPrivateKeys) {
                                            activity.temporaryPrivateKeys.notify();
                                        }

                                        dialog.cancel();
                                    }
                                });

                        AlertDialog alert = builder.create();

                        alert.show();
                    }
                });

                try {
                    synchronized (activity.temporaryPrivateKeys) {
                        activity.temporaryPrivateKeys.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                return activity.temporaryPrivateKeys.get(address);
            }
        };

        public void send(Address receivingAddress, BigInteger fee, FeePolicy feePolicy) {

            if (application.getRemoteWallet() == null)
                return;

            if (sendType != null && !sendType.equals(SendCoinsActivity.SendTypeQuickSend)
                    && application.isInP2PFallbackMode()) {
                activity.longToast(R.string.only_quick_supported);
                return;
            }

            String[] from;
            if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeCustomSend)) {
                Pair<String, String> selected = (Pair<String, String>) sendCoinsFromSpinner.getSelectedItem();

                if (selected.first.equals("Any Address")) {
                    from = wallet.getActiveAddresses();
                } else {
                    from = new String[] { selected.first.toString() };
                }
            } else {
                from = wallet.getActiveAddresses();
            }

            final BigInteger amount;

            if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeSharedSend)) {
                BigDecimal amountDecimal = BigDecimal.valueOf(amountView.getAmount().doubleValue());

                //Add the fee
                amount = amountDecimal.add(amountDecimal.divide(BigDecimal.valueOf(100))
                        .multiply(BigDecimal.valueOf(wallet.getSharedFee()))).toBigInteger();
            } else {
                amount = amountView.getAmount();
            }

            final WalletApplication application = (WalletApplication) getActivity().getApplication();

            if (application.isInP2PFallbackMode()) {

                final long blockchainLag = System.currentTimeMillis()
                        - service.blockChain.getChainHead().getHeader().getTime().getTime();

                final boolean blockchainUptodate = blockchainLag < Constants.BLOCKCHAIN_UPTODATE_THRESHOLD_MS;

                if (!blockchainUptodate) {
                    activity.longToast(R.string.blockchain_not_upto_date);
                    return;
                }

                // create spend
                final SendRequest sendRequest = SendRequest.to(receivingAddress, amountView.getAmount());

                sendRequest.fee = fee;

                new Thread(new Runnable() {
                    public void run() {
                        final Transaction transaction = application.bitcoinjWallet
                                .sendCoinsOffline(sendRequest);

                        handler.post(new Runnable() {
                            public void run() {
                                if (transaction != null) {
                                    state = State.SENDING;

                                    updateView();

                                    service.broadcastTransaction(transaction);

                                    state = State.SENT;

                                    activity.longToast(R.string.wallet_transactions_fragment_tab_sent);

                                    Intent intent = activity.getIntent();
                                    intent.putExtra("tx", transaction.getHash());
                                    activity.setResult(Activity.RESULT_OK, intent);

                                    activity.finish();

                                    updateView();

                                    EventListeners.invokeOnTransactionsChanged();
                                } else {
                                    state = State.INPUT;

                                    updateView();

                                    activity.longToast(R.string.send_coins_error_msg);
                                }
                            }
                        });
                    }
                }).start();
            } else {
                application.getRemoteWallet().sendCoinsAsync(from, receivingAddress.toString(), amount,
                        feePolicy, fee, progress);
            }
        }

        public void makeTransaction(FeePolicy feePolicy) {

            if (application.getRemoteWallet() == null)
                return;

            try {
                MyRemoteWallet wallet = application.getRemoteWallet();

                BigInteger baseFee = wallet.getBaseFee();

                BigInteger fee = null;

                if (feePolicy == FeePolicy.FeeForce) {
                    fee = baseFee;
                } else if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeCustomSend)) {
                    feePolicy = FeePolicy.FeeOnlyIfNeeded;
                    fee = feeAmountView.getAmount();
                } else {
                    fee = (wallet.getFeePolicy() == 1) ? baseFee : BigInteger.ZERO;
                }

                final BigInteger finalFee = fee;
                final FeePolicy finalFeePolicy = feePolicy;

                if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeSharedSend)) {

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                final String addressString = MyRemoteWallet
                                        .generateSharedAddress(getToAddress());

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            send(new Address(Constants.NETWORK_PARAMETERS, addressString),
                                                    finalFee, finalFeePolicy);
                                        } catch (Exception e) {
                                            e.printStackTrace();

                                            Toast.makeText(application, e.getLocalizedMessage(),
                                                    Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });
                            } catch (final Exception e) {
                                handler.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        e.printStackTrace();

                                        Toast.makeText(application, e.getLocalizedMessage(), Toast.LENGTH_LONG)
                                                .show();
                                    }
                                });
                            }
                        }

                    }).start();

                } else {
                    String addressString = getToAddress();

                    Address receivingAddress = new Address(Constants.NETWORK_PARAMETERS, addressString);

                    send(receivingAddress, fee, feePolicy);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void onClick(final View v) {
            if (application.getRemoteWallet() == null)
                return;

            MyRemoteWallet remoteWallet = application.getRemoteWallet();

            if (remoteWallet.isDoubleEncrypted() == false) {
                makeTransaction(FeePolicy.FeeOnlyIfNeeded);
            } else {
                if (remoteWallet.temporySecondPassword == null) {
                    RequestPasswordDialog.show(getFragmentManager(), new SuccessCallback() {

                        public void onSuccess() {
                            makeTransaction(FeePolicy.FeeOnlyIfNeeded);
                        }

                        public void onFail() {
                            Toast.makeText(application, R.string.send_no_password_error, Toast.LENGTH_LONG)
                                    .show();
                        }
                    }, RequestPasswordDialog.PasswordTypeSecond);
                } else {
                    makeTransaction(FeePolicy.FeeOnlyIfNeeded);
                }
            }
        }
    });

    viewCancel = (Button) view.findViewById(R.id.send_coins_cancel);
    viewCancel.setOnClickListener(new OnClickListener() {
        public void onClick(final View v) {
            activity.setResult(Activity.RESULT_CANCELED);

            activity.finish();
        }
    });

    activity.setOnChangedSendTypeListener(new OnChangedSendTypeListener() {
        @Override
        public void onChangedSendType(String type) {
            sendType = type;

            feeContainerView.setVisibility(View.GONE);
            sendCoinsFromContainer.setVisibility(View.GONE);
            availableViewContainer.setVisibility(View.VISIBLE);
            sendTypeDescriptionContainer.setVisibility(View.GONE);

            if (type.equals(SendCoinsActivity.SendTypeCustomSend)) {
                feeContainerView.setVisibility(View.VISIBLE);
                sendCoinsFromContainer.setVisibility(View.VISIBLE);
                availableViewContainer.setVisibility(View.GONE);
            } else if (type.equals(SendCoinsActivity.SendTypeSharedSend)) {
                sendTypeDescriptionContainer.setVisibility(View.VISIBLE);
                sendTypeDescription
                        .setText(getString(R.string.shared_send_description, wallet.getSharedFee() + "%"));
                sendTypeDescriptionIcon.setImageResource(R.drawable.ic_icon_shared);
            }
        }
    });

    updateView();

    return view;
}

From source file:org.openestate.io.daft_ie.DaftIeUtils.java

public static String printPositiveInteger(BigInteger value) {
    if (value == null || value.compareTo(BigInteger.ZERO) < 1)
        throw new IllegalArgumentException("Can't print positive integer value!");
    else/*from w  w  w . j  a va 2  s.  co m*/
        return DatatypeConverter.printInteger(value);
}