Example usage for java.math BigInteger add

List of usage examples for java.math BigInteger add

Introduction

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

Prototype

BigInteger add(long val) 

Source Link

Document

Package private methods used by BigDecimal code to add a BigInteger with a long.

Usage

From source file:de.decoit.visa.net.IPNetwork.java

/**
 * Increment the provided address bit mask by the specified amount and
 * return it. Since {@link java.math.BigInteger BigInteger} objects are
 * immutable this method will return a new object. The provided object will
 * remain unchanged.//www . j a v a  2s. c om
 *
 * @param pMask The mask of the address which will be incremented
 * @param pAmount The amount which will be added to the address
 * @return The incremented bit mask
 */
private BigInteger incrAddressMask(BigInteger pMask, BigInteger pAmount) {
    return pMask.add(pAmount);
}

From source file:com.spotify.hdfs2cass.CassandraPartitionerTest.java

@Test
public void testGetPartition() throws Exception {
    final int maxNodes = 5;

    final List<String> tokenRanges = new ArrayList<String>();

    BigInteger start = BigInteger.ZERO;
    BigInteger step = RandomPartitioner.MAXIMUM.divide(BigInteger.valueOf(maxNodes));
    for (int i = 0; i < maxNodes - 1; i++) {
        BigInteger end = start.add(step);

        tokenRanges.add(String.format("%d:%d", start, end));
        start = end.add(BigInteger.ONE);
    }//w  w w  .  j  a v  a 2s  .co m

    tokenRanges.add(String.format("%d:0", start));

    final JobConf conf = new JobConf();
    conf.set(ClusterInfo.SPOTIFY_CASSANDRA_TOKENS_PARAM, StringUtils.join(tokenRanges, ","));
    conf.set(ClusterInfo.SPOTIFY_CASSANDRA_PARTITIONER_PARAM, "org.apache.cassandra.dht.RandomPartitioner");

    CassandraPartitioner instance = new CassandraPartitioner();
    instance.configure(conf);

    Text key = new Text("foobar");
    assertEquals(2, instance.getPartition(key, null, 5));

    key = new Text("someotherkey");
    assertEquals(1, instance.getPartition(key, null, 5));

    key = new Text("1ce5cf4b861941f4aa799ae39ac9daa4");
    assertEquals(4, instance.getPartition(key, null, 5));
}

From source file:PalidromeArray.java

public PalidromeArray(BigInteger[] array) {
    this.totalLength = BigInteger.valueOf(array.length);
    this.halfLength = totalLength.divide(TWO);
    if (MathUtil.isOdd(totalLength)) {
        isEven = false;/*from  w  w w.j a v a 2 s  .c  om*/
        halfLength = halfLength.add(BigInteger.ONE);
    }
    this.array = new ConcurrentHashMap<BigInteger, BigInteger>();

    BigInteger index = BigInteger.ZERO;
    for (BigInteger bi : array) {
        this.array.put(index, bi);
        index = index.add(BigInteger.ONE);
    }
}

From source file:co.rsk.validators.BlockTxsValidationRule.java

@Override
public boolean isValid(Block block, Block parent) {
    if (block == null || parent == null) {
        return false;
    }/*  w  w  w . ja va  2s . com*/

    List<Transaction> txs = block.getTransactionsList();
    if (CollectionUtils.isEmpty(txs))
        return true;

    Repository parentRepo = repository.getSnapshotTo(parent.getStateRoot());

    Map<ByteArrayWrapper, BigInteger> curNonce = new HashMap<>();

    for (Transaction tx : txs) {
        byte[] txSender = tx.getSender();
        ByteArrayWrapper key = new ByteArrayWrapper(txSender);
        BigInteger expectedNonce = curNonce.get(key);
        if (expectedNonce == null) {
            expectedNonce = parentRepo.getNonce(txSender);
        }
        curNonce.put(key, expectedNonce.add(ONE));
        BigInteger txNonce = new BigInteger(1, tx.getNonce());

        if (!expectedNonce.equals(txNonce)) {
            logger.error("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}",
                    txNonce, expectedNonce, parentRepo.getNonce(txSender), tx);

            panicProcessor.panic("invalidtransaction",
                    String.format(
                            "Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s",
                            txNonce.toString(), expectedNonce.toString(),
                            parentRepo.getNonce(txSender).toString(), Hex.toHexString(tx.getHash())));

            return false;
        }
    }

    return true;
}

