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:org.ethereum.core.Block.java

private boolean checkRemascTxZeroValues(Transaction tx) {
    if (null != tx.getData() || null != tx.getSignature()) {
        return false;
    }/*from   w ww  .  j  a v  a 2 s. c  o  m*/

    return BigInteger.ZERO.equals(new BigInteger(1, tx.getValue()))
            && BigInteger.ZERO.equals(new BigInteger(1, tx.getGasLimit()))
            && BigInteger.ZERO.equals(new BigInteger(1, tx.getGasPrice()));

}

From source file:com.teamj.distribuidas.web.ExcursionUserBean.java

public void unselectDisabledRow(ToggleSelectEvent e) {
    this.subtotal = new BigDecimal(BigInteger.ZERO);
    this.totalArticulos = 0;
    for (int i = excursionArticulosSelected.size() - 1; i >= 0; i--) {
        if (excursionArticulosSelected.get(i).getArticulo().getStock() == 0) {
            this.excursionArticulosSelected.remove(i);
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_WARN, "No hay stock del artculo", ""));

        } else if ((this.excursionSelected.getFechaLimite().before(today())
                || (this.excursionSelected.getMaxAsistentes()
                        - this.excursionSelected.getUsuarioExcursiones().size() <= 0))
                && this.excursionArticulosSelected.get(i).getArticulo().getDescripcion() != null
                && this.excursionArticulosSelected.get(i).getArticulo().getDescripcion()
                        .equals(String.valueOf(this.excursionSelected.getId()))) {
            this.excursionArticulosSelected.remove(i);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
                    "La fecha lmite para inscripcin de la excursin ha caducado", ""));
        } else {//from  w w  w. j a  v a  2s .co  m
            if (this.excursionArticulosSelected.get(i).getArticulo().getDescripcion() != null
                    && this.excursionArticulosSelected.get(i).getArticulo().getDescripcion()
                            .equals(String.valueOf(this.excursionSelected.getId()))) {
                this.derechoExcursionSeleccionada = this.excursionArticulosSelected.get(i).getArticulo()
                        .getPrecio();
            } else {
                this.totalArticulos += excursionArticulosSelected.get(i).getCantidad();
                this.subtotal = this.subtotal.add(excursionArticulosSelected.get(i).getArticulo().getPrecio()
                        .multiply(new BigDecimal(excursionArticulosSelected.get(i).getCantidad())));
            }
        }

    }

}

From source file:com.example.util.FileUtils.java

/**
 * Returns a human-readable version of the file size, where the input represents a specific number of bytes.
 * <p>/*from   w w w .  j  a  va2 s. c  o m*/
 * If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the
 * nearest GB boundary.
 * </p>
 * <p>
 * Similarly for the 1MB and 1KB boundaries.
 * </p>
 * 
 * @param size
 *            the number of bytes
 * @return a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes)
 * @see <a href="https://issues.apache.org/jira/browse/IO-226">IO-226 - should the rounding be changed?</a>
 * @since 2.4
 */
// See https://issues.apache.org/jira/browse/IO-226 - should the rounding be changed?
public static String byteCountToDisplaySize(BigInteger size) {
    String displaySize;

    if (size.divide(ONE_EB_BI).compareTo(BigInteger.ZERO) > 0) {
        displaySize = String.valueOf(size.divide(ONE_EB_BI)) + " EB";
    } else if (size.divide(ONE_PB_BI).compareTo(BigInteger.ZERO) > 0) {
        displaySize = String.valueOf(size.divide(ONE_PB_BI)) + " PB";
    } else if (size.divide(ONE_TB_BI).compareTo(BigInteger.ZERO) > 0) {
        displaySize = String.valueOf(size.divide(ONE_TB_BI)) + " TB";
    } else if (size.divide(ONE_GB_BI).compareTo(BigInteger.ZERO) > 0) {
        displaySize = String.valueOf(size.divide(ONE_GB_BI)) + " GB";
    } else if (size.divide(ONE_MB_BI).compareTo(BigInteger.ZERO) > 0) {
        displaySize = String.valueOf(size.divide(ONE_MB_BI)) + " MB";
    } else if (size.divide(ONE_KB_BI).compareTo(BigInteger.ZERO) > 0) {
        displaySize = String.valueOf(size.divide(ONE_KB_BI)) + " KB";
    } else {
        displaySize = String.valueOf(size) + " bytes";
    }
    return displaySize;
}

