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:com.lenovo.tensorhusky.common.utils.ProcfsBasedProcessTree.java

private BigInteger getTotalProcessJiffies() {
    BigInteger totalStime = BigInteger.ZERO;
    long totalUtime = 0;
    for (ProcessInfo p : processTree.values()) {
        if (p != null) {
            totalUtime += p.getUtime();//from  w  ww  .  j a v a  2 s .  com
            totalStime = totalStime.add(p.getStime());
        }
    }
    return totalStime.add(BigInteger.valueOf(totalUtime));
}

From source file:org.techytax.digipoort.XbrlNtp8Helper.java

public String createTestXbrlInstance() throws Exception {
    User user = new User();
    user.setFiscalNumber(TEST_FISCAL_NUMBER);
    user.setInitials("A.");
    user.setSurname("Tester");
    user.setPhoneNumber("12345678");
    VatDeclarationData vatDeclarationData = new VatDeclarationData();
    FiscalPeriod period = DateHelper.getLatestVatPeriod(VatPeriodType.PER_QUARTER);
    vatDeclarationData.setStartDate(period.getBeginDate());
    vatDeclarationData.setEndDate(period.getEndDate());
    VatBalanceWithinEu balans = new VatBalanceWithinEu();
    balans.setTotaleKosten(BigDecimal.valueOf(95));
    balans.setCorrection(BigDecimal.valueOf(5));
    balans.setNettoOmzet(BigInteger.valueOf(191));
    balans.setTurnoverNetEu(BigInteger.ZERO);
    balans.setVatOutEu(BigInteger.ZERO);
    addBalanceData(vatDeclarationData, balans);
    return createXbrlInstance(vatDeclarationData);
}

From source file:com.amazonaws.services.kinesis.producer.KinesisProducer.java

