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:groovy.ui.GroovyMain.java

/**
 * Process a script against a single input file.
 *
 * @param s      script to execute./*from  w  w  w. j  ava2  s .co m*/
 * @param reader input file.
 * @param pw     output sink.
 */
private void processReader(Script s, BufferedReader reader, PrintWriter pw) throws IOException {
    String line;
    String lineCountName = "count";
    s.setProperty(lineCountName, BigInteger.ZERO);
    String autoSplitName = "split";
    s.setProperty("out", pw);

    try {
        InvokerHelper.invokeMethod(s, "begin", null);
    } catch (MissingMethodException mme) {
        // ignore the missing method exception
        // as it means no begin() method is present
    }

    while ((line = reader.readLine()) != null) {
        s.setProperty("line", line);
        s.setProperty(lineCountName, ((BigInteger) s.getProperty(lineCountName)).add(BigInteger.ONE));

        if (autoSplit) {
            s.setProperty(autoSplitName, line.split(splitPattern));
        }

        Object o = s.run();

        if (autoOutput && o != null) {
            pw.println(o);
        }
    }

    try {
        InvokerHelper.invokeMethod(s, "end", null);
    } catch (MissingMethodException mme) {
        // ignore the missing method exception
        // as it means no end() method is present
    }
}

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

private SendRequest createSendRequest(String sendAddress, String sendAmount) throws AddressFormatException {
    // Create a SendRequest.
    Address sendAddressObject;//  w w  w.  j  av a2  s . c o m

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

From source file:com.aegiswallet.services.PeerBlockchainService.java

@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    if (intent == null)
        return START_NOT_STICKY;

    final String action = intent.getAction();

    if (PeerBlockchainService.ACTION_CANCEL_COINS_RECEIVED.equals(action)) {
        notificationCount = 0;/*from w  w  w . j a  va2  s  .  c om*/
        notificationAccumulatedAmount = BigInteger.ZERO;
        notificationAddresses.clear();
        nm.cancel(NOTIFICATION_ID_COINS_RECEIVED);
    } else if (PeerBlockchainService.ACTION_RESET_BLOCKCHAIN.equals(action)) {
        resetBlockchainOnShutdown = true;
        stopSelf();
    } else if (PeerBlockchainService.ACTION_BROADCAST_TRANSACTION.equals(action)) {
        String addressExtra = intent.getStringExtra("address");
        String amountExtra = intent.getStringExtra("amount");
        boolean justDecrypted = intent.getBooleanExtra("justDecrypted", false);
        String tagExtra = intent.getStringExtra("tagText");
        BigInteger amountBigInt = new BigInteger(amountExtra);
        final Wallet wallet = application.getWallet();

        try {
            Address address = new Address(Constants.NETWORK_PARAMETERS, addressExtra);
            Wallet.SendRequest sendRequest = Wallet.SendRequest.to(address, amountBigInt);

            //Adding the tag to the shared prefs
            tagPrefs = application.getSharedPreferences(getString(R.string.tag_pref_filename),
                    Context.MODE_PRIVATE);

            tagPrefs.edit().putString(sendRequest.tx.getHashAsString(), tagExtra).commit();

            sendRequest.ensureMinRequiredFee = false;
            //sendRequest.fee = BigInteger.valueOf(1000);
            Transaction transaction = wallet.sendCoinsOffline(sendRequest);

            if (transaction != null && peerGroup != null) {
                ListenableFuture<Transaction> future = peerGroup.broadcastTransaction(transaction);
                //TODO: Maybe doe something with future?
            }

        } catch (AddressFormatException e) {
            Log.e(TAG, "Address format exception " + e.getMessage());
        } catch (InsufficientMoneyException e) {
            Log.e(TAG, "Insufficient Money Exception " + e.getMessage());
        } catch (NullPointerException e) {
            Log.e(TAG, "null pointer exception: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "illegal argument exception: " + e.getMessage());
        } catch (IllegalStateException e) {
            Log.e(TAG, "illegal state exception: " + e.getMessage());
        } catch (KeyCrypterException e) {
            Log.e(TAG, "key crypter exception: " + e.getMessage());
        } finally {

            if (justDecrypted) {
                if (application.getKeyCache() != null) {
                    wallet.encrypt(application.getKeyCache().getKeyCrypter(),
                            application.getKeyCache().getAesKey());

                    String x2 = prefs.getString(Constants.SHAMIR_ENCRYPTED_KEY, null);

                    if (x2 != null) {
                        String encryptedX2 = WalletUtils.encryptString(x2,
                                application.getKeyCache().getPassword());
                        prefs.edit().putString(Constants.SHAMIR_ENCRYPTED_KEY, encryptedX2).commit();
                    }

                }
            }

        }
    }

    return START_NOT_STICKY;
}

From source file:adalid.commons.util.ObjUtils.java

public static Number opposite(Object o) {
    if (o == null) {
        return null;
    } else if (o instanceof Byte) {
        Byte pdq = (Byte) o;
        return NumUtils.newByte(0 - pdq);
    } else if (o instanceof Short) {
        Short pdq = (Short) o;
        return NumUtils.newShort(0 - pdq);
    } else if (o instanceof Integer) {
        Integer pdq = (Integer) o;
        return 0 - pdq;
    } else if (o instanceof Long) {
        Long pdq = (Long) o;
        return 0L - pdq;
    } else if (o instanceof Float) {
        Float pdq = (Float) o;
        return 0.0F - pdq;
    } else if (o instanceof Double) {
        Double pdq = (Double) o;
        return 0.0D - pdq;
    } else if (o instanceof BigInteger) {
        BigInteger pdq = (BigInteger) o;
        return BigInteger.ZERO.subtract(pdq);
    } else if (o instanceof BigDecimal) {
        BigDecimal pdq = (BigDecimal) o;
        return BigDecimal.ZERO.subtract(pdq);
    }// ww w .jav  a 2 s .  c o  m
    return null;
}

From source file:com.aegiswallet.utils.WalletUtils.java

public static boolean isTransactionRelevant(Transaction tx, Wallet wallet) throws ScriptException {

    return tx.getValueSentFromMe(wallet).compareTo(BigInteger.ZERO) > 0
            || tx.getValueSentToMe(wallet).compareTo(BigInteger.ZERO) > 0 || tx.isPending();

}

From source file:org.opennms.netmgt.config.SnmpEventInfo.java

/**
 * Creates an SNMP config definition representing the data in this class.
 * The defintion will either have one specific IP element or one Range element.
 *
 * @return a {@link org.opennms.netmgt.config.snmp.Definition} object.
 */// w  w w .j a v  a  2s .  co m
public Definition createDef() {
    Definition definition = new Definition();
    if (StringUtils.isNotEmpty(getVersion()))
        definition.setVersion(getVersion());
    if (getRetryCount() != 0)
        definition.setRetry(Integer.valueOf(getRetryCount()));
    if (getTimeout() != 0)
        definition.setTimeout(Integer.valueOf(getTimeout()));
    if (getPort() != 0)
        definition.setPort(Integer.valueOf(getPort()));
    if (getMaxRepetitions() != 0)
        definition.setMaxRepetitions(Integer.valueOf(getMaxRepetitions()));
    if (getMaxVarsPerPdu() != 0)
        definition.setMaxVarsPerPdu(Integer.valueOf(getMaxVarsPerPdu()));
    if (getMaxRequestSize() != 0)
        definition.setMaxRequestSize(Integer.valueOf(getMaxRequestSize()));
    if (StringUtils.isNotEmpty(getProxyHost()))
        definition.setProxyHost(getProxyHost());

    // version dependend parameters
    if (getVersion() != null && getVersion().equals("v3")) {
        if (StringUtils.isNotEmpty(getAuthPassphrase()))
            definition.setAuthPassphrase(getAuthPassphrase());
        if (StringUtils.isNotEmpty(getAuthProtocol()))
            definition.setAuthProtocol(getAuthProtocol());
        if (StringUtils.isNotEmpty(getContextEngineId()))
            definition.setContextEngineId(getContextEngineId());
        if (StringUtils.isNotEmpty(getContextName()))
            definition.setContextName(getContextName());
        if (StringUtils.isNotEmpty(getEngineId()))
            definition.setEngineId(getEngineId());
        if (StringUtils.isNotEmpty(getEnterpriseId()))
            definition.setEnterpriseId(getEnterpriseId());
        if (StringUtils.isNotEmpty(getPrivPassPhrase()))
            definition.setPrivacyPassphrase(getPrivPassPhrase());
        if (StringUtils.isNotEmpty(getPrivProtocol()))
            definition.setPrivacyProtocol(getPrivProtocol());
        if (StringUtils.isNotEmpty(getSecurityName()))
            definition.setSecurityName(getSecurityName());
        if (getSecurityLevel() > 0)
            definition.setSecurityLevel(getSecurityLevel());
    } else { //v1, v2c or invalid version
        if (getReadCommunityString() != null)
            definition.setReadCommunity(getReadCommunityString());
        if (getWriteCommunityString() != null)
            definition.setWriteCommunity(getWriteCommunityString());
    }

    if (isSpecific()) {
        definition.addSpecific(getFirstIPAddress());
    } else {

        // first ip address of range must be < than last ip address of range
        if (BigInteger.ZERO
                .compareTo(InetAddressUtils.difference(getFirstIPAddress(), getLastIPAddress())) < 0) {
            LOG.error("createDef: Can not create Definition when specified last is < first IP address: {}",
                    this);
            throw new IllegalArgumentException(
                    "First: " + getFirstIPAddress() + " is greater than: " + getLastIPAddress());
        }

        Range range = new Range();
        range.setBegin(getFirstIPAddress());
        range.setEnd(getLastIPAddress());
        definition.addRange(range);
    }
    LOG.debug("createDef: created new Definition from: {}", this);
    return definition;
}

From source file:energy.usef.dso.service.business.DsoPlanboardBusinessService.java

/**
 * Sums the power of the Flex Orders.//from w  w w.j  ava 2 s .co  m
 *
 * @param ptuFlexOrders {@link List} of {@link PtuFlexOrder}.
 * @return the sum of the power.
 */
private BigInteger sumPowerOfFlexOrders(List<PtuFlexOrder> ptuFlexOrders) {
    BigInteger result = BigInteger.ZERO;
    for (PtuFlexOrder ptuFlexOrder : ptuFlexOrders) {
        if (AcknowledgementStatus.ACCEPTED != ptuFlexOrder.getAcknowledgementStatus()) {
            continue;
        }
        PtuFlexOffer ptuFlexOffer = getRelatedPtuFlexOffer(ptuFlexOrder);
        result = result.add(ptuFlexOffer.getPower());
    }
    return result;
}

From source file:com.oncore.calorders.rest.service.extension.OrderHistoryFacadeRESTExtension.java

/**
 * Fetch all orders by DepartmentUid and ordered by Date ascending
 *
 * @param departmentId a valid department id
 * @return a structure of orders history ordered by Date
 *
 * @throws com.oncore.calorders.core.exceptions.DataAccessException
 *//*  w  w  w.j  a  v  a  2  s  .co m*/
@GET
@Path("findAllOrderHistory/{departmentId}")
@Produces({ MediaType.APPLICATION_JSON })
public List<OrderHistoryData> findAllOrderHistory(@PathParam("departmentId") Integer departmentId)
        throws DataAccessException {
    List<OrderHistoryData> orderHistoryDatas = new ArrayList<OrderHistoryData>();
    List<OrderHistory> orderHistorys = new ArrayList<OrderHistory>();

    orderHistorys = getEntityManager().createQuery(
            "SELECT oh FROM OrderHistory oh join oh.ordStatusCd os join oh.ptyUidFk pt join pt.groupPartyAssocCollection gpa join gpa.grpUidFk g join g.depUidFk d join oh.orderProductAssocCollection opa where d.depUid = :depUid ORDER BY oh.createTs DESC",
            OrderHistory.class).setParameter("depUid", departmentId).getResultList();
    if (orderHistorys != null && orderHistorys.size() > 0) {
        for (OrderHistory orderHistory : orderHistorys) {
            OrderHistoryData data = new OrderHistoryData();

            data.setOrderHistoryId(orderHistory.getOrdUid());
            if (orderHistory.getPtyUidFk() != null
                    && orderHistory.getPtyUidFk().getGroupPartyAssocCollection() != null
                    && orderHistory.getPtyUidFk().getGroupPartyAssocCollection().size() > 0) {
                for (GroupPartyAssoc assoc : orderHistory.getPtyUidFk().getGroupPartyAssocCollection()) {
                    if (assoc.getGrpUidFk() != null && assoc.getGrpUidFk().getDepUidFk() != null) {
                        data.setOrderAgency(assoc.getGrpUidFk().getDepUidFk().getDepName());
                        break;
                    }
                }
            }

            data.setOrderDate(orderHistory.getCreateTs());

            if (orderHistory.getOrderProductAssocCollection() != null
                    && orderHistory.getOrderProductAssocCollection().size() > 0) {
                String skuConcat = new String();
                BigDecimal totalPrice = new BigDecimal(BigInteger.ZERO);
                List<OrderProductAssoc> productAssocs = new ArrayList<OrderProductAssoc>();

                for (OrderProductAssoc assoc : orderHistory.getOrderProductAssocCollection()) {
                    productAssocs.add(assoc);
                    totalPrice = totalPrice.add(assoc.getOpaPrice());
                }

                data.setOrderPrice(totalPrice);

                for (int i = 0; i < productAssocs.size(); i++) {

                    if (skuConcat.length() > 25) {
                        skuConcat = skuConcat + "...";
                        break;
                    }

                    if (productAssocs.get(i).getPrdUidFk() != null
                            && productAssocs.get(i).getPrdUidFk().getPrdSku() != null) {
                        if (i == 0) {
                            skuConcat = productAssocs.get(i).getPrdUidFk().getPrdSku();
                        } else {
                            skuConcat = skuConcat + ", " + productAssocs.get(i).getPrdUidFk().getPrdSku();
                        }
                    }
                }
                data.setOrderDescription(skuConcat.trim());
            }

            data.setOrderPoNumber(null);

            if (orderHistory.getOrdStatusCd() != null) {
                data.setOrderStatus(orderHistory.getOrdStatusCd().getShortDesc());
            }
            orderHistoryDatas.add(data);
        }

    }

    return orderHistoryDatas;
}

From source file:org.multibit.utils.CSMiscUtils.java

public static String getDescriptionOfTransactionAssetChanges(Wallet wallet, Transaction tx) {
    if (wallet == null || tx == null)
        return "";

    Map<Integer, BigInteger> receiveMap = wallet.CS.getAssetsSentToMe(tx);
    Map<Integer, BigInteger> sendMap = wallet.CS.getAssetsSentFromMe(tx);

    //   System.out.println(">>>> tx = " + tx.getHashAsString());
    //   System.out.println(">>>>     receive map = " +  receiveMap);
    //   System.out.println(">>>>     send map = " +  sendMap);

    //Map<String, String> nameAmountMap = new TreeMap<>();
    ArrayList<String> nameAmounts = new ArrayList<>();

    boolean isSentByMe = tx.sent(wallet);
    Map<Integer, BigInteger> loopMap = (isSentByMe) ? sendMap : receiveMap;

    //   Integer assetID = null;
    BigInteger netAmount = null;/* ww w .ja v  a 2s .com*/

    //   for (Map.Entry<Integer, BigInteger> entry : loopMap.entrySet()) {
    for (Integer assetID : loopMap.keySet()) {
        //       assetID = entry.getKey();
        if (assetID == null || assetID == 0)
            continue; // skip bitcoin

        BigInteger receivedAmount = receiveMap.get(assetID); // should be number of raw units
        BigInteger sentAmount = sendMap.get(assetID);
        boolean isReceivedAmountMissing = (receivedAmount == null);
        boolean isSentAmountMissing = (sentAmount == null);

        netAmount = BigInteger.ZERO;
        if (!isReceivedAmountMissing)
            netAmount = netAmount.add(receivedAmount);
        if (!isSentAmountMissing)
            netAmount = netAmount.subtract(sentAmount);

        if (isSentByMe && !isSentAmountMissing && sentAmount.equals(BigInteger.ZERO)) {
            // Catch a case where for a send transaction, the send amount for an asset is 0,
            // but the receive cmount is not 0.  Also the asset was not valid.
            continue;
        }

        CSAsset asset = wallet.CS.getAsset(assetID);
        if (asset == null) {
            // something went wrong, we have asset id but no asset, probably deleted.
            // For now, we carry on, and we display what we know.
        }

        if (netAmount.equals(BigInteger.ZERO) && isSentByMe) {
            // If net asset is 0 and this is our send transaction,
            // we don't need to show anything, as this probably due to implicit transfer.
            // So continue the loop.
            continue;
        }

        if (netAmount.equals(BigInteger.ZERO) && !isSentByMe) {
            // Receiving an asset, where the value is 0 because its not confirmed yet,
            // or not known because asset files not uploaded so we dont know display format.
            // Anyway, we don't do anything here as we do want to display this incoming
            // transaction the best we can.
        }

        //       System.out.println(">>>>     isSentAmountMissing = " + isSentAmountMissing);
        //       System.out.println(">>>>     asset reference = " + asset.getAssetReference());
        //       System.out.println(">>>>     asset name = " + asset.getName());

        String name = null;
        CoinSparkGenesis genesis = null;
        boolean isUnknown = false;
        if (asset != null) {
            genesis = asset.getGenesis();
            name = asset.getNameShort(); // could return null?
        }
        if (name == null) {
            isUnknown = true;
            if (genesis != null) {
                name = "Asset from " + genesis.getDomainName();
            } else {
                // No genesis block found yet
                name = "Other Asset";
            }
        }

        String s1 = null;
        if (asset == null || isUnknown == true || (netAmount.equals(BigInteger.ZERO) && !isSentByMe)) {
            // We don't have formatting details since asset is unknown or deleted
            // If there is a quantity, we don't display it since we don't have display format info
            // Of if incoming asset transfer, unconfirmed, it will be zero, so show ... instead
            s1 = "...";
        } else {
            BigDecimal displayUnits = getDisplayUnitsForRawUnits(asset, netAmount);
            s1 = CSMiscUtils.getFormattedDisplayString(asset, displayUnits);
        }
        String s2 = name + ": " + s1;
        nameAmounts.add(s2);
        //break; // TODO: return the first asset we find, in future return map<Integer,BigInteger>
    }

    if (!nameAmounts.isEmpty()) {
        Collections.sort(nameAmounts);
    }
    BigInteger satoshiAmount = receiveMap.get(0);
    satoshiAmount = satoshiAmount.subtract(sendMap.get(0));
    String btcAmount = Utils.bitcoinValueToFriendlyString(satoshiAmount);
    nameAmounts.add("BTC: " + btcAmount);

    String result = StringUtils.join(nameAmounts, ", ");

    //   System.out.println(">>>>     result = " +  result);

    return result;
}

From source file:cc.redberry.core.number.Complex.java

@Override
public Complex pow(BigInteger exponent) {
    if (exponent.compareTo(BigInteger.ZERO) < 0)
        return reciprocal().pow(exponent.negate());

    Complex result = Complex.ONE;//from   www  .  ja v a 2s .  co m
    Complex k2p = this;
    while (!BigInteger.ZERO.equals(exponent)) {
        if (exponent.testBit(0))
            result = result.multiply(k2p);

        k2p = k2p.multiply(k2p);
        exponent = exponent.shiftRight(1);
    }

    return result;
}