From source file:net.sf.keystore_explorer.crypto.privatekey.Pkcs8Util.java

/**
 * Detect if a PKCS #8 private key is encrypted or not.
 *
 * @param is/*from w  w w.  j  a  v  a 2s .  c o m*/
 *            Input stream containing PKCS #8 private key
 * @return Encryption type or null if not a valid PKCS #8 private key
 * @throws IOException
 *             If an I/O problem occurred
 */
public static EncryptionType getEncryptionType(InputStream is) throws IOException {
    byte[] pkcs8 = ReadUtil.readFully(is);

    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(pkcs8));

    // PEM encoded?
    if (pemInfo != null) {
        String pemType = pemInfo.getType();

        // Encrypted in pem format?
        if (pemType.equals(Pkcs8Util.PKCS8_ENC_PVK_PEM_TYPE)) {
            return ENCRYPTED;
        }
        // Unencrypted in pem format?
        else if (pemType.equals(Pkcs8Util.PKCS8_UNENC_PVK_PEM_TYPE)) {
            return UNENCRYPTED;
        }
    }

    // In ASN.1 format?
    try {
        // Read in an ASN.1 and check structure against the following
        ASN1Primitive key = ASN1Primitive.fromByteArray(pkcs8);

        if (key instanceof ASN1Sequence) {
            ASN1Sequence sequence = (ASN1Sequence) key;

            // May be unencrypted
            if ((sequence.size() == 3) || (sequence.size() == 4)) {
                // @formatter:off

                /*
                 * Unencrypted PKCS #8 Private Key:
                 *
                 * PrivateKeyInfo ::= ASN1Sequence { version Version,
                 * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
                 * privateKey PrivateKey, attributes [0] IMPLICIT Attributes
                 * OPTIONAL }
                 *
                 * Version ::= ASN1Integer PrivateKeyAlgorithmIdentifier ::=
                 * AlgorithmIdentifier PrivateKey ::= OCTET STRING
                 * Attributes ::= SET OF Attribute
                 */

                // @formatter:on

                Object obj1 = sequence.getObjectAt(0);
                Object obj2 = sequence.getObjectAt(1);
                Object obj3 = sequence.getObjectAt(2);

                if (!(obj1 instanceof ASN1Integer)) {
                    return null;
                }

                ASN1Integer version = (ASN1Integer) obj1;

                if (!version.getValue().equals(BigInteger.ZERO)) {
                    return null;
                }

                if (!(obj2 instanceof ASN1Sequence)) {
                    return null;
                }

                if (!sequenceIsAlgorithmIdentifier((ASN1Sequence) obj2)) {
                    return null;
                }

                if (!(obj3 instanceof ASN1OctetString)) {
                    return null;
                }

                return UNENCRYPTED;
            }
            // May be encrypted
            else if (sequence.size() == 2) {
                // @formatter:off

                /*
                 * Encrypted PKCS #8 Private Key:
                 *
                 * EncryptedPrivateKeyInfo ::= ASN1Sequence {
                 * encryptionAlgorithm EncryptionAlgorithmIdentifier,
                 * encryptedData EncryptedData }
                 *
                 * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
                 * EncryptedData ::= OCTET STRING
                 */

                // @formatter:on

                Object obj1 = sequence.getObjectAt(0);
                Object obj2 = sequence.getObjectAt(1);

                if (!(obj1 instanceof ASN1Sequence)) {
                    return null;
                }

                if (!sequenceIsAlgorithmIdentifier((ASN1Sequence) obj1)) {
                    return null;
                }

                if (!(obj2 instanceof ASN1OctetString)) {
                    return null;
                }

                return ENCRYPTED;
            }
        }
    } catch (Exception ex) {
        // Structure not as expected for PKCS #8
        return null;
    }

    return null;
}

From source file:org.openestate.io.kyero.KyeroUtils.java

public static String printNonNegativeInteger(BigInteger value) {
    if (value == null || value.compareTo(BigInteger.ZERO) == -1)
        throw new IllegalArgumentException("Can't print integer value '" + value + "'!");
    else//  w ww .  jav a 2 s  .c o  m
        return DatatypeConverter.printInteger(value);
}

From source file:co.rsk.blockchain.utils.BlockGenerator.java

