List of usage examples for java.math BigInteger compareTo
public int compareTo(BigInteger val)
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);/* w w w.j av a 2 s. co m*/ //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:jp.aegif.nemaki.cmis.aspect.impl.ExceptionServiceImpl.java
private void constraintStringPropertyValue(PropertyDefinition<?> definition, PropertyData<?> propertyData, String objectId) {// ww w .java 2 s . c o m final String msg = "An STRING property violates the length constraints"; if (!(propertyData instanceof PropertyString)) return; String val = ((PropertyString) propertyData).getFirstValue(); if (StringUtils.isEmpty(val)) return; BigInteger length = BigInteger.valueOf(val.length()); BigInteger max = ((PropertyStringDefinition) definition).getMaxLength(); if (max != null && max.compareTo(length) < 0) { constraint(objectId, msg); } }
From source file:jp.aegif.nemaki.cmis.aspect.impl.ExceptionServiceImpl.java
private void constraintIntegerPropertyValue(PropertyDefinition<?> definition, PropertyData<?> propertyData, String objectId) {/*from ww w. j a va 2 s . c o m*/ final String msg = "AN INTEGER property violates the range constraints"; BigInteger val = BigInteger.valueOf((Long) propertyData.getFirstValue()); BigInteger min = ((PropertyIntegerDefinition) definition).getMinValue(); if (min != null && min.compareTo(val) > 0) { constraint(objectId, msg); } BigInteger max = ((PropertyIntegerDefinition) definition).getMinValue(); if (max != null && max.compareTo(val) < 0) { constraint(objectId, msg); } }
From source file:com.ery.ertc.estorm.util.Bytes.java
/** * Iterate over keys within the passed range. *///from w w w.j av a2 s .c o m public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive, final int num) { byte[] aPadded; byte[] bPadded; if (a.length < b.length) { aPadded = padTail(a, b.length - a.length); bPadded = b; } else if (b.length < a.length) { aPadded = a; bPadded = padTail(b, a.length - b.length); } else { aPadded = a; bPadded = b; } if (compareTo(aPadded, bPadded) >= 0) { throw new IllegalArgumentException("b <= a"); } if (num <= 0) { throw new IllegalArgumentException("num cannot be < 0"); } byte[] prependHeader = { 1, 0 }; final BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); BigInteger diffBI = stopBI.subtract(startBI); if (inclusive) { diffBI = diffBI.add(BigInteger.ONE); } final BigInteger splitsBI = BigInteger.valueOf(num + 1); if (diffBI.compareTo(splitsBI) < 0) { return null; } final BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch (Exception e) { LOG.error("Exception caught during division", e); return null; } final Iterator<byte[]> iterator = new Iterator<byte[]>() { private int i = -1; @Override public boolean hasNext() { return i < num + 1; } @Override public byte[] next() { i++; if (i == 0) return a; if (i == num + 1) return b; BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i))); byte[] padded = curBI.toByteArray(); if (padded[1] == 0) padded = tail(padded, padded.length - 2); else padded = tail(padded, padded.length - 1); return padded; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return new Iterable<byte[]>() { @Override public Iterator<byte[]> iterator() { return iterator; } }; }
From source file:org.apache.kylin.common.util.Bytes.java
/** * Iterate over keys within the passed range. *//*from w w w. j a va 2 s.co m*/ public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive, final int num) { byte[] aPadded; byte[] bPadded; if (a.length < b.length) { aPadded = padTail(a, b.length - a.length); bPadded = b; } else if (b.length < a.length) { aPadded = a; bPadded = padTail(b, a.length - b.length); } else { aPadded = a; bPadded = b; } if (compareTo(aPadded, bPadded) >= 0) { throw new IllegalArgumentException("b <= a"); } if (num <= 0) { throw new IllegalArgumentException("num cannot be <= 0"); } byte[] prependHeader = { 1, 0 }; final BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); BigInteger diffBI = stopBI.subtract(startBI); if (inclusive) { diffBI = diffBI.add(BigInteger.ONE); } final BigInteger splitsBI = BigInteger.valueOf(num + 1L); if (diffBI.compareTo(splitsBI) < 0) { return null; } final BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch (Exception e) { LOG.error("Exception caught during division", e); return null; } final Iterator<byte[]> iterator = new Iterator<byte[]>() { private int i = -1; @Override public boolean hasNext() { return i < num + 1; } @Override public byte[] next() { i++; if (i == 0) return a; if (i == num + 1) return b; BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i))); byte[] padded = curBI.toByteArray(); if (padded[1] == 0) padded = tail(padded, padded.length - 2); else padded = tail(padded, padded.length - 1); return padded; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return new Iterable<byte[]>() { @Override public Iterator<byte[]> iterator() { return iterator; } }; }
From source file:org.apache.hadoop.hbase.util.Bytes.java
/** * Iterate over keys within the passed range. *///from w ww.j a va 2s. c om public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive, final int num) { byte[] aPadded; byte[] bPadded; if (a.length < b.length) { aPadded = padTail(a, b.length - a.length); bPadded = b; } else if (b.length < a.length) { aPadded = a; bPadded = padTail(b, a.length - b.length); } else { aPadded = a; bPadded = b; } if (compareTo(aPadded, bPadded) >= 0) { throw new IllegalArgumentException("b <= a"); } if (num <= 0) { throw new IllegalArgumentException("num cannot be <= 0"); } byte[] prependHeader = { 1, 0 }; final BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); BigInteger diffBI = stopBI.subtract(startBI); if (inclusive) { diffBI = diffBI.add(BigInteger.ONE); } final BigInteger splitsBI = BigInteger.valueOf(num + 1); if (diffBI.compareTo(splitsBI) < 0) { return null; } final BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch (Exception e) { LOG.error("Exception caught during division", e); return null; } final Iterator<byte[]> iterator = new Iterator<byte[]>() { private int i = -1; @Override public boolean hasNext() { return i < num + 1; } @Override public byte[] next() { i++; if (i == 0) return a; if (i == num + 1) return b; BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i))); byte[] padded = curBI.toByteArray(); if (padded[1] == 0) padded = tail(padded, padded.length - 2); else padded = tail(padded, padded.length - 1); return padded; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return new Iterable<byte[]>() { @Override public Iterator<byte[]> iterator() { return iterator; } }; }
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./*w w w. j a v a 2 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<PutRecordResult> 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:org.nd4j.linalg.util.BigDecimalMath.java
/** * Multiply and round.// w w w. ja va2s . c o m * * @param x The left factor. * @param n The right factor. * @return the product x*n */ static public BigDecimal multiplyRound(final BigDecimal x, final BigInteger n) { BigDecimal resul = x.multiply(new BigDecimal(n)); /* The estimation of the absolute error in the result is |n*err(x)| */ MathContext mc = new MathContext(n.compareTo(BigInteger.ZERO) != 0 ? x.precision() : 0); return resul.round(mc); }
From source file:org.apache.pig.data.SchemaTuple.java
protected int compare(BigInteger val, BigInteger themVal) { return val.compareTo(themVal); }
From source file:com.ephesoft.gxt.rv.server.ReviewValidateServiceImpl.java
private List<Span> getSortedList(final List<Span> spanList) { final Set<Span> set = new TreeSet<Span>(new Comparator<Span>() { public int compare(final Span firstSpan, final Span secSpan) { BigInteger s1Y0 = firstSpan.getCoordinates().getY0(); BigInteger s1Y1 = firstSpan.getCoordinates().getY1(); final BigInteger s2Y0 = secSpan.getCoordinates().getY0(); final BigInteger s2Y1 = secSpan.getCoordinates().getY1(); final int halfOfSecSpan = (s2Y1.intValue() - s2Y0.intValue()) / 2; final int y1 = s2Y1.intValue() + halfOfSecSpan; final int y0 = s2Y0.intValue() - halfOfSecSpan; // following if else code is to handle abnormal(out of synch) value y0 or y1 coordinate of new span. if (isApproxEqual(s1Y0.intValue(), s2Y0.intValue()) && s1Y1.intValue() > y1) { s1Y1 = BigInteger.valueOf(y1); firstSpan.getCoordinates().setY1(s1Y1); } else if (isApproxEqual(s1Y1.intValue(), s2Y1.intValue()) && s1Y0.intValue() < y0) { s1Y0 = BigInteger.valueOf(y0); firstSpan.getCoordinates().setY0(s1Y0); }// www .ja va 2 s . c o m final BigInteger s1Y = s1Y1.add(s1Y0); final BigInteger s2Y = s2Y1.add(s2Y0); // calculating middle of old span. final int oldSpanMid = s2Y.intValue() / 2; int returnValue = 0; // if old span's y coordinate's middle lies within range of new span's y coordinates or not. if true, the two spans // belong to same line compare them further on their x coordinates, else they belong to two different lines. if (oldSpanMid >= s1Y0.intValue() && oldSpanMid <= s1Y1.intValue()) { final BigInteger s1X1 = firstSpan.getCoordinates().getX1(); final BigInteger s2X1 = secSpan.getCoordinates().getX1(); returnValue = s1X1.compareTo(s2X1); } else { returnValue = s1Y.compareTo(s2Y); } return returnValue; } }); set.addAll(spanList); final List<Span> spanSortedList = new LinkedList<Span>(); spanSortedList.addAll(set); // TODO add the clear method to remove all elements of set since it not // required after adding it to linked list. // set.clear(); return spanSortedList; }