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:net.bither.rawprivatekey.RawPrivateKeyDiceFragment.java

private boolean checkValue(byte[] data) {
    BigInteger value = new BigInteger(1, data).mod(ECKey.CURVE.getN());
    if (value.compareTo(BigInteger.ZERO) == 0) {
        return false;
    }//from w  ww. java2 s  .co  m
    return true;
}

From source file:org.openmrs.calculation.result.ResultUtil.java

/**
 * If you pass in a CalculationResult, this method will operate upon its getValue, otherwise it will operate on the
 * object itself./*w  ww  .  j  a  va 2s. c  o m*/
 * 
 * The following are treated as false:
 * <ul>
 * <li>null</li>
 * <li>empty collections/maps</li>
 * <li>the number 0</li>
 * <li>the empty string</li>
 * <li>numeric Obs whose value is 0</li>
 * <li>text Obs whose value is ""</li>
 * <li>coded Obs whose value is the GlobalProperty concept.false</li>
 * <li>boolean Obs whose value is false</li>
 * </ul>
 * * the number 0
 * * the empty string
 * * numeric Ob
 * 
 * @param o
 * @return whether the given object is "falsey"
 * @should return true for null
 * @should return true for an empty collection
 * @should return false for a non-empty collection
 * @should return true for an empty map
 * @should return false for a non-empty map
 * @should return true for an empty string
 * @should return false for a non-empty string
 * @should return true for the number 0
 * @should return false for a non-zero number
 * @should return true for a numeric Obs whose value is 0
 * @should return false for a numeric Obs whose value is not 0
 * @should return true for a text Obs whose value is the empty string
 * @should return false for a text Obs whose value is not the empty string
 * @should return true for a coded Obs whose value is the GlobalProperty concept.false
 * @should return false for a coded Obs whose value is not the GlobalProperty concept.false
 * @should return true for a boolean Obs whose value is false
 * @should return false for a boolean Obs whose value is true
 * @should return true for an empty ListResult
 * @should return false for non-empty ListResult
 * @should return true for an empty SimpleResult
 * @should return false for a non-empty SimpleResult
 */
public static boolean isFalse(Object o) {
    if (o == null) {
        return true;
    } else if (o instanceof CalculationResult) {
        CalculationResult cr = (CalculationResult) o;
        return cr.isEmpty() || isFalse(cr.getValue());
    } else if (o instanceof Boolean) {
        return Boolean.FALSE.equals(o);
    } else if (o instanceof String) {
        return "".equals(o);
    } else if (o instanceof Collection<?>) {
        return ((Collection<?>) o).isEmpty();
    } else if (o instanceof Map<?, ?>) {
        return ((Map<?, ?>) o).isEmpty();
    } else if (o instanceof Integer || o instanceof Long) {
        return ((Number) o).longValue() == 0l;
    } else if (o instanceof BigDecimal) {
        return o.equals(BigDecimal.ZERO);
    } else if (o instanceof BigInteger) {
        return o.equals(BigInteger.ZERO);
    } else if (o instanceof Number) {
        // Double, Float, and anything else
        return ((Number) o).doubleValue() == 0d;
    } else if (o instanceof Obs) {
        Obs obs = (Obs) o;
        if (obs.getConcept().getDatatype().isNumeric()) {
            return isFalse(obs.getValueNumeric());
        } else if (obs.getConcept().getDatatype().isBoolean()) {
            // ideally we'd want to use obs.getValueBoolean, but this isn't introduced until 1.7 and this module requires 1.6.5.
            return isFalse(obs.getValueAsBoolean());
        } else if (obs.getConcept().getDatatype().isText()) {
            return isFalse(obs.getValueText());
        } else if (obs.getConcept().getDatatype().isCoded()) {
            if (OpenmrsConstants.OPENMRS_VERSION_SHORT.startsWith("1.6.")) {
                // prior to 1.7 booleans were represented as numeric 0 or 1, so if this is 1.6.x, we treat all non-null coded obs as true
                return obs.getValueCoded() == null;
            } else {
                // in 1.7+, there is a GlobalProperty for concept.false, and we should treat that as falsey
                Boolean b = obs.getValueAsBoolean();
                if (b == null) {
                    // the obs.getValueAsBoolean method returns null for any valueCoded that isn't explicitly True or False
                    return obs.getValueCoded() == null;
                } else {
                    // if the value is explicitly the GP concept.true or concept.false, we'll get back a value here
                    return !b;
                }
            }
        }
    } else if (o instanceof Concept) {
        // TODO handle this if we're on OpenMRS 1.7+ when ConceptService.getFalseConcept() was introduced 
    }
    return false;
}

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

@RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity<?> add(OAuth2Authentication authentication, @RequestParam("idFactura") int idFactura,
        @RequestParam("idProducto") int idProducto, @RequestParam("idItem") int idItem,
        @RequestParam("cantidadItem") int cantidadItem) {
    /*Instancia de nuevo detalle*/
    DetalleFactura detalleFactura = new DetalleFactura();
    /*Traemos los objectos necesarios para aadir el detalle*/
    Usuarios user = facadeService.getUsuariosDAO().findUsuarioByUsername(authentication.getName());
    Producto prod = facadeService.getProductoDAO().findById(idProducto);
    WrapperStock stock = facadeService.getStockDAO().searchStockById(idItem,
            user.getUsuarioSucursal().getIdSucursal());
    Factura factura = facadeService.getFacturaDAO().searchById(idFactura);
    /*Bandera de control*/
    boolean control = false;
    /*Variable de calculo de cantidad*/
    @SuppressWarnings("UnusedAssignment")
    int cantidadStock = 0;

    detalleFactura.setUsuarioCreacion(user.getIdUsuario());
    detalleFactura.setFechaCreacion(new Date());
    detalleFactura.setEstadoDetalle(true);

    if (prod.getCantidadTotal() >= cantidadItem) {
        if (stock.getStockTierra() != null) {
            if (stock.getStockTierra().getCantidad() >= cantidadItem) {
                cantidadStock = stock.getStockTierra().getCantidad() - cantidadItem;
                stock.getStockTierra().setCantidad(cantidadStock);
                control = true;/*from  ww  w  . j  a v  a 2s  . c o m*/
            }
        }
        if (stock.getStockBebelandia() != null) {
            if (stock.getStockBebelandia().getCantidad() >= cantidadItem) {
                cantidadStock = stock.getStockBebelandia().getCantidad() - cantidadItem;
                stock.getStockBebelandia().setCantidad(cantidadStock);
                control = true;
            }
        }
        if (stock.getStockLibertador() != null) {
            if (stock.getStockLibertador().getCantidad() >= cantidadItem) {
                cantidadStock = stock.getStockLibertador().getCantidad() - cantidadItem;
                stock.getStockLibertador().setCantidad(cantidadStock);
                control = true;
            }
        }
        if (control) {
            int cantidadTotal = prod.getCantidadTotal();
            /*seteamos cantidad nueva de productos*/
            prod.setCantidadTotal(cantidadTotal - cantidadItem);
            /*seteamos producto en el detalle*/
            detalleFactura.setProducto(prod);
            /*Calculamos el total del detalle*/
            BigDecimal monto = detalleFactura.getProducto().getPrecioVenta()
                    .multiply(BigDecimal.valueOf(cantidadItem));
            /*seteamos el total del detalle*/
            detalleFactura.setTotalDetalle(monto);
            /*seteamos la factura del detalle*/
            detalleFactura.setFactura(factura);
            /*seteamos descuento en cero*/
            detalleFactura.setDescuentoDetalle(BigDecimal.ZERO);
            /*seteamos la cantidad de items en el detalle*/
            detalleFactura.setCantidadDetalle(cantidadItem);
            /*Indicamos el idStock del detalle*/
            detalleFactura.setIdStock(idItem);
            /*Actualizamos producto*/
            facadeService.getProductoDAO().update(prod);
            /*Actualizamos el stock*/
            facadeService.getStockDAO().update(stock);
            /*Insertamos el nuevo detalle*/
            facadeService.getDetalleFacturaDAO().add(detalleFactura);
            /*Traemos lista de detalles, calculamos su nuevo total y actualizamos*/
            List<DetalleFactura> detallesFactura = facadeService.getDetalleFacturaDAO()
                    .facturaDetalle(idFactura);
            BigDecimal sumMonto = new BigDecimal(BigInteger.ZERO);
            for (DetalleFactura detailList : detallesFactura) {
                sumMonto = sumMonto.add(detailList.getTotalDetalle());
            }
            factura.setTotal(sumMonto);
            factura.setFechaModificacion(new Date());
            factura.setUsuarioModificacion(user.getIdUsuario());
            facadeService.getFacturaDAO().update(factura);
            JsonResponse msg = new JsonResponse("Success", "Detalle agregado con exito");
            return new ResponseEntity<>(msg, HttpStatus.OK);
        } else {
            JsonResponse msg = new JsonResponse("Error", "Stock insuficiente.");
            return new ResponseEntity<>(msg, HttpStatus.BAD_REQUEST);
        }
    } else {
        JsonResponse msg = new JsonResponse("Error", "Stock insuficiente.");
        return new ResponseEntity<>(msg, HttpStatus.BAD_REQUEST);
    }
}

