Example usage for java.math BigInteger compareTo

List of usage examples for java.math BigInteger compareTo

Introduction

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

Prototype

public int compareTo(BigInteger val) 

Source Link

Document

Compares this BigInteger with the specified BigInteger.

Usage

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

public static BigInteger toNanoCoins(final String value, final int shift) {

    try {//from   ww  w. j  a  v  a  2 s . co m
        final BigInteger nanoCoins = new BigDecimal(value).movePointRight(8 - shift).toBigIntegerExact();

        if (nanoCoins.signum() < 0)
            throw new IllegalArgumentException("negative amount: " + value);
        if (nanoCoins.compareTo(NetworkParameters.MAX_MONEY) > 0)
            Log.e(TAG, "AMOUNT TOO LARGE");

        return nanoCoins;
    } catch (ArithmeticException e) {
        Log.d(TAG, e.getMessage());
        return BigInteger.ZERO;
    }
}

From source file:com.amazonaws.services.kinesis.clientlibrary.types.UserRecord.java

/**
 * This method deaggregates the given list of Amazon Kinesis records into a
 * list of KPL user records. Any KPL user records whose explicit hash key or
 * partition key falls outside the range of the startingHashKey and the
 * endingHashKey are discarded from the resulting list. This method will
 * then return the resulting list of KPL user records.
 * //from  www  . j a  v  a  2 s. com
 * @param records
 *            A list of Amazon Kinesis records, each possibly aggregated.
 * @param startingHashKey
 *            A BigInteger representing the starting hash key that the
 *            explicit hash keys or partition keys of retained resulting KPL
 *            user records must be greater than or equal to.
 * @param endingHashKey
 *            A BigInteger representing the ending hash key that the the
 *            explicit hash keys or partition keys of retained resulting KPL
 *            user records must be smaller than or equal to.
 * @return A resulting list of KPL user records whose explicit hash keys or
 *          partition keys fall within the range of the startingHashKey and
 *          the endingHashKey.
 */
// CHECKSTYLE:OFF NPathComplexity
public static List<UserRecord> deaggregate(List<Record> records, BigInteger startingHashKey,
        BigInteger endingHashKey) {
    List<UserRecord> result = new ArrayList<>();
    byte[] magic = new byte[AGGREGATED_RECORD_MAGIC.length];
    byte[] digest = new byte[DIGEST_SIZE];

    for (Record r : records) {
        boolean isAggregated = true;
        long subSeqNum = 0;
        ByteBuffer bb = r.getData();

        if (bb.remaining() >= magic.length) {
            bb.get(magic);
        } else {
            isAggregated = false;
        }

        if (!Arrays.equals(AGGREGATED_RECORD_MAGIC, magic) || bb.remaining() <= DIGEST_SIZE) {
            isAggregated = false;
        }

        if (isAggregated) {
            int oldLimit = bb.limit();
            bb.limit(oldLimit - DIGEST_SIZE);
            byte[] messageData = new byte[bb.remaining()];
            bb.get(messageData);
            bb.limit(oldLimit);
            bb.get(digest);
            byte[] calculatedDigest = md5(messageData);

            if (!Arrays.equals(digest, calculatedDigest)) {
                isAggregated = false;
            } else {
                try {
                    Messages.AggregatedRecord ar = Messages.AggregatedRecord.parseFrom(messageData);
                    List<String> pks = ar.getPartitionKeyTableList();
                    List<String> ehks = ar.getExplicitHashKeyTableList();
                    long aat = r.getApproximateArrivalTimestamp() == null ? -1
                            : r.getApproximateArrivalTimestamp().getTime();
                    try {
                        int recordsInCurrRecord = 0;
                        for (Messages.Record mr : ar.getRecordsList()) {
                            String explicitHashKey = null;
                            String partitionKey = pks.get((int) mr.getPartitionKeyIndex());
                            if (mr.hasExplicitHashKeyIndex()) {
                                explicitHashKey = ehks.get((int) mr.getExplicitHashKeyIndex());
                            }

                            BigInteger effectiveHashKey = explicitHashKey != null
                                    ? new BigInteger(explicitHashKey)
                                    : new BigInteger(1, md5(partitionKey.getBytes("UTF-8")));

                            if (effectiveHashKey.compareTo(startingHashKey) < 0
                                    || effectiveHashKey.compareTo(endingHashKey) > 0) {
                                for (int toRemove = 0; toRemove < recordsInCurrRecord; ++toRemove) {
                                    result.remove(result.size() - 1);
                                }
                                break;
                            }

                            ++recordsInCurrRecord;
                            Record record = new Record().withData(ByteBuffer.wrap(mr.getData().toByteArray()))
                                    .withPartitionKey(partitionKey).withSequenceNumber(r.getSequenceNumber())
                                    .withApproximateArrivalTimestamp(aat < 0 ? null : new Date(aat));
                            result.add(new UserRecord(true, record, subSeqNum++, explicitHashKey));
                        }
                    } catch (Exception e) {
                        StringBuilder sb = new StringBuilder();
                        sb.append("Unexpected exception during deaggregation, record was:\n");
                        sb.append("PKS:\n");
                        for (String s : pks) {
                            sb.append(s).append("\n");
                        }
                        sb.append("EHKS: \n");
                        for (String s : ehks) {
                            sb.append(s).append("\n");
                        }
                        for (Messages.Record mr : ar.getRecordsList()) {
                            sb.append("Record: [hasEhk=").append(mr.hasExplicitHashKeyIndex()).append(", ")
                                    .append("ehkIdx=").append(mr.getExplicitHashKeyIndex()).append(", ")
                                    .append("pkIdx=").append(mr.getPartitionKeyIndex()).append(", ")
                                    .append("dataLen=").append(mr.getData().toByteArray().length).append("]\n");
                        }
                        sb.append("Sequence number: ").append(r.getSequenceNumber()).append("\n")
                                .append("Raw data: ")
                                .append(javax.xml.bind.DatatypeConverter.printBase64Binary(messageData))
                                .append("\n");
                        LOG.error(sb.toString(), e);
                    }
                } catch (InvalidProtocolBufferException e) {
                    isAggregated = false;
                }
            }
        }

        if (!isAggregated) {
            bb.rewind();
            result.add(new UserRecord(r));
        }
    }
    return result;
}