/**
 * Put a record asynchronously. A {@link ListenableFuture} is returned that
 * can be used to retrieve the result, either by polling or by registering a
 * callback./*from  w  w w .  j  a  v a2 s .  c o  m*/
 * 
 * <p>
 * The return value can be disregarded if you do not wish to process the
 * result. Under the covers, the KPL will automatically reattempt puts in
 * case of transient errors (including throttling). A failed result is
 * generally returned only if an irrecoverable error is detected (e.g.
 * trying to put to a stream that doesn't exist), or if the record expires.
 *
 * <p>
 * <b>Thread safe.</b>
 * 
 * <p>
 * To add a listener to the future:
 * <p>
 * <code>
 * ListenableFuture&lt;PutRecordResult&gt; f = myKinesisProducer.addUserRecord(...);
 * com.google.common.util.concurrent.Futures.addCallback(f, callback, executor);
 * </code>
 * <p>
 * where <code>callback</code> is an instance of
 * {@link com.google.common.util.concurrent.FutureCallback} and
 * <code>executor</code> is an instance of
 * {@link java.util.concurrent.Executor}.
 * <p>
 * <b>Important:</b>
 * <p>
 * If long-running tasks are performed in the callbacks, it is recommended
 * that a custom executor be provided when registering callbacks to ensure
 * that there are enough threads to achieve the desired level of
 * parallelism. By default, the KPL will use an internal thread pool to
 * execute callbacks, but this pool may not have a sufficient number of
 * threads if a large number is desired.
 * <p>
 * Another option would be to hand the result off to a different component
 * for processing and keep the callback routine fast.
 * 
 * @param stream
 *            Stream to put to.
 * @param partitionKey
 *            Partition key. Length must be at least one, and at most 256
 *            (inclusive).
 * @param explicitHashKey
 *            The hash value used to explicitly determine the shard the data
 *            record is assigned to by overriding the partition key hash.
 *            Must be a valid string representation of a positive integer
 *            with value between 0 and <tt>2^128 - 1</tt> (inclusive).
 * @param data
 *            Binary data of the record. Maximum size 1MiB.
 * @return A future for the result of the put.
 * @throws IllegalArgumentException
 *             if input does not meet stated constraints
 * @throws DaemonException
 *             if the child process is dead
 * @see ListenableFuture
 * @see UserRecordResult
 * @see KinesisProducerConfiguration#setRecordTtl(long)
 * @see UserRecordFailedException
 */
public ListenableFuture<UserRecordResult> addUserRecord(String stream, String partitionKey,
        String explicitHashKey, ByteBuffer data) {
    if (stream == null) {
        throw new IllegalArgumentException("Stream name cannot be null");
    }

    stream = stream.trim();

    if (stream.length() == 0) {
        throw new IllegalArgumentException("Stream name cannot be empty");
    }

    if (partitionKey == null) {
        throw new IllegalArgumentException("partitionKey cannot be null");
    }

    if (partitionKey.length() < 1 || partitionKey.length() > 256) {
        throw new IllegalArgumentException(
                "Invalid parition key. Length must be at least 1 and at most 256, got "
                        + partitionKey.length());
    }

    try {
        partitionKey.getBytes("UTF-8");
    } catch (Exception e) {
        throw new IllegalArgumentException("Partition key must be valid UTF-8");
    }

    BigInteger b = null;
    if (explicitHashKey != null) {
        explicitHashKey = explicitHashKey.trim();
        try {
            b = new BigInteger(explicitHashKey);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(
                    "Invalid explicitHashKey, must be an integer, got " + explicitHashKey);
        }
        if (b != null) {
            if (b.compareTo(UINT_128_MAX) > 0 || b.compareTo(BigInteger.ZERO) < 0) {
                throw new IllegalArgumentException(
                        "Invalid explicitHashKey, must be greater or equal to zero and less than or equal to (2^128 - 1), got "
                                + explicitHashKey);
            }
        }
    }

    if (data != null && data.remaining() > 1024 * 1024) {
        throw new IllegalArgumentException(
                "Data must be less than or equal to 1MB in size, got " + data.remaining() + " bytes");
    }

    long id = messageNumber.getAndIncrement();
    SettableFuture<UserRecordResult> f = SettableFuture.create();
    futures.put(id, f);

    PutRecord.Builder pr = PutRecord.newBuilder().setStreamName(stream).setPartitionKey(partitionKey)
            .setData(data != null ? ByteString.copyFrom(data) : ByteString.EMPTY);
    if (b != null) {
        pr.setExplicitHashKey(b.toString(10));
    }

    Message m = Message.newBuilder().setId(id).setPutRecord(pr.build()).build();
    child.add(m);

    return f;
}

From source file:com.trsst.Common.java

public static byte[] fromBase58(String s) {
    try {/*from  ww  w.  j  a  v  a 2  s  .  co m*/
        boolean leading = true;
        int lz = 0;
        BigInteger b = BigInteger.ZERO;
        for (char c : s.toCharArray()) {
            if (leading && c == '1') {
                ++lz;
            } else {
                leading = false;
                b = b.multiply(BigInteger.valueOf(58));
                b = b.add(BigInteger.valueOf(r58[c]));
            }
        }
        byte[] encoded = b.toByteArray();
        if (encoded[0] == 0) {
            if (lz > 0) {
                --lz;
            } else {
                byte[] e = new byte[encoded.length - 1];
                System.arraycopy(encoded, 1, e, 0, e.length);
                encoded = e;
            }
        }
        byte[] result = new byte[encoded.length + lz];
        System.arraycopy(encoded, 0, result, lz, encoded.length);

        return result;
    } catch (ArrayIndexOutOfBoundsException e) {
        throw new IllegalArgumentException("Invalid character in address");
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:com.amazonaws.kinesis.agg.AggRecord.java

/**
 * Validate the explicit hash key of an input Kinesis user record.
 * /*from   w ww.j a  va  2 s.  c o m*/
 * @param explicitHashKey
 *            The string containing the input explicit hash key to validate.
 */
private void validateExplicitHashKey(final String explicitHashKey) {
    if (explicitHashKey == null) {
        return;
    }

    BigInteger b = null;
    try {
        b = new BigInteger(explicitHashKey);
        if (b.compareTo(UINT_128_MAX) > 0 || b.compareTo(BigInteger.ZERO) < 0) {
            throw new IllegalArgumentException(
                    "Invalid explicitHashKey, must be greater or equal to zero and less than or equal to (2^128 - 1), got "
                            + explicitHashKey);
        }
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException(
                "Invalid explicitHashKey, must be an integer, got " + explicitHashKey);
    }
}

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

/**
 * Fetch all orders by PartyUid and ordered by Date ascending
 *
 * @param partyUid a valid party id/*from  ww  w.j  a  va  2 s.  c  o m*/
 * @return a structure of orders history ordered by Date
 *
 * @throws com.oncore.calorders.core.exceptions.DataAccessException
 */
@GET
@Path("findAllOrderHistoryByPartyUid/{partyUid}")
@Produces({ MediaType.APPLICATION_JSON })
public List<OrderHistoryData> findAllOrderHistoryByPartyUid(@PathParam("partyUid") Integer partyUid)
        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 pt.ptyUid = :partyUid ORDER BY oh.createTs DESC",
            OrderHistory.class).setParameter("partyUid", partyUid).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:com.ethercamp.harmony.jsonrpc.EthJsonRpcImpl.java

private String sendTransaction(CallArguments args, Account account) {
    if (args.data != null && args.data.startsWith("0x"))
        args.data = args.data.substring(2);

    // convert zero to empty byte array
    // TEMP, until decide for better behavior
    final BigInteger valueBigInt = args.value != null ? StringHexToBigInteger(args.value) : BigInteger.ZERO;
    final byte[] value = !valueBigInt.equals(BigInteger.ZERO) ? ByteUtil.bigIntegerToBytes(valueBigInt)
            : EMPTY_BYTE_ARRAY;//  w ww .j ava  2  s . co m

    final Transaction tx = new Transaction(
            args.nonce != null ? StringHexToByteArray(args.nonce)
                    : bigIntegerToBytes(pendingState.getRepository().getNonce(account.getAddress())),
            args.gasPrice != null ? StringHexToByteArray(args.gasPrice)
                    : ByteUtil.longToBytesNoLeadZeroes(eth.getGasPrice()),
            args.gas != null ? StringHexToByteArray(args.gas) : ByteUtil.longToBytes(90_000),
            args.to != null ? StringHexToByteArray(args.to) : EMPTY_BYTE_ARRAY, value,
            args.data != null ? StringHexToByteArray(args.data) : EMPTY_BYTE_ARRAY);

    tx.sign(account.getEcKey());

    validateAndSubmit(tx);

    return TypeConverter.toJsonHex(tx.getHash());
}

From source file:org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.POCast.java

@Override
public Result getNextBoolean() throws ExecException {
    PhysicalOperator in = inputs.get(0);
    Byte resultType = in.getResultType();
    switch (resultType) {
    case DataType.BAG:
    case DataType.TUPLE:
    case DataType.MAP:
    case DataType.DATETIME:
        return error();

    case DataType.BYTEARRAY: {
        DataByteArray dba;/*  w ww .  j ava 2s .co m*/
        Result res = in.getNextDataByteArray();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            try {
                dba = (DataByteArray) res.result;
            } catch (ClassCastException e) {
                // res.result is not of type ByteArray. But it can be one of the types from which cast is still possible.
                if (realType == null)
                    // Find the type and cache it.
                    realType = DataType.findType(res.result);
                try {
                    res.result = DataType.toBoolean(res.result, realType);
                } catch (ClassCastException cce) {
                    // Type has changed. Need to find type again and try casting it again.
                    realType = DataType.findType(res.result);
                    res.result = DataType.toBoolean(res.result, realType);
                }
                return res;
            }
            try {
                if (null != caster) {
                    res.result = caster.bytesToBoolean(dba.get());
                } else {
                    int errCode = 1075;
                    String msg = unknownByteArrayErrorMessage + "boolean.";
                    throw new ExecException(msg, errCode, PigException.INPUT);
                }
            } catch (ExecException ee) {
                throw ee;
            } catch (IOException e) {
                log.error("Error while casting from ByteArray to Boolean");
            }
        }
        return res;
    }

    case DataType.CHARARRAY: {
        Result res = in.getNextString();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            res.result = CastUtils.stringToBoolean((String) res.result);
        }
        return res;
    }

    case DataType.BOOLEAN:
        return in.getNextBoolean();

    case DataType.INTEGER: {
        Integer i = null;
        Result res = in.getNextInteger();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            res.result = Boolean.valueOf(((Integer) res.result).intValue() != 0);
        }
        return res;
    }

    case DataType.LONG: {
        Result res = in.getNextLong();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            res.result = Boolean.valueOf(((Long) res.result).longValue() != 0L);
        }
        return res;
    }

    case DataType.FLOAT: {
        Result res = in.getNextFloat();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            res.result = Boolean.valueOf(((Float) res.result).floatValue() != 0.0F);
        }
        return res;
    }

    case DataType.DOUBLE: {
        Result res = in.getNextDouble();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            res.result = Boolean.valueOf(((Double) res.result).doubleValue() != 0.0);
        }
        return res;
    }

    case DataType.BIGINTEGER: {
        BigInteger bi = null;
        Result res = in.getNextBigInteger();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            res.result = Boolean.valueOf(!BigInteger.ZERO.equals((BigInteger) res.result));
        }
        return res;
    }

    case DataType.BIGDECIMAL: {
        BigDecimal bd = null;
        Result res = in.getNextBigDecimal();
        if (res.returnStatus == POStatus.STATUS_OK && res.result != null) {
            res.result = Boolean.valueOf(!BigDecimal.ZERO.equals((BigDecimal) res.result));
        }
        return res;
    }

    }

    return error();
}