From source file:org.limewire.mojito.util.DHTSizeEstimator.java

/**
 * Computes and returns the approximate DHT size based 
 * on the given List of Contacts./*  www. j a v a 2  s.  c  o m*/
 */
public synchronized BigInteger computeSize(Collection<? extends Contact> nodes) {

    // Works only with more than two Nodes
    if (nodes.size() < MIN_NODE_COUNT) {
        // There's always us!
        return BigInteger.ONE.max(BigInteger.valueOf(nodes.size()));
    }

    // Get the Iterator. We assume the Contacts are sorted by
    // their xor distance!
    Iterator<? extends Contact> contacts = nodes.iterator();

    // See Azureus DHTControlImpl.estimateDHTSize()
    // Di = nearestId xor NodeIDi
    // Dc = sum(i * Di) / sum(i * i)
    // Size = 2**160 / Dc

    BigInteger sum1 = BigInteger.ZERO;
    BigInteger sum2 = BigInteger.ZERO;

    // The algorithm works relative to the ID space.
    KUID nearestId = contacts.next().getNodeID();

    // We start 1 because the nearest Node is the 0th item!
    for (int i = 1; contacts.hasNext(); i++) {
        Contact node = contacts.next();

        BigInteger distance = nearestId.xor(node.getNodeID()).toBigInteger();
        BigInteger j = BigInteger.valueOf(i);

        sum1 = sum1.add(j.multiply(distance));
        sum2 = sum2.add(j.pow(2));
    }

    BigInteger estimatedSize = BigInteger.ZERO;
    if (!sum1.equals(BigInteger.ZERO)) {
        estimatedSize = KUID.MAXIMUM.toBigInteger().multiply(sum2).divide(sum1);
    }

    // And there is always us!
    estimatedSize = BigInteger.ONE.max(estimatedSize);

    // Get the average of the local estimations
    BigInteger localSize = BigInteger.ZERO;
    localSizeHistory.add(estimatedSize);

    // Adjust the size of the List. The Setting is SIMPP-able
    // and may change!
    int maxLocalHistorySize = ContextSettings.MAX_LOCAL_HISTORY_SIZE.getValue();
    while (localSizeHistory.size() > maxLocalHistorySize && !localSizeHistory.isEmpty()) {
        localSizeHistory.remove(0);
    }

    if (!localSizeHistory.isEmpty()) {
        BigInteger localSizeSum = BigInteger.ZERO;
        for (BigInteger size : localSizeHistory) {
            localSizeSum = localSizeSum.add(size);
        }

        localSize = localSizeSum.divide(BigInteger.valueOf(localSizeHistory.size()));
    }

    // Get the combined average
    // S = (localEstimation + sum(remoteEstimation[i]))/count
    BigInteger combinedSize = localSize;
    if (ContextSettings.COUNT_REMOTE_SIZE.getValue()) {
        // Prune all duplicates and sort the values
        Set<BigInteger> remoteSizeSet = new TreeSet<BigInteger>(remoteSizeHistory);

        if (remoteSizeSet.size() >= 3) {
            BigInteger[] remote = remoteSizeSet.toArray(new BigInteger[0]);

            // Skip the smallest and largest values
            int count = 1;
            int skip = ContextSettings.SKIP_REMOTE_ESTIMATES.getValue();
            for (int i = skip; (skip >= 0) && (i < (remote.length - skip)); i++) {
                combinedSize = combinedSize.add(remote[i]);
                count++;
            }
            combinedSize = combinedSize.divide(BigInteger.valueOf(count));

            // Make sure we didn't exceed the MAXIMUM number as
            // we made an addition with the local estimation which
            // might be already 2**160 bit!
            combinedSize = combinedSize.min(MAXIMUM);
        }
    }

    // There is always us!
    return BigInteger.ONE.max(combinedSize);
}

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