From source file:org.apache.cassandra.utils.FBUtilities.java

/**
 * Given two bit arrays represented as BigIntegers, containing the given
 * number of significant bits, calculate a midpoint.
 *
 * @param left The left point./*from   www  . j a v  a2  s  .c o  m*/
 * @param right The right point.
 * @param sigbits The number of bits in the points that are significant.
 * @return A midpoint that will compare bitwise halfway between the params, and
 * a boolean representing whether a non-zero lsbit remainder was generated.
 */
public static Pair<BigInteger, Boolean> midpoint(BigInteger left, BigInteger right, int sigbits) {
    BigInteger midpoint;
    boolean remainder;
    if (left.compareTo(right) < 0) {
        BigInteger sum = left.add(right);
        remainder = sum.testBit(0);
        midpoint = sum.shiftRight(1);
    } else {
        BigInteger max = TWO.pow(sigbits);
        // wrapping case
        BigInteger distance = max.add(right).subtract(left);
        remainder = distance.testBit(0);
        midpoint = distance.shiftRight(1).add(left).mod(max);
    }
    return new Pair<BigInteger, Boolean>(midpoint, remainder);
}

From source file:org.crazydog.util.spring.NumberUtils.java

/**
 * Convert the given number into an instance of the given target class.
 *
 * @param number      the number to convert
 * @param targetClass the target class to convert to
 * @return the converted number/*  w  w w .  j a va2 s  .  c o  m*/
 * @throws IllegalArgumentException if the target class is not supported
 *                                  (i.e. not a standard Number subclass as included in the JDK)
 * @see Byte
 * @see Short
 * @see Integer
 * @see Long
 * @see BigInteger
 * @see Float
 * @see Double
 * @see BigDecimal
 */
@SuppressWarnings("unchecked")
public static <T extends Number> T convertNumberToTargetClass(Number number, Class<T> targetClass)
        throws IllegalArgumentException {

    org.springframework.util.Assert.notNull(number, "Number must not be null");
    org.springframework.util.Assert.notNull(targetClass, "Target class must not be null");

    if (targetClass.isInstance(number)) {
        return (T) number;
    } else if (Byte.class == targetClass) {
        long value = number.longValue();
        if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return (T) new Byte(number.byteValue());
    } else if (Short.class == targetClass) {
        long value = number.longValue();
        if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return (T) new Short(number.shortValue());
    } else if (Integer.class == targetClass) {
        long value = number.longValue();
        if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return (T) new Integer(number.intValue());
    } else if (Long.class == targetClass) {
        BigInteger bigInt = null;
        if (number instanceof BigInteger) {
            bigInt = (BigInteger) number;
        } else if (number instanceof BigDecimal) {
            bigInt = ((BigDecimal) number).toBigInteger();
        }
        // Effectively analogous to JDK 8's BigInteger.longValueExact()
        if (bigInt != null && (bigInt.compareTo(LONG_MIN) < 0 || bigInt.compareTo(LONG_MAX) > 0)) {
            raiseOverflowException(number, targetClass);
        }
        return (T) new Long(number.longValue());
    } else if (BigInteger.class == targetClass) {
        if (number instanceof BigDecimal) {
            // do not lose precision - use BigDecimal's own conversion
            return (T) ((BigDecimal) number).toBigInteger();
        } else {
            // original value is not a Big* number - use standard long conversion
            return (T) BigInteger.valueOf(number.longValue());
        }
    } else if (Float.class == targetClass) {
        return (T) new Float(number.floatValue());
    } else if (Double.class == targetClass) {
        return (T) new Double(number.doubleValue());
    } else if (BigDecimal.class == targetClass) {
        // always use BigDecimal(String) here to avoid unpredictability of BigDecimal(double)
        // (see BigDecimal javadoc for details)
        return (T) new BigDecimal(number.toString());
    } else {
        throw new IllegalArgumentException("Could not convert number [" + number + "] of type ["
                + number.getClass().getName() + "] to unknown target class [" + targetClass.getName() + "]");
    }
}

