Example usage for java.math BigInteger valueOf

List of usage examples for java.math BigInteger valueOf

Introduction

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

Prototype

private static BigInteger valueOf(int val[]) 

Source Link

Document

Returns a BigInteger with the given two's complement representation.

Usage

From source file:io.instacount.client.InstacountClientTest.java

@Test
public void testDecrement_NoPayload() throws InstacountClientException {
    final String counterName = UUID.randomUUID().toString();
    client.decrementShardedCounter(counterName);
    assertThat(client.getShardedCounter(counterName).getShardedCounter().getCount(),
            is(BigInteger.valueOf(-1L)));
}

From source file:it.nibbles.javacoin.block.BlockChainImpl.java

/**
 * Calculate the difficulty for the next block after the one supplied.
 *///from   w w  w  .  j  a v  a  2 s.c  om
public DifficultyTarget getNextDifficultyTarget(BlockChainLink link, Block newBlock) {
    // If we're calculating for the genesis block return
    // fixed difficulty
    if (link == null)
        return bitcoinFactory.maxDifficultyTarget();
    // Look whether it's time to change the difficulty setting
    // (only change every TARGET_RECALC blocks). If not, return the
    // setting of this block, because the next one has to have the same
    // target.
    if ((link.getHeight() + 1) % TARGET_RECALC != 0) {
        // Special rules for testnet (for testnet2 only after 15 Feb 2012)
        Block currBlock = link.getBlock();
        if (bitcoinFactory.isTestnet3()
                || (bitcoinFactory.isTestnet2() && currBlock.getCreationTime() > 1329180000000L)) {
            // If the new block's timestamp is more than 2* 10 minutes
            // then allow mining of a min-difficulty block.
            if (newBlock.getCreationTime() > link.getBlock().getCreationTime() + 2 * TARGET_SPACING)
                return bitcoinFactory.maxDifficultyTarget();
            else {
                // Return the last non-special-min-difficulty-rules-block
                // We could use a custom method here to load only block headers instead of full blocks
                // but this lack of performance is only for the testnet so we don't care
                while (link != null && (link.getHeight() % TARGET_RECALC) != 0 && link.getBlock()
                        .getCompressedTarget() == bitcoinFactory.maxDifficultyTarget().getCompressedTarget())
                    link = linkStorage.getLinkBlockHeader(link.getBlock().getPreviousBlockHash());
                if (link != null)
                    return new DifficultyTarget(link.getBlock().getCompressedTarget());
                else
                    return bitcoinFactory.maxDifficultyTarget();
            }
        }
        logger.debug("previous height {}, not change in target", link.getHeight());
        return new DifficultyTarget(link.getBlock().getCompressedTarget());
    }
    // We have to change the target. First collect the last TARGET_RECALC 
    // blocks (including the given block) 
    Block startBlock = link.getBlock();
    for (int i = 0; (i < TARGET_RECALC - 1) && (startBlock != null); i++)
        startBlock = getBlockHeader(startBlock.getPreviousBlockHash());
    // This shouldn't happen, we reached genesis
    if (startBlock == null)
        return bitcoinFactory.maxDifficultyTarget();
    // Calculate the time the TARGET_RECALC blocks took
    long calculatedTimespan = link.getBlock().getCreationTime() - startBlock.getCreationTime();
    if (calculatedTimespan < TARGET_TIMESPAN / 4)
        calculatedTimespan = TARGET_TIMESPAN / 4;
    if (calculatedTimespan > TARGET_TIMESPAN * 4)
        calculatedTimespan = TARGET_TIMESPAN * 4;
    // Calculate new target, but allow no more than maximum target
    DifficultyTarget difficultyTarget = new DifficultyTarget(link.getBlock().getCompressedTarget());
    BigInteger target = difficultyTarget.getTarget();
    target = target.multiply(BigInteger.valueOf(calculatedTimespan));
    target = target.divide(BigInteger.valueOf(TARGET_TIMESPAN));
    // Return the new difficulty setting
    DifficultyTarget resultTarget = new DifficultyTarget(target);
    DifficultyTarget maxTarget = bitcoinFactory.maxDifficultyTarget();
    if (resultTarget.compareTo(maxTarget) > 0)
        return maxTarget;
    else
        resultTarget = new DifficultyTarget(resultTarget.getCompressedTarget()); // Normalize
    logger.debug("previous height {}, recalculated target is: {}", link.getHeight(), resultTarget);
    return resultTarget;
}