public static Block createBlock(int number, int ntxs) {
    Bloom logBloom = new Bloom();
    Block parent = BlockGenerator.getGenesisBlock();

    List<Transaction> txs = new ArrayList<>();

    for (int ntx = 0; ntx < ntxs; ntx++)
        txs.add(new SimpleRskTransaction(null));

    byte[] parentMGP = (parent.getMinimumGasPrice() != null) ? parent.getMinimumGasPrice()
            : BigInteger.valueOf(10L).toByteArray();
    BigInteger minimumGasPrice = new MinimumGasPriceCalculator().calculate(new BigInteger(1, parentMGP),
            BigInteger.valueOf(100L));

    return new Block(parent.getHash(), // parent hash
            EMPTY_LIST_HASH, // uncle hash
            parent.getCoinbase(), // coinbase
            logBloom.getData(), // logs bloom
            parent.getDifficulty(), // difficulty
            number, parent.getGasLimit(), parent.getGasUsed(), parent.getTimestamp() + ++count,
            EMPTY_BYTE_ARRAY, // extraData
            EMPTY_BYTE_ARRAY, // mixHash
            BigInteger.ZERO.toByteArray(), // provisory nonce
            EMPTY_TRIE_HASH, // receipts root
            EMPTY_TRIE_HASH, // transaction receipts
            EMPTY_TRIE_HASH, // state root
            txs, // transaction list
            null, // uncle list
            minimumGasPrice.toByteArray());
}

From source file:org.lwes.EventTest.java

@Test
public void testIntBounds() {
    final Event evt = createEvent();
    evt.setEventName("Test");

    evt.setByte("byte_min", Byte.MIN_VALUE);
    evt.setByte("byte_zero", (byte) 0);
    evt.setByte("byte_one", (byte) 1);
    evt.setByte("byte_max", Byte.MAX_VALUE);

    evt.setInt16("int16_min", Short.MIN_VALUE);
    evt.setInt16("int16_zero", (short) 0);
    evt.setInt16("int16_one", (short) 1);
    evt.setInt16("int16_max", Short.MAX_VALUE);

    evt.setInt32("int32_min", Integer.MIN_VALUE);
    evt.setInt32("int32_zero", 0);
    evt.setInt32("int32_one", 1);
    evt.setInt32("int32_max", Integer.MAX_VALUE);

    evt.setInt64("int64_min", Long.MIN_VALUE);
    evt.setInt64("int64_zero", 0);
    evt.setInt64("int64_one", 1);
    evt.setInt64("int64_max", Long.MAX_VALUE);

    evt.setUInt16("uint16_zero", 0);
    evt.setUInt16("uint16_one", 1);
    evt.setUInt16("uint16_max", 0xffff);

    evt.setUInt32("uint32_zero", 0);
    evt.setUInt32("uint32_one", 1);
    evt.setUInt32("uint32_max", 0xffffffffL);

    evt.setUInt64("uint64_zero", BigInteger.ZERO);
    evt.setUInt64("uint64_one", BigInteger.ONE);
    evt.setUInt64("uint64_max", BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE));

    evt.setInt16Array("int16[]", new short[] { Short.MIN_VALUE, 0, 1, Short.MAX_VALUE });
    evt.setInt32Array("int32[]", new int[] { Integer.MIN_VALUE, 0, 1, Integer.MAX_VALUE });
    evt.setInt64Array("int64[]", new long[] { Long.MIN_VALUE, 0, 1, Long.MAX_VALUE });
    evt.setUInt16Array("uint16[]", new int[] { 0, 1, 0xffff });
    evt.setUInt32Array("uint32[]", new long[] { 0, 1, 0xffffffffL });
    evt.setUInt64Array("uint64[]", new BigInteger[] { BigInteger.ZERO, BigInteger.ONE,
            BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE) });
    evt.setUInt64Array("uint64[] prim", new long[] { 0, 1, -1 });

    final Event evt2 = createEvent();
    evt2.deserialize(evt.serialize());//from  ww w  . j a  va2  s .  co  m
    //assertEquals(evt, evt2);

    assertEquals(Byte.MIN_VALUE, evt.getByte("byte_min").byteValue());
    assertEquals((byte) 0, evt.getByte("byte_zero").byteValue());
    assertEquals((byte) 1, evt.getByte("byte_one").byteValue());
    assertEquals(Byte.MAX_VALUE, evt.getByte("byte_max").byteValue());

    assertEquals(Short.MIN_VALUE, evt.getInt16("int16_min").shortValue());
    assertEquals((short) 0, evt.getInt16("int16_zero").shortValue());
    assertEquals((short) 1, evt.getInt16("int16_one").shortValue());
    assertEquals(Short.MAX_VALUE, evt.getInt16("int16_max").shortValue());

    assertEquals(Integer.MIN_VALUE, evt.getInt32("int32_min").intValue());
    assertEquals(0, evt.getInt32("int32_zero").intValue());
    assertEquals(1, evt.getInt32("int32_one").intValue());
    assertEquals(Integer.MAX_VALUE, evt.getInt32("int32_max").intValue());

    assertEquals(Long.MIN_VALUE, evt.getInt64("int64_min").longValue());
    assertEquals(0, evt.getInt64("int64_zero").longValue());
    assertEquals(1, evt.getInt64("int64_one").longValue());
    assertEquals(Long.MAX_VALUE, evt.getInt64("int64_max").longValue());

    assertEquals(0, evt.getUInt16("uint16_zero").intValue());
    assertEquals(1, evt.getUInt16("uint16_one").intValue());
    assertEquals(0xffff, evt.getUInt16("uint16_max").intValue());

    assertEquals(0, evt.getUInt32("uint32_zero").longValue());
    assertEquals(1, evt.getUInt32("uint32_one").longValue());
    assertEquals(0xffffffffL, evt.getUInt32("uint32_max").longValue());

    assertEquals(BigInteger.ZERO, evt.getUInt64("uint64_zero"));
    assertEquals(BigInteger.ONE, evt.getUInt64("uint64_one"));
    assertEquals(BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE), evt.getUInt64("uint64_max"));

    assertArrayEquals(new short[] { Short.MIN_VALUE, 0, 1, Short.MAX_VALUE }, evt.getInt16Array("int16[]"));
    assertArrayEquals(new int[] { Integer.MIN_VALUE, 0, 1, Integer.MAX_VALUE }, evt.getInt32Array("int32[]"));
    assertArrayEquals(new long[] { Long.MIN_VALUE, 0, 1, Long.MAX_VALUE }, evt.getInt64Array("int64[]"));
    assertArrayEquals(new int[] { 0, 1, 0xffff }, evt.getUInt16Array("uint16[]"));
    assertArrayEquals(new long[] { 0, 1, 0xffffffffL }, evt.getUInt32Array("uint32[]"));
    assertArrayEquals(new BigInteger[] { BigInteger.ZERO, BigInteger.ONE,
            BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE) }, evt.getUInt64Array("uint64[]"));
    assertArrayEquals(
            new BigInteger[] { BigInteger.ZERO, BigInteger.ONE,
                    BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE) },
            evt.getUInt64Array("uint64[] prim"));
}