From source file:org.apache.spark.network.crypto.AuthEngine.java

@VisibleForTesting
byte[] rawResponse(byte[] challenge) {
    BigInteger orig = new BigInteger(challenge);
    BigInteger response = orig.add(ONE);
    return response.toByteArray();
}

From source file:org.jasig.cas.web.support.ThrottledSubmissionByIpAddressHandlerInterceptorAdapter.java

public void postHandle(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler, final ModelAndView modelAndView) throws Exception {
    if (!request.getMethod().equals("GET") || !"casLoginView".equals(modelAndView.getViewName())) {
        return;/*w w w .j  a v  a  2 s.c o  m*/
    }
    final String remoteAddr = request.getRemoteAddr();

    // workaround for the IPv6 bug in the original adapter. See CAS-639
    try {
        final String lastQuad = remoteAddr.substring(remoteAddr.lastIndexOf(".") + 1);
        final int intVersionOfLastQuad = Integer.parseInt(lastQuad);
        final Map<String, BigInteger> quadMap = this.restrictedIpAddressMaps[intVersionOfLastQuad - 1];

        synchronized (quadMap) {
            final BigInteger original = quadMap.get(lastQuad);
            BigInteger integer = ONE;

            if (original != null) {
                integer = original.add(ONE);
            }

            quadMap.put(lastQuad, integer);

            if (integer.compareTo(this.failureThreshhold) == 1) {
                log.warn("Possible hacking attack from " + remoteAddr + ". More than " + this.failureThreshhold
                        + " failed login attempts within " + this.failureTimeout + " seconds.");
                modelAndView.setViewName("casFailureAuthenticationThreshhold");
            }
        }
    } catch (NumberFormatException e) {
        log.warn(
                "Skipping ip-address blocking. Possible reason: IPv6 Address not supported: " + e.getMessage());
    } catch (Exception ex) {
        log.error(ex.getMessage());
    }
}

From source file:co.rsk.remasc.Remasc.java

/**
 * Implements the actual Remasc distribution logic
 */// ww w .j a  v  a  2 s  .c om
void processMinersFees() {
    if (!(executionTx instanceof RemascTransaction)) {
        //Detect
        // 1) tx to remasc that is not the latest tx in a block
        // 2) invocation to remasc from another contract (ie call opcode)
        throw new RemascInvalidInvocationException("Invoked Remasc outside last tx of the block");
    }
    this.addNewSiblings();

    long blockNbr = executionBlock.getNumber();

    long processingBlockNumber = blockNbr - remascConstants.getMaturity();
    if (processingBlockNumber < 1) {
        logger.debug("First block has not reached maturity yet, current block is {}", blockNbr);
        return;
    }
    BlockHeader processingBlockHeader = blockStore
            .getBlockByHashAndDepth(executionBlock.getParentHash(), remascConstants.getMaturity() - 1)
            .getHeader();
    // Adds current block fees to accumulated rewardBalance
    BigInteger processingBlockReward = BigInteger.valueOf(processingBlockHeader.getPaidFees());
    BigInteger rewardBalance = provider.getRewardBalance();
    rewardBalance = rewardBalance.add(processingBlockReward);
    provider.setRewardBalance(rewardBalance);

    if (processingBlockNumber - remascConstants.getSyntheticSpan() < 0) {
        logger.debug("First block has not reached maturity+syntheticSpan yet, current block is {}",
                executionBlock.getNumber());
        return;
    }

    // Takes from rewardBalance this block's height reward.
    BigInteger fullBlockReward = rewardBalance.divide(BigInteger.valueOf(remascConstants.getSyntheticSpan()));
    rewardBalance = rewardBalance.subtract(fullBlockReward);
    provider.setRewardBalance(rewardBalance);

    // Pay RSK labs cut
    BigInteger payToRskLabs = fullBlockReward.divide(BigInteger.valueOf(remascConstants.getRskLabsDivisor()));
    transfer(remascConstants.getRskLabsAddress(), payToRskLabs);
    fullBlockReward = fullBlockReward.subtract(payToRskLabs);

    List<Sibling> siblings = provider.getSiblings().get(processingBlockNumber);

    if (CollectionUtils.isNotEmpty(siblings)) {
        // Block has siblings, reward distribution is more complex
        boolean previousBrokenSelectionRule = provider.getBrokenSelectionRule();
        this.payWithSiblings(processingBlockHeader, fullBlockReward, siblings, previousBrokenSelectionRule);
        boolean brokenSelectionRule = this.isBrokenSelectionRule(processingBlockHeader, siblings);
        provider.setBrokenSelectionRule(brokenSelectionRule);
    } else {
        if (provider.getBrokenSelectionRule()) {
            // broken selection rule, apply punishment, ie burn part of the reward.
            BigInteger punishment = fullBlockReward
                    .divide(BigInteger.valueOf(remascConstants.getPunishmentDivisor()));
            fullBlockReward = fullBlockReward.subtract(punishment);
            provider.setBurnedBalance(provider.getBurnedBalance().add(punishment));
        }
        transfer(processingBlockHeader.getCoinbase(), fullBlockReward);
        provider.setBrokenSelectionRule(Boolean.FALSE);
    }

    this.removeUsedSiblings(processingBlockHeader);
}