From source file:com.cognitect.transit.TransitTest.java

public void testWriteCmap() throws Exception {

    Ratio r = new RatioImpl(BigInteger.valueOf(1), BigInteger.valueOf(2));
    Map m = new HashMap();
    m.put(r, 1);//from  ww w . j  av a2s. c om
    assertEquals("{\"~#cmap\":[{\"~#ratio\":[\"~n1\",\"~n2\"]},1]}", writeJsonVerbose(m));
    assertEquals("[\"~#cmap\",[[\"~#ratio\",[\"~n1\",\"~n2\"]],1]]", writeJson(m));
}

From source file:co.rsk.peg.BridgeSupport.java

/**
 * If federation change output value had to be increased to be non-dust, the federation now has
 * more BTC than it should. So, we burn some sBTC to make balances match.
 *
 * @param btcTx      The btc tx that was just completed
 * @param sentByUser The number of sBTC originaly sent by the user
 *//*  ww w .j a  v  a  2s.  c om*/
private void adjustBalancesIfChangeOutputWasDust(BtcTransaction btcTx, Coin sentByUser) {
    if (btcTx.getOutputs().size() <= 1) {
        // If there is no change, do-nothing
        return;
    }
    Coin sumInputs = Coin.ZERO;
    for (TransactionInput transactionInput : btcTx.getInputs()) {
        sumInputs = sumInputs.add(transactionInput.getValue());
    }
    Coin change = btcTx.getOutput(1).getValue();
    Coin spentByFederation = sumInputs.subtract(change);
    if (spentByFederation.isLessThan(sentByUser)) {
        Coin coinsToBurn = sentByUser.subtract(spentByFederation);
        byte[] burnAddress = SystemProperties.CONFIG.getBlockchainConfig().getCommonConstants()
                .getBurnAddress();
        transfer(rskRepository, Hex.decode(PrecompiledContracts.BRIDGE_ADDR), burnAddress,
                Denomination.satoshisToWeis(BigInteger.valueOf(coinsToBurn.getValue())));
    }
}

From source file:com.sun.faces.el.impl.Coercions.java

/**
 * Coerces a Number to the given primitive number class
 *///from   ww w  . ja  v  a2s .  com
static Number coerceToPrimitiveNumber(Number pValue, Class pClass) throws ElException {
    if (pClass == Byte.class || pClass == Byte.TYPE) {
        return PrimitiveObjects.getByte(pValue.byteValue());
    } else if (pClass == Short.class || pClass == Short.TYPE) {
        return PrimitiveObjects.getShort(pValue.shortValue());
    } else if (pClass == Integer.class || pClass == Integer.TYPE) {
        return PrimitiveObjects.getInteger(pValue.intValue());
    } else if (pClass == Long.class || pClass == Long.TYPE) {
        return PrimitiveObjects.getLong(pValue.longValue());
    } else if (pClass == Float.class || pClass == Float.TYPE) {
        return PrimitiveObjects.getFloat(pValue.floatValue());
    } else if (pClass == Double.class || pClass == Double.TYPE) {
        return PrimitiveObjects.getDouble(pValue.doubleValue());
    } else if (pClass == BigInteger.class) {
        if (pValue instanceof BigDecimal)
            return ((BigDecimal) pValue).toBigInteger();
        else
            return BigInteger.valueOf(pValue.longValue());
    } else if (pClass == BigDecimal.class) {
        if (pValue instanceof BigInteger)
            return new BigDecimal((BigInteger) pValue);
        else
            return new BigDecimal(pValue.doubleValue());
    } else {
        return PrimitiveObjects.getInteger(0);
    }
}

From source file:com.sun.honeycomb.adm.client.AdminClientImpl.java

public void setSetupCell(HCSetupCell newProps)
        throws MgmtException, ConnectException, PermissionException, AdmException {

    if (!loggedIn())
        throw new PermissionException();

    byte thisCellId = SiloInfo.getInstance().getUniqueCellId();
    HCCell cell = getCell(SiloInfo.getInstance().getServerUrl(thisCellId));

    // This push call should be changed in a future release to
    // invoke a method on the HCSetupCellAdapter instead of doing the
    // push.  See CR6684437
    newProps.push();/*  w w  w .  j  a  va  2s . c o  m*/

    String methodName = "setSetupCell";
    logSetupCellProps(Byte.toString(thisCellId), newProps, methodName);
    try {
        System.out.print("\nUpdating Switches ...");
        cell.updateSwitch(BigInteger.valueOf(0));
        System.out.print("\nUpdating Service Node ...");
        cell.updateServiceProcessor(BigInteger.valueOf(0));
        this._internalCall = true;
        System.out.println("\nRebooting nodes, switches, and service node ...");
        rebootCell(cell, true, true);
    } finally {
        System.out.println();
        this._internalCall = false;
    }
}