From source file:org.sparkbit.jsonrpc.SparkBitJSONRPCServiceImpl.java

@Override
public synchronized Boolean deletewallet(String walletID) throws com.bitmechanic.barrister.RpcException {
    log.info("DELETE WALLET");
    log.info("wallet name = " + walletID);

    Wallet w = getWalletForWalletName(walletID);
    if (w == null) {
        JSONRPCError.WALLET_NOT_FOUND.raiseRpcException();
    }//from w w  w . j av a2s.  c  om

    // Are there any asset or btc balances?  Do not allow deleting wallet if any balance exists?
    Map<Integer, Wallet.CoinSpark.AssetBalance> map = w.CS.getAllAssetBalances();
    for (Wallet.CoinSpark.AssetBalance ab : map.values()) {
        if (ab.total.compareTo(BigInteger.ZERO) > 0) {
            JSONRPCError.DELETE_WALLET_NOT_EMPTY.raiseRpcException();
        }
    }

    String filename = getFullPathForWalletName(walletID);
    final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename);
    WalletInfoData winfo = wd.getWalletInfo();
    if (wd.isBusy()) {
        JSONRPCError.WALLEY_IS_BUSY.raiseRpcException();
    }

    // Deleting a wallet even if not currently active, causes list of wallets to be unselected
    // so we need to keep track of what was active befor eremoval
    String activeFilename = this.controller.getModel().getActiveWalletFilename();
    if (wd.getWalletFilename().equals(activeFilename)) {
        activeFilename = null;
    }

    // Unhook it from the PeerGroup.
    this.controller.getMultiBitService().getPeerGroup().removeWallet(w);

    // Remove it from the model.
    this.controller.getModel().remove(wd);

    // Perform delete if possible etc.
    FileHandler fileHandler = this.controller.getFileHandler();
    try {
        fileHandler.deleteWalletAndWalletInfo(wd);

        // Delete .cs
        String csassets = filename + ".csassets";
        String csbalances = filename + ".csbalances";
        File f = new File(csassets);
        if (f.exists()) {
            if (!f.delete()) {
                //log.error(">>>> Asset DB: Cannot delete");
            }
        }
        f = new File(csbalances);
        if (f.exists()) {
            if (!f.delete()) {
                //log.error(">>>> Balances DB: Cannot delete");
            }
        }
        String cslog = filename + ".cslog";
        f = new File(cslog);
        if (f.exists()) {
            if (!f.delete()) {
                //                log.error(">>>> CS Log File: Cannot delete");
            }
        }

        // Delete cached contracts
        String csfiles = filename + ".csfiles";
        f = new File(csfiles);
        if (f.exists()) {
            FileDeleteStrategy.FORCE.delete(f);
        }

        // Delete the backup folder and cached contracts
        String backupFolderPath = BackupManager.INSTANCE
                .calculateTopLevelBackupDirectoryName(new File(filename));
        f = new File(backupFolderPath);
        if (f.exists()) {
            FileDeleteStrategy.FORCE.delete(f);
        }

    } catch (Exception e) {
        JSONRPCError.throwAsRpcException("Error deleting wallet files", e);
    }

    if (!winfo.isDeleted()) {
        JSONRPCError.throwAsRpcException("Wallet was not deleted. Reason unknown.");
    }

    // Set the new Wallet to be the old active wallet, or the first wallet
    if (activeFilename != null) {
        this.controller.getModel().setActiveWalletByFilename(activeFilename);
    } else if (!this.controller.getModel().getPerWalletModelDataList().isEmpty()) {
        WalletData firstPerWalletModelData = this.controller.getModel().getPerWalletModelDataList().get(0);
        this.controller.getModel().setActiveWalletByFilename(firstPerWalletModelData.getWalletFilename());
    }
    controller.fireRecreateAllViews(true);

    //   updateWalletFilenameMap();
    return true;
}