public void updateView() {

    try {/*from www. j av  a 2s. co  m*/
        if (application.getRemoteWallet() == null)
            return;

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

        if (application.isInP2PFallbackMode()) {
            viewBalance.setCurrencyCode(Constants.CURRENCY_CODE_BITCOIN);

            try {
                viewBalance.setAmount(application.bitcoinjWallet.getBalance(BalanceType.ESTIMATED));
            } catch (Exception e) {
                e.printStackTrace();

                viewBalance.setAmount(BigInteger.ZERO);
            }

        } else {
            boolean displayLocal = application.getShouldDisplayLocalCurrency();

            if (displayLocal && application.getRemoteWallet().getCurrencyConversion() > 0
                    && application.getRemoteWallet().getCurrencyCode() != null) {
                viewBalance.setCurrencyCode(application.getRemoteWallet().getCurrencyCode());

                viewBalance.setAmount(application.getRemoteWallet().getBalance().doubleValue()
                        / application.getRemoteWallet().getCurrencyConversion());
            } else {
                viewBalance.setCurrencyCode(Constants.CURRENCY_CODE_BITCOIN);

                viewBalance.setAmount(application.getRemoteWallet().getBalance());
            }
        }

        Address address = application.determineSelectedAddress();

        if (address != null) {
            final String addressString = address.toString();

            final int size = (int) (256 * getResources().getDisplayMetrics().density);
            qrCodeBitmap = WalletUtils.getQRCodeBitmap(addressString, size);
            qrView.setImageBitmap(qrCodeBitmap);

            qrView.setOnClickListener(new OnClickListener() {
                public void onClick(final View v) {
                    new YourAddressesDialog(getActivity(), addressString, qrCodeBitmap).show();
                }
            });

        } else {
            qrView.setVisibility(View.GONE);
        }

        getLoaderManager().restartLoader(0, null, this);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.ar.dev.tierra.api.dao.impl.FiscalDAOImpl.java

@Override
public void factura_b(List<DetalleFactura> detalles, Cliente cliente) {
    try (PrintWriter ticket = new PrintWriter("command/factura_b.200")) {
        DecimalFormat decimalFormat = new DecimalFormat();
        decimalFormat.setMaximumFractionDigits(1);
        ticket.println("b" + (char) 28 + cliente.getNombreCliente() + (char) 28 + cliente.getDocumento()
                + (char) 28 + cliente.getResponsabilidadIva() + (char) 28 + cliente.getTipoDocumento()
                + (char) 28 + cliente.getDomicilio());
        ticket.println("@" + (char) 28 + "B" + (char) 28 + "T");
        BigDecimal descuento = new BigDecimal(BigInteger.ZERO);
        for (DetalleFactura detalle : detalles) {
            if (detalle.getDescuentoDetalle() != null) {
                descuento = descuento.add(detalle.getDescuentoDetalle());
            }/*from  ww w.j  a v  a2  s . c o m*/
            String price = null;
            BigDecimal sinIVA = detalle.getProducto().getPrecioVenta().subtract(detalle.getProducto()
                    .getPrecioVenta().multiply(new BigDecimal(17.35)).divide(new BigDecimal(100)));
            price = sinIVA.setScale(4, RoundingMode.HALF_UP).toString();
            ticket.println("B" + (char) 28 /*Abrimos linea*/
                    + detalle.getProducto().getDescripcion() + (char) 28 /*Nombre producto*/
                    + detalle.getCantidadDetalle() + ".0" + (char) 28 /*Cantidad*/
                    + price.replace(",", ".") + (char) 28 /*Precio unitario*/
                    + "21.0" + (char) 28 /*Impuestos IVA*/
                    + "M" + (char) 28 /*Suma monto*/
                    + "0.0" + (char) 28 /*Impuestos internos*/
                    + "0" + (char) 28 /*Parametro display*/
                    + "b");
            /*Cierra de linea*/
        }
        if (!descuento.equals(new BigDecimal(BigInteger.ZERO))) {
            ticket.println("T" + (char) 28 /*Abrimos linea descuento*/
                    + "Descuento: " + (char) 28 /*Texto a mostrar*/
                    + descuento + (char) 28 /*Monto descuento*/
                    + "m" + (char) 28 /*m: descuento, M: aumento*/
                    + "0" + (char) 28 /*parametro display*/
                    + "T");
            /*cierre linea descuento*/
        }
        ticket.println("E");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(FiscalDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

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

    //        SendBitcoinConfirmDialog sendBitcoinConfirmDialog = null;
    ValidationErrorDialog validationErrorDialog = null;

    try {
        String sendAddress = dataProvider.getAddress();
        String sendAmount = dataProvider.getAmount();
        String sendMessage = null;
        boolean canSendMessage = false;

        /*CoinSpark START */
        CoinSparkPaymentRef paymentRef = null;

        /*
         If the address is a coinspark address, retrieve the bitcoin address and let the validator check it.
         The SendRequest object will use the bitcoin address, while the confirmation dialog will use
         whatever is displayed in the address text field i.e. coinspark address, if there is one.
         For reference, you can see what is in the textfield, which has been saved in prefs:
         String address = this.bitcoinController.getModel().getActiveWalletPreference(BitcoinModel.SEND_ADDRESS
         */
        if (sendAddress.startsWith("s")) {
            CoinSparkAddress csa = CSMiscUtils.decodeCoinSparkAddress(sendAddress);
            String btcAddress = CSMiscUtils.getBitcoinAddressStringFromCoinSparkAddress(csa);
            if (btcAddress != null) {
                sendAddress = btcAddress; // the validator will check the btcAddress like normal.
            }

            // Does a payment ref exist?
            int flags = csa.getAddressFlags();
            if ((flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_PAYMENT_REFS) > 0) {
                paymentRef = csa.getPaymentRef();
            }

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

        Validator validator = new Validator(super.bitcoinController);
        if (validator.validate(sendAddress, sendAmount)) {
            // The address and amount are valid.

            // Create a SendRequest.
            Address sendAddressObject;

            sendAddressObject = new Address(bitcoinController.getModel().getNetworkParameters(), sendAddress);
            final SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount));
            //                SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount), 6, new BigInteger("10000"),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;
                    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;
                }
            });

            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();

                            SendBitcoinConfirmDialog mySendBitcoinConfirmDialog = new SendBitcoinConfirmDialog(
                                    bitcoinController, mainFrame, sendRequest);
                            mySendBitcoinConfirmDialog.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) {
                                    ValidationErrorDialog myValidationErrorDialog = new ValidationErrorDialog(
                                            bitcoinController, mainFrame, sendRequest, true);
                                    myValidationErrorDialog.setVisible(true);
                                }
                            } else {
                                ValidationErrorDialog myValidationErrorDialog = new ValidationErrorDialog(
                                        bitcoinController, mainFrame, sendRequest, true);
                                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.
                    
            sendBitcoinConfirmDialog = new SendBitcoinConfirmDialog(super.bitcoinController, mainFrame, sendRequest);
            sendBitcoinConfirmDialog.setVisible(true);
                            } else {
            // There is not enough money.
            // TODO setup validation parameters accordingly so that it displays ok.
            validationErrorDialog = new ValidationErrorDialog(super.bitcoinController, mainFrame, sendRequest, true);
            validationErrorDialog.setVisible(true);
                            }
               */

        } else {
            validationErrorDialog = new ValidationErrorDialog(super.bitcoinController, mainFrame, null, false);
            validationErrorDialog.setVisible(true);
        }
    } catch (WrongNetworkException e1) {
        logMessage(e1);
    } catch (AddressFormatException e1) {
        logMessage(e1);
    } catch (KeyCrypterException e1) {
        logMessage(e1);
    } catch (Exception e1) {
        logMessage(e1);
    }
}