From source file:piuk.MyRemoteWallet.java

public Pair<Transaction, Long> makeTransaction(KeyBag keyWallet, List<MyTransactionOutPoint> unspent,
        String toAddress, String changeAddress, BigInteger amount, BigInteger baseFee,
        boolean consumeAllOutputs) throws Exception {

    long priority = 0;

    if (unspent == null || unspent.size() == 0)
        throw new InsufficientFundsException("No free outputs to spend.");

    if (amount == null || amount.compareTo(BigInteger.ZERO) <= 0)
        throw new Exception("You must provide an amount");

    //Construct a new transaction
    Transaction tx = new Transaction(params);

    final Script toOutputScript = ScriptBuilder.createOutputScript(new Address(MainNetParams.get(), toAddress));

    final TransactionOutput output = new TransactionOutput(params, null, Coin.valueOf(amount.longValue()),
            toOutputScript.getProgram());

    tx.addOutput(output);//from  www  .  java2  s . c om

    //Now select the appropriate inputs
    BigInteger valueSelected = BigInteger.ZERO;
    BigInteger valueNeeded = amount.add(baseFee);
    BigInteger minFreeOutputSize = BigInteger.valueOf(1000000);

    for (MyTransactionOutPoint outPoint : unspent) {

        Script scriptPubKey = outPoint.getConnectedOutput().getScriptPubKey();

        if (scriptPubKey == null) {
            throw new Exception("scriptPubKey is null");
        }

        final ECKey key = keyWallet.findKeyFromPubHash(scriptPubKey.getPubKeyHash());

        if (key == null) {
            throw new Exception("Unable to find ECKey for scriptPubKey " + scriptPubKey);
        }

        MyTransactionInput input = new MyTransactionInput(params, null, new byte[0], outPoint);

        tx.addInput(input);

        input.setScriptSig(scriptPubKey.createEmptyInputScript(key, null));

        valueSelected = valueSelected.add(BigInteger.valueOf(outPoint.getValue().longValue()));

        priority += outPoint.getValue().longValue() * outPoint.confirmations;

        if (!consumeAllOutputs) {
            if (valueSelected.compareTo(valueNeeded) == 0
                    || valueSelected.compareTo(valueNeeded.add(minFreeOutputSize)) >= 0)
                break;
        }
    }

    //Check the amount we have selected is greater than the amount we need
    if (valueSelected.compareTo(valueNeeded) < 0) {
        throw new InsufficientFundsException("Insufficient Funds");
    }

    long estimatedSize = tx.bitcoinSerialize().length + (138 * tx.getInputs().size());

    BigInteger fee = BigInteger.valueOf((int) Math.ceil(estimatedSize / 1000d)).multiply(baseFee);

    BigInteger change = valueSelected.subtract(amount).subtract(fee);

    if (change.compareTo(BigInteger.ZERO) < 0) {
        throw new Exception("Insufficient Value for Fee. Fix this lazy.");
    } else if (change.compareTo(BigInteger.ZERO) > 0) {
        //Now add the change if there is any
        final Script change_script = ScriptBuilder
                .createOutputScript(new Address(MainNetParams.get(), changeAddress));

        TransactionOutput change_output = new TransactionOutput(params, null, Coin.valueOf(change.longValue()),
                change_script.getProgram());

        tx.addOutput(change_output);
    }

    estimatedSize = tx.bitcoinSerialize().length + (138 * tx.getInputs().size());

    priority /= estimatedSize;

    return new Pair<Transaction, Long>(tx, priority);
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.common.vbb.impl.RecursiveCluster.java

/**
 * Inner Elements that are not set in relationship with any outer elements are grouped in a dedicated outer element.
 * @param model//from   w ww  .  j a  va 2 s. c o m
 * @param vpConfig
 * @param usedInners
 * @return If inner elements with no relationship to any outer element exist a CompositeSymbol as dedicated outer element is returned.
 *         Otherwise null is returned.
 */
private CompositeSymbol innerSubTransformWithNoReleationship(Model model, ViewpointConfiguration vpConfig) {
    SubstantialTypeExpression oldInner = (SubstantialTypeExpression) vpConfig.getMappingFor(inner);
    RelationshipEndExpression innerToInnerMapping = (RelationshipEndExpression) vpConfig
            .getMappingFor(innerToInner);

    CompositeSymbol container = null;

    //explicitly filter for orphans
    //take the opposite of the outer2inner relationship and filter for count=0
    RelationshipEndExpression outer2Inner = (RelationshipEndExpression) vpConfig.getMappingFor(outerToInner);
    Predicate<UniversalModelExpression> orphanPredicate = FilterPredicates.buildIntegerPredicate(
            ComparisonOperators.EQUALS,
            new CountProperty(outer2Inner.getRelationship().getOppositeEndFor(outer2Inner)), BigInteger.ZERO);
    SubstantialTypeExpression innerMapping = new FilteredSubstantialType(oldInner, orphanPredicate);

    // temporarily replace the mapping for the inner type
    vpConfig.setMappingFor(inner, innerMapping);

    Collection<UniversalModelExpression> orphans = getHierarchyRoot(model, innerMapping, innerToInnerMapping);

    if (!orphans.isEmpty()) {
        container = containerCreateSymbol.transform(null, model, vpConfig);
        APlanarSymbol containerSymbol = outerColoredCreateSymbol.transform(null, model, vpConfig);
        containerSymbol.setLineStyle(LineStyle.DASHED);
        if (containerSymbol instanceof Rectangle) {
            ((Rectangle) containerSymbol).getText()
                    .setText(MessageAccess.getString("graphicalExport.vbbCluster.noMatchingOuterElement"));
        }

        Collection<ASymbol> innerSymbols = innerSubTransform(model, vpConfig, orphans,
                model.findAll(innerMapping));
        container.getChildren().addAll(innerSymbols);

        SquareBox layouter = new SquareBox(containerSymbol, container.getChildren());
        layouter.layout();

        container.getChildren().add(0, containerSymbol);
    }

    vpConfig.setMappingFor(inner, oldInner);

    return container;
}