From source file:io.instacount.appengine.counter.service.ShardedCounterServiceImpl.java

/**
 * The cache will expire after {@code defaultCounterCountExpiration} seconds, so the counter will be accurate after
 * a minute because it performs a load from the datastore.
 *
 * @param counterName// w  w  w.j a v a 2s  . c  o  m
 * @param skipCache A boolean that allows a caller to skip memcache when retrieving a counter. Set to {@code true}
 *            to load the counter and all of its shards directly from the Datastore. Set to {@code false} to attempt
 *            to load the count from memcache, with fallback to the datastore.
 * @return
 */
@Override
public Optional<Counter> getCounter(final String counterName, final boolean skipCache) {
    Preconditions.checkNotNull(counterName);

    // This method always load the CounterData from the Datastore (or its Objectify cache), but sometimes returns
    // the
    // cached count value.

    // //////////////
    // ShortCircuit: If nothing is present in the datastore.
    // //////////////
    final Optional<CounterData> optCounterData = this.getCounterData(counterName);
    if (!optCounterData.isPresent()) {
        logger.log(Level.FINEST, String.format("Counter '%s' was not found in hte Datastore!", counterName));
        return Optional.absent();
    }

    final CounterData counterData = optCounterData.get();

    // //////////////
    // ShortCircuit: If the counter is in an indeterminate state, then return its count as 0.
    // //////////////
    if (this.counterStatusYieldsIndeterminateCount(counterData.getCounterStatus())) {
        logger.log(Level.FINEST,
                String.format("Counter '%s' was in an indeterminate state.  Returning 0!", counterName));
        return Optional.of(new CounterBuilder(counterData).withCount(BigInteger.ZERO).build());
    }

    // //////////////
    // ShortCircuit: If the counter was found in memcache.
    // //////////////
    final String memCacheKey = this.assembleCounterKeyforMemcache(counterName);
    if (!skipCache) {
        final BigInteger cachedCounterCount = this.memcacheSafeGet(memCacheKey);
        if (cachedCounterCount != null) {
            // /////////////////////////////////////
            // The count was found in memcache, so return it.
            // /////////////////////////////////////
            logger.log(Level.FINEST, String.format("Cache Hit for Counter Named '%s': value=%s", counterName,
                    cachedCounterCount));
            return Optional.of(new CounterBuilder(counterData).withCount(cachedCounterCount).build());
        } else {
            logger.log(Level.FINE,
                    String.format(
                            "Cache Miss for CounterData Named '%s': value='%s'.  Checking Datastore instead!",
                            counterName, cachedCounterCount));
        }
    }

    // /////////////////////////////////////
    // skipCache was true or the count was NOT found in memcache!
    // /////////////////////////////////////

    // Note: No Need to clear the Objectify session cache here because it will be cleared automatically and
    // repopulated upon every request.

    logger.log(Level.FINE,
            String.format("Aggregating counts from '%s' CounterDataShards for CounterData named '%s'!",
                    counterData.getNumShards(), counterData.getName()));

    // ///////////////////
    // Assemble a List of CounterShardData Keys to retrieve in parallel!
    final List<Key<CounterShardData>> keysToLoad = Lists.newArrayList();
    for (int i = 0; i < counterData.getNumShards(); i++) {
        final Key<CounterShardData> counterShardKey = CounterShardData.key(counterData.getTypedKey(), i);
        keysToLoad.add(counterShardKey);
    }

    long sum = 0;

    // For added performance, we could spawn multiple threads to wait for each value to be returned from the
    // DataStore, and then aggregate that way. However, the simple summation below is not very expensive, so
    // creating multiple threads to get each value would probably be overkill. Just let objectify do this for
    // us. Even though we have to wait for all entities to return before summation begins, the summation is a quick
    // in-memory operation with a relatively small number of shards, so parallelizing it would likely not increase
    // performance.

    // No TX - get is Strongly consistent by default, and we will exceed the TX limit for high-shard-count
    // counters if we try to do this in a TX.
    final Map<Key<CounterShardData>, CounterShardData> counterShardDatasMap = ObjectifyService.ofy()
            .transactionless().load().keys(keysToLoad);
    final Collection<CounterShardData> counterShardDatas = counterShardDatasMap.values();
    for (CounterShardData counterShardData : counterShardDatas) {
        if (counterShardData != null) {
            sum += counterShardData.getCount();
        }
    }

    logger.log(Level.FINE,
            String.format(
                    "The Datastore is reporting a count of %s for CounterData '%s' count.  Resetting memcache "
                            + "count to %s for this counter name.",
                    sum, counterData.getName(), sum));

    final BigInteger bdSum = BigInteger.valueOf(sum);
    try {
        // This method will only get here if there was nothing in Memcache, or if the caller requested to skip
        // reading the Counter count from memcache. In these cases, the value in memcache should always be replaced.
        memcacheService.put(memCacheKey, bdSum, config.getDefaultCounterCountExpiration(),
                SetPolicy.SET_ALWAYS);
    } catch (MemcacheServiceException mse) {
        // Do nothing. The method will still return even though memcache is not available.
    }

    return Optional.of(new CounterBuilder(counterData).withCount(bdSum).build());
}