From source file:com.spotify.reaper.unit.service.SegmentRunnerTest.java

@Test
public void successTest() throws InterruptedException, ReaperException, ExecutionException {
    final IStorage storage = new MemoryStorage();
    RepairUnit cf = storage// w w w . j a  v a 2  s.co  m
            .addRepairUnit(new RepairUnit.Builder("reaper", "reaper", Sets.newHashSet("reaper")));
    RepairRun run = storage.addRepairRun(
            new RepairRun.Builder("reaper", cf.getId(), DateTime.now(), 0.5, 1, RepairParallelism.PARALLEL));
    storage.addRepairSegments(Collections.singleton(
            new RepairSegment.Builder(run.getId(), new RingRange(BigInteger.ONE, BigInteger.ZERO), cf.getId())),
            run.getId());
    final long segmentId = storage.getNextFreeSegment(run.getId()).get().getId();

    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final MutableObject<Future<?>> future = new MutableObject<>();

    AppContext context = new AppContext();
    context.storage = storage;
    context.jmxConnectionFactory = new JmxConnectionFactory() {
        @Override
        public JmxProxy connect(final Optional<RepairStatusHandler> handler, String host) {
            JmxProxy jmx = mock(JmxProxy.class);
            when(jmx.getClusterName()).thenReturn("reaper");
            when(jmx.isConnectionAlive()).thenReturn(true);
            when(jmx.tokenRangeToEndpoint(anyString(), any(RingRange.class)))
                    .thenReturn(Lists.newArrayList(""));
            when(jmx.triggerRepair(any(BigInteger.class), any(BigInteger.class), anyString(),
                    Matchers.<RepairParallelism>any(), Sets.newHashSet(anyString())))
                            .then(new Answer<Integer>() {
                                @Override
                                public Integer answer(InvocationOnMock invocation) {
                                    assertEquals(RepairSegment.State.NOT_STARTED,
                                            storage.getRepairSegment(segmentId).get().getState());
                                    future.setValue(executor.submit(new Runnable() {
                                        @Override
                                        public void run() {
                                            handler.get().handle(1, ActiveRepairService.Status.STARTED,
                                                    "Repair command 1 has started");
                                            assertEquals(RepairSegment.State.RUNNING,
                                                    storage.getRepairSegment(segmentId).get().getState());
                                            // report about an unrelated repair. Shouldn't affect anything.
                                            handler.get().handle(2, ActiveRepairService.Status.SESSION_FAILED,
                                                    "Repair command 2 has failed");
                                            handler.get().handle(1, ActiveRepairService.Status.SESSION_SUCCESS,
                                                    "Repair session succeeded in command 1");
                                            assertEquals(RepairSegment.State.DONE,
                                                    storage.getRepairSegment(segmentId).get().getState());
                                            handler.get().handle(1, ActiveRepairService.Status.FINISHED,
                                                    "Repair command 1 has finished");
                                            assertEquals(RepairSegment.State.DONE,
                                                    storage.getRepairSegment(segmentId).get().getState());
                                        }
                                    }));
                                    return 1;
                                }
                            });

            return jmx;
        }
    };
    RepairRunner rr = mock(RepairRunner.class);
    RepairUnit ru = mock(RepairUnit.class);
    SegmentRunner sr = new SegmentRunner(context, segmentId, Collections.singleton(""), 1000, 0.5,
            RepairParallelism.PARALLEL, "reaper", ru, rr);
    sr.run();

    future.getValue().get();
    executor.shutdown();

    assertEquals(RepairSegment.State.DONE, storage.getRepairSegment(segmentId).get().getState());
    assertEquals(0, storage.getRepairSegment(segmentId).get().getFailCount());
}