From source file:net.pms.util.Rational.java

/**
 * Returns a {@link Rational} whose value is {@code (this * value)}.
 *
 * @param value the value to be multiplied by this {@link Rational}.
 * @return The multiplication result./*from w  w  w. j ava  2  s. c  o  m*/
 */
@Nonnull
public Rational multiply(int value) {
    return multiply(BigInteger.valueOf(value));
}

From source file:io.instacount.client.InstacountClientTest.java

@Test
public void testDecrement_Sync() throws InstacountClientException {
    final String counterName = UUID.randomUUID().toString();
    final DecrementShardedCounterResponse response = client.decrementShardedCounter(counterName,
            new DecrementShardedCounterInput(BigInteger.TEN, SYNC));
    assertThat(response.getOptCounterOperation().isPresent(), is(true));
    assertThat(response.getOptCounterOperation().get().getAmount(), is(BigInteger.TEN));
    assertThat(response.getOptCounterOperation().get().getCounterOperationType(),
            is(CounterOperationType.DECREMENT));
    assertThat(response.getOptCounterOperation().get().getShardIndex(), anyOf(is(0), is(1), is(2)));
    assertThat(response.getOptCounterOperation().get().getId(), is(not(nullValue())));

    // Get the counter and assert its value!
    assertThat(client.getShardedCounter(counterName).getShardedCounter().getCount(),
            is(BigInteger.valueOf(-10L)));
}

From source file:com.sun.honeycomb.adm.client.AdminClientImpl.java

public boolean getSwitchesState(byte cellId) throws MgmtException, ConnectException {
    HCCell cell = getCell(cellId);/*from w  w  w  .j av a 2  s.  c  om*/
    if (cell.getSwitchesState(BigInteger.valueOf(0)).intValue() == 0)
        return true;
    else
        return false;
}

From source file:co.rsk.peg.BridgeSerializationUtilsTest.java

@Test
public void serializeLockWhitelist() throws Exception {
    PowerMockito.mockStatic(RLP.class);
    mock_RLP_encodeBigInteger();// w  w  w . jav  a 2  s  .  co m
    mock_RLP_encodeList();
    mock_RLP_encodeElement();

    byte[][] addressesBytes = new byte[][] { BtcECKey.fromPrivate(BigInteger.valueOf(100)).getPubKeyHash(),
            BtcECKey.fromPrivate(BigInteger.valueOf(200)).getPubKeyHash(),
            BtcECKey.fromPrivate(BigInteger.valueOf(300)).getPubKeyHash(),
            BtcECKey.fromPrivate(BigInteger.valueOf(400)).getPubKeyHash(),
            BtcECKey.fromPrivate(BigInteger.valueOf(500)).getPubKeyHash(),
            BtcECKey.fromPrivate(BigInteger.valueOf(600)).getPubKeyHash(), };
    Coin maxToTransfer = Coin.CENT;

    LockWhitelist lockWhitelist = new LockWhitelist(Arrays.stream(addressesBytes)
            .map(bytes -> new Address(NetworkParameters.fromID(NetworkParameters.ID_REGTEST), bytes)).collect(
                    Collectors.toMap(Function.identity(), k -> new OneOffWhiteListEntry(k, maxToTransfer))),
            0);

    byte[] result = BridgeSerializationUtils.serializeOneOffLockWhitelist(
            Pair.of(lockWhitelist.getAll(OneOffWhiteListEntry.class), lockWhitelist.getDisableBlockHeight()));
    StringBuilder expectedBuilder = new StringBuilder();
    Arrays.stream(addressesBytes).sorted(UnsignedBytes.lexicographicalComparator()).forEach(bytes -> {
        expectedBuilder.append("dd");
        expectedBuilder.append(Hex.toHexString(bytes));
        expectedBuilder.append("ff");
        expectedBuilder.append(Hex.toHexString(BigInteger.valueOf(maxToTransfer.value).toByteArray()));
    });
    expectedBuilder.append("ff00");
    byte[] expected = Hex.decode(expectedBuilder.toString());
    Assert.assertThat(result, is(expected));
}