From source file:org.apache.pig.test.TestBuiltin.java

@Before
public void setUp() throws Exception {
    Util.resetStateForExecModeSwitch();

    pigServer = new PigServer(Util.getLocalTestMode(), new Properties());
    pigServer.setValidateEachStatement(true);
    // First set up data structs for "base" SUM, MIN and MAX and AVG.
    // The allowed input and expected output data structs for
    // the "Intermediate" and "Final" stages can be based on the
    // "base" case - the allowed inputs for Initial stage can be based
    // on the "base" case.  In the test cases, the
    // output of Initial is sent to Intermediate, so we don't
    // explicitly test the output of Initial and hence do not
    // need to set up expectedMap.

    // first set up EvalFuncMap and expectedMap
    setupEvalFuncMap();//  w ww  . ja va2s.  co  m

    NULL_INPUT_TUPLE = TupleFactory.getInstance().newTuple(1);
    NULL_INPUT_TUPLE.set(0, null);

    expectedMap.put("SUM", new Double(55));
    expectedMap.put("DoubleSum", new Double(170.567391834593));
    expectedMap.put("IntSum", new Long(55));
    expectedMap.put("LongSum", new Long(145776964666362L));
    expectedMap.put("FloatSum", new Double(56.15395));
    expectedMap.put("BigDecimalSum",
            new BigDecimal("99999999999999988.9999999999999999999999999999999999999999"));
    expectedMap.put("BigIntegerSum",
            new BigInteger("999999999998888888887777777777777744444488888889999999999988"));

    expectedMap.put("AVG", new Double(5.5));
    expectedMap.put("DoubleAvg", new Double(17.0567391834593));
    expectedMap.put("LongAvg", new Double(14577696466636.2));
    expectedMap.put("IntAvg", new Double(5.5));
    expectedMap.put("FloatAvg", new Double(5.615394958853722));
    expectedMap.put("BigDecimalAvg", new BigDecimal("24999999999999997.25000000000000000"));
    expectedMap.put("BigIntegerAvg", new BigDecimal("2.499999999997222222219444444444444E+59"));

    expectedMap.put("MIN", new Double(1));
    expectedMap.put("IntMin", new Integer(1));
    expectedMap.put("LongMin", new Long(2));
    expectedMap.put("FloatMin", new Float(0.09f));
    expectedMap.put("DoubleMin", new Double(0.000000834593));
    expectedMap.put("BigDecimalMin", BigDecimal.ZERO);
    expectedMap.put("BigIntegerMin", BigInteger.ZERO);
    expectedMap.put("StringMin", "input");
    expectedMap.put("DateTimeMin", new DateTime("2008-10-09T01:07:02.000Z"));

    expectedMap.put("MAX", new Double(10));
    expectedMap.put("IntMax", new Integer(10));
    expectedMap.put("LongMax", new Long(145769183483345L));
    expectedMap.put("FloatMax", new Float(10.4f));
    expectedMap.put("DoubleMax", new Double(121.0));
    expectedMap.put("BigDecimalMax",
            new BigDecimal("99999999999999977.9999999999999999999999999999999999999999"));
    expectedMap.put("BigIntegerMax",
            new BigInteger("999999999998888888887777777777777744444488888889999999999977"));
    expectedMap.put("StringMax", "unit");
    expectedMap.put("DateTimeMax", new DateTime("2014-12-25T11:11:11.000Z"));

    expectedMap.put("COUNT", new Long(10));

    // set up allowedInput
    for (String[] aggGroups : aggs) {
        int i = 0;
        for (String agg : aggGroups) {
            allowedInput.put(agg, inputTypeAsString[i++]);
        }
    }

    // The idea here is that we can reuse the same input
    // and expected output of the algebraic functions
    // for their Intermediate and Final Stages. For the
    // Initial stage we can reuse the input of the algebraic
    // function.

    for (String[] aggGroups : aggs) {
        for (String agg : aggGroups) {
            for (String stage : stages) {
                if (stage.equals("Initial")) {
                    // For the Initial function, the input should match the input
                    // for the aggregate function itself. In the test cases, the
                    // output of Initial is sent to Intermediate, so we don't
                    // explicitly test the output of Initial and hence do not
                    // need to set up expectedMap.
                    allowedInput.put(agg + stage, allowedInput.get(agg));
                } else {
                    // For IntSumIntermediate and IntSumFinal and
                    // FloatSumIntermediate and FloatSumFinal, the input is expected
                    // be of types Long and Double respectively (Initial version
                    // of these functions is supposed to convert the Int to Long
                    // and Float to Double respectively) - Likewise for SUMIntermediate
                    // and SumFinal the input is expected to be Double - The Initial
                    // version is supposed to convert byteArrays to Double
                    if ((agg).equals("IntSum") || (agg).equals("IntAvg")) {
                        allowedInput.put(agg + stage, "IntegerAsLong");
                    } else if ((agg).equals("FloatSum") || agg.equals("FloatAvg")) {
                        allowedInput.put(agg + stage, "FloatAsDouble");
                    } else if ((agg).equals("MIN") || agg.equals("MAX") || (agg.equals("SUM"))
                            || agg.equals("AVG")) {
                        // For MIN and MAX the Intermediate and Final functions
                        // expect input to be Doubles (Initial is supposed to
                        // convert the ByteArray to Double)
                        allowedInput.put(agg + stage, "ByteArrayAsDouble");
                    } else {
                        // In all other cases, the input and expected output
                        // for "Intermediate" and "Final" stages should match the input
                        // and expected output for the aggregate function itself
                        allowedInput.put(agg + stage, allowedInput.get(agg));

                    }
                    // For Average, we set up expectedMap only for the "Final" stage
                    // For other aggs, set up expected Map for both "Intermediate"
                    // and "Final"
                    if (!agg.matches("(?i)avg") || stage.equals("Final")) {
                        expectedMap.put(agg + stage, expectedMap.get(agg));
                    }
                }
            }
        }
    }

    // For Avg, the expected output (for the sum part) for Intermediate are the
    // same as SUM - so handled a little differently accordingly
    expectedMap.put("AVGIntermediate", expectedMap.get("SUM"));
    expectedMap.put("DoubleAvgIntermediate", expectedMap.get("DoubleSum"));
    expectedMap.put("LongAvgIntermediate", expectedMap.get("LongSum"));
    expectedMap.put("IntAvgIntermediate", expectedMap.get("IntSum"));
    expectedMap.put("FloatAvgIntermediate", expectedMap.get("FloatSum"));
    expectedMap.put("BigDecimalAvgIntermediate", expectedMap.get("BigDecimalSum"));
    expectedMap.put("BigIntegerAvgIntermediate", expectedMap.get("BigIntegerSum"));

    // set up input hash
    inputMap.put("Integer", Util.loadNestTuple(TupleFactory.getInstance().newTuple(1), intInput));
    inputMap.put("IntegerAsLong", Util.loadNestTuple(TupleFactory.getInstance().newTuple(1), intAsLong));
    inputMap.put("Long", Util.loadNestTuple(TupleFactory.getInstance().newTuple(1), longInput));
    inputMap.put("Float", Util.loadNestTuple(TupleFactory.getInstance().newTuple(1), floatInput));
    inputMap.put("FloatAsDouble", Util.loadNestTuple(TupleFactory.getInstance().newTuple(1), floatAsDouble));
    inputMap.put("Double", Util.loadNestTuple(TupleFactory.getInstance().newTuple(1), doubleInput));
    inputMap.put("BigDecimal", Util.loadNestTuple(TupleFactory.getInstance().newTuple(1), bigDecimalInput));
    inputMap.put("BigInteger", Util.loadNestTuple(TupleFactory.getInstance().newTuple(1), bigIntegerInput));
    inputMap.put("ByteArray", Util.loadNestTuple(TupleFactory.getInstance().newTuple(1), ByteArrayInput));
    inputMap.put("ByteArrayAsDouble", Util.loadNestTuple(TupleFactory.getInstance().newTuple(1), baAsDouble));
    inputMap.put("String", Util.loadNestTuple(TupleFactory.getInstance().newTuple(1), stringInput));
    inputMap.put("DateTime", Util.loadNestTuple(TupleFactory.getInstance().newTuple(1), datetimeInput));

    // set up input hash for accumulate
    inputMapForAccumulate.put("Integer", Util.splitCreateBagOfTuples(intInput, 3));
    inputMapForAccumulate.put("IntegerAsLong", Util.splitCreateBagOfTuples(intAsLong, 3));
    inputMapForAccumulate.put("Long", Util.splitCreateBagOfTuples(longInput, 3));
    inputMapForAccumulate.put("Float", Util.splitCreateBagOfTuples(floatInput, 3));
    inputMapForAccumulate.put("FloatAsDouble", Util.splitCreateBagOfTuples(floatAsDouble, 3));
    inputMapForAccumulate.put("Double", Util.splitCreateBagOfTuples(doubleInput, 3));
    inputMapForAccumulate.put("BigDecimal", Util.splitCreateBagOfTuples(bigDecimalInput, 3));
    inputMapForAccumulate.put("BigInteger", Util.splitCreateBagOfTuples(bigIntegerInput, 3));
    inputMapForAccumulate.put("ByteArray", Util.splitCreateBagOfTuples(ByteArrayInput, 3));
    inputMapForAccumulate.put("ByteArrayAsDouble", Util.splitCreateBagOfTuples(baAsDouble, 3));
    inputMapForAccumulate.put("String", Util.splitCreateBagOfTuples(stringInput, 3));
    inputMapForAccumulate.put("DateTime", Util.splitCreateBagOfTuples(datetimeInput, 3));
}