From source file:mil.jpeojtrs.sca.util.AnyUtils.java

/**
 * Attempts to convert the string value to the appropriate Java type.
 * /*w  w w . j a va2s. c om*/
 * @param stringValue the string form of the value
 * @param type the string form of the TypeCode
 * @return A Java object of theString corresponding to the typecode
 */
private static Object primitiveConvertString(final String stringValue, final String type) {
    if (stringValue == null) {
        return null;
    }
    if ("string".equals(type)) {
        return stringValue;
    } else if ("wstring".equals(type)) {
        return stringValue;
    } else if ("boolean".equals(type)) {
        if ("true".equalsIgnoreCase(stringValue) || "false".equalsIgnoreCase(stringValue)) {
            return Boolean.parseBoolean(stringValue);
        }
        throw new IllegalArgumentException(stringValue + " is not a valid boolean value");
    } else if ("char".equals(type)) {
        switch (stringValue.length()) {
        case 1:
            return stringValue.charAt(0);
        case 0:
            return null;
        default:
            throw new IllegalArgumentException(stringValue + " is not a valid char value");
        }
    } else if ("wchar".equals(type)) {
        return stringValue.charAt(0);
    } else if ("double".equals(type)) {
        return Double.parseDouble(stringValue);
    } else if ("float".equals(type)) {
        return Float.parseFloat(stringValue);
    } else if ("short".equals(type)) {
        return Short.decode(stringValue);
    } else if ("long".equals(type)) {
        return Integer.decode(stringValue);
    } else if ("longlong".equals(type)) {
        return Long.decode(stringValue);
    } else if ("ulong".equals(type)) {
        final long MAX_UINT = 2L * Integer.MAX_VALUE + 1L;
        final Long retVal = Long.decode(stringValue);
        if (retVal < 0 || retVal > MAX_UINT) {
            throw new IllegalArgumentException(
                    "ulong value must be greater than '0' and less than " + MAX_UINT);
        }
        return retVal;
    } else if ("ushort".equals(type)) {
        final int MAX_USHORT = 2 * Short.MAX_VALUE + 1;
        final Integer retVal = Integer.decode(stringValue);
        if (retVal < 0 || retVal > MAX_USHORT) {
            throw new IllegalArgumentException(
                    "ushort value must be greater than '0' and less than " + MAX_USHORT);
        }
        return retVal;
    } else if ("ulonglong".equals(type)) {
        final BigInteger MAX_ULONG_LONG = BigInteger.valueOf(Long.MAX_VALUE).multiply(BigInteger.valueOf(2))
                .add(BigInteger.ONE);
        final BigInteger retVal = AnyUtils.bigIntegerDecode(stringValue);
        if (retVal.compareTo(BigInteger.ZERO) < 0 || retVal.compareTo(MAX_ULONG_LONG) > 0) {
            throw new IllegalArgumentException(
                    "ulonglong value must be greater than '0' and less than " + MAX_ULONG_LONG.toString());
        }
        return retVal;
    } else if ("objref".equals(type)) {
        if ("".equals(stringValue)) {
            return null;
        }
        final List<String> objrefPrefix = Arrays.asList("IOR:", "corbaname:", "corbaloc:");
        for (final String prefix : objrefPrefix) {
            if (stringValue.startsWith(prefix)) {
                return stringValue;
            }
        }
        throw new IllegalArgumentException(stringValue + " is not a valid objref value");
    } else if ("octet".equals(type)) {
        final short MIN_OCTET = 0;
        final short MAX_OCTET = 0xFF;
        final short val = Short.decode(stringValue);
        if (val <= MAX_OCTET && val >= MIN_OCTET) {
            return Short.valueOf(val);
        }
        throw new IllegalArgumentException(stringValue + " is not a valid octet value");
    } else {
        throw new IllegalArgumentException("Unknown CORBA Type: " + type);
    }
}