From source file:de.decoit.visa.net.IPAddress.java

/**
 * Return a {@link java.math.BigInteger BigInteger} object containing the
 * bit mask of this address./*from  w w w  .  ja v a  2s . co  m*/
 *
 * @return Bit mask of this address
 */
BigInteger toBigIntBitmask() {
    BigInteger rv = BigInteger.ZERO;

    for (int i = 0; i < ipAddressGroups.length; i++) {
        rv = rv.add(BigInteger.valueOf(ipAddressGroups[i]));

        if (i < ipAddressGroups.length - 1) {
            rv = rv.shiftLeft(ipVersion.getSegmentBitCount());
        }
    }

    return rv;
}

From source file:nl.strohalm.cyclos.entities.ads.AdCategory.java

/**
 * returns a BigInteger indicating the global order index of the category. In the global order, whenever an item with children is encountered, all
 * child nodes are first handled before going on with the next item/node on the same level.<br>
 * Note that this method only works correctly with a maximum of 999 subcategories for a certain category.
 * @author rinke/*from w w w . j ava 2s .com*/
 */
public BigInteger getGlobalOrder() {
    if (globalOrder == null) {
        final int correctedLevel = AdCategory.MAX_LEVEL - getLevel();
        final BigInteger levelFactor = new BigInteger("1000").pow(correctedLevel);
        // specified indexes are always > 0. Unspecified indexes of 0 mess up the calculation, so...
        final Integer index = (getOrder() == 0) ? 1 : getOrder();
        final BigInteger parentGlobalOrder = (getParent() == null) ? BigInteger.ZERO
                : getParent().getGlobalOrder();
        globalOrder = parentGlobalOrder.add(levelFactor.multiply(new BigInteger(index.toString())));
    }
    return globalOrder;
}

From source file:de.tudarmstadt.ukp.teaching.uima.nounDecompounding.ranking.TotalFreqAmout.java

/**
 * Adds all frequency values for a special directory
 * @return/*from ww w. j  av  a2 s  .co m*/
 * @throws IOException
 */
protected BigInteger countFreq(FSDirectory dir) throws IOException {
    BigInteger count = BigInteger.valueOf(0);

    IndexReader reader = IndexReader.open(dir);
    for (int i = 0; i < reader.maxDoc(); i++) {
        if (reader.isDeleted(i)) {
            continue;
        }

        Document doc = reader.document(i);
        count = count.add(new BigInteger(doc.get("freq")));
    }

    return count;
}