From source file:org.openestate.io.is24_xml.Is24XmlUtils.java

public static String printZahl20(BigInteger value) {
    if (value == null || value.compareTo(BigInteger.ZERO) != 1)
        throw new IllegalArgumentException("Can't print integer value '" + value + "'!");
    String val = DatatypeConverter.printInteger(value);
    if (val.length() > 20)
        throw new IllegalArgumentException(
                "Can't print integer value '" + value + "'! The value exceeds maximal length of 20 digits.");
    return val;
}

From source file:mitm.common.security.crl.CRLUtils.java

/**
 * Returns 0 if crl and otherCRL have similar validity (ie no one is newer than the other), 
 * > 0 if crl is newer than otherCRL and < 0 if crl is older than otherCRL 
 *//* w  w  w.  j  a v  a 2  s  . co m*/
public static int compare(X509CRL crl, X509CRL otherCRL) throws IOException, MissingDateException {
    BigInteger crlNumber = X509CRLInspector.getCRLNumber(crl);
    BigInteger otherCRLNumber = X509CRLInspector.getCRLNumber(crl);

    Date thisUpdate = crl.getThisUpdate();
    Date otherThisUpdate = otherCRL.getThisUpdate();

    if (thisUpdate == null || otherThisUpdate == null) {
        throw new MissingDateException("One of the CRLs has a missing thisUpdate.");
    }

    int cmp;

    if (crlNumber != null && otherCRLNumber != null) {
        cmp = crlNumber.compareTo(otherCRLNumber);

        if (cmp > 0) {
            if (thisUpdate.before(otherThisUpdate)) {
                logger.warn("According to CRL numbers a new CRL is found but thisUpdate is older.");
            }

            logger.debug("The CRL number is bigger and is therefore more recent.");
        } else if (cmp == 0) {
            /* 
             * same CRL number but thisUpdate can be newer
             */
            cmp = thisUpdate.compareTo(otherThisUpdate);

            if (cmp > 0) {
                logger.debug("The CRL numbers are equal but thisUpdate is newer.");
            }
        } else {
            if (thisUpdate.after(otherThisUpdate)) {
                logger.warn("According to CRL numbers this not a new CRL but thisUpdate is newer.");
            }
        }
    } else {
        /* 
         * no CRL number so compare thisUpdate
         */
        cmp = thisUpdate.compareTo(otherThisUpdate);

        if (cmp > 0) {
            logger.debug("A more recent CRL is found.");
        }
    }

    return cmp;
}

From source file:uniol.apt.analysis.synthesize.SynthesizePN.java

private static long bigIntToLong(BigInteger value) {
    if (value.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0
            || value.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0)
        throw new ArithmeticException("Cannot represent value as long: " + value);
    return value.longValue();
}

From source file:uniol.apt.analysis.synthesize.SynthesizePN.java

private static int bigIntToInt(BigInteger value) {
    if (value.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0
            || value.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0)
        throw new ArithmeticException("Cannot represent value as int: " + value);
    return value.intValue();
}

From source file:com.wms.utils.DataUtil.java

public static boolean checkLengthIPV4numberRange(String fromIPAddress, String toIPAddress) {
    BigInteger fromIP = ipv4ToNumber(fromIPAddress);
    BigInteger toIP = ipv4ToNumber(toIPAddress);
    BigInteger limit = toIP.subtract(fromIP);
    if (limit.compareTo(new BigInteger(MAX_NUMBER_RANGE)) == 1) {
        return false;
    }/* w  w w  .  j  a va  2s. c  o  m*/
    return true;
}

From source file:com.wms.utils.DataUtil.java

public static boolean checkValidateIPv6(String fromIPAddress, String toIPAddress, int mask) {

    BigInteger fromIP = ipv6ToNumber(fromIPAddress);
    BigInteger toIP = ipv6ToNumber(toIPAddress);
    BigInteger limit = toIP.subtract(fromIP);
    if (limit.compareTo(new BigInteger(MAX_NUMBER_RANGE)) == 1) {
        return false;
    }//from  w ww  . ja va 2 s  .c  o  m
    BigInteger subnet = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16);

    fromIP = fromIP.shiftRight(128 - mask).shiftLeft(128 - mask);
    subnet = subnet.shiftRight(mask);

    BigInteger broadcastIP = fromIP.xor(subnet);

    if (toIP.compareTo(broadcastIP) == 1) {
        return false;
    }

    return true;
}