From source file:org.openvpms.component.system.common.jxpath.OpenVPMSTypeConverter.java

@SuppressWarnings("unchecked")
@Override//ww w .  j  a  v  a  2 s .  c o  m
public Object convert(Object object, Class toType) {
    if (object == null) {
        if (toType.isPrimitive()) {
            return convertNullToPrimitive(toType);
        }
        return null;
    }

    if (toType == Object.class) {
        if (object instanceof NodeSet) {
            return convert(((NodeSet) object).getValues(), toType);
        } else if (object instanceof Pointer) {
            return convert(((Pointer) object).getValue(), toType);
        }
        return object;
    }

    Class fromType = object.getClass();
    if (fromType.equals(toType) || toType.isAssignableFrom(fromType)) {
        return object;
    }

    if (fromType.isArray()) {
        int length = Array.getLength(object);
        if (toType.isArray()) {
            Class cType = toType.getComponentType();

            Object array = Array.newInstance(cType, length);
            for (int i = 0; i < length; i++) {
                Object value = Array.get(object, i);
                Array.set(array, i, convert(value, cType));
            }
            return array;
        } else if (Collection.class.isAssignableFrom(toType)) {
            Collection collection = allocateCollection(toType);
            for (int i = 0; i < length; i++) {
                collection.add(Array.get(object, i));
            }
            return unmodifiableCollection(collection);
        } else {
            if (length > 0) {
                Object value = Array.get(object, 0);
                return convert(value, toType);
            } else {
                return convert("", toType);
            }
        }
    } else if (object instanceof Collection) {
        int length = ((Collection) object).size();
        if (toType.isArray()) {
            Class cType = toType.getComponentType();
            Object array = Array.newInstance(cType, length);
            Iterator it = ((Collection) object).iterator();
            for (int i = 0; i < length; i++) {
                Object value = it.next();
                Array.set(array, i, convert(value, cType));
            }
            return array;
        } else if (Collection.class.isAssignableFrom(toType)) {
            Collection collection = allocateCollection(toType);
            collection.addAll((Collection) object);
            return unmodifiableCollection(collection);
        } else {
            if (length > 0) {
                Object value;
                if (object instanceof List) {
                    value = ((List) object).get(0);
                } else {
                    Iterator it = ((Collection) object).iterator();
                    value = it.next();
                }
                return convert(value, toType);
            } else {
                return convert("", toType);
            }
        }
    } else if (object instanceof NodeSet) {
        return convert(((NodeSet) object).getValues(), toType);
    } else if (object instanceof Pointer) {
        return convert(((Pointer) object).getValue(), toType);
    } else if (toType == String.class) {
        return object.toString();
    } else if (object instanceof Boolean) {
        if (toType == boolean.class) {
            return object;
        }
        boolean value = ((Boolean) object).booleanValue();
        return allocateNumber(toType, value ? 1 : 0);
    } else if (object instanceof BigDecimal) {
        BigDecimal value = (BigDecimal) object;
        if (toType == boolean.class || toType == Boolean.class) {
            return value == BigDecimal.ZERO ? Boolean.FALSE : Boolean.TRUE;
        }
        if (toType.isPrimitive() || Number.class.isAssignableFrom(toType)) {
            return allocateNumber(toType, value);
        }
    } else if (object instanceof BigInteger) {
        BigInteger value = (BigInteger) object;
        if (toType == boolean.class || toType == Boolean.class) {
            return value == BigInteger.ZERO ? Boolean.FALSE : Boolean.TRUE;
        }
        if (toType.isPrimitive() || Number.class.isAssignableFrom(toType)) {
            return allocateNumber(toType, value);
        }
    } else if (object instanceof Number) {
        double value = ((Number) object).doubleValue();
        if (toType == boolean.class || toType == Boolean.class) {
            return value == 0.0 ? Boolean.FALSE : Boolean.TRUE;
        }
        if (toType.isPrimitive() || Number.class.isAssignableFrom(toType)) {
            return allocateNumber(toType, value);
        }
    } else if (object instanceof Character) {
        if (toType == char.class) {
            return object;
        }
    } else if (object instanceof String) {
        Object value = convertStringToPrimitive(object, toType);
        if (value != null) {
            return value;
        }
    }

    Converter converter = ConvertUtils.lookup(toType);
    if (converter != null) {
        return converter.convert(toType, object);
    }

    throw new JXPathTypeConversionException("Cannot convert " + object.getClass() + " to " + toType);
}